diff --git a/BUILD.gn b/BUILD.gn index 433aba5..9149a891 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -1076,12 +1076,6 @@ } } - # TODO(chromium:1382224): Remove this target as soon as all the builders have switched to :chromedriver_group - group("chromedriver") { - testonly = true - deps = [ ":chromedriver_group" ] - } - # This group includes all of the targets needed to build and test Blink, # including running web tests (see below). This target is defined here because # previously //third_party/WebKit, now //third_party/blink, couldn't depend on
diff --git a/DEPS b/DEPS index c347188..e0d3183c7 100644 --- a/DEPS +++ b/DEPS
@@ -295,11 +295,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '877213bd9a41200b6f568df40cab71deec2d3bd8', + 'skia_revision': '502553f2f54b093686da6c516bcbef605bebedcd', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '7157324f4c8e786b6b3439fa0afe3ebe53bf6ffe', + 'v8_revision': '66900470cf2b7b974bd622dd42875f2a69ffaad0', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. @@ -322,7 +322,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Fuchsia sdk # and whatever else without interference from each other. - 'fuchsia_version': 'version:10.20221128.0.1', + 'fuchsia_version': 'version:10.20221128.1.1', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling google-toolbox-for-mac # and whatever else without interference from each other. @@ -374,7 +374,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': 'b4854279276a5049e9205c699f32f9920897029c', + 'devtools_frontend_revision': 'fc4b4c505539d143bcc9e68cd53d5a51f15cb6f0', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -478,7 +478,7 @@ # If you change this, also update the libc++ revision in # //buildtools/deps_revisions.gni. - 'libcxx_revision': '0488dfb230af1188de06115aaa587b09536d99e5', + 'libcxx_revision': 'c2e10323cc8190175715ea1bcdb109f59b84447c', # GN CIPD package version. 'gn_version': 'git_revision:1c4151ff5c1d6fbf7fa800b8d4bb34d3abc03a41', @@ -782,7 +782,7 @@ 'src/clank': { 'url': 'https://chrome-internal.googlesource.com/clank/internal/apps.git' + '@' + - '56ecc6364a080a94ee7e886d58adfbca8ecc765b', + 'e1ec096c608b85e3777f16dc7665c0e45a387466', 'condition': 'checkout_android and checkout_src_internal', }, @@ -881,7 +881,7 @@ 'packages': [ { 'package': 'chromium/rts/model/linux-amd64', - 'version': 'wffUPgHkPkKcQDL3dVMyYaTN4oKaNkpycy507DnO_Q8C', + 'version': 'U9qi7m3yW6_jEc3O-jymLNDEGusWThcRkGhTXm5GPckC', }, ], 'dep_type': 'cipd', @@ -892,7 +892,7 @@ 'packages': [ { 'package': 'chromium/rts/model/mac-amd64', - 'version': 'kZSr3xfywPfpPHQEn9FFwa7RCVrrps0OYR34VVv40H8C', + 'version': 'XQrojzmtd6OPgfzN1aFRNLqqWq3MPZINUJuKg7_ze54C', }, ], 'dep_type': 'cipd', @@ -903,7 +903,7 @@ 'packages': [ { 'package': 'chromium/rts/model/windows-amd64', - 'version': 'vvHQ8Spdr-M2FVxXSLbNsspv39LhCuxn_3w2X_eFeIEC', + 'version': 'PjJRjoTkHL0RyuA3NJT5C0AqHC1J7MffEO3n28_bhcgC', }, ], 'dep_type': 'cipd', @@ -1186,7 +1186,7 @@ # Tools used when building Chrome for Chrome OS. This affects both the Simple # Chrome workflow, as well as the chromeos-chrome ebuild. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'e8bff284f3c552329f03196d07b147d55578bec6', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'f34ec92d2e4c4cbeb2f1e08f79622f0fc8aa103d', 'condition': 'checkout_chromeos', }, @@ -1204,7 +1204,7 @@ # For Linux and Chromium OS. 'src/third_party/cros_system_api': { - 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + '2c7a87d4a4f5d9e55abfd6111843b2cd425c842f', + 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + '2b0f171d797c4b3b92faad46dfc5d5583ab90ec5', 'condition': 'checkout_linux', }, @@ -1214,13 +1214,13 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '0115386a26a457025605048d1ffbbf810a359a8e', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'd83509c0c3eaf76caed823a09b921871958d8237', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), 'src/third_party/devtools-frontend-internal': { - 'url': 'https://chrome-internal.googlesource.com/devtools/devtools-internal.git' + '@' + '7f08b66a8bcc37385c453b320204f198e06b5228', + 'url': 'https://chrome-internal.googlesource.com/devtools/devtools-internal.git' + '@' + '86bfc22006060dbc8f9665688fa71b76842c503b', 'condition': 'checkout_src_internal', }, @@ -1505,7 +1505,7 @@ Var('chromium_git') + '/webm/libwebp.git' + '@' + '7366f7f394af26de814296152c50e673ed0a832f', 'src/third_party/libyuv': - Var('chromium_git') + '/libyuv/libyuv.git' + '@' + '8713ba3f0bddfa19943559981acd5aad2d703d5d', + Var('chromium_git') + '/libyuv/libyuv.git' + '@' + '4a3c79cb31aee310443039c37d64377ed06f1d14', 'src/third_party/lighttpd': { 'url': Var('chromium_git') + '/chromium/deps/lighttpd.git' + '@' + Var('lighttpd_revision'), @@ -1635,7 +1635,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '1af6f10d7c0429403e0f7ad4429a0023bb70c763', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'c2fa74a858edfb42ccfe4a024de1dabd6b5fbabe', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1817,7 +1817,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'd1b65aa5a88f6efd900604dfcda840154e9f16e2', 'src/third_party/webgpu-cts/src': - Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '09447faf1a22821f35ca4a3fc9c06e3bf1125756', + Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '57304e8905d4817346246ccc6aa3f2619d08ab7e', 'src/third_party/webrtc': Var('webrtc_git') + '/src.git' + '@' + '569af3e80fcda6241f0e6d801c89f9ebbee310b3', @@ -3847,7 +3847,8 @@ '-absl', '-third_party/abseil-cpp', '+third_party/abseil-cpp/absl/base/attributes.h', - "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/cleanup/cleanup.h', + '+third_party/abseil-cpp/absl/numeric/int128.h', '+third_party/abseil-cpp/absl/types/optional.h', '+third_party/abseil-cpp/absl/types/variant.h', '+third_party/abseil-cpp/absl/utility/utility.h',
diff --git a/android_webview/browser/aw_contents_io_thread_client.cc b/android_webview/browser/aw_contents_io_thread_client.cc index 6ac5c7f..97a11fc8 100644 --- a/android_webview/browser/aw_contents_io_thread_client.cc +++ b/android_webview/browser/aw_contents_io_thread_client.cc
@@ -24,7 +24,6 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/synchronization/lock.h" -#include "base/task/task_runner_util.h" #include "base/threading/scoped_blocking_call.h" #include "components/embedder_support/android/util/input_stream.h" #include "components/embedder_support/android/util/web_resource_response.h" @@ -408,9 +407,8 @@ &RunShouldInterceptRequest, std::move(request), JavaObjectWeakGlobalRef(env, bg_thread_client_object_.obj())); } - base::PostTaskAndReplyWithResult(sequenced_task_runner_.get(), FROM_HERE, - std::move(get_response), - std::move(callback)); + sequenced_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, std::move(get_response), std::move(callback)); } bool AwContentsIoThreadClient::ShouldBlockContentUrls() const {
diff --git a/android_webview/test/shell/src/draw_fn/overlays_manager.cc b/android_webview/test/shell/src/draw_fn/overlays_manager.cc index e83e850..3d48018b 100644 --- a/android_webview/test/shell/src/draw_fn/overlays_manager.cc +++ b/android_webview/test/shell/src/draw_fn/overlays_manager.cc
@@ -8,6 +8,7 @@ #include "android_webview/public/browser/draw_fn.h" #include "android_webview/test/shell/src/draw_fn/allocator.h" +#include "base/android/build_info.h" #include "base/android/jni_array.h" #include "base/logging.h" #include "base/memory/raw_ptr.h" @@ -17,7 +18,10 @@ namespace { bool AreOverlaysSupported() { - static bool supported = gfx::SurfaceControl::IsSupported(); + static bool supported = gfx::SurfaceControl::IsSupported() && + (base::android::BuildInfo::GetInstance()->sdk_int() >= + base::android::SDK_VERSION_S); + return supported; }
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 0fe7557..21c6a49b 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -33,7 +33,6 @@ "accelerators/accelerator_history_impl.cc", "accelerators/accelerator_history_impl.h", "accelerators/accelerator_ids.h", - "accelerators/accelerator_layout_table.cc", "accelerators/accelerator_layout_table.h", "accelerators/accelerator_notifications.cc", "accelerators/accelerator_notifications.h", @@ -1907,6 +1906,7 @@ "system/video_conference/fake_video_conference_tray_controller.h", "system/video_conference/video_conference_bubble.cc", "system/video_conference/video_conference_bubble.h", + "system/video_conference/video_conference_media_state.h", "system/video_conference/video_conference_tray.cc", "system/video_conference/video_conference_tray.h", "system/video_conference/video_conference_tray_controller.cc",
diff --git a/ash/accelerators/accelerator_layout_table.cc b/ash/accelerators/accelerator_layout_table.cc deleted file mode 100644 index 93f1bb1..0000000 --- a/ash/accelerators/accelerator_layout_table.cc +++ /dev/null
@@ -1,591 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ash/accelerators/accelerator_layout_table.h" - -#include "ash/public/cpp/accelerators.h" -#include "ash/public/mojom/accelerator_info.mojom.h" -#include "base/containers/fixed_flat_map.h" - -namespace ash { - -// TODO(jimmyxgong): Reconcile this map with default accelerator keys, either -// create a separate map or modify this map to include default accelerators. -const auto kAcceleratorLayouts = - base::MakeFixedFlatMap<AcceleratorAction, AcceleratorLayoutDetails>({ - {BRIGHTNESS_DOWN, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {BRIGHTNESS_UP, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {CYCLE_BACKWARD_MRU, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {CYCLE_FORWARD_MRU, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_ACTIVATE_DESK_LEFT, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_ACTIVATE_DESK_RIGHT, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_MOVE_ACTIVE_ITEM_LEFT, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_MOVE_ACTIVE_ITEM_RIGHT, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_NEW_DESK, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_REMOVE_CURRENT_DESK, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_ACTIVATE_0, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_ACTIVATE_1, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_ACTIVATE_2, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_ACTIVATE_3, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_ACTIVATE_4, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_ACTIVATE_5, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_ACTIVATE_6, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_ACTIVATE_7, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DESKS_TOGGLE_ASSIGN_TO_ALL_DESKS, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DISABLE_CAPS_LOCK, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {EXIT, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {FOCUS_CAMERA_PREVIEW, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {FOCUS_NEXT_PANE, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {FOCUS_PREVIOUS_PANE, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {FOCUS_SHELF, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {FOCUS_PIP, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {KEYBOARD_BACKLIGHT_TOGGLE, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {KEYBOARD_BRIGHTNESS_DOWN, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {KEYBOARD_BRIGHTNESS_UP, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LAUNCH_APP_0, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LAUNCH_APP_1, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LAUNCH_APP_2, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LAUNCH_APP_3, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LAUNCH_APP_4, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LAUNCH_APP_5, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LAUNCH_APP_6, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LAUNCH_APP_7, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LAUNCH_LAST_APP, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LOCK_PRESSED, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LOCK_RELEASED, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {LOCK_SCREEN, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MAGNIFIER_ZOOM_IN, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MAGNIFIER_ZOOM_OUT, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MEDIA_FAST_FORWARD, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MEDIA_NEXT_TRACK, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MEDIA_PAUSE, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MEDIA_PLAY, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MEDIA_PLAY_PAUSE, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MEDIA_PREV_TRACK, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MEDIA_REWIND, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MEDIA_STOP, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MICROPHONE_MUTE_TOGGLE, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MOVE_ACTIVE_WINDOW_BETWEEN_DISPLAYS, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {NEW_INCOGNITO_WINDOW, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {NEW_TAB, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {NEW_WINDOW, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {OPEN_CALCULATOR, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {OPEN_CROSH, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {OPEN_DIAGNOSTICS, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {OPEN_FEEDBACK_PAGE, - {mojom::AcceleratorCategory::kSystem, - mojom::AcceleratorSubcategory::kSystemApps, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {OPEN_FILE_MANAGER, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {OPEN_GET_HELP, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {POWER_PRESSED, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {POWER_RELEASED, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {PRINT_UI_HIERARCHIES, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {PRIVACY_SCREEN_TOGGLE, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {RESTORE_TAB, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {ROTATE_SCREEN, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {ROTATE_WINDOW, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SCALE_UI_DOWN, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SCALE_UI_RESET, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SCALE_UI_UP, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SHOW_EMOJI_PICKER, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_IME_MENU_BUBBLE, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SHOW_SHORTCUT_VIEWER, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SHOW_STYLUS_TOOLS, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SHOW_TASK_MANAGER, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {START_AMBIENT_MODE, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {START_ASSISTANT, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SUSPEND, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SWAP_PRIMARY_DISPLAY, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SWITCH_IME, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SWITCH_TO_LAST_USED_IME, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SWITCH_TO_NEXT_IME, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SWITCH_TO_NEXT_USER, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {SWITCH_TO_PREVIOUS_USER, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TAKE_PARTIAL_SCREENSHOT, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TAKE_SCREENSHOT, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TAKE_WINDOW_SCREENSHOT, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_APP_LIST, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_CALENDAR, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_CAPS_LOCK, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_CLIPBOARD_HISTORY, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_DICTATION, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_DOCKED_MAGNIFIER, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_FLOATING, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_FULLSCREEN, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_FULLSCREEN_MAGNIFIER, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_HIGH_CONTRAST, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_MAXIMIZED, - {mojom::AcceleratorCategory::kWindowsAndDesk, - mojom::AcceleratorSubcategory::kSystemControls, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_MESSAGE_CENTER_BUBBLE, - {mojom::AcceleratorCategory::kTabsAndPages, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_MIRROR_MODE, - {mojom::AcceleratorCategory::kTabsAndPages, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_OVERVIEW, - {mojom::AcceleratorCategory::kTabsAndPages, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_PROJECTOR_MARKER, - {mojom::AcceleratorCategory::kTabsAndPages, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_RESIZE_LOCK_MENU, - {mojom::AcceleratorCategory::kTabsAndPages, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_SPOKEN_FEEDBACK, - {mojom::AcceleratorCategory::kTabsAndPages, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_SYSTEM_TRAY_BUBBLE, - {mojom::AcceleratorCategory::kTabsAndPages, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOGGLE_WIFI, - {mojom::AcceleratorCategory::kTabsAndPages, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOUCH_HUD_CLEAR, - {mojom::AcceleratorCategory::kTabsAndPages, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {TOUCH_HUD_MODE_CHANGE, - {mojom::AcceleratorCategory::kTabsAndPages, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {UNPIN, - {mojom::AcceleratorCategory::kTextAndInput, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {VOLUME_DOWN, - {mojom::AcceleratorCategory::kTextAndInput, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {VOLUME_MUTE, - {mojom::AcceleratorCategory::kTextAndInput, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {VOLUME_UP, - {mojom::AcceleratorCategory::kTextAndInput, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {WINDOW_CYCLE_SNAP_LEFT, - {mojom::AcceleratorCategory::kTextAndInput, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {WINDOW_CYCLE_SNAP_RIGHT, - {mojom::AcceleratorCategory::kTextAndInput, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {WINDOW_MINIMIZE, - {mojom::AcceleratorCategory::kTextAndInput, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {MINIMIZE_TOP_WINDOW_ON_BACK, - {mojom::AcceleratorCategory::kTextAndInput, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_DUMP_CALENDAR_MODEL, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_KEYBOARD_BACKLIGHT_TOGGLE, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_MICROPHONE_MUTE_TOGGLE, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_PRINT_LAYER_HIERARCHY, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_PRINT_VIEW_HIERARCHY, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_PRINT_WINDOW_HIERARCHY, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_SHOW_TOAST, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_SYSTEM_UI_STYLE_VIEWER, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TUCK_FLOATED_WINDOW_LEFT, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TUCK_FLOATED_WINDOW_RIGHT, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_DARK_MODE, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_DYNAMIC_COLOR, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_GLANCEABLES, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_SHOW_DEBUG_BORDERS, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_SHOW_FPS_COUNTER, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_SHOW_PAINT_RECTS, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_TOUCH_PAD, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_TOUCH_SCREEN, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_TABLET_MODE, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_WALLPAPER_MODE, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TRIGGER_CRASH, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEBUG_TOGGLE_HUD_DISPLAY, - {mojom::AcceleratorCategory::kDebug, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEV_ADD_REMOVE_DISPLAY, - {mojom::AcceleratorCategory::kDeveloper, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEV_TOGGLE_APP_LIST, - {mojom::AcceleratorCategory::kDeveloper, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - {DEV_TOGGLE_UNIFIED_DESKTOP, - {mojom::AcceleratorCategory::kDeveloper, - mojom::AcceleratorSubcategory::kGeneral, - /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault}}, - }); - -} // namespace ash
diff --git a/ash/accelerators/accelerator_layout_table.h b/ash/accelerators/accelerator_layout_table.h index b861ae6..f4b96a1 100644 --- a/ash/accelerators/accelerator_layout_table.h +++ b/ash/accelerators/accelerator_layout_table.h
@@ -13,17 +13,14 @@ #include "ash/public/mojom/accelerator_info.mojom.h" #include "base/containers/fixed_flat_map.h" -namespace { - -// Derived from the actions listed in `ash/accelerators/accelerator_table.h`. -constexpr int kNumAcceleratorActions = 143; - -} // namespace - namespace ash { // Contains details for UI styling of an accelerator. struct ASH_EXPORT AcceleratorLayoutDetails { + // The accelerator action id associated for a source. Concat `source` and + // `action_id` to get a unique identifier for an accelerator action. + uint32_t action_id; + // Category of the accelerator. mojom::AcceleratorCategory category; @@ -37,18 +34,592 @@ // The layout style of the accelerator, this provides additional context // on how to accelerator should be represented in the UI. mojom::AcceleratorLayoutStyle layout_style; + + // The source of which the accelerator is from. + mojom::AcceleratorSource source; }; -// A map between an accelerator action id and AcceleratorLayoutDetails. This map -// provides the UI-related details for an accelerator. -// Adding a new accelerator must add a new entry to this map. +// A fixed array of accelerator layouts used for categorization and styling of +// accelerator actions. The ordering of the array is important and is used +// 1:1 for displaying shortcuts in the shortcut customization app. +// Adding an accelerator layout in this array will create a new entry in the +// app. // TODO(jimmyxgong): This is a stub map with stub details, replace with real // one when categorization is available. -ASH_EXPORT extern const base::fixed_flat_map<AcceleratorAction, - AcceleratorLayoutDetails, - kNumAcceleratorActions, - std::less<>> - kAcceleratorLayouts; +ASH_EXPORT constexpr AcceleratorLayoutDetails kAcceleratorLayouts[] = { + {BRIGHTNESS_DOWN, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {BRIGHTNESS_UP, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {CYCLE_BACKWARD_MRU, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {CYCLE_FORWARD_MRU, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_ACTIVATE_DESK_LEFT, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_ACTIVATE_DESK_RIGHT, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_MOVE_ACTIVE_ITEM_LEFT, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_MOVE_ACTIVE_ITEM_RIGHT, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_NEW_DESK, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_REMOVE_CURRENT_DESK, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_ACTIVATE_0, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_ACTIVATE_1, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_ACTIVATE_2, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_ACTIVATE_3, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_ACTIVATE_4, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_ACTIVATE_5, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_ACTIVATE_6, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_ACTIVATE_7, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DESKS_TOGGLE_ASSIGN_TO_ALL_DESKS, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DISABLE_CAPS_LOCK, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {EXIT, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {FOCUS_CAMERA_PREVIEW, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {FOCUS_NEXT_PANE, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {FOCUS_PREVIOUS_PANE, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {FOCUS_SHELF, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {FOCUS_PIP, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {KEYBOARD_BACKLIGHT_TOGGLE, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {KEYBOARD_BRIGHTNESS_DOWN, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {KEYBOARD_BRIGHTNESS_UP, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LAUNCH_APP_0, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LAUNCH_APP_1, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LAUNCH_APP_2, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LAUNCH_APP_3, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LAUNCH_APP_4, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LAUNCH_APP_5, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LAUNCH_APP_6, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LAUNCH_APP_7, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LAUNCH_LAST_APP, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LOCK_PRESSED, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LOCK_RELEASED, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {LOCK_SCREEN, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MAGNIFIER_ZOOM_IN, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MAGNIFIER_ZOOM_OUT, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MEDIA_FAST_FORWARD, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MEDIA_NEXT_TRACK, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MEDIA_PAUSE, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MEDIA_PLAY, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MEDIA_PLAY_PAUSE, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MEDIA_PREV_TRACK, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MEDIA_REWIND, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MEDIA_STOP, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MICROPHONE_MUTE_TOGGLE, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MOVE_ACTIVE_WINDOW_BETWEEN_DISPLAYS, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {NEW_INCOGNITO_WINDOW, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {NEW_TAB, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {NEW_WINDOW, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {OPEN_CALCULATOR, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {OPEN_CROSH, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {OPEN_DIAGNOSTICS, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {OPEN_FEEDBACK_PAGE, mojom::AcceleratorCategory::kSystem, + mojom::AcceleratorSubcategory::kSystemApps, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {OPEN_FILE_MANAGER, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {OPEN_GET_HELP, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {POWER_PRESSED, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {POWER_RELEASED, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {PRINT_UI_HIERARCHIES, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {PRIVACY_SCREEN_TOGGLE, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {RESTORE_TAB, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {ROTATE_SCREEN, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {ROTATE_WINDOW, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SCALE_UI_DOWN, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SCALE_UI_RESET, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SCALE_UI_UP, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SHOW_EMOJI_PICKER, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_IME_MENU_BUBBLE, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SHOW_SHORTCUT_VIEWER, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SHOW_STYLUS_TOOLS, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SHOW_TASK_MANAGER, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {START_AMBIENT_MODE, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {START_ASSISTANT, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SUSPEND, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SWAP_PRIMARY_DISPLAY, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SWITCH_IME, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SWITCH_TO_LAST_USED_IME, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SWITCH_TO_NEXT_IME, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SWITCH_TO_NEXT_USER, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {SWITCH_TO_PREVIOUS_USER, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TAKE_PARTIAL_SCREENSHOT, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TAKE_SCREENSHOT, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TAKE_WINDOW_SCREENSHOT, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_APP_LIST, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_CALENDAR, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_CAPS_LOCK, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_CLIPBOARD_HISTORY, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_DICTATION, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_DOCKED_MAGNIFIER, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_FLOATING, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_FULLSCREEN, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_FULLSCREEN_MAGNIFIER, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_HIGH_CONTRAST, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_MAXIMIZED, mojom::AcceleratorCategory::kWindowsAndDesk, + mojom::AcceleratorSubcategory::kSystemControls, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_MESSAGE_CENTER_BUBBLE, mojom::AcceleratorCategory::kTabsAndPages, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_MIRROR_MODE, mojom::AcceleratorCategory::kTabsAndPages, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_OVERVIEW, mojom::AcceleratorCategory::kTabsAndPages, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_PROJECTOR_MARKER, mojom::AcceleratorCategory::kTabsAndPages, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_RESIZE_LOCK_MENU, mojom::AcceleratorCategory::kTabsAndPages, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_SPOKEN_FEEDBACK, mojom::AcceleratorCategory::kTabsAndPages, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_SYSTEM_TRAY_BUBBLE, mojom::AcceleratorCategory::kTabsAndPages, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOGGLE_WIFI, mojom::AcceleratorCategory::kTabsAndPages, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOUCH_HUD_CLEAR, mojom::AcceleratorCategory::kTabsAndPages, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {TOUCH_HUD_MODE_CHANGE, mojom::AcceleratorCategory::kTabsAndPages, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {UNPIN, mojom::AcceleratorCategory::kTextAndInput, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {VOLUME_DOWN, mojom::AcceleratorCategory::kTextAndInput, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {VOLUME_MUTE, mojom::AcceleratorCategory::kTextAndInput, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {VOLUME_UP, mojom::AcceleratorCategory::kTextAndInput, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {WINDOW_CYCLE_SNAP_LEFT, mojom::AcceleratorCategory::kTextAndInput, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {WINDOW_CYCLE_SNAP_RIGHT, mojom::AcceleratorCategory::kTextAndInput, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {WINDOW_MINIMIZE, mojom::AcceleratorCategory::kTextAndInput, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {MINIMIZE_TOP_WINDOW_ON_BACK, mojom::AcceleratorCategory::kTextAndInput, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_DUMP_CALENDAR_MODEL, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_KEYBOARD_BACKLIGHT_TOGGLE, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_MICROPHONE_MUTE_TOGGLE, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_PRINT_LAYER_HIERARCHY, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_PRINT_VIEW_HIERARCHY, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_PRINT_WINDOW_HIERARCHY, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_SHOW_TOAST, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_SYSTEM_UI_STYLE_VIEWER, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TUCK_FLOATED_WINDOW_LEFT, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TUCK_FLOATED_WINDOW_RIGHT, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_DARK_MODE, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_DYNAMIC_COLOR, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_GLANCEABLES, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_SHOW_DEBUG_BORDERS, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_SHOW_FPS_COUNTER, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_SHOW_PAINT_RECTS, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_TOUCH_PAD, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_TOUCH_SCREEN, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_TABLET_MODE, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_WALLPAPER_MODE, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TRIGGER_CRASH, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEBUG_TOGGLE_HUD_DISPLAY, mojom::AcceleratorCategory::kDebug, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEV_ADD_REMOVE_DISPLAY, mojom::AcceleratorCategory::kDeveloper, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEV_TOGGLE_APP_LIST, mojom::AcceleratorCategory::kDeveloper, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, + {DEV_TOGGLE_UNIFIED_DESKTOP, mojom::AcceleratorCategory::kDeveloper, + mojom::AcceleratorSubcategory::kGeneral, + /*locked=*/true, mojom::AcceleratorLayoutStyle::kDefault, + mojom::AcceleratorSource::kAsh}, +}; } // namespace ash #endif // ASH_ACCELERATORS_ACCELERATOR_LAYOUT_TABLE_H_
diff --git a/ash/display/display_color_manager.cc b/ash/display/display_color_manager.cc index 73b8d29a..fafa18c 100644 --- a/ash/display/display_color_manager.cc +++ b/ash/display/display_color_manager.cc
@@ -17,7 +17,6 @@ #include "base/path_service.h" #include "base/system/sys_info.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "components/quirks/quirks_manager.h" @@ -415,8 +414,8 @@ << " for display id: " << display_id << " with product id: " << product_string; - base::PostTaskAndReplyWithResult( - sequenced_task_runner_.get(), FROM_HERE, + sequenced_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ParseDisplayProfile, path, has_color_correction_matrix), base::BindOnce(&DisplayColorManager::UpdateCalibrationData, weak_ptr_factory_.GetWeakPtr(), display_id, product_code));
diff --git a/ash/public/cpp/ambient/ambient_ui_model.h b/ash/public/cpp/ambient/ambient_ui_model.h index fb2f4d3..2346fda 100644 --- a/ash/public/cpp/ambient/ambient_ui_model.h +++ b/ash/public/cpp/ambient/ambient_ui_model.h
@@ -16,9 +16,9 @@ enum class AmbientUiVisibility { kShown, // Screen saver is shown. kPreview, // Same as kShown, but do not lock screen or acquire wake lock. - // kPreview state is used to show a preview of the screensaver. - // Users should be able to exit from the preview mode directly - // into. Hence, no need to lock the screen or acquire wake lock. + // kPreview state is used to show a preview of the screen saver. + // Users should be able to exit from the preview mode directly. + // Hence, no need to lock the screen or acquire wake lock. kHidden, // Screen saver is closed; start inactivity timer to restart it. kClosed, // Screen saver is closed; all observers and timers are cancelled. };
diff --git a/ash/quick_pair/common/fast_pair/fast_pair_metrics.cc b/ash/quick_pair/common/fast_pair/fast_pair_metrics.cc index a838e72..815acfd 100644 --- a/ash/quick_pair/common/fast_pair/fast_pair_metrics.cc +++ b/ash/quick_pair/common/fast_pair/fast_pair_metrics.cc
@@ -486,6 +486,7 @@ "Bluetooth.ChromeOS.FastPair.FootprintsFetcher.Get.HttpResponseError"; const char kFastPairRepositoryCacheResult[] = "Bluetooth.ChromeOS.FastPair.FastPairRepository.Cache.Result"; +const char kFastPairGattConnectionStep[] = "ChromeOS.FastPair.GattConnection"; const char kHandshakeResult[] = "Bluetooth.ChromeOS.FastPair.Handshake.Result"; const char kFastPairHandshakeStepInitial[] = "Bluetooth.ChromeOS.FastPair.Handshake.Steps.InitialPairingProtocol"; @@ -881,6 +882,12 @@ base::UmaHistogramBoolean(kFastPairRepositoryCacheResult, success); } +void RecordGattInitializationStep( + FastPairGattConnectionSteps initialization_step) { + base::UmaHistogramEnumeration(kFastPairGattConnectionStep, + initialization_step); +} + void RecordHandshakeResult(bool success) { base::UmaHistogramBoolean(kHandshakeResult, success); }
diff --git a/ash/quick_pair/common/fast_pair/fast_pair_metrics.h b/ash/quick_pair/common/fast_pair/fast_pair_metrics.h index 320d34a7..38d870a 100644 --- a/ash/quick_pair/common/fast_pair/fast_pair_metrics.h +++ b/ash/quick_pair/common/fast_pair/fast_pair_metrics.h
@@ -119,6 +119,19 @@ kMaxValue = kHandshakeComplete, }; +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. This enum should be kept in sync +// with the FastPairGattConnectionSteps enum in +// src/tools/metrics/histograms/enums.xml. +enum class COMPONENT_EXPORT(QUICK_PAIR_COMMON) FastPairGattConnectionSteps { + kConnectionStarted = 0, + kConnectionReady = 1, + kFoundKeybasedPairingCharacteristic = 2, + kNotifiationsEnabledForKeybasedPairing = 3, + kConnectionEstablished = 4, + kMaxValue = kConnectionEstablished +}; + COMPONENT_EXPORT(QUICK_PAIR_COMMON) void AttemptRecordingFastPairEngagementFlow(const Device& device, FastPairEngagementFlowEvent event); @@ -255,6 +268,10 @@ void RecordFastPairRepositoryCacheResult(bool success); COMPONENT_EXPORT(QUICK_PAIR_COMMON) +void RecordGattInitializationStep( + FastPairGattConnectionSteps initialization_step); + +COMPONENT_EXPORT(QUICK_PAIR_COMMON) void RecordHandshakeResult(bool success); COMPONENT_EXPORT(QUICK_PAIR_COMMON)
diff --git a/ash/quick_pair/common/pair_failure.cc b/ash/quick_pair/common/pair_failure.cc index 31d12514..4314245 100644 --- a/ash/quick_pair/common/pair_failure.cc +++ b/ash/quick_pair/common/pair_failure.cc
@@ -87,6 +87,9 @@ stream << "[[BLE device instance lost mid pair with classic device " "instance]]"; break; + case PairFailure::kCreateBondTimeout: + stream << "[Timed out while attempting to create bond with device]"; + break; } return stream;
diff --git a/ash/quick_pair/common/pair_failure.h b/ash/quick_pair/common/pair_failure.h index 20d8d00..d04d8cc 100644 --- a/ash/quick_pair/common/pair_failure.h +++ b/ash/quick_pair/common/pair_failure.h
@@ -66,7 +66,9 @@ kAddressConnect = 22, // BLE device instance lost mid pair with classic instance kBleDeviceLostMidPair = 23, - kMaxValue = kBleDeviceLostMidPair, + // Timed out attempting to bond to device. + kCreateBondTimeout = 24, + kMaxValue = kCreateBondTimeout, }; COMPONENT_EXPORT(QUICK_PAIR_COMMON)
diff --git a/ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client_impl.cc b/ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client_impl.cc index ae4d877..3f56e8a 100644 --- a/ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client_impl.cc +++ b/ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client_impl.cc
@@ -134,6 +134,8 @@ adapter_observation_.Observe(adapter_.get()); QP_LOG(INFO) << __func__ << ": Starting the GATT connection to device"; + RecordGattInitializationStep(FastPairGattConnectionSteps::kConnectionStarted); + device->CreateGattConnection( base::BindOnce(&FastPairGattServiceClientImpl::OnGattConnection, weak_ptr_factory_.GetWeakPtr(), base::TimeTicks::Now()), @@ -227,6 +229,7 @@ service->GetDevice()->GetAddress() == device_address_) { QP_LOG(INFO) << __func__ << ": Completed discovery for Fast Pair GATT service"; + RecordGattInitializationStep(FastPairGattConnectionSteps::kConnectionReady); gatt_service_ = service; FindGattCharacteristicsAndStartNotifySessions(); } @@ -257,6 +260,8 @@ PairFailure::kKeyBasedPairingCharacteristicDiscovery); return; } + RecordGattInitializationStep( + FastPairGattConnectionSteps::kFoundKeybasedPairingCharacteristic); std::vector<device::BluetoothRemoteGattCharacteristic*> passkey_characteristics = GetCharacteristicsByUUIDs( @@ -311,6 +316,8 @@ if (key_based_characteristic_ && session->GetCharacteristic() == key_based_characteristic_) { keybased_notify_session_timer_.Stop(); + RecordGattInitializationStep( + FastPairGattConnectionSteps::kNotifiationsEnabledForKeybasedPairing); } else if (passkey_characteristic_ && session->GetCharacteristic() == passkey_characteristic_) { passkey_notify_session_timer_.Stop(); @@ -323,6 +330,9 @@ // pass key characteristics to notify, thus size "2"; if (bluetooth_gatt_notify_sessions_.size() == 2) { QP_LOG(INFO) << __func__ << ": Finished initializing GATT service"; + RecordGattInitializationStep( + FastPairGattConnectionSteps::kConnectionEstablished); + is_initialized_ = true; // This check handles the case where a timer for the characteristic's notify
diff --git a/ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client_unittest.cc b/ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client_unittest.cc index 3127dda..af9da7b3b 100644 --- a/ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client_unittest.cc +++ b/ash/quick_pair/fast_pair_handshake/fast_pair_gatt_service_client_unittest.cc
@@ -56,6 +56,7 @@ "Bluetooth.ChromeOS.FastPair.AccountKey.Write.GattErrorReason"; const char kWriteAccountKeyTimeMetric[] = "Bluetooth.ChromeOS.FastPair.AccountKey.Write.TotalTime"; +const char kFastPairGattConnectionStep[] = "ChromeOS.FastPair.GattConnection"; constexpr base::TimeDelta kConnectingTestTimeout = base::Seconds(15); @@ -559,12 +560,14 @@ histogram_tester().ExpectTotalCount(kWritePasskeyCharacteristicGattError, 0); histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); histogram_tester().ExpectTotalCount(kNotifyPasskeyCharacteristicTime, 0); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 0); SuccessfulGattConnectionSetUp(); FastForwardTimeByConnetingTimeout(); NotifyGattDiscoveryCompleteForService(); EXPECT_EQ(GetInitializedCallbackResult(), PairFailure::kGattServiceDiscoveryTimeout); EXPECT_FALSE(ServiceIsSet()); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 1); histogram_tester().ExpectTotalCount(kTotalGattConnectionTime, 1); histogram_tester().ExpectTotalCount(kGattConnectionResult, 1); histogram_tester().ExpectTotalCount(kWriteKeyBasedCharacteristicGattError, 0); @@ -581,9 +584,11 @@ histogram_tester().ExpectTotalCount(kWriteKeyBasedCharacteristicGattError, 0); histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); histogram_tester().ExpectTotalCount(kNotifyPasskeyCharacteristicTime, 0); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 0); FailedGattConnectionSetUp(); EXPECT_EQ(GetInitializedCallbackResult(), PairFailure::kCreateGattConnection); EXPECT_FALSE(ServiceIsSet()); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 1); histogram_tester().ExpectTotalCount(kTotalGattConnectionTime, 0); histogram_tester().ExpectTotalCount(kGattConnectionResult, 1); histogram_tester().ExpectTotalCount(kGattConnectionErrorMetric, 1); @@ -602,9 +607,11 @@ histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); histogram_tester().ExpectTotalCount(kWritePasskeyCharacteristicGattError, 0); histogram_tester().ExpectTotalCount(kNotifyPasskeyCharacteristicTime, 0); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 0); SuccessfulGattConnectionSetUp(); NotifyGattDiscoveryCompleteForService(); EXPECT_TRUE(gatt_service_client_->IsConnected()); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 5); histogram_tester().ExpectTotalCount(kTotalGattConnectionTime, 1); histogram_tester().ExpectTotalCount(kGattConnectionResult, 1); histogram_tester().ExpectTotalCount(kGattConnectionErrorMetric, 0); @@ -622,12 +629,14 @@ TEST_F(FastPairGattServiceClientTest, FailedKeyBasedCharacteristics) { histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 0); SetKeybasedCharacteristicError(true); SuccessfulGattConnectionSetUp(); NotifyGattDiscoveryCompleteForService(); EXPECT_EQ(GetInitializedCallbackResult(), PairFailure::kKeyBasedPairingCharacteristicDiscovery); EXPECT_FALSE(ServiceIsSet()); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 2); histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); } @@ -642,12 +651,14 @@ TEST_F(FastPairGattServiceClientTest, SuccessfulCharacteristicsStartNotify) { histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 0); SetKeybasedCharacteristicError(false); SetPasskeyCharacteristicError(false); SuccessfulGattConnectionSetUp(); NotifyGattDiscoveryCompleteForService(); EXPECT_EQ(GetInitializedCallbackResult(), absl::nullopt); EXPECT_TRUE(ServiceIsSet()); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 5); histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); } @@ -664,12 +675,14 @@ TEST_F(FastPairGattServiceClientTest, StartNotifyKeybasedFailure) { histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 0); SuccessfulGattConnectionSetUp(); SetKeybasedNotifySessionError(true); NotifyGattDiscoveryCompleteForService(); EXPECT_EQ(GetInitializedCallbackResult(), PairFailure::kKeyBasedPairingCharacteristicNotifySession); EXPECT_FALSE(ServiceIsSet()); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 3); histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); } @@ -686,12 +699,14 @@ TEST_F(FastPairGattServiceClientTest, KeyBasedStartNotifyTimeout) { histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 0); SetKeybasedNotifySessionTimeout(true); SuccessfulGattConnectionSetUp(); NotifyGattDiscoveryCompleteForService(); EXPECT_EQ(GetInitializedCallbackResult(), PairFailure::kKeyBasedPairingCharacteristicNotifySessionTimeout); EXPECT_FALSE(ServiceIsSet()); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 4); histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); } @@ -710,6 +725,7 @@ TEST_F(FastPairGattServiceClientTest, WriteKeyBasedRequest) { histogram_tester().ExpectTotalCount(kWriteKeyBasedCharacteristicGattError, 0); histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 0); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 0); SuccessfulGattConnectionSetUp(); NotifyGattDiscoveryCompleteForService(); EXPECT_EQ(GetInitializedCallbackResult(), absl::nullopt); @@ -717,6 +733,7 @@ WriteRequestToKeyBased(); TriggerKeyBasedGattChanged(); EXPECT_EQ(GetWriteCallbackResult(), absl::nullopt); + histogram_tester().ExpectTotalCount(kFastPairGattConnectionStep, 5); histogram_tester().ExpectTotalCount(kWriteKeyBasedCharacteristicGattError, 0); histogram_tester().ExpectTotalCount(kNotifyKeyBasedCharacteristicTime, 1); }
diff --git a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.cc b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.cc index e0b4d84..d2870b2e 100644 --- a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.cc +++ b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.cc
@@ -33,6 +33,9 @@ namespace { +// 15s timeout chosen to align with Android's Fast Pair implementation. +constexpr base::TimeDelta kCreateBondTimeout = base::Seconds(15); + std::string MessageTypeToString( ash::quick_pair::FastPairMessageType message_type) { switch (message_type) { @@ -251,7 +254,6 @@ void FastPairPairerImpl::StartPairing() { std::string device_address = device_->classic_address().value(); device::BluetoothDevice* bt_device = adapter_->GetDevice(device_address); - switch (device_->protocol) { case Protocol::kFastPairInitial: case Protocol::kFastPairSubsequent: @@ -264,21 +266,27 @@ << device_address << ". Found device: " << ((bt_device != nullptr) ? "Yes" : "No") << "."; - if (bt_device) { - if (bt_device->IsBonded()) { - QP_LOG(INFO) << __func__ - << ": Trying to pair to device that is already paired; " - "returning success."; - std::move(paired_callback_).Run(device_); - // In addition to recording kPairingSuccess in the callback above, - // also record that the device was already paired. - AttemptRecordingFastPairEngagementFlow( - *device_, - FastPairEngagementFlowEvent::kPairingSucceededAlreadyPaired); - AttemptSendAccountKey(); - return; - } + if (bt_device && bt_device->IsBonded()) { + QP_LOG(INFO) << __func__ + << ": Trying to pair to device that is already paired; " + "returning success."; + std::move(paired_callback_).Run(device_); + // In addition to recording kPairingSuccess in the callback above, + // also record that the device was already paired. + AttemptRecordingFastPairEngagementFlow( + *device_, + FastPairEngagementFlowEvent::kPairingSucceededAlreadyPaired); + AttemptSendAccountKey(); + return; + } + + create_bond_timeout_timer_.Start( + FROM_HERE, kCreateBondTimeout, + base::BindOnce(&FastPairPairerImpl::OnCreateBondTimeout, + base::Unretained(this))); + + if (bt_device) { bt_device->Pair(this, base::BindOnce(&FastPairPairerImpl::OnPairConnected, weak_ptr_factory_.GetWeakPtr())); @@ -286,7 +294,6 @@ adapter_->AddPairingDelegate( this, device::BluetoothAdapter::PairingDelegatePriority:: PAIRING_DELEGATE_PRIORITY_HIGH); - adapter_->ConnectDevice( device_address, /*address_type=*/absl::nullopt, @@ -308,6 +315,9 @@ void FastPairPairerImpl::OnPairConnected( absl::optional<device::BluetoothDevice::ConnectErrorCode> error) { + if (!StopCreateBondTimer(__func__)) + return; + QP_LOG(INFO) << __func__; RecordPairDeviceResult(/*success=*/!error.has_value()); @@ -325,6 +335,9 @@ } void FastPairPairerImpl::OnConnectDevice(device::BluetoothDevice* device) { + if (!StopCreateBondTimer(__func__)) + return; + QP_LOG(INFO) << __func__; ask_confirm_passkey_initial_time_ = base::TimeTicks::Now(); RecordConnectDeviceResult(/*success=*/true); @@ -334,6 +347,9 @@ } void FastPairPairerImpl::OnConnectError(const std::string& error_message) { + if (!StopCreateBondTimer(__func__)) + return; + QP_LOG(WARNING) << __func__ << " " << error_message; RecordConnectDeviceResult(/*success=*/false); std::move(pair_failed_callback_).Run(device_, PairFailure::kAddressConnect); @@ -676,5 +692,25 @@ } } +void FastPairPairerImpl::OnCreateBondTimeout() { + QP_LOG(WARNING) << __func__ + << ": Timeout while attempting to create bond with device."; + std::move(pair_failed_callback_) + .Run(device_, PairFailure::kCreateBondTimeout); +} + +bool FastPairPairerImpl::StopCreateBondTimer(const std::string& callback_name) { + if (create_bond_timeout_timer_.IsRunning()) { + create_bond_timeout_timer_.Stop(); + return true; + } + + QP_LOG(WARNING) << __func__ << ": " << callback_name + << " called after an attempt to create a bond with device" + "with classic address " + << device_->classic_address().value() << " has timed out."; + return false; +} + } // namespace quick_pair } // namespace ash
diff --git a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.h b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.h index 4730cee..f528ef2 100644 --- a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.h +++ b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl.h
@@ -14,6 +14,7 @@ #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "base/time/time.h" +#include "base/timer/timer.h" #include "chromeos/ash/services/quick_pair/public/cpp/decrypted_passkey.h" #include "chromeos/ash/services/quick_pair/public/cpp/decrypted_response.h" #include "device/bluetooth/bluetooth_device.h" @@ -111,6 +112,13 @@ device::BluetoothDevice* device, bool new_paired_status) override; + // Helper to safely stop |create_bond_timeout_timer_|. + // If the timer can be stopped because it is running, this function returns + // true. If the timer cannot be stopped, this function returns false, + // informing the caller that the timer has expired and the caller should not + // proceed with bond creation. + bool StopCreateBondTimer(const std::string& callback_name); + // device::BluetoothDevice::Pair callback void OnPairConnected( absl::optional<device::BluetoothDevice::ConnectErrorCode> error); @@ -119,6 +127,10 @@ void OnConnectDevice(device::BluetoothDevice* device); void OnConnectError(const std::string& error_message); + // Callback for timeout on creating a bond with |device_| in + // StartPairing. + void OnCreateBondTimeout(); + // FastPairHandshakeLookup::Create callback void OnHandshakeComplete(scoped_refptr<Device> device, absl::optional<PairFailure> failure); @@ -173,6 +185,10 @@ base::ScopedObservation<device::BluetoothAdapter, device::BluetoothAdapter::Observer> adapter_observation_{this}; + + // A timer to time the bonding with |device_| in StartPairing and invoke a + // timeout if necessary. + base::OneShotTimer create_bond_timeout_timer_; base::WeakPtrFactory<FastPairPairerImpl> weak_ptr_factory_{this}; };
diff --git a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl_unittest.cc b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl_unittest.cc index e9bccfd2..643a2b2 100644 --- a/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl_unittest.cc +++ b/ash/quick_pair/pairing/fast_pair/fast_pair_pairer_impl_unittest.cc
@@ -2284,5 +2284,39 @@ /*success=*/false, 0); } +// There are two pairing flows in which PairFailure::kCreateBondTimeout occurs. +// In this test's scenario, |adapter_| knows of |device_|, so the +// FastPairPairerImpl object in |fake_fast_pair_handshake_| will attempt and +// fail to pair with it directly using FastPairPairerImpl::Pair. +TEST_F(FastPairPairerImplTest, CreateBondTimeout_AdapterHasDeviceAddress) { + Login(user_manager::UserType::USER_TYPE_REGULAR); + base::RunLoop().RunUntilIdle(); + + CreateMockDevice(DeviceFastPairVersion::kHigherThanV1, + /*protocol=*/Protocol::kFastPairInitial); + CreatePairer(); + fake_fast_pair_handshake_->InvokeCallback(PairFailure::kCreateBondTimeout); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(GetPairFailure(), PairFailure::kCreateBondTimeout); +} + +// There are two pairing flows in which PairFailure::kCreateBondTimeout occurs. +// In this test's scenario, |adapter_| doesn't know of |device_|, so the +// FastPairPairerImpl object in |fake_fast_pair_handshake_| will attempt and +// fail to connect with it using FastPairPairerImpl::ConnectDevice. +TEST_F(FastPairPairerImplTest, + CreateBondTimeout_AdapterDoesNotHaveDeviceAddress) { + Login(user_manager::UserType::USER_TYPE_REGULAR); + base::RunLoop().RunUntilIdle(); + + CreateMockDevice(DeviceFastPairVersion::kHigherThanV1, + /*protocol=*/Protocol::kFastPairInitial); + SetGetDeviceNullptr(); + CreatePairer(); + fake_fast_pair_handshake_->InvokeCallback(PairFailure::kCreateBondTimeout); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(GetPairFailure(), PairFailure::kCreateBondTimeout); +} + } // namespace quick_pair } // namespace ash
diff --git a/ash/system/notification_center/notification_center_tray.cc b/ash/system/notification_center/notification_center_tray.cc index 59430309..f5c41d4 100644 --- a/ash/system/notification_center/notification_center_tray.cc +++ b/ash/system/notification_center/notification_center_tray.cc
@@ -45,9 +45,6 @@ } NotificationCenterTray::~NotificationCenterTray() { - if (GetBubbleWidget()) - GetBubbleWidget()->RemoveObserver(this); - message_center::MessageCenter::Get()->RemoveObserver(this); } @@ -64,7 +61,10 @@ void NotificationCenterTray::HandleLocaleChange() {} void NotificationCenterTray::HideBubbleWithView( - const TrayBubbleView* bubble_view) {} + const TrayBubbleView* bubble_view) { + if (bubble_->GetBubbleView() == bubble_view) + CloseBubble(); +} void NotificationCenterTray::ClickedOutsideBubble() { CloseBubble(); @@ -74,9 +74,6 @@ if (!bubble_) return; - if (GetBubbleWidget()) - GetBubbleWidget()->RemoveObserver(this); - bubble_.reset(); SetIsActive(false); @@ -91,13 +88,6 @@ return; bubble_ = std::make_unique<NotificationCenterBubble>(this); - - // Observe the bubble widget so that we can do proper clean up when it is - // being destroyed. If destruction is due to a call to `CloseBubble()` we will - // have already cleaned up state but there are cases where the bubble widget - // is destroyed independent of a call to `CloseBubble()`, e.g. ESC key press. - GetBubbleWidget()->AddObserver(this); - SetIsActive(true); // Inform the message center that the bubble is showing so that we do not @@ -140,13 +130,6 @@ UpdateVisibility(); } -// We need to call `CloseBubble()` explicitly if the bubble's widget is -// destroyed independently of `CloseBubble()` e.g. ESC key press. The bubble -// needs to be cleaned up here since it is owned by `NotificationCenterTray`. -void NotificationCenterTray::OnWidgetDestroying(views::Widget* widget) { - CloseBubble(); -} - void NotificationCenterTray::UpdateVisibility() { const bool new_visibility = message_center::MessageCenter::Get()->NotificationCount() > 0 &&
diff --git a/ash/system/notification_center/notification_center_tray.h b/ash/system/notification_center/notification_center_tray.h index 1398187..0700bfe 100644 --- a/ash/system/notification_center/notification_center_tray.h +++ b/ash/system/notification_center/notification_center_tray.h
@@ -16,7 +16,6 @@ #include "ui/message_center/message_center.h" #include "ui/message_center/message_center_observer.h" #include "ui/message_center/message_center_types.h" -#include "ui/views/widget/widget_observer.h" namespace views { class Widget; @@ -32,8 +31,7 @@ // opens a bubble with a scrollable list of all current notifications. class ASH_EXPORT NotificationCenterTray : public TrayBackgroundView, - public message_center::MessageCenterObserver, - public views::WidgetObserver { + public message_center::MessageCenterObserver { public: METADATA_HEADER(NotificationCenterTray); @@ -70,9 +68,6 @@ bool by_user) override; void OnNotificationUpdated(const std::string& notification_id) override; - // views::WidgetObserver: - void OnWidgetDestroying(views::Widget* widget) override; - // Update the visibility of the tray button based on available notifications. // If there are no notifications the tray button should be hidden and shown // otherwise.
diff --git a/chrome/browser/ash/video_conference/video_conference_state.h b/ash/system/video_conference/video_conference_media_state.h similarity index 81% rename from chrome/browser/ash/video_conference/video_conference_state.h rename to ash/system/video_conference/video_conference_media_state.h index 21f666f..d351f00 100644 --- a/chrome/browser/ash/video_conference/video_conference_state.h +++ b/ash/system/video_conference/video_conference_media_state.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_ASH_VIDEO_CONFERENCE_VIDEO_CONFERENCE_STATE_H_ -#define CHROME_BROWSER_ASH_VIDEO_CONFERENCE_VIDEO_CONFERENCE_STATE_H_ +#ifndef ASH_SYSTEM_VIDEO_CONFERENCE_VIDEO_CONFERENCE_MEDIA_STATE_H_ +#define ASH_SYSTEM_VIDEO_CONFERENCE_VIDEO_CONFERENCE_MEDIA_STATE_H_ namespace ash { @@ -26,4 +26,4 @@ } // namespace ash -#endif // CHROME_BROWSER_ASH_VIDEO_CONFERENCE_VIDEO_CONFERENCE_STATE_H_ +#endif // ASH_SYSTEM_VIDEO_CONFERENCE_VIDEO_CONFERENCE_MEDIA_STATE_H_
diff --git a/ash/wallpaper/wallpaper_controller_impl.cc b/ash/wallpaper/wallpaper_controller_impl.cc index 7eec548..ab9d2fb 100644 --- a/ash/wallpaper/wallpaper_controller_impl.cc +++ b/ash/wallpaper/wallpaper_controller_impl.cc
@@ -55,7 +55,6 @@ #include "base/strings/string_piece_forward.h" #include "base/strings/stringprintf.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "components/account_id/account_id.h" #include "components/prefs/pref_service.h" @@ -1108,15 +1107,15 @@ if (params.variants.empty()) { // |params.variants| can be empty for users who use the old wallpaper // picker. If that's the case, just follow the old flow. - base::PostTaskAndReplyWithResult( - sequenced_task_runner_.get(), FROM_HERE, + sequenced_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetExistingOnlineWallpaperPath, params.url.spec()), base::BindOnce(&WallpaperControllerImpl::SetOnlineWallpaperFromPath, set_wallpaper_weak_factory_.GetWeakPtr(), std::move(callback), params)); } else { - base::PostTaskAndReplyWithResult( - sequenced_task_runner_.get(), FROM_HERE, + sequenced_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetOnlineWallpaperVariantPaths, params.variants), base::BindOnce( &WallpaperControllerImpl::SetOnlineWallpaperFromVariantPaths, @@ -1604,9 +1603,9 @@ void WallpaperControllerImpl::GetOfflineWallpaperList( GetOfflineWallpaperListCallback callback) { - base::PostTaskAndReplyWithResult(sequenced_task_runner_.get(), FROM_HERE, - base::BindOnce(&GetOfflineWallpaperListImpl), - std::move(callback)); + sequenced_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetOfflineWallpaperListImpl), + std::move(callback)); } void WallpaperControllerImpl::SetAnimationDuration(
diff --git a/ash/wallpaper/wallpaper_utils/wallpaper_color_calculator.cc b/ash/wallpaper/wallpaper_utils/wallpaper_color_calculator.cc index 652b4c5..440c64b 100644 --- a/ash/wallpaper/wallpaper_utils/wallpaper_color_calculator.cc +++ b/ash/wallpaper/wallpaper_utils/wallpaper_color_calculator.cc
@@ -14,7 +14,6 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/task/task_runner.h" -#include "base/task/task_runner_util.h" #include "ui/gfx/color_analysis.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image_skia.h" @@ -171,8 +170,8 @@ } image_.MakeThreadSafe(); - if (base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + if (task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CalculateWallpaperColor, image_, color_profiles_), base::BindOnce(&WallpaperColorCalculator::OnAsyncCalculationComplete, weak_ptr_factory_.GetWeakPtr(),
diff --git a/ash/webui/common/resources/keyboard_key.html b/ash/webui/common/resources/keyboard_key.html index c5490d07..44e3905 100644 --- a/ash/webui/common/resources/keyboard_key.html +++ b/ash/webui/common/resources/keyboard_key.html
@@ -42,7 +42,8 @@ :host { --background-color-pressed: var(--cros-icon-color-selection); --background-color-unpressed: var(--cros-highlight-color); - --background-color-tested: var(--cros-text-highlight-color); + --background-color-tested: rgba(var(--cros-icon-color-selection-rgb), + var(--cros-second-tone-opacity)); --border-color: var(--cros-icon-color-prominent); --border-radius: var(--keyboard-key-top-radii, 3px) @@ -51,8 +52,8 @@ 3px; --icon-size: var(--keyboard-key-icon-size, 100%); --travel: var(--keyboard-key-travel, 3px); - --foreground-color-unpressed: var(--cros-icon-color-prominent); - --foreground-color-pressed: var(--cros-button-icon-color-primary); + --text-color-unpressed: var(--cros-icon-color-prominent); + --text-color-pressed: var(--cros-button-icon-color-primary); position: relative; } @@ -63,7 +64,7 @@ border-radius: var(--border-radius); border-top-width: var(--keyboard-key-border-top-width, 1px); bottom: var(--travel); - color: var(--foreground-color-unpressed); + color: var(--text-color-unpressed); display: grid; font-family: 'Google Sans', sans-serif; grid-auto-columns: 1fr; @@ -91,7 +92,7 @@ } iron-icon { - --iron-icon-fill-color: var(--foreground-color-unpressed); + --iron-icon-fill-color: var(--text-color-unpressed); --iron-icon-height: var(--icon-size); --iron-icon-width: var(--icon-size); align-self: center; @@ -142,8 +143,9 @@ :host([state='pressed']) #key { background-color: var(--background-color-pressed); + border-color: var(--background-color-pressed); bottom: 0; - color: var(--foreground-color-pressed); + color: var(--text-color-pressed); top: var(--travel); } @@ -153,7 +155,7 @@ } :host([state='pressed']) iron-icon { - --iron-icon-fill-color: var(--foreground-color-pressed); + --iron-icon-fill-color: var(--text-color-pressed); } :host([state='tested']) #key { @@ -191,13 +193,6 @@ :host(.disabled) #shadow { background-color: var(--cros-bg-color-dropped-elevation-2); } - - @media (prefers-color-scheme: dark) { - :host { - --background-color-tested: rgba(var(--google-blue-600-rgb), - var(--cros-second-tone-opacity)); - } - } </style> <div id="shadow"></div> <div id="key-background"></div>
diff --git a/ash/webui/common/resources/navigation_selector.html b/ash/webui/common/resources/navigation_selector.html index ba7aae4..61dc68c 100644 --- a/ash/webui/common/resources/navigation_selector.html +++ b/ash/webui/common/resources/navigation_selector.html
@@ -3,6 +3,11 @@ --focus-border-width: 1px; } .navigation-item { + --active-shadow-rgb: transparent; /* Disable Active Shadow on cr-button */ + --focus-shadow-color: transparent; /* Disable Focus Shadow on cr-button */ + --hover-bg-color: var(--cros-ripple-color); + --ripple-opacity: 0; /* Disable Ripple on cr-button */ + align-items: center; border-block-end-width: var(--focus-border-width); border-block-start-width: var(--focus-border-width); @@ -15,6 +20,7 @@ cursor: pointer; display: flex; font-weight: 500; + justify-content: start; margin-bottom: 8px; margin-inline-end: 2px; min-height: 32px; @@ -25,10 +31,6 @@ outline: var(--cros-focus-ring-color) solid var(--focus-border-width); } -div:hover:not(.selected).navigation-item { - background-color: var(--cros-ripple-color); -} - .navigation-item.selected { background-color: var(--cros-highlight-color); color: var(--cros-color-prominent); @@ -61,13 +63,13 @@ <div id="navigationSelectorComponent"> <div id="navigationSelectorMenu"> <template id="selectorItems" is="dom-repeat" items="{{selectorItems}}"> - <div class$="{{computeInitialClass_(item)}}" tabindex="0" + <cr-button class$="{{computeInitialClass_(item)}}" tabindex="0" part="navigation-item" on-click="onSelected_"> <iron-icon class="icon" icon="[[item.icon]]" alt="" hidden="[[!item.icon]]"></iron-icon> [[item.name]] - </div> + </cr-button> </template> </div> -</div> \ No newline at end of file +</div>
diff --git a/ash/webui/media_app_ui/media_app_guest_ui.cc b/ash/webui/media_app_ui/media_app_guest_ui.cc index c4ad74d..eb58fb6f 100644 --- a/ash/webui/media_app_ui/media_app_guest_ui.cc +++ b/ash/webui/media_app_ui/media_app_guest_ui.cc
@@ -13,7 +13,6 @@ #include "base/memory/ref_counted_memory.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "chromeos/grit/chromeos_media_app_bundle_resources.h" #include "chromeos/grit/chromeos_media_app_bundle_resources_map.h" @@ -248,9 +247,8 @@ if (path_exists) { auto font_data = std::make_unique<std::string>(); std::string* data = font_data.get(); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(&base::ReadFileToString, font_path, data), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&base::ReadFileToString, font_path, data), base::BindOnce(&FontLoaded, std::move(got_data_callback), std::move(font_data)));
diff --git a/ash/webui/personalization_app/mojom/personalization_app.mojom b/ash/webui/personalization_app/mojom/personalization_app.mojom index 25781d2..8f7c099 100644 --- a/ash/webui/personalization_app/mojom/personalization_app.mojom +++ b/ash/webui/personalization_app/mojom/personalization_app.mojom
@@ -529,6 +529,9 @@ // Notifies the JS side about the previews of the selected Google Photos // albums. OnGooglePhotosAlbumsPreviewsFetched(array<url.mojom.Url> previews); + + // Nofities the JS side when the screen saver is closed. + OnScreenSaverClosed(); }; // Provides APIs to expose Ambient mode settings.
diff --git a/ash/webui/personalization_app/resources/js/ambient/ambient_observer.ts b/ash/webui/personalization_app/resources/js/ambient/ambient_observer.ts index 105ce17..b978ee31 100644 --- a/ash/webui/personalization_app/resources/js/ambient/ambient_observer.ts +++ b/ash/webui/personalization_app/resources/js/ambient/ambient_observer.ts
@@ -91,4 +91,6 @@ const store = PersonalizationStore.getInstance(); store.dispatch(setGooglePhotosAlbumsPreviewsAction(previews)); } + + onScreenSaverClosed() {} }
diff --git a/ash/webui/scanning/resources/action_toolbar.js b/ash/webui/scanning/resources/action_toolbar.js index 140f3bf..ea3900a 100644 --- a/ash/webui/scanning/resources/action_toolbar.js +++ b/ash/webui/scanning/resources/action_toolbar.js
@@ -3,6 +3,7 @@ // found in the LICENSE file. import './scanning_shared_css.js'; +import './strings.m.js'; import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.js'; import {I18nBehavior} from 'chrome://resources/ash/common/i18n_behavior.js';
diff --git a/ash/webui/scanning/resources/loading_page.js b/ash/webui/scanning/resources/loading_page.js index d099d589..053518f 100644 --- a/ash/webui/scanning/resources/loading_page.js +++ b/ash/webui/scanning/resources/loading_page.js
@@ -5,6 +5,7 @@ import 'chrome://resources/cr_elements/cr_button/cr_button.js'; import 'chrome://resources/polymer/v3_0/iron-media-query/iron-media-query.js'; import 'chrome://resources/polymer/v3_0/paper-progress/paper-progress.js'; +import './strings.m.js'; import {I18nBehavior} from 'chrome://resources/ash/common/i18n_behavior.js'; import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
diff --git a/ash/webui/scanning/resources/multi_page_checkbox.js b/ash/webui/scanning/resources/multi_page_checkbox.js index 774ffa8..1057ea9 100644 --- a/ash/webui/scanning/resources/multi_page_checkbox.js +++ b/ash/webui/scanning/resources/multi_page_checkbox.js
@@ -4,6 +4,7 @@ import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.js'; import './scan_settings_section.js'; +import './strings.m.js'; import {I18nBehavior} from 'chrome://resources/ash/common/i18n_behavior.js'; import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
diff --git a/ash/webui/scanning/resources/multi_page_scan.js b/ash/webui/scanning/resources/multi_page_scan.js index b2ee3dac..3fc973a 100644 --- a/ash/webui/scanning/resources/multi_page_scan.js +++ b/ash/webui/scanning/resources/multi_page_scan.js
@@ -4,6 +4,7 @@ import 'chrome://resources/cr_elements/cr_button/cr_button.js'; import './scanning_fonts_css.js'; +import './strings.m.js'; import {I18nBehavior} from 'chrome://resources/ash/common/i18n_behavior.js'; import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
diff --git a/ash/webui/scanning/resources/scan_done_section.js b/ash/webui/scanning/resources/scan_done_section.js index 46ad866..82489bb 100644 --- a/ash/webui/scanning/resources/scan_done_section.js +++ b/ash/webui/scanning/resources/scan_done_section.js
@@ -6,6 +6,7 @@ import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.js'; import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; import './file_path.mojom-lite.js'; +import './strings.m.js'; import {I18nBehavior} from 'chrome://resources/ash/common/i18n_behavior.js'; import {assert} from 'chrome://resources/js/assert.js';
diff --git a/ash/webui/scanning/resources/scan_preview.js b/ash/webui/scanning/resources/scan_preview.js index 9bea70f..44a96a1 100644 --- a/ash/webui/scanning/resources/scan_preview.js +++ b/ash/webui/scanning/resources/scan_preview.js
@@ -6,6 +6,7 @@ import './action_toolbar.js'; import './scanning_fonts_css.js'; import './scanning_shared_css.js'; +import './strings.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js'; import 'chrome://resources/polymer/v3_0/iron-media-query/iron-media-query.js'; import 'chrome://resources/polymer/v3_0/paper-progress/paper-progress.js';
diff --git a/ash/webui/shimless_rma/resources/shimless_rma.html b/ash/webui/shimless_rma/resources/shimless_rma.html index 18e352b..cf90c27d 100644 --- a/ash/webui/shimless_rma/resources/shimless_rma.html +++ b/ash/webui/shimless_rma/resources/shimless_rma.html
@@ -88,16 +88,18 @@ } #logsDialog::part(dialog) { - width: 512px; + height: 640px; + width: 864px; } #logsDialog::part(wrapper) { - height: 480px; + max-height: 100%; } #logsDialog [slot=button-container] { - padding-bottom: 24px; - padding-top: 24px; + height: 40px; + padding-bottom: 12px; + padding-top: 12px; } #logsDialog [slot=title] { @@ -109,6 +111,20 @@ padding: 0 24px 0 24px; } + .logs-dialog-footer-text { + color: var(--shimless-dialog-body-text-color); + font-family: var(--shimless-dialog-body-font-family); + font-size: var(--shimless-dialog-body-font-size); + font-weight: var(--shimless-regular-font-weight); + line-height: var(--shimless-dialog-body-line-height); + } + + .logs-dialog-icon { + align-self: flex-start; + padding-inline-end: 6px; + padding-top: 2px; + } + #logText { white-space: pre-line; } @@ -219,10 +235,12 @@ slot="button-container" hidden="[[!shouldShowLogSaveAttemptContainer_(usbLogState_)]]"> <div id="logSavedIconText"> - <iron-icon id="verificationIcon" class="small-icon" + <iron-icon id="verificationIcon" class="small-icon logs-dialog-icon" icon="[[getSaveLogResultIcon_(usbLogState_)]]"> </iron-icon> - <span id="logSavedStatusText">[[logSavedStatusText_]]</span> + <span id="logSavedStatusText" class="logs-dialog-footer-text"> + [[logSavedStatusText_]] + </span> </div> <cr-button id="logRetryDialogButton" class="text-button action-button" on-click="retrySaveLogs_" @@ -238,9 +256,9 @@ slot="button-container" hidden="[[!shouldShowLogUsbMessageContainer_(usbLogState_)]]"> <div id="logSavedIconText"> - <iron-icon id="connectUsbIcon" class="small-icon" + <iron-icon id="connectUsbIcon" class="small-icon logs-dialog-icon" icon="shimless-icon:warning"></iron-icon> - <span id="connectUsbInstructions" class="instructions"> + <span id="connectUsbInstructions" class="logs-dialog-footer-text"> [[i18n('rmaLogsMissingUsbMessageText')]] </span> <cr-button id="closeLogDialogButton" class="action-button"
diff --git a/ash/webui/shortcut_customization_ui/backend/accelerator_configuration_provider.cc b/ash/webui/shortcut_customization_ui/backend/accelerator_configuration_provider.cc index 7ddd88f..b7f3a293 100644 --- a/ash/webui/shortcut_customization_ui/backend/accelerator_configuration_provider.cc +++ b/ash/webui/shortcut_customization_ui/backend/accelerator_configuration_provider.cc
@@ -77,17 +77,18 @@ } mojom::AcceleratorLayoutInfoPtr LayoutInfoToMojom( - AcceleratorActionId action_id, AcceleratorLayoutDetails layout_details) { mojom::AcceleratorLayoutInfoPtr layout_info = mojom::AcceleratorLayoutInfo::New(); layout_info->category = layout_details.category; layout_info->sub_category = layout_details.sub_category; - layout_info->description = - l10n_util::GetStringUTF16(kAcceleratorActionToStringIdMap.at(action_id)); + // TODO(michaelcheco): Description needs to switch which table it performs + // the lookup on depending on the accelerator source. + layout_info->description = l10n_util::GetStringUTF16( + kAcceleratorActionToStringIdMap.at(layout_details.action_id)); layout_info->style = layout_details.layout_style; - layout_info->source = mojom::AcceleratorSource::kAsh; - layout_info->action = static_cast<uint32_t>(action_id); + layout_info->source = layout_details.source; + layout_info->action = static_cast<uint32_t>(layout_details.action_id); return layout_info; } @@ -148,10 +149,10 @@ UpdateKeyboards(); - // Create LayoutInfos from kAcceleratorLayouts map. LayoutInfos are static + // Create LayoutInfos from kAcceleratorLayouts. LayoutInfos are static // data that provides additional details for the app for styling. - for (const auto& [action_id, layout_details] : kAcceleratorLayouts) { - layout_infos_.push_back(LayoutInfoToMojom(action_id, layout_details)); + for (const auto& layout_details : kAcceleratorLayouts) { + layout_infos_.push_back(LayoutInfoToMojom(layout_details)); } }
diff --git a/ash/webui/shortcut_customization_ui/backend/accelerator_configuration_provider_unittest.cc b/ash/webui/shortcut_customization_ui/backend/accelerator_configuration_provider_unittest.cc index 1abf38f..22638e0 100644 --- a/ash/webui/shortcut_customization_ui/backend/accelerator_configuration_provider_unittest.cc +++ b/ash/webui/shortcut_customization_ui/backend/accelerator_configuration_provider_unittest.cc
@@ -133,18 +133,21 @@ // the data provided by `AcceleratorConfigurationProvider`. void ValidateAcceleratorLayouts( const std::vector<ash::mojom::AcceleratorLayoutInfoPtr>& - actual_layout_infos, - mojom::AcceleratorSource expected_source) { + actual_layout_infos) { for (const auto& actual : actual_layout_infos) { - EXPECT_TRUE(ash::kAcceleratorLayouts.contains(actual->action)); - - const ash::AcceleratorLayoutDetails& expected = - ash::kAcceleratorLayouts.at(actual->action); - - EXPECT_EQ(expected.category, actual->category); - EXPECT_EQ(expected.sub_category, actual->sub_category); - EXPECT_EQ(expected.layout_style, actual->style); - EXPECT_EQ(expected_source, actual->source); + // Iterate through `kAcceleratorLayouts` to find the matching action. + bool found_match = false; + for (const auto& expected_layout : kAcceleratorLayouts) { + if (expected_layout.action_id == actual->action) { + EXPECT_EQ(expected_layout.category, actual->category); + EXPECT_EQ(expected_layout.sub_category, actual->sub_category); + EXPECT_EQ(expected_layout.layout_style, actual->style); + EXPECT_EQ(expected_layout.source, actual->source); + found_match = true; + break; + } + } + EXPECT_TRUE(found_match); } } @@ -363,8 +366,7 @@ // correctly mapped layout details provider_->GetAcceleratorLayoutInfos(base::BindLambdaForTesting( [&](std::vector<mojom::AcceleratorLayoutInfoPtr> actual_layout_infos) { - ValidateAcceleratorLayouts(actual_layout_infos, - mojom::AcceleratorSource::kAsh); + ValidateAcceleratorLayouts(actual_layout_infos); })); }
diff --git a/build/config/coverage/BUILD.gn b/build/config/coverage/BUILD.gn index d458fca..59941c3c 100644 --- a/build/config/coverage/BUILD.gn +++ b/build/config/coverage/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//build/config/coverage/coverage.gni") +import("//build/config/rust.gni") config("default_coverage") { if (use_clang_coverage) { @@ -26,6 +27,14 @@ "-limited-coverage-experimental=true", ] + # Rust coverage is gated on using the Chromium-built Rust toolchain as it + # needs to have a compatible LLVM version with the C++ compiler and the LLVM + # tools that will be used to process the coverage output. This is because + # the coverage file format is not stable. + if (use_chromium_rust_toolchain) { + rustflags = [ "-Cinstrument-coverage" ] + } + if (is_linux || is_chromeos) { # TODO(crbug.com/1194301): Remove this flag. cflags += [ "-fno-use-cxa-atexit" ]
diff --git a/build/fuchsia/linux_internal.sdk.sha1 b/build/fuchsia/linux_internal.sdk.sha1 index 3d8266b46..dc8fcca7 100644 --- a/build/fuchsia/linux_internal.sdk.sha1 +++ b/build/fuchsia/linux_internal.sdk.sha1
@@ -1 +1 @@ -10.20221128.0.1 +10.20221128.2.1
diff --git a/build/lacros/test_runner.py b/build/lacros/test_runner.py index 263bdc84..a786382c 100755 --- a/build/lacros/test_runner.py +++ b/build/lacros/test_runner.py
@@ -499,6 +499,7 @@ ash_process_has_started = False total_tries = 3 num_tries = 0 + ash_start_time = None # Create a log file if the user wanted to have one. log = None @@ -516,6 +517,8 @@ while not ash_process_has_started and num_tries < total_tries: num_tries += 1 + ash_start_time = time.monotonic() + logging.info('Starting ash-chrome.') if log is None: ash_process = subprocess.Popen(ash_cmd, env=ash_env) else: @@ -544,6 +547,10 @@ if not ash_process_has_started: raise RuntimeError('Timed out waiting for ash-chrome to start') + ash_elapsed_time = time.monotonic() - ash_start_time + logging.info('Started ash-chrome in %.3fs on try %d.', ash_elapsed_time, + num_tries) + # Starts tests. if enable_mojo_crosapi: forward_args.append(lacros_mojo_socket_arg) @@ -552,6 +559,7 @@ test_env['WAYLAND_DISPLAY'] = ash_wayland_socket_name test_env['EGL_PLATFORM'] = 'surfaceless' test_env['XDG_RUNTIME_DIR'] = tmp_xdg_dir_name + logging.info('Starting test process.') test_process = subprocess.Popen([args.command] + forward_args, env=test_env) return test_process.wait()
diff --git a/build/linux/sysroot_scripts/sysroots.json b/build/linux/sysroot_scripts/sysroots.json index d06a94d3..cfb3b3a 100644 --- a/build/linux/sysroot_scripts/sysroots.json +++ b/build/linux/sysroot_scripts/sysroots.json
@@ -1,43 +1,43 @@ { "bullseye_amd64": { - "Key": "20220331T153654Z-0", - "Sha1Sum": "5ebc72fdaf206572cdc6664b7e78a8eb38d7f526", + "Key": "20221105T211506Z-0", + "Sha1Sum": "3bdb3503702d35520d101fc5eec9a8ab5353149f", "SysrootDir": "debian_bullseye_amd64-sysroot", "Tarball": "debian_bullseye_amd64_sysroot.tar.xz" }, "bullseye_arm": { - "Key": "20220331T153654Z-0", - "Sha1Sum": "85f072ac9cb695ca34685a40e8b3fe37a2891951", + "Key": "20221105T211506Z-0", + "Sha1Sum": "d160892586b87782fef76ccc651fa2024a62bdcd", "SysrootDir": "debian_bullseye_arm-sysroot", "Tarball": "debian_bullseye_arm_sysroot.tar.xz" }, "bullseye_arm64": { - "Key": "20220331T153654Z-0", - "Sha1Sum": "e5afb40447cef513ff99c772449048b73d7a28ff", + "Key": "20221105T211506Z-0", + "Sha1Sum": "286feb74e2209a7a70add5497609ac27685022fa", "SysrootDir": "debian_bullseye_arm64-sysroot", "Tarball": "debian_bullseye_arm64_sysroot.tar.xz" }, "bullseye_armel": { - "Key": "20220331T153654Z-0", - "Sha1Sum": "18ca043c9e4adc5bd8a352e35e2db671ac3ed089", + "Key": "20221105T211506Z-0", + "Sha1Sum": "bd0167a99fa282fa54835a635d2d0ac18b7ab8a5", "SysrootDir": "debian_bullseye_armel-sysroot", "Tarball": "debian_bullseye_armel_sysroot.tar.xz" }, "bullseye_i386": { - "Key": "20220331T153654Z-0", - "Sha1Sum": "bb5c9d52f69a97fc934f2b269375dcba0c7db8dc", + "Key": "20221105T211506Z-0", + "Sha1Sum": "de629dcc11a6ab1b11e6d66c4180a959c6290097", "SysrootDir": "debian_bullseye_i386-sysroot", "Tarball": "debian_bullseye_i386_sysroot.tar.xz" }, "bullseye_mips": { - "Key": "20220331T153654Z-0", - "Sha1Sum": "354f0d8aafe7d034f50287b840b3dff967d9a2a1", + "Key": "20221105T211506Z-0", + "Sha1Sum": "6f27b4f65d8e190864e7c18fa281ffb418cf2e43", "SysrootDir": "debian_bullseye_mips-sysroot", "Tarball": "debian_bullseye_mips_sysroot.tar.xz" }, "bullseye_mips64el": { - "Key": "20220331T153654Z-0", - "Sha1Sum": "3b52b8b86138b2392daf915928f29281000e2461", + "Key": "20221105T211506Z-0", + "Sha1Sum": "817d0905f294c9c5af828fa5c5b814dbe9610a24", "SysrootDir": "debian_bullseye_mips64el-sysroot", "Tarball": "debian_bullseye_mips64el_sysroot.tar.xz" }
diff --git a/buildtools/deps_revisions.gni b/buildtools/deps_revisions.gni index 2625184e..c9a0fc3 100644 --- a/buildtools/deps_revisions.gni +++ b/buildtools/deps_revisions.gni
@@ -5,5 +5,5 @@ declare_args() { # Used to cause full rebuilds on libc++ rolls. This should be kept in sync # with the libcxx_revision vars in //DEPS. - libcxx_revision = "0488dfb230af1188de06115aaa587b09536d99e5" + libcxx_revision = "c2e10323cc8190175715ea1bcdb109f59b84447c" }
diff --git a/cc/paint/image_transfer_cache_entry.cc b/cc/paint/image_transfer_cache_entry.cc index 60c0ae4a..e685ab153 100644 --- a/cc/paint/image_transfer_cache_entry.cc +++ b/cc/paint/image_transfer_cache_entry.cc
@@ -280,7 +280,7 @@ reader.Read(&target_color_params->hdr_max_luminance_relative); reader.Read(&target_color_params->enable_tone_mapping); - uint32_t has_hdr_metadata; + uint32_t has_hdr_metadata = 0; reader.Read(&has_hdr_metadata); if (has_hdr_metadata) { gfx::HDRMetadata hdr_metadata; @@ -289,7 +289,7 @@ reader.Read(&max_content_light_level); reader.Read(&max_frame_average_light_level); - SkColorSpacePrimaries primaries; + SkColorSpacePrimaries primaries = SkNamedPrimariesExt::kInvalid; float luminance_max = 0; float luminance_min = 0; reader.Read(&primaries.fRX); @@ -614,6 +614,10 @@ image_ = MakeYUVImageFromUploadedPlanes( context_, plane_images_, plane_config_, subsampling_.value(), yuv_color_space_.value(), decoded_color_space); + if (!image_) { + DLOG(ERROR) << "Failed to make YUV image from planes."; + return false; + } } else { if (!ReadPixmap(reader, rgba_pixmap)) { DLOG(ERROR) << "Failed to read pixmap"; @@ -639,19 +643,24 @@ image_ = rgba_pixmap_image; } } - DCHECK(image_); + CHECK(image_); // Perform color conversion. if (target_color_params) { + auto target_color_space = target_color_params->color_space.ToSkColorSpace(); + if (!target_color_space) { + DLOG(ERROR) << "Invalid target color space."; + return false; + } + // TODO(https://crbug.com/1286088): Pass a shared cache as a parameter. gfx::ColorConversionSkFilterCache cache; - image_ = cache.ConvertImage( - image_, target_color_params->color_space.ToSkColorSpace(), - target_color_params->hdr_metadata, - target_color_params->sdr_max_luminance_nits, - target_color_params->hdr_max_luminance_relative, - target_color_params->enable_tone_mapping, - fits_on_gpu_ ? context_ : nullptr); + image_ = cache.ConvertImage(image_, target_color_space, + target_color_params->hdr_metadata, + target_color_params->sdr_max_luminance_nits, + target_color_params->hdr_max_luminance_relative, + target_color_params->enable_tone_mapping, + fits_on_gpu_ ? context_ : nullptr); if (!image_) { DLOG(ERROR) << "Failed image color conversion"; return false;
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantCollectUserDataIntegrationTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantCollectUserDataIntegrationTest.java index bf09384..0f644ed9 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantCollectUserDataIntegrationTest.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantCollectUserDataIntegrationTest.java
@@ -147,6 +147,7 @@ */ @Test @MediumTest + @DisabledTest(message = "https://crbug.com/1394156") public void testEnterPayment() throws Exception { String profileId = mHelper.addDummyProfile("John Doe", "johndoe@gmail.com"); mHelper.addDummyCreditCard(profileId); @@ -279,6 +280,7 @@ @Test @MediumTest + @DisabledTest(message = "https://crbug.com/1394156") public void testFailingAutofillSendsProperError() throws Exception { String profileId = mHelper.addDummyProfile("John Doe", "johndoe@gmail.com"); mHelper.addDummyCreditCard(profileId);
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/LocationBarModelUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/LocationBarModelUnitTest.java index 1ecb7bc..27202fdac 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/LocationBarModelUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/LocationBarModelUnitTest.java
@@ -335,4 +335,73 @@ regularLocationBarModel.destroy(); } + + @DisableFeatures({ChromeFeatureList.ANDROID_SCROLL_OPTIMIZATIONS}) + @Test + @MediumTest + public void testNoCacheWhenScrollOptimizationsDisabled() { + doReturn(123L).when(mLocationBarModelJni).init(Mockito.any()); + mJniMocker.mock(ChromeAutocompleteSchemeClassifierJni.TEST_HOOKS, + mChromeAutocompleteSchemeClassifierJni); + LocationBarModel regularLocationBarModel = + new TestRegularLocationBarModel(mRegularTabMock, mSearchEngineLogoUtils); + doReturn(true).when(mRegularTabMock).isInitialized(); + regularLocationBarModel.initializeWithNative(); + + String url = "http://www.example.com/"; + doReturn(url).when(mMockGurl).getSpec(); + doReturn(mMockGurl) + .when(mLocationBarModelJni) + .getUrlOfVisibleNavigationEntry(Mockito.anyLong(), Mockito.any()); + doReturn(url) + .when(mLocationBarModelJni) + .getFormattedFullURL(Mockito.anyLong(), Mockito.any()); + doReturn(url).when(mLocationBarModelJni).getURLForDisplay(Mockito.anyLong(), Mockito.any()); + Assert.assertTrue(regularLocationBarModel.updateVisibleGurl()); + regularLocationBarModel.destroy(); + } + + @EnableFeatures({ChromeFeatureList.ANDROID_SCROLL_OPTIMIZATIONS}) + @Test + @MediumTest + public void testCacheWhenScrollOptimizationsEnabled() { + doReturn(123L).when(mLocationBarModelJni).init(Mockito.any()); + mJniMocker.mock(ChromeAutocompleteSchemeClassifierJni.TEST_HOOKS, + mChromeAutocompleteSchemeClassifierJni); + LocationBarModel regularLocationBarModel = + new TestRegularLocationBarModel(mRegularTabMock, mSearchEngineLogoUtils); + doReturn(true).when(mRegularTabMock).isInitialized(); + regularLocationBarModel.initializeWithNative(); + + String url = "http://www.example.com/"; + doReturn(url).when(mMockGurl).getSpec(); + doReturn(mMockGurl) + .when(mLocationBarModelJni) + .getUrlOfVisibleNavigationEntry(Mockito.anyLong(), Mockito.any()); + doReturn(url) + .when(mLocationBarModelJni) + .getFormattedFullURL(Mockito.anyLong(), Mockito.any()); + doReturn(url).when(mLocationBarModelJni).getURLForDisplay(Mockito.anyLong(), Mockito.any()); + Assert.assertTrue(regularLocationBarModel.updateVisibleGurl()); + Assert.assertFalse( + "Update should be suppressed", regularLocationBarModel.updateVisibleGurl()); + + // URL changed, cache is invalid. + String url2 = "http://www.example2.com/"; + GURL mMockGurl2 = Mockito.mock(GURL.class); + doReturn(url2).when(mMockGurl2).getSpec(); + doReturn(mMockGurl2) + .when(mLocationBarModelJni) + .getUrlOfVisibleNavigationEntry(Mockito.anyLong(), Mockito.any()); + doReturn(url2) + .when(mLocationBarModelJni) + .getFormattedFullURL(Mockito.anyLong(), Mockito.any()); + doReturn(url2) + .when(mLocationBarModelJni) + .getURLForDisplay(Mockito.anyLong(), Mockito.any()); + Assert.assertTrue("New url should notify", regularLocationBarModel.updateVisibleGurl()); + Assert.assertFalse( + "Update should be suppressed again", regularLocationBarModel.updateVisibleGurl()); + regularLocationBarModel.destroy(); + } }
diff --git a/chrome/android/profiles/newest.txt b/chrome/android/profiles/newest.txt index 2eda75d..f124bff 100644 --- a/chrome/android/profiles/newest.txt +++ b/chrome/android/profiles/newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-109.0.5414.17_rc-r1-merged.afdo.bz2 +chromeos-chrome-amd64-110.0.5419.0_rc-r1-merged.afdo.bz2
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index a92e766..d93b5072 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -7725,6 +7725,9 @@ </if> <!-- User Education Tutorial Strings --> + <message name="IDS_TUTORIAL_GENERIC_SUCCESS_TITLE" desc="The title of the generic success step in the user education tutorials"> + Nicely Done! + </message> <if expr="use_titlecase"> <message name="IDS_TUTORIAL_TAB_GROUP_ADD_TAB_TO_GROUP" desc="The description of the add tab step in the tab group tutorial"> Right-click on a tab and select "Add Tab To New Group" @@ -7761,6 +7764,23 @@ Try using tab groups to organize tasks, for online shopping, and more </message> + <!-- Side Panel Tutorial Strings --> + <message name="IDS_TUTORIAL_SIDE_PANEL_READING_LIST_OPEN_SIDE_PANEL" desc="The description of the 'open side panel' step in side panel reading list tutorial"> + Click the side panel icon to open it + </message> + <message name="IDS_TUTORIAL_SIDE_PANEL_READING_LIST_ADD_TAB" desc="The description of the 'add tab' step in side panel reading list tutorial"> + Now add the current tab to your list + </message> + <message name="IDS_TUTORIAL_SIDE_PANEL_READING_LIST_MARK_READ" desc="The description of the 'mark as read' step in side panel reading list tutorial"> + Select “Mark as read” to move the page to the bottom of your list + </message> + <message name="IDS_TUTORIAL_SIDE_PANEL_READING_LIST_CLICK_DROPDOWN" desc="The description of the 'click drop down' step in side panel reading list tutorial"> + Click the drop down to choose another panel + </message> + <message name="IDS_TUTORIAL_SIDE_PANEL_READING_LIST_SUCCESS_BODY" desc="The description of the body text in the 'success' step in side panel reading list tutorial"> + Try using the side panel for bookmarks, journeys, and more + </message> + <!-- Browser Hung Plugin Detector --> <if expr="is_win"> <message name="IDS_BROWSER_HANGMONITOR" desc="A plugin on a page has hung">
diff --git a/chrome/app/generated_resources_grd/IDS_TUTORIAL_GENERIC_SUCCESS_TITLE.png.sha1 b/chrome/app/generated_resources_grd/IDS_TUTORIAL_GENERIC_SUCCESS_TITLE.png.sha1 new file mode 100644 index 0000000..3f863b91 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_TUTORIAL_GENERIC_SUCCESS_TITLE.png.sha1
@@ -0,0 +1 @@ +4d3016c7c6529eddebffeb1f20af39d2044489cc \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_ADD_TAB.png.sha1 b/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_ADD_TAB.png.sha1 new file mode 100644 index 0000000..7801b3a --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_ADD_TAB.png.sha1
@@ -0,0 +1 @@ +7c39a115bde5dd88697c32cf4afba6ccfc4095e7 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_CLICK_DROPDOWN.png.sha1 b/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_CLICK_DROPDOWN.png.sha1 new file mode 100644 index 0000000..9a0b1ba --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_CLICK_DROPDOWN.png.sha1
@@ -0,0 +1 @@ +6bd3dfe3be7549b325614ba1e1d41dad229f27a6 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_MARK_READ.png.sha1 b/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_MARK_READ.png.sha1 new file mode 100644 index 0000000..7f05160 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_MARK_READ.png.sha1
@@ -0,0 +1 @@ +ebe12684aaccf5d188075388c470d50a039e3aa5 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_OPEN_SIDE_PANEL.png.sha1 b/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_OPEN_SIDE_PANEL.png.sha1 new file mode 100644 index 0000000..2f41ce6 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_OPEN_SIDE_PANEL.png.sha1
@@ -0,0 +1 @@ +4a3c5a0fa88d644161c878d4cf10151c1f0be2fa \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_SUCCESS_BODY.png.sha1 b/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_SUCCESS_BODY.png.sha1 new file mode 100644 index 0000000..1eff133a --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_TUTORIAL_SIDE_PANEL_READING_LIST_SUCCESS_BODY.png.sha1
@@ -0,0 +1 @@ +8a9ad203042b2347b3a7f0891a4a10acc8f9e061 \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index ccb9275..af253e0 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -609,6 +609,8 @@ "image_fetcher/image_decoder_impl.h", "image_fetcher/image_fetcher_service_factory.cc", "image_fetcher/image_fetcher_service_factory.h", + "image_service/image_service_factory.cc", + "image_service/image_service_factory.h", "infobars/confirm_infobar_creator.cc", "infobars/confirm_infobar_creator.h", "infobars/infobar_responder.cc", @@ -4072,14 +4074,10 @@ "profile_resetter/triggered_profile_resetter.h", "profile_resetter/triggered_profile_resetter_factory.cc", "profile_resetter/triggered_profile_resetter_factory.h", - "profiles/delete_profile_helper.cc", - "profiles/delete_profile_helper.h", "profiles/guest_mode_policy_handler.cc", "profiles/guest_mode_policy_handler.h", "profiles/guest_profile_creation_logger.cc", "profiles/guest_profile_creation_logger.h", - "profiles/nuke_profile_directory_utils.cc", - "profiles/nuke_profile_directory_utils.h", "profiles/profile_shortcut_manager.cc", "profiles/profile_shortcut_manager.h", "profiles/profile_theme_update_service.cc", @@ -7716,6 +7714,9 @@ "supervised_user/web_approvals_manager.cc", "supervised_user/web_approvals_manager.h", ] + if (is_chromeos_ash) { + deps += [ "//chrome/browser/ash/crosapi" ] + } if (is_chromeos) { sources += [ "supervised_user/chromeos/supervised_user_favicon_request_handler.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index a8d7522..b9fc83b4 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -4576,10 +4576,6 @@ flag_descriptions::kVideoTutorialsInstantFetchName, flag_descriptions::kVideoTutorialsInstantFetchDescription, kOsAndroid, SINGLE_VALUE_TYPE(video_tutorials::switches::kVideoTutorialsInstantFetch)}, - {"android-picture-in-picture-api", - flag_descriptions::kAndroidPictureInPictureAPIName, - flag_descriptions::kAndroidPictureInPictureAPIDescription, kOsAndroid, - FEATURE_VALUE_TYPE(media::kPictureInPictureAPI)}, {"reengagement-notification", flag_descriptions::kReengagementNotificationName, flag_descriptions::kReengagementNotificationDescription, kOsAndroid, @@ -5593,6 +5589,14 @@ kJourneysVisitDedupingVariations, "HistoryJourneysVisitDeduping")}, + {"extract-related-searches-from-prefetched-zps-response", + flag_descriptions::kExtractRelatedSearchesFromPrefetchedZPSResponseName, + flag_descriptions:: + kExtractRelatedSearchesFromPrefetchedZPSResponseDescription, + kOsDesktop | kOsAndroid, + FEATURE_VALUE_TYPE(optimization_guide::features:: + kExtractRelatedSearchesFromPrefetchedZPSResponse)}, + {"page-content-annotations", flag_descriptions::kPageContentAnnotationsName, flag_descriptions::kPageContentAnnotationsDescription, kOsDesktop | kOsAndroid,
diff --git a/chrome/browser/after_startup_task_utils_unittest.cc b/chrome/browser/after_startup_task_utils_unittest.cc index e82866a..6495865 100644 --- a/chrome/browser/after_startup_task_utils_unittest.cc +++ b/chrome/browser/after_startup_task_utils_unittest.cc
@@ -12,7 +12,6 @@ #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/test/bind.h" #include "content/public/browser/browser_task_traits.h" @@ -92,8 +91,8 @@ bool GetIsBrowserStartupCompleteFromBackgroundSequence() { base::RunLoop run_loop; bool is_complete; - base::PostTaskAndReplyWithResult( - background_sequence_->real_runner(), FROM_HERE, + background_sequence_->real_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&AfterStartupTaskUtils::IsBrowserStartupComplete), base::BindOnce(&AfterStartupTaskTest::GotIsOnBrowserStartupComplete, &run_loop, &is_complete));
diff --git a/chrome/browser/android/webapk/webapk_installer.cc b/chrome/browser/android/webapk/webapk_installer.cc index 58357a4..3866d80 100644 --- a/chrome/browser/android/webapk/webapk_installer.cc +++ b/chrome/browser/android/webapk/webapk_installer.cc
@@ -26,7 +26,6 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/timer/elapsed_timer.h" @@ -232,8 +231,8 @@ bool is_app_identity_update_supported, std::vector<webapps::WebApkUpdateReason> update_reasons, base::OnceCallback<void(bool)> callback) { - base::PostTaskAndReplyWithResult( - GetBackgroundTaskRunner().get(), FROM_HERE, + GetBackgroundTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &webapps::StoreUpdateRequestToFileInBackground, update_request_path, shortcut_info, app_key, primary_icon_data, is_primary_icon_maskable, @@ -408,9 +407,8 @@ return; } - base::PostTaskAndReplyWithResult( - GetBackgroundTaskRunner().get(), FROM_HERE, - base::BindOnce(&ReadFileInBackground, update_request_path), + GetBackgroundTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadFileInBackground, update_request_path), base::BindOnce(&WebApkInstaller::OnReadUpdateRequest, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/app_controller_mac_browsertest.mm b/chrome/browser/app_controller_mac_browsertest.mm index 2456715..fa58824 100644 --- a/chrome/browser/app_controller_mac_browsertest.mm +++ b/chrome/browser/app_controller_mac_browsertest.mm
@@ -36,13 +36,11 @@ #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/lifetime/application_lifetime_desktop.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_init_params.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_observer.h" #include "chrome/browser/profiles/profile_test_util.h" #include "chrome/browser/signin/signin_util.h" @@ -831,9 +829,8 @@ ServiceAccessType::EXPLICIT_ACCESS)); // Delete profile2. - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile2->GetPath(), base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile2->GetPath(), + base::DoNothing()); content::RunAllTasksUntilIdle(); // Verify the controller's history is back to profile1.
diff --git a/chrome/browser/app_controller_mac_unittest.mm b/chrome/browser/app_controller_mac_unittest.mm index cb0a786..f88dfca 100644 --- a/chrome/browser/app_controller_mac_unittest.mm +++ b/chrome/browser/app_controller_mac_unittest.mm
@@ -16,9 +16,7 @@ #include "chrome/app/chrome_command_ids.h" #import "chrome/browser/app_controller_mac.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/profiles/profile_metrics.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_browser_process.h" @@ -201,11 +199,8 @@ base::scoped_nsobject<AppController> ac([[AppController alloc] init]); // Delete the active profile. - profile_manager_.profile_manager() - ->GetDeleteProfileHelper() - .MaybeScheduleProfileForDeletion( - dest_path1, base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager_.profile_manager()->ScheduleProfileForDeletion( + dest_path1, base::DoNothing()); base::RunLoop().RunUntilIdle();
diff --git a/chrome/browser/apps/app_service/app_icon/app_icon_loader.cc b/chrome/browser/apps/app_service/app_icon/app_icon_loader.cc index 9a53363..aed1e5d 100644 --- a/chrome/browser/apps/app_service/app_icon/app_icon_loader.cc +++ b/chrome/browser/apps/app_service/app_icon/app_icon_loader.cc
@@ -15,7 +15,6 @@ #include "base/memory/ref_counted.h" #include "base/no_destructor.h" #include "base/notreached.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" @@ -311,8 +310,8 @@ iv->uncompressed.MakeThreadSafe(); - base::PostTaskAndReplyWithResult( - standard_icon_task_runner_.get(), FROM_HERE, + standard_icon_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ApplyEffects, icon_effects, size_hint_in_dip_, std::move(iv), mask_image), base::BindOnce(&AppIconLoader::ApplyBadges, base::WrapRefCounted(this),
diff --git a/chrome/browser/apps/platform_apps/shortcut_manager.cc b/chrome/browser/apps/platform_apps/shortcut_manager.cc index 467f6ca..e687bffd 100644 --- a/chrome/browser/apps/platform_apps/shortcut_manager.cc +++ b/chrome/browser/apps/platform_apps/shortcut_manager.cc
@@ -11,6 +11,7 @@ #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/compiler_specific.h" +#include "base/functional/callback_helpers.h" #include "base/one_shot_event.h" #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" @@ -91,7 +92,7 @@ // shortcut in the applications menu (e.g., Start Menu). if (is_update) { web_app::UpdateAllShortcuts(base::UTF8ToUTF16(old_name), profile_, - extension, base::OnceClosure()); + extension, base::DoNothing()); } else { CreateShortcutsForApp(profile_, extension); }
diff --git a/chrome/browser/ash/BUILD.gn b/chrome/browser/ash/BUILD.gn index 3c03a79..84ea1ca 100644 --- a/chrome/browser/ash/BUILD.gn +++ b/chrome/browser/ash/BUILD.gn
@@ -2389,8 +2389,12 @@ "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.h", "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.cc", "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.h", + "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_display_sampler_handler.cc", + "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_display_sampler_handler.h", "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_input_sampler_handler.cc", "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_input_sampler_handler.h", + "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_memory_sampler_handler.cc", + "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_memory_sampler_handler.h", "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_sampler_handler.h", "policy/reporting/metrics_reporting/cros_reporting_settings.cc", "policy/reporting/metrics_reporting/cros_reporting_settings.h",
diff --git a/chrome/browser/ash/app_mode/kiosk_external_updater.cc b/chrome/browser/ash/app_mode/kiosk_external_updater.cc index ebefbd5..d4922384 100644 --- a/chrome/browser/ash/app_mode/kiosk_external_updater.cc +++ b/chrome/browser/ash/app_mode/kiosk_external_updater.cc
@@ -10,7 +10,6 @@ #include "base/location.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/version.h" #include "chrome/browser/ash/app_mode/kiosk_app_manager.h" #include "chrome/browser/ash/notifications/kiosk_external_update_notification.h" @@ -125,8 +124,8 @@ return; } - base::PostTaskAndReplyWithResult( - backend_task_runner_.get(), FROM_HERE, + backend_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ParseExternalUpdateManifest, base::FilePath(mount_info.mount_path)), base::BindOnce(&KioskExternalUpdater::ProcessParsedManifest, @@ -175,8 +174,8 @@ external_updates_[app_id].external_crx.path; base::FilePath temp_crx_path = crx_unpack_dir_.Append(external_crx_path.BaseName()); - base::PostTaskAndReplyWithResult( - backend_task_runner_.get(), FROM_HERE, + backend_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CopyExternalCrxAndDeleteTempDir, external_crx_path, temp_crx_path, temp_dir), base::BindOnce(&KioskExternalUpdater::PutValidatedExtension,
diff --git a/chrome/browser/ash/arc/file_system_watcher/file_system_scanner.cc b/chrome/browser/ash/arc/file_system_watcher/file_system_scanner.cc index 44f76ff..a30b5c84 100644 --- a/chrome/browser/ash/arc/file_system_watcher/file_system_scanner.cc +++ b/chrome/browser/ash/arc/file_system_watcher/file_system_scanner.cc
@@ -11,7 +11,6 @@ #include "ash/components/arc/session/arc_bridge_service.h" #include "base/files/file_enumerator.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "chrome/browser/ash/arc/file_system_watcher/arc_file_system_watcher_util.h" #include "content/public/browser/browser_task_traits.h" @@ -211,8 +210,8 @@ // several SystemTimeClock change happened later (in separate CL). To do the // skip, we could have a boolean variable full_scan_requested, and PostTask // full_scan_requested from the OnFullScanFinished. - base::PostTaskAndReplyWithResult( - scan_runner_.get(), FROM_HERE, + scan_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FullScan, cros_dir_, previous_scan_time_, cros_dir_, android_dir_), base::BindOnce(&FileSystemScanner::OnFullScanFinished, @@ -239,8 +238,8 @@ if (state_ != State::kIdle) return; state_ = State::kWaitingForScanToFinish; - base::PostTaskAndReplyWithResult( - scan_runner_.get(), FROM_HERE, + scan_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&RegularScan, previous_scan_time_, cros_dir_, android_dir_, ctime_callback_), base::BindOnce(&FileSystemScanner::OnRegularScanFinished,
diff --git a/chrome/browser/ash/arc/fileapi/arc_content_file_system_file_stream_reader.cc b/chrome/browser/ash/arc/fileapi/arc_content_file_system_file_stream_reader.cc index e77d979..742273d 100644 --- a/chrome/browser/ash/arc/fileapi/arc_content_file_system_file_stream_reader.cc +++ b/chrome/browser/ash/arc/fileapi/arc_content_file_system_file_stream_reader.cc
@@ -12,7 +12,6 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "chrome/browser/ash/arc/fileapi/arc_content_file_system_size_util.h" @@ -116,8 +115,8 @@ // |file_| is alive on ReadFile(), since the destructor will destruct // |task_runner_| along with |file_| and ReadFile() won't be called. - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadFile, file_.get(), base::WrapRefCounted(buffer), buffer_length), base::BindOnce(&ArcContentFileSystemFileStreamReader::OnRead, @@ -183,9 +182,8 @@ } // |file_| is alive on SeekFile(), since the destructor will destruct // |task_runner_| along with |file_| and SeekFile() won't be called. - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(&SeekFile, file_.get(), offset_), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SeekFile, file_.get(), offset_), base::BindOnce(&ArcContentFileSystemFileStreamReader::OnSeekFile, weak_ptr_factory_.GetWeakPtr(), buf, buffer_length, std::move(callback))); @@ -238,8 +236,8 @@ auto num_bytes_to_read = std::min( static_cast<int64_t>(temporary_buffer->size()), num_bytes_to_consume); // TODO(hashimoto): This may block the worker thread forever. crbug.com/673222 - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadFile, file_.get(), temporary_buffer, num_bytes_to_read), base::BindOnce(
diff --git a/chrome/browser/ash/arc/fileapi/arc_content_file_system_file_stream_writer.cc b/chrome/browser/ash/arc/fileapi/arc_content_file_system_file_stream_writer.cc index bd868307..f331f95f 100644 --- a/chrome/browser/ash/arc/fileapi/arc_content_file_system_file_stream_writer.cc +++ b/chrome/browser/ash/arc/fileapi/arc_content_file_system_file_stream_writer.cc
@@ -12,7 +12,6 @@ #include "base/callback_helpers.h" #include "base/files/file.h" #include "base/logging.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "content/public/browser/browser_thread.h" @@ -113,8 +112,8 @@ // |file_| is alive on FlushFile(), since the destructor will destruct // |task_runner_| along with |file_| and FlushFile() won't be called. - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, base::BindOnce(&FlushFile, file_.get()), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FlushFile, file_.get()), base::BindOnce(&ArcContentFileSystemFileStreamWriter::OnFlushFile, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); return net::ERR_IO_PENDING; @@ -141,8 +140,8 @@ // |file_| is alive on WriteFile(), since the destructor will destruct // |task_runner_| along with |file_| and WriteFile() won't be called. - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&WriteFile, file_.get(), base::WrapRefCounted(buffer), buffer_length), base::BindOnce(&ArcContentFileSystemFileStreamWriter::OnWrite, @@ -204,9 +203,8 @@ } // |file_| is alive on SeekFile(), since the destructor will destruct // |task_runner_| along with |file_| and SeekFile() won't be called. - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(&SeekFile, file_.get(), offset_), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SeekFile, file_.get(), offset_), base::BindOnce(&ArcContentFileSystemFileStreamWriter::OnSeekFile, weak_ptr_factory_.GetWeakPtr(), buf, buffer_length, std::move(callback)));
diff --git a/chrome/browser/ash/arc/fileapi/file_stream_forwarder.cc b/chrome/browser/ash/arc/fileapi/file_stream_forwarder.cc index c33be0d..7e1f9d7 100644 --- a/chrome/browser/ash/arc/fileapi/file_stream_forwarder.cc +++ b/chrome/browser/ash/arc/fileapi/file_stream_forwarder.cc
@@ -11,7 +11,6 @@ #include "base/callback_helpers.h" #include "base/files/file_util.h" #include "base/strings/string_piece.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "content/public/browser/browser_task_traits.h" @@ -116,8 +115,8 @@ remaining_size_ -= result; DCHECK_GE(remaining_size_, 0); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( [](int fd, scoped_refptr<net::IOBuffer> buf, int size) { const bool result = base::WriteFileDescriptor(
diff --git a/chrome/browser/ash/arc/nearby_share/share_info_file_stream_adapter.cc b/chrome/browser/ash/arc/nearby_share/share_info_file_stream_adapter.cc index 6baff26..fe8c0ba 100644 --- a/chrome/browser/ash/arc/nearby_share/share_info_file_stream_adapter.cc +++ b/chrome/browser/ash/arc/nearby_share/share_info_file_stream_adapter.cc
@@ -11,7 +11,6 @@ #include "base/files/file_util.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_piece.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "chrome/browser/ash/arc/nearby_share/arc_nearby_share_uma.h" @@ -120,8 +119,8 @@ }, dest_fd_.get(), net_iobuf_, bytes_read); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, std::move(write_fd_func), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, std::move(write_fd_func), base::BindOnce(&ShareInfoFileStreamAdapter::OnWriteFinished, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/ash/arc/process/arc_process_service.cc b/chrome/browser/ash/arc/process/arc_process_service.cc index 01b8af0..6fbf9c3 100644 --- a/chrome/browser/ash/arc/process/arc_process_service.cc +++ b/chrome/browser/ash/arc/process/arc_process_service.cc
@@ -29,7 +29,6 @@ #include "base/memory/singleton.h" #include "base/process/process.h" #include "base/process/process_iterator.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/time/time.h" @@ -372,8 +371,8 @@ RequestProcessListCallback callback, std::vector<mojom::RunningAppProcessInfoPtr> processes) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&UpdateAndReturnProcessList, cached_process_snapshot_, nspid_to_pid_, std::move(processes)), std::move(callback)); @@ -385,8 +384,8 @@ RequestMemoryInfoCallback callback, std::vector<mojom::ArcMemoryDumpPtr> process_dumps) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&UpdateAndReturnMemoryInfo, cached_process_snapshot_, nspid_to_pid_, std::move(process_dumps)), std::move(callback)); @@ -494,8 +493,8 @@ void ArcProcessService::ContinueSystemProcessListRequest( RequestProcessListCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetArcSystemProcessList, cached_process_snapshot_), std::move(callback)); @@ -532,8 +531,8 @@ return; } - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetArcSystemProcessList, cached_process_snapshot_), base::BindOnce(&ArcProcessService::OnGetSystemProcessList, weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
diff --git a/chrome/browser/ash/arc/tracing/arc_system_stat_collector.cc b/chrome/browser/ash/arc/tracing/arc_system_stat_collector.cc index 3d00ff6..15b4a20 100644 --- a/chrome/browser/ash/arc/tracing/arc_system_stat_collector.cc +++ b/chrome/browser/ash/arc/tracing/arc_system_stat_collector.cc
@@ -22,7 +22,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/system/sys_info.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/thread_restrictions.h" @@ -365,9 +364,8 @@ background_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(&SystemReadersContext::InitOnBackgroundThread), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SystemReadersContext::InitOnBackgroundThread), base::BindOnce(&ArcSystemStatCollector::OnInitOnUiThread, weak_ptr_factory_.GetWeakPtr())); } @@ -591,8 +589,8 @@ LOG(WARNING) << "Dropping update, already pending"; return; } - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ArcSystemStatCollector::ReadSystemStatOnBackgroundThread, std::move(context_)), base::BindOnce(&ArcSystemStatCollector::UpdateSystemStatOnUiThread,
diff --git a/chrome/browser/ash/customization/customization_wallpaper_util.cc b/chrome/browser/ash/customization/customization_wallpaper_util.cc index 90c0b621..05836a1b 100644 --- a/chrome/browser/ash/customization/customization_wallpaper_util.cc +++ b/chrome/browser/ash/customization/customization_wallpaper_util.cc
@@ -8,7 +8,6 @@ #include "base/files/file_util.h" #include "base/location.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "chrome/browser/ash/customization/customization_document.h" #include "chrome/browser/ash/login/users/avatar/user_image_loader.h" @@ -106,8 +105,8 @@ base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); - base::PostTaskAndReplyWithResult( - task_runner.get(), FROM_HERE, + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ResizeAndSaveCustomizedDefaultWallpaper, wallpaper->image().DeepCopy(), resized_small_path, resized_large_path), @@ -171,8 +170,8 @@ base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); - base::PostTaskAndReplyWithResult( - task_runner.get(), FROM_HERE, + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CheckCustomizedWallpaperFilesExist, resized_small_path, resized_large_path), base::BindOnce(&SetCustomizedDefaultWallpaperAfterCheck, wallpaper_url,
diff --git a/chrome/browser/ash/drive/drive_integration_service.cc b/chrome/browser/ash/drive/drive_integration_service.cc index 6d545f0..6d44a17 100644 --- a/chrome/browser/ash/drive/drive_integration_service.cc +++ b/chrome/browser/ash/drive/drive_integration_service.cc
@@ -23,7 +23,6 @@ #include "base/strings/stringprintf.h" #include "base/system/sys_info.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/default_clock.h" #include "base/time/time.h" @@ -886,8 +885,8 @@ if (mount_start_.is_null() || was_ever_mounted) { mount_start_ = base::TimeTicks::Now(); } - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&EnsureDirectoryExists, drivefs_holder_->drivefs_host()->GetDataPath()), base::BindOnce(&DriveIntegrationService::MaybeMountDrive, @@ -1056,8 +1055,8 @@ state_ = INITIALIZING; - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &InitializeMetadata, cache_root_directory_, metadata_storage_.get(), file_manager::util::GetDownloadsFolderForProfile(profile_)), @@ -1105,8 +1104,8 @@ if (!metadata_storage_) return; - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &GetPinnedAndDirtyFiles, std::move(metadata_storage_), cache_root_directory_,
diff --git a/chrome/browser/ash/file_manager/file_watcher.cc b/chrome/browser/ash/file_manager/file_watcher.cc index 8473a05d..f66184d 100644 --- a/chrome/browser/ash/file_manager/file_watcher.cc +++ b/chrome/browser/ash/file_manager/file_watcher.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/logging.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "chrome/browser/ash/crostini/crostini_util.h" #include "chrome/browser/ash/file_manager/path_util.h" @@ -132,8 +131,8 @@ return; } - base::PostTaskAndReplyWithResult( - sequenced_task_runner_.get(), FROM_HERE, + sequenced_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CreateAndStartFilePathWatcher, local_path, google_apis::CreateRelayCallback(file_watcher_callback)), base::BindOnce(&FileWatcher::OnWatcherStarted,
diff --git a/chrome/browser/ash/login/eula_browsertest.cc b/chrome/browser/ash/login/eula_browsertest.cc index f095832..fdce96f 100644 --- a/chrome/browser/ash/login/eula_browsertest.cc +++ b/chrome/browser/ash/login/eula_browsertest.cc
@@ -12,7 +12,6 @@ #include "base/callback.h" #include "base/run_loop.h" #include "base/strings/string_util.h" -#include "base/task/task_runner_util.h" #include "base/test/bind.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" @@ -121,11 +120,12 @@ }; base::RunLoop runloop; - base::PostTaskAndReplyWithResult( - GoogleUpdateSettings::CollectStatsConsentTaskRunner(), FROM_HERE, - base::BindOnce(&GoogleUpdateSettings::GetCollectStatsConsent), - base::BindOnce(on_get_collect_stats_consent_callback, - runloop.QuitClosure(), &consented)); + GoogleUpdateSettings::CollectStatsConsentTaskRunner() + ->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce(&GoogleUpdateSettings::GetCollectStatsConsent), + base::BindOnce(on_get_collect_stats_consent_callback, + runloop.QuitClosure(), &consented)); runloop.Run(); return consented;
diff --git a/chrome/browser/ash/login/users/avatar/user_image_loader.cc b/chrome/browser/ash/login/users/avatar/user_image_loader.cc index f00ece16..6c1cd48 100644 --- a/chrome/browser/ash/login/users/avatar/user_image_loader.cc +++ b/chrome/browser/ash/login/users/avatar/user_image_loader.cc
@@ -16,7 +16,6 @@ #include "base/metrics/histogram_functions.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "chrome/browser/ash/login/helper.h" #include "chrome/browser/browser_process.h" @@ -172,8 +171,8 @@ SkBitmap* bitmap = new SkBitmap; auto* image_format = new user_manager::UserImage::ImageFormat( user_manager::UserImage::FORMAT_UNKNOWN); - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CropImage, decoded_image, target_size, bitmap, image_format), base::BindOnce(&UserImageRequest::OnImageCropped, @@ -371,9 +370,8 @@ int pixels_per_side, LoadedCallback loaded_cb) { std::string* data = new std::string; - base::PostTaskAndReplyWithResult( - background_task_runner.get(), FROM_HERE, - base::BindOnce(&base::ReadFileToString, file_path, data), + background_task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&base::ReadFileToString, file_path, data), base::BindOnce(&DecodeImage, ImageInfo(file_path, pixels_per_side, image_codec, std::move(loaded_cb)),
diff --git a/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc b/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc index 36fd626..f3beb76 100644 --- a/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc +++ b/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc
@@ -22,7 +22,6 @@ #include "base/strings/string_util.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" @@ -482,8 +481,8 @@ old_image_path = base::FilePath::FromUTF8Unsafe(*value); } - base::PostTaskAndReplyWithResult( - parent_->background_task_runner_.get(), FROM_HERE, + parent_->background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SaveAndDeleteImage, image_bytes, image_path_, old_image_path), base::BindOnce(&Job::OnSaveImageDone, weak_factory_.GetWeakPtr()));
diff --git a/chrome/browser/ash/ownership/owner_settings_service_ash.cc b/chrome/browser/ash/ownership/owner_settings_service_ash.cc index 95360d8..3d0e365 100644 --- a/chrome/browser/ash/ownership/owner_settings_service_ash.cc +++ b/chrome/browser/ash/ownership/owner_settings_service_ash.cc
@@ -21,7 +21,6 @@ #include "base/memory/ptr_util.h" #include "base/metrics/histogram_functions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/thread_checker.h" #include "chrome/browser/ash/login/session/user_session_manager.h" @@ -179,8 +178,8 @@ base::ThreadPool::CreateTaskRunner( {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); - base::PostTaskAndReplyWithResult( - task_runner.get(), FROM_HERE, + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DoesPrivateKeyExistAsyncHelper, owner_key_util), std::move(callback)); }
diff --git a/chrome/browser/ash/policy/core/cached_policy_key_loader.cc b/chrome/browser/ash/policy/core/cached_policy_key_loader.cc index d4e55ac..0bd4d38 100644 --- a/chrome/browser/ash/policy/core/cached_policy_key_loader.cc +++ b/chrome/browser/ash/policy/core/cached_policy_key_loader.cc
@@ -15,7 +15,6 @@ #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "chromeos/ash/components/cryptohome/cryptohome_parameters.h" #include "chromeos/ash/components/dbus/userdataauth/cryptohome_misc_client.h" @@ -152,8 +151,8 @@ void CachedPolicyKeyLoader::TriggerLoadPolicyKey() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CachedPolicyKeyLoader::LoadPolicyKey, cached_policy_key_path_), base::BindOnce(&CachedPolicyKeyLoader::OnPolicyKeyLoaded,
diff --git a/chrome/browser/ash/policy/reporting/arc_app_install_event_log_manager.cc b/chrome/browser/ash/policy/reporting/arc_app_install_event_log_manager.cc index 7e6c0388..0806f8a3 100644 --- a/chrome/browser/ash/policy/reporting/arc_app_install_event_log_manager.cc +++ b/chrome/browser/ash/policy/reporting/arc_app_install_event_log_manager.cc
@@ -8,7 +8,6 @@ #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/file_util.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "chrome/browser/profiles/profile.h" @@ -40,8 +39,8 @@ uploader_->SetDelegate(this); log_ = std::make_unique<ArcLog>(); app_log_upload_ = std::make_unique<AppLogUpload>(this); - base::PostTaskAndReplyWithResult( - log_task_runner_.get(), FROM_HERE, + log_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ArcLog::Init, base::Unretained(log_.get()), GetLogFilePath(*profile)), base::BindOnce(&ArcAppInstallEventLogManager::AppLogUpload::OnLogInit, @@ -83,8 +82,8 @@ << event.event_type(); } - base::PostTaskAndReplyWithResult( - log_task_runner_.get(), FROM_HERE, + log_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ArcLog::Add, base::Unretained(log_.get()), packages, event), base::BindOnce(&ArcAppInstallEventLogManager::AppLogUpload::OnLogChange, @@ -98,8 +97,8 @@ void ArcAppInstallEventLogManager::SerializeForUpload( ArcAppInstallEventLogUploader::Delegate::SerializationCallback callback) { - base::PostTaskAndReplyWithResult( - log_task_runner_.get(), FROM_HERE, + log_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ArcAppInstallEventLogManager::ArcLog::Serialize, base::Unretained(log_.get())), base::BindOnce( @@ -117,8 +116,8 @@ } app_log_upload_->upload_requested_ = false; - base::PostTaskAndReplyWithResult( - log_task_runner_.get(), FROM_HERE, + log_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &ArcAppInstallEventLogManager::ArcLog::ClearSerializedAndStore, base::Unretained(log_.get())),
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.cc index d3d8ae6..ce1d623 100644 --- a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.cc +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.cc
@@ -9,7 +9,9 @@ #include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_boot_performance_sampler_handler.h" #include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.h" #include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.h" +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_display_sampler_handler.h" #include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_input_sampler_handler.h" +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_memory_sampler_handler.h" #include "chromeos/ash/services/cros_healthd/public/cpp/service_connection.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -19,240 +21,6 @@ namespace cros_healthd = ::ash::cros_healthd::mojom; -MemoryEncryptionState TranslateMemoryEncryptionState( - cros_healthd::EncryptionState encryption_state) { - switch (encryption_state) { - case cros_healthd::EncryptionState::kUnknown: - return MEMORY_ENCRYPTION_STATE_UNKNOWN; - case cros_healthd::EncryptionState::kEncryptionDisabled: - return MEMORY_ENCRYPTION_STATE_DISABLED; - case cros_healthd::EncryptionState::kTmeEnabled: - return MEMORY_ENCRYPTION_STATE_TME; - case cros_healthd::EncryptionState::kMktmeEnabled: - return MEMORY_ENCRYPTION_STATE_MKTME; - } - - NOTREACHED(); -} - -MemoryEncryptionAlgorithm TranslateMemoryEncryptionAlgorithm( - cros_healthd::CryptoAlgorithm encryption_algorithm) { - switch (encryption_algorithm) { - case cros_healthd::CryptoAlgorithm::kUnknown: - return MEMORY_ENCRYPTION_ALGORITHM_UNKNOWN; - case cros_healthd::CryptoAlgorithm::kAesXts128: - return MEMORY_ENCRYPTION_ALGORITHM_AES_XTS_128; - case cros_healthd::CryptoAlgorithm::kAesXts256: - return MEMORY_ENCRYPTION_ALGORITHM_AES_XTS_256; - } - - NOTREACHED(); -} - -void HandleMemoryResult(OptionalMetricCallback callback, - CrosHealthdMetricSampler::MetricType metric_type, - cros_healthd::TelemetryInfoPtr result) { - absl::optional<MetricData> metric_data; - const auto& memory_result = result->memory_result; - - if (!memory_result.is_null()) { - switch (memory_result->which()) { - case cros_healthd::MemoryResult::Tag::kError: { - DVLOG(1) << "cros_healthd: Error getting memory info: " - << memory_result->get_error()->msg; - break; - } - - case cros_healthd::MemoryResult::Tag::kMemoryInfo: { - const auto& memory_info = memory_result->get_memory_info(); - if (memory_result.is_null()) { - DVLOG(1) << "Null MemoryInfo from cros_healthd"; - break; - } - - // Gather memory info. - if (metric_type == CrosHealthdMetricSampler::MetricType::kInfo) { - metric_data = absl::make_optional<MetricData>(); - auto* const memory_encryption_info_out = - metric_data->mutable_info_data() - ->mutable_memory_info() - ->mutable_tme_info(); - const auto* const memory_encryption_info = - memory_info->memory_encryption_info.get(); - - if (memory_encryption_info) { - memory_encryption_info_out->set_encryption_state( - TranslateMemoryEncryptionState( - memory_encryption_info->encryption_state)); - memory_encryption_info_out->set_encryption_algorithm( - TranslateMemoryEncryptionAlgorithm( - memory_encryption_info->active_algorithm)); - memory_encryption_info_out->set_max_keys( - memory_encryption_info->max_key_number); - memory_encryption_info_out->set_key_length( - memory_encryption_info->key_length); - } else { - // If encryption info isn't set, mark it as disabled. - memory_encryption_info_out->set_encryption_state( - MEMORY_ENCRYPTION_STATE_DISABLED); - } - } - break; - } - } - } - - std::move(callback).Run(std::move(metric_data)); -} - -void HandleDisplayResult(OptionalMetricCallback callback, - CrosHealthdMetricSampler::MetricType metric_type, - cros_healthd::TelemetryInfoPtr result) { - absl::optional<MetricData> metric_data; - const auto& display_result = result->display_result; - if (!display_result.is_null()) { - switch (display_result->which()) { - case cros_healthd::DisplayResult::Tag::kError: { - DVLOG(1) << "cros_healthd: Error getting bus info: " - << display_result->get_error()->msg; - break; - } - - case cros_healthd::DisplayResult::Tag::kDisplayInfo: { - const auto& display_info = display_result->get_display_info(); - if (display_info.is_null()) { - DVLOG(1) << "Null DisplayInfo from cros_healthd"; - break; - } - - metric_data = absl::make_optional<MetricData>(); - const auto* const embedded_display_info = display_info->edp_info.get(); - if (metric_type == CrosHealthdMetricSampler::MetricType::kInfo) { - // Gather e-privacy screen info. - auto* const privacy_screen_info_out = - metric_data->mutable_info_data()->mutable_privacy_screen_info(); - privacy_screen_info_out->set_supported( - embedded_display_info->privacy_screen_supported); - - // Gather displays info. - auto* const internal_dp_out = metric_data->mutable_info_data() - ->mutable_display_info() - ->add_display_device(); - internal_dp_out->set_is_internal(true); - if (embedded_display_info->display_name.has_value()) { - internal_dp_out->set_display_name( - embedded_display_info->display_name.value()); - } - if (embedded_display_info->display_width) { - internal_dp_out->set_display_width( - embedded_display_info->display_width->value); - } - if (embedded_display_info->display_height) { - internal_dp_out->set_display_height( - embedded_display_info->display_height->value); - } - if (embedded_display_info->manufacturer.has_value()) { - internal_dp_out->set_manufacturer( - embedded_display_info->manufacturer.value()); - } - if (embedded_display_info->model_id) { - internal_dp_out->set_model_id( - embedded_display_info->model_id->value); - } - if (embedded_display_info->manufacture_year) { - internal_dp_out->set_manufacture_year( - embedded_display_info->manufacture_year->value); - } - if (display_info->dp_infos) { - for (const auto& current_external_display : - *display_info->dp_infos) { - auto* const external_dp_out = metric_data->mutable_info_data() - ->mutable_display_info() - ->add_display_device(); - external_dp_out->set_is_internal(false); - if (current_external_display->display_name.has_value()) { - external_dp_out->set_display_name( - current_external_display->display_name.value()); - } - if (current_external_display->display_width) { - external_dp_out->set_display_width( - current_external_display->display_width->value); - } - if (current_external_display->display_height) { - external_dp_out->set_display_height( - current_external_display->display_height->value); - } - if (current_external_display->manufacturer.has_value()) { - external_dp_out->set_manufacturer( - current_external_display->manufacturer.value()); - } - if (current_external_display->model_id) { - external_dp_out->set_model_id( - current_external_display->model_id->value); - } - if (current_external_display->manufacture_year) { - external_dp_out->set_manufacture_year( - current_external_display->manufacture_year->value); - } - } - } - } else if (metric_type == - CrosHealthdMetricSampler::MetricType::kTelemetry) { - // Gather displays telemetry. - auto* const internal_dp_out = metric_data->mutable_telemetry_data() - ->mutable_displays_telemetry() - ->add_display_status(); - internal_dp_out->set_is_internal(true); - if (embedded_display_info->display_name.has_value()) { - internal_dp_out->set_display_name( - embedded_display_info->display_name.value()); - } - if (embedded_display_info->resolution_horizontal) { - internal_dp_out->set_resolution_horizontal( - embedded_display_info->resolution_horizontal->value); - } - if (embedded_display_info->resolution_vertical) { - internal_dp_out->set_resolution_vertical( - embedded_display_info->resolution_vertical->value); - } - if (embedded_display_info->refresh_rate) { - internal_dp_out->set_refresh_rate( - embedded_display_info->refresh_rate->value); - } - if (display_info->dp_infos) { - for (const auto& current_external_display : - *display_info->dp_infos) { - auto* const external_dp_out = - metric_data->mutable_telemetry_data() - ->mutable_displays_telemetry() - ->add_display_status(); - external_dp_out->set_is_internal(false); - if (current_external_display->display_name.has_value()) { - external_dp_out->set_display_name( - current_external_display->display_name.value()); - } - if (current_external_display->resolution_horizontal) { - external_dp_out->set_resolution_horizontal( - current_external_display->resolution_horizontal->value); - } - if (current_external_display->resolution_vertical) { - external_dp_out->set_resolution_vertical( - current_external_display->resolution_vertical->value); - } - if (current_external_display->refresh_rate) { - external_dp_out->set_refresh_rate( - current_external_display->refresh_rate->value); - } - } - } - } - break; - } - } - } - std::move(callback).Run(std::move(metric_data)); -} - void OnHealthdInfoReceived(OptionalMetricCallback callback, cros_healthd::ProbeCategoryEnum probe_category, CrosHealthdMetricSampler::MetricType metric_type, @@ -275,7 +43,8 @@ break; } case cros_healthd::ProbeCategoryEnum::kMemory: { - HandleMemoryResult(std::move(callback), metric_type, std::move(result)); + CrosHealthdMemorySamplerHandler handler = CrosHealthdMemorySamplerHandler(); + handler.HandleResult(std::move(result), std::move(callback)); break; } case cros_healthd::ProbeCategoryEnum::kBootPerformance: { @@ -290,7 +59,8 @@ break; } case cros_healthd::ProbeCategoryEnum::kDisplay: { - HandleDisplayResult(std::move(callback), metric_type, std::move(result)); + auto handler = CrosHealthdDisplaySamplerHandler(metric_type); + handler.HandleResult(std::move(result), std::move(callback)); break; } default: {
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_display_sampler_handler.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_display_sampler_handler.cc new file mode 100644 index 0000000..23d2c978 --- /dev/null +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_display_sampler_handler.cc
@@ -0,0 +1,174 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_display_sampler_handler.h" + +#include <utility> + +#include "base/logging.h" +#include "base/notreached.h" +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.h" +#include "components/reporting/metrics/sampler.h" +#include "components/reporting/proto/synced/metric_data.pb.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace reporting { + +namespace cros_healthd = ::ash::cros_healthd::mojom; + +CrosHealthdDisplaySamplerHandler::CrosHealthdDisplaySamplerHandler( + CrosHealthdMetricSampler::MetricType metric_type) + : metric_type_(metric_type) {} + +CrosHealthdDisplaySamplerHandler::~CrosHealthdDisplaySamplerHandler() = default; + +void CrosHealthdDisplaySamplerHandler::HandleResult( + cros_healthd::TelemetryInfoPtr result, + OptionalMetricCallback callback) const { + absl::optional<MetricData> metric_data; + const auto& display_result = result->display_result; + if (!display_result.is_null()) { + switch (display_result->which()) { + case cros_healthd::DisplayResult::Tag::kError: { + DVLOG(1) << "cros_healthd: Error getting bus info: " + << display_result->get_error()->msg; + break; + } + + case cros_healthd::DisplayResult::Tag::kDisplayInfo: { + const auto& display_info = display_result->get_display_info(); + if (display_info.is_null()) { + DVLOG(1) << "Null DisplayInfo from cros_healthd"; + break; + } + + metric_data = absl::make_optional<MetricData>(); + const auto* const embedded_display_info = display_info->edp_info.get(); + if (metric_type_ == CrosHealthdMetricSampler::MetricType::kInfo) { + // Gather e-privacy screen info. + auto* const privacy_screen_info_out = + metric_data->mutable_info_data()->mutable_privacy_screen_info(); + privacy_screen_info_out->set_supported( + embedded_display_info->privacy_screen_supported); + + // Gather displays info. + auto* const internal_dp_out = metric_data->mutable_info_data() + ->mutable_display_info() + ->add_display_device(); + internal_dp_out->set_is_internal(true); + if (embedded_display_info->display_name.has_value()) { + internal_dp_out->set_display_name( + embedded_display_info->display_name.value()); + } + if (embedded_display_info->display_width) { + internal_dp_out->set_display_width( + embedded_display_info->display_width->value); + } + if (embedded_display_info->display_height) { + internal_dp_out->set_display_height( + embedded_display_info->display_height->value); + } + if (embedded_display_info->manufacturer.has_value()) { + internal_dp_out->set_manufacturer( + embedded_display_info->manufacturer.value()); + } + if (embedded_display_info->model_id) { + internal_dp_out->set_model_id( + embedded_display_info->model_id->value); + } + if (embedded_display_info->manufacture_year) { + internal_dp_out->set_manufacture_year( + embedded_display_info->manufacture_year->value); + } + if (display_info->dp_infos) { + for (const auto& current_external_display : + *display_info->dp_infos) { + auto* const external_dp_out = metric_data->mutable_info_data() + ->mutable_display_info() + ->add_display_device(); + external_dp_out->set_is_internal(false); + if (current_external_display->display_name.has_value()) { + external_dp_out->set_display_name( + current_external_display->display_name.value()); + } + if (current_external_display->display_width) { + external_dp_out->set_display_width( + current_external_display->display_width->value); + } + if (current_external_display->display_height) { + external_dp_out->set_display_height( + current_external_display->display_height->value); + } + if (current_external_display->manufacturer.has_value()) { + external_dp_out->set_manufacturer( + current_external_display->manufacturer.value()); + } + if (current_external_display->model_id) { + external_dp_out->set_model_id( + current_external_display->model_id->value); + } + if (current_external_display->manufacture_year) { + external_dp_out->set_manufacture_year( + current_external_display->manufacture_year->value); + } + } + } + } else if (metric_type_ == + CrosHealthdMetricSampler::MetricType::kTelemetry) { + // Gather displays telemetry. + auto* const internal_dp_out = metric_data->mutable_telemetry_data() + ->mutable_displays_telemetry() + ->add_display_status(); + internal_dp_out->set_is_internal(true); + if (embedded_display_info->display_name.has_value()) { + internal_dp_out->set_display_name( + embedded_display_info->display_name.value()); + } + if (embedded_display_info->resolution_horizontal) { + internal_dp_out->set_resolution_horizontal( + embedded_display_info->resolution_horizontal->value); + } + if (embedded_display_info->resolution_vertical) { + internal_dp_out->set_resolution_vertical( + embedded_display_info->resolution_vertical->value); + } + if (embedded_display_info->refresh_rate) { + internal_dp_out->set_refresh_rate( + embedded_display_info->refresh_rate->value); + } + if (display_info->dp_infos) { + for (const auto& current_external_display : + *display_info->dp_infos) { + auto* const external_dp_out = + metric_data->mutable_telemetry_data() + ->mutable_displays_telemetry() + ->add_display_status(); + external_dp_out->set_is_internal(false); + if (current_external_display->display_name.has_value()) { + external_dp_out->set_display_name( + current_external_display->display_name.value()); + } + if (current_external_display->resolution_horizontal) { + external_dp_out->set_resolution_horizontal( + current_external_display->resolution_horizontal->value); + } + if (current_external_display->resolution_vertical) { + external_dp_out->set_resolution_vertical( + current_external_display->resolution_vertical->value); + } + if (current_external_display->refresh_rate) { + external_dp_out->set_refresh_rate( + current_external_display->refresh_rate->value); + } + } + } + } + break; + } + } + } + std::move(callback).Run(std::move(metric_data)); +} + +} // namespace reporting
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_display_sampler_handler.h b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_display_sampler_handler.h new file mode 100644 index 0000000..714b9af --- /dev/null +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_display_sampler_handler.h
@@ -0,0 +1,43 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_DISPLAY_SAMPLER_HANDLER_H_ +#define CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_DISPLAY_SAMPLER_HANDLER_H_ + +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.h" +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_sampler_handler.h" +#include "chromeos/ash/services/cros_healthd/public/mojom/cros_healthd_probe.mojom.h" +#include "components/reporting/metrics/sampler.h" + +namespace reporting { + +namespace cros_healthd = ::ash::cros_healthd::mojom; + +// Class that handles the resulting data after probing the croshealthd for the +// Display category. +class CrosHealthdDisplaySamplerHandler : public CrosHealthdSamplerHandler { + public: + CrosHealthdDisplaySamplerHandler( + CrosHealthdMetricSampler::MetricType metric_type); + + CrosHealthdDisplaySamplerHandler(const CrosHealthdDisplaySamplerHandler&) = + delete; + CrosHealthdDisplaySamplerHandler& operator=( + const CrosHealthdDisplaySamplerHandler&) = delete; + + ~CrosHealthdDisplaySamplerHandler() override; + + // HandleResult converts |result_| to MetricData. + void HandleResult(cros_healthd::TelemetryInfoPtr result, + OptionalMetricCallback callback) const override; + + private: + // Holds the value of the passed in Metric Type to use when processing the + // |result| parameter. + CrosHealthdMetricSampler::MetricType metric_type_; +}; + +} // namespace reporting + +#endif // CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_DISPLAY_SAMPLER_HANDLER_H_
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_memory_sampler_handler.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_memory_sampler_handler.cc new file mode 100644 index 0000000..36e3c85 --- /dev/null +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_memory_sampler_handler.cc
@@ -0,0 +1,108 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_memory_sampler_handler.h" + +#include <utility> + +#include "base/logging.h" +#include "components/reporting/metrics/sampler.h" +#include "components/reporting/proto/synced/metric_data.pb.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace reporting { + +namespace cros_healthd = ::ash::cros_healthd::mojom; + +namespace { + +MemoryEncryptionState TranslateMemoryEncryptionState( + cros_healthd::EncryptionState encryption_state) { + switch (encryption_state) { + case cros_healthd::EncryptionState::kUnknown: + return MEMORY_ENCRYPTION_STATE_UNKNOWN; + case cros_healthd::EncryptionState::kEncryptionDisabled: + return MEMORY_ENCRYPTION_STATE_DISABLED; + case cros_healthd::EncryptionState::kTmeEnabled: + return MEMORY_ENCRYPTION_STATE_TME; + case cros_healthd::EncryptionState::kMktmeEnabled: + return MEMORY_ENCRYPTION_STATE_MKTME; + } + + NOTREACHED(); +} + +MemoryEncryptionAlgorithm TranslateMemoryEncryptionAlgorithm( + cros_healthd::CryptoAlgorithm encryption_algorithm) { + switch (encryption_algorithm) { + case cros_healthd::CryptoAlgorithm::kUnknown: + return MEMORY_ENCRYPTION_ALGORITHM_UNKNOWN; + case cros_healthd::CryptoAlgorithm::kAesXts128: + return MEMORY_ENCRYPTION_ALGORITHM_AES_XTS_128; + case cros_healthd::CryptoAlgorithm::kAesXts256: + return MEMORY_ENCRYPTION_ALGORITHM_AES_XTS_256; + } + + NOTREACHED(); +} + +} // namespace + +CrosHealthdMemorySamplerHandler::~CrosHealthdMemorySamplerHandler() = default; + +void CrosHealthdMemorySamplerHandler::HandleResult( + cros_healthd::TelemetryInfoPtr result, + OptionalMetricCallback callback) const { + absl::optional<MetricData> metric_data; + const auto& memory_result = result->memory_result; + + if (!memory_result.is_null()) { + switch (memory_result->which()) { + case cros_healthd::MemoryResult::Tag::kError: { + DVLOG(1) << "cros_healthd: Error getting memory info: " + << memory_result->get_error()->msg; + break; + } + + case cros_healthd::MemoryResult::Tag::kMemoryInfo: { + const auto& memory_info = memory_result->get_memory_info(); + if (memory_result.is_null()) { + DVLOG(1) << "Null MemoryInfo from cros_healthd"; + break; + } + + // Gather memory info. + metric_data = absl::make_optional<MetricData>(); + auto* const memory_encryption_info_out = + metric_data->mutable_info_data() + ->mutable_memory_info() + ->mutable_tme_info(); + const auto* const memory_encryption_info = + memory_info->memory_encryption_info.get(); + + if (memory_encryption_info) { + memory_encryption_info_out->set_encryption_state( + TranslateMemoryEncryptionState( + memory_encryption_info->encryption_state)); + memory_encryption_info_out->set_encryption_algorithm( + TranslateMemoryEncryptionAlgorithm( + memory_encryption_info->active_algorithm)); + memory_encryption_info_out->set_max_keys( + memory_encryption_info->max_key_number); + memory_encryption_info_out->set_key_length( + memory_encryption_info->key_length); + } else { + // If encryption info isn't set, mark it as disabled. + memory_encryption_info_out->set_encryption_state( + MEMORY_ENCRYPTION_STATE_DISABLED); + } + break; + } + } + } + + std::move(callback).Run(std::move(metric_data)); +} + +} // namespace reporting
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_memory_sampler_handler.h b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_memory_sampler_handler.h new file mode 100644 index 0000000..9a89b9b2 --- /dev/null +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_memory_sampler_handler.h
@@ -0,0 +1,36 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_MEMORY_SAMPLER_HANDLER_H_ +#define CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_MEMORY_SAMPLER_HANDLER_H_ + +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_sampler_handler.h" +#include "chromeos/ash/services/cros_healthd/public/mojom/cros_healthd_probe.mojom.h" +#include "components/reporting/metrics/sampler.h" + +namespace reporting { + +namespace cros_healthd = ::ash::cros_healthd::mojom; + +// Class that handles the resulting data after probing the croshealthd for the +// Memory category. +class CrosHealthdMemorySamplerHandler : public CrosHealthdSamplerHandler { + public: + CrosHealthdMemorySamplerHandler() = default; + + CrosHealthdMemorySamplerHandler(const CrosHealthdMemorySamplerHandler&) = + delete; + CrosHealthdMemorySamplerHandler& operator=( + const CrosHealthdMemorySamplerHandler&) = delete; + + ~CrosHealthdMemorySamplerHandler() override; + + // HandleResult converts |result| to MetricData. + void HandleResult(cros_healthd::TelemetryInfoPtr result, + OptionalMetricCallback callback) const override; +}; + +} // namespace reporting + +#endif // CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_MEMORY_SAMPLER_HANDLER_H_
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager.cc index b400aca..b4032b1 100644 --- a/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager.cc +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager.cc
@@ -7,6 +7,7 @@ #include <algorithm> #include <memory> #include <string> +#include <utility> #include <vector> #include "base/check.h" @@ -14,6 +15,7 @@ #include "base/feature_list.h" #include "base/location.h" #include "base/strings/string_piece.h" +#include "base/time/time.h" #include "base/values.h" #include "chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_events_observer.h" #include "chrome/browser/ash/policy/reporting/metrics_reporting/audio/audio_events_observer.h" @@ -31,7 +33,6 @@ #include "chromeos/ash/components/settings/cros_settings_names.h" #include "components/reporting/client/report_queue_configuration.h" #include "components/reporting/metrics/collector_base.h" -#include "components/reporting/metrics/configured_sampler.h" #include "components/reporting/metrics/metric_event_observer.h" #include "components/reporting/metrics/metric_event_observer_manager.h" #include "components/reporting/metrics/metric_report_queue.h" @@ -45,12 +46,12 @@ namespace reporting { namespace { -constexpr char kSamplerAudioTelemetry[] = "audio_telemetry"; -constexpr char kSamplerBootPerformance[] = "boot_performance"; -constexpr char kSamplerHttpsLatency[] = "https_latency"; -constexpr char kSamplerNetworkTelemetry[] = "network_telemetry"; -constexpr char kSamplerPeripheralTelemetry[] = "peripheral_telemetry"; -constexpr char kSamplerDisplaysTelemetry[] = "displays_telemetry"; +constexpr char kAudioTelemetry[] = "audio_telemetry"; +constexpr char kBootPerformance[] = "boot_performance"; +constexpr char kHttpsLatency[] = "https_latency"; +constexpr char kNetworkTelemetry[] = "network_telemetry"; +constexpr char kPeripheralTelemetry[] = "peripheral_telemetry"; +constexpr char kDisplaysTelemetry[] = "displays_telemetry"; } // namespace @@ -121,10 +122,7 @@ EventType::kUser, Destination::PERIPHERAL_EVENTS, Priority::SECURITY); InitOnAffiliatedLogin(profile); - delayed_init_on_login_timer_.Start( - FROM_HERE, delegate_->GetInitDelay(), - base::BindOnce(&MetricReportingManager::DelayedInitOnAffiliatedLogin, - base::Unretained(this), profile)); + DelayedInitOnAffiliatedLogin(profile); } void MetricReportingManager::DeviceSettingsUpdated() { @@ -133,13 +131,13 @@ } } -std::vector<ConfiguredSampler*> MetricReportingManager::GetTelemetrySamplers( +std::vector<CollectorBase*> MetricReportingManager::GetTelemetryCollectors( MetricEventType event_type) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); switch (event_type) { case NETWORK_SIGNAL_STRENGTH_LOW: case NETWORK_SIGNAL_STRENGTH_RECOVERED: - return GetTelemetrySamplersFromSetting( + return GetTelemetryCollectorsFromSetting( ::ash::kReportDeviceSignalStrengthEventDrivenTelemetry); default: return {}; @@ -153,9 +151,6 @@ if (delegate_->IsDeprovisioned()) { return; } - // Initialize telemetry samplers that can be used before login. - InitDeviceTelemetrySamplers(); - info_report_queue_ = delegate_->CreateMetricReportQueue( EventType::kDevice, Destination::INFO_METRIC, Priority::SLOW_BATCH); telemetry_report_queue_ = delegate_->CreatePeriodicUploadReportQueue( @@ -164,8 +159,7 @@ metrics::GetDefaultReportUploadFrequency()); event_report_queue_ = delegate_->CreateMetricReportQueue( EventType::kDevice, Destination::EVENT_METRIC, Priority::SLOW_BATCH); - delayed_init_timer_.Start(FROM_HERE, delegate_->GetInitDelay(), this, - &MetricReportingManager::DelayedInit); + DelayedInit(); if (managed_session_service) { managed_session_observation_.Observe(managed_session_service); @@ -179,12 +173,12 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); delegate_.reset(); - one_shot_collectors_.clear(); - periodic_collectors_.clear(); + telemetry_collectors_.clear(); + info_collectors_.clear(); event_observer_managers_.clear(); - info_samplers_.clear(); - telemetry_sampler_map_.clear(); + samplers_.clear(); info_report_queue_.reset(); + network_bandwidth_collector_.reset(); telemetry_report_queue_.reset(); user_telemetry_report_queue_.reset(); event_report_queue_.reset(); @@ -192,22 +186,12 @@ user_peripheral_events_and_telemetry_report_queue_.reset(); } -void MetricReportingManager::InitDeviceTelemetrySamplers() { - auto boot_performance_sampler = std::make_unique<CrosHealthdMetricSampler>( - ::ash::cros_healthd::mojom::ProbeCategoryEnum::kBootPerformance, - CrosHealthdMetricSampler::MetricType::kTelemetry); - InitTelemetryConfiguredSampler( - /*sampler_name=*/kSamplerBootPerformance, - std::move(boot_performance_sampler), - /*enable_setting_path=*/::ash::kReportDeviceBootMode, - /*default_value=*/true); -} - void MetricReportingManager::DelayedInit() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (delegate_->IsDeprovisioned()) { return; } - + // Info collectors init is delayed by default. CreateCrosHealthdInfoCollector( ::ash::cros_healthd::mojom::ProbeCategoryEnum::kCpu, ::ash::kReportDeviceCpuInfo, @@ -238,11 +222,18 @@ /*setting_enabled_default_value=*/true); // Boot performance telemetry collector. - InitOneShotTelemetryCollector(kSamplerBootPerformance, - telemetry_report_queue_.get()); + auto boot_performance_sampler = std::make_unique<CrosHealthdMetricSampler>( + ::ash::cros_healthd::mojom::ProbeCategoryEnum::kBootPerformance, + CrosHealthdMetricSampler::MetricType::kTelemetry); + InitOneShotTelemetryCollector( + /*collector_name=*/kBootPerformance, boot_performance_sampler.get(), + telemetry_report_queue_.get(), + /*enable_setting_path=*/::ash::kReportDeviceBootMode, + /*enable_default_value=*/true, delegate_->GetInitDelay()); + samplers_.push_back(std::move(boot_performance_sampler)); - initial_upload_timer_.Start(FROM_HERE, delegate_->GetInitialUploadDelay(), - this, &MetricReportingManager::UploadTelemetry); + initial_upload_timer_.Start(FROM_HERE, GetUploadDelay(), this, + &MetricReportingManager::UploadTelemetry); } void MetricReportingManager::InitOnAffiliatedLogin(Profile* profile) { @@ -250,17 +241,17 @@ return; } - InitTelemetrySamplersOnAffiliatedLogin(); - InitEventObserverManager( std::make_unique<AudioEventsObserver>(), user_event_report_queue_.get(), /*enable_setting_path=*/::ash::kReportDeviceAudioStatus, - metrics::kReportDeviceAudioStatusDefaultValue); + metrics::kReportDeviceAudioStatusDefaultValue, + /*init_delay=*/base::TimeDelta()); // Network health events observer. InitEventObserverManager( std::make_unique<NetworkEventsObserver>(), event_report_queue_.get(), /*enable_setting_path=*/::ash::kReportDeviceNetworkStatus, - metrics::kReportDeviceNetworkStatusDefaultValue); + metrics::kReportDeviceNetworkStatusDefaultValue, + /*init_delay=*/base::TimeDelta()); InitPeripheralsCollectors(); // Start observing app events only if the feature flag is set. @@ -269,55 +260,21 @@ InitEventObserverManager( std::move(app_events_observer), user_event_report_queue_.get(), /*enable_setting_path=*/::ash::kReportDeviceAppInfo, - metrics::kReportDeviceAppInfoDefaultValue); + metrics::kReportDeviceAppInfoDefaultValue, + /*init_delay=*/base::TimeDelta()); } } -void MetricReportingManager::InitTelemetrySamplersOnAffiliatedLogin() { - // Initialize telemetry samplers that can only be used after affiliated login. - auto audio_telemetry_sampler = std::make_unique<CrosHealthdMetricSampler>( - ::ash::cros_healthd::mojom::ProbeCategoryEnum::kAudio, - CrosHealthdMetricSampler::MetricType::kTelemetry); - InitTelemetryConfiguredSampler( - /*sampler_name=*/kSamplerAudioTelemetry, - std::move(audio_telemetry_sampler), - /*enable_setting_path=*/::ash::kReportDeviceAudioStatus, - metrics::kReportDeviceAudioStatusDefaultValue); - InitNetworkConfiguredSampler(/*sampler_name=*/kSamplerHttpsLatency, - delegate_->GetHttpsLatencySampler()); - InitNetworkConfiguredSampler( - /*sampler_name=*/kSamplerNetworkTelemetry, - delegate_->GetNetworkTelemetrySampler()); - auto peripheral_telemetry_sampler = - std::make_unique<CrosHealthdMetricSampler>( - ::ash::cros_healthd::mojom::ProbeCategoryEnum::kBus, - CrosHealthdMetricSampler::MetricType::kTelemetry); - InitTelemetryConfiguredSampler( - /*sampler_name=*/kSamplerPeripheralTelemetry, - std::move(peripheral_telemetry_sampler), - /*enable_setting_path=*/::ash::kReportDevicePeripherals, - metrics::kReportDevicePeripheralsDefaultValue); - auto displays_telemetry_sampler = std::make_unique<CrosHealthdMetricSampler>( - ash::cros_healthd::mojom::ProbeCategoryEnum::kDisplay, - CrosHealthdMetricSampler::MetricType::kTelemetry); - InitTelemetryConfiguredSampler( - /*sampler_name=*/kSamplerDisplaysTelemetry, - std::move(displays_telemetry_sampler), - /*enable_setting_path=*/::ash::kReportDeviceGraphicsStatus, - metrics::kReportDeviceGraphicsStatusDefaultValue); -} - void MetricReportingManager::DelayedInitOnAffiliatedLogin(Profile* profile) { if (delegate_->IsDeprovisioned()) { return; } - InitNetworkCollectors(profile); InitAudioCollectors(); InitDisplayCollectors(); - initial_upload_timer_.Start(FROM_HERE, delegate_->GetInitialUploadDelay(), - this, &MetricReportingManager::UploadTelemetry); + initial_upload_timer_.Start(FROM_HERE, GetUploadDelay(), this, + &MetricReportingManager::UploadTelemetry); } void MetricReportingManager::InitInfoCollector( @@ -329,89 +286,93 @@ if (!info_report_queue_) { return; } - one_shot_collectors_.emplace_back(delegate_->CreateOneShotCollector( + + info_collectors_.push_back(delegate_->CreateOneShotCollector( sampler.get(), info_report_queue_.get(), &reporting_settings_, - enable_setting_path, setting_enabled_default_value)); - info_samplers_.emplace_back(std::move(sampler)); + enable_setting_path, setting_enabled_default_value, + delegate_->GetInitDelay())); + samplers_.push_back(std::move(sampler)); } void MetricReportingManager::InitOneShotTelemetryCollector( - const std::string& sampler_name, - MetricReportQueue* metric_report_queue) { + const std::string& collector_name, + Sampler* sampler, + MetricReportQueue* metric_report_queue, + const std::string& enable_setting_path, + bool enable_default_value, + base::TimeDelta init_delay) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(base::Contains(telemetry_sampler_map_, sampler_name)); - + DCHECK(!base::Contains(telemetry_collectors_, collector_name)); if (!metric_report_queue) { return; } - auto* const configured_sampler = - telemetry_sampler_map_.at(sampler_name).get(); - periodic_collectors_.emplace_back(delegate_->CreateOneShotCollector( - configured_sampler->GetSampler(), metric_report_queue, - &reporting_settings_, configured_sampler->GetEnableSettingPath(), - configured_sampler->GetSettingEnabledDefaultValue())); + auto collector = delegate_->CreateOneShotCollector( + sampler, metric_report_queue, &reporting_settings_, enable_setting_path, + enable_default_value, init_delay); + telemetry_collectors_.insert({collector_name, std::move(collector)}); } void MetricReportingManager::InitPeriodicCollector( - const std::string& sampler_name, + const std::string& collector_name, + Sampler* sampler, MetricReportQueue* metric_report_queue, + const std::string& enable_setting_path, + bool enable_default_value, const std::string& rate_setting_path, base::TimeDelta default_rate, - int rate_unit_to_ms) { + int rate_unit_to_ms, + base::TimeDelta init_delay) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(base::Contains(telemetry_sampler_map_, sampler_name)); - + DCHECK(!base::Contains(telemetry_collectors_, collector_name)); if (!metric_report_queue) { return; } - auto* const configured_sampler = - telemetry_sampler_map_.at(sampler_name).get(); - periodic_collectors_.emplace_back(delegate_->CreatePeriodicCollector( - configured_sampler->GetSampler(), metric_report_queue, - &reporting_settings_, configured_sampler->GetEnableSettingPath(), - configured_sampler->GetSettingEnabledDefaultValue(), rate_setting_path, - default_rate, rate_unit_to_ms)); + auto collector = delegate_->CreatePeriodicCollector( + sampler, metric_report_queue, &reporting_settings_, enable_setting_path, + enable_default_value, rate_setting_path, default_rate, rate_unit_to_ms, + init_delay); + telemetry_collectors_.insert({collector_name, std::move(collector)}); } void MetricReportingManager::InitPeriodicEventCollector( - const std::string& sampler_name, + Sampler* sampler, std::unique_ptr<PeriodicEventCollector::EventDetector> event_detector, MetricReportQueue* metric_report_queue, + const std::string& enable_setting_path, + bool enable_default_value, const std::string& rate_setting_path, base::TimeDelta default_rate, - int rate_unit_to_ms) { + int rate_unit_to_ms, + base::TimeDelta init_delay) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(base::Contains(telemetry_sampler_map_, sampler_name)); - if (!metric_report_queue) { return; } - auto* const configured_sampler = - telemetry_sampler_map_.at(sampler_name).get(); auto periodic_event_collector = std::make_unique<PeriodicEventCollector>( - configured_sampler->GetSampler(), std::move(event_detector), - &reporting_settings_, rate_setting_path, default_rate, rate_unit_to_ms); + sampler, std::move(event_detector), &reporting_settings_, + rate_setting_path, default_rate, rate_unit_to_ms); InitEventObserverManager(std::move(periodic_event_collector), - metric_report_queue, - configured_sampler->GetEnableSettingPath(), - configured_sampler->GetSettingEnabledDefaultValue()); + metric_report_queue, enable_setting_path, + enable_default_value, init_delay); } void MetricReportingManager::InitEventObserverManager( std::unique_ptr<MetricEventObserver> event_observer, MetricReportQueue* metric_report_queue, const std::string& enable_setting_path, - bool setting_enabled_default_value) { + bool setting_enabled_default_value, + base::TimeDelta init_delay) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!metric_report_queue) { return; } event_observer_managers_.emplace_back(delegate_->CreateEventObserverManager( std::move(event_observer), metric_report_queue, &reporting_settings_, enable_setting_path, setting_enabled_default_value, - /*sampler_pool=*/this)); + /*collector_pool=*/this, init_delay)); } void MetricReportingManager::UploadTelemetry() { @@ -431,41 +392,32 @@ default_value); } -void MetricReportingManager::InitTelemetryConfiguredSampler( - const std::string& sampler_name, - std::unique_ptr<Sampler> sampler, - const std::string& enable_setting_path, - bool default_value) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - auto configured_sampler = std::make_unique<ConfiguredSampler>( - std::move(sampler), enable_setting_path, default_value, - &reporting_settings_); - telemetry_sampler_map_.insert({sampler_name, std::move(configured_sampler)}); -} - void MetricReportingManager::InitNetworkCollectors(Profile* profile) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Network health telemetry. - InitNetworkPeriodicCollector(kSamplerNetworkTelemetry, - telemetry_report_queue_.get()); + InitNetworkPeriodicCollector(kNetworkTelemetry, + delegate_->GetNetworkTelemetrySampler()); - // HttpsLatency telemetry. - InitNetworkPeriodicCollector(kSamplerHttpsLatency, - telemetry_report_queue_.get()); - + // HttpsLatency collectors. + auto https_latency_sampler = delegate_->GetHttpsLatencySampler(); // HttpsLatency events. InitPeriodicEventCollector( - kSamplerHttpsLatency, std::make_unique<HttpsLatencyEventDetector>(), - event_report_queue_.get(), + https_latency_sampler.get(), + std::make_unique<HttpsLatencyEventDetector>(), event_report_queue_.get(), + /*enable_setting_path=*/::ash::kReportDeviceNetworkStatus, + metrics::kReportDeviceNetworkStatusDefaultValue, ::ash::kReportDeviceNetworkTelemetryEventCheckingRateMs, metrics::GetDefaultEventCheckingRate( - metrics::kDefaultNetworkTelemetryEventCheckingRate)); + metrics::kDefaultNetworkTelemetryEventCheckingRate), + /*rate_unit_to_ms=*/1, delegate_->GetInitDelay()); + // HttpsLatency telemetry. + InitNetworkPeriodicCollector(kHttpsLatency, std::move(https_latency_sampler)); // Network bandwidth telemetry. - network_bandwidth_sampler_ = std::make_unique<NetworkBandwidthSampler>( + auto network_bandwidth_sampler = std::make_unique<NetworkBandwidthSampler>( g_browser_process->network_quality_tracker(), profile); - periodic_collectors_.emplace_back(delegate_->CreatePeriodicCollector( - network_bandwidth_sampler_.get(), user_telemetry_report_queue_.get(), + network_bandwidth_collector_ = delegate_->CreatePeriodicCollector( + network_bandwidth_sampler.get(), user_telemetry_report_queue_.get(), &reporting_settings_, /*enable_setting_path=*/ ::ash::kReportDeviceNetworkStatus, @@ -473,36 +425,43 @@ ::ash::kReportDeviceNetworkTelemetryCollectionRateMs, metrics::GetDefaultCollectionRate( metrics::kDefaultNetworkTelemetryCollectionRate), - /*rate_unit_to_ms=*/1)); + /*rate_unit_to_ms=*/1, delegate_->GetInitDelay()); + samplers_.push_back(std::move(network_bandwidth_sampler)); } void MetricReportingManager::InitNetworkPeriodicCollector( - const std::string& sampler_name, - MetricReportQueue* metric_report_queue) { - InitPeriodicCollector(sampler_name, metric_report_queue, - ::ash::kReportDeviceNetworkTelemetryCollectionRateMs, - metrics::GetDefaultCollectionRate( - metrics::kDefaultNetworkTelemetryCollectionRate)); -} - -void MetricReportingManager::InitNetworkConfiguredSampler( - const std::string& sampler_name, + const std::string& collector_name, std::unique_ptr<Sampler> sampler) { - InitTelemetryConfiguredSampler( - sampler_name, std::move(sampler), + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + InitPeriodicCollector( + collector_name, sampler.get(), telemetry_report_queue_.get(), /*enable_setting_path=*/::ash::kReportDeviceNetworkStatus, - metrics::kReportDeviceNetworkStatusDefaultValue); + metrics::kReportDeviceNetworkStatusDefaultValue, + ::ash::kReportDeviceNetworkTelemetryCollectionRateMs, + metrics::GetDefaultCollectionRate( + metrics::kDefaultNetworkTelemetryCollectionRate), + /*rate_unit_to_ms=*/1, delegate_->GetInitDelay()); + samplers_.push_back(std::move(sampler)); } void MetricReportingManager::InitAudioCollectors() { - InitPeriodicCollector(kSamplerAudioTelemetry, + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + auto audio_telemetry_sampler = std::make_unique<CrosHealthdMetricSampler>( + ::ash::cros_healthd::mojom::ProbeCategoryEnum::kAudio, + CrosHealthdMetricSampler::MetricType::kTelemetry); + InitPeriodicCollector(kAudioTelemetry, audio_telemetry_sampler.get(), user_telemetry_report_queue_.get(), + /*enable_setting_path=*/::ash::kReportDeviceAudioStatus, + metrics::kReportDeviceAudioStatusDefaultValue, ::ash::kReportDeviceAudioStatusCheckingRateMs, metrics::GetDefaultCollectionRate( - metrics::kDefaultAudioTelemetryCollectionRate)); + metrics::kDefaultAudioTelemetryCollectionRate), + /*rate_unit_to_ms=*/1, delegate_->GetInitDelay()); + samplers_.push_back(std::move(audio_telemetry_sampler)); } void MetricReportingManager::InitPeripheralsCollectors() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Peripheral events if (!user_peripheral_events_and_telemetry_report_queue_) { return; @@ -512,24 +471,40 @@ user_peripheral_events_and_telemetry_report_queue_.get(), &reporting_settings_, ::ash::kReportDevicePeripherals, metrics::kReportDevicePeripheralsDefaultValue, - /*sampler_pool=*/this)); + /*collector_pool=*/this)); // Peripheral telemetry + auto peripheral_telemetry_sampler = + std::make_unique<CrosHealthdMetricSampler>( + ::ash::cros_healthd::mojom::ProbeCategoryEnum::kBus, + CrosHealthdMetricSampler::MetricType::kTelemetry); InitOneShotTelemetryCollector( - kSamplerPeripheralTelemetry, - user_peripheral_events_and_telemetry_report_queue_.get()); + kPeripheralTelemetry, peripheral_telemetry_sampler.get(), + user_peripheral_events_and_telemetry_report_queue_.get(), + /*enable_setting_path=*/::ash::kReportDevicePeripherals, + metrics::kReportDevicePeripheralsDefaultValue, + /*init_delay=*/base::TimeDelta()); + samplers_.push_back(std::move(peripheral_telemetry_sampler)); } void MetricReportingManager::InitDisplayCollectors() { - InitPeriodicCollector(kSamplerDisplaysTelemetry, - telemetry_report_queue_.get(), - ::ash::kReportUploadFrequency, - metrics::GetDefaultCollectionRate( - metrics::kDefaultGraphicsTelemetryCollectionRate)); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + auto displays_telemetry_sampler = std::make_unique<CrosHealthdMetricSampler>( + ash::cros_healthd::mojom::ProbeCategoryEnum::kDisplay, + CrosHealthdMetricSampler::MetricType::kTelemetry); + InitPeriodicCollector( + kDisplaysTelemetry, displays_telemetry_sampler.get(), + telemetry_report_queue_.get(), + /*enable_setting_path=*/::ash::kReportDeviceGraphicsStatus, + metrics::kReportDeviceGraphicsStatusDefaultValue, + ::ash::kReportUploadFrequency, + metrics::GetDefaultCollectionRate(metrics::kDefaultReportUploadFrequency), + /*rate_unit_to_ms=*/1, delegate_->GetInitDelay()); + samplers_.push_back(std::move(displays_telemetry_sampler)); } -std::vector<ConfiguredSampler*> -MetricReportingManager::GetTelemetrySamplersFromSetting( +std::vector<CollectorBase*> +MetricReportingManager::GetTelemetryCollectorsFromSetting( base::StringPiece setting_name) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -540,9 +515,9 @@ return {}; } - std::vector<ConfiguredSampler*> samplers; + std::vector<CollectorBase*> samplers; for (const base::Value& telemetry : *telemetry_list) { - if (samplers.size() == telemetry_sampler_map_.size()) { + if (samplers.size() == telemetry_collectors_.size()) { // All samplers are already used, remaining telemetry names would be // either invalid or duplicates. break; @@ -550,13 +525,18 @@ const std::string* telemetry_name = telemetry.GetIfString(); if (telemetry_name && - base::Contains(telemetry_sampler_map_, *telemetry_name) && + base::Contains(telemetry_collectors_, *telemetry_name) && !base::Contains(samplers, - telemetry_sampler_map_.at(*telemetry_name).get())) { - samplers.push_back(telemetry_sampler_map_.at(*telemetry_name).get()); + telemetry_collectors_.at(*telemetry_name).get())) { + samplers.push_back(telemetry_collectors_.at(*telemetry_name).get()); } } return samplers; } +base::TimeDelta MetricReportingManager::GetUploadDelay() const { + // Upload delay time starts after init delay. + return delegate_->GetInitDelay() + delegate_->GetInitialUploadDelay(); +} + } // namespace reporting
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager.h b/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager.h index 9fca4c18..35441a0 100644 --- a/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager.h +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager.h
@@ -21,8 +21,7 @@ #include "chrome/browser/chromeos/reporting/metric_reporting_manager_delegate_base.h" #include "chrome/browser/profiles/profile.h" #include "chromeos/ash/services/cros_healthd/public/mojom/cros_healthd_probe.mojom.h" -#include "components/reporting/metrics/configured_sampler.h" -#include "components/reporting/metrics/event_driven_telemetry_sampler_pool.h" +#include "components/reporting/metrics/event_driven_telemetry_collector_pool.h" #include "components/reporting/metrics/periodic_event_collector.h" #include "components/reporting/proto/synced/record_constants.pb.h" @@ -41,7 +40,7 @@ // reporting. class MetricReportingManager : public policy::ManagedSessionService::Observer, public ::ash::DeviceSettingsService::Observer, - public EventDrivenTelemetrySamplerPool { + public EventDrivenTelemetryCollectorPool { public: // Delegate class for dependencies and behaviors that need to be overridden // for testing purposes. @@ -78,8 +77,8 @@ // DeviceSettingsService::Observer: void DeviceSettingsUpdated() override; - // EventDrivenTelemetrySamplerPool: - std::vector<ConfiguredSampler*> GetTelemetrySamplers( + // EventDrivenTelemetryCollectorPool: + std::vector<CollectorBase*> GetTelemetryCollectors( MetricEventType event_type) override; private: @@ -111,28 +110,40 @@ const std::string& enable_setting_path, bool setting_enabled_default_value); - void InitOneShotTelemetryCollector(const std::string& sampler_name, - MetricReportQueue* metric_report_queue); + void InitOneShotTelemetryCollector(const std::string& collector_name, + Sampler* sampler, + MetricReportQueue* metric_report_queue, + const std::string& enable_setting_path, + bool enable_default_value, + base::TimeDelta init_delay); - void InitPeriodicCollector(const std::string& sampler_name, + void InitPeriodicCollector(const std::string& collector_name, + Sampler* sampler, MetricReportQueue* metric_report_queue, + const std::string& enable_setting_path, + bool enable_default_value, const std::string& rate_setting_path, base::TimeDelta default_rate, - int rate_unit_to_ms = 1); + int rate_unit_to_ms, + base::TimeDelta init_delay); void InitPeriodicEventCollector( - const std::string& sampler_name, + Sampler* sampler, std::unique_ptr<PeriodicEventCollector::EventDetector> event_detector, MetricReportQueue* metric_report_queue, + const std::string& enable_setting_path, + bool enable_default_value, const std::string& rate_setting_path, base::TimeDelta default_rate, - int rate_unit_to_ms = 1); + int rate_unit_to_ms, + base::TimeDelta init_delay); void InitEventObserverManager( std::unique_ptr<MetricEventObserver> event_observer, MetricReportQueue* report_queue, const std::string& enable_setting_path, - bool setting_enabled_default_value); + bool setting_enabled_default_value, + base::TimeDelta init_delay); void UploadTelemetry(); @@ -141,15 +152,10 @@ const std::string& setting_path, bool default_value); - void InitTelemetryConfiguredSampler(const std::string& sampler_name, - std::unique_ptr<Sampler> sampler, - const std::string& enable_setting_path, - bool default_value); - void InitNetworkCollectors(Profile* profile); - void InitNetworkPeriodicCollector(const std::string& sampler_name, - MetricReportQueue* metric_report_queue); + void InitNetworkPeriodicCollector(const std::string& collector_name, + std::unique_ptr<Sampler> sampler); void InitNetworkConfiguredSampler(const std::string& sampler_name, std::unique_ptr<Sampler> sampler); @@ -160,7 +166,9 @@ void InitDisplayCollectors(); - std::vector<ConfiguredSampler*> GetTelemetrySamplersFromSetting( + base::TimeDelta GetUploadDelay() const; + + std::vector<CollectorBase*> GetTelemetryCollectorsFromSetting( base::StringPiece setting_name); CrosReportingSettings reporting_settings_; @@ -173,15 +181,17 @@ // enforced by destructing all of them using the `Shutdown` method if they // need to be deleted before the destruction of the MetricReportingManager // instance. - std::vector<std::unique_ptr<Sampler>> info_samplers_ + std::vector<std::unique_ptr<Sampler>> samplers_ GUARDED_BY_CONTEXT(sequence_checker_); - base::flat_map<std::string, std::unique_ptr<ConfiguredSampler>> - telemetry_sampler_map_ GUARDED_BY_CONTEXT(sequence_checker_); - std::vector<std::unique_ptr<CollectorBase>> periodic_collectors_; - std::vector<std::unique_ptr<CollectorBase>> one_shot_collectors_; + base::flat_map<std::string, std::unique_ptr<CollectorBase>> + telemetry_collectors_ GUARDED_BY_CONTEXT(sequence_checker_); + + std::vector<std::unique_ptr<CollectorBase>> info_collectors_ + GUARDED_BY_CONTEXT(sequence_checker_); + std::vector<std::unique_ptr<MetricEventObserverManager>> - event_observer_managers_; + event_observer_managers_ GUARDED_BY_CONTEXT(sequence_checker_); std::unique_ptr<MetricReportQueue> info_report_queue_; std::unique_ptr<MetricReportQueue> telemetry_report_queue_; @@ -199,16 +209,12 @@ ::ash::DeviceSettingsService::Observer> device_settings_observation_{this}; - base::OneShotTimer delayed_init_timer_; - - base::OneShotTimer delayed_init_on_login_timer_; - base::OneShotTimer initial_upload_timer_; - // This sampler will be removed with lacros, so we avoid adding it to - // `telemetry_sampler_map_` to make sure it won't be used for event driven + // This collector will be removed with lacros, so we avoid adding it to + // `telemetry_collectors_` to make sure it won't be used for event driven // telemetry. - std::unique_ptr<Sampler> network_bandwidth_sampler_; + std::unique_ptr<CollectorBase> network_bandwidth_collector_; std::unique_ptr<Delegate> delegate_; };
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager_unittest.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager_unittest.cc index 53dd8907..b13d129 100644 --- a/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager_unittest.cc +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/metric_reporting_manager_unittest.cc
@@ -12,13 +12,15 @@ #include "base/memory/raw_ptr.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" +#include "base/time/time.h" #include "base/values.h" #include "chrome/browser/ash/settings/scoped_testing_cros_settings.h" #include "chrome/browser/ash/settings/stub_cros_settings_provider.h" +#include "chrome/browser/chromeos/reporting/metric_default_utils.h" #include "chromeos/ash/components/settings/cros_settings_names.h" +#include "components/reporting/client/report_queue_configuration.h" #include "components/reporting/metrics/collector_base.h" -#include "components/reporting/metrics/configured_sampler.h" -#include "components/reporting/metrics/event_driven_telemetry_sampler_pool.h" +#include "components/reporting/metrics/event_driven_telemetry_collector_pool.h" #include "components/reporting/metrics/fakes/fake_metric_event_observer.h" #include "components/reporting/metrics/fakes/fake_metric_report_queue.h" #include "components/reporting/metrics/fakes/fake_reporting_settings.h" @@ -27,6 +29,7 @@ #include "components/reporting/metrics/metric_report_queue.h" #include "components/reporting/metrics/sampler.h" #include "components/reporting/proto/synced/metric_data.pb.h" +#include "components/reporting/proto/synced/record_constants.pb.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -52,7 +55,7 @@ reporting_settings, /*enable_setting_path=*/"", /*setting_enabled_default_value=*/false, - /*sampler_pool=*/nullptr), + /*collector_pool=*/nullptr), observer_manager_count_(observer_manager_count) { ++(*observer_manager_count_); } @@ -70,18 +73,29 @@ class FakeCollector : public CollectorBase { public: + FakeCollector() : CollectorBase(/*sampler=*/nullptr) {} + explicit FakeCollector(int* collector_count) - : CollectorBase(nullptr), collector_count_(collector_count) { - ++(*collector_count_); + : CollectorBase(/*sampler=*/nullptr), collector_count_(collector_count) { + if (collector_count_) { + ++(*collector_count_); + } } FakeCollector(const FakeCollector& other) = delete; FakeCollector& operator=(const FakeCollector& other) = delete; - ~FakeCollector() override { --(*collector_count_); } + ~FakeCollector() override { + if (collector_count_) { + --(*collector_count_); + } + } protected: - void OnMetricDataCollected(absl::optional<MetricData>) override {} + // CollectorBase: + void OnMetricDataCollected(bool is_event_driven, + absl::optional<MetricData> metric_data) override {} + bool CanCollect() const override { return true; } private: raw_ptr<int> collector_count_; @@ -124,7 +138,8 @@ MetricReportQueue* metric_report_queue, ReportingSettings* reporting_settings, const std::string& enable_setting_path, - bool setting_enabled_default_value), + bool setting_enabled_default_value, + base::TimeDelta init_delay), (override)); MOCK_METHOD(std::unique_ptr<CollectorBase>, @@ -136,7 +151,8 @@ bool setting_enabled_default_value, const std::string& rate_setting_path, base::TimeDelta default_rate, - int rate_unit_to_ms), + int rate_unit_to_ms, + base::TimeDelta init_delay), (override)); MOCK_METHOD(std::unique_ptr<MetricEventObserverManager>, @@ -146,7 +162,8 @@ ReportingSettings* reporting_settings, const std::string& enable_setting_path, bool setting_enabled_default_value, - EventDrivenTelemetrySamplerPool* sampler_pool), + EventDrivenTelemetryCollectorPool* collector_pool, + base::TimeDelta init_delay), (override)); MOCK_METHOD(std::unique_ptr<Sampler>, @@ -202,58 +219,49 @@ std::vector<base::test::FeatureRef> disabled_features; bool is_affiliated; MetricReportingSettingData setting_data; + bool has_init_delay; int expected_count_before_login; int expected_count_after_login; - int expected_count_after_login_delay; }; +test::FakeMetricReportQueue* CreateMockMetricReportQueueHelper( + ::testing::NiceMock<MockDelegate>* mock_delegate, + EventType event_type, + Destination destination, + Priority priority) { + auto metric_report_queue = std::make_unique<test::FakeMetricReportQueue>(); + auto* metric_report_queue_ptr = metric_report_queue.get(); + ON_CALL(*mock_delegate, + CreateMetricReportQueue(event_type, destination, priority)) + .WillByDefault(Return(ByMove(std::move(metric_report_queue)))); + return metric_report_queue_ptr; +} + class MetricReportingManagerTest : public ::testing::TestWithParam<MetricReportingManagerTestCase> { protected: void SetUp() override { - auto info_queue = std::make_unique<test::FakeMetricReportQueue>(); - info_queue_ptr_ = info_queue.get(); + mock_delegate_ = std::make_unique<::testing::NiceMock<MockDelegate>>(); + info_queue_ptr_ = CreateMockMetricReportQueueHelper( + mock_delegate_.get(), EventType::kDevice, Destination::INFO_METRIC, + Priority::SLOW_BATCH); + event_queue_ptr_ = CreateMockMetricReportQueueHelper( + mock_delegate_.get(), EventType::kDevice, Destination::EVENT_METRIC, + Priority::SLOW_BATCH); + user_telemetry_queue_ptr_ = CreateMockMetricReportQueueHelper( + mock_delegate_.get(), EventType::kUser, Destination::TELEMETRY_METRIC, + Priority::MANUAL_BATCH); + peripheral_queue_ptr_ = CreateMockMetricReportQueueHelper( + mock_delegate_.get(), EventType::kUser, Destination::PERIPHERAL_EVENTS, + Priority::SECURITY); + user_event_queue_ptr_ = CreateMockMetricReportQueueHelper( + mock_delegate_.get(), EventType::kUser, Destination::EVENT_METRIC, + Priority::SLOW_BATCH); + auto telemetry_queue = std::make_unique<test::FakeMetricReportQueue>(); telemetry_queue_ptr_ = telemetry_queue.get(); - auto event_queue = std::make_unique<test::FakeMetricReportQueue>(); - event_queue_ptr_ = event_queue.get(); - auto user_telemetry_queue = std::make_unique<test::FakeMetricReportQueue>(); - user_telemetry_queue_ptr_ = user_telemetry_queue.get(); - auto peripheral_queue = std::make_unique<test::FakeMetricReportQueue>(); - peripheral_queue_ptr_ = peripheral_queue.get(); - auto user_event_queue = std::make_unique<test::FakeMetricReportQueue>(); - user_event_queue_ptr_ = user_event_queue.get(); - - mock_delegate_ = std::make_unique<::testing::NiceMock<MockDelegate>>(); - - ON_CALL(*mock_delegate_, CreateMetricReportQueue(EventType::kDevice, - Destination::INFO_METRIC, - Priority::SLOW_BATCH)) - .WillByDefault(Return(ByMove(std::move(info_queue)))); - ON_CALL(*mock_delegate_, CreateMetricReportQueue(EventType::kDevice, - Destination::EVENT_METRIC, - Priority::SLOW_BATCH)) - .WillByDefault(Return(ByMove(std::move(event_queue)))); - ON_CALL(*mock_delegate_, - CreatePeriodicUploadReportQueue( - EventType::kDevice, Destination::TELEMETRY_METRIC, - Priority::MANUAL_BATCH, _, ::ash::kReportUploadFrequency, _, - /*rate_unit_to_ms=*/1)) + ON_CALL(*mock_delegate_, CreatePeriodicUploadReportQueue) .WillByDefault(Return(ByMove(std::move(telemetry_queue)))); - ON_CALL( - *mock_delegate_, - CreateMetricReportQueue(EventType::kUser, Destination::TELEMETRY_METRIC, - Priority::MANUAL_BATCH)) - .WillByDefault(Return(ByMove(std::move(user_telemetry_queue)))); - ON_CALL(*mock_delegate_, - CreateMetricReportQueue(EventType::kUser, - Destination::PERIPHERAL_EVENTS, - Priority::SECURITY)) - .WillByDefault(Return(ByMove(std::move(peripheral_queue)))); - ON_CALL(*mock_delegate_, - CreateMetricReportQueue(EventType::kUser, Destination::EVENT_METRIC, - Priority::SLOW_BATCH)) - .WillByDefault(Return(ByMove(std::move(user_event_queue)))); } base::test::SingleThreadTaskEnvironment task_environment_{ @@ -272,7 +280,6 @@ TEST_F(MetricReportingManagerTest, InitiallyDeprovisioned) { auto fake_reporting_settings = std::make_unique<test::FakeReportingSettings>(); - const auto init_delay = mock_delegate_->GetInitDelay(); int one_shot_collector_count = 0; int periodic_collector_count = 0; int periodic_event_collector_count = 0; @@ -295,8 +302,6 @@ auto metric_reporting_manager = MetricReportingManager::CreateForTesting( std::move(mock_delegate_), nullptr); - task_environment_.FastForwardBy(init_delay); - EXPECT_EQ(one_shot_collector_count, 0); EXPECT_EQ(periodic_collector_count, 0); EXPECT_EQ(periodic_event_collector_count, 0); @@ -304,8 +309,6 @@ metric_reporting_manager->OnLogin(nullptr); - task_environment_.FastForwardBy(init_delay); - EXPECT_EQ(one_shot_collector_count, 0); EXPECT_EQ(periodic_collector_count, 0); EXPECT_EQ(periodic_event_collector_count, 0); @@ -316,12 +319,14 @@ TEST_P(MetricReportingManagerInfoTest, Default) { const MetricReportingManagerTestCase& test_case = GetParam(); + const base::TimeDelta init_delay = test_case.has_init_delay + ? metrics::InitDelayParam::Get() + : base::TimeDelta(); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures(test_case.enabled_features, test_case.disabled_features); - const auto init_delay = mock_delegate_->GetInitDelay(); auto* const mock_delegate_ptr = mock_delegate_.get(); int collector_count = 0; ON_CALL(*mock_delegate_ptr, IsAffiliated) @@ -329,23 +334,17 @@ ON_CALL(*mock_delegate_ptr, CreateOneShotCollector( _, info_queue_ptr_, _, test_case.setting_data.enable_setting_path, - test_case.setting_data.setting_enabled_default_value)) + test_case.setting_data.setting_enabled_default_value, init_delay)) .WillByDefault( [&]() { return std::make_unique<FakeCollector>(&collector_count); }); auto metric_reporting_manager = MetricReportingManager::CreateForTesting( std::move(mock_delegate_), nullptr); - EXPECT_EQ(collector_count, 0); - - task_environment_.FastForwardBy(init_delay); - EXPECT_EQ(collector_count, test_case.expected_count_before_login); metric_reporting_manager->OnLogin(nullptr); - task_environment_.FastForwardBy(init_delay); - EXPECT_EQ(collector_count, test_case.expected_count_after_login); ON_CALL(*mock_delegate_ptr, IsDeprovisioned).WillByDefault(Return(true)); @@ -362,30 +361,33 @@ /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/false, network_info_settings, + /*has_init_delay=*/true, /*expected_count_before_login=*/1, /*expected_count_after_login=*/1}, {"CpuInfo", /*enabled_features=*/{}, /*disabled_features=*/{}, - /*is_affiliated=*/false, cpu_info_settings, + /*is_affiliated=*/false, cpu_info_settings, /*has_init_delay=*/true, /*expected_count_before_login=*/1, /*expected_count_after_login=*/1}, {"MemoryInfo", /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/false, memory_info_settings, + /*has_init_delay=*/true, /*expected_count_before_login=*/1, /*expected_count_after_login=*/1}, {"BusInfo", /*enabled_features=*/{}, /*disabled_features=*/{}, - /*is_affiliated=*/true, bus_info_settings, + /*is_affiliated=*/true, bus_info_settings, /*has_init_delay=*/true, /*expected_count_before_login=*/1, /*expected_count_after_login=*/1}, {"GraphicsInfo", /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/true, graphics_info_settings, + /*has_init_delay=*/true, /*expected_count_before_login=*/2, /*expected_count_after_login=*/2}}), [](const testing::TestParamInfo<MetricReportingManagerInfoTest::ParamType>& @@ -395,6 +397,9 @@ TEST_P(MetricReportingManagerEventTest, Default) { const MetricReportingManagerTestCase& test_case = GetParam(); + const base::TimeDelta init_delay = test_case.has_init_delay + ? metrics::InitDelayParam::Get() + : base::TimeDelta(); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures(test_case.enabled_features, @@ -402,7 +407,6 @@ auto fake_reporting_settings = std::make_unique<test::FakeReportingSettings>(); - const auto init_delay = mock_delegate_->GetInitDelay(); auto* const mock_delegate_ptr = mock_delegate_.get(); int observer_manager_count = 0; ON_CALL(*mock_delegate_ptr, IsAffiliated) @@ -411,16 +415,17 @@ *mock_delegate_ptr, CreateEventObserverManager( _, event_queue_ptr_, _, test_case.setting_data.enable_setting_path, - test_case.setting_data.setting_enabled_default_value, _)) + test_case.setting_data.setting_enabled_default_value, _, init_delay)) .WillByDefault([&]() { return std::make_unique<FakeMetricEventObserverManager>( fake_reporting_settings.get(), &observer_manager_count); }); - ON_CALL(*mock_delegate_ptr, - CreateEventObserverManager( - _, user_event_queue_ptr_, _, - test_case.setting_data.enable_setting_path, - test_case.setting_data.setting_enabled_default_value, _)) + ON_CALL( + *mock_delegate_ptr, + CreateEventObserverManager( + _, user_event_queue_ptr_, _, + test_case.setting_data.enable_setting_path, + test_case.setting_data.setting_enabled_default_value, _, init_delay)) .WillByDefault([&]() { return std::make_unique<FakeMetricEventObserverManager>( fake_reporting_settings.get(), &observer_manager_count); @@ -435,10 +440,6 @@ EXPECT_EQ(observer_manager_count, test_case.expected_count_after_login); - task_environment_.FastForwardBy(init_delay); - - EXPECT_EQ(observer_manager_count, test_case.expected_count_after_login_delay); - ON_CALL(*mock_delegate_ptr, IsDeprovisioned).WillByDefault(Return(true)); metric_reporting_manager->DeviceSettingsUpdated(); @@ -448,64 +449,70 @@ INSTANTIATE_TEST_SUITE_P( MetricReportingManagerEventTests, MetricReportingManagerEventTest, - ::testing::ValuesIn<MetricReportingManagerTestCase>({ - {"NetworkEvent_Unaffiliated", - /*enabled_features=*/{}, - /*disabled_features=*/{}, - /*is_affiliated=*/false, network_event_settings, - /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, - /*expected_count_after_login_delay=*/0}, - {"NetworkEvent_Default", - /*enabled_features=*/{}, - /*disabled_features=*/{}, - /*is_affiliated=*/true, network_event_settings, - /*expected_count_before_login=*/0, - /*expected_count_after_login=*/1, - /*expected_count_after_login_delay=*/2}, - {"AudioEvent_Unaffiliated", - /*enabled_features=*/{}, - /*disabled_features=*/{}, - /*is_affiliated=*/false, audio_metric_settings, - /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, - /*expected_count_after_login_delay=*/0}, - {"AudioEvent_Default", - /*enabled_features=*/{}, - /*disabled_features=*/{}, - /*is_affiliated=*/true, audio_metric_settings, - /*expected_count_before_login=*/0, - /*expected_count_after_login=*/1, - /*expected_count_after_login_delay=*/1}, - {"AppEvents_Unaffiliated", - /*enabled_features=*/{}, - /*disabled_features=*/{}, - /*is_affiliated=*/false, app_event_settings, - /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, - /*expected_count_after_login_delay=*/0}, - {"AppEvents_Default", - /*enabled_features=*/{}, - /*disabled_features=*/{}, - /*is_affiliated=*/true, app_event_settings, - /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, - /*expected_count_after_login_delay=*/0}, - {"AppEvents_FeatureFlagEnabled", - /*enabled_features=*/{kEnableAppMetricsReporting}, - /*disabled_features=*/{}, - /*is_affiliated=*/true, app_event_settings, - /*expected_count_before_login=*/0, - /*expected_count_after_login=*/1, - /*expected_count_after_login_delay=*/1}, - {"AppEvents_FeatureFlagDisabled", - /*enabled_features=*/{}, - /*disabled_features=*/{kEnableAppMetricsReporting}, - /*is_affiliated=*/true, app_event_settings, - /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, - /*expected_count_after_login_delay=*/0}, - }), + ::testing::ValuesIn<MetricReportingManagerTestCase>( + {{"NetworkEvent_Unaffiliated", + /*enabled_features=*/{}, + /*disabled_features=*/{}, + /*is_affiliated=*/false, network_event_settings, + /*has_init_delay=*/false, + /*expected_count_before_login=*/0, + /*expected_count_after_login=*/0}, + {"NetworkEvent_Default", + /*enabled_features=*/{}, + /*disabled_features=*/{}, + /*is_affiliated=*/true, network_event_settings, + /*has_init_delay=*/false, + /*expected_count_before_login=*/0, + /*expected_count_after_login=*/1}, + {"HttpsLatencyEvent_Default", + /*enabled_features=*/{}, + /*disabled_features=*/{}, + /*is_affiliated=*/true, network_event_settings, + /*has_init_delay=*/true, + /*expected_count_before_login=*/0, + /*expected_count_after_login=*/1}, + {"AudioEvent_Unaffiliated", + /*enabled_features=*/{}, + /*disabled_features=*/{}, + /*is_affiliated=*/false, audio_metric_settings, + /*has_init_delay=*/false, + /*expected_count_before_login=*/0, + /*expected_count_after_login=*/0}, + {"AudioEvent_Default", + /*enabled_features=*/{}, + /*disabled_features=*/{}, + /*is_affiliated=*/true, audio_metric_settings, + /*has_init_delay=*/false, + /*expected_count_before_login=*/0, + /*expected_count_after_login=*/1}, + {"AppEvents_Unaffiliated", + /*enabled_features=*/{}, + /*disabled_features=*/{}, + /*is_affiliated=*/false, app_event_settings, + /*has_init_delay=*/false, + /*expected_count_before_login=*/0, + /*expected_count_after_login=*/0}, + {"AppEvents_Default", + /*enabled_features=*/{}, + /*disabled_features=*/{}, + /*is_affiliated=*/true, app_event_settings, + /*has_init_delay=*/false, + /*expected_count_before_login=*/0, + /*expected_count_after_login=*/0}, + {"AppEvents_FeatureFlagEnabled", + /*enabled_features=*/{kEnableAppMetricsReporting}, + /*disabled_features=*/{}, + /*is_affiliated=*/true, app_event_settings, + /*has_init_delay=*/false, + /*expected_count_before_login=*/0, + /*expected_count_after_login=*/1}, + {"AppEvents_FeatureFlagDisabled", + /*enabled_features=*/{}, + /*disabled_features=*/{kEnableAppMetricsReporting}, + /*is_affiliated=*/true, app_event_settings, + /*has_init_delay=*/false, + /*expected_count_before_login=*/0, + /*expected_count_after_login=*/0}}), [](const testing::TestParamInfo<MetricReportingManagerInfoTest::ParamType>& info) { return info.param.test_name; }); @@ -516,6 +523,9 @@ // queue. TEST_P(MetricReportingManagerPeripheralTest, Default) { const MetricReportingManagerTestCase& test_case = GetParam(); + const base::TimeDelta init_delay = test_case.has_init_delay + ? metrics::InitDelayParam::Get() + : base::TimeDelta(); auto fake_reporting_settings = std::make_unique<test::FakeReportingSettings>(); @@ -523,11 +533,12 @@ int observer_manager_count = 0; ON_CALL(*mock_delegate_ptr, IsAffiliated) .WillByDefault(Return(test_case.is_affiliated)); - ON_CALL(*mock_delegate_ptr, - CreateEventObserverManager( - _, peripheral_queue_ptr_, _, - test_case.setting_data.enable_setting_path, - test_case.setting_data.setting_enabled_default_value, _)) + ON_CALL( + *mock_delegate_ptr, + CreateEventObserverManager( + _, peripheral_queue_ptr_, _, + test_case.setting_data.enable_setting_path, + test_case.setting_data.setting_enabled_default_value, _, init_delay)) .WillByDefault([&]() { return std::make_unique<FakeMetricEventObserverManager>( fake_reporting_settings.get(), &observer_manager_count); @@ -556,12 +567,14 @@ /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/false, peripheral_metric_settings, + /*has_init_delay=*/false, /*expected_count_before_login=*/0, /*expected_count_after_login=*/0}, {"PeripheralEvent_Default", /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/true, peripheral_metric_settings, + /*has_init_delay=*/false, /*expected_count_before_login=*/0, /*expected_count_after_login=*/1}}), [](const testing::TestParamInfo<MetricReportingManagerInfoTest::ParamType>& @@ -571,27 +584,24 @@ }; TEST_F(MetricReportingManagerTelemetryTest, OneShotCollectorBootPerformance) { - const auto init_delay = mock_delegate_->GetInitDelay(); const auto upload_delay = mock_delegate_->GetInitialUploadDelay(); auto* const mock_delegate_ptr = mock_delegate_.get(); int collector_count = 0; ON_CALL(*mock_delegate_ptr, CreateOneShotCollector(_, telemetry_queue_ptr_, _, - ::ash::kReportDeviceBootMode, true)) + ::ash::kReportDeviceBootMode, true, + metrics::InitDelayParam::Get())) .WillByDefault( [&]() { return std::make_unique<FakeCollector>(&collector_count); }); auto metric_reporting_manager = MetricReportingManager::CreateForTesting( std::move(mock_delegate_), nullptr); - EXPECT_EQ(collector_count, 0); - - task_environment_.FastForwardBy(init_delay); - EXPECT_EQ(collector_count, 1); - task_environment_.FastForwardBy(upload_delay); + task_environment_.FastForwardBy(upload_delay + + metrics::InitDelayParam::Get()); EXPECT_EQ(telemetry_queue_ptr_->GetNumFlush(), 1); @@ -603,12 +613,14 @@ TEST_P(MetricReportingManagerTelemetryTest, Default) { const MetricReportingManagerTestCase& test_case = GetParam(); + const base::TimeDelta init_delay = test_case.has_init_delay + ? metrics::InitDelayParam::Get() + : base::TimeDelta(); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures(test_case.enabled_features, test_case.disabled_features); - const auto init_delay = mock_delegate_->GetInitDelay(); const auto upload_delay = mock_delegate_->GetInitialUploadDelay(); auto* const mock_delegate_ptr = mock_delegate_.get(); int collector_count = 0; @@ -620,7 +632,7 @@ test_case.setting_data.enable_setting_path, test_case.setting_data.setting_enabled_default_value, test_case.setting_data.rate_setting_path, _, - test_case.setting_data.rate_unit_to_ms)) + test_case.setting_data.rate_unit_to_ms, init_delay)) .WillByDefault( [&]() { return std::make_unique<FakeCollector>(&collector_count); }); ON_CALL(*mock_delegate_ptr, @@ -629,18 +641,17 @@ test_case.setting_data.enable_setting_path, test_case.setting_data.setting_enabled_default_value, test_case.setting_data.rate_setting_path, _, - test_case.setting_data.rate_unit_to_ms)) + test_case.setting_data.rate_unit_to_ms, init_delay)) .WillByDefault( [&]() { return std::make_unique<FakeCollector>(&collector_count); }); auto metric_reporting_manager = MetricReportingManager::CreateForTesting( std::move(mock_delegate_), nullptr); - task_environment_.FastForwardBy(init_delay); - EXPECT_EQ(collector_count, test_case.expected_count_before_login); - task_environment_.FastForwardBy(upload_delay); + task_environment_.FastForwardBy(upload_delay + + metrics::InitDelayParam::Get()); EXPECT_EQ(telemetry_queue_ptr_->GetNumFlush(), 1); @@ -648,12 +659,9 @@ EXPECT_EQ(collector_count, test_case.expected_count_after_login); - task_environment_.FastForwardBy(init_delay); - - EXPECT_EQ(collector_count, test_case.expected_count_after_login_delay); - const int expected_login_flush_count = test_case.is_affiliated ? 1 : 0; - task_environment_.FastForwardBy(upload_delay); + task_environment_.FastForwardBy(upload_delay + + metrics::InitDelayParam::Get()); EXPECT_EQ(telemetry_queue_ptr_->GetNumFlush(), 1 + expected_login_flush_count); @@ -671,79 +679,118 @@ {{"NetworkTelemetry_Unaffiliated", /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/false, network_telemetry_settings, + /*has_init_delay=*/true, /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, - /*expected_count_after_login_delay=*/0}, + /*expected_count_after_login=*/0}, {"NetworkTelemetry_Default", /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/true, network_telemetry_settings, + /*has_init_delay=*/true, /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, // 3 collectors should be created after login, network telemetry, // https latency, and network bandwidth. - /*expected_count_after_login_delay=*/3}, + /*expected_count_after_login=*/3}, {"AudioTelemetry_Unaffiliated", /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/false, audio_metric_settings, + /*has_init_delay=*/true, /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, - /*expected_count_after_login_delay=*/0}, + /*expected_count_after_login=*/0}, {"AudioTelemetry_Default", /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/true, audio_metric_settings, + /*has_init_delay=*/true, /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, - /*expected_count_after_login_delay=*/1}, + /*expected_count_after_login=*/1}, {"DisplaysTelemetry_Unaffiliated", /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/false, displays_telemetry_settings, + /*has_init_delay=*/true, /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, - /*expected_count_after_login_delay=*/0}, + /*expected_count_after_login=*/0}, {"DisplaysTelemetry_Default", /*enabled_features=*/{}, /*disabled_features=*/{}, /*is_affiliated=*/true, displays_telemetry_settings, + /*has_init_delay=*/true, /*expected_count_before_login=*/0, - /*expected_count_after_login=*/0, - /*expected_count_after_login_delay=*/1}}), + /*expected_count_after_login=*/1}}), [](const testing::TestParamInfo< MetricReportingManagerTelemetryTest::ParamType>& info) { return info.param.test_name; }); -struct EventDrivenTelemetrySamplerPoolTestCase { +struct EventDrivenTelemetryCollectorPoolTestCase { std::string test_name; MetricEventType event_type; std::string setting_name; }; -class EventDrivenTelemetrySamplerPoolTest - : public ::testing::TestWithParam<EventDrivenTelemetrySamplerPoolTestCase> { +class EventDrivenTelemetryCollectorPoolTest + : public ::testing::TestWithParam< + EventDrivenTelemetryCollectorPoolTestCase> { protected: void SetUp() override { + auto https_latency_collector = std::make_unique<FakeCollector>(); + https_latency_collector_ptr_ = https_latency_collector.get(); + auto network_telemetry_collector = std::make_unique<FakeCollector>(); + network_telemetry_collector_ptr_ = network_telemetry_collector.get(); + auto https_latency_sampler = std::make_unique<test::FakeSampler>(); - https_latency_sampler_ptr_ = https_latency_sampler.get(); + auto* const https_latency_sampler_ptr = https_latency_sampler.get(); auto network_telemetry_sampler = std::make_unique<test::FakeSampler>(); - network_telemetry_sampler_ptr_ = network_telemetry_sampler.get(); + auto* const network_telemetry_sampler_ptr = network_telemetry_sampler.get(); mock_delegate_ = std::make_unique<::testing::NiceMock<MockDelegate>>(); + + // Info queue. + CreateMockMetricReportQueueHelper(mock_delegate_.get(), EventType::kDevice, + Destination::INFO_METRIC, + Priority::SLOW_BATCH); + // Event queue. + CreateMockMetricReportQueueHelper(mock_delegate_.get(), EventType::kDevice, + Destination::EVENT_METRIC, + Priority::SLOW_BATCH); + // User telemetry queue. + CreateMockMetricReportQueueHelper(mock_delegate_.get(), EventType::kUser, + Destination::TELEMETRY_METRIC, + Priority::MANUAL_BATCH); + // Peripherals queue. + CreateMockMetricReportQueueHelper(mock_delegate_.get(), EventType::kUser, + Destination::PERIPHERAL_EVENTS, + Priority::SECURITY); + // User event queue. + CreateMockMetricReportQueueHelper(mock_delegate_.get(), EventType::kUser, + Destination::EVENT_METRIC, + Priority::SLOW_BATCH); + // Telemetry queue. + ON_CALL(*mock_delegate_, CreatePeriodicUploadReportQueue) + .WillByDefault( + Return(ByMove(std::make_unique<test::FakeMetricReportQueue>()))); + ON_CALL(*mock_delegate_, GetHttpsLatencySampler) .WillByDefault(Return(ByMove(std::move(https_latency_sampler)))); ON_CALL(*mock_delegate_, GetNetworkTelemetrySampler) .WillByDefault(Return(ByMove(std::move(network_telemetry_sampler)))); + ON_CALL(*mock_delegate_, + CreatePeriodicCollector(network_telemetry_sampler_ptr, _, _, _, _, + _, _, _, _)) + .WillByDefault(Return(ByMove(std::move(network_telemetry_collector)))); + ON_CALL(*mock_delegate_, CreatePeriodicCollector(https_latency_sampler_ptr, + _, _, _, _, _, _, _, _)) + .WillByDefault(Return(ByMove(std::move(https_latency_collector)))); } base::test::SingleThreadTaskEnvironment task_environment_; - Sampler* https_latency_sampler_ptr_; - Sampler* network_telemetry_sampler_ptr_; + raw_ptr<CollectorBase> https_latency_collector_ptr_; + raw_ptr<CollectorBase> network_telemetry_collector_ptr_; std::unique_ptr<::testing::NiceMock<MockDelegate>> mock_delegate_; }; -TEST_P(EventDrivenTelemetrySamplerPoolTest, +TEST_P(EventDrivenTelemetryCollectorPoolTest, SettingBasedTelemetry_AffiliatedOnly) { - EventDrivenTelemetrySamplerPoolTestCase test_case = GetParam(); + EventDrivenTelemetryCollectorPoolTestCase test_case = GetParam(); ash::ScopedTestingCrosSettings cros_settings; base::Value::List telemetry_list; @@ -762,36 +809,31 @@ auto metric_reporting_manager = MetricReportingManager::CreateForTesting( std::move(mock_delegate_), nullptr); - std::vector<ConfiguredSampler*> event_telemetry = - metric_reporting_manager->GetTelemetrySamplers(test_case.event_type); + std::vector<CollectorBase*> event_telemetry = + metric_reporting_manager->GetTelemetryCollectors(test_case.event_type); ASSERT_TRUE(event_telemetry.empty()); metric_reporting_manager->OnLogin(nullptr); event_telemetry = - metric_reporting_manager->GetTelemetrySamplers(test_case.event_type); + metric_reporting_manager->GetTelemetryCollectors(test_case.event_type); ASSERT_THAT(event_telemetry, SizeIs(2)); - EXPECT_THAT(event_telemetry[0]->GetSampler(), - Eq(network_telemetry_sampler_ptr_)); - EXPECT_THAT(event_telemetry[0]->GetEnableSettingPath(), - StrEq(ash::kReportDeviceNetworkStatus)); - EXPECT_THAT(event_telemetry[1]->GetSampler(), Eq(https_latency_sampler_ptr_)); - EXPECT_THAT(event_telemetry[1]->GetEnableSettingPath(), - StrEq(ash::kReportDeviceNetworkStatus)); + EXPECT_THAT(event_telemetry[0], Eq(network_telemetry_collector_ptr_)); + EXPECT_THAT(event_telemetry[1], Eq(https_latency_collector_ptr_)); } INSTANTIATE_TEST_SUITE_P( - EventDrivenTelemetrySamplerPoolTests, - EventDrivenTelemetrySamplerPoolTest, - ::testing::ValuesIn<EventDrivenTelemetrySamplerPoolTestCase>( + EventDrivenTelemetryCollectorPoolTests, + EventDrivenTelemetryCollectorPoolTest, + ::testing::ValuesIn<EventDrivenTelemetryCollectorPoolTestCase>( {{"SignalStrengthLow", MetricEventType::NETWORK_SIGNAL_STRENGTH_LOW, ash::kReportDeviceSignalStrengthEventDrivenTelemetry}, {"SignalStrengthRecovered", MetricEventType::NETWORK_SIGNAL_STRENGTH_RECOVERED, ash::kReportDeviceSignalStrengthEventDrivenTelemetry}}), [](const testing::TestParamInfo< - EventDrivenTelemetrySamplerPoolTest::ParamType>& info) { + EventDrivenTelemetryCollectorPoolTest::ParamType>& info) { return info.param.test_name; });
diff --git a/chrome/browser/ash/power/auto_screen_brightness/als_file_reader.cc b/chrome/browser/ash/power/auto_screen_brightness/als_file_reader.cc index ea6e7f5..68edcbd 100644 --- a/chrome/browser/ash/power/auto_screen_brightness/als_file_reader.cc +++ b/chrome/browser/ash/power/auto_screen_brightness/als_file_reader.cc
@@ -13,7 +13,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" -#include "base/task/task_runner_util.h" #include "base/time/time.h" #include "chrome/browser/ash/power/auto_screen_brightness/utils.h" #include "content/public/browser/browser_thread.h" @@ -125,17 +124,16 @@ void AlsFileReader::RetryAlsPath() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, base::BindOnce(&GetAlsPath), + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetAlsPath), base::BindOnce(&AlsFileReader::OnAlsPathReadAttempted, weak_ptr_factory_.GetWeakPtr())); } void AlsFileReader::ReadAlsPeriodically() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, - base::BindOnce(&ReadAlsFromFile, ambient_light_path_), + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadAlsFromFile, ambient_light_path_), base::BindOnce(&AlsFileReader::OnAlsRead, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/ash/power/auto_screen_brightness/als_reader.cc b/chrome/browser/ash/power/auto_screen_brightness/als_reader.cc index efef740d..65116898 100644 --- a/chrome/browser/ash/power/auto_screen_brightness/als_reader.cc +++ b/chrome/browser/ash/power/auto_screen_brightness/als_reader.cc
@@ -13,7 +13,6 @@ #include "base/process/launch.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "chromeos/components/sensors/buildflags.h" #if BUILDFLAG(USE_IIOSERVICE) @@ -75,8 +74,8 @@ {base::TaskPriority::BEST_EFFORT, base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, base::BindOnce(&GetNumAls), + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetNumAls), base::BindOnce(&AlsReader::OnNumAlsRetrieved, weak_ptr_factory_.GetWeakPtr())); #endif // BUILDFLAG(USE_IIOSERVICE)
diff --git a/chrome/browser/ash/power/auto_screen_brightness/model_config_loader_impl.cc b/chrome/browser/ash/power/auto_screen_brightness/model_config_loader_impl.cc index 4ee98493..f4ac7b3 100644 --- a/chrome/browser/ash/power/auto_screen_brightness/model_config_loader_impl.cc +++ b/chrome/browser/ash/power/auto_screen_brightness/model_config_loader_impl.cc
@@ -17,7 +17,6 @@ #include "base/metrics/field_trial_params.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/values.h" #include "content/public/browser/browser_thread.h" @@ -173,8 +172,8 @@ void ModelConfigLoaderImpl::Init(const base::FilePath& model_params_path) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadModelParamsFromDisk, model_params_path, is_testing_), base::BindOnce(&ModelConfigLoaderImpl::OnModelParamsLoadedFromDisk, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chrome/browser/ash/power/auto_screen_brightness/modeller_impl.cc b/chrome/browser/ash/power/auto_screen_brightness/modeller_impl.cc index 2227b23..7913dc97 100644 --- a/chrome/browser/ash/power/auto_screen_brightness/modeller_impl.cc +++ b/chrome/browser/ash/power/auto_screen_brightness/modeller_impl.cc
@@ -19,7 +19,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/default_tick_clock.h" #include "base/time/time.h" @@ -402,8 +401,8 @@ user_activity_observation_.Observe(user_activity_detector); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ModellerImpl::GetModelSavingSpecFromProfilePath, profile->GetPath()), base::BindOnce(&ModellerImpl::OnModelSavingSpecReadFromProfile, @@ -468,8 +467,8 @@ return; } - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadModelFromDisk, *model_saving_spec_, is_testing_), base::BindOnce(&ModellerImpl::OnModelLoadedFromDisk, weak_ptr_factory_.GetWeakPtr())); @@ -547,8 +546,8 @@ DCHECK(model_.global_curve); // Run SetInitialCurves calculations on background thread to avoid blocking UI // thread. - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &SetInitialCurves, trainer_.get(), *model_.global_curve, model_.personal_curve ? *model_.personal_curve : *model_.global_curve, @@ -626,8 +625,8 @@ } training_start_ = tick_clock_->NowTicks(); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&TrainModel, trainer_.get(), std::move(data_cache_), is_testing_), base::BindOnce(&ModellerImpl::OnTrainingFinished, @@ -661,8 +660,8 @@ (export_personal_curve ? "NewCurve" : "NoNewCurve"); base::UmaHistogramTimes(histogram_name, now - training_start_.value()); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SaveModelToDisk, *model_saving_spec_, model_, global_curve_reset_, export_personal_curve, is_testing_), base::BindOnce(&ModellerImpl::OnModelSavedToDisk,
diff --git a/chrome/browser/ash/power/process_data_collector.cc b/chrome/browser/ash/power/process_data_collector.cc index 04a472a..a72b705 100644 --- a/chrome/browser/ash/power/process_data_collector.cc +++ b/chrome/browser/ash/power/process_data_collector.cc
@@ -31,7 +31,6 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/platform_thread.h" #include "base/threading/scoped_blocking_call.h" @@ -363,8 +362,8 @@ } void ProcessDataCollector::SampleCpuUsage() { - base::PostTaskAndReplyWithResult( - cpu_data_task_runner_.get(), FROM_HERE, + cpu_data_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ProcessDataCollector::ComputeSampleAsync, config_, prev_samples_, curr_samples_, curr_summary_), base::BindOnce(&ProcessDataCollector::SaveSamplesOnUIThread,
diff --git a/chrome/browser/ash/power/smart_charging/smart_charging_manager.cc b/chrome/browser/ash/power/smart_charging/smart_charging_manager.cc index dff4edd..b4d94e09 100644 --- a/chrome/browser/ash/power/smart_charging/smart_charging_manager.cc +++ b/chrome/browser/ash/power/smart_charging/smart_charging_manager.cc
@@ -12,7 +12,6 @@ #include "base/files/important_file_writer.h" #include "base/location.h" #include "base/metrics/histogram_macros.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" @@ -539,9 +538,8 @@ void SmartChargingManager::MaybeLoadFromDisk( const base::FilePath& profile_path) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, - base::BindOnce(&LoadFromDisk, profile_path), + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadFromDisk, profile_path), base::BindOnce(&SmartChargingManager::OnLoadProtoFromDiskComplete, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/ash/printing/bulk_printers_calculator.cc b/chrome/browser/ash/printing/bulk_printers_calculator.cc index b9fe283d..500a00cc81 100644 --- a/chrome/browser/ash/printing/bulk_printers_calculator.cc +++ b/chrome/browser/ash/printing/bulk_printers_calculator.cc
@@ -16,7 +16,6 @@ #include "base/observer_list.h" #include "base/sequence_checker.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/values.h" @@ -263,8 +262,8 @@ data_is_set_ = true; TaskData task_data = std::make_unique<TaskDataInternal>(++last_received_task_); - base::PostTaskAndReplyWithResult( - restrictions_runner_.get(), FROM_HERE, + restrictions_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Restrictions::SetData, restrictions_, std::move(task_data), std::move(data)), base::BindOnce(&BulkPrintersCalculatorImpl::OnComputationComplete, @@ -275,8 +274,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); TaskData task_data = std::make_unique<TaskDataInternal>(++last_received_task_); - base::PostTaskAndReplyWithResult( - restrictions_runner_.get(), FROM_HERE, + restrictions_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Restrictions::UpdateAccessMode, restrictions_, std::move(task_data), mode), base::BindOnce(&BulkPrintersCalculatorImpl::OnComputationComplete, @@ -287,8 +286,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); TaskData task_data = std::make_unique<TaskDataInternal>(++last_received_task_); - base::PostTaskAndReplyWithResult( - restrictions_runner_.get(), FROM_HERE, + restrictions_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Restrictions::UpdateBlocklist, restrictions_, std::move(task_data), blocklist), base::BindOnce(&BulkPrintersCalculatorImpl::OnComputationComplete, @@ -299,8 +298,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); TaskData task_data = std::make_unique<TaskDataInternal>(++last_received_task_); - base::PostTaskAndReplyWithResult( - restrictions_runner_.get(), FROM_HERE, + restrictions_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Restrictions::UpdateAllowlist, restrictions_, std::move(task_data), allowlist), base::BindOnce(&BulkPrintersCalculatorImpl::OnComputationComplete,
diff --git a/chrome/browser/ash/printing/print_servers_provider.cc b/chrome/browser/ash/printing/print_servers_provider.cc index 3ccbb3da..c76d1ac 100644 --- a/chrome/browser/ash/printing/print_servers_provider.cc +++ b/chrome/browser/ash/printing/print_servers_provider.cc
@@ -14,7 +14,6 @@ #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/values.h" @@ -214,8 +213,8 @@ void SetData(std::unique_ptr<std::string> data) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); const bool previously_completed = IsCompleted(); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ParseData, ++last_received_task_, std::move(data)), base::BindOnce(&PrintServersProviderImpl::OnComputationComplete, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chrome/browser/ash/scanning/scan_service.cc b/chrome/browser/ash/scanning/scan_service.cc index 6a92870..1c6a284 100644 --- a/chrome/browser/ash/scanning/scan_service.cc +++ b/chrome/browser/ash/scanning/scan_service.cc
@@ -23,7 +23,6 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/time/time.h" @@ -496,8 +495,8 @@ return; } - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SavePage, scan_to_path, file_type, std::move(scanned_image), page_number, start_time_), base::BindOnce(&ScanService::OnPageSaved, @@ -510,8 +509,8 @@ if (failure_mode == lorgnette::SCAN_FAILURE_MODE_NO_FAILURE && !scanned_images_.empty()) { DCHECK(!scanned_file_paths_.empty()); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SaveAsPdf, scanned_images_, scanned_file_paths_.back(), rotate_alternate_pages_, is_multi_page_scan, scan_dpi_), base::BindOnce(&ScanService::OnPdfSaved, @@ -520,8 +519,8 @@ // Post a task to the task runner to ensure all the pages have been saved // before reporting the scan job as complete. - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( [](lorgnette::ScanFailureMode failure_mode) { return failure_mode; }, failure_mode),
diff --git a/chrome/browser/ash/tpm_firmware_update.cc b/chrome/browser/ash/tpm_firmware_update.cc index 36e21b1..fbe916a 100644 --- a/chrome/browser/ash/tpm_firmware_update.cc +++ b/chrome/browser/ash/tpm_firmware_update.cc
@@ -16,7 +16,6 @@ #include "base/memory/weak_ptr.h" #include "base/path_service.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/values.h" #include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h" @@ -199,13 +198,13 @@ // this function terminates. Thus, the final check needs to run independent // of |this| and takes |callback_| ownership. if (callback_) { - base::PostTaskAndReplyWithResult(background_task_runner_.get(), FROM_HERE, - base::BindOnce([]() { - Status status; - CheckAvailabilityStatus(&status); - return status; - }), - std::move(callback_)); + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce([]() { + Status status; + CheckAvailabilityStatus(&status); + return status; + }), + std::move(callback_)); } }
diff --git a/chrome/browser/ash/video_conference/BUILD.gn b/chrome/browser/ash/video_conference/BUILD.gn index b46875a..9bfa9ad 100644 --- a/chrome/browser/ash/video_conference/BUILD.gn +++ b/chrome/browser/ash/video_conference/BUILD.gn
@@ -12,7 +12,6 @@ "video_conference_client_wrapper.h", "video_conference_manager_ash.cc", "video_conference_manager_ash.h", - "video_conference_state.h", "video_conference_tray_controller_impl.cc", "video_conference_tray_controller_impl.h", ] @@ -30,6 +29,7 @@ sources = [ "video_conference_manager_ash_unittest.cc" ] deps = [ ":video_conference", + "//ash", "//base", "//base/test:test_support", "//chromeos/crosapi/mojom",
diff --git a/chrome/browser/ash/video_conference/video_conference_client_wrapper.cc b/chrome/browser/ash/video_conference/video_conference_client_wrapper.cc index 92c5bcc1..c6afe39 100644 --- a/chrome/browser/ash/video_conference/video_conference_client_wrapper.cc +++ b/chrome/browser/ash/video_conference/video_conference_client_wrapper.cc
@@ -7,12 +7,12 @@ #include <cstdint> #include <utility> +#include "ash/system/video_conference/video_conference_media_state.h" #include "base/check.h" #include "base/functional/bind.h" #include "base/memory/raw_ptr.h" #include "base/unguessable_token.h" #include "chrome/browser/ash/video_conference/video_conference_manager_ash.h" -#include "chrome/browser/ash/video_conference/video_conference_state.h" #include "chromeos/crosapi/mojom/video_conference.mojom-shared.h" #include "chromeos/crosapi/mojom/video_conference.mojom.h" #include "mojo/public/cpp/bindings/pending_remote.h"
diff --git a/chrome/browser/ash/video_conference/video_conference_client_wrapper.h b/chrome/browser/ash/video_conference/video_conference_client_wrapper.h index 2c67e8e..77b3a20 100644 --- a/chrome/browser/ash/video_conference/video_conference_client_wrapper.h +++ b/chrome/browser/ash/video_conference/video_conference_client_wrapper.h
@@ -7,8 +7,8 @@ #include <cstdint> +#include "ash/system/video_conference/video_conference_media_state.h" #include "base/memory/raw_ptr.h" -#include "chrome/browser/ash/video_conference/video_conference_state.h" #include "chromeos/crosapi/mojom/video_conference.mojom.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h"
diff --git a/chrome/browser/ash/video_conference/video_conference_manager_ash.cc b/chrome/browser/ash/video_conference/video_conference_manager_ash.cc index d794b49..e778bf2 100644 --- a/chrome/browser/ash/video_conference/video_conference_manager_ash.cc +++ b/chrome/browser/ash/video_conference/video_conference_manager_ash.cc
@@ -9,13 +9,13 @@ #include <utility> #include <vector> +#include "ash/system/video_conference/video_conference_media_state.h" #include "base/barrier_callback.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/logging.h" #include "base/unguessable_token.h" #include "chrome/browser/ash/video_conference/video_conference_client_wrapper.h" -#include "chrome/browser/ash/video_conference/video_conference_state.h" #include "chromeos/crosapi/mojom/video_conference.mojom.h" #include "mojo/public/cpp/bindings/pending_remote.h"
diff --git a/chrome/browser/ash/video_conference/video_conference_manager_ash.h b/chrome/browser/ash/video_conference/video_conference_manager_ash.h index 095e8273..f250ca6 100644 --- a/chrome/browser/ash/video_conference/video_conference_manager_ash.h +++ b/chrome/browser/ash/video_conference/video_conference_manager_ash.h
@@ -11,7 +11,6 @@ #include <vector> #include "base/functional/callback.h" -#include "chrome/browser/ash/video_conference/video_conference_state.h" #include "chromeos/crosapi/mojom/video_conference.mojom.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver_set.h" @@ -23,6 +22,7 @@ namespace ash { class VideoConferenceClientWrapper; +struct VideoConferenceMediaState; // VideoConferenceManagerAsh is the central hub responsible for: // 1. Connecting VC clients to System UI components.
diff --git a/chrome/browser/ash/video_conference/video_conference_manager_ash_unittest.cc b/chrome/browser/ash/video_conference/video_conference_manager_ash_unittest.cc index 468d683d..36e478f 100644 --- a/chrome/browser/ash/video_conference/video_conference_manager_ash_unittest.cc +++ b/chrome/browser/ash/video_conference/video_conference_manager_ash_unittest.cc
@@ -8,12 +8,12 @@ #include <utility> #include <vector> +#include "ash/system/video_conference/video_conference_media_state.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/task_environment.h" #include "base/time/time.h" #include "base/unguessable_token.h" -#include "chrome/browser/ash/video_conference/video_conference_state.h" #include "chromeos/crosapi/mojom/video_conference.mojom.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl.cc b/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl.cc index 6b452a6..fba1f7dd 100644 --- a/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl.cc +++ b/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl.cc
@@ -81,6 +81,8 @@ base::BindRepeating( &PersonalizationAppAmbientProviderImpl::OnAnimationThemeChanged, base::Unretained(this))); + ambient_ui_model_observer_.Observe( + Shell::Get()->ambient_controller()->ambient_ui_model()); } PersonalizationAppAmbientProviderImpl:: @@ -576,4 +578,12 @@ Shell::Get()->ambient_controller()->StartScreenSaverPreview(); } +void PersonalizationAppAmbientProviderImpl::OnAmbientUiVisibilityChanged( + AmbientUiVisibility visibility) { + if (ambient_observer_remote_.is_bound() && + visibility == AmbientUiVisibility::kClosed) { + ambient_observer_remote_->OnScreenSaverClosed(); + } +} + } // namespace ash::personalization_app
diff --git a/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl.h b/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl.h index 5b39637d..52fd837 100644 --- a/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl.h +++ b/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl.h
@@ -5,8 +5,10 @@ #ifndef CHROME_BROWSER_ASH_WEB_APPLICATIONS_PERSONALIZATION_APP_PERSONALIZATION_APP_AMBIENT_PROVIDER_IMPL_H_ #define CHROME_BROWSER_ASH_WEB_APPLICATIONS_PERSONALIZATION_APP_PERSONALIZATION_APP_AMBIENT_PROVIDER_IMPL_H_ +#include "base/scoped_observation.h" + #include "ash/constants/ambient_animation_theme.h" -#include "ash/public/cpp/ambient/ambient_backend_controller.h" +#include "ash/public/cpp/ambient/ambient_ui_model.h" #include "ash/public/cpp/ambient/common/ambient_settings.h" #include "ash/webui/personalization_app/mojom/personalization_app.mojom.h" #include "ash/webui/personalization_app/personalization_app_ambient_provider.h" @@ -26,7 +28,8 @@ namespace ash::personalization_app { class PersonalizationAppAmbientProviderImpl - : public PersonalizationAppAmbientProvider { + : public PersonalizationAppAmbientProvider, + public AmbientUiModelObserver { public: explicit PersonalizationAppAmbientProviderImpl(content::WebUI* web_ui); @@ -41,6 +44,9 @@ mojo::PendingReceiver<ash::personalization_app::mojom::AmbientProvider> receiver) override; + // AmbientUiModelObserver: + void OnAmbientUiVisibilityChanged(AmbientUiVisibility visibility) override; + // ash::personalization_app::mojom:AmbientProvider: void IsAmbientModeEnabled(IsAmbientModeEnabledCallback callback) override; void SetAmbientObserver( @@ -101,7 +107,8 @@ void FetchGooglePhotosAlbumsPreviews( const std::vector<std::string>& album_ids); - void OnGooglePhotosAlbumsPreviewsFetched(const std::vector<GURL>& preview_urls); + void OnGooglePhotosAlbumsPreviewsFetched( + const std::vector<GURL>& preview_urls); ash::PersonalAlbum* FindPersonalAlbumById(const std::string& album_id); @@ -153,6 +160,9 @@ // A flag to record if the user has seen the ambient mode page. bool page_viewed_ = false; + base::ScopedObservation<AmbientUiModel, AmbientUiModelObserver> + ambient_ui_model_observer_{this}; + base::WeakPtrFactory<PersonalizationAppAmbientProviderImpl> write_weak_factory_{this}; base::WeakPtrFactory<PersonalizationAppAmbientProviderImpl>
diff --git a/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl_unittest.cc b/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl_unittest.cc index a968148c..3ebfc4d1 100644 --- a/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl_unittest.cc +++ b/chrome/browser/ash/web_applications/personalization_app/personalization_app_ambient_provider_impl_unittest.cc
@@ -6,12 +6,14 @@ #include <memory> #include <vector> - +#include "ash/ambient/ambient_controller.h" #include "ash/ambient/test/ambient_ash_test_helper.h" #include "ash/constants/ambient_animation_theme.h" #include "ash/public/cpp/ambient/ambient_prefs.h" #include "ash/public/cpp/ambient/common/ambient_settings.h" #include "ash/public/cpp/ambient/fake_ambient_backend_controller_impl.h" +#include "ash/shell.h" +#include "ash/test/ash_test_base.h" #include "ash/webui/personalization_app/mojom/personalization_app.mojom.h" #include "base/callback_helpers.h" #include "base/ranges/algorithm.h" @@ -68,6 +70,8 @@ previews_ = std::move(previews); } + void OnScreenSaverClosed() override { screen_saver_closed_ = true; } + mojo::PendingRemote<ash::personalization_app::mojom::AmbientObserver> pending_remote() { if (ambient_observer_receiver_.is_bound()) { @@ -112,6 +116,8 @@ ambient_observer_receiver_{this}; bool ambient_mode_enabled_ = false; + bool screen_saver_closed_ = false; + ash::AmbientAnimationTheme animation_theme_ = ash::AmbientAnimationTheme::kSlideshow; ash::AmbientModeTopicSource topic_source_ = @@ -124,10 +130,13 @@ } // namespace -class PersonalizationAppAmbientProviderImplTest : public testing::Test { +class PersonalizationAppAmbientProviderImplTest : public ash::AshTestBase { public: PersonalizationAppAmbientProviderImplTest() - : profile_manager_(TestingBrowserProcess::GetGlobal()) {} + : ash::AshTestBase(std::unique_ptr<base::test::TaskEnvironment>( + std::make_unique<content::BrowserTaskEnvironment>( + base::test::TaskEnvironment::TimeSource::MOCK_TIME))), + profile_manager_(TestingBrowserProcess::GetGlobal()) {} PersonalizationAppAmbientProviderImplTest( const PersonalizationAppAmbientProviderImplTest&) = delete; PersonalizationAppAmbientProviderImplTest& operator=( @@ -137,6 +146,8 @@ protected: // testing::Test: void SetUp() override { + ash::AshTestBase::SetUp(); + ASSERT_TRUE(profile_manager_.SetUp()); profile_ = profile_manager_.CreateTestingProfile(kFakeTestEmail); @@ -151,12 +162,17 @@ ambient_provider_remote_.BindNewPipeAndPassReceiver()); SetEnabledPref(true); + GetAmbientAshTestHelper()->ambient_client().SetAutomaticalyIssueToken(true); + + Shell::Get()->ambient_controller()->set_backend_controller_for_testing( + nullptr); + fake_backend_controller_ = std::make_unique<ash::FakeAmbientBackendControllerImpl>(); - ambient_ash_test_helper_ = std::make_unique<ash::AmbientAshTestHelper>(); - ambient_ash_test_helper_->ambient_client().SetAutomaticalyIssueToken(true); } + void TearDown() override { ash::AshTestBase::TearDown(); } + TestingProfile* profile() { return profile_; } mojo::Remote<ash::personalization_app::mojom::AmbientProvider>& @@ -288,7 +304,7 @@ } void FastForwardBy(base::TimeDelta time) { - task_environment_.FastForwardBy(time); + task_environment()->FastForwardBy(time); } bool IsFetchSettingsPendingAtBackend() const { @@ -311,8 +327,6 @@ } private: - content::BrowserTaskEnvironment task_environment_{ - base::test::TaskEnvironment::TimeSource::MOCK_TIME}; TestingProfileManager profile_manager_; content::TestWebUI web_ui_; std::unique_ptr<content::WebContents> web_contents_;
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index c6e96b2..b71d47dd 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -203,7 +203,6 @@ #include "chrome/browser/ui/page_info/chrome_page_info_client.h" #include "ui/base/resource/resource_bundle_android.h" #else -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/resource_coordinator/tab_activity_watcher.h" #include "chrome/browser/resource_coordinator/tab_manager.h" #include "chrome/browser/resources_integrity.h" @@ -1157,13 +1156,9 @@ #if !BUILDFLAG(IS_ANDROID) // Ephemeral profiles may have been left behind if the browser crashed. - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .CleanUpEphemeralProfiles(); + g_browser_process->profile_manager()->CleanUpEphemeralProfiles(); // Files of deleted profiles can also be left behind after a crash. - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .CleanUpDeletedProfiles(); + g_browser_process->profile_manager()->CleanUpDeletedProfiles(); #endif // !BUILDFLAG(IS_ANDROID) #if BUILDFLAG(ENABLE_EXTENSIONS)
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_histogram_helper.h b/chrome/browser/chromeos/policy/dlp/dlp_histogram_helper.h index 6fad526..f86ed5c 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_histogram_helper.h +++ b/chrome/browser/chromeos/policy/dlp/dlp_histogram_helper.h
@@ -57,6 +57,7 @@ constexpr char kConfidentialContentsCount[] = "ConfidentialContentsCount"; constexpr char kActiveFileEventsCount[] = "ActiveFileEventsCount"; constexpr char kErrorsReportQueueNotReady[] = "Errors.ReportQueueNotReady"; +constexpr char kErrorsFilesPolicySetup[] = "Errors.FilesPolicySetup"; } // namespace dlp
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.cc b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.cc index 43b3562..5b766b9 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.cc
@@ -183,6 +183,8 @@ } void OnSetDlpFilesPolicy(const ::dlp::SetDlpFilesPolicyResponse response) { + DlpBooleanHistogram(dlp::kErrorsFilesPolicySetup, + response.has_error_message()); if (response.has_error_message()) { DlpScopedFileAccessDelegate::DeleteInstance(); LOG(ERROR) << "Failed to set DLP Files policy and start DLP daemon, error: "
diff --git a/chrome/browser/chromeos/printing/cups_wrapper_impl.cc b/chrome/browser/chromeos/printing/cups_wrapper_impl.cc index e8fae30..f20fdd09 100644 --- a/chrome/browser/chromeos/printing/cups_wrapper_impl.cc +++ b/chrome/browser/chromeos/printing/cups_wrapper_impl.cc
@@ -11,7 +11,6 @@ #include "base/logging.h" #include "base/sequence_checker.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" @@ -47,8 +46,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // It's safe to pass unretained pointer here because we delete |backend_| on // the same task runner. - base::PostTaskAndReplyWithResult( - backend_task_runner_.get(), FROM_HERE, + backend_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Backend::QueryCupsPrintJobs, base::Unretained(backend_.get()), printer_ids), std::move(callback)); @@ -71,8 +70,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // It's safe to pass unretained pointer here because we delete |backend_| on // the same task runner. - base::PostTaskAndReplyWithResult( - backend_task_runner_.get(), FROM_HERE, + backend_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Backend::QueryCupsPrinterStatus, base::Unretained(backend_.get()), printer_id), std::move(callback));
diff --git a/chrome/browser/chromeos/reporting/metric_default_utils.h b/chrome/browser/chromeos/reporting/metric_default_utils.h index 9f52a1c2..94e83ec 100644 --- a/chrome/browser/chromeos/reporting/metric_default_utils.h +++ b/chrome/browser/chromeos/reporting/metric_default_utils.h
@@ -28,10 +28,6 @@ constexpr base::TimeDelta kDefaultNetworkTelemetryEventCheckingRate = base::Minutes(10); -// Default graphics telemetry collection rate. -constexpr base::TimeDelta kDefaultGraphicsTelemetryCollectionRate = - base::Hours(3); - // Default record upload frequency. constexpr base::TimeDelta kDefaultReportUploadFrequency = base::Hours(3);
diff --git a/chrome/browser/chromeos/reporting/metric_reporting_manager_delegate_base.cc b/chrome/browser/chromeos/reporting/metric_reporting_manager_delegate_base.cc index c1fd539..73ce8898 100644 --- a/chrome/browser/chromeos/reporting/metric_reporting_manager_delegate_base.cc +++ b/chrome/browser/chromeos/reporting/metric_reporting_manager_delegate_base.cc
@@ -4,11 +4,12 @@ #include "chrome/browser/chromeos/reporting/metric_reporting_manager_delegate_base.h" +#include "base/time/time.h" #include "chrome/browser/chromeos/reporting/metric_default_utils.h" #include "chrome/browser/enterprise/util/affiliation.h" #include "components/reporting/client/report_queue_factory.h" #include "components/reporting/metrics/collector_base.h" -#include "components/reporting/metrics/event_driven_telemetry_sampler_pool.h" +#include "components/reporting/metrics/event_driven_telemetry_collector_pool.h" #include "components/reporting/metrics/metric_event_observer.h" #include "components/reporting/metrics/metric_report_queue.h" #include "components/reporting/metrics/one_shot_collector.h" @@ -72,11 +73,12 @@ bool setting_enabled_default_value, const std::string& rate_setting_path, base::TimeDelta default_rate, - int rate_unit_to_ms) { + int rate_unit_to_ms, + base::TimeDelta init_delay) { return std::make_unique<PeriodicCollector>( sampler, metric_report_queue, reporting_settings, enable_setting_path, setting_enabled_default_value, rate_setting_path, default_rate, - rate_unit_to_ms); + rate_unit_to_ms, init_delay); } std::unique_ptr<CollectorBase> @@ -85,10 +87,11 @@ MetricReportQueue* metric_report_queue, ReportingSettings* reporting_settings, const std::string& enable_setting_path, - bool setting_enabled_default_value) { + bool setting_enabled_default_value, + base::TimeDelta init_delay) { return std::make_unique<OneShotCollector>( sampler, metric_report_queue, reporting_settings, enable_setting_path, - setting_enabled_default_value); + setting_enabled_default_value, init_delay); } std::unique_ptr<MetricEventObserverManager> @@ -98,10 +101,12 @@ ReportingSettings* reporting_settings, const std::string& enable_setting_path, bool setting_enabled_default_value, - EventDrivenTelemetrySamplerPool* sampler_pool) { + EventDrivenTelemetryCollectorPool* collector_pool, + base::TimeDelta init_delay) { return std::make_unique<MetricEventObserverManager>( std::move(event_observer), metric_report_queue, reporting_settings, - enable_setting_path, setting_enabled_default_value, sampler_pool); + enable_setting_path, setting_enabled_default_value, collector_pool, + init_delay); } bool MetricReportingManagerDelegateBase::IsAffiliated(Profile* profile) const {
diff --git a/chrome/browser/chromeos/reporting/metric_reporting_manager_delegate_base.h b/chrome/browser/chromeos/reporting/metric_reporting_manager_delegate_base.h index 6dff113..b994051 100644 --- a/chrome/browser/chromeos/reporting/metric_reporting_manager_delegate_base.h +++ b/chrome/browser/chromeos/reporting/metric_reporting_manager_delegate_base.h
@@ -7,10 +7,11 @@ #include <memory> +#include "base/time/time.h" #include "chrome/browser/profiles/profile.h" #include "components/reporting/client/report_queue_configuration.h" #include "components/reporting/metrics/collector_base.h" -#include "components/reporting/metrics/event_driven_telemetry_sampler_pool.h" +#include "components/reporting/metrics/event_driven_telemetry_collector_pool.h" #include "components/reporting/metrics/metric_event_observer.h" #include "components/reporting/metrics/metric_event_observer_manager.h" #include "components/reporting/metrics/metric_report_queue.h" @@ -58,7 +59,8 @@ bool setting_enabled_default_value, const std::string& rate_setting_path, base::TimeDelta default_rate, - int rate_unit_to_ms); + int rate_unit_to_ms, + base::TimeDelta init_delay = base::TimeDelta()); // Creates a new collector for one shot metric collection. The rate is // controlled by the specified setting and we fall back to the defaults @@ -68,7 +70,8 @@ MetricReportQueue* metric_report_queue, ReportingSettings* reporting_settings, const std::string& enable_setting_path, - bool setting_enabled_default_value); + bool setting_enabled_default_value, + base::TimeDelta init_delay = base::TimeDelta()); // Creates a new event observer manager to manage events reporting. The rate // is controlled by the specified setting and we fall back to the defaults @@ -80,7 +83,8 @@ ReportingSettings* reporting_settings, const std::string& enable_setting_path, bool setting_enabled_default_value, - EventDrivenTelemetrySamplerPool* sampler_pool); + EventDrivenTelemetryCollectorPool* collector_pool, + base::TimeDelta init_delay = base::TimeDelta()); // Checks for profile affiliation and returns true if affiliated. False // otherwise.
diff --git a/chrome/browser/chromeos/reporting/metric_reporting_manager_lacros_unittest.cc b/chrome/browser/chromeos/reporting/metric_reporting_manager_lacros_unittest.cc index 102879f..1317f92 100644 --- a/chrome/browser/chromeos/reporting/metric_reporting_manager_lacros_unittest.cc +++ b/chrome/browser/chromeos/reporting/metric_reporting_manager_lacros_unittest.cc
@@ -10,6 +10,7 @@ #include "base/callback_helpers.h" #include "base/memory/raw_ptr.h" #include "base/test/bind.h" +#include "base/time/time.h" #include "chrome/browser/chromeos/reporting/device_reporting_settings_lacros.h" #include "chrome/browser/chromeos/reporting/metric_default_utils.h" #include "chrome/test/base/testing_browser_process.h" @@ -47,7 +48,10 @@ ~FakeCollector() override { --(*collector_count_); } protected: - void OnMetricDataCollected(absl::optional<MetricData>) override {} + // CollectorBase: + void OnMetricDataCollected(bool is_event_driven, + absl::optional<MetricData> metric_data) override {} + bool CanCollect() const override { return true; } private: raw_ptr<int> collector_count_; @@ -88,7 +92,8 @@ bool setting_enabled_default_value, const std::string& rate_setting_path, base::TimeDelta default_rate, - int rate_unit_to_ms), + int rate_unit_to_ms, + base::TimeDelta init_delay), (override)); MOCK_METHOD(std::unique_ptr<MetricReportQueue>, @@ -212,7 +217,7 @@ test_case.setting_data.enable_setting_path, test_case.setting_data.setting_enabled_default_value, test_case.setting_data.rate_setting_path, _, - test_case.setting_data.rate_unit_to_ms)) + test_case.setting_data.rate_unit_to_ms, _)) .WillByDefault([&periodic_collector_count]() { return std::make_unique<FakeCollector>(&periodic_collector_count); });
diff --git a/chrome/browser/client_hints/client_hints_browsertest.cc b/chrome/browser/client_hints/client_hints_browsertest.cc index b2b0a97..e3ee5f2 100644 --- a/chrome/browser/client_hints/client_hints_browsertest.cc +++ b/chrome/browser/client_hints/client_hints_browsertest.cc
@@ -3395,9 +3395,9 @@ : public CriticalClientHintsBrowserTest, public testing::WithParamInterface<net::HttpStatusCode> {}; -INSTANTIATE_TEST_CASE_P(AllRedirectCodes, - CriticalClientHintsRedirectBrowserTest, - testing::ValuesIn(kRedirectStatusCodes)); +INSTANTIATE_TEST_SUITE_P(AllRedirectCodes, + CriticalClientHintsRedirectBrowserTest, + testing::ValuesIn(kRedirectStatusCodes)); IN_PROC_BROWSER_TEST_P(CriticalClientHintsRedirectBrowserTest, RestartDuringRedirect) {
diff --git a/chrome/browser/download/save_package_file_picker.cc b/chrome/browser/download/save_package_file_picker.cc index b538a93..9192dfa 100644 --- a/chrome/browser/download/save_package_file_picker.cc +++ b/chrome/browser/download/save_package_file_picker.cc
@@ -236,27 +236,31 @@ if (g_should_prompt_for_filename) { select_file_dialog_ = ui::SelectFileDialog::Create( this, std::make_unique<ChromeSelectFilePolicy>(web_contents)); - select_file_dialog_->SelectFile( - ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(), - suggested_path_copy, &file_type_info, file_type_index, - default_extension_copy, - platform_util::GetTopLevel(web_contents->GetNativeView()), nullptr); - } else { - // Just use 'suggested_path_copy' instead of opening the dialog prompt. - // Go through FileSelected() for consistency. - FileSelected(suggested_path_copy, file_type_index, nullptr); + if (select_file_dialog_) { + select_file_dialog_->SelectFile( + ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(), + suggested_path_copy, &file_type_info, file_type_index, + default_extension_copy, + platform_util::GetTopLevel(web_contents->GetNativeView()), nullptr); + return; + } } + + // If |g_should_prompt_for_filename| is unset or |select_file_dialog_| could + // not be instantiated for some reason, just use 'suggested_path_copy' instead + // of opening the dialog prompt. Go through FileSelected() for consistency. + FileSelected(suggested_path_copy, file_type_index, nullptr); } -SavePackageFilePicker::~SavePackageFilePicker() { -} +SavePackageFilePicker::~SavePackageFilePicker() = default; void SavePackageFilePicker::SetShouldPromptUser(bool should_prompt) { g_should_prompt_for_filename = should_prompt; } -void SavePackageFilePicker::FileSelected( - const base::FilePath& path, int index, void* unused_params) { +void SavePackageFilePicker::FileSelected(const base::FilePath& path, + int index, + void* unused_params) { std::unique_ptr<SavePackageFilePicker> delete_this(this); RenderProcessHost* process = RenderProcessHost::FromID(render_process_id_); if (!process)
diff --git a/chrome/browser/extensions/activity_log/counting_policy.cc b/chrome/browser/extensions/activity_log/counting_policy.cc index cb8e68c..ee48339 100644 --- a/chrome/browser/extensions/activity_log/counting_policy.cc +++ b/chrome/browser/extensions/activity_log/counting_policy.cc
@@ -45,7 +45,6 @@ #include "base/memory/scoped_refptr.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "base/task/task_runner_util.h" #include "chrome/browser/extensions/activity_log/activity_log_task_runner.h" #include "chrome/common/chrome_constants.h" #include "sql/statement.h" @@ -713,8 +712,8 @@ const std::string& arg_url, const int days_ago, base::OnceCallback<void(std::unique_ptr<Action::ActionVector>)> callback) { - base::PostTaskAndReplyWithResult( - GetActivityLogTaskRunner().get(), FROM_HERE, + GetActivityLogTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CountingPolicy::DoReadFilteredData, base::Unretained(this), extension_id, type, api_name, page_url, arg_url, days_ago),
diff --git a/chrome/browser/extensions/activity_log/fullstream_ui_policy.cc b/chrome/browser/extensions/activity_log/fullstream_ui_policy.cc index f7c6306b..d398226 100644 --- a/chrome/browser/extensions/activity_log/fullstream_ui_policy.cc +++ b/chrome/browser/extensions/activity_log/fullstream_ui_policy.cc
@@ -18,7 +18,6 @@ #include "base/memory/ptr_util.h" #include "base/memory/scoped_refptr.h" #include "base/strings/stringprintf.h" -#include "base/task/task_runner_util.h" #include "chrome/browser/extensions/activity_log/activity_action_constants.h" #include "chrome/browser/extensions/activity_log/activity_database.h" #include "chrome/browser/extensions/activity_log/activity_log_task_runner.h" @@ -391,8 +390,8 @@ const std::string& arg_url, const int days_ago, base::OnceCallback<void(std::unique_ptr<Action::ActionVector>)> callback) { - base::PostTaskAndReplyWithResult( - GetActivityLogTaskRunner().get(), FROM_HERE, + GetActivityLogTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FullStreamUIPolicy::DoReadFilteredData, base::Unretained(this), extension_id, type, api_name, page_url, arg_url, days_ago),
diff --git a/chrome/browser/extensions/api/identity/web_auth_flow_browsertest.cc b/chrome/browser/extensions/api/identity/web_auth_flow_browsertest.cc index 389c6fc..e160835e 100644 --- a/chrome/browser/extensions/api/identity/web_auth_flow_browsertest.cc +++ b/chrome/browser/extensions/api/identity/web_auth_flow_browsertest.cc
@@ -226,7 +226,7 @@ } } -INSTANTIATE_TEST_CASE_P( +INSTANTIATE_TEST_SUITE_P( , WebAuthFlowGuestPartitionParamTest, testing::Combine(testing::Bool(),
diff --git a/chrome/browser/extensions/api/scripting/scripting_api.cc b/chrome/browser/extensions/api/scripting/scripting_api.cc index 8dc1f067..b3e29dc 100644 --- a/chrome/browser/extensions/api/scripting/scripting_api.cc +++ b/chrome/browser/extensions/api/scripting/scripting_api.cc
@@ -12,7 +12,6 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/types/optional_util.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/tab_helper.h" @@ -979,8 +978,8 @@ // made immediately following this one. loader->AddPendingDynamicScriptIDs(std::move(new_script_ids)); - base::PostTaskAndReplyWithResult( - GetExtensionFileTaskRunner().get(), FROM_HERE, + GetExtensionFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ValidateParsedScriptsOnFileThread, script_parsing::GetSymlinkPolicy(extension()), std::move(parsed_scripts)), @@ -1242,8 +1241,8 @@ // made immediately following this one. loader->AddPendingDynamicScriptIDs(std::move(ids_to_update)); - base::PostTaskAndReplyWithResult( - GetExtensionFileTaskRunner().get(), FROM_HERE, + GetExtensionFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ValidateParsedScriptsOnFileThread, script_parsing::GetSymlinkPolicy(extension()), std::move(parsed_scripts)),
diff --git a/chrome/browser/extensions/component_loader.cc b/chrome/browser/extensions/component_loader.cc index 2e42d18..b87c268 100644 --- a/chrome/browser/extensions/component_loader.cc +++ b/chrome/browser/extensions/component_loader.cc
@@ -16,7 +16,6 @@ #include "base/json/json_string_value_serializer.h" #include "base/metrics/histogram_macros.h" #include "base/path_service.h" -#include "base/task/task_runner_util.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" #include "build/branding_buildflags.h" @@ -583,8 +582,8 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); const base::FilePath::CharType* manifest_filename = IsNormalSession() ? manifest_file_name : guest_manifest_file_name; - base::PostTaskAndReplyWithResult( - GetExtensionFileTaskRunner().get(), FROM_HERE, + GetExtensionFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadManifestOnFileThread, root_directory, manifest_filename, true), base::BindOnce(&ComponentLoader::FinishAddComponentFromDir, @@ -598,8 +597,8 @@ const std::string& name_string, const std::string& description_string) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskAndReplyWithResult( - GetExtensionFileTaskRunner().get(), FROM_HERE, + GetExtensionFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadManifestOnFileThread, root_directory, extensions::kManifestFilename, false), base::BindOnce(&ComponentLoader::FinishAddComponentFromDir,
diff --git a/chrome/browser/extensions/webstore_installer.cc b/chrome/browser/extensions/webstore_installer.cc index 3cf8e4d..94f4fb1 100644 --- a/chrome/browser/extensions/webstore_installer.cc +++ b/chrome/browser/extensions/webstore_installer.cc
@@ -27,7 +27,6 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/download/download_crx_util.h" @@ -550,8 +549,8 @@ base::FilePath download_directory(g_download_directory_for_tests ? *g_download_directory_for_tests : download_path); - base::PostTaskAndReplyWithResult( - GetExtensionFileTaskRunner().get(), FROM_HERE, + GetExtensionFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetDownloadFilePath, download_directory, extension_id), base::BindOnce(&WebstoreInstaller::StartDownload, this, extension_id)); }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 8d29c8ef..69d9d50 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -154,11 +154,6 @@ "expiry_milestone": 140 }, { - "name": "android-picture-in-picture-api", - "owners": [ "steimel", "jazzhsu", "media-dev" ], - "expiry_milestone": 120 - }, - { "name": "animated-image-resume", "owners": [ "cblume", "vmpstr" ], "expiry_milestone": 93 @@ -990,7 +985,7 @@ "snianu@microsoft.com", "chrome-owp-storage@google.com" ], - "expiry_milestone": 110 + "expiry_milestone": 115 }, { "name": "closed-tab-cache", @@ -1230,6 +1225,11 @@ "expiry_milestone": 120 }, { + "name": "default-browser-blue-dot-promo", + "owners": ["nicolasmacbeth@google.com", "bling-get-set-up@google.com"], + "expiry_milestone": 114 + }, + { "name": "default-browser-fullscreen-promo-experiment", "owners": [ "thegreenfrog", "bling-flags@google.com" ], "expiry_milestone": 93 @@ -3527,6 +3527,11 @@ "expiry_milestone": -1 }, { + "name": "extract-related-searches-from-prefetched-zps-response", + "owners": [ "khalidpeer", "chrome-journeys@google.com" ], + "expiry_milestone": 120 + }, + { "name": "fail-fast-quiet-chip", "owners": [ "elklm", "//components/permissions/PERMISSIONS_OWNERS"], "expiry_milestone": 115 @@ -6673,7 +6678,7 @@ { "name" : "unified-side-panel", "owners": [ "chrome-desktop-ui-sea@google.com", "corising", "pbos", "tluk" ], - "expiry_milestone" : 109 + "expiry_milestone" : 110 }, { "name": "unsafely-treat-insecure-origin-as-secure",
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 35cd761b..b072420 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -254,11 +254,6 @@ "Use a custom URL as part of the \"Messages\" feature under " "\"Connected Devices\" settings."; -const char kAndroidPictureInPictureAPIName[] = - "Picture-in-Picture Web API for Android"; -const char kAndroidPictureInPictureAPIDescription[] = - "Enable Picture-in-Picture Web API for Android"; - const char kUseDMSAAForTilesName[] = "Use DMSAA for tiles"; const char kUseDMSAAForTilesDescription[] = "Switches skia to use DMSAA instead of MSAA for tile raster"; @@ -1756,6 +1751,12 @@ const char kJourneysVisitDedupingDescription[] = "Enables variations for how visits are deduped"; +const char kExtractRelatedSearchesFromPrefetchedZPSResponseName[] = + "Extract Related Searches from Prefetched ZPS Response"; +const char kExtractRelatedSearchesFromPrefetchedZPSResponseDescription[] = + "Enables page annotation logic to source related searches data from " + "prefetched ZPS responses"; + const char kLargeFaviconFromGoogleName[] = "Large favicons from Google"; const char kLargeFaviconFromGoogleDescription[] = "Request large favicons from Google's favicon service";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 02b235d3..efbafe6 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -165,9 +165,6 @@ extern const char kUseCustomMessagesDomainName[]; extern const char kUseCustomMessagesDomainDescription[]; -extern const char kAndroidPictureInPictureAPIName[]; -extern const char kAndroidPictureInPictureAPIDescription[]; - extern const char kAssistantConsentModalName[]; extern const char kAssistantConsentModalDescription[]; @@ -993,6 +990,9 @@ extern const char kJourneysVisitDedupingName[]; extern const char kJourneysVisitDedupingDescription[]; +extern const char kExtractRelatedSearchesFromPrefetchedZPSResponseName[]; +extern const char kExtractRelatedSearchesFromPrefetchedZPSResponseDescription[]; + extern const char kLargeFaviconFromGoogleName[]; extern const char kLargeFaviconFromGoogleDescription[];
diff --git a/chrome/browser/history_clusters/entity_image_service.cc b/chrome/browser/history_clusters/entity_image_service.cc index a5400545..899db81 100644 --- a/chrome/browser/history_clusters/entity_image_service.cc +++ b/chrome/browser/history_clusters/entity_image_service.cc
@@ -8,10 +8,7 @@ #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/i18n/case_conversion.h" -#include "base/memory/singleton.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_keyed_service_factory.h" -#include "chrome/browser/sync/sync_service_factory.h" #include "components/history_clusters/core/config.h" #include "components/omnibox/browser/remote_suggestions_service.h" #include "components/omnibox/browser/search_suggestion_parser.h" @@ -24,40 +21,6 @@ namespace { -// Anonymous namespace factory based on LookalikeUrlServiceFactory. -class EntityImageServiceFactory : public ProfileKeyedServiceFactory { - public: - static EntityImageService* GetForProfile(Profile* profile) { - return static_cast<EntityImageService*>( - GetInstance()->GetServiceForBrowserContext(profile, - /*create=*/true)); - } - static EntityImageServiceFactory* GetInstance() { - return base::Singleton<EntityImageServiceFactory>::get(); - } - - EntityImageServiceFactory(const EntityImageServiceFactory&) = delete; - EntityImageServiceFactory& operator=(const EntityImageServiceFactory&) = - delete; - - private: - friend struct base::DefaultSingletonTraits<EntityImageServiceFactory>; - - // EntityImageServiceFactory: - EntityImageServiceFactory() - : ProfileKeyedServiceFactory("EntityImageServiceFactory") { - DependsOn(SyncServiceFactory::GetInstance()); - } - - ~EntityImageServiceFactory() override = default; - - // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* profile) const override { - return new EntityImageService(static_cast<Profile*>(profile)); - } -}; - // A one-time use object that encapsulates tagging a vector of clusters with // entity images. Used to manage all the fetch jobs dispatched, and runs the // main callback after it's done. @@ -145,15 +108,12 @@ class EntityImageService::SuggestEntityImageURLFetcher { public: SuggestEntityImageURLFetcher( - Profile* profile, - ChromeAutocompleteProviderClient* autocomplete_provider_client, + AutocompleteProviderClient* autocomplete_provider_client, const std::u16string& search_query, const std::string& entity_id) - : profile_(profile), - autocomplete_provider_client_(autocomplete_provider_client), + : autocomplete_provider_client_(autocomplete_provider_client), search_query_(base::i18n::ToLower(search_query)), entity_id_(entity_id) { - DCHECK(profile); DCHECK(autocomplete_provider_client); } SuggestEntityImageURLFetcher(const SuggestEntityImageURLFetcher&) = delete; @@ -228,7 +188,6 @@ std::move(callback_).Run(GURL()); } - const raw_ptr<Profile> profile_; const raw_ptr<AutocompleteProviderClient> autocomplete_provider_client_; // The search query and entity ID we are searching for. @@ -244,21 +203,16 @@ base::WeakPtrFactory<SuggestEntityImageURLFetcher> weak_factory_{this}; }; -EntityImageService::EntityImageService(Profile* profile) - : profile_(profile), - autocomplete_provider_client_(profile), - url_consent_helper_(unified_consent::UrlKeyedDataCollectionConsentHelper:: - NewPersonalizedDataCollectionConsentHelper( - SyncServiceFactory::GetForProfile(profile))) { -} +EntityImageService::EntityImageService( + std::unique_ptr<AutocompleteProviderClient> autocomplete_provider_client, + syncer::SyncService* sync_service) + : autocomplete_provider_client_(std::move(autocomplete_provider_client)), + url_consent_helper_( + unified_consent::UrlKeyedDataCollectionConsentHelper:: + NewPersonalizedDataCollectionConsentHelper(sync_service)) {} EntityImageService::~EntityImageService() = default; -// static -EntityImageService* EntityImageService::Get(Profile* profile) { - return EntityImageServiceFactory::GetForProfile(profile); -} - void EntityImageService::PopulateEntityImagesFor( std::vector<history::Cluster> clusters, base::OnceCallback<void(std::vector<history::Cluster>)> callback) { @@ -283,7 +237,7 @@ DCHECK(url_consent_helper_ && url_consent_helper_->IsEnabled()); auto fetcher = std::make_unique<SuggestEntityImageURLFetcher>( - profile_, &autocomplete_provider_client_, search_query, entity_id); + autocomplete_provider_client_.get(), search_query, entity_id); // Use a raw pointer temporary so we can give ownership of the unique_ptr to // the callback and have a well defined SuggestEntityImageURLFetcher lifetime.
diff --git a/chrome/browser/history_clusters/entity_image_service.h b/chrome/browser/history_clusters/entity_image_service.h index d8fee001..e68929f 100644 --- a/chrome/browser/history_clusters/entity_image_service.h +++ b/chrome/browser/history_clusters/entity_image_service.h
@@ -5,36 +5,35 @@ #ifndef CHROME_BROWSER_HISTORY_CLUSTERS_ENTITY_IMAGE_SERVICE_H_ #define CHROME_BROWSER_HISTORY_CLUSTERS_ENTITY_IMAGE_SERVICE_H_ +#include <memory> #include <string> #include "base/functional/callback_forward.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/autocomplete/chrome_autocomplete_provider_client.h" -#include "chrome/browser/profiles/profile.h" #include "components/history/core/browser/history_types.h" #include "components/keyed_service/core/keyed_service.h" +#include "components/omnibox/browser/autocomplete_provider_client.h" +#include "components/sync/driver/sync_service.h" #include "components/unified_consent/url_keyed_data_collection_consent_helper.h" namespace history_clusters { // Used to get the image URL associated with a cluster. It doesn't actually // fetch the image, that's up to the UI to do. +// TODO(tommycli): Move to /components and rename to `ImageService`. class EntityImageService : public KeyedService { public: using ResultCallback = base::OnceCallback<void(const GURL& image_url)>; - // This should only be called by the internal factory. Most callers should use - // the `Get()` method instead. - explicit EntityImageService(Profile* profile); + EntityImageService( + std::unique_ptr<AutocompleteProviderClient> autocomplete_provider_client, + syncer::SyncService* sync_service); EntityImageService(const EntityImageService&) = delete; EntityImageService& operator=(const EntityImageService&) = delete; ~EntityImageService() override; - // Gets the fetcher associated with `profile`. Always succeeds. - static EntityImageService* Get(Profile* profile); - // Populates entity images into the `image_url` of any eligible visits within // every cluster in `clusters`. `clusters` should be moved into the parameter. // `callback` is called when we're done, and it can be called synchronously @@ -58,9 +57,7 @@ ResultCallback callback, const GURL& image_url); - const raw_ptr<Profile> profile_; - ChromeAutocompleteProviderClient autocomplete_provider_client_; - + std::unique_ptr<AutocompleteProviderClient> autocomplete_provider_client_; std::unique_ptr<unified_consent::UrlKeyedDataCollectionConsentHelper> url_consent_helper_;
diff --git a/chrome/browser/image_service/OWNERS b/chrome/browser/image_service/OWNERS new file mode 100644 index 0000000..d912c7e --- /dev/null +++ b/chrome/browser/image_service/OWNERS
@@ -0,0 +1,2 @@ +sophiechang@chromium.org +tommycli@chromium.org
diff --git a/chrome/browser/image_service/README.md b/chrome/browser/image_service/README.md new file mode 100644 index 0000000..921b7c82 --- /dev/null +++ b/chrome/browser/image_service/README.md
@@ -0,0 +1,4 @@ +# //chrome/browser/image_service + +Service implementation for Chrome Images feature, to provide relevant images +for Chrome UI usage. \ No newline at end of file
diff --git a/chrome/browser/image_service/image_service_factory.cc b/chrome/browser/image_service/image_service_factory.cc new file mode 100644 index 0000000..e713a937f --- /dev/null +++ b/chrome/browser/image_service/image_service_factory.cc
@@ -0,0 +1,44 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/image_service/image_service_factory.h" + +#include "base/no_destructor.h" +#include "chrome/browser/autocomplete/chrome_autocomplete_provider_client.h" +#include "chrome/browser/history_clusters/entity_image_service.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/sync/sync_service_factory.h" + +namespace image_service { + +// static +history_clusters::EntityImageService* ImageServiceFactory::GetForBrowserContext( + content::BrowserContext* browser_context) { + return static_cast<history_clusters::EntityImageService*>( + GetInstance().GetServiceForBrowserContext(browser_context, true)); +} + +// static +ImageServiceFactory& ImageServiceFactory::GetInstance() { + static base::NoDestructor<ImageServiceFactory> instance; + return *instance; +} + +ImageServiceFactory::ImageServiceFactory() + : ProfileKeyedServiceFactory("ImageService") { + DependsOn(SyncServiceFactory::GetInstance()); +} + +ImageServiceFactory::~ImageServiceFactory() = default; + +KeyedService* ImageServiceFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + auto* profile = Profile::FromBrowserContext(context); + // TODO(tommycli): Move EntityImageService to the image_service component. + return new history_clusters::EntityImageService( + std::make_unique<ChromeAutocompleteProviderClient>(profile), + SyncServiceFactory::GetForProfile(profile)); +} + +} // namespace image_service
diff --git a/chrome/browser/image_service/image_service_factory.h b/chrome/browser/image_service/image_service_factory.h new file mode 100644 index 0000000..9f34a3f --- /dev/null +++ b/chrome/browser/image_service/image_service_factory.h
@@ -0,0 +1,43 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_IMAGE_SERVICE_IMAGE_SERVICE_FACTORY_H_ +#define CHROME_BROWSER_IMAGE_SERVICE_IMAGE_SERVICE_FACTORY_H_ + +#include "base/no_destructor.h" +#include "chrome/browser/profiles/profile_keyed_service_factory.h" + +namespace content { +class BrowserContext; +} + +namespace history_clusters { +class EntityImageService; +} + +namespace image_service { + +// Factory for BrowserContext keyed ImageService, which provides images for +// Journeys related features. +class ImageServiceFactory : public ProfileKeyedServiceFactory { + public: + // This can return nullptr in tests. + static history_clusters::EntityImageService* GetForBrowserContext( + content::BrowserContext* browser_context); + + private: + friend base::NoDestructor<ImageServiceFactory>; + static ImageServiceFactory& GetInstance(); + + ImageServiceFactory(); + ~ImageServiceFactory() override; + + // BrowserContextKeyedServiceFactory: + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const override; +}; + +} // namespace image_service + +#endif // CHROME_BROWSER_IMAGE_SERVICE_IMAGE_SERVICE_FACTORY_H_
diff --git a/chrome/browser/lacros/account_manager/account_profile_mapper.cc b/chrome/browser/lacros/account_manager/account_profile_mapper.cc index 4360c15c..217cb69a 100644 --- a/chrome/browser/lacros/account_manager/account_profile_mapper.cc +++ b/chrome/browser/lacros/account_manager/account_profile_mapper.cc
@@ -19,7 +19,6 @@ #include "base/ranges/algorithm.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/lacros/account_manager/add_account_helper.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" @@ -511,11 +510,9 @@ // profile. // TODO(https://crbug.com/1257610): ensure that the user cannot cancel the // profile deletion. - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .MaybeScheduleProfileForDeletion( - entry->GetPath(), base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_PRIMARY_ACCOUNT_REMOVED_LACROS); + g_browser_process->profile_manager()->MaybeScheduleProfileForDeletion( + entry->GetPath(), base::DoNothing(), + ProfileMetrics::DELETE_PROFILE_PRIMARY_ACCOUNT_REMOVED_LACROS); } } return removed_ids;
diff --git a/chrome/browser/lifetime/browser_shutdown.cc b/chrome/browser/lifetime/browser_shutdown.cc index e09b41d6..17d63fc 100644 --- a/chrome/browser/lifetime/browser_shutdown.cc +++ b/chrome/browser/lifetime/browser_shutdown.cc
@@ -30,7 +30,7 @@ #include "chrome/browser/buildflags.h" #include "chrome/browser/lifetime/application_lifetime_chromeos.h" #include "chrome/browser/lifetime/switch_utils.h" -#include "chrome/browser/profiles/nuke_profile_directory_utils.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" @@ -289,7 +289,7 @@ // crbug.com/95079 - This needs to happen after the browser process object // goes away. - NukeDeletedProfilesFromDisk(); + ProfileManager::NukeDeletedProfilesFromDisk(); #if BUILDFLAG(IS_CHROMEOS_ASH) ash::BootTimesRecorder::Get()->AddLogoutTimeMarker("BrowserDeleted", true);
diff --git a/chrome/browser/media/history/media_history_keyed_service.cc b/chrome/browser/media/history/media_history_keyed_service.cc index 35779f7..69e061b 100644 --- a/chrome/browser/media/history/media_history_keyed_service.cc +++ b/chrome/browser/media/history/media_history_keyed_service.cc
@@ -7,7 +7,6 @@ #include "base/containers/contains.h" #include "base/feature_list.h" #include "base/memory/raw_ptr.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/media/history/media_history_keyed_service_factory.h" @@ -203,8 +202,8 @@ void MediaHistoryKeyedService::GetMediaHistoryStats( base::OnceCallback<void(mojom::MediaHistoryStatsPtr)> callback) { - base::PostTaskAndReplyWithResult( - store_->GetForRead()->db_task_runner_.get(), FROM_HERE, + store_->GetForRead()->db_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MediaHistoryStore::GetMediaHistoryStats, store_->GetForRead()), std::move(callback)); @@ -213,8 +212,8 @@ void MediaHistoryKeyedService::GetOriginRowsForDebug( base::OnceCallback<void(std::vector<mojom::MediaHistoryOriginRowPtr>)> callback) { - base::PostTaskAndReplyWithResult( - store_->GetForRead()->db_task_runner_.get(), FROM_HERE, + store_->GetForRead()->db_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MediaHistoryStore::GetOriginRowsForDebug, store_->GetForRead()), std::move(callback)); @@ -223,8 +222,8 @@ void MediaHistoryKeyedService::GetMediaHistoryPlaybackRowsForDebug( base::OnceCallback<void(std::vector<mojom::MediaHistoryPlaybackRowPtr>)> callback) { - base::PostTaskAndReplyWithResult( - store_->GetForRead()->db_task_runner_.get(), FROM_HERE, + store_->GetForRead()->db_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MediaHistoryStore::GetMediaHistoryPlaybackRowsForDebug, store_->GetForRead()), std::move(callback)); @@ -235,8 +234,8 @@ absl::optional<GetPlaybackSessionsFilter> filter, base::OnceCallback< void(std::vector<mojom::MediaHistoryPlaybackSessionRowPtr>)> callback) { - base::PostTaskAndReplyWithResult( - store_->GetForRead()->db_task_runner_.get(), FROM_HERE, + store_->GetForRead()->db_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MediaHistoryStore::GetPlaybackSessions, store_->GetForRead(), num_sessions, std::move(filter)), std::move(callback)); @@ -257,8 +256,8 @@ void MediaHistoryKeyedService::GetHighWatchTimeOrigins( const base::TimeDelta& audio_video_watchtime_min, base::OnceCallback<void(const std::vector<url::Origin>&)> callback) { - base::PostTaskAndReplyWithResult( - store_->GetForRead()->db_task_runner_.get(), FROM_HERE, + store_->GetForRead()->db_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MediaHistoryStore::GetHighWatchTimeOrigins, store_->GetForRead(), audio_video_watchtime_min), std::move(callback)); @@ -267,8 +266,8 @@ void MediaHistoryKeyedService::GetURLsInTableForTest( const std::string& table, base::OnceCallback<void(std::set<GURL>)> callback) { - base::PostTaskAndReplyWithResult( - store_->GetForRead()->db_task_runner_.get(), FROM_HERE, + store_->GetForRead()->db_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MediaHistoryStore::GetURLsInTableForTest, store_->GetForRead(), table), std::move(callback));
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc index 9ef81e5f2..7185a61 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc
@@ -9,7 +9,6 @@ #include "base/task/bind_post_task.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "chrome/browser/media/router/discovery/access_code/access_code_cast_pref_updater.h" @@ -180,18 +179,17 @@ previous_routes_ = new_routes; if (added_routes.size() > 0) { - base::PostTaskAndReplyWithResult( - access_code_sink_service_->GetCastMediaSinkServiceImpl() - ->task_runner() - .get(), - FROM_HERE, - base::BindOnce( - &CastMediaSinkServiceImpl::GetSinkById, - base::Unretained( - access_code_sink_service_->GetCastMediaSinkServiceImpl()), - MediaRoute::GetSinkIdFromMediaRouteId(*added_routes.begin())), - base::BindOnce(&AccessCodeCastSinkService::HandleMediaRouteAdded, - access_code_sink_service_->GetWeakPtr())); + access_code_sink_service_->GetCastMediaSinkServiceImpl() + ->task_runner() + ->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce( + &CastMediaSinkServiceImpl::GetSinkById, + base::Unretained( + access_code_sink_service_->GetCastMediaSinkServiceImpl()), + MediaRoute::GetSinkIdFromMediaRouteId(*added_routes.begin())), + base::BindOnce(&AccessCodeCastSinkService::HandleMediaRouteAdded, + access_code_sink_service_->GetWeakPtr())); } // No routes were removed. @@ -205,19 +203,18 @@ auto first = removed_routes.begin(); removed_route_id_ = *first; - base::PostTaskAndReplyWithResult( - access_code_sink_service_->GetCastMediaSinkServiceImpl() - ->task_runner() - .get(), - FROM_HERE, - base::BindOnce( - &CastMediaSinkServiceImpl::GetSinkById, - base::Unretained( - access_code_sink_service_->GetCastMediaSinkServiceImpl()), - MediaRoute::GetSinkIdFromMediaRouteId(removed_route_id_)), - base::BindOnce( - &AccessCodeCastSinkService::HandleMediaRouteRemovedByAccessCode, - access_code_sink_service_->GetWeakPtr())); + access_code_sink_service_->GetCastMediaSinkServiceImpl() + ->task_runner() + ->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce( + &CastMediaSinkServiceImpl::GetSinkById, + base::Unretained( + access_code_sink_service_->GetCastMediaSinkServiceImpl()), + MediaRoute::GetSinkIdFromMediaRouteId(removed_route_id_)), + base::BindOnce( + &AccessCodeCastSinkService::HandleMediaRouteRemovedByAccessCode, + access_code_sink_service_->GetWeakPtr())); } bool AccessCodeCastSinkService::IsSinkValidAccessCodeSink( @@ -314,8 +311,8 @@ << "Must have a valid CastMediaSinkServiceImpl!"; // Check to see if the media sink already exists in the media router. - base::PostTaskAndReplyWithResult( - cast_media_sink_service_impl_->task_runner().get(), FROM_HERE, + cast_media_sink_service_impl_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CastMediaSinkServiceImpl::HasSink, base::Unretained(cast_media_sink_service_impl_), sink.id()), @@ -400,8 +397,8 @@ // For all other cases (such as remembered devices), just use the default // parameters that the CastMediaSinkServiceImpl already uses. default: { - base::PostTaskAndReplyWithResult( - cast_media_sink_service_impl_->task_runner().get(), FROM_HERE, + cast_media_sink_service_impl_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CastMediaSinkServiceImpl::CreateCastSocketOpenParams, base::Unretained(cast_media_sink_service_impl_), sink), base::BindOnce(&AccessCodeCastSinkService::OpenChannelWithParams, @@ -502,8 +499,8 @@ void AccessCodeCastSinkService::StoreSinkInPrefsById( const MediaSink::Id sink_id) { - base::PostTaskAndReplyWithResult( - cast_media_sink_service_impl_->task_runner().get(), FROM_HERE, + cast_media_sink_service_impl_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CastMediaSinkServiceImpl::GetSinkById, base::Unretained(cast_media_sink_service_impl_), sink_id), base::BindOnce(&AccessCodeCastSinkService::StoreSinkInPrefs, @@ -561,8 +558,8 @@ void AccessCodeCastSinkService::SetExpirationTimerById( const MediaSink::Id sink_id) { - base::PostTaskAndReplyWithResult( - cast_media_sink_service_impl_->task_runner().get(), FROM_HERE, + cast_media_sink_service_impl_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CastMediaSinkServiceImpl::GetSinkById, base::Unretained(cast_media_sink_service_impl_), sink_id), base::BindOnce(&AccessCodeCastSinkService::SetExpirationTimer, @@ -713,8 +710,8 @@ RemoveSinkIdFromAllEntries(sink_id); // Must find the sink from media router for removal since it has more total // information. - base::PostTaskAndReplyWithResult( - cast_media_sink_service_impl_->task_runner().get(), FROM_HERE, + cast_media_sink_service_impl_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CastMediaSinkServiceImpl::GetSinkById, base::Unretained(cast_media_sink_service_impl_), sink_id), base::BindOnce( @@ -799,8 +796,8 @@ // There are no active routes for this sink so it is safe to remove from the // media router. Must find the sink from media router for removal since it // has more total information. - base::PostTaskAndReplyWithResult( - cast_media_sink_service_impl_->task_runner().get(), FROM_HERE, + cast_media_sink_service_impl_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CastMediaSinkServiceImpl::GetSinkById, base::Unretained(cast_media_sink_service_impl_), sink_id),
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc index b19ab03..6e0ccd28 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc
@@ -7,7 +7,6 @@ #if BUILDFLAG(IS_WIN) #include "base/win/windows_version.h" #endif -#include "base/task/task_runner_util.h" #include "base/test/metrics/histogram_tester.h" #include "chrome/browser/buildflags.h" #include "chrome/browser/media/router/discovery/access_code/access_code_cast_constants.h" @@ -129,14 +128,16 @@ EXPECT_FALSE( GetPrefUpdater()->GetMediaSinkInternalValueBySinkId("cast:<1234>")); - base::PostTaskAndReplyWithResult( - mock_cast_media_sink_service_impl()->task_runner().get(), FROM_HERE, - base::BindOnce(&CastMediaSinkServiceImpl::HasSink, - base::Unretained(mock_cast_media_sink_service_impl()), - "cast:<1234>"), - base::BindOnce( - &AccessCodeCastIntegrationBrowserTest::ExpectMediaRouterHasNoSinks, - weak_ptr_factory_.GetWeakPtr())); + mock_cast_media_sink_service_impl() + ->task_runner() + ->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce(&CastMediaSinkServiceImpl::HasSink, + base::Unretained(mock_cast_media_sink_service_impl()), + "cast:<1234>"), + base::BindOnce(&AccessCodeCastIntegrationBrowserTest:: + ExpectMediaRouterHasNoSinks, + weak_ptr_factory_.GetWeakPtr())); } // TODO(b/242928209): Saved device tests are flaky on linux-rel/Mac/ChromeOS. @@ -219,14 +220,16 @@ EXPECT_TRUE( GetPrefUpdater()->GetMediaSinkInternalValueBySinkId("cast:<1234>")); - base::PostTaskAndReplyWithResult( - mock_cast_media_sink_service_impl()->task_runner().get(), FROM_HERE, - base::BindOnce(&CastMediaSinkServiceImpl::HasSink, - base::Unretained(mock_cast_media_sink_service_impl()), - "cast:<1234>"), - base::BindOnce( - &AccessCodeCastIntegrationBrowserTest::ExpectMediaRouterHasSink, - weak_ptr_factory_.GetWeakPtr())); + mock_cast_media_sink_service_impl() + ->task_runner() + ->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce(&CastMediaSinkServiceImpl::HasSink, + base::Unretained(mock_cast_media_sink_service_impl()), + "cast:<1234>"), + base::BindOnce( + &AccessCodeCastIntegrationBrowserTest::ExpectMediaRouterHasSink, + weak_ptr_factory_.GetWeakPtr())); } } // namespace media_router
diff --git a/chrome/browser/media/router/mojo/media_route_provider_util_win.cc b/chrome/browser/media/router/mojo/media_route_provider_util_win.cc index 3987d94..70adac6 100644 --- a/chrome/browser/media/router/mojo/media_route_provider_util_win.cc +++ b/chrome/browser/media/router/mojo/media_route_provider_util_win.cc
@@ -9,7 +9,6 @@ #include "base/location.h" #include "base/logging.h" #include "base/path_service.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "chrome/installer/util/firewall_manager_win.h" @@ -37,9 +36,9 @@ void CanFirewallUseLocalPorts(base::OnceCallback<void(bool)> callback) { auto task_runner = base::ThreadPool::CreateCOMSTATaskRunner( {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); - base::PostTaskAndReplyWithResult(task_runner.get(), FROM_HERE, - base::BindOnce(&DoCanFirewallUseLocalPorts), - std::move(callback)); + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DoCanFirewallUseLocalPorts), + std::move(callback)); } } // namespace media_router
diff --git a/chrome/browser/media/webrtc/tab_desktop_media_list.cc b/chrome/browser/media/webrtc/tab_desktop_media_list.cc index 95c42a0..a0115ca 100644 --- a/chrome/browser/media/webrtc/tab_desktop_media_list.cc +++ b/chrome/browser/media/webrtc/tab_desktop_media_list.cc
@@ -10,7 +10,6 @@ #include "base/containers/adapters.h" #include "base/hash/hash.h" #include "base/task/bind_post_task.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "chrome/browser/media/webrtc/desktop_media_list_layout_config.h" @@ -239,8 +238,8 @@ for (const auto& it : favicon_pairs) { // Create a thumbail in a different thread and update the thumbnail in // current thread. - base::PostTaskAndReplyWithResult( - image_resize_task_runner_.get(), FROM_HERE, + image_resize_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CreateEnclosedFaviconImage, thumbnail_size_, it.second), base::BindOnce(&TabDesktopMediaList::UpdateSourceThumbnail, weak_factory_.GetWeakPtr(), it.first));
diff --git a/chrome/browser/media/webrtc/webrtc_logging_controller.cc b/chrome/browser/media/webrtc/webrtc_logging_controller.cc index 23b050cb..e643e30 100644 --- a/chrome/browser/media/webrtc/webrtc_logging_controller.cc +++ b/chrome/browser/media/webrtc/webrtc_logging_controller.cc
@@ -15,7 +15,6 @@ #include "base/metrics/histogram_functions.h" #include "base/supports_user_data.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "build/build_config.h" #include "chrome/browser/media/webrtc/webrtc_event_log_manager.h" #include "chrome/browser/media/webrtc/webrtc_log_uploader.h" @@ -121,9 +120,8 @@ base::UmaHistogramSparse("WebRtcTextLogging.UploadStarted", web_app_id_); - base::PostTaskAndReplyWithResult( - log_uploader_->background_task_runner().get(), FROM_HERE, - base::BindOnce(log_directory_getter_), + log_uploader_->background_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(log_directory_getter_), base::BindOnce(&WebRtcLoggingController::TriggerUpload, this, std::move(callback))); } @@ -207,9 +205,8 @@ std::unique_ptr<WebRtcLogPaths> log_paths(new WebRtcLogPaths()); ReleaseRtpDumps(log_paths.get()); - base::PostTaskAndReplyWithResult( - log_uploader_->background_task_runner().get(), FROM_HERE, - base::BindOnce(log_directory_getter_), + log_uploader_->background_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(log_directory_getter_), base::BindOnce(&WebRtcLoggingController::StoreLogInDirectory, this, log_id, std::move(log_paths), std::move(callback))); } @@ -235,9 +232,8 @@ base::BindRepeating(&WebRtcLoggingController::OnRtpPacket, this)); if (!rtp_dump_handler_) { - base::PostTaskAndReplyWithResult( - log_uploader_->background_task_runner().get(), FROM_HERE, - base::BindOnce(log_directory_getter_), + log_uploader_->background_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(log_directory_getter_), base::BindOnce(&WebRtcLoggingController::CreateRtpDumpHandlerAndStart, this, type, std::move(callback))); return; @@ -287,9 +283,8 @@ LogsDirectoryErrorCallback error_callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!callback.is_null()); - base::PostTaskAndReplyWithResult( - log_uploader_->background_task_runner().get(), FROM_HERE, - base::BindOnce(log_directory_getter_), + log_uploader_->background_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(log_directory_getter_), base::BindOnce(&WebRtcLoggingController::GrantLogsDirectoryAccess, this, std::move(callback), std::move(error_callback))); } @@ -404,9 +399,8 @@ case WebRtcTextLogHandler::STOPPED: text_log_handler_->ChannelClosing(); if (upload_log_on_render_close_) { - base::PostTaskAndReplyWithResult( - log_uploader_->background_task_runner().get(), FROM_HERE, - base::BindOnce(log_directory_getter_), + log_uploader_->background_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(log_directory_getter_), base::BindOnce(&WebRtcLoggingController::TriggerUpload, this, UploadDoneCallback())); } else {
diff --git a/chrome/browser/media_galleries/fileapi/device_media_async_file_util.cc b/chrome/browser/media_galleries/fileapi/device_media_async_file_util.cc index aa1d98a..062b0ba 100644 --- a/chrome/browser/media_galleries/fileapi/device_media_async_file_util.cc +++ b/chrome/browser/media_galleries/fileapi/device_media_async_file_util.cc
@@ -14,7 +14,6 @@ #include "base/files/file_util.h" #include "base/memory/ptr_util.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "chrome/browser/media_galleries/fileapi/media_path_filter.h" #include "chrome/browser/media_galleries/fileapi/mtp_device_async_delegate.h" #include "chrome/browser/media_galleries/fileapi/mtp_device_map_service.h" @@ -171,8 +170,8 @@ media_task_runner); if (validate_media_files) { - base::PostTaskAndReplyWithResult( - media_task_runner, FROM_HERE, + media_task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&NativeMediaFileUtil::IsMediaFile, platform_path), base::BindOnce(&OnDidCheckMediaForCreateSnapshotFile, std::move(callback), file_info, file)); @@ -604,8 +603,8 @@ } scoped_refptr<base::SequencedTaskRunner> task_runner(context->task_runner()); - base::PostTaskAndReplyWithResult( - task_runner.get(), FROM_HERE, + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CreateSnapshotFileOnBlockingPool, profile_path_), base::BindOnce(&OnSnapshotFileCreatedRunTask, std::move(context), std::move(callback), url, validate_media_files())); @@ -687,8 +686,8 @@ return; } - base::PostTaskAndReplyWithResult( - task_runner, FROM_HERE, + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MediaPathFilterWrapper::CheckFilePath, media_path_filter_wrapper_, path), base::BindOnce(&OnDidCheckMediaForGetFileInfo, std::move(callback), @@ -706,8 +705,8 @@ return; } - base::PostTaskAndReplyWithResult( - task_runner, FROM_HERE, + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MediaPathFilterWrapper::FilterMediaEntries, media_path_filter_wrapper_, std::move(file_list)), base::BindOnce(&OnDidCheckMediaForReadDirectory, callback, has_more));
diff --git a/chrome/browser/media_galleries/fileapi/native_media_file_util.cc b/chrome/browser/media_galleries/fileapi/native_media_file_util.cc index 07eb554..c616133 100644 --- a/chrome/browser/media_galleries/fileapi/native_media_file_util.cc +++ b/chrome/browser/media_galleries/fileapi/native_media_file_util.cc
@@ -15,7 +15,6 @@ #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "chrome/browser/media_galleries/fileapi/media_path_filter.h" #include "components/services/filesystem/public/mojom/types.mojom.h" #include "content/public/browser/browser_task_traits.h" @@ -220,8 +219,8 @@ std::move(callback).Run(base::File(), base::OnceClosure()); return; } - base::PostTaskAndReplyWithResult( - media_task_runner, FROM_HERE, + media_task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&storage::NativeFileUtil::CreateOrOpen, platform_path, file_flags), base::BindOnce(&DidOpenSnapshot, std::move(callback), @@ -266,8 +265,8 @@ StatusCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); storage::FileSystemOperationContext* context_ptr = context.get(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&NativeMediaFileUtil::Core::CreateDirectory, base::Unretained(core_.get()), std::move(context), url, exclusive, recursive), @@ -333,8 +332,8 @@ StatusCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); storage::FileSystemOperationContext* context_ptr = context.get(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&NativeMediaFileUtil::Core::CopyOrMoveFileLocal, base::Unretained(core_.get()), std::move(context), src_url, dest_url, options, true /* copy */), @@ -350,8 +349,8 @@ StatusCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); storage::FileSystemOperationContext* context_ptr = context.get(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&NativeMediaFileUtil::Core::CopyOrMoveFileLocal, base::Unretained(core_.get()), std::move(context), src_url, dest_url, options, false /* copy */), @@ -366,8 +365,8 @@ StatusCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); storage::FileSystemOperationContext* context_ptr = context.get(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&NativeMediaFileUtil::Core::CopyInForeignFile, base::Unretained(core_.get()), std::move(context), src_file_path, dest_url), @@ -381,8 +380,8 @@ StatusCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); storage::FileSystemOperationContext* context_ptr = context.get(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&NativeMediaFileUtil::Core::DeleteFile, base::Unretained(core_.get()), std::move(context), url), std::move(callback)); @@ -396,8 +395,8 @@ StatusCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); storage::FileSystemOperationContext* context_ptr = context.get(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&NativeMediaFileUtil::Core::DeleteDirectory, base::Unretained(core_.get()), std::move(context), url), std::move(callback));
diff --git a/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win.cc b/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win.cc index 251fde80..310b77a 100644 --- a/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win.cc +++ b/chrome/browser/media_galleries/win/mtp_device_delegate_impl_win.cc
@@ -22,7 +22,6 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/threading/scoped_blocking_call.h" #include "chrome/browser/media_galleries/fileapi/media_file_system_backend.h" #include "chrome/browser/media_galleries/win/mtp_device_object_entry.h" @@ -530,9 +529,9 @@ if ((init_state_ == INITIALIZED) && !task_in_progress_) { DCHECK(pending_tasks_.empty()); DCHECK(!current_snapshot_details_.get()); - base::PostTaskAndReplyWithResult( - media_task_runner_.get(), task_info.location, std::move(task_info.task), - std::move(task_info.reply)); + media_task_runner_->PostTaskAndReplyWithResult(task_info.location, + std::move(task_info.task), + std::move(task_info.reply)); task_in_progress_ = true; return; } @@ -540,8 +539,8 @@ pending_tasks_.push(std::move(task_info)); if (init_state_ == UNINITIALIZED) { init_state_ = PENDING_INIT; - base::PostTaskAndReplyWithResult( - media_task_runner_.get(), FROM_HERE, + media_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&OpenDeviceOnBlockingPoolThread, storage_device_info_.pnp_device_id, storage_device_info_.registered_device_path), @@ -553,8 +552,8 @@ void MTPDeviceDelegateImplWin::WriteDataChunkIntoSnapshotFile() { DCHECK(current_snapshot_details_.get()); - base::PostTaskAndReplyWithResult( - media_task_runner_.get(), FROM_HERE, + media_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &WriteDataChunkIntoSnapshotFileOnBlockingPoolThread, current_snapshot_details_->file_info(), @@ -574,9 +573,9 @@ return; PendingTaskInfo& task_info = pending_tasks_.front(); task_in_progress_ = true; - base::PostTaskAndReplyWithResult(media_task_runner_.get(), task_info.location, - std::move(task_info.task), - std::move(task_info.reply)); + media_task_runner_->PostTaskAndReplyWithResult(task_info.location, + std::move(task_info.task), + std::move(task_info.reply)); pending_tasks_.pop(); }
diff --git a/chrome/browser/metrics/metrics_reporting_state.cc b/chrome/browser/metrics/metrics_reporting_state.cc index d324efc..e345d21 100644 --- a/chrome/browser/metrics/metrics_reporting_state.cc +++ b/chrome/browser/metrics/metrics_reporting_state.cc
@@ -8,7 +8,6 @@ #include "base/callback.h" #include "base/feature_list.h" #include "base/metrics/histogram_macros.h" -#include "base/task/task_runner_util.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" @@ -140,11 +139,11 @@ metrics::structured::NeutrinoDevicesLocation:: kChangeMetricsReportingStateWithReply); #endif // BUILDFLAG(IS_CHROMEOS_ASH) - base::PostTaskAndReplyWithResult( - GoogleUpdateSettings::CollectStatsConsentTaskRunner(), FROM_HERE, - base::BindOnce(&SetGoogleUpdateSettings, enabled), - base::BindOnce(&SetMetricsReporting, enabled, std::move(callback_fn), - called_from)); + GoogleUpdateSettings::CollectStatsConsentTaskRunner() + ->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SetGoogleUpdateSettings, enabled), + base::BindOnce(&SetMetricsReporting, enabled, std::move(callback_fn), + called_from)); } void UpdateMetricsPrefsOnPermissionChange(
diff --git a/chrome/browser/metrics/perf/perf_events_collector.cc b/chrome/browser/metrics/perf/perf_events_collector.cc index 3fa4c47..05d43e5 100644 --- a/chrome/browser/metrics/perf/perf_events_collector.cc +++ b/chrome/browser/metrics/perf/perf_events_collector.cc
@@ -149,7 +149,7 @@ // Collect precise=3 (:ppp) cycle events on microarchitectures and kernels that // support it. const char kPerfLBRCallgraphPPPCmd[] = - "-- record -a -e cycles:ppp -c 4000037 --call-graph lbr"; + "-- record -a -e cycles:ppp -c 6000011 --call-graph lbr"; const char kPerfCyclesPPPHGCmd[] = "-- record -a -e cycles:pppHG -c 1000003";
diff --git a/chrome/browser/metrics/perf/perf_events_collector_unittest.cc b/chrome/browser/metrics/perf/perf_events_collector_unittest.cc index 47dd711..3f196407 100644 --- a/chrome/browser/metrics/perf/perf_events_collector_unittest.cc +++ b/chrome/browser/metrics/perf/perf_events_collector_unittest.cc
@@ -44,7 +44,7 @@ const char kPerfFPCallgraphPPPHGCmd[] = "-- record -a -e cycles:pppHG -g -c 4000037"; const char kPerfLBRCallgraphPPPCmd[] = - "-- record -a -e cycles:ppp -c 4000037 --call-graph lbr"; + "-- record -a -e cycles:ppp -c 6000011 --call-graph lbr"; const char kPerfLBRCmd[] = "-- record -a -e r20c4 -b -c 800011"; const char kPerfLBRCmdAtom[] = "-- record -a -e rc4 -b -c 800011"; const char kPerfITLBMissCyclesCmdIvyBridge[] =
diff --git a/chrome/browser/notifications/notification_platform_bridge_linux.cc b/chrome/browser/notifications/notification_platform_bridge_linux.cc index 1fe1f27..309a3cf 100644 --- a/chrome/browser/notifications/notification_platform_bridge_linux.cc +++ b/chrome/browser/notifications/notification_platform_bridge_linux.cc
@@ -27,7 +27,6 @@ #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted_memory.h" -#include "base/metrics/histogram_macros.h" #include "base/strings/escape.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" @@ -80,17 +79,13 @@ const char kSignalNotificationReplied[] = "NotificationReplied"; // Capabilities. -const char kCapabilityActionIcons[] = "action-icons"; const char kCapabilityActions[] = "actions"; const char kCapabilityBody[] = "body"; const char kCapabilityBodyHyperlinks[] = "body-hyperlinks"; const char kCapabilityBodyImages[] = "body-images"; const char kCapabilityBodyMarkup[] = "body-markup"; -const char kCapabilityIconMulti[] = "icon-multi"; -const char kCapabilityIconStatic[] = "icon-static"; const char kCapabilityInlineReply[] = "inline-reply"; const char kCapabilityPersistence[] = "persistence"; -const char kCapabilitySound[] = "sound"; const char kCapabilityXKdeOriginName[] = "x-kde-origin-name"; const char kCapabilityXKdeReplyPlaceholderText[] = "x-kde-reply-placeholder-text"; @@ -533,7 +528,6 @@ for (const std::string& capability : capabilities) capabilities_.insert(capability); } - RecordMetricsForCapabilities(); if (!base::Contains(capabilities_, kCapabilityBody) || !base::Contains(capabilities_, kCapabilityActions)) { OnConnectionInitializationFinishedOnTaskRunner( @@ -1046,10 +1040,6 @@ void OnConnectionInitializationFinishedOnTaskRunner( ConnectionInitializationStatusCode status) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); - UMA_HISTOGRAM_ENUMERATION( - "Notifications.Linux.BridgeInitializationStatus", - static_cast<int>(status), - static_cast<int>(ConnectionInitializationStatusCode::NUM_ITEMS)); bool success = status == ConnectionInitializationStatusCode::SUCCESS; // Note: Not all code paths set connect_signals_in_progress_ to true! @@ -1092,37 +1082,6 @@ product_logo_file_watcher_.reset(); } - void RecordMetricsForCapabilities() { - // Histogram macros must be called with the same name for each - // callsite, so we can't roll the below into a nice loop. - UMA_HISTOGRAM_BOOLEAN( - "Notifications.Freedesktop.Capabilities.ActionIcons", - base::Contains(capabilities_, kCapabilityActionIcons)); - UMA_HISTOGRAM_BOOLEAN("Notifications.Freedesktop.Capabilities.Actions", - base::Contains(capabilities_, kCapabilityActions)); - UMA_HISTOGRAM_BOOLEAN("Notifications.Freedesktop.Capabilities.Body", - base::Contains(capabilities_, kCapabilityBody)); - UMA_HISTOGRAM_BOOLEAN( - "Notifications.Freedesktop.Capabilities.BodyHyperlinks", - 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.InlineReply", - base::Contains(capabilities_, kCapabilityInlineReply)); - UMA_HISTOGRAM_BOOLEAN( - "Notifications.Freedesktop.Capabilities.Persistence", - base::Contains(capabilities_, kCapabilityPersistence)); - UMA_HISTOGRAM_BOOLEAN("Notifications.Freedesktop.Capabilities.Sound", - base::Contains(capabilities_, kCapabilitySound)); - } - void RewriteProductLogoFile() { product_logo_file_watcher_.reset(); product_logo_file_ = WriteDataToTmpFile(product_logo_png_bytes_);
diff --git a/chrome/browser/offline_pages/android/offline_page_archive_publisher_impl.cc b/chrome/browser/offline_pages/android/offline_page_archive_publisher_impl.cc index a8a36b32..524249a 100644 --- a/chrome/browser/offline_pages/android/offline_page_archive_publisher_impl.cc +++ b/chrome/browser/offline_pages/android/offline_page_archive_publisher_impl.cc
@@ -16,7 +16,6 @@ #include "base/files/file_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "chrome/android/chrome_jni_headers/OfflinePageArchivePublisherBridge_jni.h" #include "chrome/browser/offline_pages/android/offline_page_bridge.h" #include "components/offline_pages/core/archive_manager.h" @@ -114,8 +113,8 @@ const OfflinePageItem& offline_page, const scoped_refptr<base::SequencedTaskRunner>& background_task_runner, PublishArchiveDoneCallback publish_done_callback) const { - base::PostTaskAndReplyWithResult( - background_task_runner.get(), FROM_HERE, + background_task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MoveAndRegisterArchive, offline_page, archive_manager_->GetPublicArchivesDir(), delegate_), base::BindOnce(std::move(publish_done_callback), offline_page));
diff --git a/chrome/browser/offline_pages/offline_page_request_handler.cc b/chrome/browser/offline_pages/offline_page_request_handler.cc index fa8144c..b7e936a 100644 --- a/chrome/browser/offline_pages/offline_page_request_handler.cc +++ b/chrome/browser/offline_pages/offline_page_request_handler.cc
@@ -16,7 +16,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" @@ -755,8 +754,8 @@ // Delegate to background task runner to finalize the hash to get the digest // since it is time consuming. Once it is done, |digest_finalized_callback| // will be called with the digest. - base::PostTaskAndReplyWithResult( - file_task_runner_.get(), FROM_HERE, + file_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ThreadSafeArchiveValidator::Finish, archive_validator_), std::move(digest_finalized_callback)); }
diff --git a/chrome/browser/password_manager/password_store_utils.cc b/chrome/browser/password_manager/password_store_utils.cc index 9615e75a..d0c188e 100644 --- a/chrome/browser/password_manager/password_store_utils.cc +++ b/chrome/browser/password_manager/password_store_utils.cc
@@ -99,19 +99,6 @@ } // namespace -password_manager::PasswordStoreInterface* GetPasswordStore( - Profile* profile, - bool use_account_store) { - if (use_account_store) { - return AccountPasswordStoreFactory::GetForProfile( - profile, ServiceAccessType::EXPLICIT_ACCESS) - .get(); - } - return PasswordStoreFactory::GetForProfile(profile, - ServiceAccessType::EXPLICIT_ACCESS) - .get(); -} - void DelayReportingPasswordStoreMetrics(Profile* profile) { profile->SetUserData(kPasswordStoreMetricsReporterKey, std::make_unique<StoreMetricReporterHelper>(profile));
diff --git a/chrome/browser/password_manager/password_store_utils.h b/chrome/browser/password_manager/password_store_utils.h index b1eb942d..13d85e6c 100644 --- a/chrome/browser/password_manager/password_store_utils.h +++ b/chrome/browser/password_manager/password_store_utils.h
@@ -9,17 +9,8 @@ #include "base/memory/scoped_refptr.h" -namespace password_manager { -class PasswordStoreInterface; -} - class Profile; -// Returns the password store associated with the currently active profile. -password_manager::PasswordStoreInterface* GetPasswordStore( - Profile* profile, - bool use_account_store); - // Query the password stores and reports multiple metrics. The actual reporting // is delayed by 30 seconds, to ensure it doesn't happen during the "hot phase" // of Chrome startup.
diff --git a/chrome/browser/performance_monitor/system_monitor.cc b/chrome/browser/performance_monitor/system_monitor.cc index 72970c42..54621fb 100644 --- a/chrome/browser/performance_monitor/system_monitor.cc +++ b/chrome/browser/performance_monitor/system_monitor.cc
@@ -11,7 +11,6 @@ #include "base/memory/ptr_util.h" #include "base/notreached.h" #include "base/observer_list.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "build/build_config.h" @@ -207,8 +206,8 @@ void SystemMonitor::RefreshCallback() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SystemMonitor::EvaluateMetrics, GetMetricsToEvaluate()), base::BindOnce(&SystemMonitor::NotifyObservers, weak_factory_.GetWeakPtr()));
diff --git a/chrome/browser/permissions/crowd_deny_preload_data.cc b/chrome/browser/permissions/crowd_deny_preload_data.cc index 77847f08..0f980ca1 100644 --- a/chrome/browser/permissions/crowd_deny_preload_data.cc +++ b/chrome/browser/permissions/crowd_deny_preload_data.cc
@@ -13,7 +13,6 @@ #include "base/location.h" #include "base/no_destructor.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "components/permissions/permission_uma_util.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" @@ -86,8 +85,8 @@ // On failure, LoadAndParseAndIndexPreloadDataFromDisk will return an empty // map. Replace the in-memory state with that regardless, so that the stale // old data will no longer be used. - base::PostTaskAndReplyWithResult( - loading_task_runner_.get(), FROM_HERE, + loading_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadAndParseAndIndexPreloadDataFromDisk, proto_path), base::BindOnce(&CrowdDenyPreloadData::SetSiteReputations, base::Unretained(this)));
diff --git a/chrome/browser/policy/browser_dm_token_storage_android_unittest.cc b/chrome/browser/policy/browser_dm_token_storage_android_unittest.cc index 9efc0358..f3ec2bd 100644 --- a/chrome/browser/policy/browser_dm_token_storage_android_unittest.cc +++ b/chrome/browser/policy/browser_dm_token_storage_android_unittest.cc
@@ -7,7 +7,6 @@ #include "base/bind.h" #include "base/location.h" #include "base/run_loop.h" -#include "base/task/task_runner_util.h" #include "chrome/browser/policy/android/cloud_management_shared_preferences.h" #include "components/policy/core/browser/browser_policy_connector_base.h" #include "components/policy/core/common/mock_policy_service.h" @@ -89,9 +88,8 @@ auto task = storage.SaveDMTokenTask(kDMToken, storage.InitClientId()); auto reply = base::BindOnce(&TestStoreDMTokenDelegate::OnDMTokenStored, base::Unretained(&callback_delegate)); - base::PostTaskAndReplyWithResult(storage.SaveDMTokenTaskRunner().get(), - FROM_HERE, std::move(task), - std::move(reply)); + storage.SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(task), std::move(reply)); run_loop.Run();
diff --git a/chrome/browser/policy/browser_dm_token_storage_linux_unittest.cc b/chrome/browser/policy/browser_dm_token_storage_linux_unittest.cc index 1a2b817..54a88b2 100644 --- a/chrome/browser/policy/browser_dm_token_storage_linux_unittest.cc +++ b/chrome/browser/policy/browser_dm_token_storage_linux_unittest.cc
@@ -13,7 +13,6 @@ #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/test/scoped_path_override.h" #include "chrome/common/chrome_paths.h" #include "content/public/test/browser_task_environment.h" @@ -157,9 +156,8 @@ storage_delegate.InitClientId()); auto reply = base::BindOnce(&TestStoreDMTokenDelegate::OnDMTokenUpdated, base::Unretained(&callback_delegate)); - base::PostTaskAndReplyWithResult( - storage_delegate.SaveDMTokenTaskRunner().get(), FROM_HERE, - std::move(task), std::move(reply)); + storage_delegate.SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(task), std::move(reply)); callback_delegate.Wait(); ASSERT_TRUE(callback_delegate.WasCalled()); @@ -205,9 +203,8 @@ auto delete_reply = base::BindOnce(&TestStoreDMTokenDelegate::OnDMTokenUpdated, base::Unretained(&delete_callback_delegate)); - base::PostTaskAndReplyWithResult( - storage_delegate.SaveDMTokenTaskRunner().get(), FROM_HERE, - std::move(delete_task), std::move(delete_reply)); + storage_delegate.SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(delete_task), std::move(delete_reply)); delete_callback_delegate.Wait(); ASSERT_TRUE(delete_callback_delegate.WasCalled()); @@ -239,9 +236,8 @@ auto delete_reply = base::BindOnce(&TestStoreDMTokenDelegate::OnDMTokenUpdated, base::Unretained(&callback_delegate)); - base::PostTaskAndReplyWithResult( - storage_delegate.SaveDMTokenTaskRunner().get(), FROM_HERE, - std::move(delete_task), std::move(delete_reply)); + storage_delegate.SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(delete_task), std::move(delete_reply)); callback_delegate.Wait(); ASSERT_TRUE(callback_delegate.WasCalled());
diff --git a/chrome/browser/policy/browser_dm_token_storage_mac_unittest.cc b/chrome/browser/policy/browser_dm_token_storage_mac_unittest.cc index 3bab661..5c28ce2 100644 --- a/chrome/browser/policy/browser_dm_token_storage_mac_unittest.cc +++ b/chrome/browser/policy/browser_dm_token_storage_mac_unittest.cc
@@ -16,7 +16,6 @@ #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/test/scoped_path_override.h" #include "chrome/common/chrome_paths.h" #include "content/public/test/browser_task_environment.h" @@ -87,9 +86,8 @@ storage_delegate.InitClientId()); auto reply = base::BindOnce(&TestStoreDMTokenDelegate::OnDMTokenUpdated, base::Unretained(&callback_delegate)); - base::PostTaskAndReplyWithResult( - storage_delegate.SaveDMTokenTaskRunner().get(), FROM_HERE, - std::move(task), std::move(reply)); + storage_delegate.SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(task), std::move(reply)); callback_delegate.Wait(); ASSERT_TRUE(callback_delegate.success()); @@ -138,9 +136,8 @@ auto delete_reply = base::BindOnce(&TestStoreDMTokenDelegate::OnDMTokenUpdated, base::Unretained(&delete_callback_delegate)); - base::PostTaskAndReplyWithResult( - storage_delegate.SaveDMTokenTaskRunner().get(), FROM_HERE, - std::move(delete_task), std::move(delete_reply)); + storage_delegate.SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(delete_task), std::move(delete_reply)); delete_callback_delegate.Wait(); ASSERT_TRUE(delete_callback_delegate.WasCalled()); @@ -174,9 +171,8 @@ auto delete_reply = base::BindOnce(&TestStoreDMTokenDelegate::OnDMTokenUpdated, base::Unretained(&callback_delegate)); - base::PostTaskAndReplyWithResult( - storage_delegate.SaveDMTokenTaskRunner().get(), FROM_HERE, - std::move(delete_task), std::move(delete_reply)); + storage_delegate.SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(delete_task), std::move(delete_reply)); callback_delegate.Wait(); ASSERT_TRUE(callback_delegate.WasCalled());
diff --git a/chrome/browser/profiles/delete_profile_helper.cc b/chrome/browser/profiles/delete_profile_helper.cc deleted file mode 100644 index ef3047b..0000000 --- a/chrome/browser/profiles/delete_profile_helper.cc +++ /dev/null
@@ -1,388 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/profiles/delete_profile_helper.h" - -#include "base/bind.h" -#include "base/feature_list.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/functional/callback.h" -#include "base/json/values_util.h" -#include "base/logging.h" -#include "base/task/thread_pool.h" -#include "chrome/browser/browser_features.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/download/download_core_service.h" -#include "chrome/browser/download/download_core_service_factory.h" -#include "chrome/browser/password_manager/password_store_factory.h" -#include "chrome/browser/profiles/nuke_profile_directory_utils.h" -#include "chrome/browser/profiles/profile_attributes_entry.h" -#include "chrome/browser/profiles/profile_attributes_storage.h" -#include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/profiles/profiles_state.h" -#include "chrome/browser/sync/sync_service_factory.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_finder.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/common/pref_names.h" -#include "components/keep_alive_registry/keep_alive_types.h" -#include "components/keep_alive_registry/scoped_keep_alive.h" -#include "components/password_manager/core/browser/password_store_interface.h" -#include "components/prefs/scoped_user_pref_update.h" -#include "components/sync/driver/sync_service.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" - -namespace { - -// Called after a deleted profile was checked and cleaned up. -void ProfileCleanedUp(base::Value profile_path_value) { - ScopedListPrefUpdate deleted_profiles(g_browser_process->local_state(), - prefs::kProfilesDeleted); - deleted_profiles->EraseValue(profile_path_value); -} - -// Helper function that deletes entries from the kProfilesLastActive pref list. -// It is called when every ephemeral profile is handled. -void RemoveFromLastActiveProfilesPrefList(const base::FilePath& path) { - PrefService* local_state = g_browser_process->local_state(); - DCHECK(local_state); - ScopedListPrefUpdate update(local_state, prefs::kProfilesLastActive); - base::Value::List& profile_list = update.Get(); - base::Value entry_value = base::Value(path.BaseName().AsUTF8Unsafe()); - profile_list.EraseValue(entry_value); -} - -bool IsRegisteredAsEphemeral(ProfileAttributesStorage* storage, - const base::FilePath& profile_dir) { - ProfileAttributesEntry* entry = - storage->GetProfileAttributesWithPath(profile_dir); - return entry && entry->IsEphemeral(); -} - -} // namespace - -DeleteProfileHelper::DeleteProfileHelper(ProfileManager& profile_manager) - : profile_manager_(profile_manager) {} - -DeleteProfileHelper::~DeleteProfileHelper() = default; - -void DeleteProfileHelper::MaybeScheduleProfileForDeletion( - const base::FilePath& profile_dir, - ProfileLoadedCallback callback, - ProfileMetrics::ProfileDelete deletion_source) { - if (!ScheduleProfileDirectoryForDeletion(profile_dir)) - return; - - ProfileAttributesStorage& storage = - profile_manager_->GetProfileAttributesStorage(); - ProfileAttributesEntry* entry = - storage.GetProfileAttributesWithPath(profile_dir); - if (entry) { - storage.RecordDeletedProfileState(entry); - } - ProfileMetrics::LogProfileDeleteUser(deletion_source); - - DCHECK(profiles::IsMultipleProfilesEnabled()); - DCHECK(!IsProfileDirectoryMarkedForDeletion(profile_dir)); - - Profile* profile = profile_manager_->GetProfileByPath(profile_dir); - if (profile) { -#if BUILDFLAG(IS_CHROMEOS_LACROS) - CHECK(!profile->IsMainProfile()); -#endif // BUILDFLAG(IS_CHROMEOS_LACROS) - // Cancel all in-progress downloads before deleting the profile to prevent a - // "Do you want to exit Google Chrome and cancel the downloads?" prompt - // (crbug.com/336725). - DownloadCoreService* service = - DownloadCoreServiceFactory::GetForBrowserContext(profile); - service->CancelDownloads(); - DCHECK_EQ(0, service->NonMaliciousDownloadCount()); - - // Close all browser windows before deleting the profile. If the user - // cancels the closing of any tab in an OnBeforeUnload event, profile - // deletion is also cancelled. (crbug.com/289390) - BrowserList::CloseAllBrowsersWithProfile( - profile, - base::BindRepeating( - &DeleteProfileHelper::EnsureActiveProfileExistsBeforeDeletion, - base::Unretained(this), base::Passed(std::move(callback))), - base::BindRepeating(&CancelProfileDeletion), false); - } else { - EnsureActiveProfileExistsBeforeDeletion(std::move(callback), profile_dir); - } -} - -void DeleteProfileHelper::ScheduleEphemeralProfileForDeletion( - const base::FilePath& profile_dir) { - DCHECK(IsRegisteredAsEphemeral( - &profile_manager_->GetProfileAttributesStorage(), profile_dir)); - DCHECK_EQ(0u, chrome::GetBrowserCount( - profile_manager_->GetProfileByPath(profile_dir))); - absl::optional<base::FilePath> new_active_profile_dir = - profile_manager_->FindLastActiveProfile(base::BindRepeating( - [](const base::FilePath& profile_dir, ProfileAttributesEntry* entry) { - return entry->GetPath() != profile_dir; - }, - profile_dir)); - if (!new_active_profile_dir.has_value()) - new_active_profile_dir = - profile_manager_->GenerateNextProfileDirectoryPath(); - DCHECK(!new_active_profile_dir->empty()); - RemoveFromLastActiveProfilesPrefList(profile_dir); - - FinishDeletingProfile(profile_dir, new_active_profile_dir.value()); -} - -void DeleteProfileHelper::CleanUpEphemeralProfiles() { - base::FilePath last_used_profile_base_name = - profile_manager_->GetLastUsedProfileBaseName(); - bool last_active_profile_deleted = false; - base::FilePath new_profile_path; - std::vector<base::FilePath> profiles_to_delete; - ProfileAttributesStorage& storage = - profile_manager_->GetProfileAttributesStorage(); - std::vector<ProfileAttributesEntry*> entries = - storage.GetAllProfilesAttributes(); - for (ProfileAttributesEntry* entry : entries) { - base::FilePath profile_path = entry->GetPath(); - if (entry->IsEphemeral()) { - profiles_to_delete.push_back(profile_path); - RemoveFromLastActiveProfilesPrefList(profile_path); - if (profile_path.BaseName() == last_used_profile_base_name) - last_active_profile_deleted = true; - } else if (new_profile_path.empty()) { - new_profile_path = profile_path; - } - } - - // If the last active profile was ephemeral or all profiles are deleted due to - // ephemeral, set a new one. - if (last_active_profile_deleted || - (entries.size() == profiles_to_delete.size() && - !profiles_to_delete.empty())) { - if (new_profile_path.empty()) - new_profile_path = profile_manager_->GenerateNextProfileDirectoryPath(); - - profiles::SetLastUsedProfile(new_profile_path.BaseName()); - } - - for (const base::FilePath& profile_path : profiles_to_delete) { - base::ThreadPool::PostTask( - FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, - base::BindOnce(&NukeProfileFromDisk, profile_path, - base::OnceClosure())); - - storage.RemoveProfile(profile_path); - } -} - -void DeleteProfileHelper::CleanUpDeletedProfiles() { - PrefService* local_state = g_browser_process->local_state(); - DCHECK(local_state); - const base::Value::List& deleted_profiles = - local_state->GetList(prefs::kProfilesDeleted); - - for (const base::Value& value : deleted_profiles) { - absl::optional<base::FilePath> profile_path = base::ValueToFilePath(value); - // Although it should never happen, make sure this is a valid path in the - // user_data_dir, so we don't accidentally delete something else. - if (profile_path && profile_manager_->IsAllowedProfilePath(*profile_path)) { - if (base::PathExists(*profile_path)) { - LOG(WARNING) << "Files of a deleted profile still exist after restart. " - "Cleaning up now."; - base::ThreadPool::PostTask( - FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, - base::BindOnce(&NukeProfileFromDisk, *profile_path, - base::BindOnce(&ProfileCleanedUp, value.Clone()))); - } else { - // Everything is fine, the profile was removed on shutdown. - content::GetUIThreadTaskRunner({})->PostTask( - FROM_HERE, base::BindOnce(&ProfileCleanedUp, value.Clone())); - } - } else { - LOG(ERROR) << "Found invalid profile path in deleted_profiles: " - << profile_path->AsUTF8Unsafe(); - NOTREACHED(); - } - } -} - -void DeleteProfileHelper::EnsureActiveProfileExistsBeforeDeletion( - ProfileLoadedCallback callback, - const base::FilePath& profile_dir) { - // In case we delete non-active profile and current profile is valid, proceed. - const base::FilePath last_used_profile_path = - profile_manager_->GetLastUsedProfileDir(); - const base::FilePath guest_profile_path = - profile_manager_->GetGuestProfilePath(); - Profile* last_used_profile = - profile_manager_->GetProfileByPath(last_used_profile_path); - if (last_used_profile_path != profile_dir && - last_used_profile_path != guest_profile_path && last_used_profile) { - FinishDeletingProfile(profile_dir, last_used_profile_path); - return; - } - - // Search for an active browser and use its profile as active if possible. - for (Browser* browser : *BrowserList::GetInstance()) { - Profile* profile = browser->profile(); - base::FilePath cur_path = profile->GetPath(); - if (cur_path != profile_dir && cur_path != guest_profile_path && - !IsProfileDirectoryMarkedForDeletion(cur_path)) { - OnNewActiveProfileInitialized(profile_dir, cur_path, std::move(callback), - nullptr, profile); - return; - } - } - - // There no valid browsers to fallback, search for any existing valid profile. - ProfileAttributesStorage& storage = - profile_manager_->GetProfileAttributesStorage(); - base::FilePath fallback_profile_path; - std::vector<ProfileAttributesEntry*> entries = - storage.GetAllProfilesAttributes(); - for (ProfileAttributesEntry* entry : entries) { - base::FilePath cur_path = entry->GetPath(); - // Make sure that this profile is not pending deletion. - if (cur_path != profile_dir && cur_path != guest_profile_path && - !IsProfileDirectoryMarkedForDeletion(cur_path)) { - fallback_profile_path = cur_path; - break; - } - } - - // If we're deleting the last profile, then create a new profile in its place. - // Load existing profile otherwise. - if (fallback_profile_path.empty()) { - fallback_profile_path = - profile_manager_->GenerateNextProfileDirectoryPath(); - // A new profile about to be created. - ProfileMetrics::LogProfileAddNewUser( - ProfileMetrics::ADD_NEW_USER_LAST_DELETED); - } - - // When this is called all browser windows may be about to be destroyed - // (but still exist in BrowserList), which means shutdown may be about to - // start. Use a KeepAlive to ensure shutdown doesn't start. - std::unique_ptr<ScopedKeepAlive> keep_alive = - std::make_unique<ScopedKeepAlive>(KeepAliveOrigin::PROFILE_MANAGER, - KeepAliveRestartOption::DISABLED); - // Create and/or load fallback profile. - profile_manager_->CreateProfileAsync( - fallback_profile_path, - base::BindOnce(&DeleteProfileHelper::OnNewActiveProfileInitialized, - base::Unretained(this), profile_dir, fallback_profile_path, - std::move(callback), std::move(keep_alive))); -} - -void DeleteProfileHelper::FinishDeletingProfile( - const base::FilePath& profile_dir, - const base::FilePath& new_active_profile_dir) { - // Update the last used profile pref before closing browser windows. This - // way the correct last used profile is set for any notification observers. - profiles::SetLastUsedProfile(new_active_profile_dir.BaseName()); - - // Attempt to load the profile before deleting it to properly clean up - // profile-specific data stored outside the profile directory. - profile_manager_->LoadProfileByPath( - profile_dir, false, - base::BindOnce(&DeleteProfileHelper::OnLoadProfileForProfileDeletion, - base::Unretained(this), profile_dir)); - if (!IsProfileDirectoryMarkedForDeletion(profile_dir)) { - // Prevents CreateProfileAsync from re-creating the profile. - MarkProfileDirectoryForDeletion(profile_dir); - } -} - -void DeleteProfileHelper::OnLoadProfileForProfileDeletion( - const base::FilePath& profile_dir, - Profile* profile) { - ProfileAttributesStorage& storage = - profile_manager_->GetProfileAttributesStorage(); - - if (!IsProfileDirectoryMarkedForDeletion(profile_dir)) { - // Ensure RemoveProfile() knows to nuke the profile directory after it's - // done. - MarkProfileDirectoryForDeletion(profile_dir); - } - - if (profile) { - // TODO(estade): Migrate additional code in this block to observe - // ProfileManager instead of handling shutdown here. - profile_manager_->NotifyOnProfileMarkedForPermanentDeletion(profile); - - // Disable sync for doomed profile. - if (SyncServiceFactory::HasSyncService(profile)) { - syncer::SyncService* sync_service = - SyncServiceFactory::GetForProfile(profile); - // Ensure data is cleared even if sync was already off. - sync_service->StopAndClear(); - } - - // Some platforms store passwords in keychains. They should be removed. - scoped_refptr<password_manager::PasswordStoreInterface> password_store = - PasswordStoreFactory::GetForProfile(profile, - ServiceAccessType::EXPLICIT_ACCESS) - .get(); - if (password_store.get()) { - password_store->RemoveLoginsCreatedBetween(base::Time(), - base::Time::Max()); - } - - // The Profile Data doesn't get wiped until Chrome closes. Since we promised - // that the user's data would be removed, do so immediately. - // - // With DestroyProfileOnBrowserClose, this adds a KeepAlive. So the Profile* - // only gets deleted *after* browsing data is removed. This also clears some - // keepalives in the process, e.g. due to background extensions getting - // uninstalled. - profiles::RemoveBrowsingDataForProfile(profile_dir); - - // Clean-up pref data that won't be cleaned up by deleting the profile dir. - profile->GetPrefs()->OnStoreDeletionFromDisk(); - - } else { - // We failed to load the profile, but it's safe to delete a not yet loaded - // Profile from disk. - base::ThreadPool::PostTask( - FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, - base::BindOnce(&NukeProfileFromDisk, profile_dir, base::OnceClosure())); - } - - storage.RemoveProfile(profile_dir); - - if (profile && - base::FeatureList::IsEnabled(features::kDestroyProfileOnBrowserClose)) { - // Allow the Profile* to be deleted, even if it had no browser windows. - profile_manager_->ClearFirstBrowserWindowKeepAlive(profile); - } -} - -void DeleteProfileHelper::OnNewActiveProfileInitialized( - const base::FilePath& profile_to_delete_path, - const base::FilePath& new_active_profile_path, - ProfileLoadedCallback callback, - std::unique_ptr<ScopedKeepAlive> keep_alive, - Profile* loaded_profile) { - DCHECK(loaded_profile); - if (IsProfileDirectoryMarkedForDeletion(new_active_profile_path)) { - // If the profile we tried to load as the next active profile has been - // deleted, then retry deleting this profile to redo the logic to load - // the next available profile. - EnsureActiveProfileExistsBeforeDeletion(std::move(callback), - profile_to_delete_path); - return; - } - - FinishDeletingProfile(profile_to_delete_path, new_active_profile_path); - std::move(callback).Run(loaded_profile); -}
diff --git a/chrome/browser/profiles/delete_profile_helper.h b/chrome/browser/profiles/delete_profile_helper.h deleted file mode 100644 index e7d097bd..0000000 --- a/chrome/browser/profiles/delete_profile_helper.h +++ /dev/null
@@ -1,93 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_PROFILES_DELETE_PROFILE_HELPER_H_ -#define CHROME_BROWSER_PROFILES_DELETE_PROFILE_HELPER_H_ - -#include "base/functional/callback_forward.h" -#include "base/memory/raw_ref.h" -#include "chrome/browser/profiles/profile_metrics.h" -#include "third_party/abseil-cpp/absl/types/optional.h" - -namespace base { -class FilePath; -} - -class Profile; -class ProfileManager; -class ScopedKeepAlive; - -// This class offers a few helper functions for profile deletion. Note that the -// `DeleteProfileHelper` does not delete actual C++ Profile objects, as this is -// done through the `ScopedProfileKeepAlive` mechanism and -// `ProfileManager::RemoveProfile()`. -// The `DeleteProfileHelper` is responsible for: -// - deleting the profile as a user-visible concept: removes it from the -// `ProfileAttributesStorage` and deletes the user data on disk. -// - creates or loads another profile before the last profile is deleted. -class DeleteProfileHelper { - public: - using ProfileLoadedCallback = base::OnceCallback<void(Profile*)>; - - explicit DeleteProfileHelper(ProfileManager& profile_manager); - - ~DeleteProfileHelper(); - - DeleteProfileHelper(const DeleteProfileHelper&) = delete; - DeleteProfileHelper& operator=(const DeleteProfileHelper&) = delete; - - // Schedules the profile at the given path to be deleted on shutdown. If we're - // deleting the last profile, a new one will be created in its place, and in - // that case the callback will be called when profile creation is complete. - // Silently exits if profile is either scheduling or marked for deletion. - void MaybeScheduleProfileForDeletion( - const base::FilePath& profile_dir, - ProfileLoadedCallback callback, - ProfileMetrics::ProfileDelete deletion_source); - - // Schedules the ephemeral profile at the given path to be deleted on - // shutdown. New profiles will not be created. - void ScheduleEphemeralProfileForDeletion(const base::FilePath& profile_dir); - - // Checks if any ephemeral profiles are left behind (e.g. because of a browser - // crash) and schedule them for deletion. - void CleanUpEphemeralProfiles(); - - // Checks if files of deleted profiles are left behind (e.g. because of a - // browser crash) and delete them in case they still exist. - void CleanUpDeletedProfiles(); - - private: - // Continues the scheduled profile deletion after closing all the profile's - // browsers tabs. Creates a new profile if the profile to be deleted is the - // last non-supervised profile. In the Mac, loads the next non-supervised - // profile if the profile to be deleted is the active profile. - void EnsureActiveProfileExistsBeforeDeletion( - ProfileLoadedCallback callback, - const base::FilePath& profile_dir); - - // Schedules the profile at the given path to be deleted on shutdown, - // and marks the new profile as active. - void FinishDeletingProfile(const base::FilePath& profile_dir, - const base::FilePath& new_active_profile_dir); - void OnLoadProfileForProfileDeletion(const base::FilePath& profile_dir, - Profile* profile); - - // If the `loaded_profile` has been loaded successfully and isn't already - // scheduled for deletion, then finishes adding `profile_to_delete_dir` to the - // queue of profiles to be deleted, and updates the kProfileLastUsed - // preference based on `last_non_supervised_profile_path`. `keep_alive` may be - // null and is used to ensure shutdown does not start. - void OnNewActiveProfileInitialized( - const base::FilePath& profile_to_delete_path, - const base::FilePath& last_non_supervised_profile_path, - ProfileLoadedCallback callback, - std::unique_ptr<ScopedKeepAlive> keep_alive, - Profile* loaded_profile); - - const raw_ref<ProfileManager> - profile_manager_; // Owns the `DeleteProfileHelper`. -}; - -#endif // CHROME_BROWSER_PROFILES_DELETE_PROFILE_HELPER_H_
diff --git a/chrome/browser/profiles/nuke_profile_directory_utils.cc b/chrome/browser/profiles/nuke_profile_directory_utils.cc deleted file mode 100644 index 7f947f3..0000000 --- a/chrome/browser/profiles/nuke_profile_directory_utils.cc +++ /dev/null
@@ -1,163 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/profiles/nuke_profile_directory_utils.h" - -#include <map> - -#include "base/check_op.h" -#include "base/containers/contains.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/json/values_util.h" -#include "base/metrics/histogram_functions.h" -#include "base/no_destructor.h" -#include "base/task/thread_pool.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/profile_metrics.h" -#include "chrome/common/chrome_paths_internal.h" -#include "chrome/common/pref_names.h" -#include "components/prefs/scoped_user_pref_update.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" - -namespace { - -// Used in metrics for NukeProfileFromDisk(). Keep in sync with enums.xml. -// -// Entries should not be renumbered and numeric values should never be reused. -// -// Note: there are maximum 3 attempts to nuke a profile. -enum class NukeProfileResult { - // Success values. Make sure they are consecutive. - kSuccessFirstAttempt = 0, - kSuccessSecondAttempt = 1, - kSuccessThirdAttempt = 2, - - // Failure values. Make sure they are consecutive. - kFailureFirstAttempt = 10, - kFailureSecondAttempt = 11, - kFailureThirdAttempt = 12, - kMaxValue = kFailureThirdAttempt, -}; - -const size_t kNukeProfileMaxRetryCount = 3; - -// Profile deletion can pass through two stages: -enum class ProfileDeletionStage { - // At SCHEDULING stage some actions are made before profile deletion, - // where one of them is the closure of browser windows. Deletion is cancelled - // if the user choose explicitly not to close any of the tabs. - SCHEDULING, - // At MARKED stage profile can be safely removed from disk. - MARKED -}; - -using ProfileDeletionMap = std::map<base::FilePath, ProfileDeletionStage>; -ProfileDeletionMap& ProfilesToDelete() { - static base::NoDestructor<ProfileDeletionMap> profiles_to_delete; - return *profiles_to_delete; -} - -NukeProfileResult GetNukeProfileResult(size_t retry_count, bool success) { - DCHECK_LT(retry_count, kNukeProfileMaxRetryCount); - const size_t value = - retry_count + - static_cast<size_t>(success ? NukeProfileResult::kSuccessFirstAttempt - : NukeProfileResult::kFailureFirstAttempt); - DCHECK_LE(value, static_cast<size_t>(NukeProfileResult::kMaxValue)); - return static_cast<NukeProfileResult>(value); -} - -// Implementation of NukeProfileFromDisk(), retrying at most |max_retry_count| -// times on failure. |retry_count| (initially 0) keeps track of the -// number of attempts so far. -void NukeProfileFromDiskImpl(const base::FilePath& profile_path, - size_t retry_count, - size_t max_retry_count, - base::OnceClosure done_callback) { - // TODO(crbug.com/1191455): Make FileSystemProxy/FileSystemImpl expose its - // LockTable, and/or fire events when locks are released. That way we could - // wait for all the locks in |profile_path| to be released, rather than having - // this retry logic. - const base::TimeDelta kRetryDelay = base::Seconds(1); - - // Delete both the profile directory and its corresponding cache. - base::FilePath cache_path; - chrome::GetUserCacheDirectory(profile_path, &cache_path); - - bool success = base::DeletePathRecursively(profile_path); - success = base::DeletePathRecursively(cache_path) && success; - - base::UmaHistogramEnumeration("Profile.NukeFromDisk.Result", - GetNukeProfileResult(retry_count, success)); - - if (!success && retry_count < max_retry_count - 1) { - // Failed, try again in |kRetryDelay| seconds. - base::ThreadPool::PostDelayedTask( - FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, - base::BindOnce(&NukeProfileFromDiskImpl, profile_path, retry_count + 1, - max_retry_count, std::move(done_callback)), - kRetryDelay); - return; - } - - if (done_callback) { - content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, - std::move(done_callback)); - } -} - -} // namespace - -void NukeDeletedProfilesFromDisk() { - for (const auto& item : ProfilesToDelete()) { - if (item.second == ProfileDeletionStage::MARKED) { - NukeProfileFromDiskImpl(item.first, /*retry_count=*/0, - /*max_retry_count=*/1, base::OnceClosure()); - } - } - ProfilesToDelete().clear(); -} - -void NukeProfileFromDisk(const base::FilePath& profile_path, - base::OnceClosure done_callback) { - NukeProfileFromDiskImpl(profile_path, /*retry_count=*/0, - kNukeProfileMaxRetryCount, std::move(done_callback)); -} - -bool IsProfileDirectoryMarkedForDeletion(const base::FilePath& profile_path) { - const auto it = ProfilesToDelete().find(profile_path); - return it != ProfilesToDelete().end() && - it->second == ProfileDeletionStage::MARKED; -} - -void CancelProfileDeletion(const base::FilePath& path) { - DCHECK(!base::Contains(ProfilesToDelete(), path) || - ProfilesToDelete()[path] == ProfileDeletionStage::SCHEDULING); - ProfilesToDelete().erase(path); - ProfileMetrics::LogProfileDeleteUser(ProfileMetrics::DELETE_PROFILE_ABORTED); -} - -// Schedule a profile for deletion if it isn't already scheduled. -// Returns whether the profile has been newly scheduled. -bool ScheduleProfileDirectoryForDeletion(const base::FilePath& path) { - if (base::Contains(ProfilesToDelete(), path)) - return false; - ProfilesToDelete()[path] = ProfileDeletionStage::SCHEDULING; - return true; -} - -void MarkProfileDirectoryForDeletion(const base::FilePath& path) { - DCHECK(!base::Contains(ProfilesToDelete(), path) || - ProfilesToDelete()[path] == ProfileDeletionStage::SCHEDULING); - ProfilesToDelete()[path] = ProfileDeletionStage::MARKED; - // Remember that this profile was deleted and files should have been deleted - // on shutdown. In case of a crash remaining files are removed on next start. - ScopedListPrefUpdate deleted_profiles(g_browser_process->local_state(), - prefs::kProfilesDeleted); - deleted_profiles->Append(base::FilePathToValue(path)); -}
diff --git a/chrome/browser/profiles/nuke_profile_directory_utils.h b/chrome/browser/profiles/nuke_profile_directory_utils.h deleted file mode 100644 index 3719ad6..0000000 --- a/chrome/browser/profiles/nuke_profile_directory_utils.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_PROFILES_NUKE_PROFILE_DIRECTORY_UTILS_H_ -#define CHROME_BROWSER_PROFILES_NUKE_PROFILE_DIRECTORY_UTILS_H_ - -#include "base/functional/callback_forward.h" - -namespace base { -class FilePath; -} - -// Physically remove deleted profile directories from disk. -void NukeDeletedProfilesFromDisk(); - -// Physically remove deleted profile directories from disk. Afterwards, calls -// |done_callback| on the UI thread. -void NukeProfileFromDisk(const base::FilePath& profile_path, - base::OnceClosure done_callback); - -// Returns if profile is marked for deletion. -bool IsProfileDirectoryMarkedForDeletion(const base::FilePath& profile_path); - -// Cancel a scheduling deletion, so ScheduleProfileDirectoryForDeletion can be -// called again successfully. -void CancelProfileDeletion(const base::FilePath& path); - -// Schedule a profile for deletion if it isn't already scheduled. -// Returns whether the profile has been newly scheduled. -bool ScheduleProfileDirectoryForDeletion(const base::FilePath& path); - -// Marks the profile path for deletion. It will be deleted when -// `NukeDeletedProfilesFromDisk()` is called. -void MarkProfileDirectoryForDeletion(const base::FilePath& path); - -#endif // CHROME_BROWSER_PROFILES_NUKE_PROFILE_DIRECTORY_UTILS_H_
diff --git a/chrome/browser/profiles/profile_attributes_storage.cc b/chrome/browser/profiles/profile_attributes_storage.cc index 6af9aa7..871d62d 100644 --- a/chrome/browser/profiles/profile_attributes_storage.cc +++ b/chrome/browser/profiles/profile_attributes_storage.cc
@@ -21,7 +21,6 @@ #include "base/ranges/algorithm.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/values.h" @@ -599,9 +598,8 @@ return nullptr; cached_avatar_images_loading_[key] = true; - base::PostTaskAndReplyWithResult( - file_task_runner_.get(), FROM_HERE, - base::BindOnce(&ReadBitmap, image_path), + file_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadBitmap, image_path), base::BindOnce(&ProfileAttributesStorage::OnAvatarPictureLoaded, const_cast<ProfileAttributesStorage*>(this)->AsWeakPtr(), profile_path, key)); @@ -845,9 +843,8 @@ if (data->empty()) { LOG(ERROR) << "Failed to PNG encode the image."; } else { - base::PostTaskAndReplyWithResult( - file_task_runner_.get(), FROM_HERE, - base::BindOnce(&SaveBitmap, std::move(data), image_path), + file_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SaveBitmap, std::move(data), image_path), base::BindOnce(&ProfileAttributesStorage::OnAvatarPictureSaved, AsWeakPtr(), key, profile_path, std::move(callback))); }
diff --git a/chrome/browser/profiles/profile_manager.cc b/chrome/browser/profiles/profile_manager.cc index 1964c9f7..fc3709fc 100644 --- a/chrome/browser/profiles/profile_manager.cc +++ b/chrome/browser/profiles/profile_manager.cc
@@ -25,11 +25,14 @@ #include "base/json/values_util.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" +#include "base/metrics/user_metrics.h" +#include "base/no_destructor.h" #include "base/observer_list.h" #include "base/ranges/algorithm.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/task/deferred_sequenced_task_runner.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/trace_event/trace_event.h" @@ -37,20 +40,24 @@ #include "build/chromeos_buildflags.h" #include "chrome/browser/accessibility/accessibility_labels_service.h" #include "chrome/browser/accessibility/accessibility_labels_service_factory.h" +#include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/browser_features.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browsing_data/chrome_browsing_data_lifetime_manager.h" #include "chrome/browser/browsing_data/chrome_browsing_data_lifetime_manager_factory.h" #include "chrome/browser/buildflags.h" #include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "chrome/browser/download/download_core_service.h" +#include "chrome/browser/download/download_core_service_factory.h" #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/navigation_predictor/navigation_predictor_keyed_service_factory.h" +#include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/permissions/adaptive_quiet_notification_permission_ui_enabler.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" -#include "chrome/browser/profiles/delete_profile_helper.h" +#include "chrome/browser/profiles/bookmark_model_loaded_observer.h" #include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h" -#include "chrome/browser/profiles/nuke_profile_directory_utils.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_init_params.h" #include "chrome/browser/profiles/profile_attributes_storage.h" @@ -58,25 +65,31 @@ #include "chrome/browser/profiles/profile_destroyer.h" #include "chrome/browser/profiles/profile_key.h" #include "chrome/browser/profiles/profile_manager_observer.h" +#include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_selections.h" #include "chrome/browser/profiles/profiles_state.h" #include "chrome/browser/signin/account_reconcilor_factory.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/primary_account_policy_manager_factory.h" #include "chrome/browser/signin/signin_util.h" +#include "chrome/browser/sync/sync_service_factory.h" +#include "chrome/browser/ui/startup/startup_browser_creator.h" #include "chrome/browser/ui/sync/sync_promo_ui.h" #include "chrome/browser/unified_consent/unified_consent_service_factory.h" #include "chrome/common/buildflags.h" #include "chrome/common/chrome_constants.h" +#include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "components/account_id/account_id.h" +#include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/common/bookmark_pref_names.h" #include "components/browsing_data/core/pref_names.h" #include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/password_manager/core/browser/password_store_interface.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/search_engines/default_search_manager.h" @@ -87,6 +100,7 @@ #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" #include "components/sync/base/stop_source.h" +#include "components/sync/driver/sync_service.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" @@ -123,6 +137,8 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" +#include "components/keep_alive_registry/keep_alive_types.h" +#include "components/keep_alive_registry/scoped_keep_alive.h" #include "components/live_caption/live_caption_controller.h" #endif @@ -162,10 +178,46 @@ #include "chrome/browser/chromeos/extensions/contact_center_insights/contact_center_insights_extension_manager.h" #endif +using base::UserMetricsAction; using content::BrowserThread; namespace { +// Used in metrics for NukeProfileFromDisk(). Keep in sync with enums.xml. +// +// Entries should not be renumbered and numeric values should never be reused. +// +// Note: there are maximum 3 attempts to nuke a profile. +enum class NukeProfileResult { + // Success values. Make sure they are consecutive. + kSuccessFirstAttempt = 0, + kSuccessSecondAttempt = 1, + kSuccessThirdAttempt = 2, + + // Failure values. Make sure they are consecutive. + kFailureFirstAttempt = 10, + kFailureSecondAttempt = 11, + kFailureThirdAttempt = 12, + kMaxValue = kFailureThirdAttempt, +}; + +const size_t kNukeProfileMaxRetryCount = 3; + +// Profile deletion can pass through two stages: +enum class ProfileDeletionStage { + // At SCHEDULING stage some actions are made before profile deletion, + // where one of them is the closure of browser windows. Deletion is cancelled + // if the user choose explicitly not to close any of the tabs. + SCHEDULING, + // At MARKED stage profile can be safely removed from disk. + MARKED +}; +using ProfileDeletionMap = std::map<base::FilePath, ProfileDeletionStage>; +ProfileDeletionMap& ProfilesToDelete() { + static base::NoDestructor<ProfileDeletionMap> profiles_to_delete; + return *profiles_to_delete; +} + int64_t ComputeFilesSize(const base::FilePath& directory, const base::FilePath::StringType& pattern) { int64_t running_size = 0; @@ -227,6 +279,103 @@ UMA_HISTOGRAM_COUNTS_10000("Profile.AppCount", enabled_app_count); } +#if !BUILDFLAG(IS_ANDROID) +// Schedule a profile for deletion if it isn't already scheduled. +// Returns whether the profile has been newly scheduled. +bool ScheduleProfileDirectoryForDeletion(const base::FilePath& path) { + if (base::Contains(ProfilesToDelete(), path)) + return false; + ProfilesToDelete()[path] = ProfileDeletionStage::SCHEDULING; + return true; +} + +void MarkProfileDirectoryForDeletion(const base::FilePath& path) { + DCHECK(!base::Contains(ProfilesToDelete(), path) || + ProfilesToDelete()[path] == ProfileDeletionStage::SCHEDULING); + ProfilesToDelete()[path] = ProfileDeletionStage::MARKED; + // Remember that this profile was deleted and files should have been deleted + // on shutdown. In case of a crash remaining files are removed on next start. + ScopedListPrefUpdate deleted_profiles(g_browser_process->local_state(), + prefs::kProfilesDeleted); + deleted_profiles->Append(base::FilePathToValue(path)); +} + +// Cancel a scheduling deletion, so ScheduleProfileDirectoryForDeletion can be +// called again successfully. +void CancelProfileDeletion(const base::FilePath& path) { + DCHECK(!base::Contains(ProfilesToDelete(), path) || + ProfilesToDelete()[path] == ProfileDeletionStage::SCHEDULING); + ProfilesToDelete().erase(path); + ProfileMetrics::LogProfileDeleteUser(ProfileMetrics::DELETE_PROFILE_ABORTED); +} +#endif + +NukeProfileResult GetNukeProfileResult(size_t retry_count, bool success) { + DCHECK_LT(retry_count, kNukeProfileMaxRetryCount); + const size_t value = + retry_count + + static_cast<size_t>(success ? NukeProfileResult::kSuccessFirstAttempt + : NukeProfileResult::kFailureFirstAttempt); + DCHECK_LE(value, static_cast<size_t>(NukeProfileResult::kMaxValue)); + return static_cast<NukeProfileResult>(value); +} + +// Implementation of NukeProfileFromDisk(), retrying at most |max_retry_count| +// times on failure. |retry_count| (initially 0) keeps track of the +// number of attempts so far. +void NukeProfileFromDiskImpl(const base::FilePath& profile_path, + size_t retry_count, + size_t max_retry_count, + base::OnceClosure done_callback) { + // TODO(crbug.com/1191455): Make FileSystemProxy/FileSystemImpl expose its + // LockTable, and/or fire events when locks are released. That way we could + // wait for all the locks in |profile_path| to be released, rather than having + // this retry logic. + const base::TimeDelta kRetryDelay = base::Seconds(1); + + // Delete both the profile directory and its corresponding cache. + base::FilePath cache_path; + chrome::GetUserCacheDirectory(profile_path, &cache_path); + + bool success = base::DeletePathRecursively(profile_path); + success = base::DeletePathRecursively(cache_path) && success; + + base::UmaHistogramEnumeration("Profile.NukeFromDisk.Result", + GetNukeProfileResult(retry_count, success)); + + if (!success && retry_count < max_retry_count - 1) { + // Failed, try again in |kRetryDelay| seconds. + base::ThreadPool::PostDelayedTask( + FROM_HERE, + {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + base::BindOnce(&NukeProfileFromDiskImpl, profile_path, retry_count + 1, + max_retry_count, std::move(done_callback)), + kRetryDelay); + return; + } + + if (done_callback) { + content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, + std::move(done_callback)); + } +} + +// Physically remove deleted profile directories from disk. Afterwards, calls +// |done_callback| on the UI thread. +void NukeProfileFromDisk(const base::FilePath& profile_path, + base::OnceClosure done_callback) { + NukeProfileFromDiskImpl(profile_path, /*retry_count=*/0, + kNukeProfileMaxRetryCount, std::move(done_callback)); +} + +// Called after a deleted profile was checked and cleaned up. +void ProfileCleanedUp(base::Value profile_path_value) { + ScopedListPrefUpdate deleted_profiles(g_browser_process->local_state(), + prefs::kProfilesDeleted); + deleted_profiles->EraseValue(profile_path_value); +} + #if BUILDFLAG(ENABLE_EXTENSIONS) // Returns the number of installed (and enabled) apps, excluding any component @@ -280,6 +429,17 @@ return entry && entry->IsEphemeral(); } +// Helper function that deletes entries from the kProfilesLastActive pref list. +// It is called when every ephemeral profile is handled. +void RemoveFromLastActiveProfilesPrefList(base::FilePath path) { + PrefService* local_state = g_browser_process->local_state(); + DCHECK(local_state); + ScopedListPrefUpdate update(local_state, prefs::kProfilesLastActive); + base::Value::List& profile_list = update.Get(); + base::Value entry_value = base::Value(path.BaseName().AsUTF8Unsafe()); + profile_list.EraseValue(entry_value); +} + #if BUILDFLAG(IS_CHROMEOS_ASH) bool IsLoggedIn() { return user_manager::UserManager::IsInitialized() && @@ -318,6 +478,21 @@ return out; } +base::FilePath GetLastUsedProfileBaseName() { + PrefService* local_state = g_browser_process->local_state(); + DCHECK(local_state); + base::FilePath last_used_profile_base_name = + local_state->GetFilePath(prefs::kProfileLastUsed); + // Make sure the system profile can't be the one marked as the last one used + // since it shouldn't get a browser. + if (!last_used_profile_base_name.empty() && + last_used_profile_base_name.value() != chrome::kSystemProfileDir) { + return last_used_profile_base_name; + } + + return base::FilePath::FromASCII(chrome::kInitialProfile); +} + #if BUILDFLAG(IS_CHROMEOS) void UpdateSupervisedUserPref(Profile* profile, bool is_child) { DCHECK(profile); @@ -367,12 +542,7 @@ } // namespace ProfileManager::ProfileManager(const base::FilePath& user_data_dir) - : user_data_dir_(user_data_dir) -#if !BUILDFLAG(IS_ANDROID) - , - delete_profile_helper_(std::make_unique<DeleteProfileHelper>(*this)) -#endif -{ + : user_data_dir_(user_data_dir) { #if !BUILDFLAG(IS_ANDROID) closing_all_browsers_subscription_ = chrome::AddClosingAllBrowsersCallback( base::BindRepeating(&ProfileManager::OnClosingAllBrowsersChanged, @@ -418,6 +588,14 @@ ProfileDestroyer::DestroyPendingProfilesForShutdown(); } +// static +bool ProfileManager::IsProfileDirectoryMarkedForDeletion( + const base::FilePath& profile_path) { + const auto it = ProfilesToDelete().find(profile_path); + return it != ProfilesToDelete().end() && + it->second == ProfileDeletionStage::MARKED; +} + #if BUILDFLAG(ENABLE_SESSION_SERVICE) // static void ProfileManager::ShutdownSessionServices() { @@ -438,6 +616,16 @@ #endif // static +void ProfileManager::NukeDeletedProfilesFromDisk() { + for (const auto& item : ProfilesToDelete()) { + if (item.second == ProfileDeletionStage::MARKED) + NukeProfileFromDiskImpl(item.first, /*retry_count=*/0, + /*max_retry_count=*/1, base::OnceClosure()); + } + ProfilesToDelete().clear(); +} + +// static Profile* ProfileManager::GetLastUsedProfile() { ProfileManager* profile_manager = g_browser_process->profile_manager(); @@ -748,22 +936,6 @@ return user_data_dir_.Append(GetLastUsedProfileBaseName()); } -// static -base::FilePath ProfileManager::GetLastUsedProfileBaseName() { - PrefService* local_state = g_browser_process->local_state(); - DCHECK(local_state); - base::FilePath last_used_profile_base_name = - local_state->GetFilePath(prefs::kProfileLastUsed); - // Make sure the system profile can't be the one marked as the last one used - // since it shouldn't get a browser. - if (!last_used_profile_base_name.empty() && - last_used_profile_base_name.value() != chrome::kSystemProfileDir) { - return last_used_profile_base_name; - } - - return base::FilePath::FromASCII(chrome::kInitialProfile); -} - base::FilePath ProfileManager::GetProfileDirForEmail(const std::string& email) { for (const auto* entry : GetProfileAttributesStorage().GetAllProfilesAttributes()) { @@ -805,10 +977,8 @@ return false; } -#if !BUILDFLAG(IS_ANDROID) if (IsProfileDirectoryMarkedForDeletion(path)) return false; -#endif return true; } @@ -988,6 +1158,77 @@ } #endif +#if !BUILDFLAG(IS_ANDROID) +void ProfileManager::MaybeScheduleProfileForDeletion( + const base::FilePath& profile_dir, + ProfileLoadedCallback callback, + ProfileMetrics::ProfileDelete deletion_source) { + if (!ScheduleProfileDirectoryForDeletion(profile_dir)) + return; + + ProfileAttributesStorage& storage = GetProfileAttributesStorage(); + ProfileAttributesEntry* entry = + storage.GetProfileAttributesWithPath(profile_dir); + if (entry) { + storage.RecordDeletedProfileState(entry); + } + ProfileMetrics::LogProfileDeleteUser(deletion_source); + + ScheduleProfileForDeletion(profile_dir, std::move(callback)); +} + +void ProfileManager::ScheduleProfileForDeletion( + const base::FilePath& profile_dir, + ProfileLoadedCallback callback) { + DCHECK(profiles::IsMultipleProfilesEnabled()); + DCHECK(!IsProfileDirectoryMarkedForDeletion(profile_dir)); + + Profile* profile = GetProfileByPath(profile_dir); + if (profile) { +#if BUILDFLAG(IS_CHROMEOS_LACROS) + CHECK(!profile->IsMainProfile()); +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) + // Cancel all in-progress downloads before deleting the profile to prevent a + // "Do you want to exit Google Chrome and cancel the downloads?" prompt + // (crbug.com/336725). + DownloadCoreService* service = + DownloadCoreServiceFactory::GetForBrowserContext(profile); + service->CancelDownloads(); + DCHECK_EQ(0, service->NonMaliciousDownloadCount()); + + // Close all browser windows before deleting the profile. If the user + // cancels the closing of any tab in an OnBeforeUnload event, profile + // deletion is also cancelled. (crbug.com/289390) + BrowserList::CloseAllBrowsersWithProfile( + profile, + base::BindRepeating( + &ProfileManager::EnsureActiveProfileExistsBeforeDeletion, + base::Unretained(this), base::Passed(std::move(callback))), + base::BindRepeating(&CancelProfileDeletion), false); + } else { + EnsureActiveProfileExistsBeforeDeletion(std::move(callback), profile_dir); + } +} + +void ProfileManager::ScheduleEphemeralProfileForDeletion( + const base::FilePath& profile_dir) { + DCHECK_EQ(0u, chrome::GetBrowserCount(GetProfileByPath(profile_dir))); + DCHECK(IsRegisteredAsEphemeral(&GetProfileAttributesStorage(), profile_dir)); + absl::optional<base::FilePath> new_active_profile_dir = + FindLastActiveProfile(base::BindRepeating( + [](const base::FilePath& profile_dir, ProfileAttributesEntry* entry) { + return entry->GetPath() != profile_dir; + }, + profile_dir)); + if (!new_active_profile_dir.has_value()) + new_active_profile_dir = GenerateNextProfileDirectoryPath(); + DCHECK(!new_active_profile_dir->empty()); + RemoveFromLastActiveProfilesPrefList(profile_dir); + + FinishDeletingProfile(profile_dir, new_active_profile_dir.value()); +} +#endif // !BUILDFLAG(IS_ANDROID) + void ProfileManager::AutoloadProfiles() { // If running in the background is disabled for the browser, do not autoload // any profiles. @@ -1010,6 +1251,83 @@ } } +void ProfileManager::CleanUpEphemeralProfiles() { + const base::FilePath last_used_profile_base_name = + GetLastUsedProfileBaseName(); + bool last_active_profile_deleted = false; + base::FilePath new_profile_path; + std::vector<base::FilePath> profiles_to_delete; + ProfileAttributesStorage& storage = GetProfileAttributesStorage(); + std::vector<ProfileAttributesEntry*> entries = + storage.GetAllProfilesAttributes(); + for (ProfileAttributesEntry* entry : entries) { + base::FilePath profile_path = entry->GetPath(); + if (entry->IsEphemeral()) { + profiles_to_delete.push_back(profile_path); + RemoveFromLastActiveProfilesPrefList(profile_path); + if (profile_path.BaseName() == last_used_profile_base_name) + last_active_profile_deleted = true; + } else if (new_profile_path.empty()) { + new_profile_path = profile_path; + } + } + + // If the last active profile was ephemeral or all profiles are deleted due to + // ephemeral, set a new one. + if (last_active_profile_deleted || + (entries.size() == profiles_to_delete.size() && + !profiles_to_delete.empty())) { + if (new_profile_path.empty()) + new_profile_path = GenerateNextProfileDirectoryPath(); + + profiles::SetLastUsedProfile(new_profile_path.BaseName()); + } + + for (const base::FilePath& profile_path : profiles_to_delete) { + base::ThreadPool::PostTask( + FROM_HERE, + {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + base::BindOnce(&NukeProfileFromDisk, profile_path, + base::OnceClosure())); + + storage.RemoveProfile(profile_path); + } +} + +void ProfileManager::CleanUpDeletedProfiles() { + PrefService* local_state = g_browser_process->local_state(); + DCHECK(local_state); + const base::Value::List& deleted_profiles = + local_state->GetList(prefs::kProfilesDeleted); + + for (const base::Value& value : deleted_profiles) { + absl::optional<base::FilePath> profile_path = base::ValueToFilePath(value); + // Although it should never happen, make sure this is a valid path in the + // user_data_dir, so we don't accidentally delete something else. + if (profile_path && IsAllowedProfilePath(*profile_path)) { + if (base::PathExists(*profile_path)) { + LOG(WARNING) << "Files of a deleted profile still exist after restart. " + "Cleaning up now."; + base::ThreadPool::PostTask( + FROM_HERE, + {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + base::BindOnce(&NukeProfileFromDisk, *profile_path, + base::BindOnce(&ProfileCleanedUp, value.Clone()))); + } else { + // Everything is fine, the profile was removed on shutdown. + content::GetUIThreadTaskRunner({})->PostTask( + FROM_HERE, base::BindOnce(&ProfileCleanedUp, value.Clone())); + } + } else { + LOG(ERROR) << "Found invalid profile path in deleted_profiles: " + << profile_path->AsUTF8Unsafe(); + NOTREACHED(); + } + } +} + void ProfileManager::InitProfileUserPrefs(Profile* profile) { TRACE_EVENT0("browser", "ProfileManager::InitProfileUserPrefs"); ProfileAttributesStorage& storage = GetProfileAttributesStorage(); @@ -1297,12 +1615,6 @@ DeleteProfileIfNoKeepAlive(info); } -void ProfileManager::NotifyOnProfileMarkedForPermanentDeletion( - Profile* profile) { - for (auto& observer : observers_) - observer.OnProfileMarkedForPermanentDeletion(profile); -} - void ProfileManager::DeleteProfileIfNoKeepAlive(const ProfileInfo* info) { #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) if (GetTotalRefCount(info->keep_alives) != 0) @@ -1742,6 +2054,153 @@ } #if !BUILDFLAG(IS_ANDROID) +void ProfileManager::EnsureActiveProfileExistsBeforeDeletion( + ProfileLoadedCallback callback, + const base::FilePath& profile_dir) { + // In case we delete non-active profile and current profile is valid, proceed. + const base::FilePath last_used_profile_path = GetLastUsedProfileDir(); + const base::FilePath guest_profile_path = GetGuestProfilePath(); + Profile* last_used_profile = GetProfileByPath(last_used_profile_path); + if (last_used_profile_path != profile_dir && + last_used_profile_path != guest_profile_path && last_used_profile) { + FinishDeletingProfile(profile_dir, last_used_profile_path); + return; + } + + // Search for an active browser and use its profile as active if possible. + for (Browser* browser : *BrowserList::GetInstance()) { + Profile* profile = browser->profile(); + base::FilePath cur_path = profile->GetPath(); + if (cur_path != profile_dir && cur_path != guest_profile_path && + !IsProfileDirectoryMarkedForDeletion(cur_path)) { + OnNewActiveProfileInitialized(profile_dir, cur_path, std::move(callback), + nullptr, profile); + return; + } + } + + // There no valid browsers to fallback, search for any existing valid profile. + ProfileAttributesStorage& storage = GetProfileAttributesStorage(); + base::FilePath fallback_profile_path; + std::vector<ProfileAttributesEntry*> entries = + storage.GetAllProfilesAttributes(); + for (ProfileAttributesEntry* entry : entries) { + base::FilePath cur_path = entry->GetPath(); + // Make sure that this profile is not pending deletion. + if (cur_path != profile_dir && cur_path != guest_profile_path && + !IsProfileDirectoryMarkedForDeletion(cur_path)) { + fallback_profile_path = cur_path; + break; + } + } + + // If we're deleting the last profile, then create a new profile in its place. + // Load existing profile otherwise. + if (fallback_profile_path.empty()) { + fallback_profile_path = GenerateNextProfileDirectoryPath(); + // A new profile about to be created. + ProfileMetrics::LogProfileAddNewUser( + ProfileMetrics::ADD_NEW_USER_LAST_DELETED); + } + + // When this is called all browser windows may be about to be destroyed + // (but still exist in BrowserList), which means shutdown may be about to + // start. Use a KeepAlive to ensure shutdown doesn't start. + std::unique_ptr<ScopedKeepAlive> keep_alive = + std::make_unique<ScopedKeepAlive>(KeepAliveOrigin::PROFILE_MANAGER, + KeepAliveRestartOption::DISABLED); + // Create and/or load fallback profile. + CreateProfileAsync( + fallback_profile_path, + base::BindOnce(&ProfileManager::OnNewActiveProfileInitialized, + base::Unretained(this), profile_dir, fallback_profile_path, + std::move(callback), std::move(keep_alive))); +} + +void ProfileManager::OnLoadProfileForProfileDeletion( + const base::FilePath& profile_dir, + Profile* profile) { + ProfileAttributesStorage& storage = GetProfileAttributesStorage(); + + if (!IsProfileDirectoryMarkedForDeletion(profile_dir)) { + // Ensure RemoveProfile() knows to nuke the profile directory after it's + // done. + MarkProfileDirectoryForDeletion(profile_dir); + } + + if (profile) { + // TODO(estade): Migrate additional code in this block to observe + // ProfileManager instead of handling shutdown here. + for (auto& observer : observers_) + observer.OnProfileMarkedForPermanentDeletion(profile); + + // Disable sync for doomed profile. + if (SyncServiceFactory::HasSyncService(profile)) { + syncer::SyncService* sync_service = + SyncServiceFactory::GetForProfile(profile); + // Ensure data is cleared even if sync was already off. + sync_service->StopAndClear(); + } + + // Some platforms store passwords in keychains. They should be removed. + scoped_refptr<password_manager::PasswordStoreInterface> password_store = + PasswordStoreFactory::GetForProfile(profile, + ServiceAccessType::EXPLICIT_ACCESS) + .get(); + if (password_store.get()) { + password_store->RemoveLoginsCreatedBetween(base::Time(), + base::Time::Max()); + } + + // The Profile Data doesn't get wiped until Chrome closes. Since we promised + // that the user's data would be removed, do so immediately. + // + // With DestroyProfileOnBrowserClose, this adds a KeepAlive. So the Profile* + // only gets deleted *after* browsing data is removed. This also clears some + // keepalives in the process, e.g. due to background extensions getting + // uninstalled. + profiles::RemoveBrowsingDataForProfile(profile_dir); + + // Clean-up pref data that won't be cleaned up by deleting the profile dir. + profile->GetPrefs()->OnStoreDeletionFromDisk(); + + } else { + // We failed to load the profile, but it's safe to delete a not yet loaded + // Profile from disk. + base::ThreadPool::PostTask( + FROM_HERE, + {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + base::BindOnce(&NukeProfileFromDisk, profile_dir, base::OnceClosure())); + } + + storage.RemoveProfile(profile_dir); + + if (profile && + base::FeatureList::IsEnabled(features::kDestroyProfileOnBrowserClose)) { + // Allow the Profile* to be deleted, even if it had no browser windows. + ClearFirstBrowserWindowKeepAlive(profile); + } +} + +void ProfileManager::FinishDeletingProfile( + const base::FilePath& profile_dir, + const base::FilePath& new_active_profile_dir) { + // Update the last used profile pref before closing browser windows. This + // way the correct last used profile is set for any notification observers. + profiles::SetLastUsedProfile(new_active_profile_dir.BaseName()); + + // Attempt to load the profile before deleting it to properly clean up + // profile-specific data stored outside the profile directory. + LoadProfileByPath( + profile_dir, false, + base::BindOnce(&ProfileManager::OnLoadProfileForProfileDeletion, + base::Unretained(this), profile_dir)); + if (!IsProfileDirectoryMarkedForDeletion(profile_dir)) { + // Prevents CreateProfileAsync from re-creating the profile. + MarkProfileDirectoryForDeletion(profile_dir); + } +} absl::optional<base::FilePath> ProfileManager::FindLastActiveProfile( base::RepeatingCallback<bool(ProfileAttributesEntry*)> predicate) { @@ -1783,10 +2242,6 @@ #endif //! BUILDFLAG(IS_CHROMEOS_ASH) } -DeleteProfileHelper& ProfileManager::GetDeleteProfileHelper() { - return *delete_profile_helper_; -} - #endif // !BUILDFLAG(IS_ANDROID) ProfileManager::ProfileInfo* ProfileManager::RegisterOwnedProfile( @@ -2026,7 +2481,7 @@ // Delete if the profile is an ephemeral profile and it is not in the // profile creation flow. // TODO(crbug.com/1369535): Delete the profile when there is no keep alive. - delete_profile_helper_->ScheduleEphemeralProfileForDeletion(path); + ScheduleEphemeralProfileForDeletion(path); } else if (!profile->IsOffTheRecord()) { auto* browsing_data_lifetime_manager = ChromeBrowsingDataLifetimeManagerFactory::GetForProfile( @@ -2102,6 +2557,26 @@ profile_manager_->UpdateLastUser(last_active); } +void ProfileManager::OnNewActiveProfileInitialized( + const base::FilePath& profile_to_delete_path, + const base::FilePath& new_active_profile_path, + ProfileLoadedCallback callback, + std::unique_ptr<ScopedKeepAlive> keep_alive, + Profile* loaded_profile) { + DCHECK(loaded_profile); + if (IsProfileDirectoryMarkedForDeletion(new_active_profile_path)) { + // If the profile we tried to load as the next active profile has been + // deleted, then retry deleting this profile to redo the logic to load + // the next available profile. + EnsureActiveProfileExistsBeforeDeletion(std::move(callback), + profile_to_delete_path); + return; + } + + FinishDeletingProfile(profile_to_delete_path, new_active_profile_path); + std::move(callback).Run(loaded_profile); +} + void ProfileManager::OnClosingAllBrowsersChanged(bool closing) { // Save active profiles when the browser begins shutting down, or if shutdown // is cancelled. The active profiles won't be changed during the shutdown
diff --git a/chrome/browser/profiles/profile_manager.h b/chrome/browser/profiles/profile_manager.h index 57173de2..e0d0b86 100644 --- a/chrome/browser/profiles/profile_manager.h +++ b/chrome/browser/profiles/profile_manager.h
@@ -25,7 +25,6 @@ #include "base/timer/timer.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_shortcut_manager.h" @@ -39,10 +38,10 @@ class AccountProfileMapper; #endif -class DeleteProfileHelper; class ProfileAttributesStorage; enum class ProfileKeepAliveOrigin; class ProfileManagerObserver; +class ScopedKeepAlive; class ScopedProfileKeepAlive; // Manages the lifecycle of Profile objects. @@ -63,6 +62,9 @@ static void ShutdownSessionServices(); #endif + // Physically remove deleted profile directories from disk. + static void NukeDeletedProfilesFromDisk(); + // Get the Profile last used (the Profile to which owns the most recently // focused window) with this Chrome build. If no signed profile has been // stored in Local State, hand back the Default profile. @@ -185,7 +187,6 @@ // Get the path of the last used profile, or if that's undefined, the default // profile. base::FilePath GetLastUsedProfileDir(); - static base::FilePath GetLastUsedProfileBaseName(); // Returns the path of a profile with the requested account, or the empty // path if none exists. @@ -260,21 +261,42 @@ #endif #if !BUILDFLAG(IS_ANDROID) - // Searches for the latest active profile that respects |predicate|, already - // loaded preferably. Returns nullopt if no existing profile respects all the - // conditions. - absl::optional<base::FilePath> FindLastActiveProfile( - base::RepeatingCallback<bool(ProfileAttributesEntry*)> predicate); + // Less strict version of ScheduleProfileForDeletion(), silently exits if + // profile is either scheduling or marked for deletion. + void MaybeScheduleProfileForDeletion( + const base::FilePath& profile_dir, + ProfileLoadedCallback callback, + ProfileMetrics::ProfileDelete deletion_source); + + // Schedules the profile at the given path to be deleted on shutdown. If we're + // deleting the last profile, a new one will be created in its place, and in + // that case the callback will be called when profile creation is complete. + void ScheduleProfileForDeletion(const base::FilePath& profile_dir, + ProfileLoadedCallback callback); + + // Schedules the ephemeral profile at the given path to be deleted on + // shutdown. New profiles will not be created. + void ScheduleEphemeralProfileForDeletion(const base::FilePath& profile_dir); // Deletes Guest profile's browsing data. static void CleanUpGuestProfile(); - - DeleteProfileHelper& GetDeleteProfileHelper(); #endif + // Returns if profile is marked for deletion. + static bool IsProfileDirectoryMarkedForDeletion( + const base::FilePath& profile_dir); + // Autoloads profiles if they are running background apps. void AutoloadProfiles(); + // Checks if any ephemeral profiles are left behind (e.g. because of a browser + // crash) and schedule them for deletion. + void CleanUpEphemeralProfiles(); + + // Checks if files of deleted profiles are left behind (e.g. because of a + // browser crash) and delete them in case they still exist. + void CleanUpDeletedProfiles(); + // Initializes user prefs of |profile|. This includes profile name and // avatar values. void InitProfileUserPrefs(Profile* profile); @@ -328,12 +350,6 @@ // browser window. void ClearFirstBrowserWindowKeepAlive(const Profile* profile); - // Returns whether |path| is allowed for profile creation. - bool IsAllowedProfilePath(const base::FilePath& path) const; - - // Notifies `OnProfileMarkedForPermanentDeletion()` to the observers. - void NotifyOnProfileMarkedForPermanentDeletion(Profile* profile); - protected: // Creates a new profile by calling into the profile's profile creation // method. Virtual so that unittests can return a TestingProfile instead @@ -464,6 +480,29 @@ // null if creation fails. Profile* CreateAndInitializeProfile(const base::FilePath& profile_dir); +#if !BUILDFLAG(IS_ANDROID) + // Continues the scheduled profile deletion after closing all the profile's + // browsers tabs. Creates a new profile if the profile to be deleted is the + // last non-supervised profile. In the Mac, loads the next non-supervised + // profile if the profile to be deleted is the active profile. + void EnsureActiveProfileExistsBeforeDeletion( + ProfileLoadedCallback callback, + const base::FilePath& profile_dir); + + // Schedules the profile at the given path to be deleted on shutdown, + // and marks the new profile as active. + void FinishDeletingProfile(const base::FilePath& profile_dir, + const base::FilePath& new_active_profile_dir); + void OnLoadProfileForProfileDeletion(const base::FilePath& profile_dir, + Profile* profile); + + // Searches for the latest active profile that respects |predicate|, already + // loaded preferably. Returns nullopt if no existing profile respects all the + // conditions. + absl::optional<base::FilePath> FindLastActiveProfile( + base::RepeatingCallback<bool(ProfileAttributesEntry*)> predicate); +#endif + // Registers profile with given info. Returns pointer to created ProfileInfo // entry. ProfileInfo* RegisterUnownedProfile(Profile* profile); @@ -478,6 +517,9 @@ // should be used carefully. Profile* GetProfileByPathInternal(const base::FilePath& path) const; + // Returns whether |path| is allowed for profile creation. + bool IsAllowedProfilePath(const base::FilePath& path) const; + // Whether a new profile can be created at |path|. bool CanCreateProfileAtPath(const base::FilePath& path) const; @@ -520,6 +562,18 @@ raw_ptr<ProfileManager> profile_manager_; }; + // If the `loaded_profile` has been loaded successfully and isn't already + // scheduled for deletion, then finishes adding `profile_to_delete_dir` to the + // queue of profiles to be deleted, and updates the kProfileLastUsed + // preference based on `last_non_supervised_profile_path`. `keep_alive` may be + // null and is used to ensure shutdown does not start. + void OnNewActiveProfileInitialized( + const base::FilePath& profile_to_delete_path, + const base::FilePath& last_non_supervised_profile_path, + ProfileLoadedCallback callback, + std::unique_ptr<ScopedKeepAlive> keep_alive, + Profile* loaded_profile); + void OnClosingAllBrowsersChanged(bool closing); #endif // !BUILDFLAG(IS_ANDROID) @@ -554,8 +608,6 @@ #if !BUILDFLAG(IS_ANDROID) BrowserListObserver browser_list_observer_{this}; - - std::unique_ptr<DeleteProfileHelper> delete_profile_helper_; #endif // !BUILDFLAG(IS_ANDROID) // Maps profile path to ProfileInfo (if profile has been created). Use
diff --git a/chrome/browser/profiles/profile_manager_browsertest.cc b/chrome/browser/profiles/profile_manager_browsertest.cc index c4f252d..fe57097 100644 --- a/chrome/browser/profiles/profile_manager_browsertest.cc +++ b/chrome/browser/profiles/profile_manager_browsertest.cc
@@ -28,7 +28,6 @@ #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_test_util.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/profiles/profiles_state.h" @@ -314,9 +313,8 @@ storage.GetAllProfilesAttributes().front()->GetPath(); EXPECT_FALSE(singleton_profile_path.empty()); MultipleProfileDeletionObserver profile_deletion_observer(1u); - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - singleton_profile_path, base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(singleton_profile_path, + base::DoNothing()); // Run the message loop until the profile is actually deleted (as indicated // by the callback above being called). @@ -355,8 +353,7 @@ // Delete inactive profile. MultipleProfileDeletionObserver profile_deletion_observer(1u); - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - new_path, base::DoNothing(), ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(new_path, base::DoNothing()); profile_deletion_observer.Wait(); // Make sure there only preexisted profile left. @@ -383,7 +380,7 @@ base::FilePath current_profile_path = browser()->profile()->GetPath(); base::FilePath new_last_used_path = new_profile_path; #if BUILDFLAG(IS_CHROMEOS_LACROS) - // Deleting the main profile on Lacros is not allwed. + // Deleting the main profile on Lacros is not allowed. // Set the current profile to the new profile. new_last_used_path = browser()->profile()->GetPath(); ASSERT_EQ(Browser::GetCreationStatusForProfile(new_profile), @@ -399,9 +396,8 @@ // Delete current profile. MultipleProfileDeletionObserver profile_deletion_observer(1u); - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - current_profile_path, base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(current_profile_path, + base::DoNothing()); profile_deletion_observer.Wait(); // Make sure a profile created earlier become the only profile. @@ -451,9 +447,8 @@ if (Profile::IsMainProfilePath(profile_path)) continue; #endif - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile_path, base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile_path, + base::DoNothing()); old_profile_paths.push_back(profile_path); } profile_deletion_observer.Wait(); @@ -773,11 +768,8 @@ EXPECT_EQ(1u, verify_add.GetPasswords().size()); MultipleProfileDeletionObserver profile_deletion_observer(1U); - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .MaybeScheduleProfileForDeletion( - profile->GetPath(), base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + g_browser_process->profile_manager()->ScheduleProfileForDeletion( + profile->GetPath(), base::DoNothing()); // run_loop.Run(); profile_deletion_observer.Wait();
diff --git a/chrome/browser/profiles/profile_manager_unittest.cc b/chrome/browser/profiles/profile_manager_unittest.cc index 2f36295..5462092 100644 --- a/chrome/browser/profiles/profile_manager_unittest.cc +++ b/chrome/browser/profiles/profile_manager_unittest.cc
@@ -28,7 +28,6 @@ #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h" #include "chrome/browser/profiles/keep_alive/scoped_profile_keep_alive.h" #include "chrome/browser/profiles/profile.h" @@ -1544,7 +1543,7 @@ initial_last_active_profile_list.Append( base::Value(path2.BaseName().MaybeAsASCII())); - profile_manager->GetDeleteProfileHelper().CleanUpEphemeralProfiles(); + profile_manager->CleanUpEphemeralProfiles(); content::RunAllTasksUntilIdle(); const base::Value::List& final_last_active_profile_list = local_state->GetList(prefs::kProfilesLastActive); @@ -1562,7 +1561,7 @@ // Mark the remaining profile ephemeral and clean up. storage.GetAllProfilesAttributes()[0]->SetIsEphemeral(true); - profile_manager->GetDeleteProfileHelper().CleanUpEphemeralProfiles(); + profile_manager->CleanUpEphemeralProfiles(); content::RunAllTasksUntilIdle(); // The profile should be deleted, and the last used profile set to a new one. @@ -1615,7 +1614,7 @@ initial_last_active_profile_list.Append( base::Value(path.BaseName().MaybeAsASCII())); - profile_manager->GetDeleteProfileHelper().CleanUpEphemeralProfiles(); + profile_manager->CleanUpEphemeralProfiles(); content::RunAllTasksUntilIdle(); const base::Value::List& final_last_active_profile_list = local_state->GetList(prefs::kProfilesLastActive); @@ -1654,7 +1653,7 @@ PrefService* local_state = g_browser_process->local_state(); local_state->SetString(prefs::kProfileLastUsed, std::string("Guest Profile")); - profile_manager->GetDeleteProfileHelper().CleanUpEphemeralProfiles(); + profile_manager->CleanUpEphemeralProfiles(); content::RunAllTasksUntilIdle(); ASSERT_EQ(0u, storage.GetNumberOfProfiles()); @@ -1771,9 +1770,7 @@ local_state->SetString(prefs::kProfileLastUsed, profile_basename1); // Delete the active profile. - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile_path1, base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile_path1, base::DoNothing()); content::RunAllTasksUntilIdle(); EXPECT_EQ(profile_path2, profile_manager->GetLastUsedProfile()->GetPath()); @@ -1806,9 +1803,7 @@ local_state->SetString(prefs::kProfileLastUsed, profile_basename1); // Delete the active profile. - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile_path1, base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile_path1, base::DoNothing()); content::RunAllTasksUntilIdle(); // A new profile should have been created @@ -1868,9 +1863,7 @@ local_state->SetString(prefs::kProfileLastUsed, guest_profile_basename); // Delete the other profile. - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile_path1, base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile_path1, base::DoNothing()); content::RunAllTasksUntilIdle(); // A new profile should have been created. @@ -1914,9 +1907,8 @@ profiles::GetAvatarNameForProfile(profile2->GetPath())); // Deleting a profile means returning to the default name. - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile2->GetPath(), base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile2->GetPath(), + base::DoNothing()); content::RunAllTasksUntilIdle(); EXPECT_EQ(default_profile_name, profiles::GetAvatarNameForProfile(profile1->GetPath())); @@ -1959,9 +1951,8 @@ profiles::GetAvatarNameForProfile(profile2->GetPath())); // Deleting a profile means returning to the original, custom name. - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile2->GetPath(), base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile2->GetPath(), + base::DoNothing()); content::RunAllTasksUntilIdle(); EXPECT_EQ(custom_profile_name, profiles::GetAvatarNameForProfile(profile1->GetPath())); @@ -2013,9 +2004,8 @@ profiles::GetAvatarNameForProfile(profile2->GetPath())); // Deleting a profile means returning to the original, actual profile name. - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile2->GetPath(), base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile2->GetPath(), + base::DoNothing()); content::RunAllTasksUntilIdle(); EXPECT_EQ(gaia_given_name, profiles::GetAvatarNameForProfile(profile1->GetPath())); @@ -2137,9 +2127,7 @@ // Delete the active profile. This should switch and load the unloaded // profile. - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile_path1, base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile_path1, base::DoNothing()); content::RunAllTasksUntilIdle(); @@ -2213,14 +2201,10 @@ // Try to break this flow by setting the active profile to Profile2 in the // middle (so after the first posted message), and trying to delete Profile2, // so that the ProfileManager has to look for a different profile to load. - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile_path1, base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile_path1, base::DoNothing()); local_state->SetString(prefs::kProfileLastUsed, profile_path2.BaseName().MaybeAsASCII()); - profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion( - profile_path2, base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + profile_manager->ScheduleProfileForDeletion(profile_path2, base::DoNothing()); content::RunAllTasksUntilIdle(); EXPECT_EQ(profile_path3, profile_manager->GetLastUsedProfile()->GetPath());
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/options/options.js b/chrome/browser/resources/chromeos/accessibility/chromevox/options/options.js index cbf63da..23848ede 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/options/options.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/options/options.js
@@ -8,7 +8,6 @@ import {constants} from '../../common/constants.js'; import {BackgroundBridge} from '../common/background_bridge.js'; import {BrailleTable} from '../common/braille/braille_table.js'; -import {ContentScriptBridge} from '../common/content_script_bridge.js'; import {Msgs} from '../common/msgs.js'; import {PanelCommand, PanelCommandType} from '../common/panel_command.js'; import {PunctuationEchoes, TtsSettings} from '../common/tts_types.js'; @@ -31,7 +30,6 @@ * @this {OptionsPage} */ static async init() { - ContentScriptBridge.init(); OptionsPage.populateVoicesSelect(); BrailleTable.getAll(function(tables) { /** @type {!Array<BrailleTable.Table>} */ @@ -159,12 +157,6 @@ } }); - ContentScriptBridge.addMessageListener(function(message) { - if (message['prefs']) { - OptionsPage.update(); - } - }); - const clearVirtualDisplay = function() { const groups = []; const sizeOfDisplay =
diff --git a/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn index ea7a818..8871ac1 100644 --- a/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn
@@ -222,6 +222,7 @@ "testing/accessibility_test_base.js", "testing/assert_additions.js", "testing/callback_helper.js", + "testing/common_e2e_test_base.js", "testing/doc_utils.js", "testing/e2e_test_base.js", ]
diff --git a/chrome/browser/resources/chromeos/accessibility/common/array_util_test.js b/chrome/browser/resources/chromeos/accessibility/common/array_util_test.js index 51ed502..ba3afbfb9 100644 --- a/chrome/browser/resources/chromeos/accessibility/common/array_util_test.js +++ b/chrome/browser/resources/chromeos/accessibility/common/array_util_test.js
@@ -3,10 +3,10 @@ // found in the LICENSE file. // Include test fixture. -GEN_INCLUDE(['../select_to_speak/select_to_speak_e2e_test_base.js']); +GEN_INCLUDE(['testing/common_e2e_test_base.js']); /** Test fixture for array_util.js. */ -ArrayUtilTest = class extends SelectToSpeakE2ETest { +AccessibilityExtensionArrayUtilTest = class extends CommonE2ETestBase { /** @override */ async setUpDeferred() { await super.setUpDeferred(); @@ -14,7 +14,7 @@ } }; -AX_TEST_F('ArrayUtilTest', 'ContentsAreEqual', function() { +AX_TEST_F('AccessibilityExtensionArrayUtilTest', 'ContentsAreEqual', function() { const even1 = [2, 4, 6, 8]; const even2 = [2, 4, 6, 8]; const odd = [1, 3, 5, 7, 9];
diff --git a/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.html b/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.html index 4079f4f2..a1398904 100644 --- a/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.html +++ b/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.html
@@ -25,6 +25,11 @@ margin: 0; } + cr-toolbar-search-field { + margin: 14px; + width: auto; + } + iron-icon { --icon-size: 16px; height: var(--icon-size); @@ -169,7 +174,7 @@ display: flex; flex-direction: row; gap: 4px; - margin: 14px 14px 0 14px; + margin: 0 14px; } .price-discounted { @@ -199,6 +204,9 @@ </style> <div class="column" id="powerBookmarksContainer"> + <cr-toolbar-search-field label="$i18n{searchBookmarks}" + clear-label="$i18n{clearSearch}" on-search-changed="onSearchChanged_"> + </cr-toolbar-search-field> <div class="label-row"> <template is="dom-repeat" items="[[labels_]]"> <button class="label" selected$="[[item.active]]" @@ -233,8 +241,8 @@ <div class="bookmarks" hidden="[[!shownBookmarks_.length]]"> <template is="dom-repeat" items="[[shownBookmarks_]]"> <power-bookmark-row id="bookmark-[[item.id]]" bookmark="[[item]]" - description= - "[[getBookmarkDescription_(item, descriptions_.*, compact_)]]" + description= "[[getBookmarkDescription_(item, compactDescriptions_.*, + expandedDescriptions_.*, compact_)]]" compact="[[compact_]]" on-row-clicked="onRowClicked_"> <div slot="extra-content-container">
diff --git a/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.ts b/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.ts index 3aa7065b..530ef48 100644 --- a/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.ts +++ b/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.ts
@@ -10,6 +10,7 @@ import '//resources/cr_elements/cr_action_menu/cr_action_menu.js'; import '//resources/cr_elements/cr_button/cr_button.js'; import '//resources/cr_elements/cr_icon_button/cr_icon_button.js'; +import '//resources/cr_elements/cr_toolbar/cr_toolbar_search_field.js'; import '//resources/cr_elements/icons.html.js'; import {CrActionMenuElement} from '//resources/cr_elements/cr_action_menu/cr_action_menu.js'; @@ -106,7 +107,7 @@ static get observers() { return [ 'updateShownBookmarks_(folders_.*, ' + - 'activeFolderPath_.*, labels_.*, activeSortIndex_)', + 'activeFolderPath_.*, labels_.*, activeSortIndex_, searchQuery_)', ]; } @@ -127,6 +128,7 @@ private showPriceTracking_: boolean; private activeSortIndex_: number; private sortTypes_: string[]; + private searchQuery_: string|undefined; override connectedCallback() { super.connectedCallback(); @@ -429,11 +431,9 @@ topLevelBookmarks.concat(folder.children!)); shownBookmarks = topLevelBookmarks; } - // Price tracking label - if (this.labels_[0]!.active) { - shownBookmarks = shownBookmarks.filter( - (bookmark, _) => this.isPriceTracked_(bookmark)); - } + shownBookmarks = shownBookmarks.filter( + (b: chrome.bookmarks.BookmarkTreeNode) => + this.nodeMatchesContentFilters_(b)); const sortChangedPosition = this.sortBookmarks_(shownBookmarks); if (sortChangedPosition) { this.shownBookmarks_ = shownBookmarks.slice(); @@ -442,6 +442,22 @@ } } + private nodeMatchesContentFilters_( + bookmark: chrome.bookmarks.BookmarkTreeNode): boolean { + // Price tracking label + if (this.labels_[0]!.active && !this.isPriceTracked_(bookmark)) { + return false; + } else if ( + this.searchQuery_ && + !(bookmark.title && + bookmark.title.toLocaleLowerCase().includes(this.searchQuery_!)) && + !(bookmark.url && + bookmark.url.toLocaleLowerCase().includes(this.searchQuery_!))) { + return false; + } + return true; + } + /** * Apply the current active sort type to the given bookmarks list. Returns * true if any elements in the list changed position. @@ -545,6 +561,10 @@ this.pop('activeFolderPath_'); } + private onSearchChanged_(e: CustomEvent<string>) { + this.searchQuery_ = e.detail.toLocaleLowerCase(); + } + private onShowSortMenuClicked_(event: MouseEvent) { event.preventDefault(); event.stopPropagation();
diff --git a/chrome/browser/resources/side_panel/reading_list/app.html b/chrome/browser/resources/side_panel/reading_list/app.html index bdbe4f7..b8c4722 100644 --- a/chrome/browser/resources/side_panel/reading_list/app.html +++ b/chrome/browser/resources/side_panel/reading_list/app.html
@@ -155,9 +155,9 @@ <div hidden="[[!unreadItems_.length]]" class="sub-heading"> $i18n{unreadHeader} </div> - <template id="ureadItemsList" is="dom-repeat" items="[[unreadItems_]]"> + <template id="unreadItemsList" is="dom-repeat" items="[[unreadItems_]]"> <reading-list-item data-url$="[[item.url.url]]" on-focus="onItemFocus_" - aria-label="[[ariaLabel_(item)]]" class="mwb-list-item" + aria-label="[[ariaLabel_(item)]]" class="mwb-list-item unread-item" data="[[item]]" button-ripples="[[buttonRipples]]" tabindex="0"> </reading-list-item> </template>
diff --git a/chrome/browser/resources/side_panel/reading_list/app.ts b/chrome/browser/resources/side_panel/reading_list/app.ts index 7b50293..f1504732 100644 --- a/chrome/browser/resources/side_panel/reading_list/app.ts +++ b/chrome/browser/resources/side_panel/reading_list/app.ts
@@ -15,15 +15,16 @@ import {HelpBubbleMixin, HelpBubbleMixinInterface} from 'chrome://resources/cr_components/help_bubble/help_bubble_mixin.js'; import {assertNotReached} from 'chrome://resources/js/assert_ts.js'; +import {EventTracker} from 'chrome://resources/js/event_tracker.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {listenOnce} from 'chrome://resources/js/util_ts.js'; import {IronSelectorElement} from 'chrome://resources/polymer/v3_0/iron-selector/iron-selector.js'; -import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {DomRepeat, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './app.html.js'; import {CurrentPageActionButtonState, ReadLaterEntriesByStatus, ReadLaterEntry} from './reading_list.mojom-webui.js'; import {ReadingListApiProxy, ReadingListApiProxyImpl} from './reading_list_api_proxy.js'; -import {ReadingListItemElement} from './reading_list_item.js'; +import {MARKED_AS_READ_UI_EVENT, ReadingListItemElement} from './reading_list_item.js'; const navigationKeys: Set<string> = new Set(['ArrowDown', 'ArrowUp']); @@ -34,9 +35,14 @@ $: { readingListList: HTMLElement, selector: IronSelectorElement, + unreadItemsList: DomRepeat, }; } +// browser_element_identifiers constants +const ADD_CURRENT_TAB_ELEMENT_ID = 'kAddCurrentTabToReadingListElementId'; +const READING_LIST_UNREAD_ELEMENT_ID = 'kSidePanelReadingListUnreadElementId'; +const MARKED_AS_READ_NATIVE_EVENT_ID = 'kSidePanelReadingMarkedAsReadEventId'; export class ReadingListAppElement extends ReadingListAppElementBase { static get is() { @@ -91,6 +97,7 @@ ReadingListApiProxyImpl.getInstance(); private listenerIds_: number[] = []; private visibilityChangedListener_: () => void; + private readingListEventTracker_: EventTracker = new EventTracker(); constructor() { super(); @@ -126,6 +133,9 @@ this.updateReadLaterEntries_(); this.apiProxy_.updateCurrentPageActionButtonState(); } + + this.readingListEventTracker_.add( + this.root!, MARKED_AS_READ_UI_EVENT, this.onMarkedAsRead.bind(this)); } override disconnectedCallback() { @@ -136,6 +146,27 @@ document.removeEventListener( 'visibilitychange', this.visibilityChangedListener_); + + this.unregisterHelpBubble(READING_LIST_UNREAD_ELEMENT_ID); + + this.readingListEventTracker_.remove(this.root!, MARKED_AS_READ_UI_EVENT); + } + + override ready() { + super.ready(); + + this.registerHelpBubble( + ADD_CURRENT_TAB_ELEMENT_ID, '#currentPageActionButton'); + + this.$.unreadItemsList.addEventListener( + 'rendered-item-count-changed', () => { + const firstUnreadItem = + this.root!.querySelector('.unread-item') as HTMLElement | null; + if (firstUnreadItem) { + this.registerHelpBubble( + READING_LIST_UNREAD_ELEMENT_ID, firstUnreadItem); + } + }); } /** @@ -232,11 +263,24 @@ private onCurrentPageActionButtonClick_() { if (this.getCurrentPageActionButtonMarkAsRead_()) { this.apiProxy_.markCurrentTabAsRead(); + this.sendTutorialCustomEvent(); } else { this.apiProxy_.addCurrentTab(); } } + private onMarkedAsRead() { + this.sendTutorialCustomEvent(); + } + + private sendTutorialCustomEvent() { + this.notifyHelpBubbleAnchorCustomEvent( + READING_LIST_UNREAD_ELEMENT_ID, + MARKED_AS_READ_NATIVE_EVENT_ID, + ); + } + + private onItemKeyDown_(e: KeyboardEvent) { if (e.shiftKey || !navigationKeys.has(e.key)) { return;
diff --git a/chrome/browser/resources/side_panel/reading_list/reading_list_item.ts b/chrome/browser/resources/side_panel/reading_list/reading_list_item.ts index 2e29282a..4d93fd90 100644 --- a/chrome/browser/resources/side_panel/reading_list/reading_list_item.ts +++ b/chrome/browser/resources/side_panel/reading_list/reading_list_item.ts
@@ -19,6 +19,8 @@ import {ReadingListApiProxy, ReadingListApiProxyImpl} from './reading_list_api_proxy.js'; import {getTemplate} from './reading_list_item.html.js'; +export const MARKED_AS_READ_UI_EVENT = 'reading-list-marked-as-read'; + const navigationKeys: Set<string> = new Set([' ', 'Enter', 'ArrowRight', 'ArrowLeft']); @@ -137,6 +139,10 @@ private onUpdateStatusClick_(e: Event) { e.stopPropagation(); this.apiProxy_.updateReadStatus(this.data.url, !this.data.read); + if (!this.data.read) { + this.dispatchEvent(new CustomEvent( + MARKED_AS_READ_UI_EVENT, {bubbles: true, composed: true})); + } } private onItemDeleteClick_(e: Event) { @@ -169,6 +175,9 @@ interface HTMLElementTagNameMap { 'reading-list-item': ReadingListItemElement; } + interface HTMLElementEventMap { + [MARKED_AS_READ_UI_EVENT]: CustomEvent; + } } customElements.define(ReadingListItemElement.is, ReadingListItemElement);
diff --git a/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.ts b/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.ts index 562e410..98373d1 100644 --- a/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.ts +++ b/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.ts
@@ -85,6 +85,7 @@ private manageProfilesBrowserProxy_: ManageProfilesBrowserProxy = ManageProfilesBrowserProxyImpl.getInstance(); private resizeObserver_: ResizeObserver|null = null; + private previousRoute_: Routes|null = null; override ready() { super.ready(); @@ -95,6 +96,8 @@ if (!isProfileCreationAllowed()) { this.$.addProfile.style.display = 'none'; } + + this.addEventListener('view-enter-finish', this.onViewEnterFinish_); } override connectedCallback() { @@ -112,6 +115,21 @@ this.resizeObserver_!.disconnect(); } + override onRouteChange(route: Routes) { + if (route === Routes.MAIN) { + return; + } + this.previousRoute_ = route; + } + + private onViewEnterFinish_() { + if (this.previousRoute_ !== Routes.NEW_PROFILE) { + return; + } + // Focus the 'Add' button if coming back from the Add Profile flow. + this.$.addProfile.focus(); + } + private addResizeObserver_() { const profilesContainer = this.$.profilesContainer; this.resizeObserver_ = new ResizeObserver(() => {
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc index 754917e..02354b61 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc
@@ -22,7 +22,6 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "chrome/browser/browser_process.h" @@ -155,8 +154,8 @@ base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})), scoped_temp_dir_(new base::ScopedTempDir(), base::OnTaskRunnerDeleter(blocking_task_runner_)) { - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ChromeCleanerFetcher::CreateTemporaryDirectory, base::Unretained(this)), base::BindOnce(&ChromeCleanerFetcher::OnTemporaryDirectoryCreated,
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_win.cc index 0dd1fc5f..22d278b 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_win.cc
@@ -21,7 +21,6 @@ #include "base/process/launch.h" #include "base/process/process.h" #include "base/sequence_checker.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/trace_event/typed_macros.h" @@ -278,9 +277,8 @@ // invocations are finished. auto reporter_done = base::BindOnce( &ReporterRunner::ReporterDone, base::Unretained(this), next_invocation); - base::PostTaskAndReplyWithResult(task_runner, FROM_HERE, - std::move(launch_and_wait), - std::move(reporter_done)); + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, std::move(launch_and_wait), std::move(reporter_done)); } // This method is called on the UI thread when an invocation of the reporter
diff --git a/chrome/browser/sessions/session_restore.cc b/chrome/browser/sessions/session_restore.cc index 2208e7fc..9f6691e8 100644 --- a/chrome/browser/sessions/session_restore.cc +++ b/chrome/browser/sessions/session_restore.cc
@@ -285,8 +285,9 @@ // Restore and show the browser. const int initial_tab_count = 0; + bool did_show_browser = false; RestoreTabsToBrowser(*(*i), browser, initial_tab_count, &created_contents, - &new_group_ids); + &new_group_ids, did_show_browser); NotifySessionServiceOfRestoredTabs(browser, initial_tab_count); } @@ -658,8 +659,15 @@ // but unminimized. base::flat_map<tab_groups::TabGroupId, tab_groups::TabGroupId> new_group_ids; + // TODO(https://crbug.com/1378744): did_show_browser is for tracking + // down a bug. + bool did_show_browser = false; RestoreTabsToBrowser(*(*i), browser, initial_tab_count, created_contents, - &new_group_ids); + &new_group_ids, did_show_browser); + // Newly created browsers should be shown by RestoreTabsToBrowser. If they + // aren't shown, they are likely to be never shown. + if (browser != browser_) + DCHECK(did_show_browser); (*tab_count) += (static_cast<int>(browser->tab_strip_model()->count()) - initial_tab_count); @@ -766,7 +774,8 @@ int initial_tab_count, std::vector<RestoredTab>* created_contents, base::flat_map<tab_groups::TabGroupId, tab_groups::TabGroupId>* - new_group_ids) { + new_group_ids, + bool& did_show_browser) { DVLOG(1) << "RestoreTabsToBrowser " << window.tabs.size(); // TODO(https://crbug.com/1032348): Change to DCHECK once we understand // why some browsers don't have an active tab on startup. @@ -813,7 +822,7 @@ // windows or when launching a hosted app from the app launcher. int tab_index = i + initial_tab_count; RestoreTab(tab, browser, created_contents, new_group_ids, tab_index, - is_selected_tab, last_active_time); + is_selected_tab, last_active_time, did_show_browser); } } @@ -829,7 +838,8 @@ tab_groups::TabGroupId>* new_group_ids, const int tab_index, bool is_selected_tab, - base::TimeTicks last_active_time) { + base::TimeTicks last_active_time, + bool& did_show_browser) { // It's possible (particularly for foreign sessions) to receive a tab // without valid navigations. In that case, just skip it. // See crbug.com/154129. @@ -880,6 +890,8 @@ if (!is_selected_tab) return; + if (browser != browser_) + did_show_browser = true; ShowBrowser(browser, browser->tab_strip_model()->GetIndexOfWebContents( web_contents)); }
diff --git a/chrome/browser/signin/primary_account_policy_manager.cc b/chrome/browser/signin/primary_account_policy_manager.cc index e6a33db5..313753c 100644 --- a/chrome/browser/signin/primary_account_policy_manager.cc +++ b/chrome/browser/signin/primary_account_policy_manager.cc
@@ -8,7 +8,6 @@ #include "base/strings/utf_string_conversions.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profiles_state.h" #include "chrome/browser/signin/identity_manager_factory.h" @@ -297,13 +296,10 @@ DCHECK(profiles::IsMultipleProfilesEnabled()); - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .MaybeScheduleProfileForDeletion( - profile_path, - hide_ui_for_testing_ - ? base::DoNothing() - : base::BindOnce(&webui::OpenNewWindowForProfile), - ProfileMetrics::DELETE_PROFILE_PRIMARY_ACCOUNT_NOT_ALLOWED); + g_browser_process->profile_manager()->MaybeScheduleProfileForDeletion( + profile_path, + hide_ui_for_testing_ ? base::DoNothing() + : base::BindOnce(&webui::OpenNewWindowForProfile), + ProfileMetrics::DELETE_PROFILE_PRIMARY_ACCOUNT_NOT_ALLOWED); } #endif // defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_CHROMEOS)
diff --git a/chrome/browser/signin/signin_ui_util_browsertest.cc b/chrome/browser/signin/signin_ui_util_browsertest.cc index f95f77e..7778e28 100644 --- a/chrome/browser/signin/signin_ui_util_browsertest.cc +++ b/chrome/browser/signin/signin_ui_util_browsertest.cc
@@ -11,7 +11,6 @@ #include "base/test/bind.h" #include "build/buildflag.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" @@ -66,11 +65,8 @@ EXPECT_EQ(1, browser->tab_strip_model()->count()); // Profile deletion closes the browser. - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .MaybeScheduleProfileForDeletion( - new_profile->GetPath(), base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + g_browser_process->profile_manager()->ScheduleProfileForDeletion( + new_profile->GetPath(), base::DoNothing()); ui_test_utils::WaitForBrowserToClose(browser); EXPECT_FALSE(chrome::FindBrowserWithProfile(new_profile));
diff --git a/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc b/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc index f7508e13..66ef0a95 100644 --- a/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc +++ b/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc
@@ -22,7 +22,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "chrome/common/chrome_constants.h" @@ -311,8 +310,8 @@ void SpellcheckCustomDictionary::Load() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SpellcheckCustomDictionary::LoadDictionaryFile, custom_dictionary_path_), base::BindOnce(&SpellcheckCustomDictionary::OnLoaded,
diff --git a/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc b/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc index 04921a6..c331a7935e 100644 --- a/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc +++ b/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
@@ -17,7 +17,6 @@ #include "base/observer_list.h" #include "base/path_service.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "build/build_config.h" @@ -258,8 +257,8 @@ } #endif - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SaveDictionaryData, std::move(data), dictionary_file_.path), base::BindOnce(&SpellcheckHunspellDictionary::SaveDictionaryDataComplete, @@ -482,8 +481,8 @@ // support this language. In either case, we must use Hunspell for this // language, unless we are on Android, which doesn't support Hunspell. #if !BUILDFLAG(IS_ANDROID) && BUILDFLAG(USE_RENDERER_SPELLCHECKER) - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&InitializeDictionaryLocation, base::RetainedRef(task_runner_.get()), language_), base::BindOnce(
diff --git a/chrome/browser/storage_access_api/api_browsertest.cc b/chrome/browser/storage_access_api/api_browsertest.cc index 0b34119..40a1b696 100644 --- a/chrome/browser/storage_access_api/api_browsertest.cc +++ b/chrome/browser/storage_access_api/api_browsertest.cc
@@ -657,9 +657,9 @@ EXPECT_FALSE(storage::test::HasStorageAccessForFrame(GetFrame())); } -INSTANTIATE_TEST_CASE_P(/* no prefix */, - StorageAccessAPIBrowserTest, - testing::Combine(testing::Bool(), testing::Bool())); +INSTANTIATE_TEST_SUITE_P(/* no prefix */, + StorageAccessAPIBrowserTest, + testing::Combine(testing::Bool(), testing::Bool())); class StorageAccessAPIStorageBrowserTest : public StorageAccessAPIBaseBrowserTest, @@ -980,9 +980,9 @@ EXPECT_FALSE(storage::test::HasStorageAccessForFrame(GetFrame())); } -INSTANTIATE_TEST_CASE_P(/* no prefix */, - StorageAccessAPIForOriginBrowserTest, - testing::Combine(testing::Bool(), testing::Bool())); +INSTANTIATE_TEST_SUITE_P(/* no prefix */, + StorageAccessAPIForOriginBrowserTest, + testing::Combine(testing::Bool(), testing::Bool())); // Tests to validate First-Party Set use with `requestStorageAccessForOrigin`. class StorageAccessAPIForOriginWithFirstPartySetsBrowserTest @@ -1228,7 +1228,7 @@ .ExtractBool()); } -INSTANTIATE_TEST_CASE_P( +INSTANTIATE_TEST_SUITE_P( /* no prefix */, StorageAccessAPIForOriginExplicitlyDisabledBrowserTest, testing::Bool());
diff --git a/chrome/browser/supervised_user/supervised_user_extension_browsertest.cc b/chrome/browser/supervised_user/supervised_user_extension_browsertest.cc index 0b44aff2..be61a77 100644 --- a/chrome/browser/supervised_user/supervised_user_extension_browsertest.cc +++ b/chrome/browser/supervised_user/supervised_user_extension_browsertest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "base/files/file_path.h" +#include "chrome/browser/ash/login/test/device_state_mixin.h" #include "chrome/browser/ash/login/test/logged_in_user_mixin.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/profiles/profile.h" @@ -107,6 +108,9 @@ private: InProcessBrowserTestMixinHost mixin_host_; + ash::DeviceStateMixin device_state_{ + &mixin_host_, + ash::DeviceStateMixin::State::OOBE_COMPLETED_CONSUMER_OWNED}; // We want to log in as child user for all of the PRE tests, and regular user // otherwise. ash::LoggedInUserMixin logged_in_user_mixin_{
diff --git a/chrome/browser/supervised_user/web_approvals_manager.cc b/chrome/browser/supervised_user/web_approvals_manager.cc index 30d1eb9..de86e06 100644 --- a/chrome/browser/supervised_user/web_approvals_manager.cc +++ b/chrome/browser/supervised_user/web_approvals_manager.cc
@@ -20,7 +20,6 @@ #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h" #include "components/url_matcher/url_util.h" #include "content/public/browser/web_contents.h" -#include "ui/gfx/codec/png_codec.h" #include "url/gurl.h" #if BUILDFLAG(IS_ANDROID) @@ -28,11 +27,23 @@ #endif // BUILDFLAG(IS_ANDROID) #if BUILDFLAG(IS_CHROMEOS_ASH) -#include "chrome/browser/ui/webui/ash/parent_access/parent_access_ui.mojom.h" -#endif // BUILDFLAG(IS_CHROMEOS_ASH) +#include "base/notreached.h" +#include "chrome/browser/ash/crosapi/crosapi_ash.h" +#include "chrome/browser/ash/crosapi/crosapi_manager.h" +#include "chrome/browser/ash/crosapi/parent_access_ash.h" +#endif namespace { +#if BUILDFLAG(IS_CHROMEOS_ASH) +crosapi::mojom::ParentAccess* GetParentAccess() { + crosapi::mojom::ParentAccess* parent_access = + crosapi::CrosapiManager::Get()->crosapi_ash()->parent_access_ash(); + DCHECK(parent_access); + return parent_access; +} +#endif + constexpr char kLocalWebApprovalDurationHistogramName[] = "FamilyLinkUser.LocalWebApprovalCompleteRequestTotalDuration"; constexpr char kLocalWebApprovalResultHistogramName[] = @@ -61,18 +72,40 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) WebApprovalsManager::LocalApprovalResult ChromeOSResultToLocalApprovalResult( - ash::ParentAccessDialog::Result::Status result) { + crosapi::mojom::ParentAccessResult::Tag result) { switch (result) { - case ash::ParentAccessDialog::Result::Status::kApproved: + case crosapi::mojom::ParentAccessResult::Tag::kApproved: return WebApprovalsManager::LocalApprovalResult::kApproved; - case ash::ParentAccessDialog::Result::Status::kDeclined: + case crosapi::mojom::ParentAccessResult::Tag::kDeclined: return WebApprovalsManager::LocalApprovalResult::kDeclined; - case ash::ParentAccessDialog::Result::Status::kCanceled: + case crosapi::mojom::ParentAccessResult::Tag::kCanceled: return WebApprovalsManager::LocalApprovalResult::kCanceled; - case ash::ParentAccessDialog::Result::Status::kError: + case crosapi::mojom::ParentAccessResult::Tag::kError: return WebApprovalsManager::LocalApprovalResult::kError; } } + +void HandleChromeOSErrorResult( + crosapi::mojom::ParentAccessErrorResult::Type type) { + switch (type) { + case crosapi::mojom::ParentAccessErrorResult::Type::kNotAChildUser: + // Fatal debug error because this can only occur due to a programming + // error. + DLOG(FATAL) << "ParentAccess UI invoked by non-child user"; + return; + case crosapi::mojom::ParentAccessErrorResult::Type::kAlreadyVisible: + // Fatal debug error because this can only occur due to a programming + // error. + DLOG(FATAL) << "ParentAccess UI invoked while instance already visible"; + return; + case crosapi::mojom::ParentAccessErrorResult::Type::kUnknown: + LOG(ERROR) << "Unknown error in ParentAccess UI"; + return; + case crosapi::mojom::ParentAccessErrorResult::Type::kNone: + NOTREACHED(); + return; + } +} #endif // BUILDFLAG(IS_CHROMEOS_ASH) std::string LocalApprovalResultToString( @@ -123,38 +156,16 @@ const gfx::ImageSkia& favicon, ApprovalRequestInitiatedCallback callback) { #if BUILDFLAG(IS_CHROMEOS_ASH) - // TODO(b/250954669): replace this with call to the ParentAccess crosapi with - // appropriate parameters and handle the ParentAccess crosapi result. SupervisedUserSettingsService* settings_service = SupervisedUserSettingsServiceFactory::GetForKey( Profile::FromBrowserContext(web_contents->GetBrowserContext()) ->GetProfileKey()); - std::vector<uint8_t> favicon_bytes; - gfx::PNGCodec::FastEncodeBGRASkBitmap(*favicon.bitmap(), false, - &favicon_bytes); - parent_access_ui::mojom::ParentAccessParamsPtr params = - parent_access_ui::mojom::ParentAccessParams::New( - parent_access_ui::mojom::ParentAccessParams::FlowType::kWebsiteAccess, - parent_access_ui::mojom::FlowTypeParams::NewWebApprovalsParams( - parent_access_ui::mojom::WebApprovalsParams::New( - url.GetWithEmptyPath(), child_display_name, favicon_bytes))); - - ash::ParentAccessDialogProvider provider; - ash::ParentAccessDialogProvider::ShowError result = provider.Show( - std::move(params), + GetParentAccess()->GetWebsiteParentApproval( + url.GetWithEmptyPath(), child_display_name, favicon, base::BindOnce( &WebApprovalsManager::OnLocalApprovalRequestCompletedChromeOS, weak_ptr_factory_.GetWeakPtr(), settings_service, url, base::TimeTicks::Now())); - - if (result != ash::ParentAccessDialogProvider::ShowError::kNone) { - LOG(ERROR) << "Error showing ParentAccessDialog: " - << static_cast<int>(result); - base::UmaHistogramEnumeration(kLocalWebApprovalResultHistogramName, - LocalApprovalResult::kError); - std::move(callback).Run(false); - return; - } std::move(callback).Run(true); #elif BUILDFLAG(IS_ANDROID) SupervisedUserSettingsService* settings_service = @@ -278,9 +289,12 @@ SupervisedUserSettingsService* settings_service, const GURL& url, base::TimeTicks start_time, - std::unique_ptr<ash::ParentAccessDialog::Result> result) { + crosapi::mojom::ParentAccessResultPtr result) { CompleteLocalApprovalRequest( settings_service, url, start_time, - ChromeOSResultToLocalApprovalResult(result->status)); + ChromeOSResultToLocalApprovalResult(result->which())); + + if (result->is_error()) + HandleChromeOSErrorResult(result->get_error()->type); } #endif // BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/browser/supervised_user/web_approvals_manager.h b/chrome/browser/supervised_user/web_approvals_manager.h index 37b2c58..2e6b4d34 100644 --- a/chrome/browser/supervised_user/web_approvals_manager.h +++ b/chrome/browser/supervised_user/web_approvals_manager.h
@@ -19,7 +19,7 @@ #include "ui/gfx/image/image_skia.h" #if BUILDFLAG(IS_CHROMEOS_ASH) -#include "chrome/browser/ui/webui/ash/parent_access/parent_access_dialog.h" +#include "chromeos/crosapi/mojom/parent_access.mojom.h" #endif #if BUILDFLAG(IS_ANDROID) @@ -155,7 +155,7 @@ SupervisedUserSettingsService* settings_service, const GURL& url, base::TimeTicks start_time, - std::unique_ptr<ash::ParentAccessDialog::Result> result); + crosapi::mojom::ParentAccessResultPtr result); #endif // BUILDFLAG(IS_CHROMEOS_ASH) // Helpers for private method testing.
diff --git a/chrome/browser/supervised_user/web_approvals_manager_unittest.cc b/chrome/browser/supervised_user/web_approvals_manager_unittest.cc index 52b2e63f..fbda9d2 100644 --- a/chrome/browser/supervised_user/web_approvals_manager_unittest.cc +++ b/chrome/browser/supervised_user/web_approvals_manager_unittest.cc
@@ -25,7 +25,7 @@ #endif // BUILDFLAG(IS_ANDROID) #if BUILDFLAG(IS_CHROMEOS_ASH) -#include "chrome/browser/ui/webui/ash/parent_access/parent_access_dialog.h" +#include "chromeos/crosapi/mojom/parent_access.mojom.h" #endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace { @@ -288,8 +288,9 @@ EXPECT_CALL(supervisedUserSettingsServiceMock, RecordLocalWebsiteApproval(url.host())); - auto dialog_result = std::make_unique<ash::ParentAccessDialog::Result>(); - dialog_result->status = ash::ParentAccessDialog::Result::Status::kApproved; + auto result = crosapi::mojom::ParentAccessResult::NewApproved( + crosapi::mojom::ParentAccessApprovedResult::New( + "TEST_TOKEN", base::Time::FromDoubleT(123456UL))); // Capture approval start time and forward clock by the fake approval // duration. @@ -298,8 +299,7 @@ task_environment().FastForwardBy(approval_duration); web_approvals_manager().OnLocalApprovalRequestCompletedChromeOS( - &supervisedUserSettingsServiceMock, url, start_time, - std::move(dialog_result)); + &supervisedUserSettingsServiceMock, url, start_time, std::move(result)); histogram_tester.ExpectUniqueSample( WebApprovalsManager::GetLocalApprovalResultHistogram(), @@ -321,8 +321,8 @@ RecordLocalWebsiteApproval(url.host())) .Times(0); - auto dialog_result = std::make_unique<ash::ParentAccessDialog::Result>(); - dialog_result->status = ash::ParentAccessDialog::Result::Status::kDeclined; + auto result = crosapi::mojom::ParentAccessResult::NewDeclined( + crosapi::mojom::ParentAccessDeclinedResult::New()); // Capture approval start time and forward clock by the fake approval // duration. @@ -331,8 +331,7 @@ task_environment().FastForwardBy(approval_duration); web_approvals_manager().OnLocalApprovalRequestCompletedChromeOS( - &supervisedUserSettingsServiceMock, url, start_time, - std::move(dialog_result)); + &supervisedUserSettingsServiceMock, url, start_time, std::move(result)); histogram_tester.ExpectUniqueSample( WebApprovalsManager::GetLocalApprovalResultHistogram(), @@ -354,8 +353,8 @@ RecordLocalWebsiteApproval(url.host())) .Times(0); - auto dialog_result = std::make_unique<ash::ParentAccessDialog::Result>(); - dialog_result->status = ash::ParentAccessDialog::Result::Status::kCanceled; + auto result = crosapi::mojom::ParentAccessResult::NewCanceled( + crosapi::mojom::ParentAccessCanceledResult::New()); // Capture approval start time and forward clock by the fake approval // duration. @@ -364,8 +363,7 @@ task_environment().FastForwardBy(approval_duration); web_approvals_manager().OnLocalApprovalRequestCompletedChromeOS( - &supervisedUserSettingsServiceMock, url, start_time, - std::move(dialog_result)); + &supervisedUserSettingsServiceMock, url, start_time, std::move(result)); // Check that the approval duration was NOT recorded for canceled request. histogram_tester.ExpectTotalCount( @@ -385,8 +383,9 @@ RecordLocalWebsiteApproval(url.host())) .Times(0); - auto dialog_result = std::make_unique<ash::ParentAccessDialog::Result>(); - dialog_result->status = ash::ParentAccessDialog::Result::Status::kError; + auto result = crosapi::mojom::ParentAccessResult::NewError( + crosapi::mojom::ParentAccessErrorResult::New( + crosapi::mojom::ParentAccessErrorResult::Type::kUnknown)); // Capture approval start time and forward clock by the fake approval // duration. @@ -395,8 +394,7 @@ task_environment().FastForwardBy(approval_duration); web_approvals_manager().OnLocalApprovalRequestCompletedChromeOS( - &supervisedUserSettingsServiceMock, url, start_time, - std::move(dialog_result)); + &supervisedUserSettingsServiceMock, url, start_time, std::move(result)); // Check that the approval duration was NOT recorded on error. histogram_tester.ExpectTotalCount(
diff --git a/chrome/browser/sync/sync_encryption_keys_tab_helper_unittest.cc b/chrome/browser/sync/sync_encryption_keys_tab_helper_unittest.cc index 5d3b65f..be3d355 100644 --- a/chrome/browser/sync/sync_encryption_keys_tab_helper_unittest.cc +++ b/chrome/browser/sync/sync_encryption_keys_tab_helper_unittest.cc
@@ -103,7 +103,9 @@ EXPECT_FALSE(HasEncryptionKeysApiInMainFrame()); } -TEST_F(SyncEncryptionKeysTabHelperTest, ShouldNotExposeMojoApiIfNavigatedAway) { +// TODO(https://crbug.com/1394191): flaky on android bots. +TEST_F(SyncEncryptionKeysTabHelperTest, + DISABLED_ShouldNotExposeMojoApiIfNavigatedAway) { web_contents_tester()->NavigateAndCommit(GaiaUrls::GetInstance()->gaia_url()); ASSERT_TRUE(HasEncryptionKeysApiInMainFrame()); web_contents_tester()->NavigateAndCommit(GURL("http://page.com")); @@ -136,8 +138,9 @@ EXPECT_FALSE(HasEncryptionKeysApiInMainFrame()); } +// TODO(https://crbug.com/1394191): flaky on android bots. TEST_F(SyncEncryptionKeysTabHelperTest, - ShouldNotExposeMojoApiIfNavigatedAwayToErrorPage) { + DISABLED_ShouldNotExposeMojoApiIfNavigatedAwayToErrorPage) { web_contents_tester()->NavigateAndCommit(GaiaUrls::GetInstance()->gaia_url()); ASSERT_TRUE(HasEncryptionKeysApiInMainFrame());
diff --git a/chrome/browser/sync_file_system/local/local_file_sync_context.cc b/chrome/browser/sync_file_system/local/local_file_sync_context.cc index 873715f..15f1792a9 100644 --- a/chrome/browser/sync_file_system/local/local_file_sync_context.cc +++ b/chrome/browser/sync_file_system/local/local_file_sync_context.cc
@@ -15,7 +15,6 @@ #include "base/location.h" #include "base/observer_list.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "chrome/browser/sync_file_system/file_change.h" #include "chrome/browser/sync_file_system/local/local_file_change_tracker.h" #include "chrome/browser/sync_file_system/local/local_origin_change_observer.h" @@ -122,8 +121,8 @@ DCHECK(file_system_context); DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); - base::PostTaskAndReplyWithResult( - file_system_context->default_file_task_runner(), FROM_HERE, + file_system_context->default_file_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LocalFileSyncContext::GetNextURLsForSyncOnFileThread, this, base::RetainedRef(file_system_context)), base::BindOnce(&LocalFileSyncContext::TryPrepareForLocalSync, this, @@ -655,8 +654,8 @@ std::set<GURL>* origins_with_changes = new std::set<GURL>; std::unique_ptr<LocalFileChangeTracker>* tracker_ptr( new std::unique_ptr<LocalFileChangeTracker>); - base::PostTaskAndReplyWithResult( - file_system_context->default_file_task_runner(), FROM_HERE, + file_system_context->default_file_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &LocalFileSyncContext::InitializeChangeTrackerOnFileThread, this, tracker_ptr, base::RetainedRef(file_system_context),
diff --git a/chrome/browser/task_manager/sampling/shared_sampler_win.cc b/chrome/browser/task_manager/sampling/shared_sampler_win.cc index e720f45aa..54c362c 100644 --- a/chrome/browser/task_manager/sampling/shared_sampler_win.cc +++ b/chrome/browser/task_manager/sampling/shared_sampler_win.cc
@@ -13,7 +13,6 @@ #include "base/bit_cast.h" #include "base/command_line.h" #include "base/path_service.h" -#include "base/task/task_runner_util.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "chrome/browser/task_manager/sampling/shared_sampler_win_defines.h" @@ -290,9 +289,8 @@ DCHECK(callbacks_map_.find(process_id) != callbacks_map_.end()); if (refresh_flags_ == 0) { - base::PostTaskAndReplyWithResult( - blocking_pool_runner_.get(), FROM_HERE, - base::BindOnce(&SharedSampler::RefreshOnWorkerThread, this), + blocking_pool_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SharedSampler::RefreshOnWorkerThread, this), base::BindOnce(&SharedSampler::OnRefreshDone, this)); } else { // http://crbug.com/678471
diff --git a/chrome/browser/task_manager/sampling/task_group_sampler.cc b/chrome/browser/task_manager/sampling/task_group_sampler.cc index 218df0a0..212bfc45 100644 --- a/chrome/browser/task_manager/sampling/task_group_sampler.cc +++ b/chrome/browser/task_manager/sampling/task_group_sampler.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/callback.h" #include "base/process/process_metrics.h" -#include "base/task/task_runner_util.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/task_manager/task_manager_observer.h" @@ -73,25 +72,23 @@ if (TaskManagerObserver::IsResourceRefreshEnabled(REFRESH_TYPE_CPU, refresh_flags)) { - base::PostTaskAndReplyWithResult( - blocking_pool_runner_.get(), FROM_HERE, - base::BindOnce(&TaskGroupSampler::RefreshCpuUsage, this), + blocking_pool_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&TaskGroupSampler::RefreshCpuUsage, this), base::BindOnce(on_cpu_refresh_callback_)); } if (TaskManagerObserver::IsResourceRefreshEnabled(REFRESH_TYPE_SWAPPED_MEM, refresh_flags)) { - base::PostTaskAndReplyWithResult( - blocking_pool_runner_.get(), FROM_HERE, - base::BindOnce(&TaskGroupSampler::RefreshSwappedMem, this), + blocking_pool_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&TaskGroupSampler::RefreshSwappedMem, this), base::BindOnce(on_swapped_mem_refresh_callback_)); } #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) if (TaskManagerObserver::IsResourceRefreshEnabled(REFRESH_TYPE_IDLE_WAKEUPS, refresh_flags)) { - base::PostTaskAndReplyWithResult( - blocking_pool_runner_.get(), FROM_HERE, + blocking_pool_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&TaskGroupSampler::RefreshIdleWakeupsPerSecond, this), base::BindOnce(on_idle_wakeups_callback_)); } @@ -100,17 +97,16 @@ #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC) if (TaskManagerObserver::IsResourceRefreshEnabled(REFRESH_TYPE_FD_COUNT, refresh_flags)) { - base::PostTaskAndReplyWithResult( - blocking_pool_runner_.get(), FROM_HERE, - base::BindOnce(&TaskGroupSampler::RefreshOpenFdCount, this), + blocking_pool_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&TaskGroupSampler::RefreshOpenFdCount, this), base::BindOnce(on_open_fd_count_callback_)); } #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC) if (TaskManagerObserver::IsResourceRefreshEnabled(REFRESH_TYPE_PRIORITY, refresh_flags)) { - base::PostTaskAndReplyWithResult( - blocking_pool_runner_.get(), FROM_HERE, + blocking_pool_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&TaskGroupSampler::RefreshProcessPriority, this), base::BindOnce(on_process_priority_callback_)); }
diff --git a/chrome/browser/thumbnail/generator/android/thumbnail_media_parser_impl.cc b/chrome/browser/thumbnail/generator/android/thumbnail_media_parser_impl.cc index 44eb514..18119c01 100644 --- a/chrome/browser/thumbnail/generator/android/thumbnail_media_parser_impl.cc +++ b/chrome/browser/thumbnail/generator/android/thumbnail_media_parser_impl.cc
@@ -10,7 +10,6 @@ #include "base/files/file.h" #include "base/files/file_util.h" #include "base/numerics/safe_conversions.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "cc/paint/skia_paint_canvas.h" @@ -82,9 +81,8 @@ } // Get the size of the file if needed. - base::PostTaskAndReplyWithResult( - file_task_runner_.get(), FROM_HERE, - base::BindOnce(&GetFileSize, file_path_), + file_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetFileSize, file_path_), base::BindOnce(&ThumbnailMediaParserImpl::OnReadFileSize, weak_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/LocationBarModel.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/LocationBarModel.java index 9484fc0e3..befa0471 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/LocationBarModel.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/LocationBarModel.java
@@ -308,9 +308,13 @@ return tab != null && tab.isInitialized() ? tab.getUrl() : GURL.emptyGURL(); } + /** + * Reterived updated cached values for the current URL. + * @return whether the URL value has changed. + */ @VisibleForTesting - void updateVisibleGurl() { - if (!mOptimizationsEnabled) return; + boolean updateVisibleGurl() { + if (!mOptimizationsEnabled) return true; try (TraceEvent te = TraceEvent.scoped("LocationBarModel.updateVisibleGurl")) { if (isInOverviewAndShowingOmnibox()) { mFormattedFullUrl = ""; @@ -322,12 +326,16 @@ if (!gurl.equals(mVisibleGurl)) { mVisibleGurl = gurl; recalculateFormattedUrls(); + return true; } } + return false; } public void notifyUrlChanged() { - updateVisibleGurl(); + if (!updateVisibleGurl()) return; + // Url has changed, propagate it. + for (LocationBarDataProvider.Observer observer : mLocationBarDataObservers) { observer.onUrlChanged(); }
diff --git a/chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc b/chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc index b8974193..343e5f2e 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc +++ b/chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc
@@ -28,7 +28,6 @@ #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/values.h" #include "chrome/browser/ash/arc/arc_util.h" @@ -2265,8 +2264,8 @@ GetForegroundIconPath(app_id, descriptor); const base::FilePath background_icon_path = GetBackgroundIconPath(app_id, descriptor); - base::PostTaskAndReplyWithResult( - file_task_runner_.get(), FROM_HERE, + file_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&InstallIconFromFileThread, icon_path, foreground_icon_path, background_icon_path, std::move(icon)),
diff --git a/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc b/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc index e5a6a3c..73e3bd85 100644 --- a/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc +++ b/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc
@@ -22,6 +22,7 @@ #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/ash/drive/drive_integration_service.h" #include "chrome/browser/ash/drive/drivefs_test_support.h" +#include "chrome/browser/ash/login/test/device_state_mixin.h" #include "chrome/browser/ash/login/test/fake_gaia_mixin.h" #include "chrome/browser/ash/login/test/logged_in_user_mixin.h" #include "chrome/browser/ash/system_web_apps/system_web_app_manager.h" @@ -376,6 +377,8 @@ } private: + DeviceStateMixin device_state_{ + &mixin_host_, DeviceStateMixin::State::OOBE_COMPLETED_CONSUMER_OWNED}; LoggedInUserMixin logged_in_user_mixin_{ &mixin_host_, is_child() ? LoggedInUserMixin::LogInType::kChild
diff --git a/chrome/browser/ui/ash/shelf/chrome_shelf_controller.cc b/chrome/browser/ui/ash/shelf/chrome_shelf_controller.cc index 2e95453a..6102315f 100644 --- a/chrome/browser/ui/ash/shelf/chrome_shelf_controller.cc +++ b/chrome/browser/ui/ash/shelf/chrome_shelf_controller.cc
@@ -33,7 +33,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" @@ -1106,9 +1105,8 @@ copy = image.DeepCopy(); } - base::PostTaskAndReplyWithResult( - standard_icon_task_runner_.get(), FROM_HERE, - base::BindOnce(&CreateStandardImageOnWorkerThread, copy), + standard_icon_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CreateStandardImageOnWorkerThread, copy), base::BindOnce(&ChromeShelfController::UpdateAppImage, weak_ptr_factory_.GetWeakPtr(), app_id)); }
diff --git a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc index 0de6c7b78..dc4caa5 100644 --- a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc +++ b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc
@@ -67,7 +67,8 @@ this, &GetWebContents()); DCHECK(dialog_view_); - AutofillMetrics::LogCardUnmaskAuthenticationSelectionDialogShown(); + AutofillMetrics::LogCardUnmaskAuthenticationSelectionDialogShown( + challenge_options_.size()); } void CardUnmaskAuthenticationSelectionDialogControllerImpl::
diff --git a/chrome/browser/ui/browser.cc b/chrome/browser/ui/browser.cc index e1273f18..7cbabbcd 100644 --- a/chrome/browser/ui/browser.cc +++ b/chrome/browser/ui/browser.cc
@@ -69,7 +69,6 @@ #include "chrome/browser/printing/background_printing_manager.h" #include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h" #include "chrome/browser/profiles/keep_alive/scoped_profile_keep_alive.h" -#include "chrome/browser/profiles/nuke_profile_directory_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_destroyer.h" #include "chrome/browser/profiles/profile_manager.h" @@ -432,7 +431,7 @@ if (!IncognitoModePrefs::CanOpenBrowser(profile) || (profile->IsGuestSession() && !profile->IsOffTheRecord()) || !profile->AllowsBrowserWindows() || - IsProfileDirectoryMarkedForDeletion(profile->GetPath())) { + ProfileManager::IsProfileDirectoryMarkedForDeletion(profile->GetPath())) { return CreationStatus::kErrorProfileUnsuitable; }
diff --git a/chrome/browser/ui/browser_element_identifiers.cc b/chrome/browser/ui/browser_element_identifiers.cc index 6c0aa423..a246dfe 100644 --- a/chrome/browser/ui/browser_element_identifiers.cc +++ b/chrome/browser/ui/browser_element_identifiers.cc
@@ -8,6 +8,7 @@ #include "ui/base/interaction/element_tracker.h" // Please keep this list alphabetized. +DEFINE_ELEMENT_IDENTIFIER_VALUE(kAddCurrentTabToReadingListElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kAppMenuButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kAppUninstallDialogOkButtonId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kAutofillCreditCardSuggestionEntryElementId); @@ -26,7 +27,9 @@ DEFINE_ELEMENT_IDENTIFIER_VALUE(kReadLaterButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kReadLaterSidePanelWebViewElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelCloseButtonElementId); +DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelComboboxElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelOpenInNewTabButtonElementId); +DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelReadingListUnreadElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSavePasswordComboboxElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSideSearchButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabAlertIndicatorButtonElementId); @@ -42,3 +45,5 @@ DEFINE_ELEMENT_IDENTIFIER_VALUE(kWebUIIPHDemoElementIdentifier); DEFINE_CUSTOM_ELEMENT_EVENT_TYPE(kTabGroupedCustomEventId); +DEFINE_CUSTOM_ELEMENT_EVENT_TYPE(kSidePanelComboboxChangedCustomEventId); +DEFINE_CUSTOM_ELEMENT_EVENT_TYPE(kSidePanelReadingMarkedAsReadEventId);
diff --git a/chrome/browser/ui/browser_element_identifiers.h b/chrome/browser/ui/browser_element_identifiers.h index fa375e0..b7b5f96 100644 --- a/chrome/browser/ui/browser_element_identifiers.h +++ b/chrome/browser/ui/browser_element_identifiers.h
@@ -17,6 +17,7 @@ // These should gradually replace values in view_ids.h. // Please keep this list alphabetized. +DECLARE_ELEMENT_IDENTIFIER_VALUE(kAddCurrentTabToReadingListElementId); DECLARE_ELEMENT_IDENTIFIER_VALUE(kAppMenuButtonElementId); DECLARE_ELEMENT_IDENTIFIER_VALUE(kAppUninstallDialogOkButtonId); DECLARE_ELEMENT_IDENTIFIER_VALUE(kAutofillCreditCardSuggestionEntryElementId); @@ -35,7 +36,9 @@ DECLARE_ELEMENT_IDENTIFIER_VALUE(kReadLaterButtonElementId); DECLARE_ELEMENT_IDENTIFIER_VALUE(kReadLaterSidePanelWebViewElementId); DECLARE_ELEMENT_IDENTIFIER_VALUE(kSidePanelCloseButtonElementId); +DECLARE_ELEMENT_IDENTIFIER_VALUE(kSidePanelComboboxElementId); DECLARE_ELEMENT_IDENTIFIER_VALUE(kSidePanelOpenInNewTabButtonElementId); +DECLARE_ELEMENT_IDENTIFIER_VALUE(kSidePanelReadingListUnreadElementId); DECLARE_ELEMENT_IDENTIFIER_VALUE(kSavePasswordComboboxElementId); DECLARE_ELEMENT_IDENTIFIER_VALUE(kSideSearchButtonElementId); DECLARE_ELEMENT_IDENTIFIER_VALUE(kTabAlertIndicatorButtonElementId); @@ -51,5 +54,7 @@ DECLARE_ELEMENT_IDENTIFIER_VALUE(kWebUIIPHDemoElementIdentifier); DECLARE_CUSTOM_ELEMENT_EVENT_TYPE(kTabGroupedCustomEventId); +DECLARE_CUSTOM_ELEMENT_EVENT_TYPE(kSidePanelComboboxChangedCustomEventId); +DECLARE_CUSTOM_ELEMENT_EVENT_TYPE(kSidePanelReadingMarkedAsReadEventId); #endif // CHROME_BROWSER_UI_BROWSER_ELEMENT_IDENTIFIERS_H_
diff --git a/chrome/browser/ui/color/new_tab_page_color_mixer.cc b/chrome/browser/ui/color/new_tab_page_color_mixer.cc index 50c2359..3f345dde 100644 --- a/chrome/browser/ui/color/new_tab_page_color_mixer.cc +++ b/chrome/browser/ui/color/new_tab_page_color_mixer.cc
@@ -95,13 +95,11 @@ ui::ColorTransform primary_foreground_color = ui::GetColorWithMaxContrast(element_background_color); ui::ColorTransform themed_foreground_color = SelectBasedOnWhiteNtpBackground( - {primary_foreground_color}, + {gfx::kGoogleBlue600}, ui::PickGoogleColor(element_background_color, element_background_color, color_utils::kMinimumReadableContrastRatio)); - const ui::ColorTransform select_topmost_element_background_color = - SelectBasedOnWhiteNtpBackground(gfx::kGoogleBlue600, - themed_foreground_color); + themed_foreground_color; const ui::ColorTransform select_topmost_element_foreground_color = GetColorWithMaxContrast(select_topmost_element_background_color); @@ -112,8 +110,7 @@ mixer[kColorNewTabPageBorder] = SelectBasedOnWhiteNtpBackground( {gfx::kGoogleGrey300}, element_background_color); mixer[kColorNewTabPageChipBackground] = element_background_color; - mixer[kColorNewTabPageButtonBackground] = SelectBasedOnWhiteNtpBackground( - {ui::kColorFrameActive}, element_background_color); + mixer[kColorNewTabPageButtonBackground] = element_background_color; mixer[kColorNewTabPageButtonForeground] = themed_foreground_color; mixer[kColorNewTabPageCartModuleDiscountChipBackground] = SelectBasedOnDarkInput(element_background_color, gfx::kGoogleGrey800, @@ -128,10 +125,7 @@ ui::SetAlpha({gfx::kGoogleGrey900}, /* 10% opacity */ 0.1 * SK_AlphaOPAQUE)); mixer[kColorNewTabPageLogo] = element_background_color; - mixer[kColorNewTabPageLink] = SelectBasedOnWhiteNtpBackground( - ui::PickGoogleColor({ui::kColorFrameActive}, element_background_color, - color_utils::kMinimumReadableContrastRatio), - themed_foreground_color); + mixer[kColorNewTabPageLink] = themed_foreground_color; mixer[kColorNewTabPageFirstRunBackground] = {kColorNewTabPageBackground}; mixer[kColorNewTabPageModuleBackground] = element_background_color; mixer[kColorNewTabPageChipBackground] =
diff --git a/chrome/browser/ui/color/new_tab_page_color_mixer_unittest.cc b/chrome/browser/ui/color/new_tab_page_color_mixer_unittest.cc index d6d18b6..93ea8c9 100644 --- a/chrome/browser/ui/color/new_tab_page_color_mixer_unittest.cc +++ b/chrome/browser/ui/color/new_tab_page_color_mixer_unittest.cc
@@ -118,7 +118,11 @@ EXPECT_EQ(provider.GetColor(kColorToolbar), kSampleToolbarColor); EXPECT_EQ(provider.GetColor(kColorNewTabPageBackground), kSampleToolbarColor); - EXPECT_EQ(provider.GetColor(kColorNewTabPageButtonBackground), SK_ColorBLUE); + EXPECT_EQ(provider.GetColor(kColorNewTabPageButtonBackground), + kSampleToolbarColor); + EXPECT_EQ(provider.GetColor(kColorNewTabPageButtonForeground), + gfx::kGoogleBlue600); + EXPECT_EQ(provider.GetColor(kColorNewTabPageLink), gfx::kGoogleBlue600); } } // namespace
diff --git a/chrome/browser/ui/hats/mock_trust_safety_sentiment_service.h b/chrome/browser/ui/hats/mock_trust_safety_sentiment_service.h index f3585af6..57b7aec 100644 --- a/chrome/browser/ui/hats/mock_trust_safety_sentiment_service.h +++ b/chrome/browser/ui/hats/mock_trust_safety_sentiment_service.h
@@ -41,6 +41,11 @@ InteractedWithPrivacySandbox3, (FeatureArea feature_area), (override)); + MOCK_METHOD(void, RanPasswordCheck, (), (override)); + MOCK_METHOD(void, + ClearedBrowsingData, + (browsing_data::BrowsingDataType datatype), + (override)); MOCK_METHOD(void, FinishedPrivacyGuide, (), (override)); };
diff --git a/chrome/browser/ui/passwords/bubble_controllers/items_bubble_controller.cc b/chrome/browser/ui/passwords/bubble_controllers/items_bubble_controller.cc index 721f262..2b5d07e 100644 --- a/chrome/browser/ui/passwords/bubble_controllers/items_bubble_controller.cc +++ b/chrome/browser/ui/passwords/bubble_controllers/items_bubble_controller.cc
@@ -6,6 +6,8 @@ #include "base/strings/utf_string_conversions.h" #include "chrome/browser/favicon/favicon_service_factory.h" +#include "chrome/browser/password_manager/account_password_store_factory.h" +#include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/password_manager/password_store_utils.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/sync/sync_service_factory.h" @@ -68,8 +70,14 @@ Profile* profile = GetProfile(); if (!profile) return; - password_manager::PasswordStoreInterface* password_store = - GetPasswordStore(profile, password_form.IsUsingAccountStore()); + scoped_refptr<password_manager::PasswordStoreInterface> password_store = + password_form.IsUsingAccountStore() + ? AccountPasswordStoreFactory::GetForProfile( + profile, ServiceAccessType::EXPLICIT_ACCESS) + .get() + : PasswordStoreFactory::GetForProfile( + profile, ServiceAccessType::EXPLICIT_ACCESS) + .get(); DCHECK(password_store); if (action == PasswordAction::kRemovePassword)
diff --git a/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc b/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc index c4331ad..b5180df 100644 --- a/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc +++ b/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.h" #include "chrome/browser/ui/browser.h" @@ -12,16 +13,27 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/metrics/autofill_metrics.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "content/public/test/browser_test.h" namespace autofill { +// Parameters of the CardUnmaskAuthenticationSelectionDialogBrowserTest. +using ChallengeOptionTypes = std::vector<CardUnmaskChallengeOptionType>; +using EnableCvcForVcnYellowPathIsEnabled = bool; + class CardUnmaskAuthenticationSelectionDialogBrowserTest : public DialogBrowserTest, public testing::WithParamInterface< - std::vector<CardUnmaskChallengeOptionType>> { + std::tuple<ChallengeOptionTypes, + EnableCvcForVcnYellowPathIsEnabled>> { public: - CardUnmaskAuthenticationSelectionDialogBrowserTest() = default; + CardUnmaskAuthenticationSelectionDialogBrowserTest() { + feature_list_.InitWithFeatureState( + /*feature=*/features::kAutofillEnableCvcForVcnYellowPath, + /*enabled=*/GetEnableCvcForVcnYellowPathIsEnabled()); + } + CardUnmaskAuthenticationSelectionDialogBrowserTest( const CardUnmaskAuthenticationSelectionDialogBrowserTest&) = delete; CardUnmaskAuthenticationSelectionDialogBrowserTest& operator=( @@ -68,40 +80,69 @@ FromWebContents(browser()->tab_strip_model()->GetActiveWebContents()); } + ChallengeOptionTypes GetChallengeOptionTypes() { + return std::get<0>(GetParam()); + } + + EnableCvcForVcnYellowPathIsEnabled GetEnableCvcForVcnYellowPathIsEnabled() { + return std::get<1>(GetParam()); + } + private: std::vector<CardUnmaskChallengeOption> challenge_options_list_; + base::test::ScopedFeatureList feature_list_; }; -INSTANTIATE_TEST_SUITE_P(, - CardUnmaskAuthenticationSelectionDialogBrowserTest, - testing::Values( - std::vector<CardUnmaskChallengeOptionType>{ - CardUnmaskChallengeOptionType::kSmsOtp}, - std::vector<CardUnmaskChallengeOptionType>{ - CardUnmaskChallengeOptionType::kSmsOtp, - CardUnmaskChallengeOptionType::kCvc})); +INSTANTIATE_TEST_SUITE_P( + , + CardUnmaskAuthenticationSelectionDialogBrowserTest, + testing::Combine(testing::Values( + std::vector<CardUnmaskChallengeOptionType>{ + CardUnmaskChallengeOptionType::kSmsOtp}, + std::vector<CardUnmaskChallengeOptionType>{ + CardUnmaskChallengeOptionType::kSmsOtp, + CardUnmaskChallengeOptionType::kCvc}), + testing::Bool())); // Ensures the UI can be shown. IN_PROC_BROWSER_TEST_P(CardUnmaskAuthenticationSelectionDialogBrowserTest, InvokeUi_CardUnmaskAuthSelectionDialogDisplays) { base::HistogramTester histogram_tester; - SetChallengeOptionList(test::GetCardUnmaskChallengeOptions(GetParam())); + SetChallengeOptionList( + test::GetCardUnmaskChallengeOptions(GetChallengeOptionTypes())); ShowAndVerifyUi(); - histogram_tester.ExpectUniqueSample( - "Autofill.CardUnmaskAuthenticationSelectionDialog.Shown", true, 1); + EXPECT_THAT( + histogram_tester.GetAllSamples( + "Autofill.CardUnmaskAuthenticationSelectionDialog.Shown2"), + // If the CVC flag is on, then the count depends on the number of + // challenge options, i.e. `GetParam().size()`. If the CVC flag is + // off, it will always be 1. + base::BucketsAre(base::Bucket(GetEnableCvcForVcnYellowPathIsEnabled() + ? GetChallengeOptionTypes().size() + : 1, + 1))); } // Ensures closing tab while dialog being visible is correctly handled. IN_PROC_BROWSER_TEST_P(CardUnmaskAuthenticationSelectionDialogBrowserTest, CanCloseTabWhileDialogShowing) { base::HistogramTester histogram_tester; - SetChallengeOptionList(test::GetCardUnmaskChallengeOptions(GetParam())); + SetChallengeOptionList( + test::GetCardUnmaskChallengeOptions(GetChallengeOptionTypes())); ShowUi(""); VerifyUi(); browser()->tab_strip_model()->GetActiveWebContents()->Close(); base::RunLoop().RunUntilIdle(); - histogram_tester.ExpectUniqueSample( - "Autofill.CardUnmaskAuthenticationSelectionDialog.Shown", true, 1); + EXPECT_THAT( + histogram_tester.GetAllSamples( + "Autofill.CardUnmaskAuthenticationSelectionDialog.Shown2"), + // If the CVC flag is on, then the count depends on the number of + // challenge options, i.e. `GetParam().size()`. If the CVC flag is + // off, it will always be 1. + base::BucketsAre(base::Bucket(GetEnableCvcForVcnYellowPathIsEnabled() + ? GetChallengeOptionTypes().size() + : 1, + 1))); histogram_tester.ExpectUniqueSample( "Autofill.CardUnmaskAuthenticationSelectionDialog.Result", AutofillMetrics::CardUnmaskAuthenticationSelectionDialogResultMetric:: @@ -113,13 +154,22 @@ IN_PROC_BROWSER_TEST_P(CardUnmaskAuthenticationSelectionDialogBrowserTest, CanCloseBrowserWhileDialogShowing) { base::HistogramTester histogram_tester; - SetChallengeOptionList(test::GetCardUnmaskChallengeOptions(GetParam())); + SetChallengeOptionList( + test::GetCardUnmaskChallengeOptions(GetChallengeOptionTypes())); ShowUi(""); VerifyUi(); browser()->window()->Close(); base::RunLoop().RunUntilIdle(); - histogram_tester.ExpectUniqueSample( - "Autofill.CardUnmaskAuthenticationSelectionDialog.Shown", true, 1); + EXPECT_THAT( + histogram_tester.GetAllSamples( + "Autofill.CardUnmaskAuthenticationSelectionDialog.Shown2"), + // If the CVC flag is on, then the count depends on the number of + // challenge options, i.e. `GetParam().size()`. If the CVC flag is + // off, it will always be 1. + base::BucketsAre(base::Bucket(GetEnableCvcForVcnYellowPathIsEnabled() + ? GetChallengeOptionTypes().size() + : 1, + 1))); histogram_tester.ExpectUniqueSample( "Autofill.CardUnmaskAuthenticationSelectionDialog.Result", AutofillMetrics::CardUnmaskAuthenticationSelectionDialogResultMetric:: @@ -132,7 +182,8 @@ CardUnmaskAuthenticationSelectionDialogBrowserTest, CanceledByUserAfterSelectionResultsMetricsLoggedAsExpected) { base::HistogramTester histogram_tester; - SetChallengeOptionList(test::GetCardUnmaskChallengeOptions(GetParam())); + SetChallengeOptionList( + test::GetCardUnmaskChallengeOptions(GetChallengeOptionTypes())); ShowUi(""); VerifyUi(); // Put the dialog in pending state.
diff --git a/chrome/browser/ui/views/frame/browser_frame_mac.mm b/chrome/browser/ui/views/frame/browser_frame_mac.mm index 89d13e27..e44e3918 100644 --- a/chrome/browser/ui/views/frame/browser_frame_mac.mm +++ b/chrome/browser/ui/views/frame/browser_frame_mac.mm
@@ -360,11 +360,8 @@ if (browser_view_->GetIsWebAppType()) params->window_title_hidden = true; } else if (browser_view_->GetIsPictureInPictureType()) { - // Somewhat confusingly, `kDefault` is required for `NS...Borderless` to do - // anything. Setting it to `kFrameless` causes it to have a frame. - params->window_class = remote_cocoa::mojom::WindowClass::kDefault; - params->style_mask = NSWindowStyleMaskBorderless; - params->window_title_hidden = true; + params->window_class = remote_cocoa::mojom::WindowClass::kFrameless; + params->style_mask = NSWindowStyleMaskFullSizeContentView; } else { params->window_class = remote_cocoa::mojom::WindowClass::kDefault; }
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_chromeos.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_chromeos.cc index 177dd77..2c8428c 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_chromeos.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_chromeos.cc
@@ -187,15 +187,15 @@ if (browser_view()->GetIsWebAppType() && (!browser->is_type_app_popup() || - browser_view()->AppUsesWindowControlsOverlay())) { + browser_view()->AppUsesWindowControlsOverlay() || + browser_view()->AppUsesBorderlessMode())) { // Add the container for extra web app buttons (e.g app menu button). set_web_app_frame_toolbar(AddChildView( std::make_unique<WebAppFrameToolbarView>(frame(), browser_view()))); + if (AppIsBorderlessPwa()) + UpdateBorderlessModeEnabled(); } - if (AppIsBorderlessPwa()) - UpdateBorderlessModeEnabled(); - browser_view()->immersive_mode_controller()->AddObserver(this); }
diff --git a/chrome/browser/ui/views/frame/browser_view_layout_delegate.h b/chrome/browser/ui/views/frame/browser_view_layout_delegate.h index 273b6b7a..65b78d2 100644 --- a/chrome/browser/ui/views/frame/browser_view_layout_delegate.h +++ b/chrome/browser/ui/views/frame/browser_view_layout_delegate.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_VIEWS_FRAME_BROWSER_VIEW_LAYOUT_DELEGATE_H_ #define CHROME_BROWSER_UI_VIEWS_FRAME_BROWSER_VIEW_LAYOUT_DELEGATE_H_ +#include "chrome/browser/ui/browser.h" #include "ui/gfx/native_widget_types.h" class ExclusiveAccessBubbleViews;
diff --git a/chrome/browser/ui/views/profiles/profile_management_step_controller.cc b/chrome/browser/ui/views/profiles/profile_management_step_controller.cc index ff0e8f2..827e349 100644 --- a/chrome/browser/ui/views/profiles/profile_management_step_controller.cc +++ b/chrome/browser/ui/views/profiles/profile_management_step_controller.cc
@@ -6,7 +6,6 @@ #include "base/memory/raw_ptr.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" @@ -153,9 +152,8 @@ finish_flow_callback_->Reset(); // The profile setup did not continue. Schedule it for deletion. - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .ScheduleEphemeralProfileForDeletion(profile_->GetPath()); + g_browser_process->profile_manager()->ScheduleEphemeralProfileForDeletion( + profile_->GetPath()); } }
diff --git a/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.cc b/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.cc index 1af51a56..6b6623c 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.cc
@@ -5,9 +5,7 @@ #include "chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h" -#include "chrome/browser/profiles/nuke_profile_directory_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" @@ -72,10 +70,10 @@ // Schedule the ephemeral profile for deletion if it wasn't deleted yet, // since it's not needed any more. if (!profile_path_.has_value() && - !IsProfileDirectoryMarkedForDeletion(profile_->GetPath())) { + !ProfileManager::IsProfileDirectoryMarkedForDeletion( + profile_->GetPath())) { g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .ScheduleEphemeralProfileForDeletion(profile_->GetPath()); + ->ScheduleEphemeralProfileForDeletion(profile_->GetPath()); } }
diff --git a/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider_browsertest.cc b/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider_browsertest.cc index ce63419..ab003b3 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider_browsertest.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider_browsertest.cc
@@ -2,13 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.h" - #include "base/functional/callback_helpers.h" #include "base/test/mock_callback.h" -#include "chrome/browser/profiles/nuke_profile_directory_utils.h" -#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/views/profiles/profile_picker_dice_sign_in_provider.h" #include "chrome/browser/ui/views/profiles/profile_picker_web_contents_host.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/web_contents.h" @@ -93,7 +91,8 @@ } // On exit, the provider should schedule the profile it created for deletion. - EXPECT_TRUE(IsProfileDirectoryMarkedForDeletion(provider_profile_path)); + EXPECT_TRUE(ProfileManager::IsProfileDirectoryMarkedForDeletion( + provider_profile_path)); } IN_PROC_BROWSER_TEST_F(ProfilePickerDiceSignInProviderBrowserTest, @@ -130,5 +129,6 @@ } // Since a profile has been passed in, the provider should not delete it. - EXPECT_FALSE(IsProfileDirectoryMarkedForDeletion(provider_profile_path)); + EXPECT_FALSE(ProfileManager::IsProfileDirectoryMarkedForDeletion( + provider_profile_path)); }
diff --git a/chrome/browser/ui/views/profiles/profile_picker_flow_controller.cc b/chrome/browser/ui/views/profiles/profile_picker_flow_controller.cc index 467a9ce..f0d1caf3 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_flow_controller.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_flow_controller.cc
@@ -8,7 +8,6 @@ #include "base/trace_event/trace_event.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_metrics.h" @@ -136,9 +135,8 @@ // Record unfinished signed-in profile creation. if (!is_finishing_) { // Schedule the profile for deletion, it's not needed any more. - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .ScheduleEphemeralProfileForDeletion(profile()->GetPath()); + g_browser_process->profile_manager()->ScheduleEphemeralProfileForDeletion( + profile()->GetPath()); // TODO(crbug.com/1300109): Consider moving this recording into // ProfilePickerTurnSyncOnDelegate and unify this code with Cancel(). @@ -171,9 +169,8 @@ is_finishing_ = true; // Schedule the profile for deletion, it's not needed any more. - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .ScheduleEphemeralProfileForDeletion(profile()->GetPath()); + g_browser_process->profile_manager()->ScheduleEphemeralProfileForDeletion( + profile()->GetPath()); } void FinishAndOpenBrowser(PostHostClearedCallback callback) override {
diff --git a/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc b/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc index 0fbb7b52..8ad4a31 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc
@@ -32,7 +32,6 @@ #include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_builder.h" -#include "chrome/browser/profiles/nuke_profile_directory_utils.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" @@ -1814,7 +1813,7 @@ #else EXPECT_FALSE(contents_profile->IsSystemProfile()); // The sign-in profile should be marked for deletion. - IsProfileDirectoryMarkedForDeletion(contents_profile_path); + ProfileManager::IsProfileDirectoryMarkedForDeletion(contents_profile_path); #endif EXPECT_EQ(initial_profile_count, g_browser_process->profile_manager() ->GetProfileAttributesStorage()
diff --git a/chrome/browser/ui/views/session_crashed_bubble_view.cc b/chrome/browser/ui/views/session_crashed_bubble_view.cc index 5fbf4eb0..12b66165 100644 --- a/chrome/browser/ui/views/session_crashed_bubble_view.cc +++ b/chrome/browser/ui/views/session_crashed_bubble_view.cc
@@ -14,7 +14,6 @@ #include "base/callback_helpers.h" #include "base/memory/raw_ptr.h" #include "base/metrics/histogram_macros.h" -#include "base/task/task_runner_util.h" #include "build/branding_buildflags.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" @@ -213,11 +212,12 @@ browser); if (DoesSupportConsentCheck()) { - base::PostTaskAndReplyWithResult( - GoogleUpdateSettings::CollectStatsConsentTaskRunner(), FROM_HERE, - base::BindOnce(&GoogleUpdateSettings::GetCollectStatsConsent), - base::BindOnce(&SessionCrashedBubbleView::Show, - std::move(browser_observer), skip_tab_checking)); + GoogleUpdateSettings::CollectStatsConsentTaskRunner() + ->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce(&GoogleUpdateSettings::GetCollectStatsConsent), + base::BindOnce(&SessionCrashedBubbleView::Show, + std::move(browser_observer), skip_tab_checking)); } else { SessionCrashedBubbleView::Show(std::move(browser_observer), skip_tab_checking, false);
diff --git a/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc b/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc index bc3d6fa0..8de6446 100644 --- a/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc +++ b/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc
@@ -25,6 +25,7 @@ #include "components/feature_engagement/public/feature_constants.h" #include "components/strings/grit/components_strings.h" #include "components/vector_icons/vector_icons.h" +#include "ui/base/interaction/element_tracker.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/metadata/metadata_impl_macros.h" @@ -37,6 +38,7 @@ #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/controls/separator.h" +#include "ui/views/interaction/element_tracker_views.h" #include "ui/views/layout/flex_layout_view.h" #include "ui/views/vector_icons.h" #include "ui/views/view_class_properties.h" @@ -530,6 +532,8 @@ header_combobox_ = header->AddChildView(CreateCombobox()); header_combobox_->SetFocusBehavior(views::View::FocusBehavior::ALWAYS); + header_combobox_->SetProperty(views::kElementIdentifierKey, + kSidePanelComboboxElementId); header_open_in_new_tab_button_ = header->AddChildView(CreateControlButton( header.get(), @@ -583,6 +587,8 @@ bool SidePanelCoordinator::OnComboboxChangeTriggered(size_t index) { SidePanelEntry::Key entry_key = combobox_model_->GetKeyAt(index); Show(entry_key, SidePanelUtil::SidePanelOpenTrigger::kComboboxSelected); + views::ElementTrackerViews::GetInstance()->NotifyCustomEvent( + kSidePanelComboboxChangedCustomEventId, header_combobox_); return true; }
diff --git a/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.cc b/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.cc index f3c9dfa9..166f6cf 100644 --- a/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.cc +++ b/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.cc
@@ -20,7 +20,6 @@ #include "base/process/process.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "components/dbus/menu/menu.h" #include "components/dbus/properties/dbus_properties.h" @@ -476,8 +475,8 @@ return; if (should_write_icon_to_file_) { - base::PostTaskAndReplyWithResult( - icon_task_runner_.get(), FROM_HERE, + icon_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(WriteIconFile, icon_file_id_++, gfx::Image(image).As1xPNGBytes()), base::BindOnce(&StatusIconLinuxDbus::OnIconFileWritten, this));
diff --git a/chrome/browser/ui/views/tabs/tab_strip_scroll_container.cc b/chrome/browser/ui/views/tabs/tab_strip_scroll_container.cc index 97247ca..381d8ea 100644 --- a/chrome/browser/ui/views/tabs/tab_strip_scroll_container.cc +++ b/chrome/browser/ui/views/tabs/tab_strip_scroll_container.cc
@@ -211,6 +211,9 @@ } } } + + // disable the scroll buttons if fully scrolled and re-enable them otherwise + MaybeUpdateScrollButtonState(); } int TabStripScrollContainer::GetTabStripAvailableWidth() const { @@ -228,23 +231,49 @@ } void TabStripScrollContainer::FrameColorsChanged() { - SkColor foreground_color = + SkColor foreground_enabled_color = tab_strip_->GetTabForegroundColor(TabActive::kInactive); - /* Use placeholder color for disabled state because these buttons should - never be disabled (they are hidden when the tab strip is not full) */ + // TODO(crbug.com/1385859): Get a disabled color that is lighter + // and changes with the frame background color + SkColor foreground_disabled_color = + GetColorProvider()->GetColor(kColorTabForegroundInactiveFrameInactive); + + /* When the buttons are fully scrolled in a direction the corresponding button + is disabled. They are hidden when there are not enough tabs to be in tab + scrolling mode. */ if (leading_scroll_button_) { - views::SetImageFromVectorIconWithColor(leading_scroll_button_, - kLeadingScrollIcon, foreground_color, - gfx::kPlaceholderColor); + views::SetImageFromVectorIconWithColor( + leading_scroll_button_, kLeadingScrollIcon, foreground_enabled_color, + foreground_disabled_color); } if (trailing_scroll_button_) { views::SetImageFromVectorIconWithColor( - trailing_scroll_button_, kTrailingScrollIcon, foreground_color, - gfx::kPlaceholderColor); + trailing_scroll_button_, kTrailingScrollIcon, foreground_enabled_color, + foreground_disabled_color); } overflow_indicator_strategy_->FrameColorsChanged(); } +void TabStripScrollContainer::MaybeUpdateScrollButtonState() { + if (trailing_scroll_button_) { + if (scroll_view_->GetVisibleRect().right() == + scroll_view_->contents()->GetLocalBounds().right()) { + trailing_scroll_button_->SetEnabled(false); + } else { + trailing_scroll_button_->SetEnabled(true); + } + } + + if (leading_scroll_button_) { + if (scroll_view_->GetVisibleRect().x() == + scroll_view_->contents()->GetLocalBounds().x()) { + leading_scroll_button_->SetEnabled(false); + } else { + leading_scroll_button_->SetEnabled(true); + } + } +} + bool TabStripScrollContainer::IsRectInWindowCaption(const gfx::Rect& rect) { const auto get_target_rect = [&](views::View* target) { gfx::RectF rect_in_target_coords_f(rect);
diff --git a/chrome/browser/ui/views/tabs/tab_strip_scroll_container.h b/chrome/browser/ui/views/tabs/tab_strip_scroll_container.h index dd90e7d..40fcb02 100644 --- a/chrome/browser/ui/views/tabs/tab_strip_scroll_container.h +++ b/chrome/browser/ui/views/tabs/tab_strip_scroll_container.h
@@ -58,6 +58,9 @@ // Scrolls the tabstrip towards the last tab in the tabstrip. void ScrollTowardsTrailingTab(); + // enable or disable the scroll buttons based on the scroll position + void MaybeUpdateScrollButtonState(); + // Subscription for scrolling of content view base::CallbackListSubscription on_contents_scrolled_subscription_;
diff --git a/chrome/browser/ui/views/user_education/browser_user_education_service.cc b/chrome/browser/ui/views/user_education/browser_user_education_service.cc index a01d59b..7342595c 100644 --- a/chrome/browser/ui/views/user_education/browser_user_education_service.cc +++ b/chrome/browser/ui/views/user_education/browser_user_education_service.cc
@@ -54,7 +54,9 @@ const char kTabGroupTutorialMetricPrefix[] = "TabGroup"; const char kTabGroupWithGroupTutorialMetricPrefix[] = "TabGroupWithGroup"; +const char kSidePanelReadingListTutorialMetricPrefix[] = "SidePanelReadingList"; constexpr char kTabGroupHeaderElementName[] = "TabGroupHeader"; +constexpr char kReadingListItemElementName[] = "ReadingListItem"; class BrowserHelpBubbleDelegate : public user_education::HelpBubbleDelegate { public: @@ -125,6 +127,8 @@ const char kTabGroupTutorialId[] = "Tab Group Tutorial"; const char kTabGroupWithExistingGroupTutorialId[] = "Tab Group With Existing Group Tutorial"; +const char kSidePanelReadingListTutorialId[] = + "Side Panel Reading List Tutorial"; user_education::HelpBubbleDelegate* GetHelpBubbleDelegate() { static base::NoDestructor<BrowserHelpBubbleDelegate> delegate; @@ -461,4 +465,84 @@ tutorial_registry.AddTutorial(kTabGroupWithExistingGroupTutorialId, std::move(with_group_description)); } + + { // Side panel reading list tutorial + + // The Description for kSidePanelReadingListTutorialId + TutorialDescription side_panel_description; + + // Open side panel + TutorialDescription::Step open_side_panel_step( + 0, IDS_TUTORIAL_SIDE_PANEL_READING_LIST_OPEN_SIDE_PANEL, + ui::InteractionSequence::StepType::kShown, kReadLaterButtonElementId, + std::string(), HelpBubbleArrow::kTopRight); + side_panel_description.steps.emplace_back(open_side_panel_step); + + // Click "Add current tab" + TutorialDescription::Step add_current_tab_step( + 0, IDS_TUTORIAL_SIDE_PANEL_READING_LIST_ADD_TAB, + ui::InteractionSequence::StepType::kShown, + kAddCurrentTabToReadingListElementId, std::string(), + HelpBubbleArrow::kTopLeft, ui::CustomElementEventType(), absl::nullopt, + /* transition_only_on_event =*/false, + user_education::TutorialDescription::NameElementsCallback(), + /* in_any_context =*/true); + side_panel_description.steps.emplace_back(add_current_tab_step); + + // When shown, name the element + TutorialDescription::Step new_reading_list_item_step( + 0, 0, ui::InteractionSequence::StepType::kShown, + kSidePanelReadingListUnreadElementId, std::string(), + HelpBubbleArrow::kNone, ui::CustomElementEventType(), + /* must_remain_visible =*/true, + /* transition_only_on_event =*/true, + base::BindRepeating( + [](ui::InteractionSequence* sequence, ui::TrackedElement* element) { + sequence->NameElement( + element, base::StringPiece(kReadingListItemElementName)); + return true; + }), + /* in_any_context =*/true); + side_panel_description.steps.emplace_back(new_reading_list_item_step); + + // Mark as read + TutorialDescription::Step mark_as_read_step( + 0, IDS_TUTORIAL_SIDE_PANEL_READING_LIST_MARK_READ, + ui::InteractionSequence::StepType::kShown, ui::ElementIdentifier(), + kReadingListItemElementName, HelpBubbleArrow::kTopLeft); + side_panel_description.steps.emplace_back(mark_as_read_step); + + TutorialDescription::Step detect_mark_as_read_step( + 0, 0, ui::InteractionSequence::StepType::kCustomEvent, + ui::ElementIdentifier(), kReadingListItemElementName, + HelpBubbleArrow::kNone, kSidePanelReadingMarkedAsReadEventId); + side_panel_description.steps.emplace_back(detect_mark_as_read_step); + + // Click drop down + TutorialDescription::Step click_dropdown_step( + 0, IDS_TUTORIAL_SIDE_PANEL_READING_LIST_CLICK_DROPDOWN, + ui::InteractionSequence::StepType::kShown, kSidePanelComboboxElementId, + std::string(), HelpBubbleArrow::kTopLeft); + side_panel_description.steps.emplace_back(click_dropdown_step); + + TutorialDescription::Step detect_click_dropdown_step( + 0, 0, ui::InteractionSequence::StepType::kCustomEvent, + kSidePanelComboboxElementId, std::string(), HelpBubbleArrow::kNone, + kSidePanelComboboxChangedCustomEventId); + side_panel_description.steps.emplace_back(detect_click_dropdown_step); + + // Completion of the tutorial. + TutorialDescription::Step success_step( + IDS_TUTORIAL_GENERIC_SUCCESS_TITLE, + IDS_TUTORIAL_SIDE_PANEL_READING_LIST_SUCCESS_BODY, + ui::InteractionSequence::StepType::kShown, kTabStripRegionElementId, + std::string(), HelpBubbleArrow::kNone); + side_panel_description.steps.emplace_back(success_step); + + side_panel_description.histograms = user_education::MakeTutorialHistograms< + kSidePanelReadingListTutorialMetricPrefix>( + side_panel_description.steps.size()); + tutorial_registry.AddTutorial(kSidePanelReadingListTutorialId, + std::move(side_panel_description)); + } }
diff --git a/chrome/browser/ui/web_applications/test/system_web_app_interactive_uitest.cc b/chrome/browser/ui/web_applications/test/system_web_app_interactive_uitest.cc index 2612204..91ebd27 100644 --- a/chrome/browser/ui/web_applications/test/system_web_app_interactive_uitest.cc +++ b/chrome/browser/ui/web_applications/test/system_web_app_interactive_uitest.cc
@@ -34,7 +34,6 @@ #include "chrome/browser/ash/system_web_apps/test_support/test_system_web_app_installation.h" #include "chrome/browser/ash/web_applications/os_url_handler_system_web_app_info.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" #include "chrome/browser/ui/app_list/app_service/app_service_app_item.h" @@ -654,11 +653,8 @@ const AppId& app_id1 = GetAppId(profile1); const AppId& app_id2 = GetAppId(profile2); - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .MaybeScheduleProfileForDeletion( - profile2->GetPath(), base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + g_browser_process->profile_manager()->ScheduleProfileForDeletion( + profile2->GetPath(), base::DoNothing()); { auto launch_params = apps::AppLaunchParams(
diff --git a/chrome/browser/ui/web_applications/web_app_browsertest.cc b/chrome/browser/ui/web_applications/web_app_browsertest.cc index d05f6d3..9b67b9d6 100644 --- a/chrome/browser/ui/web_applications/web_app_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_browsertest.cc
@@ -16,6 +16,7 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/metrics/user_action_tester.h" #include "base/test/scoped_feature_list.h" +#include "base/test/test_future.h" #include "base/time/time.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" @@ -61,6 +62,7 @@ #include "chrome/browser/web_applications/user_display_mode.h" #include "chrome/browser/web_applications/web_app.h" #include "chrome/browser/web_applications/web_app_command_manager.h" +#include "chrome/browser/web_applications/web_app_command_scheduler.h" #include "chrome/browser/web_applications/web_app_constants.h" #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/browser/web_applications/web_app_install_finalizer.h" @@ -1669,6 +1671,63 @@ EXPECT_EQ(browser()->tab_strip_model()->count(), 1); } +using WebAppBrowserTest_UpdateShortcuts = WebAppBrowserTest; + +IN_PROC_BROWSER_TEST_F(WebAppBrowserTest_UpdateShortcuts, UpdateShortcut) { + base::ScopedAllowBlockingForTesting allow_blocking; + std::unique_ptr<ShortcutOverrideForTesting::BlockingRegistration> + shortcut_override = + ShortcutOverrideForTesting::OverrideForTesting(base::GetHomeDir()); + + NavigateToURLAndWait(browser(), GetInstallableAppURL()); + + WebAppProvider* provider = WebAppProvider::GetForTest(profile()); + + base::test::TestFuture<const AppId&, webapps::InstallResultCode> + install_future; + provider->scheduler().FetchManifestAndInstall( + webapps::WebappInstallSource::OMNIBOX_INSTALL_ICON, + browser()->tab_strip_model()->GetActiveWebContents()->GetWeakPtr(), + /*bypass_service_worker_check=*/false, + base::BindOnce(test::TestAcceptDialogCallback), + install_future.GetCallback(), + /*use_fallback=*/false); + + const AppId& app_id = install_future.Get<0>(); + EXPECT_EQ(provider->registrar().GetAppShortName(app_id), + GetInstallableAppName()); + + { + ScopedRegistryUpdate update(&provider->sync_bridge()); + update->UpdateApp(app_id)->SetName("test_app_2"); + } + + base::HistogramTester tester; + base::test::TestFuture<Result> result; + provider->os_integration_manager().UpdateShortcuts( + app_id, "Manifest test app", result.GetCallback()); + ASSERT_TRUE(result.Wait()); + EXPECT_THAT(result.Get(), testing::Eq(Result::kOk)); + + bool can_create_shortcuts = provider->os_integration_manager() + .shortcut_manager_for_testing() + .CanCreateShortcuts(); + if (can_create_shortcuts) { + EXPECT_THAT(tester.GetAllSamples("WebApp.Shortcuts.Update.Result"), + BucketsAre(base::Bucket(true, 1))); + } else { + EXPECT_THAT(tester.GetAllSamples("WebApp.Shortcuts.Update.Result"), + testing::IsEmpty()); + } + + base::test::TestFuture<std::unique_ptr<ShortcutInfo>> shortcut_future; + provider->os_integration_manager().GetShortcutInfoForApp( + app_id, shortcut_future.GetCallback()); + auto shortcut_info = shortcut_future.Take(); + EXPECT_NE(shortcut_info, nullptr); + EXPECT_EQ(shortcut_info->title, u"test_app_2"); +} + // Tests that reparenting a display: browser app tab results in a minimal-ui // app window. IN_PROC_BROWSER_TEST_F(WebAppBrowserTest, ReparentDisplayBrowserApp) {
diff --git a/chrome/browser/ui/web_applications/web_app_profile_deletion_browsertest.cc b/chrome/browser/ui/web_applications/web_app_profile_deletion_browsertest.cc index 45f0e41..61034f5 100644 --- a/chrome/browser/ui/web_applications/web_app_profile_deletion_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_profile_deletion_browsertest.cc
@@ -8,9 +8,7 @@ #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_test_util.h" #include "chrome/browser/ui/web_applications/web_app_controller_browsertest.h" #include "chrome/browser/web_applications/test/web_app_test_observers.h" @@ -31,11 +29,8 @@ } void ScheduleCurrentProfileForDeletion() { - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .MaybeScheduleProfileForDeletion( - profile()->GetPath(), base::DoNothing(), - ProfileMetrics::DELETE_PROFILE_USER_MANAGER); + g_browser_process->profile_manager()->ScheduleProfileForDeletion( + profile()->GetPath(), base::DoNothing()); } };
diff --git a/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc b/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc index 938510b..32d5db4 100644 --- a/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc +++ b/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc
@@ -12,12 +12,15 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/webui/theme_source.h" #include "chrome/browser/ui/webui/welcome/helpers.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/enterprise/browser/controller/fake_browser_dm_token_storage.h" +#include "components/password_manager/core/common/password_manager_features.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/notification_registrar.h" @@ -149,6 +152,10 @@ public: ChromeURLDataManagerWebUITrustedTypesTest() { std::vector<base::test::FeatureRef> enabled_features; + enabled_features.push_back(features::kSidePanelJourneys); + enabled_features.push_back(features::kSupportTool); + enabled_features.push_back( + password_manager::features::kPasswordManagerRedesign); #if !BUILDFLAG(IS_CHROMEOS) if (GetParam() == std::string("chrome://welcome")) enabled_features.push_back(welcome::kForceEnabled); @@ -247,11 +254,14 @@ static constexpr const char* const kChromeUrls[] = { "chrome://accessibility", "chrome://apc-internals", + "chrome://app-service-internals", "chrome://attribution-internals", "chrome://autofill-internals", // "chrome://blob-internals", "chrome://bookmarks", + "chrome://bookmarks-side-panel.top-chrome", "chrome://chrome-urls", + "chrome://commander", "chrome://components", "chrome://connection-help", "chrome://connection-monitoring-detected", @@ -270,6 +280,7 @@ "chrome://gpu", "chrome://histograms", "chrome://history", + "chrome://history-clusters-side-panel.top-chrome", "chrome://identity-internals", "chrome://indexeddb-internals", "chrome://inspect", @@ -281,6 +292,7 @@ "chrome://media-history", "chrome://media-internals", "chrome://media-router-internals", + "chrome://metrics-internals", // TODO(crbug.com/1217395): DCHECK failure // "chrome://memory-internals", "chrome://net-export", @@ -291,31 +303,34 @@ "chrome://newtab", "chrome://ntp-tiles-internals", "chrome://omnibox", + "chrome://password-manager", "chrome://password-manager-internals", "chrome://policy", "chrome://predictors", "chrome://prefs-internals", - // "chrome://print", + "chrome://print", "chrome://process-internals", "chrome://quota-internals", "chrome://reset-password", "chrome://safe-browsing", "chrome://serviceworker-internals", + "chrome://segmentation-internals", "chrome://settings", - // TODO(crbug.com/1115600): DCHECK failure when opening - // "chrome://signin-dice-web-intercept", "chrome://signin-internals", "chrome://site-engagement", + "chrome://support-tool", // TODO(crbug.com/1099564): Navigating to chrome://sync-confirmation and // quickly navigating away cause DCHECK failure. // "chrome://sync-confirmation", "chrome://sync-internals", "chrome://syncfs-internals", "chrome://system", + "chrome://tab-search.top-chrome", // TODO(crbug.com/1099565): Navigating to chrome://tab-strip and quickly // navigating away cause DCHECK failure. // "chrome://tab-strip", "chrome://terms", + "chrome://topics-internals", // "chrome://tracing", "chrome://translate-internals", "chrome://ukm", @@ -325,6 +340,7 @@ "chrome://web-app-internals", "chrome://webrtc-internals", "chrome://webrtc-logs", + "chrome://webui-gallery", #if BUILDFLAG(IS_ANDROID) "chrome://explore-sites-internals", "chrome://internals/notifications", @@ -370,6 +386,7 @@ #if !BUILDFLAG(IS_CHROMEOS) "chrome://apps", "chrome://browser-switch", + "chrome://profile-picker", // "chrome://welcome", #endif #if !BUILDFLAG(IS_CHROMEOS_ASH) @@ -389,6 +406,12 @@ #if BUILDFLAG(IS_WIN) "chrome://conflicts", #endif +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + "chrome://signin-dice-web-intercept/?debug", +#endif +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) + "chrome://webuijserror", +#endif }; INSTANTIATE_TEST_SUITE_P(
diff --git a/chrome/browser/ui/webui/history_clusters/history_clusters_handler.cc b/chrome/browser/ui/webui/history_clusters/history_clusters_handler.cc index 834bab1..16f9e72 100644 --- a/chrome/browser/ui/webui/history_clusters/history_clusters_handler.cc +++ b/chrome/browser/ui/webui/history_clusters/history_clusters_handler.cc
@@ -22,6 +22,7 @@ #include "chrome/browser/history_clusters/entity_image_service.h" #include "chrome/browser/history_clusters/history_clusters_metrics_logger.h" #include "chrome/browser/history_clusters/history_clusters_service_factory.h" +#include "chrome/browser/image_service/image_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/sync/sync_service_factory.h" @@ -513,15 +514,21 @@ bool can_load_more, bool is_continuation) { // TODO(tommycli): It's weird that there's one more post-processing step here - // that's not encapsulated within `QueryClustersState`. That's because - // `EntityImageService` can't live in the component yet, because it depends - // on code in the /chrome directory. Fix this using dependency injection. - auto* entity_image_service = EntityImageService::Get(GetProfile()); - entity_image_service->PopulateEntityImagesFor( - std::move(clusters_batch), - base::BindOnce(&HistoryClustersHandler::SendClustersToPage, - weak_ptr_factory_.GetWeakPtr(), query, can_load_more, - is_continuation)); + // that's not encapsulated within `QueryClustersState`. After componentizing + // ImageService, have HistoryClustersService pass a pointer to it in the + // constructor, so `QueryClustersState` can do this for itself. + if (auto* image_service = + image_service::ImageServiceFactory::GetForBrowserContext( + GetProfile())) { + image_service->PopulateEntityImagesFor( + std::move(clusters_batch), + base::BindOnce(&HistoryClustersHandler::SendClustersToPage, + weak_ptr_factory_.GetWeakPtr(), query, can_load_more, + is_continuation)); + } else { + SendClustersToPage(query, can_load_more, is_continuation, + std::move(clusters_batch)); + } } void HistoryClustersHandler::SendClustersToPage(
diff --git a/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc b/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc index 6e44fa51..1c4d772 100644 --- a/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc +++ b/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc
@@ -11,7 +11,6 @@ #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/ref_counted_memory.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "build/build_config.h" @@ -253,8 +252,8 @@ #endif // BUILDFLAG(ENABLE_OOP_PRINTING) VLOG(1) << "Getting default printer in-process"; - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync, g_browser_process->GetApplicationLocale()), std::move(cb)); @@ -278,8 +277,8 @@ #endif // BUILDFLAG(ENABLE_OOP_PRINTING) VLOG(1) << "Enumerate printers start in-process"; - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&EnumeratePrintersAsync, g_browser_process->GetApplicationLocale()), base::BindOnce(&ConvertPrinterListForCallback, std::move(callback), @@ -307,8 +306,8 @@ #endif // BUILDFLAG(ENABLE_OOP_PRINTING) VLOG(1) << "Getting printer capabilities in-process for " << device_name; - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FetchCapabilitiesAsync, device_name, g_browser_process->GetApplicationLocale()), std::move(cb));
diff --git a/chrome/browser/ui/webui/profile_helper.cc b/chrome/browser/ui/webui/profile_helper.cc index c0d7e248..5f3aa784 100644 --- a/chrome/browser/ui/webui/profile_helper.cc +++ b/chrome/browser/ui/webui/profile_helper.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/delete_profile_helper.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_window.h" @@ -54,10 +53,8 @@ ProfileMetrics::ProfileDelete deletion_source) { if (!profiles::IsMultipleProfilesEnabled()) return; - g_browser_process->profile_manager() - ->GetDeleteProfileHelper() - .MaybeScheduleProfileForDeletion( - file_path, base::BindOnce(&OpenNewWindowForProfile), deletion_source); + g_browser_process->profile_manager()->MaybeScheduleProfileForDeletion( + file_path, base::BindOnce(&OpenNewWindowForProfile), deletion_source); } } // namespace webui
diff --git a/chrome/browser/ui/webui/side_panel/bookmarks/bookmarks_side_panel_ui.cc b/chrome/browser/ui/webui/side_panel/bookmarks/bookmarks_side_panel_ui.cc index 499fc0f1..bad0b94 100644 --- a/chrome/browser/ui/webui/side_panel/bookmarks/bookmarks_side_panel_ui.cc +++ b/chrome/browser/ui/webui/side_panel/bookmarks/bookmarks_side_panel_ui.cc
@@ -71,6 +71,8 @@ {"addCurrentTab", IDS_READ_LATER_ADD_CURRENT_TAB}, {"emptyTitle", IDS_BOOKMARKS_EMPTY_STATE_TITLE}, {"emptyBody", IDS_BOOKMARKS_EMPTY_STATE_BODY}, + {"searchBookmarks", IDS_BOOKMARK_MANAGER_SEARCH_BUTTON}, + {"clearSearch", IDS_BOOKMARK_MANAGER_CLEAR_SEARCH}, }; for (const auto& str : kLocalizedStrings) webui::AddLocalizedString(source, str.name, str.id);
diff --git a/chrome/browser/ui/webui/side_panel/reading_list/reading_list_ui.cc b/chrome/browser/ui/webui/side_panel/reading_list/reading_list_ui.cc index 2c1590b..5165c2bd 100644 --- a/chrome/browser/ui/webui/side_panel/reading_list/reading_list_ui.cc +++ b/chrome/browser/ui/webui/side_panel/reading_list/reading_list_ui.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/commerce/shopping_service_factory.h" #include "chrome/browser/feature_engagement/tracker_factory.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser_element_identifiers.h" #include "chrome/browser/ui/read_later/reading_list_model_factory.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/webui/favicon_source.h" @@ -89,6 +90,8 @@ IDS_BOOKMARKS_EDIT_BOOKMARK_LIST_A11Y_LABEL}, {"emptyTitle", IDS_BOOKMARKS_EMPTY_STATE_TITLE}, {"emptyBody", IDS_BOOKMARKS_EMPTY_STATE_BODY}, + {"searchBookmarks", IDS_BOOKMARK_MANAGER_SEARCH_BUTTON}, + {"clearSearch", IDS_BOOKMARK_MANAGER_CLEAR_SEARCH}, }; for (const auto& str : kLocalizedStrings) webui::AddLocalizedString(source, str.name, str.id); @@ -204,7 +207,10 @@ mojo::PendingReceiver<help_bubble::mojom::HelpBubbleHandler> handler) { help_bubble_handler_ = std::make_unique<user_education::HelpBubbleHandler>( std::move(handler), std::move(client), web_ui()->GetWebContents(), - std::vector<ui::ElementIdentifier>{}); + std::vector<ui::ElementIdentifier>{ + kAddCurrentTabToReadingListElementId, + kSidePanelReadingListUnreadElementId, + }); } void ReadingListUI::CreateShoppingListHandler(
diff --git a/chrome/browser/web_applications/alternative_error_page_override_info_browsertest.cc b/chrome/browser/web_applications/alternative_error_page_override_info_browsertest.cc index 52bda9b4..64985b87 100644 --- a/chrome/browser/web_applications/alternative_error_page_override_info_browsertest.cc +++ b/chrome/browser/web_applications/alternative_error_page_override_info_browsertest.cc
@@ -177,17 +177,17 @@ app_url, /*render_frame_host=*/nullptr, profile, net::ERR_INTERNET_DISCONNECTED); - // Expect mojom struct with icon url. + // Expect mojom struct with everything (except the icon) filled out. EXPECT_TRUE(info); - EXPECT_EQ( - *info->alternative_error_page_params.Find("icon_url"), - "data:image/" - "png;base64," - "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAA4UlEQVQ4jZVSuwqFMAw1" - "8baI2M3FyUXXfoGT3+FvC/" - "6A4iQKUrFDcweht7fWwUwhOSc5eUDXddEbw1foKIo+" - "1iOiIAIAiAgAfIINubh7KtABALTWxhjOuYVax58BAM7zLIqirmtEvMS4an8EIkJEpZSU" - "smkaIYQQwhjjSUK3tmVmWaaUWtc1jmNvGbGU0m3COZ/neRiGtm3zPO/" - "7Pk3T8JYuSVrrsiyrqjqOY5omzrkx5nGtRMQYG8dx33et9bZtSZK46D+" - "Cy1yWBREvtJcNH44xdg8GZrh3u5d7fI0ne/2tX8uNb4qnIrpWAAAAAElFTkSuQmCC"); + EXPECT_EQ(*info->alternative_error_page_params.Find("app_short_name"), + "Manifest test app"); + // This test may at first glance seem like an end-to-end test of the default + // offline experience, but should be considered more of a unit test for just + // the initial values provided to the default offline page. For a proper + // end-to-end test, see WebAppOfflinePageIconShowing in the + // WebAppOfflinePageTest suite. + EXPECT_EQ(*info->alternative_error_page_params.Find("icon_url"), "''"); + EXPECT_EQ(*info->alternative_error_page_params.Find( + "web_app_default_offline_message"), + "You're offline"); }
diff --git a/chrome/browser/web_applications/commands/update_file_handler_command.cc b/chrome/browser/web_applications/commands/update_file_handler_command.cc index 827bafa..b335cbb 100644 --- a/chrome/browser/web_applications/commands/update_file_handler_command.cc +++ b/chrome/browser/web_applications/commands/update_file_handler_command.cc
@@ -113,12 +113,10 @@ if (file_handling_enabled && (!handlers || handlers->empty())) { OnFileHandlerUpdated(file_handling_enabled, Result::kOk); } else { - // TODO(https://crbug.com/1374916): get result from UpdateShortcuts. lock_->os_integration_manager().UpdateShortcuts( app_id_, /*old_name=*/{}, base::BindOnce(&UpdateFileHandlerCommand::OnFileHandlerUpdated, - weak_factory_.GetWeakPtr(), file_handling_enabled, - Result::kOk)); + weak_factory_.GetWeakPtr(), file_handling_enabled)); } #else
diff --git a/chrome/browser/web_applications/extensions/web_app_extension_shortcut.cc b/chrome/browser/web_applications/extensions/web_app_extension_shortcut.cc index b4e7a87..36f75e2 100644 --- a/chrome/browser/web_applications/extensions/web_app_extension_shortcut.cc +++ b/chrome/browser/web_applications/extensions/web_app_extension_shortcut.cc
@@ -11,6 +11,8 @@ #include "base/callback.h" #include "base/callback_helpers.h" #include "base/command_line.h" +#include "base/functional/callback_forward.h" +#include "base/metrics/histogram_functions.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/task_traits.h" @@ -20,6 +22,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/web_applications/os_integration/os_integration_manager.h" +#include "chrome/browser/web_applications/web_app_constants.h" #include "chrome/browser/web_applications/web_app_id.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" @@ -66,11 +69,11 @@ void UpdateAllShortcutsForShortcutInfo( const std::u16string& old_app_title, - base::OnceClosure callback, + ResultCallback callback, std::unique_ptr<ShortcutInfo> shortcut_info) { base::FilePath shortcut_data_dir = internals::GetShortcutDataDir(*shortcut_info); - internals::PostShortcutIOTaskAndReply( + internals::PostShortcutIOTaskAndReplyWithResult( base::BindOnce(&internals::UpdatePlatformShortcuts, std::move(shortcut_data_dir), old_app_title), std::move(shortcut_info), std::move(callback)); @@ -289,9 +292,16 @@ base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - GetShortcutInfoForApp(app, profile, - base::BindOnce(&UpdateAllShortcutsForShortcutInfo, - old_app_title, std::move(callback))); + ResultCallback metrics_callback = + base::BindOnce([](Result result) { + base::UmaHistogramBoolean("WebApp.Shortcuts.Update.Result", + (result == Result::kOk)); + }).Then(std::move(callback)); + + GetShortcutInfoForApp( + app, profile, + base::BindOnce(&UpdateAllShortcutsForShortcutInfo, old_app_title, + std::move(metrics_callback))); } #if !BUILDFLAG(IS_MAC)
diff --git a/chrome/browser/web_applications/extensions/web_app_extension_shortcut_mac.mm b/chrome/browser/web_applications/extensions/web_app_extension_shortcut_mac.mm index 5a8764c9..c5a7b83 100644 --- a/chrome/browser/web_applications/extensions/web_app_extension_shortcut_mac.mm +++ b/chrome/browser/web_applications/extensions/web_app_extension_shortcut_mac.mm
@@ -140,6 +140,8 @@ if (!registry) return; + // Note: This can be replaced with a `BarrierCallback`, and the callback is + // now guaranteed to be called on the calling thread. scoped_refptr<Latch> latch = new Latch(std::move(callback)); // Update all apps.
diff --git a/chrome/browser/web_applications/os_integration/os_integration_manager.cc b/chrome/browser/web_applications/os_integration/os_integration_manager.cc index 0dfdbabe..2ba15060 100644 --- a/chrome/browser/web_applications/os_integration/os_integration_manager.cc +++ b/chrome/browser/web_applications/os_integration/os_integration_manager.cc
@@ -28,6 +28,7 @@ #include "chrome/browser/web_applications/os_integration/web_app_shortcut.h" #include "chrome/browser/web_applications/os_integration/web_app_uninstallation_via_os_settings_registration.h" #include "chrome/browser/web_applications/proto/web_app_os_integration_state.pb.h" +#include "chrome/browser/web_applications/web_app_constants.h" #include "chrome/browser/web_applications/web_app_id.h" #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/browser/web_applications/web_app_registry_update.h" @@ -305,8 +306,7 @@ OsHookType::kFileHandlers))); UpdateShortcuts(app_id, old_name, base::BindOnce(barrier->CreateBarrierCallbackForType( - OsHookType::kShortcuts), - Result::kOk)); + OsHookType::kShortcuts))); UpdateShortcutsMenu(app_id, web_app_info, base::BindOnce(barrier->CreateBarrierCallbackForType( OsHookType::kShortcutsMenu))); @@ -627,9 +627,22 @@ void OsIntegrationManager::UpdateShortcuts(const AppId& app_id, base::StringPiece old_name, - base::OnceClosure callback) { + ResultCallback callback) { DCHECK(shortcut_manager_); - shortcut_manager_->UpdateShortcuts(app_id, old_name, std::move(callback)); + if (!shortcut_manager_->CanCreateShortcuts()) { + std::move(callback).Run(Result::kOk); + return; + } + + ResultCallback metrics_callback = + base::BindOnce([](Result result) { + base::UmaHistogramBoolean("WebApp.Shortcuts.Update.Result", + (result == Result::kOk)); + return result; + }).Then(std::move(callback)); + + shortcut_manager_->UpdateShortcuts(app_id, old_name, + std::move(metrics_callback)); } void OsIntegrationManager::UpdateShortcutsMenu( @@ -723,7 +736,8 @@ // `UpdateOSHooks`, which also recreates the shortcuts, only do it if // required. if (force_shortcut_updates_if_needed) { - UpdateShortcuts(app_id, "", std::move(shortcuts_callback)); + UpdateShortcuts(app_id, "", + base::IgnoreArgs<Result>(std::move(shortcuts_callback))); return; } #endif
diff --git a/chrome/browser/web_applications/os_integration/os_integration_manager.h b/chrome/browser/web_applications/os_integration/os_integration_manager.h index f4249d0..685e7037 100644 --- a/chrome/browser/web_applications/os_integration/os_integration_manager.h +++ b/chrome/browser/web_applications/os_integration/os_integration_manager.h
@@ -206,7 +206,7 @@ virtual void UpdateShortcuts(const AppId& app_id, base::StringPiece old_name, - base::OnceClosure callback); + ResultCallback callback); // AppRegistrarObserver: void OnWebAppProfileWillBeDeleted(const AppId& app_id) override;
diff --git a/chrome/browser/web_applications/os_integration/os_integration_manager_unittest.cc b/chrome/browser/web_applications/os_integration/os_integration_manager_unittest.cc index 0259f7fc..f498c39 100644 --- a/chrome/browser/web_applications/os_integration/os_integration_manager_unittest.cc +++ b/chrome/browser/web_applications/os_integration/os_integration_manager_unittest.cc
@@ -207,8 +207,8 @@ #if !BUILDFLAG(IS_WIN) EXPECT_CALL(manager, UpdateShortcuts(app_id, base::StringPiece(), testing::_)) .WillOnce([](const AppId& app_id, base::StringPiece old_name, - base::OnceClosure update_finished_callback) { - std::move(update_finished_callback).Run(); + ResultCallback update_finished_callback) { + std::move(update_finished_callback).Run(Result::kOk); }); #endif
diff --git a/chrome/browser/web_applications/os_integration/web_app_shortcut.cc b/chrome/browser/web_applications/os_integration/web_app_shortcut.cc index 94cb167..5615063 100644 --- a/chrome/browser/web_applications/os_integration/web_app_shortcut.cc +++ b/chrome/browser/web_applications/os_integration/web_app_shortcut.cc
@@ -17,6 +17,8 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" +#include "base/functional/bind.h" +#include "base/functional/callback_helpers.h" #include "base/logging.h" #include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" @@ -33,6 +35,7 @@ #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "chrome/browser/web_applications/os_integration/web_app_file_handler_registration.h" +#include "chrome/browser/web_applications/web_app_constants.h" #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/common/chrome_constants.h" #include "content/public/browser/browser_task_traits.h" @@ -87,10 +90,11 @@ } void DeleteShortcutInfoOnUIThread(std::unique_ptr<ShortcutInfo> shortcut_info, - base::OnceClosure callback) { + ResultCallback callback, + Result result) { shortcut_info.reset(); if (callback) - std::move(callback).Run(); + std::move(callback).Run(result); } void CreatePlatformShortcutsAndPostCallback( @@ -362,8 +366,19 @@ void PostShortcutIOTask(base::OnceCallback<void(const ShortcutInfo&)> task, std::unique_ptr<ShortcutInfo> shortcut_info) { - PostShortcutIOTaskAndReply(std::move(task), std::move(shortcut_info), - base::OnceClosure()); + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + // Ownership of |shortcut_info| moves to the Reply, which is guaranteed to + // outlive the const reference. + const ShortcutInfo& shortcut_info_ref = *shortcut_info; + GetShortcutIOTaskRunner()->PostTaskAndReply( + FROM_HERE, base::BindOnce(std::move(task), std::cref(shortcut_info_ref)), + base::BindOnce( + [](std::unique_ptr<ShortcutInfo> shortcut_info) { + // This lambda is to own and delete the shortcut info. + shortcut_info.reset(); + }, + std::move(shortcut_info))); } void ScheduleCreatePlatformShortcuts( @@ -401,16 +416,16 @@ std::move(callback))); } -void PostShortcutIOTaskAndReply( - base::OnceCallback<void(const ShortcutInfo&)> task, +void PostShortcutIOTaskAndReplyWithResult( + base::OnceCallback<Result(const ShortcutInfo&)> task, std::unique_ptr<ShortcutInfo> shortcut_info, - base::OnceClosure reply) { + ResultCallback reply) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Ownership of |shortcut_info| moves to the Reply, which is guaranteed to // outlive the const reference. const ShortcutInfo& shortcut_info_ref = *shortcut_info; - GetShortcutIOTaskRunner()->PostTaskAndReply( + GetShortcutIOTaskRunner()->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(std::move(task), std::cref(shortcut_info_ref)), base::BindOnce(&DeleteShortcutInfoOnUIThread, std::move(shortcut_info), std::move(reply)));
diff --git a/chrome/browser/web_applications/os_integration/web_app_shortcut.h b/chrome/browser/web_applications/os_integration/web_app_shortcut.h index 2124e796..f897ff66 100644 --- a/chrome/browser/web_applications/os_integration/web_app_shortcut.h +++ b/chrome/browser/web_applications/os_integration/web_app_shortcut.h
@@ -286,19 +286,20 @@ // platform specific implementation of the UpdateAllShortcuts function, and // is executed on the FILE thread. On Windows, this also updates shortcuts in // the pinned taskbar directories. -void UpdatePlatformShortcuts(const base::FilePath& shortcut_data_path, - const std::u16string& old_app_title, - const ShortcutInfo& shortcut_info); +// Returns true if update was performed successfully and false otherwise +Result UpdatePlatformShortcuts(const base::FilePath& shortcut_data_path, + const std::u16string& old_app_title, + const ShortcutInfo& shortcut_info); // Run an IO task on a worker thread. Ownership of |shortcut_info| transfers // to a closure that deletes it on the UI thread when the task is complete. // Tasks posted here run with BEST_EFFORT priority and block shutdown. void PostShortcutIOTask(base::OnceCallback<void(const ShortcutInfo&)> task, std::unique_ptr<ShortcutInfo> shortcut_info); -void PostShortcutIOTaskAndReply( - base::OnceCallback<void(const ShortcutInfo&)> task, +void PostShortcutIOTaskAndReplyWithResult( + base::OnceCallback<Result(const ShortcutInfo&)> task, std::unique_ptr<ShortcutInfo> shortcut_info, - base::OnceClosure reply); + ResultCallback reply); // The task runner for running shortcut tasks. On Windows this will be a task // runner that permits access to COM libraries. Shortcut tasks typically deal
diff --git a/chrome/browser/web_applications/os_integration/web_app_shortcut_chromeos.cc b/chrome/browser/web_applications/os_integration/web_app_shortcut_chromeos.cc index 06b29d1..803cc49 100644 --- a/chrome/browser/web_applications/os_integration/web_app_shortcut_chromeos.cc +++ b/chrome/browser/web_applications/os_integration/web_app_shortcut_chromeos.cc
@@ -10,6 +10,7 @@ #include "base/callback.h" #include "base/location.h" #include "base/task/task_runner.h" +#include "chrome/browser/web_applications/web_app_constants.h" namespace web_app { @@ -34,9 +35,11 @@ /*shortcut_deleted=*/true)); } -void UpdatePlatformShortcuts(const base::FilePath& web_app_path, - const std::u16string& old_app_title, - const ShortcutInfo& shortcut_info) {} +Result UpdatePlatformShortcuts(const base::FilePath& web_app_path, + const std::u16string& old_app_title, + const ShortcutInfo& shortcut_info) { + return Result::kOk; +} ShortcutLocations GetAppExistingShortCutLocationImpl( const ShortcutInfo& shortcut_info) {
diff --git a/chrome/browser/web_applications/os_integration/web_app_shortcut_linux.cc b/chrome/browser/web_applications/os_integration/web_app_shortcut_linux.cc index f38e14c..6a21a31 100644 --- a/chrome/browser/web_applications/os_integration/web_app_shortcut_linux.cc +++ b/chrome/browser/web_applications/os_integration/web_app_shortcut_linux.cc
@@ -660,7 +660,7 @@ return result; } -void UpdateDesktopShortcuts(base::Environment* env, +bool UpdateDesktopShortcuts(base::Environment* env, const ShortcutInfo& shortcut_info) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::MAY_BLOCK); @@ -675,7 +675,7 @@ if (creation_locations.applications_menu_location == APP_MENU_LOCATION_NONE) creation_locations.applications_menu_location = APP_MENU_LOCATION_HIDDEN; - CreateDesktopShortcut(env, shortcut_info, creation_locations); + return CreateDesktopShortcut(env, shortcut_info, creation_locations); } std::vector<base::FilePath> GetShortcutLocations( @@ -751,11 +751,12 @@ shortcut_info.extension_id))); } -void UpdatePlatformShortcuts(const base::FilePath& /*web_app_path*/, - const std::u16string& /*old_app_title*/, - const ShortcutInfo& shortcut_info) { +Result UpdatePlatformShortcuts(const base::FilePath& /*web_app_path*/, + const std::u16string& /*old_app_title*/, + const ShortcutInfo& shortcut_info) { std::unique_ptr<base::Environment> env(base::Environment::Create()); - UpdateDesktopShortcuts(env.get(), shortcut_info); + return (UpdateDesktopShortcuts(env.get(), shortcut_info) ? Result::kOk + : Result::kError); } void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) {
diff --git a/chrome/browser/web_applications/os_integration/web_app_shortcut_linux.h b/chrome/browser/web_applications/os_integration/web_app_shortcut_linux.h index b6c7714..dd076bd 100644 --- a/chrome/browser/web_applications/os_integration/web_app_shortcut_linux.h +++ b/chrome/browser/web_applications/os_integration/web_app_shortcut_linux.h
@@ -74,7 +74,7 @@ const base::FilePath& profile_path, const std::string& extension_id); -void UpdateDesktopShortcuts(base::Environment* env, +bool UpdateDesktopShortcuts(base::Environment* env, const ShortcutInfo& shortcut_info); // Delete any desktop shortcuts on desktop or in the application menu that have
diff --git a/chrome/browser/web_applications/os_integration/web_app_shortcut_mac.mm b/chrome/browser/web_applications/os_integration/web_app_shortcut_mac.mm index 22b739b..15aef9d 100644 --- a/chrome/browser/web_applications/os_integration/web_app_shortcut_mac.mm +++ b/chrome/browser/web_applications/os_integration/web_app_shortcut_mac.mm
@@ -4,6 +4,7 @@ #import "chrome/browser/web_applications/os_integration/web_app_shortcut_mac.h" #include "base/logging.h" +#include "chrome/browser/web_applications/web_app_constants.h" #import <Cocoa/Cocoa.h> #include <stdint.h> @@ -1554,9 +1555,9 @@ } } -void UpdatePlatformShortcuts(const base::FilePath& app_data_path, - const std::u16string& old_app_title, - const ShortcutInfo& shortcut_info) { +Result UpdatePlatformShortcuts(const base::FilePath& app_data_path, + const std::u16string& old_app_title, + const ShortcutInfo& shortcut_info) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::MAY_BLOCK); // If this is set, then keeping this as a local variable ensures it is not @@ -1565,7 +1566,7 @@ scoped_refptr<ShortcutOverrideForTesting> shortcut_override = web_app::GetShortcutOverrideForTesting(); if (AppShimLaunchDisabled()) - return; + return Result::kOk; WebAppShortcutCreator shortcut_creator(app_data_path, &shortcut_info); std::vector<base::FilePath> updated_shim_paths; @@ -1574,7 +1575,10 @@ // relying on asynchronous creation at installation. if (g_app_shims_allow_update_and_launch_in_tests) create_if_needed = true; - shortcut_creator.UpdateShortcuts(create_if_needed, &updated_shim_paths); + return ( + shortcut_creator.UpdateShortcuts(create_if_needed, &updated_shim_paths) + ? Result::kOk + : Result::kError); } void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) {
diff --git a/chrome/browser/web_applications/os_integration/web_app_shortcut_manager.cc b/chrome/browser/web_applications/os_integration/web_app_shortcut_manager.cc index 81202c5..5286c987 100644 --- a/chrome/browser/web_applications/os_integration/web_app_shortcut_manager.cc +++ b/chrome/browser/web_applications/os_integration/web_app_shortcut_manager.cc
@@ -13,6 +13,9 @@ #include "base/callback.h" #include "base/command_line.h" #include "base/files/file_path.h" +#include "base/functional/bind.h" +#include "base/functional/callback_forward.h" +#include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/no_destructor.h" #include "base/stl_util.h" @@ -23,6 +26,7 @@ #include "chrome/browser/web_applications/os_integration/web_app_protocol_handler_manager.h" #include "chrome/browser/web_applications/os_integration/web_app_shortcut.h" #include "chrome/browser/web_applications/web_app.h" +#include "chrome/browser/web_applications/web_app_constants.h" #include "chrome/browser/web_applications/web_app_icon_manager.h" #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/common/pref_names.h" @@ -129,10 +133,8 @@ void WebAppShortcutManager::UpdateShortcuts( const AppId& app_id, base::StringPiece old_name, - base::OnceClosure update_finished_callback) { - if (!CanCreateShortcuts()) - return; - + ResultCallback update_finished_callback) { + DCHECK(CanCreateShortcuts()); GetShortcutInfoForApp( app_id, base::BindOnce( @@ -329,17 +331,19 @@ void WebAppShortcutManager::OnShortcutInfoRetrievedUpdateShortcuts( std::u16string old_name, - base::OnceClosure update_finished_callback, + ResultCallback update_finished_callback, std::unique_ptr<ShortcutInfo> shortcut_info) { if (GetShortcutUpdateCallbackForTesting()) std::move(GetShortcutUpdateCallbackForTesting()).Run(shortcut_info.get()); - if (suppress_shortcuts_for_testing_ || !shortcut_info) + if (suppress_shortcuts_for_testing_ || !shortcut_info) { + std::move(update_finished_callback).Run(Result::kOk); return; + } base::FilePath shortcut_data_dir = internals::GetShortcutDataDir(*shortcut_info); - internals::PostShortcutIOTaskAndReply( + internals::PostShortcutIOTaskAndReplyWithResult( base::BindOnce(&internals::UpdatePlatformShortcuts, std::move(shortcut_data_dir), std::move(old_name)), std::move(shortcut_info), std::move(update_finished_callback)); @@ -518,7 +522,8 @@ weak_ptr_factory_.GetWeakPtr())); for (const auto& app_id : app_ids) { - UpdateShortcuts(app_id, /*old_name=*/{}, done_callback); + UpdateShortcuts(app_id, /*old_name=*/{}, + base::IgnoreArgs<Result>(done_callback)); } UpdateShortcutsForAllAppsCallback update_callback =
diff --git a/chrome/browser/web_applications/os_integration/web_app_shortcut_manager.h b/chrome/browser/web_applications/os_integration/web_app_shortcut_manager.h index f2cf863..791fefc 100644 --- a/chrome/browser/web_applications/os_integration/web_app_shortcut_manager.h +++ b/chrome/browser/web_applications/os_integration/web_app_shortcut_manager.h
@@ -8,6 +8,7 @@ #include <map> #include <memory> +#include "base/functional/callback_forward.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/web_applications/os_integration/web_app_shortcut.h" @@ -65,7 +66,7 @@ // Fetch already-updated shortcut data and deploy to OS integration. void UpdateShortcuts(const AppId& app_id, base::StringPiece old_name, - base::OnceClosure update_finished_callback); + ResultCallback update_finished_callback); void DeleteShortcuts(const AppId& app_id, const base::FilePath& shortcuts_data_dir, std::unique_ptr<ShortcutInfo> shortcut_info, @@ -149,7 +150,7 @@ void OnShortcutInfoRetrievedUpdateShortcuts( std::u16string old_name, - base::OnceClosure update_finished_callback, + ResultCallback update_finished_callback, std::unique_ptr<ShortcutInfo> info); void OnShortcutsMenuIconsReadRegisterShortcutsMenu(
diff --git a/chrome/browser/web_applications/os_integration/web_app_shortcut_win.cc b/chrome/browser/web_applications/os_integration/web_app_shortcut_win.cc index c64b1bf..1e785a1b 100644 --- a/chrome/browser/web_applications/os_integration/web_app_shortcut_win.cc +++ b/chrome/browser/web_applications/os_integration/web_app_shortcut_win.cc
@@ -288,19 +288,20 @@ } } -void UpdateShortcuts(const base::FilePath& web_app_path, - const base::FilePath& profile_path, - const std::u16string& old_app_title, - const ShortcutInfo& shortcut_info) { +Result UpdateShortcuts(const base::FilePath& web_app_path, + const base::FilePath& profile_path, + const std::u16string& old_app_title, + const ShortcutInfo& shortcut_info) { // Empty titles match all shortcuts, which we don't want, so if we somehow // get an empty app title, ignore the update. if (old_app_title.empty()) - return; + return Result::kOk; const std::vector<base::FilePath> all_shortcuts = FindMatchingShortcuts(web_app_path, profile_path, old_app_title); const bool title_change = old_app_title != shortcut_info.title; + Result result = Result::kOk; for (const auto& shortcut : all_shortcuts) { const base::FilePath new_shortcut = shortcut.DirName() @@ -328,6 +329,7 @@ } else { DVLOG(1) << "Error renaming shortcut " << shortcut_info.title << " error code " << std::hex << error; + result = Result::kError; } } @@ -358,7 +360,7 @@ } } if (pinned_shortcuts.empty()) - return; + return result; // Rename the pinned shortcuts. The shortcut filename is used to determine the // display name for a pinned icon, so renaming the shortcut file in the @@ -387,6 +389,7 @@ } else { DVLOG(1) << "Error renaming shortcut " << shortcut_info.title << " error code " << std::hex << error; + result = Result::kError; } } // SHCNE_ALLEVENTS prevents the WebApp icon on the taskbar from becoming a @@ -397,6 +400,7 @@ SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST | SHCNE_ALLEVENTS | SHCNF_FLUSHNOWAIT, nullptr, nullptr); + return result; } // Gets the directories with shortcuts for an app, and deletes the shortcuts. @@ -595,9 +599,9 @@ return true; } -void UpdatePlatformShortcuts(const base::FilePath& web_app_path, - const std::u16string& old_app_title, - const ShortcutInfo& shortcut_info) { +Result UpdatePlatformShortcuts(const base::FilePath& web_app_path, + const std::u16string& old_app_title, + const ShortcutInfo& shortcut_info) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::MAY_BLOCK); // If this is set, then keeping this as a local variable ensures it is not @@ -608,12 +612,15 @@ // Update the icon if necessary. const base::FilePath icon_file = GetIconFilePath(web_app_path, shortcut_info.title); - CheckAndSaveIcon(icon_file, shortcut_info.favicon, true); + bool success_updating_icon = + CheckAndSaveIcon(icon_file, shortcut_info.favicon, true); if (old_app_title != shortcut_info.title) { // The app's title has changed. Rename existing shortcuts. - UpdateShortcuts(web_app_path, shortcut_info.profile_path, old_app_title, - shortcut_info); + if (UpdateShortcuts(web_app_path, shortcut_info.profile_path, old_app_title, + shortcut_info) == Result::kError) { + success_updating_icon = false; + } // Also delete the old icon file and checksum file, to avoid leaving // orphaned files on disk. The new one was recreated above. @@ -624,6 +631,7 @@ base::DeleteFile(old_icon_file); base::DeleteFile(old_checksum_file); } + return (success_updating_icon ? Result::kOk : Result::kError); } ShortcutLocations GetAppExistingShortCutLocationImpl(
diff --git a/chrome/browser/web_applications/os_integration/web_app_stubs.cc b/chrome/browser/web_applications/os_integration/web_app_stubs.cc index 0644e13..eb3e053 100644 --- a/chrome/browser/web_applications/os_integration/web_app_stubs.cc +++ b/chrome/browser/web_applications/os_integration/web_app_stubs.cc
@@ -65,10 +65,11 @@ return false; } -void UpdatePlatformShortcuts(const base::FilePath& web_app_path, - const std::u16string& old_app_title, - const ShortcutInfo& shortcut_info) { +Result UpdatePlatformShortcuts(const base::FilePath& web_app_path, + const std::u16string& old_app_title, + const ShortcutInfo& shortcut_info) { NOTIMPLEMENTED(); + return Result::kOk; } void DeletePlatformShortcuts(const base::FilePath& web_app_path,
diff --git a/chrome/browser/web_applications/test/mock_os_integration_manager.h b/chrome/browser/web_applications/test/mock_os_integration_manager.h index e1b47a4..6f2e3a8 100644 --- a/chrome/browser/web_applications/test/mock_os_integration_manager.h +++ b/chrome/browser/web_applications/test/mock_os_integration_manager.h
@@ -120,7 +120,7 @@ UpdateShortcuts, (const AppId& app_id, base::StringPiece old_name, - base::OnceClosure callback), + ResultCallback callback), (override)); // Utility methods:
diff --git a/chrome/browser/web_applications/web_app_utils.cc b/chrome/browser/web_applications/web_app_utils.cc index 92e409c..766392fc 100644 --- a/chrome/browser/web_applications/web_app_utils.cc +++ b/chrome/browser/web_applications/web_app_utils.cc
@@ -19,6 +19,7 @@ #include "base/containers/flat_set.h" #include "base/containers/flat_tree.h" #include "base/files/file_path.h" +#include "base/memory/weak_ptr.h" #include "base/strings/string_piece_forward.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -36,6 +37,7 @@ #include "chrome/browser/web_applications/web_app_sync_bridge.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_features.h" +#include "chrome/common/chrome_isolated_world_ids.h" #include "chrome/grit/generated_resources.h" #include "components/custom_handlers/protocol_handler.h" #include "components/grit/components_resources.h" @@ -43,6 +45,8 @@ #include "components/site_engagement/content/site_engagement_service.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/render_frame_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_observer.h" #include "content/public/common/alternative_error_page_override_info.mojom-forward.h" #include "content/public/common/alternative_error_page_override_info.mojom.h" #include "content/public/common/content_features.h" @@ -89,6 +93,106 @@ return GURL("data:image/png;base64," + encoded); } +// This class is responsible for fetching the app icon for a web app and for +// providing it to the DefaultOffline page that's currently showing. The class +// monitors the lifetime of the web_contents for the page and deletes itself +// under these conditions: +// +// 1) It is unable to determine which icon to download. +// 2) The default offline page being monitored (it's web_contents) is destroyed. +// 3) The page starts loading something else. +// 4) (Success case) The icon is successfully fetched and delivered to the web +// page. +// +// Note that this class can not rely on downloading the bits off the network +// because it has to work even when the app is launched for the first time while +// network is disconnected. +class AppIconFetcherTask : public content::WebContentsObserver { + public: + static void FetchAndPopulateIcon(content::WebContents* web_contents, + WebAppProvider* web_app_provider, + const AppId& app_id) { + new AppIconFetcherTask(web_contents, web_app_provider, app_id); + } + + private: + AppIconFetcherTask(content::WebContents* web_contents, + WebAppProvider* web_app_provider, + const AppId& app_id) + : WebContentsObserver(web_contents) { + // For best results, this should be of equal (or slightly higher) value than + // the width and height of the presented icon on the default offline error + // page (see webapp_default_offline.[html|css] for icon details). + const int kDesiredSizeForIcon = 160; + web_app_provider->icon_manager().ReadIconAndResize( + app_id, IconPurpose::ANY, kDesiredSizeForIcon, + base::BindOnce(&AppIconFetcherTask::OnIconFetched, + weak_factory_.GetWeakPtr(), kDesiredSizeForIcon)); + } + + AppIconFetcherTask() = delete; + + // WebContentsObserver: + void WebContentsDestroyed() override { delete this; } + + void DidStartLoading() override { + // Loading will have started already when the error page is being + // constructed, so if we receive this event, it means that a new navigation + // is taking place (so we can drop any remaining work). + delete this; + } + + void DidStopLoading() override { + document_ready_ = true; + MaybeSendImageAndSelfDestruct(); + } + + void OnIconFetched(int fetched_size, + std::map<SquareSizePx, SkBitmap> icon_bitmaps) { + DCHECK(icon_bitmaps.size() == 1); + DCHECK(icon_bitmaps.begin()->first == fetched_size); + if (icon_bitmaps.size() == 0) { + delete this; + return; + } + icon_url_ = EncodeIconAsUrl(icon_bitmaps.begin()->second); + MaybeSendImageAndSelfDestruct(); + } + + // This function does nothing until both of these conditions have been met: + // 1) The app icon image has been fetched. + // 2) The offline page is ready to receive the image. + // Once they are met, this function will send the icon to the web page and + // delete itself. Callers should not assume it is safe to do more work after + // calling this function. + void MaybeSendImageAndSelfDestruct() { + if (!document_ready_ || icon_url_.is_empty()) { + return; + } + DCHECK(web_contents()); + DCHECK(icon_url_.is_valid()); + + std::u16string app_icon_inline = + std::u16string(u"var icon = document.getElementById('icon');") + + u"icon.src ='" + base::UTF8ToUTF16(icon_url_.spec()) + u"';"; + + content::RenderFrameHost* host = web_contents()->GetPrimaryMainFrame(); + host->ExecuteJavaScriptInIsolatedWorld(app_icon_inline, base::DoNothing(), + ISOLATED_WORLD_ID_EXTENSIONS); + + delete this; + } + + // This url will contain the fetched icon bits inlined as a data: url. + GURL icon_url_; + + // Whether the Default Offline page is ready to receive the icon. + bool document_ready_ = false; + + // A weak factory for this class, must be last in the member list. + base::WeakPtrFactory<AppIconFetcherTask> weak_factory_{this}; +}; + // Note: This can never return kBrowser. This is because the user has // specified that the web app should be displayed in a window, and thus // the lowest fallback that we can go to is kMinimalUi. @@ -269,6 +373,11 @@ return nullptr; } + // Fetch the app icon asynchronously and provide it to the error page. + AppIconFetcherTask::FetchAndPopulateIcon( + content::WebContents::FromRenderFrameHost(render_frame_host), + web_app_provider, app_id.value()); + auto alternative_error_page_info = content::mojom::AlternativeErrorPageOverrideInfo::New(); // TODO(crbug.com/1285128): Ensure sufficient contrast. @@ -277,12 +386,10 @@ web_app_registrar.GetAppShortName(*app_id)); dict.Set(default_offline::kMessage, l10n_util::GetStringUTF16(IDS_ERRORPAGES_HEADING_YOU_ARE_OFFLINE)); - // TODO(crbug.com/1285723): The FavIcon is not the right icon to use here, as - // the design calls for showing an icon around ten times that size. This will - // probably need to be changed to fetch the right icon asynchronously. - SkBitmap bitmap = web_app_provider->icon_manager().GetFavicon(*app_id); - std::string icon_url = EncodeIconAsUrl(bitmap).spec(); - dict.Set(default_offline::kIconUrl, icon_url); + // Android uses kIconUrl to provide the icon url synchronously, but Desktop + // sends down a blank image source and then updates it asynchronously once it + // is available. + dict.Set(default_offline::kIconUrl, "''"); alternative_error_page_info->alternative_error_page_params = std::move(dict); alternative_error_page_info->resource_id = IDR_WEBAPP_DEFAULT_OFFLINE_HTML; return alternative_error_page_info;
diff --git a/chrome/browser/webapps/web_app_offline_browsertest.cc b/chrome/browser/webapps/web_app_offline_browsertest.cc index 07924a7f..fa6be78c7 100644 --- a/chrome/browser/webapps/web_app_offline_browsertest.cc +++ b/chrome/browser/webapps/web_app_offline_browsertest.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/hash/hash.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -213,22 +214,23 @@ ASSERT_TRUE(embedded_test_server()->Start()); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - StartWebAppAndDisconnect(web_contents, "/favicon/title2_with_favicon.html"); + StartWebAppAndDisconnect(web_contents, + "/banners/no_sw_fetch_handler_test_page.html"); + WaitForLoadStop(web_contents); if (GetParam() == PageFlagParam::kWithDefaultPageFlag) { - // Expect that the icon on default offline page is showing. - EXPECT_TRUE( + // Expect that the icon on the default offline page is showing. + EXPECT_EQ( + "You're offline", EvalJs(web_contents, - "document.getElementById('default-web-app-msg') !== null") - .ExtractBool()); - EXPECT_EQ(EvalJs(web_contents, "document.getElementById('icon').src") - .ExtractString(), - "data:image/" - "png;base64," - "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAYElEQVQ4jd2SKxLA" - "MAhEXzKdweFyp97/" - "DHVxOFQrGjr9iCY2qAX2LYbEujNSecg9GeD9gEPtYCpsJ2Ag4CCxs49wKM2Qm1Xj" - "DqEraEyuLMjIo/+tpeXdGYMSQt9AmuCXDpHoFE1lEw9DAAAAAElFTkSuQmCC"); + "document.getElementById('default-web-app-msg').textContent") + .ExtractString()); + EXPECT_EQ("Manifest test app", + EvalJs(web_contents, "document.title").ExtractString()); + EXPECT_EQ(4064523964u, + base::PersistentHash( + EvalJs(web_contents, "document.getElementById('icon').src") + .ExtractString())); } else { // Expect that the default offline page is not showing. EXPECT_TRUE(
diff --git a/chrome/browser/win/conflicts/module_blocklist_cache_updater.cc b/chrome/browser/win/conflicts/module_blocklist_cache_updater.cc index f8b31df7..1bb0513 100644 --- a/chrome/browser/win/conflicts/module_blocklist_cache_updater.cc +++ b/chrome/browser/win/conflicts/module_blocklist_cache_updater.cc
@@ -18,7 +18,6 @@ #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "base/win/registry.h" @@ -415,8 +414,8 @@ CalculateTimeDateStamp(base::Time::Now() - kMaxEntryAge); // Update the module blocklist cache on a background sequence. - base::PostTaskAndReplyWithResult( - background_sequence_.get(), FROM_HERE, + background_sequence_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&UpdateModuleBlocklistCache, cache_file_path, module_list_filter_, std::move(newly_blocklisted_modules_), std::move(blocked_modules_), kMaxModuleCount,
diff --git a/chrome/browser/win/conflicts/module_inspector.cc b/chrome/browser/win/conflicts/module_inspector.cc index 1741110..3ccd479 100644 --- a/chrome/browser/win/conflicts/module_inspector.cc +++ b/chrome/browser/win/conflicts/module_inspector.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/path_service.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "chrome/browser/win/conflicts/module_info_util.h" @@ -156,8 +155,8 @@ is_after_startup_ = true; // Read the inspection cache now that it won't affect startup. - base::PostTaskAndReplyWithResult( - cache_task_runner_.get(), FROM_HERE, + cache_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadInspectionResultsCacheOnBackgroundSequence, GetInspectionResultsCachePath()), base::BindOnce(&ModuleInspector::OnInspectionResultsCacheRead,
diff --git a/chrome/browser/win/conflicts/module_load_attempt_log_listener.cc b/chrome/browser/win/conflicts/module_load_attempt_log_listener.cc index dc294ed..f2d5a0c 100644 --- a/chrome/browser/win/conflicts/module_load_attempt_log_listener.cc +++ b/chrome/browser/win/conflicts/module_load_attempt_log_listener.cc
@@ -14,7 +14,6 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/string_piece.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "chrome/browser/win/conflicts/module_blocklist_cache_util.h" #include "chrome/chrome_elf/third_party_dlls/public_api.h" @@ -91,9 +90,8 @@ } void ModuleLoadAttemptLogListener::StartDrainingLogs() { - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(&DrainLogOnBackgroundTask), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DrainLogOnBackgroundTask), base::BindOnce(&ModuleLoadAttemptLogListener::OnLogDrained, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/win/conflicts/third_party_conflicts_manager.cc b/chrome/browser/win/conflicts/third_party_conflicts_manager.cc index 42dbd003..24b5363 100644 --- a/chrome/browser/win/conflicts/third_party_conflicts_manager.cc +++ b/chrome/browser/win/conflicts/third_party_conflicts_manager.cc
@@ -19,7 +19,6 @@ #include "base/strings/stringprintf.h" #include "base/task/sequenced_task_runner.h" #include "base/task/task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/version.h" #include "base/win/registry.h" @@ -257,8 +256,8 @@ // The InstalledApplications instance is only needed for the incompatible // applications warning. if (IncompatibleApplicationsUpdater::IsWarningEnabled()) { - base::PostTaskAndReplyWithResult( - background_sequence_.get(), FROM_HERE, base::BindOnce([]() { + background_sequence_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce([]() { return std::make_unique<InstalledApplications>(); }), base::BindOnce( @@ -269,9 +268,8 @@ // And the initial blocklisted modules are only needed for the third-party // modules blocking. if (ModuleBlocklistCacheUpdater::IsBlockingEnabled()) { - base::PostTaskAndReplyWithResult( - background_sequence_.get(), FROM_HERE, - base::BindOnce(&ReadInitialBlocklistedModules), + background_sequence_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadInitialBlocklistedModules), base::BindOnce( &ThirdPartyConflictsManager::OnInitialBlocklistedModulesRead, weak_ptr_factory_.GetWeakPtr())); @@ -311,9 +309,8 @@ module_list_received_ = true; - base::PostTaskAndReplyWithResult( - background_sequence_.get(), FROM_HERE, - base::BindOnce(&CreateModuleListFilter, path), + background_sequence_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CreateModuleListFilter, path), base::BindOnce(&ThirdPartyConflictsManager::OnModuleListFilterCreated, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 0892a87..82afb3d 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1669615051-a62915db538f95448f00ffe3abc7fcde21747b27.profdata +chrome-linux-main-1669656314-87a55cb4f2f124f1c38c11c8ffcbed4f055d5072.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index 19ff2c6..51e0443 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1669636706-569565eeeddc08a8fb0c03d1ca9edaf95e0fafce.profdata +chrome-mac-arm-main-1669656314-86dbfdccf4c06acf64e604567105df143f81c177.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index d6c5b7e..f5633a6e 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1669636706-524966aa0eda4aa94c2e73ab1049b9dc5c33c498.profdata +chrome-mac-main-1669656314-c98d45ab595374a6d7328896e785e597f17bf8b7.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 1a74411..373f869 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1669636706-60b08a96ab56b538df3e69790d97014d92ff68c5.profdata +chrome-win32-main-1669647535-a05bdcbc278a8a3579c58cc8ea090754a0d65aeb.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 5e00fac..b2ae1cb 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1669636706-e6696c29b9f646a1a81542c231f82fa34c1ec3aa.profdata +chrome-win64-main-1669647535-1b78e1a15937228f2435c0c69b40ceebbf158dd8.profdata
diff --git a/chrome/chrome_cleaner/engines/target/test_engine_delegate.cc b/chrome/chrome_cleaner/engines/target/test_engine_delegate.cc index e035a83..35b36df 100644 --- a/chrome/chrome_cleaner/engines/target/test_engine_delegate.cc +++ b/chrome/chrome_cleaner/engines/target/test_engine_delegate.cc
@@ -18,7 +18,6 @@ #include "base/memory/scoped_refptr.h" #include "base/strings/string_piece.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/win/scoped_handle.h" #include "chrome/chrome_cleaner/constants/uws_id.h" #include "chrome/chrome_cleaner/engines/common/engine_result_codes.h" @@ -267,8 +266,8 @@ scoped_refptr<EngineRequestsProxy> privileged_scan_calls, scoped_refptr<EngineScanResultsProxy> report_result_calls) { DCHECK(work_thread_); - base::PostTaskAndReplyWithResult( - work_thread_->task_runner().get(), FROM_HERE, + work_thread_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ScanForUwS, enabled_uws, enabled_trace_locations, include_details, privileged_file_calls, report_result_calls), @@ -284,8 +283,8 @@ scoped_refptr<CleanerEngineRequestsProxy> privileged_removal_calls, scoped_refptr<EngineCleanupResultsProxy> report_result_calls) { DCHECK(work_thread_); - base::PostTaskAndReplyWithResult( - work_thread_->task_runner().get(), FROM_HERE, + work_thread_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CleanUwS, enabled_uws, privileged_file_calls, privileged_removal_calls), base::BindOnce(&CleanupDone, privileged_file_calls, privileged_scan_calls,
diff --git a/chrome/common/printing/printer_capabilities_unittest.cc b/chrome/common/printing/printer_capabilities_unittest.cc index fba7efd..cefaa0f91 100644 --- a/chrome/common/printing/printer_capabilities_unittest.cc +++ b/chrome/common/printing/printer_capabilities_unittest.cc
@@ -8,7 +8,6 @@ #include "base/bind.h" #include "base/memory/ref_counted.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" @@ -80,8 +79,8 @@ base::RunLoop run_loop; base::Value::Dict settings; - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetSettingsOnBlockingTaskRunner, printer_name, basic_info, std::move(papers), /*has_secure_protocol=*/false, test_backend_),
diff --git a/chrome/services/media_gallery_util/media_metadata_parser.cc b/chrome/services/media_gallery_util/media_metadata_parser.cc index b75a488..13f14a9 100644 --- a/chrome/services/media_gallery_util/media_metadata_parser.cc +++ b/chrome/services/media_gallery_util/media_metadata_parser.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/location.h" #include "base/strings/string_util.h" -#include "base/task/task_runner_util.h" #include "base/threading/thread.h" #include "media/base/data_source.h" #include "media/filters/audio_video_metadata_extractor.h" @@ -122,8 +121,8 @@ media_thread_ = std::make_unique<base::Thread>("media_thread"); CHECK(media_thread_->Start()); - base::PostTaskAndReplyWithResult( - media_thread_->task_runner().get(), FROM_HERE, + media_thread_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ParseAudioVideoMetadata, source_.get(), get_attached_images_, mime_type_, images), base::BindOnce(&FinishParseAudioVideoMetadata, std::move(callback),
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 6ce6fcb12..b5d61743 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -9022,6 +9022,10 @@ "../browser/supervised_user/supervised_user_url_filter_unittest.cc", "../browser/supervised_user/web_approvals_manager_unittest.cc", ] + if (is_chromeos_ash) { + deps += [ "//chrome/browser/ash/crosapi" ] + } + if (enable_extensions) { sources += [ "../browser/supervised_user/supervised_user_extension_unittest.cc" ]
diff --git a/chrome/test/chromedriver/chrome/cast_tracker_unittest.cc b/chrome/test/chromedriver/chrome/cast_tracker_unittest.cc index b6fa09ee..00b6490 100644 --- a/chrome/test/chromedriver/chrome/cast_tracker_unittest.cc +++ b/chrome/test/chromedriver/chrome/cast_tracker_unittest.cc
@@ -50,31 +50,31 @@ TEST_F(CastTrackerTest, OnSinksUpdated) { const base::Value empty_sinks = base::Value(base::Value::List()); - base::DictionaryValue params; + base::Value::Dict params; EXPECT_EQ(0u, cast_tracker_->sinks().GetList().size()); base::Value::List sinks; sinks.Append(CreateSink("sink1", "1")); sinks.Append(CreateSink("sink2", "2")); - params.SetKey("sinks", base::Value(std::move(sinks))); + params.Set("sinks", base::Value(std::move(sinks))); cast_tracker_->OnEvent(&devtools_client_, "Cast.sinksUpdated", params); EXPECT_EQ(2u, cast_tracker_->sinks().GetList().size()); - params.SetKey("sinks", base::Value(base::Value::Type::LIST)); + params.Set("sinks", base::Value(base::Value::Type::LIST)); cast_tracker_->OnEvent(&devtools_client_, "Cast.sinksUpdated", params); EXPECT_EQ(0u, cast_tracker_->sinks().GetList().size()); } TEST_F(CastTrackerTest, OnIssueUpdated) { const std::string issue_message = "There was an issue"; - base::DictionaryValue params; + base::Value::Dict params; EXPECT_EQ("", cast_tracker_->issue().GetString()); - params.SetKey("issueMessage", base::Value(issue_message)); + params.Set("issueMessage", base::Value(issue_message)); cast_tracker_->OnEvent(&devtools_client_, "Cast.issueUpdated", params); EXPECT_EQ(issue_message, cast_tracker_->issue().GetString()); - params.SetKey("issueMessage", base::Value("")); + params.Set("issueMessage", base::Value("")); cast_tracker_->OnEvent(&devtools_client_, "Cast.issueUpdated", params); EXPECT_EQ("", cast_tracker_->issue().GetString()); }
diff --git a/chrome/test/chromedriver/chrome/console_logger_unittest.cc b/chrome/test/chromedriver/chrome/console_logger_unittest.cc index a22a93f..5e1a1dc6 100644 --- a/chrome/test/chromedriver/chrome/console_logger_unittest.cc +++ b/chrome/test/chromedriver/chrome/console_logger_unittest.cc
@@ -37,8 +37,9 @@ } Status TriggerEvent(const std::string& method, - const base::DictionaryValue& params) { - return listener_->OnEvent(this, method, params); + const base::Value::Dict& params) { + return static_cast<ConsoleLogger*>(listener_)->OnEvent(this, method, + params); } // Overridden from DevToolsClient: @@ -118,23 +119,24 @@ EXPECT_EQ(expected_message, entry->message); } -void ConsoleLogParams(base::DictionaryValue* out_params, - const char* source, - const char* url, - const char* level, +// Log params into `out_dict`. If a string param is empty it is not set. +void ConsoleLogParams(base::Value::Dict* out_dict, + const std::string& source, + const std::string& url, + const std::string& level, int line_number, - const char* text) { - base::Value::Dict* out_dict = out_params->GetIfDict(); + const std::string& text) { CHECK(out_dict); - if (source) + if (!source.empty()) out_dict->SetByDottedPath("entry.source", source); - if (url) + + if (!url.empty()) out_dict->SetByDottedPath("entry.url", url); - if (level) + if (!level.empty()) out_dict->SetByDottedPath("entry.level", level); if (line_number != -1) out_dict->SetByDottedPath("entry.lineNumber", line_number); - if (text) + if (!text.empty()) out_dict->SetByDottedPath("entry.text", text); } @@ -151,38 +153,38 @@ EXPECT_EQ("Runtime.enable", client.PopSentCommand()); EXPECT_TRUE(client.PopSentCommand().empty()); - base::DictionaryValue params1; // All fields are set. + base::Value::Dict params1; // All fields are set. ConsoleLogParams(¶ms1, "source1", "url1", "verbose", 10, "text1"); ASSERT_EQ(kOk, client.TriggerEvent("Log.entryAdded", params1).code()); // Ignored -- wrong method. ASSERT_EQ(kOk, client.TriggerEvent("Log.gaga", params1).code()); - base::DictionaryValue params2; // All optionals are not set. - ConsoleLogParams(¶ms2, "source2", nullptr, "log", -1, "text2"); + base::Value::Dict params2; // All optionals are not set. + ConsoleLogParams(¶ms2, "source2", "", "log", -1, "text2"); ASSERT_EQ(kOk, client.TriggerEvent("Log.entryAdded", params2).code()); - base::DictionaryValue params3; // Line, no source. - ConsoleLogParams(¶ms3, nullptr, "url3", "warning", 30, "text3"); + base::Value::Dict params3; // Line, no source. + ConsoleLogParams(¶ms3, "", "url3", "warning", 30, "text3"); ASSERT_EQ(kUnknownError, client.TriggerEvent("Log.entryAdded", params3).code()); - base::DictionaryValue params5; // Bad level name. + base::Value::Dict params5; // Bad level name. ConsoleLogParams(¶ms5, "source5", "url5", "gaga", 50, "ulala"); ASSERT_EQ(kUnknownError, client.TriggerEvent("Log.entryAdded", params5).code()); - base::DictionaryValue params6; // Unset level. - ConsoleLogParams(¶ms6, "source6", "url6", nullptr, 60, nullptr); + base::Value::Dict params6; // Unset level. + ConsoleLogParams(¶ms6, "source6", "url6", "", 60, ""); ASSERT_EQ(kUnknownError, client.TriggerEvent("Log.entryAdded", params6).code()); - base::DictionaryValue params7; // No text. - ConsoleLogParams(¶ms7, "source7", "url7", "log", -1, nullptr); + base::Value::Dict params7; // No text. + ConsoleLogParams(¶ms7, "source7", "url7", "log", -1, ""); ASSERT_EQ(kUnknownError, client.TriggerEvent("Log.entryAdded", params7).code()); - base::DictionaryValue params8; // No message object. - params8.GetDict().Set("gaga", 8); + base::Value::Dict params8; // No message object. + params8.Set("gaga", 8); ASSERT_EQ(kUnknownError, client.TriggerEvent("Log.entryAdded", params8).code());
diff --git a/chrome/test/chromedriver/chrome/geolocation_override_manager_unittest.cc b/chrome/test/chromedriver/chrome/geolocation_override_manager_unittest.cc index b14c7d0..7b7d7bb 100644 --- a/chrome/test/chromedriver/chrome/geolocation_override_manager_unittest.cc +++ b/chrome/test/chromedriver/chrome/geolocation_override_manager_unittest.cc
@@ -59,7 +59,7 @@ TEST(GeolocationOverrideManager, SendsCommandOnNavigation) { RecorderDevToolsClient client; GeolocationOverrideManager manager(&client); - base::DictionaryValue main_frame_params; + base::Value::Dict main_frame_params; ASSERT_EQ(kOk, manager.OnEvent(&client, "Page.frameNavigated", main_frame_params) .code()); @@ -75,8 +75,8 @@ ASSERT_NO_FATAL_FAILURE( AssertGeolocationCommand(client.commands_[1], geoposition)); - base::DictionaryValue sub_frame_params; - sub_frame_params.SetString("frame.parentId", "id"); + base::Value::Dict sub_frame_params; + sub_frame_params.SetByDottedPath("frame.parentId", "id"); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.frameNavigated", sub_frame_params).code());
diff --git a/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc b/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc index 8766e1e..e64152b 100644 --- a/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc +++ b/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc
@@ -30,10 +30,10 @@ RecorderDevToolsClient client; BrowserInfo browser_info; JavaScriptDialogManager manager(&client, &browser_info); - base::DictionaryValue params; - params.SetString("message", "hi"); - params.SetString("type", "prompt"); - params.SetString("defaultPrompt", "This is a default text"); + base::Value::Dict params; + params.Set("message", "hi"); + params.Set("type", "prompt"); + params.Set("defaultPrompt", "This is a default text"); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); @@ -49,10 +49,10 @@ RecorderDevToolsClient client; BrowserInfo browser_info; JavaScriptDialogManager manager(&client, &browser_info); - base::DictionaryValue params; - params.SetString("message", "hi"); - params.SetString("type", "prompt"); - params.SetString("defaultPrompt", ""); + base::Value::Dict params; + params.Set("message", "hi"); + params.Set("type", "prompt"); + params.Set("defaultPrompt", ""); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); @@ -65,10 +65,10 @@ RecorderDevToolsClient client; BrowserInfo browser_info; JavaScriptDialogManager manager(&client, &browser_info); - base::DictionaryValue params; - params.SetString("message", "hi"); - params.SetString("type", "alert"); - params.SetString("defaultPrompt", ""); + base::Value::Dict params; + params.Set("message", "hi"); + params.Set("type", "alert"); + params.Set("defaultPrompt", ""); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code());
diff --git a/chrome/test/chromedriver/chrome/mobile_emulation_override_manager_unittest.cc b/chrome/test/chromedriver/chrome/mobile_emulation_override_manager_unittest.cc index 879a9b6..fa21671 100644 --- a/chrome/test/chromedriver/chrome/mobile_emulation_override_manager_unittest.cc +++ b/chrome/test/chromedriver/chrome/mobile_emulation_override_manager_unittest.cc
@@ -70,7 +70,7 @@ RecorderDevToolsClient client; DeviceMetrics device_metrics(1, 2, 3.0, true, true); MobileEmulationOverrideManager manager(&client, &device_metrics); - base::DictionaryValue main_frame_params; + base::Value::Dict main_frame_params; ASSERT_EQ(kOk, manager.OnEvent(&client, "Page.frameNavigated", main_frame_params) .code()); @@ -82,8 +82,8 @@ ASSERT_NO_FATAL_FAILURE( AssertDeviceMetricsCommand(client.commands_[2], device_metrics)); - base::DictionaryValue sub_frame_params; - sub_frame_params.SetString("frame.parentId", "id"); + base::Value::Dict sub_frame_params; + sub_frame_params.SetByDottedPath("frame.parentId", "id"); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.frameNavigated", sub_frame_params).code());
diff --git a/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc b/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc index b0cc27c..aab4350 100644 --- a/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc +++ b/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc
@@ -31,11 +31,10 @@ class DeterminingLoadStateDevToolsClient : public StubDevToolsClient { public: - DeterminingLoadStateDevToolsClient( - bool has_empty_base_url, - bool is_loading, - const std::string& send_event_first, - base::DictionaryValue* send_event_first_params) + DeterminingLoadStateDevToolsClient(bool has_empty_base_url, + bool is_loading, + const std::string& send_event_first, + base::Value::Dict* send_event_first_params) : has_empty_base_url_(has_empty_base_url), is_loading_(is_loading), send_event_first_(send_event_first), @@ -47,34 +46,32 @@ const base::Value::Dict& params, base::Value* result) override { if (method == "DOM.getDocument") { - base::Value result_dict(base::Value::Type::DICTIONARY); + base::Value::Dict result_dict; if (has_empty_base_url_) { - result_dict.GetDict().SetByDottedPath("root.baseURL", "about:blank"); - result_dict.GetDict().SetByDottedPath("root.documentURL", - "http://test"); + result_dict.SetByDottedPath("root.baseURL", "about:blank"); + result_dict.SetByDottedPath("root.documentURL", "http://test"); } else { - result_dict.GetDict().SetByDottedPath("root.baseURL", "http://test"); - result_dict.GetDict().SetByDottedPath("root.documentURL", - "http://test"); + result_dict.SetByDottedPath("root.baseURL", "http://test"); + result_dict.SetByDottedPath("root.documentURL", "http://test"); } - *result = std::move(result_dict); + *result = base::Value(std::move(result_dict)); return Status(kOk); } else if (method == "Runtime.evaluate") { const std::string* expression = params.FindString("expression"); if (expression) { - base::Value result_dict(base::Value::Type::DICTIONARY); + base::Value::Dict result_dict; if (*expression == "1") - result_dict.GetDict().SetByDottedPath("result.value", 1); + result_dict.SetByDottedPath("result.value", 1); else if (*expression == "document.readyState") - result_dict.GetDict().SetByDottedPath("result.value", "loading"); - *result = std::move(result_dict); + result_dict.SetByDottedPath("result.value", "loading"); + *result = base::Value(std::move(result_dict)); return Status(kOk); } } if (send_event_first_.length()) { for (DevToolsEventListener* listener : listeners_) { - Status status = listener->OnEvent( + Status status = static_cast<NavigationTracker*>(listener)->OnEvent( this, send_event_first_, *send_event_first_params_); if (status.IsError()) return status; @@ -91,7 +88,7 @@ bool has_empty_base_url_; bool is_loading_; std::string send_event_first_; - raw_ptr<base::DictionaryValue> send_event_first_params_; + raw_ptr<base::Value::Dict> send_event_first_params_; }; class EvaluateScriptWebView : public StubWebView { @@ -121,7 +118,7 @@ } // namespace TEST(NavigationTracker, FrameLoadStartStop) { - base::DictionaryValue dict; + base::Value::Dict dict; BrowserInfo browser_info; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( @@ -134,8 +131,8 @@ NavigationTracker tracker(client_ptr, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params; - params.GetDict().Set("frameId", client_ptr->GetId()); + base::Value::Dict params; + params.Set("frameId", client_ptr->GetId()); ASSERT_EQ( kOk, @@ -150,7 +147,7 @@ // can sometimes see two Page.frameStartedLoading events with only a single // Page.loadEventFired event. TEST(NavigationTracker, FrameLoadStartStartStop) { - base::DictionaryValue dict; + base::Value::Dict dict; BrowserInfo browser_info; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( @@ -163,8 +160,8 @@ NavigationTracker tracker(client_ptr, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params; - params.GetDict().Set("frameId", client_ptr->GetId()); + base::Value::Dict params; + params.Set("frameId", client_ptr->GetId()); ASSERT_EQ( kOk, @@ -180,7 +177,7 @@ } TEST(NavigationTracker, MultipleFramesLoad) { - base::DictionaryValue dict; + base::Value::Dict dict; BrowserInfo browser_info; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( @@ -193,34 +190,34 @@ NavigationTracker tracker(client_ptr, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params; + base::Value::Dict params; std::string top_frame_id = client_ptr->GetId(); - params.GetDict().Set("frameId", top_frame_id); + params.Set("frameId", top_frame_id); ASSERT_EQ( kOk, tracker.OnEvent(client_ptr, "Page.frameStartedLoading", params).code()); ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, true)); - params.SetString("frameId", "2"); + params.Set("frameId", "2"); ASSERT_EQ( kOk, tracker.OnEvent(client_ptr, "Page.frameStartedLoading", params).code()); ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, true)); - params.GetDict().Set("frameId", "2"); + params.Set("frameId", "2"); ASSERT_EQ( kOk, tracker.OnEvent(client_ptr, "Page.frameStoppedLoading", params).code()); // Inner frame stops loading. loading_state_ should remain true // since top frame is still loading ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, true)); - params.GetDict().Set("frameId", top_frame_id); + params.Set("frameId", top_frame_id); ASSERT_EQ(kOk, tracker.OnEvent(client_ptr, "Page.loadEventFired", params).code()); ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, false)); - params.GetDict().Set("frameId", "3"); + params.Set("frameId", "3"); ASSERT_EQ( kOk, tracker.OnEvent(client_ptr, "Page.frameStoppedLoading", params).code()); @@ -234,7 +231,7 @@ } TEST(NavigationTracker, NavigationScheduledForOtherFrame) { - base::DictionaryValue dict; + base::Value::Dict dict; BrowserInfo browser_info; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( @@ -247,9 +244,9 @@ NavigationTracker tracker(client_ptr, NavigationTracker::kNotLoading, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params_scheduled; - params_scheduled.GetDict().Set("delay", 0); - params_scheduled.GetDict().Set("frameId", "other"); + base::Value::Dict params_scheduled; + params_scheduled.Set("delay", 0); + params_scheduled.Set("frameId", "other"); ASSERT_EQ(kOk, tracker .OnEvent(client_ptr, "Page.frameScheduledNavigation", @@ -259,7 +256,7 @@ } TEST(NavigationTracker, CurrentFrameLoading) { - base::DictionaryValue dict; + base::Value::Dict dict; BrowserInfo browser_info; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( @@ -270,10 +267,10 @@ NavigationTracker tracker(client_ptr, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params; + base::Value::Dict params; std::string top_frame_id = client_ptr->GetId(); std::string current_frame_id = "2"; - params.GetDict().Set("frameId", current_frame_id); + params.Set("frameId", current_frame_id); // verify initial state ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, true)); @@ -300,7 +297,7 @@ ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, false)); // loading state should not respond to unknown frame events - params.GetDict().Set("frameId", "4"); + params.Set("frameId", "4"); ASSERT_EQ( kOk, tracker.OnEvent(client_ptr, "Page.frameStartedLoading", params).code()); @@ -312,7 +309,7 @@ } TEST(NavigationTracker, FrameAttachDetach) { - base::DictionaryValue dict; + base::Value::Dict dict; BrowserInfo browser_info; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( @@ -323,10 +320,10 @@ NavigationTracker tracker(client_ptr, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params; + base::Value::Dict params; std::string top_frame_id = client_ptr->GetId(); std::string current_frame_id = "2"; - params.GetDict().Set("frameId", current_frame_id); + params.Set("frameId", current_frame_id); // verify initial state ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, true)); @@ -353,7 +350,7 @@ } TEST(NavigationTracker, SetFrameNoFrame) { - base::DictionaryValue dict; + base::Value::Dict dict; BrowserInfo browser_info; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( @@ -364,14 +361,14 @@ NavigationTracker tracker(client_ptr, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params; + base::Value::Dict params; std::string top_frame_id = client_ptr->GetId(); web_view.nextEvaluateScript("uninitialized", kOk); ASSERT_NO_FATAL_FAILURE(tracker.SetFrame(std::string())); ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, true)); ASSERT_NO_FATAL_FAILURE(tracker.SetFrame("2")); ASSERT_NO_FATAL_FAILURE(tracker.SetFrame(std::string())); - params.GetDict().Set("frameId", top_frame_id); + params.Set("frameId", top_frame_id); web_view.nextEvaluateScript("complete", kOk); ASSERT_EQ( kOk, @@ -379,7 +376,7 @@ ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, false)); // loading state should not respond to unknown frame events - params.SetString("frameId", "2"); + params.Set("frameId", "2"); ASSERT_EQ( kOk, tracker.OnEvent(client_ptr, "Page.frameStartedLoading", params).code()); @@ -437,7 +434,7 @@ } TEST(NavigationTracker, UnknownStatePageNotLoadAtAll) { - base::DictionaryValue dict; + base::Value::Dict dict; BrowserInfo browser_info; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( @@ -454,7 +451,7 @@ } TEST(NavigationTracker, UnknownStateForcesStart) { - base::DictionaryValue dict; + base::Value::Dict dict; BrowserInfo browser_info; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( @@ -469,7 +466,7 @@ } TEST(NavigationTracker, UnknownStateForcesStartReceivesStop) { - base::DictionaryValue dict; + base::Value::Dict dict; BrowserInfo browser_info; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( @@ -482,8 +479,8 @@ NavigationTracker tracker(client_ptr, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params; - params.GetDict().Set("frameId", client_ptr->GetId()); + base::Value::Dict params; + params.Set("frameId", client_ptr->GetId()); ASSERT_EQ(kOk, tracker.OnEvent(client_ptr, "Page.loadEventFired", params).code()); ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, false)); @@ -495,7 +492,7 @@ " \"WebKit-Version\": \"537.36 (@199461)\"}"; ASSERT_TRUE(ParseBrowserInfo(version_string, &browser_info).IsOk()); - base::DictionaryValue dict; + base::Value::Dict dict; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( false, true, std::string(), &dict); @@ -505,9 +502,9 @@ NavigationTracker tracker(client_ptr, NavigationTracker::kNotLoading, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params; - base::DictionaryValue result; - result.GetDict().Set("frameId", client_ptr->GetId()); + base::Value::Dict params; + base::Value::Dict result; + result.Set("frameId", client_ptr->GetId()); web_view.nextEvaluateScript("loading", kOk); tracker.OnCommandSuccess(client_ptr, "Page.navigate", &result, Timeout()); ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, true)); @@ -523,7 +520,7 @@ " \"WebKit-Version\": \"537.36 (@199461)\"}"; ASSERT_TRUE(ParseBrowserInfo(version_string, &browser_info).IsOk()); - base::DictionaryValue dict; + base::Value::Dict dict; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( false, true, std::string(), &dict); @@ -533,10 +530,10 @@ NavigationTracker tracker(client_ptr, NavigationTracker::kNotLoading, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params; - base::DictionaryValue result; - result.GetDict().Set("frameId", client_ptr->GetId()); - result.GetDict().Set("errorText", "net::ERR_PROXY_CONNECTION_FAILED"); + base::Value::Dict params; + base::Value::Dict result; + result.Set("frameId", client_ptr->GetId()); + result.Set("errorText", "net::ERR_PROXY_CONNECTION_FAILED"); web_view.nextEvaluateScript("loading", kOk); ASSERT_NE( kOk, @@ -552,7 +549,7 @@ " \"WebKit-Version\": \"537.36 (@199461)\"}"; ASSERT_TRUE(ParseBrowserInfo(version_string, &browser_info).IsOk()); - base::DictionaryValue dict; + base::Value::Dict dict; std::unique_ptr<DevToolsClient> client_uptr = std::make_unique<DeterminingLoadStateDevToolsClient>( false, true, std::string(), &dict); @@ -562,10 +559,10 @@ NavigationTracker tracker(client_ptr, NavigationTracker::kNotLoading, &web_view, &browser_info, &dialog_manager); - base::DictionaryValue params; - base::DictionaryValue result; - result.GetDict().Set("frameId", client_ptr->GetId()); - result.GetDict().Set("errorText", "net::ERR_CERT_COMMON_NAME_INVALID"); + base::Value::Dict params; + base::Value::Dict result; + result.Set("frameId", client_ptr->GetId()); + result.Set("errorText", "net::ERR_CERT_COMMON_NAME_INVALID"); web_view.nextEvaluateScript("loading", kOk); tracker.OnCommandSuccess(client_ptr, "Page.navigate", &result, Timeout()); ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, true));
diff --git a/chrome/test/chromedriver/chrome/network_conditions_override_manager_unittest.cc b/chrome/test/chromedriver/chrome/network_conditions_override_manager_unittest.cc index 098af64..d881da4 100644 --- a/chrome/test/chromedriver/chrome/network_conditions_override_manager_unittest.cc +++ b/chrome/test/chromedriver/chrome/network_conditions_override_manager_unittest.cc
@@ -65,7 +65,7 @@ TEST(NetworkConditionsOverrideManager, SendsCommandOnNavigation) { RecorderDevToolsClient client; NetworkConditionsOverrideManager manager(&client); - base::DictionaryValue main_frame_params; + base::Value::Dict main_frame_params; ASSERT_EQ(kOk, manager.OnEvent(&client, "Page.frameNavigated", main_frame_params) .code()); @@ -81,8 +81,8 @@ ASSERT_NO_FATAL_FAILURE( AssertNetworkConditionsCommand(client.commands_[2], network_conditions)); - base::DictionaryValue sub_frame_params; - sub_frame_params.SetString("frame.parentId", "id"); + base::Value::Dict sub_frame_params; + sub_frame_params.SetByDottedPath("frame.parentId", "id"); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.frameNavigated", sub_frame_params).code());
diff --git a/chrome/test/chromedriver/performance_logger_unittest.cc b/chrome/test/chromedriver/performance_logger_unittest.cc index df49f039..0c932a4 100644 --- a/chrome/test/chromedriver/performance_logger_unittest.cc +++ b/chrome/test/chromedriver/performance_logger_unittest.cc
@@ -26,15 +26,14 @@ namespace { struct DevToolsCommand { - DevToolsCommand(const std::string& in_method, - base::DictionaryValue* in_params) + DevToolsCommand(const std::string& in_method, base::Value::Dict* in_params) : method(in_method) { params.reset(in_params); } ~DevToolsCommand() {} std::string method; - std::unique_ptr<base::DictionaryValue> params; + std::unique_ptr<base::Value::Dict> params; }; class FakeDevToolsClient : public StubDevToolsClient { @@ -51,18 +50,14 @@ return false; } - Status TriggerEvent(const std::string& method) { - base::Value::Dict empty_params; - return listener_->OnEvent( - this, method, - base::Value::AsDictionaryValue(base::Value(std::move(empty_params)))); - } - Status TriggerEvent(const std::string& method, const base::Value::Dict& params) { - return listener_->OnEvent( - this, method, - base::Value::AsDictionaryValue(base::Value(params.Clone()))); + return static_cast<PerformanceLogger*>(listener_)->OnEvent(this, method, + params); + } + + Status TriggerEvent(const std::string& method) { + return TriggerEvent(method, base::Value::Dict()); } // Overridden from DevToolsClient: @@ -71,10 +66,9 @@ Status SendCommandAndGetResult(const std::string& method, const base::Value::Dict& params, base::Value* result) override { - sent_commands_.push_back(std::make_unique<DevToolsCommand>( - method, base::DictionaryValue::From( - base::Value::ToUniquePtrValue(base::Value(params.Clone()))) - .release())); + auto dict = std::make_unique<base::Value::Dict>(params.Clone()); + sent_commands_.push_back( + std::make_unique<DevToolsCommand>(method, dict.release())); *result = base::Value(base::Value::Type::DICTIONARY); return Status(kOk); } @@ -303,16 +297,16 @@ DevToolsCommand* cmd; ASSERT_TRUE(client.PopSentCommand(&cmd)); EXPECT_EQ("Tracing.start", cmd->method); - base::ListValue* categories; - EXPECT_TRUE(cmd->params->GetList("traceConfig.includedCategories", - &categories)); - ASSERT_EQ(2u, categories->GetList().size()); - ASSERT_TRUE(categories->GetList()[0].is_string()); - EXPECT_EQ("benchmark", categories->GetList()[0].GetString()); - ASSERT_TRUE(categories->GetList()[1].is_string()); - EXPECT_EQ("blink.console", categories->GetList()[1].GetString()); + const base::Value::List* categories = + cmd->params->FindListByDottedPath("traceConfig.includedCategories"); + ASSERT_TRUE(categories); + ASSERT_EQ(2u, categories->size()); + ASSERT_TRUE((*categories)[0].is_string()); + EXPECT_EQ("benchmark", (*categories)[0].GetString()); + ASSERT_TRUE((*categories)[1].is_string()); + EXPECT_EQ("blink.console", (*categories)[1].GetString()); int expected_interval = - cmd->params->FindIntKey("bufferUsageReportingInterval").value_or(-1); + cmd->params->FindInt("bufferUsageReportingInterval").value_or(-1); EXPECT_GT(expected_interval, 0); ASSERT_FALSE(client.PopSentCommand(&cmd));
diff --git a/chrome/test/data/webui/chromeos/scanning/BUILD.gn b/chrome/test/data/webui/chromeos/scanning/BUILD.gn index 8985403..89c4324b 100644 --- a/chrome/test/data/webui/chromeos/scanning/BUILD.gn +++ b/chrome/test/data/webui/chromeos/scanning/BUILD.gn
@@ -35,7 +35,6 @@ ":scanner_select_test", ":scanning_app_test", ":scanning_app_test_utils", - ":scanning_app_unified_test", ":source_select_test", ":test_scanning_browser_proxy", ] @@ -158,9 +157,6 @@ deps = [ "..:chai_assert" ] } -js_library("scanning_app_unified_test") { -} - js_library("source_select_test") { deps = [ ":scanning_app_test_utils",
diff --git a/chrome/test/data/webui/chromeos/scanning/action_toolbar_test.js b/chrome/test/data/webui/chromeos/scanning/action_toolbar_test.js index 9eef3aa..63e48cf 100644 --- a/chrome/test/data/webui/chromeos/scanning/action_toolbar_test.js +++ b/chrome/test/data/webui/chromeos/scanning/action_toolbar_test.js
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/action_toolbar.js'; +import {assertEquals, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; -import {assertEquals, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; - -export function actionToolbarTest() { +suite('actionToolbarTest', function() { /** @type {?ActionToolbarElement} */ let actionToolbar = null; @@ -73,4 +73,4 @@ assertEquals(expectedPageIndex, pageIndexFromEvent); }); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/color_mode_select_test.js b/chrome/test/data/webui/chromeos/scanning/color_mode_select_test.js index e12dd94..020fb4a 100644 --- a/chrome/test/data/webui/chromeos/scanning/color_mode_select_test.js +++ b/chrome/test/data/webui/chromeos/scanning/color_mode_select_test.js
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/color_mode_select.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getColorModeString} from 'chrome://scanning/scanning_app_util.js'; - import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {assertOrderedAlphabetically, changeSelect} from './scanning_app_test_utils.js'; @@ -17,7 +17,7 @@ COLOR: ash.scanning.mojom.ColorMode.kColor, }; -export function colorModeSelectTest() { +suite('colorModeSelectTest', function() { /** @type {?ColorModeSelectElement} */ let colorModeSelect = null; @@ -105,4 +105,4 @@ select.options[select.selectedIndex].value); }); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/file_type_select_test.js b/chrome/test/data/webui/chromeos/scanning/file_type_select_test.js index 58e0709..30f53e4 100644 --- a/chrome/test/data/webui/chromeos/scanning/file_type_select_test.js +++ b/chrome/test/data/webui/chromeos/scanning/file_type_select_test.js
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/file_type_select.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; @@ -14,7 +15,7 @@ PNG: ash.scanning.mojom.FileType.kPng, }; -export function fileTypeSelectTest() { +suite('fileTypeSelectTest', function() { /** @type {?FileTypeSelectElement} */ let fileTypeSelect = null; @@ -51,4 +52,4 @@ FileType.JPG.toString(), fileTypeSelect.selectedFileType); }); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/loading_page_test.js b/chrome/test/data/webui/chromeos/scanning/loading_page_test.js index 518f56ae..080ece7b 100644 --- a/chrome/test/data/webui/chromeos/scanning/loading_page_test.js +++ b/chrome/test/data/webui/chromeos/scanning/loading_page_test.js
@@ -2,18 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/loading_page.js'; import {AppState} from 'chrome://scanning/scanning_app_types.js'; -import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; - import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {MockController} from 'chrome://webui-test/chromeos/mock_controller.m.js'; import {isVisible} from 'chrome://webui-test/chromeos/test_util.js'; +import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; import {FakeMediaQueryList} from './scanning_app_test_utils.js'; -export function loadingPageTest() { +suite('loadingPageTest', function() { const scanningSrcBase = 'chrome://scanning/'; /** @type {?LoadingPageElement} */ @@ -136,4 +136,4 @@ await setFakePrefersColorSchemeDark(true); assertEquals(getLoadingSvg().src, darkModeSvg); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/multi_page_checkbox_test.js b/chrome/test/data/webui/chromeos/scanning/multi_page_checkbox_test.js index a9a13cb..c9bf908 100644 --- a/chrome/test/data/webui/chromeos/scanning/multi_page_checkbox_test.js +++ b/chrome/test/data/webui/chromeos/scanning/multi_page_checkbox_test.js
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/multi_page_checkbox.js'; +import {assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; -import {assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; - -export function multiPageCheckboxTest() { +suite('multiPageCheckboxTest', function() { /** @type {?MultiPageCheckboxElement} */ let multiPageCheckbox = null; @@ -35,4 +35,4 @@ multiPageCheckbox.$$('#checkboxText').click(); assertFalse(multiPageCheckbox.multiPageScanChecked); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/multi_page_scan_test.js b/chrome/test/data/webui/chromeos/scanning/multi_page_scan_test.js index bcad02f..7c843d3 100644 --- a/chrome/test/data/webui/chromeos/scanning/multi_page_scan_test.js +++ b/chrome/test/data/webui/chromeos/scanning/multi_page_scan_test.js
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/multi_page_scan.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {AppState} from 'chrome://scanning/scanning_app_types.js'; import {ScanningBrowserProxyImpl} from 'chrome://scanning/scanning_browser_proxy.js'; -import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; - import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {isVisible} from 'chrome://webui-test/chromeos/test_util.js'; +import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; import {TestScanningBrowserProxy} from './test_scanning_browser_proxy.js'; -export function multiPageScanTest() { +suite('multiPageScanTest', function() { /** @type {?MultiPageScanElement} */ let multiPageScan = null; @@ -130,4 +130,4 @@ multiPageScan.$$('#cancelButton').click(); assertTrue(clickCancelEventFired); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/page_size_select_test.js b/chrome/test/data/webui/chromeos/scanning/page_size_select_test.js index de21fb0..58b4cee 100644 --- a/chrome/test/data/webui/chromeos/scanning/page_size_select_test.js +++ b/chrome/test/data/webui/chromeos/scanning/page_size_select_test.js
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/page_size_select.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getPageSizeString} from 'chrome://scanning/scanning_app_util.js'; - import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {assertOrderedAlphabetically, changeSelect} from './scanning_app_test_utils.js'; @@ -21,7 +21,7 @@ Max: ash.scanning.mojom.PageSize.kMax, }; -export function pageSizeSelectTest() { +suite('pageSizeSelectTest', function() { /** @type {?PageSizeSelectElement} */ let pageSizeSelect = null; @@ -126,4 +126,4 @@ select.options[select.selectedIndex].value); }); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/resolution_select_test.js b/chrome/test/data/webui/chromeos/scanning/resolution_select_test.js index 3a0bcf7..45c1281 100644 --- a/chrome/test/data/webui/chromeos/scanning/resolution_select_test.js +++ b/chrome/test/data/webui/chromeos/scanning/resolution_select_test.js
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/resolution_select.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {changeSelect} from './scanning_app_test_utils.js'; -export function resolutionSelectTest() { +suite('resolutionSelectTest', function() { /** @type {?ResolutionSelectElement} */ let resolutionSelect = null; @@ -99,4 +99,4 @@ assertEquals('300', select.options[select.selectedIndex].value); }); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/scan_done_section_test.js b/chrome/test/data/webui/chromeos/scanning/scan_done_section_test.js index 70094993..34f8cb54 100644 --- a/chrome/test/data/webui/chromeos/scanning/scan_done_section_test.js +++ b/chrome/test/data/webui/chromeos/scanning/scan_done_section_test.js
@@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/scan_done_section.js'; import {ScanningBrowserProxyImpl} from 'chrome://scanning/scanning_browser_proxy.js'; -import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; - import {assertArrayEquals, assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {isVisible} from 'chrome://webui-test/chromeos/test_util.js'; +import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; import {TestScanningBrowserProxy} from './test_scanning_browser_proxy.js'; -export function scanDoneSectionTest() { +suite('scanDoneSectionTest', function() { /** @type {?ScanDoneSectionElement} */ let scanDoneSection = null; @@ -200,4 +200,4 @@ scanDoneSection.$$('#editButtonLabel').textContent.trim()); }); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/scan_preview_test.js b/chrome/test/data/webui/chromeos/scanning/scan_preview_test.js index 347a4ff..8326b2d 100644 --- a/chrome/test/data/webui/chromeos/scanning/scan_preview_test.js +++ b/chrome/test/data/webui/chromeos/scanning/scan_preview_test.js
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/scan_preview.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; @@ -9,11 +10,10 @@ import {setAccessibilityFeaturesForTesting} from 'chrome://scanning/mojo_interface_provider.js'; import {AppState} from 'chrome://scanning/scanning_app_types.js'; import {ScanningBrowserProxyImpl} from 'chrome://scanning/scanning_browser_proxy.js'; -import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; - import {assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {MockController} from 'chrome://webui-test/chromeos/mock_controller.m.js'; import {isVisible} from 'chrome://webui-test/chromeos/test_util.js'; +import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; import {FakeMediaQueryList} from './scanning_app_test_utils.js'; import {TestScanningBrowserProxy} from './test_scanning_browser_proxy.js'; @@ -47,7 +47,7 @@ } } -export function scanPreviewTest() { +suite('scanPreviewTest', function() { /** @type {?ScanPreviewElement} */ let scanPreview = null; @@ -459,4 +459,4 @@ await setFakePrefersColorSchemeDark(true); assertEquals(getReadyToScanSvg().src, darkModeSvg); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/scan_to_select_test.js b/chrome/test/data/webui/chromeos/scanning/scan_to_select_test.js index 274aa586..301db0b 100644 --- a/chrome/test/data/webui/chromeos/scanning/scan_to_select_test.js +++ b/chrome/test/data/webui/chromeos/scanning/scan_to_select_test.js
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/scan_to_select.js'; import {ScanningBrowserProxyImpl} from 'chrome://scanning/scanning_browser_proxy.js'; - import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {changeSelect} from './scanning_app_test_utils.js'; import {TestScanningBrowserProxy} from './test_scanning_browser_proxy.js'; -export function scanToSelectTest() { +suite('scanToSelectTest', function() { /** @type {?ScanToSelectElement} */ let scanToSelect = null; @@ -118,4 +118,4 @@ assertEquals(0, select.selectedIndex); }); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/scanner_select_test.js b/chrome/test/data/webui/chromeos/scanning/scanner_select_test.js index 1f1fd34d..cd076722 100644 --- a/chrome/test/data/webui/chromeos/scanning/scanner_select_test.js +++ b/chrome/test/data/webui/chromeos/scanning/scanner_select_test.js
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/scanner_select.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {ScannerArr, ScannerInfo} from 'chrome://scanning/scanning_app_types.js'; import {getScannerDisplayName, tokenToString} from 'chrome://scanning/scanning_app_util.js'; -import {waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; - import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; +import {waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; import {assertOrderedAlphabetically, createScanner} from './scanning_app_test_utils.js'; @@ -22,7 +22,7 @@ /** @type {!mojoBase.mojom.UnguessableToken} */ ({high: 0, low: 2}); const secondScannerName = 'Scanner 2'; -export function scannerSelectTest() { +suite('scannerSelectTest', function() { /** @type {?ScannerSelectElement} */ let scannerSelect = null; @@ -116,4 +116,4 @@ assertEquals(firstScannerIdString, scannerSelect.$$('select').value); }); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/scanning_app_browsertest.js b/chrome/test/data/webui/chromeos/scanning/scanning_app_browsertest.js index a178496..4070df7 100644 --- a/chrome/test/data/webui/chromeos/scanning/scanning_app_browsertest.js +++ b/chrome/test/data/webui/chromeos/scanning/scanning_app_browsertest.js
@@ -3,18 +3,12 @@ // found in the LICENSE file. /** - * @fileoverview Test suite for chrome://scanning. - * Unified polymer testing suite for scanning app. - * - * To run all tests in a single instance (default, faster): + * @fileoverview Test suite for chrome://scanning. Tests + * individual polymer components in isolation. To run all tests in a single + * instance (default, faster): * `browser_tests --gtest_filter=ScanningApp*` - * - * To run each test in a new instance: - * `browser_tests --run-manual --gtest_filter=ScanningAppBrowserTest.MANUAL_*` - * - * To run a single test suite, such as 'ScanApp': - * `browser_tests --run-manual - * --gtest_filter=ScanningAppBrowserTest.MANUAL_ScanApp` + * To run a single test suite such as 'ActionToolbar': + * browser_tests --gtest_filter=ScanningAppActionToolbar.All */ GEN_INCLUDE(['//chrome/test/data/webui/polymer_browser_test_base.js']); @@ -22,50 +16,42 @@ GEN('#include "ash/constants/ash_features.h"'); GEN('#include "content/public/test/browser_test.h"'); -/** - * @constructor - * @extends {PolymerTest} - */ -function ScanningAppBrowserTest() {} +this.ScanningAppBrowserTest = class extends PolymerTest {}; -ScanningAppBrowserTest.prototype = { - __proto__: PolymerTest.prototype, - browsePreload: 'chrome://scanning/test_loader.html?module=chromeos/' + - 'scanning/scanning_app_unified_test.js&host=test', -}; - -// List of names of suites in unified test to register for individual debugging. -// You must register all suites in unified test here as well for consistency, -// although technically is not necessary. -const debug_suites_list = [ - 'ActionToolbar', - 'ColorModeSelect', - 'FileTypeSelect', - 'LoadingPage', - 'MultiPageCheckbox', - 'MultiPageScan', - 'PageSizeSelect', - 'ResolutionSelect', - 'ScanApp', - 'ScanDoneSection', - 'ScannerSelect', - 'ScanPreview', - 'ScanToSelect', - 'SourceSelect', +const tests = [ + ['ActionToolbar', 'action_toolbar_test.js'], + ['ColorModeSelect', 'color_mode_select_test.js'], + ['FileTypeSelect', 'file_type_select_test.js'], + ['LoadingPage', 'loading_page_test.js'], + ['MultiPageCheckbox', 'multi_page_checkbox_test.js'], + ['MultiPageScan', 'multi_page_scan_test.js'], + ['PageSizeSelect', 'page_size_select_test.js'], + ['ResolutionSelect', 'resolution_select_test.js'], + ['ScanApp', 'scanning_app_test.js'], + ['ScanDoneSection', 'scan_done_section_test.js'], + ['ScannerSelect', 'scanner_select_test.js'], + ['ScanPreview', 'scan_preview_test.js'], + ['ScanToSelect', 'scan_to_select_test.js'], + ['SourceSelect', 'source_select_test.js'], ]; -// Flaky. See crbug.com/1334465 -TEST_F('ScanningAppBrowserTest', 'All', function() { - assertDeepEquals( - debug_suites_list, test_suites_list, - 'List of registered tests suites and debug suites do not match.\n' + - 'Did you forget to add your test in debug_suites_list?'); - mocha.run(); -}); -// Register each suite listed as individual tests for debugging purposes. -for (const suiteName of debug_suites_list) { - TEST_F('ScanningAppBrowserTest', `MANUAL_${suiteName}`, function() { - runMochaSuite(suiteName); - }); +tests.forEach(test => registerTest(...test)); + +/* + * Add a `caseName` to a specific test to disable it i.e. 'DISABLED_All' + * @param {string} testName + * @param {string} module + * @param {string} caseName + */ +function registerTest(testName, module, caseName) { + const className = `ScanningApp${testName}`; + this[className] = class extends ScanningAppBrowserTest { + /** @override */ + get browsePreload() { + return `chrome://scanning/test_loader.html` + + `?module=chromeos/scanning/${module}&host=test`; + } + }; + TEST_F(className, caseName || 'All', () => mocha.run()); }
diff --git a/chrome/test/data/webui/chromeos/scanning/scanning_app_test.js b/chrome/test/data/webui/chromeos/scanning/scanning_app_test.js index bc57e9d..5583e47 100644 --- a/chrome/test/data/webui/chromeos/scanning/scanning_app_test.js +++ b/chrome/test/data/webui/chromeos/scanning/scanning_app_test.js
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/scanning_app.js'; import 'chrome://resources/cr_elements/cr_button/cr_button.js'; -import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {PromiseResolver} from 'chrome://resources/ash/common/promise_resolver.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {setScanServiceForTesting} from 'chrome://scanning/mojo_interface_provider.js'; import {MAX_NUM_SAVED_SCANNERS, ScannerArr, ScannerSetting, ScanSettings, StartMultiPageScanResponse} from 'chrome://scanning/scanning_app_types.js'; import {getColorModeString, getPageSizeString, tokenToString} from 'chrome://scanning/scanning_app_util.js'; import {ScanningBrowserProxyImpl} from 'chrome://scanning/scanning_browser_proxy.js'; -import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; - import {assertArrayEquals, assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {isVisible} from 'chrome://webui-test/chromeos/test_util.js'; +import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; import {changeSelect, createScanner, createScannerSource} from './scanning_app_test_utils.js'; import {TestScanningBrowserProxy} from './test_scanning_browser_proxy.js'; @@ -405,7 +405,7 @@ } } -export function scanningAppTest() { +suite('scanningAppTest', function() { /** @type {?ScanningAppElement} */ let scanningApp = null; @@ -2613,4 +2613,4 @@ scanningApp.$$('#pageSizeSelect').$$('select').value); }); }); -} +});
diff --git a/chrome/test/data/webui/chromeos/scanning/scanning_app_test_utils.js b/chrome/test/data/webui/chromeos/scanning/scanning_app_test_utils.js index 8344f2469..a6919953 100644 --- a/chrome/test/data/webui/chromeos/scanning/scanning_app_test_utils.js +++ b/chrome/test/data/webui/chromeos/scanning/scanning_app_test_utils.js
@@ -1,10 +1,11 @@ // Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {alphabeticalCompare} from 'chrome://scanning/scanning_app_util.js'; -import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; +import './scanning_mojom_imports.js'; +import {alphabeticalCompare} from 'chrome://scanning/scanning_app_util.js'; import {assertEquals, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; +import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; /** * @param {!Array} arr
diff --git a/chrome/test/data/webui/chromeos/scanning/scanning_app_unified_test.js b/chrome/test/data/webui/chromeos/scanning/scanning_app_unified_test.js deleted file mode 100644 index 04e4e3c..0000000 --- a/chrome/test/data/webui/chromeos/scanning/scanning_app_unified_test.js +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2020 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// TODO(crbug/1004256): Use es6 module for mojo binding. -import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -import 'chrome://resources/mojo/mojo/public/mojom/base/big_buffer.mojom-lite.js'; -import 'chrome://resources/mojo/mojo/public/mojom/base/string16.mojom-lite.js'; -import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; -import 'chrome://scanning/file_path.mojom-lite.js'; -import 'chrome://scanning/scanning.mojom-lite.js'; - -import {actionToolbarTest} from './action_toolbar_test.js'; -import {colorModeSelectTest} from './color_mode_select_test.js'; -import {fileTypeSelectTest} from './file_type_select_test.js'; -import {loadingPageTest} from './loading_page_test.js'; -import {multiPageCheckboxTest} from './multi_page_checkbox_test.js'; -import {multiPageScanTest} from './multi_page_scan_test.js'; -import {pageSizeSelectTest} from './page_size_select_test.js'; -import {resolutionSelectTest} from './resolution_select_test.js'; -import {scanDoneSectionTest} from './scan_done_section_test.js'; -import {scanPreviewTest} from './scan_preview_test.js'; -import {scanToSelectTest} from './scan_to_select_test.js'; -import {scannerSelectTest} from './scanner_select_test.js'; -import {scanningAppTest} from './scanning_app_test.js'; -import {sourceSelectTest} from './source_select_test.js'; - -window.test_suites_list = []; - -function runSuite(suiteName, testFn) { - window.test_suites_list.push(suiteName); - suite(suiteName, testFn); -} - -runSuite('ActionToolbar', actionToolbarTest); -runSuite('ColorModeSelect', colorModeSelectTest); -runSuite('FileTypeSelect', fileTypeSelectTest); -runSuite('LoadingPage', loadingPageTest); -runSuite('MultiPageCheckbox', multiPageCheckboxTest); -runSuite('MultiPageScan', multiPageScanTest); -runSuite('PageSizeSelect', pageSizeSelectTest); -runSuite('ResolutionSelect', resolutionSelectTest); -runSuite('ScanApp', scanningAppTest); -runSuite('ScanDoneSection', scanDoneSectionTest); -runSuite('ScannerSelect', scannerSelectTest); -runSuite('ScanPreview', scanPreviewTest); -runSuite('ScanToSelect', scanToSelectTest); -runSuite('SourceSelect', sourceSelectTest);
diff --git a/chrome/test/data/webui/chromeos/scanning/scanning_mojom_imports.js b/chrome/test/data/webui/chromeos/scanning/scanning_mojom_imports.js new file mode 100644 index 0000000..7f04edc --- /dev/null +++ b/chrome/test/data/webui/chromeos/scanning/scanning_mojom_imports.js
@@ -0,0 +1,10 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; +import 'chrome://resources/mojo/mojo/public/mojom/base/big_buffer.mojom-lite.js'; +import 'chrome://resources/mojo/mojo/public/mojom/base/string16.mojom-lite.js'; +import 'chrome://resources/mojo/mojo/public/mojom/base/unguessable_token.mojom-lite.js'; +import 'chrome://scanning/file_path.mojom-lite.js'; +import 'chrome://scanning/scanning.mojom-lite.js';
diff --git a/chrome/test/data/webui/chromeos/scanning/source_select_test.js b/chrome/test/data/webui/chromeos/scanning/source_select_test.js index 123f78e..c36706a4 100644 --- a/chrome/test/data/webui/chromeos/scanning/source_select_test.js +++ b/chrome/test/data/webui/chromeos/scanning/source_select_test.js
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import './scanning_mojom_imports.js'; import 'chrome://scanning/source_select.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getSourceTypeString} from 'chrome://scanning/scanning_app_util.js'; - import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {assertOrderedAlphabetically, createScannerSource} from './scanning_app_test_utils.js'; @@ -40,7 +40,7 @@ [ColorMode.BLACK_AND_WHITE, ColorMode.GRAYSCALE, ColorMode.COLOR]; const resolutions = [75, 150, 300]; -export function sourceSelectTest() { +suite('sourceSelectTest', function() { /** @type {?SourceSelectElement} */ let sourceSelect = null; @@ -132,4 +132,4 @@ flush(); assertEquals(sourceSelect.selectedOption, sourceSelect.options[0].name); }); -} +});
diff --git a/chrome/test/data/webui/cr_components/help_bubble_mixin_test.ts b/chrome/test/data/webui/cr_components/help_bubble_mixin_test.ts index c4acca1..22cc67d6 100644 --- a/chrome/test/data/webui/cr_components/help_bubble_mixin_test.ts +++ b/chrome/test/data/webui/cr_components/help_bubble_mixin_test.ts
@@ -12,7 +12,7 @@ import {HelpBubbleMixin, HelpBubbleMixinInterface} from 'chrome://resources/cr_components/help_bubble/help_bubble_mixin.js'; import {HelpBubbleProxy, HelpBubbleProxyImpl} from 'chrome://resources/cr_components/help_bubble/help_bubble_proxy.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; +import {assertDeepEquals, assertEquals, assertFalse, assertThrows, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; import {TestBrowserProxy} from 'chrome://webui-test/test_browser_proxy.js'; import {isVisible} from 'chrome://webui-test/test_util.js'; @@ -21,6 +21,7 @@ const PARAGRAPH_NATIVE_ID: string = 'kHelpBubbleMixinTestParagraphElementId'; const LIST_NATIVE_ID: string = 'kHelpBubbleMixinTestListElementId'; const SPAN_NATIVE_ID: string = 'kHelpBubbleMixinTestSpanElementId'; +const LIST_ITEM_NATIVE_ID: string = 'kHelpBubbleMixinTestListItemElementId'; const EVENT1_NAME: string = 'kFirstExampleCustomEvent'; const EVENT2_NAME: string = 'kSecondExampleCustomEvent'; const CLOSE_BUTTON_ALT_TEXT: string = 'Close help bubble.'; @@ -56,7 +57,7 @@ <h1 id='title'>This is the title</h1> <p id='p1'>Some paragraph text</p> <ul id='bulletList'> - <li>List item 1</li> + <li id='list-item'>List item 1</li> <li>List item 2</li> </ul> <span>Span text</span> @@ -69,10 +70,10 @@ const spanEl = this.shadowRoot!.querySelector('span'); assertTrue(spanEl !== null, 'connectedCallback: span element exists'); - titleBubble = this.registerHelpBubble(TITLE_NATIVE_ID, '#title'); - p1Bubble = this.registerHelpBubble(PARAGRAPH_NATIVE_ID, '#p1'); - bulletListBubble = this.registerHelpBubble(LIST_NATIVE_ID, '#bulletList'); - spanBubble = this.registerHelpBubble(SPAN_NATIVE_ID, spanEl); + titleBubble = this.registerHelpBubble(TITLE_NATIVE_ID, '#title')!; + p1Bubble = this.registerHelpBubble(PARAGRAPH_NATIVE_ID, '#p1')!; + bulletListBubble = this.registerHelpBubble(LIST_NATIVE_ID, '#bulletList')!; + spanBubble = this.registerHelpBubble(SPAN_NATIVE_ID, spanEl)!; } } @@ -737,4 +738,65 @@ 'helpBubbleClosed is called with correct arguments'); assertFalse(container.isHelpBubbleShowing(), 'no bubbles are showing'); }); + + test('help bubble mixin can unregister', () => { + let listItemBubble = + container.registerHelpBubble(LIST_ITEM_NATIVE_ID, '#bulletList'); + assertTrue(listItemBubble !== null, 'help bubble is registered'); + assertTrue( + container.canShowHelpBubble(listItemBubble!), + 'help bubble can be shown'); + + // re-register when help bubble is not showing + listItemBubble = + container.registerHelpBubble(LIST_ITEM_NATIVE_ID, '#list-item'); + assertTrue( + listItemBubble !== null, + 'help bubble can be re-registered with same nativeId'); + assertTrue( + container.canShowHelpBubble(listItemBubble!), + 'help bubble can be shown after re-registering'); + + // un-register directly when help bubble is not showing + container.unregisterHelpBubble(LIST_ITEM_NATIVE_ID); + assertFalse( + container.canShowHelpBubble(listItemBubble!), + 'help bubble cannot be shown'); + // unregisterHelpBubble clears out the nativeIds + assertThrows( + () => container.showHelpBubble(listItemBubble!, defaultParams), + 'Can\'t show help bubble', + ); + }); + + test('help bubble mixin can unregister when bubble is showing', () => { + const listItemBubble = + container.registerHelpBubble(LIST_ITEM_NATIVE_ID, '#list-item'); + assertTrue(listItemBubble !== null, 'help bubble is registered'); + assertTrue( + container.canShowHelpBubble(listItemBubble!), + 'help bubble can be shown'); + assertFalse(container.isHelpBubbleShowing()); + assertFalse(container.isHelpBubbleShowingForTesting('list-item')); + + container.showHelpBubble(listItemBubble!, defaultParams); + assertTrue(container.isHelpBubbleShowing()); + assertTrue(container.isHelpBubbleShowingForTesting('list-item')); + + // re-register when help bubble is shown + const result = + container.registerHelpBubble(LIST_ITEM_NATIVE_ID, '#list-item'); + assertTrue( + result === null, 'registerHelpBubble fails when help bubble is shown'); + assertTrue( + container.isHelpBubbleShowing(), + 're-registering does not hide help bubble'); + assertTrue(container.isHelpBubbleShowingForTesting('list-item')); + + // unregister directly when help bubble is shown + container.unregisterHelpBubble(LIST_ITEM_NATIVE_ID); + assertFalse( + container.isHelpBubbleShowing(), 'unregister hides help bubble'); + assertFalse(container.isHelpBubbleShowingForTesting('list-item')); + }); });
diff --git a/chromecast/common/cast_resource_delegate.cc b/chromecast/common/cast_resource_delegate.cc index 1d083a3..e065a14 100644 --- a/chromecast/common/cast_resource_delegate.cc +++ b/chromecast/common/cast_resource_delegate.cc
@@ -4,6 +4,8 @@ #include "chromecast/common/cast_resource_delegate.h" +#include <ostream> + #include "base/files/file_path.h" #include "base/notreached.h" #include "base/path_service.h"
diff --git a/chromeos/ash/components/local_search_service/inverted_index_search.cc b/chromeos/ash/components/local_search_service/inverted_index_search.cc index 864ef3a..cae5e997b 100644 --- a/chromeos/ash/components/local_search_service/inverted_index_search.cc +++ b/chromeos/ash/components/local_search_service/inverted_index_search.cc
@@ -13,7 +13,6 @@ #include "base/i18n/rtl.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/time/time.h" @@ -99,9 +98,8 @@ AddOrUpdateCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!data.empty()); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, - base::BindOnce(&ExtractDocumentsContent, data), + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ExtractDocumentsContent, data), base::BindOnce( &InvertedIndexSearch::FinalizeAddOrUpdate, weak_ptr_factory_.GetWeakPtr(), @@ -128,9 +126,8 @@ UpdateDocumentsCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!data.empty()); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, - base::BindOnce(&ExtractDocumentsContent, data), + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ExtractDocumentsContent, data), base::BindOnce( &InvertedIndexSearch::FinalizeUpdateDocuments, weak_ptr_factory_.GetWeakPtr(),
diff --git a/chromeos/ash/components/network/hotspot_state_handler_unittest.cc b/chromeos/ash/components/network/hotspot_state_handler_unittest.cc index f7e5532..ca9c066 100644 --- a/chromeos/ash/components/network/hotspot_state_handler_unittest.cc +++ b/chromeos/ash/components/network/hotspot_state_handler_unittest.cc
@@ -193,7 +193,7 @@ base::Value(shill::kTetheringStateFailure)); status_dict.GetDict().Set( shill::kTetheringStatusErrorProperty, - base::Value(shill::kTetheringErrorUpstreamNotReady)); + base::Value(shill::kTetheringEnableResultUpstreamNotAvailable)); network_state_test_helper_.manager_test()->SetManagerProperty( shill::kTetheringStatusProperty, status_dict); base::RunLoop().RunUntilIdle(); @@ -202,7 +202,7 @@ hotspot_config::mojom::HotspotState::kDisabled); EXPECT_EQ(4u, observer_.hotspot_status_changed_count()); EXPECT_EQ(1u, observer_.hotspot_state_failed_count()); - EXPECT_EQ(shill::kTetheringErrorUpstreamNotReady, + EXPECT_EQ(shill::kTetheringEnableResultUpstreamNotAvailable, observer_.last_hotspot_failed_error()); // Verify the edge case where the state is failure but error is not provided.
diff --git a/chromeos/ash/components/network/onc/onc_certificate_importer_impl.cc b/chromeos/ash/components/network/onc/onc_certificate_importer_impl.cc index 48b8de45..0bd7627 100644 --- a/chromeos/ash/components/network/onc/onc_certificate_importer_impl.cc +++ b/chromeos/ash/components/network/onc/onc_certificate_importer_impl.cc
@@ -17,7 +17,6 @@ #include "base/logging.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" @@ -79,9 +78,8 @@ weak_factory_.GetWeakPtr(), std::move(done_callback)); // The NSSCertDatabase must be accessed on |io_task_runner_| - base::PostTaskAndReplyWithResult(io_task_runner_.get(), FROM_HERE, - std::move(task), - std::move(callback_to_this)); + io_task_runner_->PostTaskAndReplyWithResult(FROM_HERE, std::move(task), + std::move(callback_to_this)); } void CertificateImporterImpl::RunDoneCallback(DoneCallback callback,
diff --git a/chromeos/ash/services/device_sync/cryptauth_key.cc b/chromeos/ash/services/device_sync/cryptauth_key.cc index 537ad865..9cc14e1 100644 --- a/chromeos/ash/services/device_sync/cryptauth_key.cc +++ b/chromeos/ash/services/device_sync/cryptauth_key.cc
@@ -44,27 +44,28 @@ // static absl::optional<CryptAuthKey> CryptAuthKey::FromDictionary( - const base::Value& dict) { - if (!dict.is_dict()) + const base::Value& value) { + if (!value.is_dict()) return absl::nullopt; - absl::optional<int> opt_status = dict.FindIntKey(kStatusDictKey); + const base::Value::Dict& dict = value.GetDict(); + absl::optional<int> opt_status = dict.FindInt(kStatusDictKey); if (!opt_status) return absl::nullopt; CryptAuthKey::Status status = static_cast<CryptAuthKey::Status>(*opt_status); - absl::optional<int> opt_type = dict.FindIntKey(kTypeDictKey); + absl::optional<int> opt_type = dict.FindInt(kTypeDictKey); if (!opt_type || !cryptauthv2::KeyType_IsValid(*opt_type)) return absl::nullopt; cryptauthv2::KeyType type = static_cast<cryptauthv2::KeyType>(*opt_type); - const std::string* handle = dict.FindStringKey(kHandleDictKey); + const std::string* handle = dict.FindString(kHandleDictKey); if (!handle || handle->empty()) return absl::nullopt; if (IsSymmetricKeyType(type)) { absl::optional<std::string> symmetric_key = - util::DecodeFromValueString(dict.FindKey(kSymmetricKeyDictKey)); + util::DecodeFromValueString(dict.Find(kSymmetricKeyDictKey)); if (!symmetric_key || symmetric_key->empty()) return absl::nullopt; @@ -74,9 +75,9 @@ DCHECK(IsAsymmetricKeyType(type)); absl::optional<std::string> public_key = - util::DecodeFromValueString(dict.FindKey(kPublicKeyDictKey)); + util::DecodeFromValueString(dict.Find(kPublicKeyDictKey)); absl::optional<std::string> private_key = - util::DecodeFromValueString(dict.FindKey(kPrivateKeyDictKey)); + util::DecodeFromValueString(dict.Find(kPrivateKeyDictKey)); if (!public_key || !private_key || public_key->empty()) { return absl::nullopt; } @@ -124,27 +125,27 @@ return IsAsymmetricKeyType(type_); } -base::Value CryptAuthKey::AsSymmetricKeyDictionary() const { +base::Value::Dict CryptAuthKey::AsSymmetricKeyDictionary() const { DCHECK(IsSymmetricKey()); - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey(kHandleDictKey, base::Value(handle_)); - dict.SetKey(kStatusDictKey, base::Value(status_)); - dict.SetKey(kTypeDictKey, base::Value(type_)); - dict.SetKey(kSymmetricKeyDictKey, util::EncodeAsValueString(symmetric_key_)); + base::Value::Dict dict; + dict.Set(kHandleDictKey, handle_); + dict.Set(kStatusDictKey, status_); + dict.Set(kTypeDictKey, type_); + dict.Set(kSymmetricKeyDictKey, util::EncodeAsValueString(symmetric_key_)); return dict; } -base::Value CryptAuthKey::AsAsymmetricKeyDictionary() const { +base::Value::Dict CryptAuthKey::AsAsymmetricKeyDictionary() const { DCHECK(IsAsymmetricKey()); - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey(kHandleDictKey, base::Value(handle_)); - dict.SetKey(kStatusDictKey, base::Value(status_)); - dict.SetKey(kTypeDictKey, base::Value(type_)); - dict.SetKey(kPublicKeyDictKey, util::EncodeAsValueString(public_key_)); - dict.SetKey(kPrivateKeyDictKey, util::EncodeAsValueString(private_key_)); + base::Value::Dict dict; + dict.Set(kHandleDictKey, handle_); + dict.Set(kStatusDictKey, status_); + dict.Set(kTypeDictKey, type_); + dict.Set(kPublicKeyDictKey, util::EncodeAsValueString(public_key_)); + dict.Set(kPrivateKeyDictKey, util::EncodeAsValueString(private_key_)); return dict; }
diff --git a/chromeos/ash/services/device_sync/cryptauth_key.h b/chromeos/ash/services/device_sync/cryptauth_key.h index f3286df..38dc148b 100644 --- a/chromeos/ash/services/device_sync/cryptauth_key.h +++ b/chromeos/ash/services/device_sync/cryptauth_key.h
@@ -26,7 +26,7 @@ // this status is meaningless. enum Status { kActive, kInactive }; - static absl::optional<CryptAuthKey> FromDictionary(const base::Value& dict); + static absl::optional<CryptAuthKey> FromDictionary(const base::Value& value); // Constructor for symmetric keys. CryptAuthKey(const std::string& symmetric_key, @@ -67,16 +67,16 @@ void set_status(Status status) { status_ = status; } - // Converts CryptAuthKey to a dictionary-type Value of the form + // Converts CryptAuthKey to a Value::Dict of the form // { // "handle": <handle_> // "status": <status_ as int> // "symmetric_key": <symmetric_key_> // "type": <type_ as int> // } - base::Value AsSymmetricKeyDictionary() const; + base::Value::Dict AsSymmetricKeyDictionary() const; - // Converts CryptAuthKey to a dictionary-type Value of the form + // Converts CryptAuthKey to a Value::Dict of the form // { // "handle": <handle_> // "private_key" : <private_key_> @@ -84,7 +84,7 @@ // "status": <status_ as int> // "type": <type_ as int> // } - base::Value AsAsymmetricKeyDictionary() const; + base::Value::Dict AsAsymmetricKeyDictionary() const; bool operator==(const CryptAuthKey& other) const; bool operator!=(const CryptAuthKey& other) const;
diff --git a/chromeos/ash/services/device_sync/cryptauth_key_bundle.cc b/chromeos/ash/services/device_sync/cryptauth_key_bundle.cc index 1248c1a..8242ac4 100644 --- a/chromeos/ash/services/device_sync/cryptauth_key_bundle.cc +++ b/chromeos/ash/services/device_sync/cryptauth_key_bundle.cc
@@ -77,11 +77,8 @@ // static absl::optional<CryptAuthKeyBundle> CryptAuthKeyBundle::FromDictionary( - const base::Value& dict) { - if (!dict.is_dict()) - return absl::nullopt; - - const std::string* name_string = dict.FindStringKey(kBundleNameDictKey); + const base::Value::Dict& dict) { + const std::string* name_string = dict.FindString(kBundleNameDictKey); if (!name_string) return absl::nullopt; @@ -92,12 +89,12 @@ CryptAuthKeyBundle bundle(*name); - const base::Value* keys = dict.FindKey(kKeyListDictKey); - if (!keys || !keys->is_list()) + const base::Value::List* keys = dict.FindList(kKeyListDictKey); + if (!keys) return absl::nullopt; bool active_key_exists = false; - for (const base::Value& key_dict : keys->GetListDeprecated()) { + for (const base::Value& key_dict : *keys) { absl::optional<CryptAuthKey> key = CryptAuthKey::FromDictionary(key_dict); if (!key) return absl::nullopt; @@ -118,7 +115,7 @@ } const base::Value* encoded_serialized_key_directive = - dict.FindKey(kKeyDirectiveDictKey); + dict.Find(kKeyDirectiveDictKey); if (encoded_serialized_key_directive) { absl::optional<cryptauthv2::KeyDirective> key_directive = util::DecodeProtoMessageFromValueString<cryptauthv2::KeyDirective>(
diff --git a/chromeos/ash/services/device_sync/cryptauth_key_bundle.h b/chromeos/ash/services/device_sync/cryptauth_key_bundle.h index 7a5a2b1..b674b1f 100644 --- a/chromeos/ash/services/device_sync/cryptauth_key_bundle.h +++ b/chromeos/ash/services/device_sync/cryptauth_key_bundle.h
@@ -60,7 +60,7 @@ const std::string& name); static absl::optional<CryptAuthKeyBundle> FromDictionary( - const base::Value& dict); + const base::Value::Dict& dict); CryptAuthKeyBundle(Name name);
diff --git a/chromeos/ash/services/device_sync/cryptauth_key_bundle_unittest.cc b/chromeos/ash/services/device_sync/cryptauth_key_bundle_unittest.cc index 91e491d..0516659 100644 --- a/chromeos/ash/services/device_sync/cryptauth_key_bundle_unittest.cc +++ b/chromeos/ash/services/device_sync/cryptauth_key_bundle_unittest.cc
@@ -234,7 +234,7 @@ TEST(DeviceSyncCryptAuthKeyBundleTest, ToAndFromDictionary_Trivial) { CryptAuthKeyBundle bundle(CryptAuthKeyBundle::Name::kLegacyAuthzenKey); absl::optional<CryptAuthKeyBundle> bundle_from_dict = - CryptAuthKeyBundle::FromDictionary(bundle.AsDictionary()); + CryptAuthKeyBundle::FromDictionary(bundle.AsDictionary().GetDict()); ASSERT_TRUE(bundle_from_dict); EXPECT_EQ(*bundle_from_dict, bundle); } @@ -259,7 +259,7 @@ bundle.set_key_directive(key_directive); absl::optional<CryptAuthKeyBundle> bundle_from_dict = - CryptAuthKeyBundle::FromDictionary(bundle.AsDictionary()); + CryptAuthKeyBundle::FromDictionary(bundle.AsDictionary().GetDict()); ASSERT_TRUE(bundle_from_dict); EXPECT_EQ(*bundle_from_dict, bundle); }
diff --git a/chromeos/ash/services/device_sync/cryptauth_key_registry_impl.cc b/chromeos/ash/services/device_sync/cryptauth_key_registry_impl.cc index c1cec17..0c73303e 100644 --- a/chromeos/ash/services/device_sync/cryptauth_key_registry_impl.cc +++ b/chromeos/ash/services/device_sync/cryptauth_key_registry_impl.cc
@@ -48,7 +48,7 @@ for (const CryptAuthKeyBundle::Name& name : CryptAuthKeyBundle::AllNames()) { std::string name_string = CryptAuthKeyBundle::KeyBundleNameEnumToString(name); - const base::Value* bundle_dict = dict.Find(name_string); + const base::Value::Dict* bundle_dict = dict.FindDict(name_string); if (!bundle_dict) continue;
diff --git a/chromeos/ash/services/device_sync/cryptauth_key_unittest.cc b/chromeos/ash/services/device_sync/cryptauth_key_unittest.cc index bc803f6..7b22ba14 100644 --- a/chromeos/ash/services/device_sync/cryptauth_key_unittest.cc +++ b/chromeos/ash/services/device_sync/cryptauth_key_unittest.cc
@@ -63,11 +63,11 @@ CryptAuthKey symmetric_key(kFakeSymmetricKey, CryptAuthKey::Status::kActive, cryptauthv2::KeyType::RAW256, kFakeHandle); - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("handle", base::Value(kFakeHandle)); - dict.SetKey("status", base::Value(CryptAuthKey::Status::kActive)); - dict.SetKey("type", base::Value(cryptauthv2::KeyType::RAW256)); - dict.SetKey("symmetric_key", util::EncodeAsValueString(kFakeSymmetricKey)); + base::Value::Dict dict; + dict.Set("handle", kFakeHandle); + dict.Set("status", CryptAuthKey::Status::kActive); + dict.Set("type", cryptauthv2::KeyType::RAW256); + dict.Set("symmetric_key", util::EncodeAsValueString(kFakeSymmetricKey)); EXPECT_EQ(symmetric_key.AsSymmetricKeyDictionary(), dict); } @@ -77,38 +77,40 @@ CryptAuthKey::Status::kActive, cryptauthv2::KeyType::P256, kFakeHandle); - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("handle", base::Value(kFakeHandle)); - dict.SetKey("status", base::Value(CryptAuthKey::Status::kActive)); - dict.SetKey("type", base::Value(cryptauthv2::KeyType::P256)); - dict.SetKey("public_key", util::EncodeAsValueString(kFakePublicKey)); - dict.SetKey("private_key", util::EncodeAsValueString(kFakePrivateKey)); + base::Value::Dict dict; + dict.Set("handle", kFakeHandle); + dict.Set("status", CryptAuthKey::Status::kActive); + dict.Set("type", cryptauthv2::KeyType::P256); + dict.Set("public_key", util::EncodeAsValueString(kFakePublicKey)); + dict.Set("private_key", util::EncodeAsValueString(kFakePrivateKey)); EXPECT_EQ(asymmetric_key.AsAsymmetricKeyDictionary(), dict); } TEST(DeviceSyncCryptAuthKeyTest, SymmetricKeyFromDictionary) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("handle", base::Value(kFakeHandle)); - dict.SetKey("status", base::Value(CryptAuthKey::Status::kActive)); - dict.SetKey("type", base::Value(cryptauthv2::KeyType::RAW256)); - dict.SetKey("symmetric_key", util::EncodeAsValueString(kFakeSymmetricKey)); + base::Value::Dict dict; + dict.Set("handle", kFakeHandle); + dict.Set("status", CryptAuthKey::Status::kActive); + dict.Set("type", cryptauthv2::KeyType::RAW256); + dict.Set("symmetric_key", util::EncodeAsValueString(kFakeSymmetricKey)); - absl::optional<CryptAuthKey> key = CryptAuthKey::FromDictionary(dict); + absl::optional<CryptAuthKey> key = + CryptAuthKey::FromDictionary(base::Value(std::move(dict))); ASSERT_TRUE(key); EXPECT_EQ(*key, CryptAuthKey(kFakeSymmetricKey, CryptAuthKey::Status::kActive, cryptauthv2::KeyType::RAW256, kFakeHandle)); } TEST(DeviceSyncCryptAuthKeyTest, AsymmetricKeyFromDictionary) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("handle", base::Value(kFakeHandle)); - dict.SetKey("status", base::Value(CryptAuthKey::Status::kActive)); - dict.SetKey("type", base::Value(cryptauthv2::KeyType::P256)); - dict.SetKey("public_key", util::EncodeAsValueString(kFakePublicKey)); - dict.SetKey("private_key", util::EncodeAsValueString(kFakePrivateKey)); + base::Value::Dict dict; + dict.Set("handle", kFakeHandle); + dict.Set("status", CryptAuthKey::Status::kActive); + dict.Set("type", cryptauthv2::KeyType::P256); + dict.Set("public_key", util::EncodeAsValueString(kFakePublicKey)); + dict.Set("private_key", util::EncodeAsValueString(kFakePrivateKey)); - absl::optional<CryptAuthKey> key = CryptAuthKey::FromDictionary(dict); + absl::optional<CryptAuthKey> key = + CryptAuthKey::FromDictionary(base::Value(std::move(dict))); ASSERT_TRUE(key); EXPECT_EQ(*key, CryptAuthKey(kFakePublicKey, kFakePrivateKey, CryptAuthKey::Status::kActive, @@ -116,61 +118,61 @@ } TEST(DeviceSyncCryptAuthKeyTest, KeyFromDictionary_MissingHandle) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("status", base::Value(CryptAuthKey::Status::kActive)); - dict.SetKey("type", base::Value(cryptauthv2::KeyType::RAW256)); - dict.SetKey("symmetric_key", base::Value(kFakeSymmetricKey)); + base::Value::Dict dict; + dict.Set("status", CryptAuthKey::Status::kActive); + dict.Set("type", cryptauthv2::KeyType::RAW256); + dict.Set("symmetric_key", kFakeSymmetricKey); - EXPECT_FALSE(CryptAuthKey::FromDictionary(dict)); + EXPECT_FALSE(CryptAuthKey::FromDictionary(base::Value(std::move(dict)))); } TEST(DeviceSyncCryptAuthKeyTest, KeyFromDictionary_MissingStatus) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("handle", base::Value(kFakeHandle)); - dict.SetKey("type", base::Value(cryptauthv2::KeyType::RAW256)); - dict.SetKey("symmetric_key", base::Value(kFakeSymmetricKey)); + base::Value::Dict dict; + dict.Set("handle", kFakeHandle); + dict.Set("type", cryptauthv2::KeyType::RAW256); + dict.Set("symmetric_key", kFakeSymmetricKey); - EXPECT_FALSE(CryptAuthKey::FromDictionary(dict)); + EXPECT_FALSE(CryptAuthKey::FromDictionary(base::Value(std::move(dict)))); } TEST(DeviceSyncCryptAuthKeyTest, KeyFromDictionary_MissingType) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("handle", base::Value(kFakeHandle)); - dict.SetKey("status", base::Value(CryptAuthKey::Status::kActive)); - dict.SetKey("symmetric_key", base::Value(kFakeSymmetricKey)); + base::Value::Dict dict; + dict.Set("handle", kFakeHandle); + dict.Set("status", CryptAuthKey::Status::kActive); + dict.Set("symmetric_key", kFakeSymmetricKey); - EXPECT_FALSE(CryptAuthKey::FromDictionary(dict)); + EXPECT_FALSE(CryptAuthKey::FromDictionary(base::Value(std::move(dict)))); } TEST(DeviceSyncCryptAuthKeyTest, SymmetricKeyFromDictionary_MissingSymmetricKey) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("handle", base::Value(kFakeHandle)); - dict.SetKey("status", base::Value(CryptAuthKey::Status::kActive)); - dict.SetKey("type", base::Value(cryptauthv2::KeyType::RAW256)); + base::Value::Dict dict; + dict.Set("handle", kFakeHandle); + dict.Set("status", CryptAuthKey::Status::kActive); + dict.Set("type", cryptauthv2::KeyType::RAW256); - EXPECT_FALSE(CryptAuthKey::FromDictionary(dict)); + EXPECT_FALSE(CryptAuthKey::FromDictionary(base::Value(std::move(dict)))); } TEST(DeviceSyncCryptAuthKeyTest, AsymmetricKeyFromDictionary_MissingPublicKey) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("handle", base::Value(kFakeHandle)); - dict.SetKey("status", base::Value(CryptAuthKey::Status::kActive)); - dict.SetKey("type", base::Value(cryptauthv2::KeyType::P256)); - dict.SetKey("private_key", base::Value(kFakePrivateKey)); + base::Value::Dict dict; + dict.Set("handle", kFakeHandle); + dict.Set("status", CryptAuthKey::Status::kActive); + dict.Set("type", cryptauthv2::KeyType::P256); + dict.Set("private_key", kFakePrivateKey); - EXPECT_FALSE(CryptAuthKey::FromDictionary(dict)); + EXPECT_FALSE(CryptAuthKey::FromDictionary(base::Value(std::move(dict)))); } TEST(DeviceSyncCryptAuthKeyTest, AsymmetricKeyFromDictionary_MissingPrivateKey) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("handle", base::Value(kFakeHandle)); - dict.SetKey("status", base::Value(CryptAuthKey::Status::kActive)); - dict.SetKey("type", base::Value(cryptauthv2::KeyType::P256)); - dict.SetKey("public_key", base::Value(kFakePublicKey)); + base::Value::Dict dict; + dict.Set("handle", kFakeHandle); + dict.Set("status", CryptAuthKey::Status::kActive); + dict.Set("type", cryptauthv2::KeyType::P256); + dict.Set("public_key", kFakePublicKey); - EXPECT_FALSE(CryptAuthKey::FromDictionary(dict)); + EXPECT_FALSE(CryptAuthKey::FromDictionary(base::Value(std::move(dict)))); } TEST(DeviceSyncCryptAuthKeyTest, Equality) {
diff --git a/chromeos/ash/services/hotspot_config/cros_hotspot_config_unittest.cc b/chromeos/ash/services/hotspot_config/cros_hotspot_config_unittest.cc index a345038..44a1f67f 100644 --- a/chromeos/ash/services/hotspot_config/cros_hotspot_config_unittest.cc +++ b/chromeos/ash/services/hotspot_config/cros_hotspot_config_unittest.cc
@@ -237,7 +237,7 @@ base::Value(shill::kTetheringStateFailure)); status_dict.GetDict().Set( shill::kTetheringStatusErrorProperty, - base::Value(shill::kTetheringErrorUpstreamNotReady)); + base::Value(shill::kTetheringEnableResultUpstreamNotAvailable)); helper()->manager_test()->SetManagerProperty(shill::kTetheringStatusProperty, status_dict); base::RunLoop().RunUntilIdle(); @@ -245,7 +245,7 @@ EXPECT_EQ(GetHotspotInfo()->state, mojom::HotspotState::kDisabled); EXPECT_EQ(observer()->hotspot_info_changed_count(), 6u); EXPECT_EQ(observer()->hotspot_state_failed_count(), 1u); - EXPECT_EQ(shill::kTetheringErrorUpstreamNotReady, + EXPECT_EQ(shill::kTetheringEnableResultUpstreamNotAvailable, observer()->last_hotspot_failed_error()); }
diff --git a/chromeos/components/quick_answers/utils/spell_check_language.cc b/chromeos/components/quick_answers/utils/spell_check_language.cc index 5a35a5d..1d3f4a7 100644 --- a/chromeos/components/quick_answers/utils/spell_check_language.cc +++ b/chromeos/components/quick_answers/utils/spell_check_language.cc
@@ -7,7 +7,6 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/path_service.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" @@ -99,9 +98,8 @@ language_ = language; dictionary_file_path_ = GetDictionaryFilePath(language); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(&base::PathExists, dictionary_file_path_), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&base::PathExists, dictionary_file_path_), base::BindOnce(&SpellCheckLanguage::OnPathExistsComplete, weak_factory_.GetWeakPtr())); } @@ -124,9 +122,8 @@ .Pass()); } - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(&OpenDictionaryFile, dictionary_file_path_), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&OpenDictionaryFile, dictionary_file_path_), base::BindOnce(&SpellCheckLanguage::OnOpenDictionaryFileComplete, weak_factory_.GetWeakPtr())); } @@ -142,8 +139,8 @@ return; } - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&base::ReplaceFile, tmp_path, dictionary_file_path_, nullptr), base::BindOnce(&SpellCheckLanguage::OnSaveDictionaryDataComplete,
diff --git a/chromeos/printing/ppd_cache.cc b/chromeos/printing/ppd_cache.cc index 916ba33b..79c73f8 100644 --- a/chromeos/printing/ppd_cache.cc +++ b/chromeos/printing/ppd_cache.cc
@@ -14,7 +14,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/synchronization/lock.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" @@ -144,9 +143,9 @@ // Public API functions. void Find(const std::string& key, FindCallback cb) override { - base::PostTaskAndReplyWithResult( - fetch_task_runner_.get(), FROM_HERE, - base::BindOnce(&FindImpl, cache_base_dir_, key), std::move(cb)); + fetch_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FindImpl, cache_base_dir_, key), + std::move(cb)); } // Store the given contents at the given key. If cb is non-null, it will
diff --git a/chromeos/profiles/bigcore.afdo.newest.txt b/chromeos/profiles/bigcore.afdo.newest.txt index 0879270..c1cea2b 100644 --- a/chromeos/profiles/bigcore.afdo.newest.txt +++ b/chromeos/profiles/bigcore.afdo.newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-bigcore-109-5412.2-1669029745-benchmark-109.0.5414.17-r1-redacted.afdo.xz +chromeos-chrome-amd64-bigcore-110-5391.0-1668430627-benchmark-110.0.5419.0-r1-redacted.afdo.xz
diff --git a/components/assist_ranker/ranker_model_loader_impl.cc b/components/assist_ranker/ranker_model_loader_impl.cc index 82fdaf0..816710f 100644 --- a/components/assist_ranker/ranker_model_loader_impl.cc +++ b/components/assist_ranker/ranker_model_loader_impl.cc
@@ -16,7 +16,6 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/sequenced_task_runner_handle.h" #include "components/assist_ranker/proto/ranker_model.pb.h" @@ -144,9 +143,8 @@ DCHECK(!model_path_.empty()); state_ = LoaderState::LOADING_FROM_FILE; load_start_time_ = base::TimeTicks::Now(); - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(&LoadFromFile, model_path_), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadFromFile, model_path_), base::BindOnce(&RankerModelLoaderImpl::OnFileLoaded, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/components/attribution_reporting/suitable_origin.cc b/components/attribution_reporting/suitable_origin.cc index c04ba130..94aad17 100644 --- a/components/attribution_reporting/suitable_origin.cc +++ b/components/attribution_reporting/suitable_origin.cc
@@ -13,12 +13,15 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" #include "url/origin.h" +#include "url/url_constants.h" namespace attribution_reporting { // static bool SuitableOrigin::IsSuitable(const url::Origin& origin) { - return network::IsOriginPotentiallyTrustworthy(origin); + const std::string& scheme = origin.scheme(); + return (scheme == url::kHttpScheme || scheme == url::kHttpsScheme) && + network::IsOriginPotentiallyTrustworthy(origin); } // static
diff --git a/components/attribution_reporting/suitable_origin.h b/components/attribution_reporting/suitable_origin.h index 3d13c08..d352e50f 100644 --- a/components/attribution_reporting/suitable_origin.h +++ b/components/attribution_reporting/suitable_origin.h
@@ -27,10 +27,8 @@ // origin. // // These origins must be potentially trustworthy, as determined by -// `network::IsOriginPotentiallyTrustworthy()`. -// -// In the future, this type will also enforce the use of HTTP or HTTPS as the -// origin's scheme (crbug.com/1351086). +// `network::IsOriginPotentiallyTrustworthy()`, and their scheme must be HTTP or +// HTTPS. // // It is an error to use instances of this type after moving. class COMPONENT_EXPORT(ATTRIBUTION_REPORTING) SuitableOrigin {
diff --git a/components/attribution_reporting/suitable_origin_unittest.cc b/components/attribution_reporting/suitable_origin_unittest.cc index 2d9b4ab..e1133ea 100644 --- a/components/attribution_reporting/suitable_origin_unittest.cc +++ b/components/attribution_reporting/suitable_origin_unittest.cc
@@ -34,6 +34,14 @@ url::Origin::Create(GURL("http://localhost")), true, }, + { + url::Origin::Create(GURL("ws://a.test")), + false, + }, + { + url::Origin::Create(GURL("wss://a.test")), + false, + }, }; for (const auto& test_case : kTestCases) { @@ -85,6 +93,16 @@ url::Origin::Create(GURL("https://a.test")), "https://a.test", }, + { + "ws://a.test", + absl::nullopt, + nullptr, + }, + { + "wss://a.test", + absl::nullopt, + nullptr, + }, }; for (const auto& test_case : kTestCases) {
diff --git a/components/autofill/README b/components/autofill/README deleted file mode 100644 index 44be6bf..0000000 --- a/components/autofill/README +++ /dev/null
@@ -1,23 +0,0 @@ -Autofill is in the process of becoming a layered component -(https://sites.google.com/a/chromium.org/dev/developers/design-documents/layered-components-design) -to enable it to be shared cleanly on iOS. - -When this process is complete, this component will have the following structure: - -- core/: shared code that does not depend on src/content/ or src/ios/ - - browser/: Browser process code - - common/: Code shared by the browser and the renderer -- content/: Driver for the shared code based on the content layer. - - browser/: Browser process code. - - renderer/: Renderer process code. - - common/: Code shared by the browser and the renderer. -- ios/: Driver for the shared code based on src/ios. - -See -https://sites.google.com/a/chromium.org/dev/developers/design-documents/layered-components-technical-approach/making-autofill-into-a-layered-component -for an outline of the project. - -For pointers on how to continue getting your work done as the component moves -into its new structure, see -https://sites.google.com/a/chromium.org/dev/developers/design-documents/layered-components-technical-approach/making-autofill-into-a-layered-component#TOC-Help-How-Do-I-Get-My-Autofill-Related-Work-Done- -
diff --git a/components/autofill/README.md b/components/autofill/README.md new file mode 100644 index 0000000..63a5a56 --- /dev/null +++ b/components/autofill/README.md
@@ -0,0 +1,146 @@ +# Autofill + +Autofill is a [layered +component](https://sites.google.com/a/chromium.org/dev/developers/design-documents/layered-components-design). +It has the following structure: + +- [`core/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core): Code shared by `content/` and `ios/`. + - [`browser/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser): Browser process code. + - [`common/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/common): Code shared by the browser and the renderer. +- [`content/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content): Driver using the `//content` layer (all platforms except iOS). + - [`browser/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content/browser): Browser process code. + - [`renderer/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content/renderer): Renderer process code. + - [`common/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content/common): Code shared by the browser and the renderer. +- [`ios/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/ios): Driver using `//ios` (as opposed to `//content`). +- [`android/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/android): Java code for Android. + +## High-level architecture + +The following architecture diagram shows instances of Autofill's core objects. +For simplicity, we only consider the case of Chrome Autofill on non-iOS +platforms. The diagram is best read bottom-up because every Autofill flow starts +with `AutofillAgent` extracting a form from the DOM. + +``` +┌────────────────────┐ +│PersonalDataManager ├────────┬──────────────────┐ +│1 per BrowserContext│ owns N│ owns N│ +└─▲──────────────────┘ ┌─▼─────────────┐ ┌─▼────────┐ + │ │AutofillProfile│ │CreditCard│ + │weak ref └───────────────┘ └──────────┘ +┌─┴───────────────┐ +│FormDataImporter ◄─────────────────────┐ +│1 per WebContents│ events│ +└─▲───────────────┘ │ + │ │ ┌───────────────┐ + │ ┌────────────────────────┐ ┌─┴────────────────────┐ │Autofill server│ + │ │AutofillExternalDelegate◄────────┤BrowserAutofillManager├───────┐ └─────────────▲─┘ + │ │1 per RenderFrameHost │ owns 1│1 per RenderFrameHost │ votes│ HTTP│ + │ └──────────────────────┬─┘ └─▲──────────────────┬─┘ ┌─▼───────────────────▼─┐ + │ events│ │ events│ │AutofillDownloadManager│ + │ │ │ │ │1 per RenderFrameHost │ + │ │ │ │ └─────────────────────▲─┘ + │ │ │ │ │ + │ │ │ │ │ + │ │ │ └──┐ ┌──────────────┐ │ + │ │ │ │ │FormStructure │ │ + │ │ │ │ │1 per FormData│ │ + │ │ │ │ └─▲────────────┘ │ + │ │ │ │ │ │ + │owns 1 │ │events │ │sets types queries│ +┌─┴──────────────────┐ │ ┌─┴───────────────────┐ │ │owns N owns 1│ +│ChromeAutofillClient◄─────┼──────────┤AutofillManager ├─┼───┴──────────────────────┘ +│1 per WebContents │ │ weak ref│1 per RenderFrameHost│ │ +└────────────────────┘ │ └─▲─────────────────┬─┘ │ + │ │ events│ │ + └────────────┼────────────────►│◄──┘ + │ │ + ┌────────────┼─────────────────┼────────────┐ + │owns 1 │events │ │ + │ │owns 1 │ │ +┌──────────────────────────┴─┐ ┌─┴─────────────────▼─┐ ┌─▼───────────────────┐ +│ContentAutofillDriverFactory├────────►ContentAutofillDriver◄────────►ContentAutofillRouter│ +│1 per WebContents │owns N │1 per RenderFrameHost│ events │1 per WebContents │ +└────────────────────────────┘ └─▲─────────┬─────────┘ └─────────────────────┘ + │ │ +Browser │ │fill form and +1 process │ │other events +────────────────────────────────────────┼─────────┼───────────────────────────────────────── +Renderer events, often with│ │ +N processes FormData objects │ │ + │ │ + ┌─┴─────────▼─────┐ ┌─────────────────────┐ + │AutofillAgent ├───────►form_autofill_util.cc│ + │1 per RenderFrame│calls └─────────────────────┘ + └─────────────────┘ +``` +To edit the diagram, copy-paste it to asciiflow.com. + +A [`WebContents`](https://source.chromium.org/chromium/chromium/src/+/main:content/public/browser/web_contents.h) +corresponds to a tab. A [`RenderFrameHost`](https://source.chromium.org/chromium/chromium/src/+/main:content/public/browser/render_frame_host.h) +roughly corresponds to a frame or a document (but to neither exactly; they +differ in whether or not they survive navigations; details are [here](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/render_document.md) +and [details](https://docs.google.com/document/d/1C2VKkFRSc0kdmqjKan1G4NlNlxWZqE4Wam41FNMgnmA/edit#)). +A [`BrowserContext`](https://source.chromium.org/chromium/chromium/src/+/main:content/public/browser/browser_context.h) +corresponds to a [`Profile`](https://www.chromium.org/developers/design-documents/profile-architecture/). + +### Differences among platforms and embedders + +* Desktop vs Android: Android has different UI, which mostly lives in + `//chrome`. +* non-iOS vs iOS: iOS also uses `AutofillManager` and everything north of it, + but `AutofillDriverIOS*` instead of `ContentAutofill*`, and a different but + identically named `AutofillAgent`. +* Chrome vs WebView: WebView also uses `AutofillManager` and everything south + of it, but `AwAutofillClient` instead of `ChromeAutofillClient`, and + `AndroidAutofillManager` instead of `BrowserAutofillManager`. + +### Links to files + +- [`core/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core) + - [`common/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/common) + - [`form_data.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/common/form_data.h) + - [`browser/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser) + - [`autofill_client.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/autofill_client.h) + - [`//android_webview/browser/aw_autofill_client.h`](https://source.chromium.org/chromium/chromium/src/+/main:android_webview/browser/aw_autofill_client.h) (WebView implementation) + - [`//chrome/browser/ui/autofill/chrome_autofill_client.h`](https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/ui/autofill/chrome_autofill_client.h) (Chrome implementation) + - [`autofill_download_manager.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/autofill_download_manager.h) + - [`autofill_driver.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/autofill_driver.h) + - [`../../content/browser/content_autofill_driver.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/autofill_driver.h) (non-iOS implementation) + - [`../../ios/browser/autofill_driver_ios.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/ios/browser/autofill_driver_ios.h) (iOS implementation) + - [`autofill_external_delegate.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/autofill_external_delegate.h) + - [`autofill_manager.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/autofill_manager.h) + - [`browser_autofill_manager.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/browser_autofill_manager.h) (Chrome specialization) + - [`//components/android_autofill/browser/android_autofill_manager.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/android_autofill/browser/android_autofill_manager.h) (WebView specialization) + - [`data_model/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/data_model) + - [`autofill_profile.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/data_model/autofill_profile.h) + - [`credit_card.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/data_model/credit_card.h) + - [`form_data_importer.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/form_data_importer.h) + - [`form_structure.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/form_structure.h) + - [`personal_data_manager.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/personal_data_manager.h) + - [`proto/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/proto/) (Autofill server) +- [`content/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content) + - [`browser/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content/browser) + - [`content_autofill_driver.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content/browser/content_autofill_driver.h) + - [`content_autofill_driver_factory.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content/browser/content_autofill_driver_factory.h) + - [`content_autofill_router.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content/browser/content_autofill_router.h) + - [`renderer/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content/renderer) + - [`autofill_agent.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content/renderer/autofill_agent.h) + - [`form_autofill_util.cc`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/content/renderer/autofill_agent.h) +- [`ios/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/ios) + - [`browser/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/ios/browser) + - [`autofill_agent.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/ios/browser/autofill_agent.h) + - [`autofill_driver_ios.h`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/ios/browser/autofill_driver_ios.h) + - [`form_util/`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/ios/form_util) + - [`form.js`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/ios/form_util/resources/form.js) + - [`fill.js`](https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/ios/form_util/resources/fill.js) + +# Related directories + +There are some closely related directories in `//chrome`: + +- [`//chrome/browser/autofill`](https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/autofill) +- [`//chrome/browser/ui/android/autofill`](https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/ui/android/autofill) + - [`//chrome/android/java/src/org/chromium/chrome/browser/autofill`](https://source.chromium.org/chromium/chromium/src/+/main:chrome/android/java/src/org/chromium/chrome/browser/autofill/) +- [`//chrome/browser/ui/autofill`](https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/ui/autofill) +- [`//chrome/browser/ui/views/autofill`](https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/ui/views/autofill)
diff --git a/components/autofill/core/browser/geo/alternative_state_name_map_updater.cc b/components/autofill/core/browser/geo/alternative_state_name_map_updater.cc index f74e067..94407f896 100644 --- a/components/autofill/core/browser/geo/alternative_state_name_map_updater.cc +++ b/components/autofill/core/browser/geo/alternative_state_name_map_updater.cc
@@ -18,7 +18,6 @@ #include "base/ranges/algorithm.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "components/autofill/core/browser/geo/country_data.h" @@ -169,8 +168,8 @@ // |country_code| is used as the filename. // Example -> File "DE" contains the geographical states data of Germany. - base::PostTaskAndReplyWithResult( - GetTaskRunner().get(), FROM_HERE, + GetTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadDataFromFile, data_download_path.AppendASCII(country_code.value())), base::BindOnce(
diff --git a/components/autofill/core/browser/metrics/autofill_metrics.cc b/components/autofill/core/browser/metrics/autofill_metrics.cc index 0f3b894..37f4b0d0 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics.cc +++ b/components/autofill/core/browser/metrics/autofill_metrics.cc
@@ -27,6 +27,7 @@ #include "components/autofill/core/browser/form_types.h" #include "components/autofill/core/browser/metrics/autofill_metrics_utils.h" #include "components/autofill/core/browser/metrics/form_events/form_event_logger_base.h" +#include "components/autofill/core/browser/payments/card_unmask_challenge_option.h" #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_prefs.h" @@ -842,9 +843,18 @@ } // static -void AutofillMetrics::LogCardUnmaskAuthenticationSelectionDialogShown() { - base::UmaHistogramBoolean( - "Autofill.CardUnmaskAuthenticationSelectionDialog.Shown", true); +void AutofillMetrics::LogCardUnmaskAuthenticationSelectionDialogShown( + size_t number_of_challenge_options) { + static_assert(static_cast<int>(CardUnmaskChallengeOptionType::kMaxValue) < + 10); + DCHECK_GE(number_of_challenge_options, 0U); + // We are using an exact linear histogram, with a max of 10. This is a + // reasonable max so that the histogram is not sparse, as we do not foresee + // ever having more than 10 challenge options at the same time on a dialog to + // authenticate a virtual card. + base::UmaHistogramExactLinear( + "Autofill.CardUnmaskAuthenticationSelectionDialog.Shown2", + number_of_challenge_options, /*exclusive_max=*/10); } // static
diff --git a/components/autofill/core/browser/metrics/autofill_metrics.h b/components/autofill/core/browser/metrics/autofill_metrics.h index 3e7a476..a06a434 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics.h +++ b/components/autofill/core/browser/metrics/autofill_metrics.h
@@ -1101,9 +1101,10 @@ static void LogCardUnmaskAuthenticationSelectionDialogResultMetric( CardUnmaskAuthenticationSelectionDialogResultMetric metric); - // Logs true every time the Card Unmask Authentication Selection Dialog is - // shown. - static void LogCardUnmaskAuthenticationSelectionDialogShown(); + // Logs the number of challenge options shown every time the Card Unmask + // Authentication Selection Dialog is shown. + static void LogCardUnmaskAuthenticationSelectionDialogShown( + size_t number_of_challenge_options); static void LogCreditCardInfoBarMetric( InfoBarMetric metric,
diff --git a/components/autofill/core/browser/payments/credit_card_access_manager.cc b/components/autofill/core/browser/payments/credit_card_access_manager.cc index dd0a8f0..572b839 100644 --- a/components/autofill/core/browser/payments/credit_card_access_manager.cc +++ b/components/autofill/core/browser/payments/credit_card_access_manager.cc
@@ -852,7 +852,7 @@ return false; #else // We should not offer FIDO opt-in for virtual cards. - if (card_->record_type() == CreditCard::VIRTUAL_CARD) + if (!card_ || card_->record_type() == CreditCard::VIRTUAL_CARD) return false; // If this card is not eligible for offering FIDO opt-in, we should not offer
diff --git a/components/browsing_data/content/database_helper.cc b/components/browsing_data/content/database_helper.cc index bfbb2a0..9eb30884 100644 --- a/components/browsing_data/content/database_helper.cc +++ b/components/browsing_data/content/database_helper.cc
@@ -15,7 +15,6 @@ #include "base/files/file_util.h" #include "base/location.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "components/browsing_data/content/browsing_data_helper.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" @@ -44,8 +43,8 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!callback.is_null()); - base::PostTaskAndReplyWithResult( - tracker_->task_runner(), FROM_HERE, + tracker_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( [](storage::DatabaseTracker* tracker) { std::list<StorageUsageInfo> result;
diff --git a/components/browsing_topics/browsing_topics_state.cc b/components/browsing_topics/browsing_topics_state.cc index 4b973c8..d3de4c2e 100644 --- a/components/browsing_topics/browsing_topics_state.cc +++ b/components/browsing_topics/browsing_topics_state.cc
@@ -11,7 +11,6 @@ #include "base/json/json_string_value_serializer.h" #include "base/json/values_util.h" #include "base/metrics/histogram_functions.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "components/browsing_topics/util.h" @@ -65,9 +64,8 @@ backend_task_runner_, kSaveDelay, /*histogram_suffix=*/"BrowsingTopicsState") { - base::PostTaskAndReplyWithResult( - backend_task_runner_.get(), FROM_HERE, - base::BindOnce(&LoadFileOnBackendTaskRunner, writer_.path()), + backend_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadFileOnBackendTaskRunner, writer_.path()), base::BindOnce(&BrowsingTopicsState::DidLoadFile, weak_ptr_factory_.GetWeakPtr(), std::move(loaded_callback)));
diff --git a/components/cast_receiver/browser/streaming_controller_base.cc b/components/cast_receiver/browser/streaming_controller_base.cc index d69f2a7..b8ab7b1 100644 --- a/components/cast_receiver/browser/streaming_controller_base.cc +++ b/components/cast_receiver/browser/streaming_controller_base.cc
@@ -65,11 +65,12 @@ cast_streaming::ReceiverConfig config, cast_streaming::ReceiverSession::Client* client) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(!client_); - config_ = std::move(config); + config_.emplace(std::move(config)); client_ = client; - ProcessConfig(config_); + ProcessConfig(*config_); TryStartPlayback(); } @@ -85,7 +86,7 @@ } void StreamingControllerBase::TryStartPlayback() { - if (playback_started_cb_ && demuxer_connector_) { + if (playback_started_cb_ && demuxer_connector_ && config_) { cast_streaming::ReceiverSession::MessagePortProvider message_port_provider = base::BindOnce( [](std::unique_ptr<cast_api_bindings::MessagePort> port) { @@ -93,7 +94,7 @@ }, std::move(message_port_)); receiver_session_ = cast_streaming::ReceiverSession::Create( - config_, std::move(message_port_provider), client_); + *config_, std::move(message_port_provider), client_); DCHECK(receiver_session_); StartPlayback(receiver_session_.get(), std::move(demuxer_connector_),
diff --git a/components/cast_receiver/browser/streaming_controller_base.h b/components/cast_receiver/browser/streaming_controller_base.h index 367aa1d..c2f7f67 100644 --- a/components/cast_receiver/browser/streaming_controller_base.h +++ b/components/cast_receiver/browser/streaming_controller_base.h
@@ -79,8 +79,8 @@ PlaybackStartedCB playback_started_cb_; // Populated in InitializeReceiverSession() - cast_streaming::ReceiverConfig config_; - cast_streaming::ReceiverSession::Client* client_; + absl::optional<cast_streaming::ReceiverConfig> config_ = absl::nullopt; + cast_streaming::ReceiverSession::Client* client_ = nullptr; // Mojo connections. Initially populated in MainFrameReadyToCommitNavigation() // with connections to the Renderer process, and transferred to
diff --git a/components/content_creation/notes/core/templates/template_store.cc b/components/content_creation/notes/core/templates/template_store.cc index 9a4ebb7..1dd4d2d5 100644 --- a/components/content_creation/notes/core/templates/template_store.cc +++ b/components/content_creation/notes/core/templates/template_store.cc
@@ -10,7 +10,6 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/rand_util.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/time/time.h" @@ -87,9 +86,8 @@ if (IsDynamicTemplatesEnabled()) { FetchTemplates(std::move(callback)); } else { - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(&TemplateStore::BuildDefaultTemplates), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&TemplateStore::BuildDefaultTemplates), base::BindOnce(&TemplateStore::OnTemplatesReceived, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); }
diff --git a/components/cronet/android/BUILD.gn b/components/cronet/android/BUILD.gn index fa01227..a80dc31 100644 --- a/components/cronet/android/BUILD.gn +++ b/components/cronet/android/BUILD.gn
@@ -135,11 +135,21 @@ _cronet_version_header_include_dir = "$target_gen_dir/cronet_version_header" +proto_library("request_context_config_proto") { + sources = [ "proto/request_context_config.proto" ] +} + +proto_java_library("request_context_config_java_proto") { + proto_path = "." + sources = [ "proto/request_context_config.proto" ] +} + source_set("cronet_static") { deps = [ ":buildflags", ":cronet_jni_headers", ":cronet_jni_registration", + ":request_context_config_proto", "//base", "//base/third_party/dynamic_annotations", "//components/cronet:cronet_common", @@ -422,6 +432,7 @@ deps = [ ":cronet_api_java", ":cronet_impl_common_base_java", + ":request_context_config_java_proto", "//base:jni_java", "//build/android:build_java", "//third_party/android_deps:com_google_code_findbugs_jsr305_java", @@ -552,6 +563,7 @@ ":package_api_java", ":package_impl_common_java", ":repackage_native", + ":request_context_config_java_proto", "//third_party/android_deps:com_google_code_findbugs_jsr305_java", "//third_party/androidx:androidx_drawerlayout_drawerlayout_java", "//third_party/androidx:androidx_interpolator_interpolator_java",
diff --git a/components/cronet/android/DEPS b/components/cronet/android/DEPS index d6643eb6..fdfb852 100644 --- a/components/cronet/android/DEPS +++ b/components/cronet/android/DEPS
@@ -2,4 +2,5 @@ "+components/metrics", "+crypto", "+jni", + "+third_party/protobuf", ]
diff --git a/components/cronet/android/cronet_context_adapter.cc b/components/cronet/android/cronet_context_adapter.cc index 8ae0e42..2f890cb 100644 --- a/components/cronet/android/cronet_context_adapter.cc +++ b/components/cronet/android/cronet_context_adapter.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "components/cronet/android/cronet_context_adapter.h" +#include "components/cronet/android/proto/request_context_config.pb.h" #include <limits.h> #include <stddef.h> @@ -65,20 +66,6 @@ using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; -namespace { - -// Helper method that takes a Java string that can be null, in which case it -// will get converted to an empty string. -std::string ConvertNullableJavaStringToUTF8(JNIEnv* env, - const JavaParamRef<jstring>& jstr) { - std::string str; - if (!jstr.is_null()) - base::android::ConvertJavaStringToUTF8(env, jstr, &str); - return str; -} - -} // namespace - namespace cronet { CronetContextAdapter::CronetContextAdapter( @@ -242,38 +229,37 @@ // Create a URLRequestContextConfig from the given parameters. static jlong JNI_CronetUrlRequestContext_CreateRequestContextConfig( JNIEnv* env, - const JavaParamRef<jstring>& juser_agent, - const JavaParamRef<jstring>& jstorage_path, - jboolean jquic_enabled, - const JavaParamRef<jstring>& jquic_default_user_agent_id, - jboolean jhttp2_enabled, - jboolean jbrotli_enabled, - jboolean jdisable_cache, - jint jhttp_cache_mode, - jlong jhttp_cache_max_size, - const JavaParamRef<jstring>& jexperimental_quic_connection_options, - jlong jmock_cert_verifier, - jboolean jenable_network_quality_estimator, - jboolean jbypass_public_key_pinning_for_local_trust_anchors, - jint jnetwork_thread_priority) { + const JavaParamRef<jbyteArray>& javaSerializedProto) { + const int serializedProtoLength = env->GetArrayLength(javaSerializedProto); + org::chromium::net::RequestContextConfigOptions configOptions; + + std::vector<uint8_t> serializedProto; + + JavaByteArrayToByteVector(env, javaSerializedProto, &serializedProto); + + if (!configOptions.ParseFromArray(serializedProto.data(), + serializedProtoLength)) { + return 0; + } + std::unique_ptr<URLRequestContextConfig> url_request_context_config = URLRequestContextConfig::CreateURLRequestContextConfig( - jquic_enabled, - ConvertNullableJavaStringToUTF8(env, jquic_default_user_agent_id), - jhttp2_enabled, jbrotli_enabled, - static_cast<URLRequestContextConfig::HttpCacheType>(jhttp_cache_mode), - jhttp_cache_max_size, jdisable_cache, - ConvertNullableJavaStringToUTF8(env, jstorage_path), - /* accept_languages */ std::string(), - ConvertNullableJavaStringToUTF8(env, juser_agent), - ConvertNullableJavaStringToUTF8( - env, jexperimental_quic_connection_options), - base::WrapUnique( - reinterpret_cast<net::CertVerifier*>(jmock_cert_verifier)), - jenable_network_quality_estimator, - jbypass_public_key_pinning_for_local_trust_anchors, - jnetwork_thread_priority >= -20 && jnetwork_thread_priority <= 19 - ? absl::optional<double>(jnetwork_thread_priority) + configOptions.quic_enabled(), + configOptions.quic_default_user_agent_id(), + configOptions.http2_enabled(), configOptions.brotli_enabled(), + static_cast<URLRequestContextConfig::HttpCacheType>( + configOptions.http_cache_mode()), + configOptions.http_cache_max_size(), configOptions.disable_cache(), + configOptions.storage_path(), + /* accept_languages */ std::string(), configOptions.user_agent(), + configOptions.experimental_options(), + base::WrapUnique(reinterpret_cast<net::CertVerifier*>( + configOptions.mock_cert_verifier())), + configOptions.enable_network_quality_estimator(), + configOptions.bypass_public_key_pinning_for_local_trust_anchors(), + configOptions.network_thread_priority() >= -20 && + configOptions.network_thread_priority() <= 19 + ? absl::optional<double>(configOptions.network_thread_priority()) : absl::optional<double>()); return reinterpret_cast<jlong>(url_request_context_config.release()); }
diff --git a/components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java b/components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java index f12ba832..9a4bc5a 100644 --- a/components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java +++ b/components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java
@@ -23,6 +23,7 @@ import org.chromium.net.ExperimentalBidirectionalStream; import org.chromium.net.NetworkQualityRttListener; import org.chromium.net.NetworkQualityThroughputListener; +import org.chromium.net.RequestContextConfigOptions; import org.chromium.net.RequestFinishedInfo; import org.chromium.net.RttThroughputValues; import org.chromium.net.UrlRequest; @@ -248,14 +249,8 @@ @VisibleForTesting public static long createNativeUrlRequestContextConfig(CronetEngineBuilderImpl builder) { final long urlRequestContextConfig = - CronetUrlRequestContextJni.get().createRequestContextConfig(builder.getUserAgent(), - builder.storagePath(), builder.quicEnabled(), - builder.getDefaultQuicUserAgentId(), builder.http2Enabled(), - builder.brotliEnabled(), builder.cacheDisabled(), builder.httpCacheMode(), - builder.httpCacheMaxSize(), builder.experimentalOptions(), - builder.mockCertVerifier(), builder.networkQualityEstimatorEnabled(), - builder.publicKeyPinningBypassForLocalTrustAnchorsEnabled(), - builder.threadPriority(Process.THREAD_PRIORITY_BACKGROUND)); + CronetUrlRequestContextJni.get().createRequestContextConfig( + createRequestContextConfigOptions(builder).toByteArray()); if (urlRequestContextConfig == 0) { throw new IllegalArgumentException("Experimental options parsing failed."); } @@ -270,6 +265,43 @@ return urlRequestContextConfig; } + private static RequestContextConfigOptions createRequestContextConfigOptions( + CronetEngineBuilderImpl engineBuilder) { + RequestContextConfigOptions.Builder resultBuilder = + RequestContextConfigOptions.newBuilder() + .setQuicEnabled(engineBuilder.quicEnabled()) + .setHttp2Enabled(engineBuilder.http2Enabled()) + .setBrotliEnabled(engineBuilder.brotliEnabled()) + .setDisableCache(engineBuilder.cacheDisabled()) + .setHttpCacheMode(engineBuilder.httpCacheMode()) + .setHttpCacheMaxSize(engineBuilder.httpCacheMaxSize()) + .setMockCertVerifier(engineBuilder.mockCertVerifier()) + .setEnableNetworkQualityEstimator( + engineBuilder.networkQualityEstimatorEnabled()) + .setBypassPublicKeyPinningForLocalTrustAnchors( + engineBuilder.publicKeyPinningBypassForLocalTrustAnchorsEnabled()) + .setNetworkThreadPriority( + engineBuilder.threadPriority(Process.THREAD_PRIORITY_BACKGROUND)); + + if (engineBuilder.getUserAgent() != null) { + resultBuilder.setUserAgent(engineBuilder.getUserAgent()); + } + + if (engineBuilder.storagePath() != null) { + resultBuilder.setStoragePath(engineBuilder.storagePath()); + } + + if (engineBuilder.getDefaultQuicUserAgentId() != null) { + resultBuilder.setQuicDefaultUserAgentId(engineBuilder.getDefaultQuicUserAgentId()); + } + + if (engineBuilder.experimentalOptions() != null) { + resultBuilder.setExperimentalOptions(engineBuilder.experimentalOptions()); + } + + return resultBuilder.build(); + } + @Override public ExperimentalBidirectionalStream.Builder newBidirectionalStreamBuilder( String url, BidirectionalStream.Callback callback, Executor executor) { @@ -616,18 +648,12 @@ return new CronetURLStreamHandlerFactory(this); } - /** - * Mark request as started to prevent shutdown when there are active - * requests. - */ + /** Mark request as started to prevent shutdown when there are active requests. */ void onRequestStarted() { mActiveRequestCount.incrementAndGet(); } - /** - * Mark request as finished to allow shutdown when there are no active - * requests. - */ + /** Mark request as finished to allow shutdown when there are no active requests. */ void onRequestDestroyed() { mActiveRequestCount.decrementAndGet(); } @@ -653,8 +679,7 @@ } /** - * @return loggingLevel see {@link #LOG_NONE}, {@link #LOG_DEBUG} and - * {@link #LOG_VERBOSE}. + * @return loggingLevel see {@link #LOG_NONE}, {@link #LOG_DEBUG} and {@link #LOG_VERBOSE}. */ private int getLoggingLevel() { int loggingLevel; @@ -790,12 +815,7 @@ // Native methods are implemented in cronet_url_request_context_adapter.cc. @NativeMethods interface Natives { - long createRequestContextConfig(String userAgent, String storagePath, boolean quicEnabled, - String quicUserAgentId, boolean http2Enabled, boolean brotliEnabled, - boolean disableCache, int httpCacheMode, long httpCacheMaxSize, - String experimentalOptions, long mockCertVerifier, - boolean enableNetworkQualityEstimator, - boolean bypassPublicKeyPinningForLocalTrustAnchors, int networkThreadPriority); + long createRequestContextConfig(byte[] serializedRequestContextConfigOptions); void addQuicHint(long urlRequestContextConfig, String host, int port, int alternatePort); void addPkp(long urlRequestContextConfig, String host, byte[][] hashes,
diff --git a/components/cronet/android/proto/request_context_config.proto b/components/cronet/android/proto/request_context_config.proto new file mode 100644 index 0000000..348bd84 --- /dev/null +++ b/components/cronet/android/proto/request_context_config.proto
@@ -0,0 +1,24 @@ +syntax = "proto2"; + +package org.chromium.net; + +option java_multiple_files = true; +option java_package = "org.chromium.net"; +option optimize_for = LITE_RUNTIME; // crbug/800281 + +message RequestContextConfigOptions { + optional string user_agent = 1; + optional string storage_path = 2; + optional bool quic_enabled = 3; + optional string quic_default_user_agent_id = 4; + optional bool http2_enabled = 5; + optional bool brotli_enabled = 6; + optional bool disable_cache = 7; + optional int32 http_cache_mode = 8; + optional int64 http_cache_max_size = 9; + optional string experimental_options = 10; + optional int64 mock_cert_verifier = 11; + optional bool enable_network_quality_estimator = 12; + optional bool bypass_public_key_pinning_for_local_trust_anchors = 13; + optional int32 network_thread_priority = 14; +}
diff --git a/components/download/internal/background_service/file_monitor_impl.cc b/components/download/internal/background_service/file_monitor_impl.cc index e5d275c..3b2aa3d6 100644 --- a/components/download/internal/background_service/file_monitor_impl.cc +++ b/components/download/internal/background_service/file_monitor_impl.cc
@@ -9,7 +9,6 @@ #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/stl_util.h" -#include "base/task/task_runner_util.h" #include "base/threading/scoped_blocking_call.h" namespace download { @@ -102,8 +101,8 @@ FileMonitorImpl::~FileMonitorImpl() = default; void FileMonitorImpl::Initialize(InitCallback callback) { - base::PostTaskAndReplyWithResult( - file_thread_task_runner_.get(), FROM_HERE, + file_thread_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&InitializeAndCreateDownloadDirectory, download_file_dir_), std::move(callback)); } @@ -156,9 +155,8 @@ } void FileMonitorImpl::HardRecover(InitCallback callback) { - base::PostTaskAndReplyWithResult( - file_thread_task_runner_.get(), FROM_HERE, - base::BindOnce(&HardRecoverOnFileThread, download_file_dir_), + file_thread_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&HardRecoverOnFileThread, download_file_dir_), std::move(callback)); }
diff --git a/components/download/internal/common/download_item_impl.cc b/components/download/internal/common/download_item_impl.cc index 6ba1c46..a843fd4 100644 --- a/components/download/internal/common/download_item_impl.cc +++ b/components/download/internal/common/download_item_impl.cc
@@ -41,7 +41,6 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/trace_event/memory_usage_estimator.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" @@ -563,8 +562,8 @@ if (delete_file_afterward) { if (download_file_) { - base::PostTaskAndReplyWithResult( - GetDownloadTaskRunner().get(), FROM_HERE, + GetDownloadTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DownloadFileDetach, std::move(download_file_)), std::move(callback)); } else { @@ -574,8 +573,8 @@ Remove(); // Download item has now been deleted. } else if (download_file_) { - base::PostTaskAndReplyWithResult( - GetDownloadTaskRunner().get(), FROM_HERE, + GetDownloadTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MakeCopyOfDownloadFile, download_file_.get()), std::move(callback)); } else { @@ -777,8 +776,8 @@ return; } - base::PostTaskAndReplyWithResult( - GetDownloadTaskRunner().get(), FROM_HERE, + GetDownloadTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&download::RenameDownloadedFile, GetFullPath(), display_name), base::BindOnce(&DownloadItemImpl::RenameDownloadedFileDone, @@ -1003,9 +1002,8 @@ std::move(callback), true)); return; } - base::PostTaskAndReplyWithResult( - GetDownloadTaskRunner().get(), FROM_HERE, - base::BindOnce(&DeleteDownloadedFile, GetFullPath()), + GetDownloadTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DeleteDownloadedFile, GetFullPath()), base::BindOnce(&DeleteDownloadedFileDone, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); }
diff --git a/components/download/internal/common/download_path_reservation_tracker.cc b/components/download/internal/common/download_path_reservation_tracker.cc index 5e4defb..7f5678c9 100644 --- a/components/download/internal/common/download_path_reservation_tracker.cc +++ b/components/download/internal/common/download_path_reservation_tracker.cc
@@ -21,7 +21,6 @@ #include "base/strings/stringprintf.h" #include "base/task/lazy_thread_pool_task_runner.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/third_party/icu/icu_utf.h" #include "base/time/time.h" #include "build/build_config.h" @@ -518,9 +517,8 @@ download_item->GetStartTime(), conflict_action}; - base::PostTaskAndReplyWithResult( - GetTaskRunner().get(), FROM_HERE, - base::BindOnce(&CreateReservation, info, reserved_path), + GetTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CreateReservation, info, reserved_path), base::BindOnce(&RunGetReservedPathCallback, std::move(callback), base::Owned(reserved_path))); } @@ -542,8 +540,8 @@ const base::FilePath& target_path, DownloadItem* download_item, CheckDownloadPathCallback callback) { - base::PostTaskAndReplyWithResult( - GetTaskRunner().get(), FROM_HERE, + GetTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&IsAdditionalPathReserved, target_path, download_item), std::move(callback)); }
diff --git a/components/drive/drive_uploader.cc b/components/drive/drive_uploader.cc index ab9a3ef..83dc42dd 100644 --- a/components/drive/drive_uploader.cc +++ b/components/drive/drive_uploader.cc
@@ -13,7 +13,6 @@ #include "base/files/file_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" -#include "base/task/task_runner_util.h" #include "components/drive/service/drive_service_interface.h" #include "google_apis/drive/drive_api_parser.h" #include "services/device/public/mojom/wake_lock.mojom.h" @@ -265,8 +264,8 @@ DVLOG(1) << "Uploading file: " << upload_file_info->DebugString(); UploadFileInfo* info_ptr = upload_file_info.get(); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&base::GetFileSize, info_ptr->file_path, &info_ptr->content_length), base::BindOnce(&DriveUploader::StartUploadFileAfterGetFileSize,
diff --git a/components/embedder_support/user_agent_utils_unittest.cc b/components/embedder_support/user_agent_utils_unittest.cc index 29e2d84..bd0d9ed 100644 --- a/components/embedder_support/user_agent_utils_unittest.cc +++ b/components/embedder_support/user_agent_utils_unittest.cc
@@ -218,10 +218,16 @@ } if (!model.empty()) { - if (base::SysInfo::GetAndroidBuildCodename() == "REL") - ASSERT_EQ(base::SysInfo::HardwareModelName(), model); - else + if (base::SysInfo::GetAndroidBuildCodename() == "REL") { + // In UA reduction Phase 6, we change the deviceModel token to "K". + ASSERT_EQ(base::FeatureList::IsEnabled( + blink::features::kReduceUserAgentAndroidVersionDeviceModel) + ? "K" + : base::SysInfo::HardwareModelName(), + model); + } else { ASSERT_EQ("", model); + } } #elif BUILDFLAG(IS_FUCHSIA) // X11; Fuchsia
diff --git a/components/enterprise/browser/controller/browser_dm_token_storage.cc b/components/enterprise/browser/controller/browser_dm_token_storage.cc index d0d1a44..e070493 100644 --- a/components/enterprise/browser/controller/browser_dm_token_storage.cc +++ b/components/enterprise/browser/controller/browser_dm_token_storage.cc
@@ -20,7 +20,6 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/syslog_logging.h" -#include "base/task/task_runner_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" @@ -213,18 +212,16 @@ auto task = delegate_->SaveDMTokenTask(token, RetrieveClientId()); auto reply = base::BindOnce(&BrowserDMTokenStorage::OnDMTokenStored, weak_factory_.GetWeakPtr()); - base::PostTaskAndReplyWithResult(delegate_->SaveDMTokenTaskRunner().get(), - FROM_HERE, std::move(task), - std::move(reply)); + delegate_->SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(task), std::move(reply)); } void BrowserDMTokenStorage::DeleteDMToken() { auto task = delegate_->DeleteDMTokenTask(RetrieveClientId()); auto reply = base::BindOnce(&BrowserDMTokenStorage::OnDMTokenStored, weak_factory_.GetWeakPtr()); - base::PostTaskAndReplyWithResult(delegate_->SaveDMTokenTaskRunner().get(), - FROM_HERE, std::move(task), - std::move(reply)); + delegate_->SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(task), std::move(reply)); } } // namespace policy
diff --git a/components/gcm_driver/gcm_driver_desktop.cc b/components/gcm_driver/gcm_driver_desktop.cc index 329e8ef..83f2541 100644 --- a/components/gcm_driver/gcm_driver_desktop.cc +++ b/components/gcm_driver/gcm_driver_desktop.cc
@@ -16,7 +16,6 @@ #include "base/observer_list.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/timer/timer.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" @@ -580,8 +579,8 @@ scoped_refptr<RegistrationInfo> registration_info, const std::string& registration_id, ValidateRegistrationCallback callback) { - base::PostTaskAndReplyWithResult( - io_thread_.get(), FROM_HERE, + io_thread_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GCMDriverDesktop::IOWorker::ValidateRegistration, base::Unretained(io_worker_.get()), std::move(registration_info), registration_id),
diff --git a/components/google/core/common/google_util.cc b/components/google/core/common/google_util.cc index ce786898..455fff78 100644 --- a/components/google/core/common/google_util.cc +++ b/components/google/core/common/google_util.cc
@@ -349,16 +349,16 @@ const std::string param_name = "async"; const std::string key_value = key + ":" + value; bool replaced = false; - const std::string input = url.query(); + const base::StringPiece input = url.query_piece(); url::Component cursor(0, input.size()); std::string output; url::Component key_range, value_range; while (url::ExtractQueryKeyValue(input.data(), &cursor, &key_range, &value_range)) { - const base::StringPiece input_key(input.data() + key_range.begin, - key_range.len); - std::string key_value_pair(input, key_range.begin, - value_range.end() - key_range.begin); + const base::StringPiece input_key = + input.substr(key_range.begin, key_range.len); + std::string key_value_pair( + input.substr(key_range.begin, value_range.end() - key_range.begin)); if (!replaced && input_key == param_name) { // Check |replaced| as only the first match should be replaced. replaced = true;
diff --git a/components/image_fetcher/core/cache/image_data_store_disk.cc b/components/image_fetcher/core/cache/image_data_store_disk.cc index 4c7a43f..1d3c4b9 100644 --- a/components/image_fetcher/core/cache/image_data_store_disk.cc +++ b/components/image_fetcher/core/cache/image_data_store_disk.cc
@@ -13,7 +13,6 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" @@ -130,9 +129,8 @@ void ImageDataStoreDisk::Initialize(base::OnceClosure callback) { DCHECK(initialization_status_ == InitializationStatus::UNINITIALIZED); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(InitializeImpl, storage_path_), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(InitializeImpl, storage_path_), base::BindOnce(&ImageDataStoreDisk::OnInitializationComplete, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } @@ -161,8 +159,8 @@ return; } - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(LoadImageImpl, storage_path_, key, needs_transcoding), base::BindOnce(&ImageDataStoreDisk::OnImageLoaded, weak_ptr_factory_.GetWeakPtr(), needs_transcoding, @@ -184,9 +182,9 @@ return; } - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(GetAllKeysImpl, storage_path_), std::move(callback)); + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(GetAllKeysImpl, storage_path_), + std::move(callback)); } void ImageDataStoreDisk::OnInitializationComplete(
diff --git a/components/image_fetcher/ios/ios_image_decoder_impl.mm b/components/image_fetcher/ios/ios_image_decoder_impl.mm index 6f1df2b..f389847 100644 --- a/components/image_fetcher/ios/ios_image_decoder_impl.mm +++ b/components/image_fetcher/ios/ios_image_decoder_impl.mm
@@ -12,7 +12,6 @@ #include "base/callback.h" #import "base/ios/ios_util.h" #include "base/memory/weak_ptr.h" -#import "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #import "components/image_fetcher/ios/webp_decoder.h" #include "ios/web/public/thread/web_thread.h" @@ -87,8 +86,8 @@ decodeBlock = ^NSData*() { return data; }; } - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, base::BindOnce(decodeBlock), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(decodeBlock), base::BindOnce(&IOSImageDecoderImpl::CreateUIImageAndRunCallback, weak_factory_.GetWeakPtr(), std::move(callback))); }
diff --git a/components/lens/BUILD.gn b/components/lens/BUILD.gn index 09317ce3..afff95cfa 100644 --- a/components/lens/BUILD.gn +++ b/components/lens/BUILD.gn
@@ -7,8 +7,6 @@ static_library("lens") { sources = [ "lens_entrypoints.h", - "lens_features.cc", - "lens_features.h", "lens_metadata.cc", "lens_metadata.h", "lens_rendering_environment.h", @@ -22,6 +20,20 @@ "//net", "//url", ] + public_deps = [ ":features" ] +} + +component("features") { + output_name = "lens_features" + + defines = [ "IS_LENS_FEATURES_IMPL" ] + + sources = [ + "lens_features.cc", + "lens_features.h", + ] + + deps = [ "//base" ] } mojom("lens_mojo") {
diff --git a/components/lens/lens_features.h b/components/lens/lens_features.h index 9395478..69ea044 100644 --- a/components/lens/lens_features.h +++ b/components/lens/lens_features.h
@@ -7,6 +7,7 @@ #include <string> +#include "base/component_export.h" #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" @@ -14,196 +15,253 @@ namespace features { // Enables context menu search by image sending to the Lens homepage. +COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kLensStandalone); // Feature that controls the compression of images before they are sent to Lens. +COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kLensImageCompression); // Enables a variety of changes aimed to improve user's engagement with current // Lens features. +COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kLensSearchOptimizations); // Enables Lens integration into the Chrome screenshot sharing feature by adding // a "Search Image" button. +COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kLensSearchImageInScreenshotSharing); // Enables Latency logging for the LensStandalone feature. +COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kEnableLatencyLogging); // Enable the Lens Region Search feature on the PDF viewer. +COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kEnableRegionSearchOnPdfViewer); // Enables the modification of the instruction chip UI that is presented when // region search is opened. +COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kLensInstructionChipImprovements); // Enables the image search side panel experience for third party default search // engines +COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kEnableImageSearchSidePanelFor3PDse); // Enables launching the region search experience in a new tab with WebUI. +COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kLensRegionSearchStaticPage); // Enables using more optimized image formats for Lens requests. +COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kLensImageFormatOptimizations); // Enables using `Google` as the visual search provider instead of `Google // Lens`. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kUseGoogleAsVisualSearchProvider; // Enables alternate option 1 for the Region Search context menu item text. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kRegionSearchUseMenuItemAltText1; // Enables alternate option 2 for the Region Search context menu item text. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kRegionSearchUseMenuItemAltText2; // Enables alternate option 3 for the Region Search context menu item text. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kRegionSearchUseMenuItemAltText3; // Enables UKM logging for the Lens Region Search feature. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kEnableUKMLoggingForRegionSearch; // Enables UKM logging for the LensStandalone feature. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kEnableUKMLoggingForImageSearch; // Enables the side panel for Lens features on Chrome where supported. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kEnableSidePanelForLens; // The base URL for Lens. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<std::string> kHomepageURLForLens; // Enable Lens HTML redirect fix. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kEnableLensHtmlRedirectFix; // Enables Lens fullscreen search on Desktop platforms. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kEnableFullscreenSearch; // Enables using side panel in the Chrome Screenshot sharing feature integration // instead of a new tab. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kUseSidePanelForScreenshotSharing; // Forces the Chrome Screenshot sharing dialog bubble to stay open after the // user clicks the Search Image button. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kEnablePersistentBubble; // Enables the use of the selection with image icon when using the instruction // chip improvements feature. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kUseSelectionIconWithImage; // Enables the use of an alternative string for the instruction chip. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kUseAltChipString; // Enables encoding to WebP for image search queries. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kUseWebpInImageSearch; // Value in range 0-100 that dictates the encoding quality for image search // lossy formats, with 100 being the best quality. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<int> kEncodingQualityImageSearch; // Enables encoding to WebP for region search queries. This param takes // precedence over kUseJpegInRegionSearch. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kUseWebpInRegionSearch; // Enables encoding to JPEG for region search queries. This param does // nothing if kUseWebpInRegionSearch is enabled. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<bool> kUseJpegInRegionSearch; // Value in range 0-100 that dictates the encoding quality for region search // lossy formats, with 100 being the best quality. +COMPONENT_EXPORT(LENS_FEATURES) extern const base::FeatureParam<int> kEncodingQualityRegionSearch; // Enables Latency logging for the LensStandalone feature. +COMPONENT_EXPORT(LENS_FEATURES) extern bool GetEnableLatencyLogging(); // Returns whether the image search side panel is supported for third party // default search engines +COMPONENT_EXPORT(LENS_FEATURES) extern bool GetEnableImageSearchUnifiedSidePanelFor3PDse(); // Returns whether to enable UKM logging for Lens Region Search feature. +COMPONENT_EXPORT(LENS_FEATURES) extern bool GetEnableUKMLoggingForRegionSearch(); // Returns whether to enable UKM logging for LensStandalone feature. +COMPONENT_EXPORT(LENS_FEATURES) extern bool GetEnableUKMLoggingForImageSearch(); // Returns the max pixel width/height for the image to be sent to Lens via // region search. The images are sent at 1x as PNGs. +COMPONENT_EXPORT(LENS_FEATURES) extern int GetMaxPixelsForRegionSearch(); // Returns the max area for the image to be sent to Lens via region search. +COMPONENT_EXPORT(LENS_FEATURES) extern int GetMaxAreaForRegionSearch(); // Returns the max pixel width/height for the image to be sent to Lens. +COMPONENT_EXPORT(LENS_FEATURES) extern int GetMaxPixelsForImageSearch(); // The URL for the Lens home page. +COMPONENT_EXPORT(LENS_FEATURES) extern std::string GetHomepageURLForLens(); // Returns whether to apply fix for HTML redirects. +COMPONENT_EXPORT(LENS_FEATURES) extern bool GetEnableLensHtmlRedirectFix(); // Returns whether Lens fullscreen search is enabled. +COMPONENT_EXPORT(LENS_FEATURES) extern bool IsLensFullscreenSearchEnabled(); // Returns whether to use alternative option 1 for the Region Search context // menu item text. +COMPONENT_EXPORT(LENS_FEATURES) extern bool UseRegionSearchMenuItemAltText1(); // Returns whether to use alternative option 2 for the Region Search context // menu item text. +COMPONENT_EXPORT(LENS_FEATURES) extern bool UseRegionSearchMenuItemAltText2(); // Returns whether to use alternative option 3 for the Region Search context // menu item text. +COMPONENT_EXPORT(LENS_FEATURES) extern bool UseRegionSearchMenuItemAltText3(); // Returns whether to use `Google` as the visual search provider for all // relevant Lens context menu strings. +COMPONENT_EXPORT(LENS_FEATURES) extern bool UseGoogleAsVisualSearchProvider(); // Returns whether the Lens side panel is enabled for image search. +COMPONENT_EXPORT(LENS_FEATURES) extern bool IsLensSidePanelEnabled(); // Returns whether the Lens side panel is enabled for region search. +COMPONENT_EXPORT(LENS_FEATURES) extern bool IsLensSidePanelEnabledForRegionSearch(); // Returns whether the Search Image button in the Chrome Screenshot Sharing // feature is enabled +COMPONENT_EXPORT(LENS_FEATURES) extern bool IsLensInScreenshotSharingEnabled(); // Returns whether the instruction chip improvement feature is enabled. +COMPONENT_EXPORT(LENS_FEATURES) extern bool IsLensInstructionChipImprovementsEnabled(); // Returns whether to use the Chrome Side Panel for the Lens integration in // Chrome Screenshot Sharing feature +COMPONENT_EXPORT(LENS_FEATURES) extern bool UseSidePanelForScreenshotSharing(); // Returns whether the Chrome Screenshot Sharing Bubble disappears after the // user clicks the Search Image button +COMPONENT_EXPORT(LENS_FEATURES) extern bool EnablePersistentBubble(); // Returns if we should use the selection with image icon instead of the default // when using the instruction chip improvements feature. +COMPONENT_EXPORT(LENS_FEATURES) extern bool UseSelectionIconWithImage(); // Returns whether we should use an alternative instruction chip string. +COMPONENT_EXPORT(LENS_FEATURES) extern bool UseAltChipString(); // Returns whether we should use a WebUI static page for region search. +COMPONENT_EXPORT(LENS_FEATURES) extern bool IsLensRegionSearchStaticPageEnabled(); // Returns whether to use WebP encoding for image search queries. +COMPONENT_EXPORT(LENS_FEATURES) extern bool IsWebpForImageSearchEnabled(); // Get the encoding quality for image search queries. +COMPONENT_EXPORT(LENS_FEATURES) extern int GetImageSearchEncodingQuality(); // Returns whether to use WebP encoding for region search queries. +COMPONENT_EXPORT(LENS_FEATURES) extern bool IsWebpForRegionSearchEnabled(); // Returns whether to use JPEG encoding for region search queries. +COMPONENT_EXPORT(LENS_FEATURES) extern bool IsJpegForRegionSearchEnabled(); // Get the encoding quality for region search queries. +COMPONENT_EXPORT(LENS_FEATURES) extern int GetRegionSearchEncodingQuality(); } // namespace features } // namespace lens
diff --git a/components/leveldb_proto/internal/proto_leveldb_wrapper.cc b/components/leveldb_proto/internal/proto_leveldb_wrapper.cc index b3de64f8..49475c7 100644 --- a/components/leveldb_proto/internal/proto_leveldb_wrapper.cc +++ b/components/leveldb_proto/internal/proto_leveldb_wrapper.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/callback_forward.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "components/leveldb_proto/internal/leveldb_database.h" #include "components/leveldb_proto/internal/proto_leveldb_wrapper_metrics.h" @@ -204,8 +203,8 @@ DCHECK(database); db_ = database; - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(InitFromTaskRunner, base::Unretained(db_), database_dir, options, destroy_on_corruption, metrics_id_), std::move(callback)); @@ -216,8 +215,8 @@ std::unique_ptr<KeyVector> keys_to_remove, typename Callbacks::UpdateCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(UpdateEntriesFromTaskRunner, base::Unretained(db_), std::move(entries_to_save), std::move(keys_to_remove), metrics_id_), @@ -239,8 +238,8 @@ const std::string& target_prefix, Callbacks::UpdateCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(UpdateEntriesWithRemoveFilterFromTaskRunner, base::Unretained(db_), std::move(entries_to_save), delete_key_filter, target_prefix, metrics_id_), @@ -404,8 +403,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(db_); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(DestroyFromTaskRunner, base::Unretained(db_), metrics_id_), std::move(callback)); } @@ -415,8 +414,8 @@ const std::string& client_id, const scoped_refptr<base::SequencedTaskRunner>& task_runner, Callbacks::DestroyCallback callback) { - base::PostTaskAndReplyWithResult( - task_runner.get(), FROM_HERE, + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(DestroyWithDirectoryFromTaskRunner, db_dir, client_id), std::move(callback)); }
diff --git a/components/metrics/file_metrics_provider.cc b/components/metrics/file_metrics_provider.cc index b87d802..c39ccb4 100644 --- a/components/metrics/file_metrics_provider.cc +++ b/components/metrics/file_metrics_provider.cc
@@ -24,7 +24,6 @@ #include "base/strings/string_piece.h" #include "base/task/single_thread_task_runner.h" #include "base/task/task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/time/time.h" @@ -820,8 +819,8 @@ DCHECK(source->allocator); // Do the actual work as a background task. - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &FileMetricsProvider::ProvideIndependentMetricsOnTaskRunner, source_ptr, system_profile_proto, snapshot_manager),
diff --git a/components/net_log/net_export_file_writer.cc b/components/net_log/net_export_file_writer.cc index ecd2840f..e07ffad 100644 --- a/components/net_log/net_export_file_writer.cc +++ b/components/net_log/net_export_file_writer.cc
@@ -18,7 +18,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/values.h" #include "build/build_config.h" @@ -110,8 +109,8 @@ NotifyStateObserversAsync(); - base::PostTaskAndReplyWithResult( - file_task_runner_.get(), FROM_HERE, + file_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SetUpDefaultLogPath, default_log_base_dir_getter_), base::BindOnce(&NetExportFileWriter::SetStateAfterSetUpDefaultLogPath, weak_ptr_factory_.GetWeakPtr())); @@ -147,8 +146,8 @@ net_log_exporter_.set_disconnect_handler(base::BindOnce( &NetExportFileWriter::OnConnectionError, base::Unretained(this))); - base::PostTaskAndReplyWithResult( - file_task_runner_.get(), FROM_HERE, + file_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&NetExportFileWriter::CreateOutputFile, log_path_), base::BindOnce(&NetExportFileWriter::StartNetLogAfterCreateFile, weak_ptr_factory_.GetWeakPtr(), capture_mode, @@ -274,9 +273,9 @@ DCHECK(file_task_runner_); DCHECK(!log_path_.empty()); - base::PostTaskAndReplyWithResult(file_task_runner_.get(), FROM_HERE, - base::BindOnce(&GetPathIfExists, log_path_), - std::move(path_callback)); + file_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetPathIfExists, log_path_), + std::move(path_callback)); } std::string NetExportFileWriter::CaptureModeToString(
diff --git a/components/ntp_snippets/pref_util.cc b/components/ntp_snippets/pref_util.cc index adeb7e4..55e5121 100644 --- a/components/ntp_snippets/pref_util.cc +++ b/components/ntp_snippets/pref_util.cc
@@ -5,6 +5,7 @@ #include "components/ntp_snippets/pref_util.h" #include <memory> +#include <ostream> #include "base/values.h" #include "components/prefs/pref_service.h"
diff --git a/components/offline_items_collection/core/utilities/file_existence_checker.h b/components/offline_items_collection/core/utilities/file_existence_checker.h index 8342abd..2c15806 100644 --- a/components/offline_items_collection/core/utilities/file_existence_checker.h +++ b/components/offline_items_collection/core/utilities/file_existence_checker.h
@@ -14,7 +14,6 @@ #include "base/files/file_util.h" #include "base/memory/ref_counted.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" namespace offline_items_collection { @@ -41,8 +40,8 @@ const scoped_refptr<base::SequencedTaskRunner>& blocking_task_runner, FileWithIdCollection<T> items_to_check, ResultCallback<T> callback) { - base::PostTaskAndReplyWithResult( - blocking_task_runner.get(), FROM_HERE, + blocking_task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileExistenceChecker::CheckForMissingFilesBlocking<T>, std::move(items_to_check)), std::move(callback));
diff --git a/components/offline_pages/core/background/request_queue_store.cc b/components/offline_pages/core/background/request_queue_store.cc index f91fd53..8a73720 100644 --- a/components/offline_pages/core/background/request_queue_store.cc +++ b/components/offline_pages/core/background/request_queue_store.cc
@@ -16,7 +16,6 @@ #include "base/logging.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "components/offline_pages/core/background/save_page_request.h" #include "components/offline_pages/core/offline_page_item_utils.h" #include "sql/database.h" @@ -591,9 +590,8 @@ db_ = std::make_unique<sql::Database>(sql::DatabaseOptions{ .exclusive_locking = true, .page_size = 4096, .cache_size = 500}); - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(&InitDatabaseSync, db_.get(), db_file_path_), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&InitDatabaseSync, db_.get(), db_file_path_), base::BindOnce(&RequestQueueStore::OnOpenConnectionDone, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } @@ -607,9 +605,8 @@ base::BindOnce(std::move(callback), false, std::move(requests))); return; } - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(&GetAllRequestsSync, db_.get()), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetAllRequestsSync, db_.get()), base::BindOnce(&InvokeGetRequestsCallback, std::move(callback))); } @@ -625,9 +622,8 @@ return; } - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(&GetRequestsByIdsSync, db_.get(), request_ids), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetRequestsByIdsSync, db_.get(), request_ids), std::move(callback)); } @@ -641,9 +637,8 @@ return; } - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(&AddRequestSync, db_.get(), request, options), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&AddRequestSync, db_.get(), request, options), std::move(callback)); } @@ -657,9 +652,8 @@ return; } - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(&UpdateRequestsSync, db_.get(), requests), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&UpdateRequestsSync, db_.get(), requests), std::move(callback)); } @@ -674,9 +668,8 @@ return; } - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(&RemoveRequestsSync, db_.get(), request_ids), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&RemoveRequestsSync, db_.get(), request_ids), std::move(callback)); } @@ -684,8 +677,8 @@ const base::RepeatingCallback<bool(const SavePageRequest&)>& remove_predicate, UpdateCallback callback) { - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(RemoveRequestsIfSync, db_.get(), remove_predicate), std::move(callback)); } @@ -694,17 +687,16 @@ int64_t request_id, SavePageRequest::AutoFetchNotificationState state, base::OnceCallback<void(bool updated)> callback) { - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(SetAutoFetchNotificationStateSync, db_.get(), request_id, state), std::move(callback)); } void RequestQueueStore::Reset(ResetCallback callback) { - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(ResetSync, db_.get(), db_file_path_), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(ResetSync, db_.get(), db_file_path_), base::BindOnce(&RequestQueueStore::OnResetDone, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); }
diff --git a/components/offline_pages/task/sql_store_base.cc b/components/offline_pages/task/sql_store_base.cc index 07e05681..ad832b94 100644 --- a/components/offline_pages/task/sql_store_base.cc +++ b/components/offline_pages/task/sql_store_base.cc
@@ -12,7 +12,6 @@ #include "base/logging.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/trace_event/trace_event.h" namespace offline_pages { @@ -106,8 +105,8 @@ .cache_size = 500}), base::OnTaskRunnerDeleter(background_task_runner_)); - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&InitializeSync, db_.get(), db_file_path_, histogram_tag_, GetSchemaInitializationFunction()), base::BindOnce(&SqlStoreBase::InitializeDone,
diff --git a/components/offline_pages/task/sql_store_base.h b/components/offline_pages/task/sql_store_base.h index b3c6f31..a8ffc71 100644 --- a/components/offline_pages/task/sql_store_base.h +++ b/components/offline_pages/task/sql_store_base.h
@@ -15,7 +15,6 @@ #include "base/location.h" #include "base/memory/weak_ptr.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/time/time.h" #include "sql/database.h" @@ -135,9 +134,8 @@ base::BindOnce(std::move(result_callback), std::move(default_value))); return; } - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, - base::BindOnce(std::move(run_callback), db), + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(std::move(run_callback), db), base::BindOnce(&SqlStoreBase::RescheduleClosing<T>, weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
diff --git a/components/omnibox/browser/on_device_head_provider.cc b/components/omnibox/browser/on_device_head_provider.cc index 841ec4c7..4c19e65 100644 --- a/components/omnibox/browser/on_device_head_provider.cc +++ b/components/omnibox/browser/on_device_head_provider.cc
@@ -15,7 +15,6 @@ #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" @@ -222,8 +221,8 @@ return; } - base::PostTaskAndReplyWithResult( - worker_task_runner_.get(), FROM_HERE, + worker_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&OnDeviceHeadProvider::GetSuggestionsFromModel, GetOnDeviceHeadModelFilename(), provider_max_matches_, std::move(params)),
diff --git a/components/optimization_guide/core/optimization_guide_features.cc b/components/optimization_guide/core/optimization_guide_features.cc index 4f84c210..b1d55992 100644 --- a/components/optimization_guide/core/optimization_guide_features.cc +++ b/components/optimization_guide/core/optimization_guide_features.cc
@@ -198,6 +198,10 @@ "OptimizationGuideInstallWideModelStore", base::FEATURE_DISABLED_BY_DEFAULT); +BASE_FEATURE(kExtractRelatedSearchesFromPrefetchedZPSResponse, + "ExtractRelatedSearchesFromPrefetchedZPSResponse", + base::FEATURE_DISABLED_BY_DEFAULT); + // The default value here is a bit of a guess. // TODO(crbug/1163244): This should be tuned once metrics are available. base::TimeDelta PageTextExtractionOutstandingRequestsGracePeriod() {
diff --git a/components/optimization_guide/core/optimization_guide_features.h b/components/optimization_guide/core/optimization_guide_features.h index aca141a..63485f9a 100644 --- a/components/optimization_guide/core/optimization_guide_features.h +++ b/components/optimization_guide/core/optimization_guide_features.h
@@ -47,6 +47,7 @@ BASE_DECLARE_FEATURE(kRemotePageMetadata); BASE_DECLARE_FEATURE(kOptimizationHintsComponent); BASE_DECLARE_FEATURE(kOptimizationGuideInstallWideModelStore); +BASE_DECLARE_FEATURE(kExtractRelatedSearchesFromPrefetchedZPSResponse); // Enables use of task runner with trait CONTINUE_ON_SHUTDOWN for page content // annotations on-device models.
diff --git a/components/ownership/owner_settings_service.cc b/components/ownership/owner_settings_service.cc index 046e970..c19c7c2 100644 --- a/components/ownership/owner_settings_service.cc +++ b/components/ownership/owner_settings_service.cc
@@ -17,7 +17,6 @@ #include "base/logging.h" #include "base/task/single_thread_task_runner.h" #include "base/task/task_runner.h" -#include "base/task/task_runner_util.h" #include "base/values.h" #include "components/ownership/owner_key_util.h" #include "crypto/scoped_nss_types.h" @@ -136,8 +135,8 @@ // the key that was actually included in a policy gets marked as persisted // (theoretically a different key can be re-assigned to |public_key_| in // between the async calls). - return base::PostTaskAndReplyWithResult( - task_runner, FROM_HERE, + return task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&AssembleAndSignPolicy, std::move(policy), public_key_, private_key_), base::BindOnce(std::move(callback), public_key_));
diff --git a/components/password_manager/core/browser/export/password_manager_exporter.cc b/components/password_manager/core/browser/export/password_manager_exporter.cc index a2e062cf..6a2b088 100644 --- a/components/password_manager/core/browser/export/password_manager_exporter.cc +++ b/components/password_manager/core/browser/export/password_manager_exporter.cc
@@ -12,7 +12,6 @@ #include "base/location.h" #include "base/metrics/histogram_macros.h" #include "base/task/lazy_thread_pool_task_runner.h" -#include "base/task/task_runner_util.h" #include "build/build_config.h" #include "components/password_manager/core/browser/export/password_csv_writer.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" @@ -89,8 +88,8 @@ return credential.blocked_by_user; }); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&PasswordCSVWriter::SerializePasswords, credentials), base::BindOnce(&PasswordManagerExporter::SetSerialisedPasswordList, weak_factory_.GetWeakPtr(), credentials.size())); @@ -160,8 +159,8 @@ return; } - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(DoWriteOnTaskRunner, write_function_, set_permissions_function_, destination_, std::move(serialised_password_list_)),
diff --git a/components/performance_manager/performance_manager_impl.h b/components/performance_manager/performance_manager_impl.h index 2536ded1..dec2bcc 100644 --- a/components/performance_manager/performance_manager_impl.h +++ b/components/performance_manager/performance_manager_impl.h
@@ -15,7 +15,6 @@ #include "base/location.h" #include "base/sequence_checker.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "components/performance_manager/graph/graph_impl.h" #include "components/performance_manager/public/graph/frame_node.h" #include "components/performance_manager/public/graph/page_node.h" @@ -196,8 +195,8 @@ const base::Location& from_here, base::OnceCallback<TaskReturnType(GraphImpl*)> task, base::OnceCallback<void(TaskReturnType)> reply) { - base::PostTaskAndReplyWithResult( - GetTaskRunner().get(), from_here, + GetTaskRunner()->PostTaskAndReplyWithResult( + from_here, base::BindOnce( &PerformanceManagerImpl::RunCallbackWithGraphAndReplyWithResult< TaskReturnType>,
diff --git a/components/performance_manager/persistence/site_data/leveldb_site_data_store.cc b/components/performance_manager/persistence/site_data/leveldb_site_data_store.cc index 775d7c6..50e6e2e 100644 --- a/components/performance_manager/persistence/site_data/leveldb_site_data_store.cc +++ b/components/performance_manager/persistence/site_data/leveldb_site_data_store.cc
@@ -18,7 +18,6 @@ #include "base/metrics/histogram_macros.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "build/build_config.h" @@ -455,8 +454,8 @@ // Trigger the asynchronous task and make it run the callback on this thread // once it returns. - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LevelDBSiteDataStore::AsyncHelper::ReadSiteDataFromDB, base::Unretained(async_helper_.get()), origin), std::move(callback)); @@ -501,8 +500,8 @@ }, std::move(callback)); - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LevelDBSiteDataStore::AsyncHelper::GetDatabaseSize, base::Unretained(async_helper_.get())), std::move(reply_callback));
diff --git a/components/policy/core/browser/url_blocklist_manager.cc b/components/policy/core/browser/url_blocklist_manager.cc index f7a42811..d9533712 100644 --- a/components/policy/core/browser/url_blocklist_manager.cc +++ b/components/policy/core/browser/url_blocklist_manager.cc
@@ -19,7 +19,6 @@ #include "base/strings/string_util.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/values.h" #include "build/build_config.h" @@ -269,8 +268,8 @@ GetPrefList(pref_service_, blocklist_pref_path_); const base::Value::List* allow = GetPrefList(pref_service_, allowlist_pref_path_); - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &BuildBlocklist, base::Owned(block
diff --git a/components/policy/core/common/cloud/user_cloud_policy_store.cc b/components/policy/core/common/cloud/user_cloud_policy_store.cc index 010038d..d735684f 100644 --- a/components/policy/core/common/cloud/user_cloud_policy_store.cc +++ b/components/policy/core/common/cloud/user_cloud_policy_store.cc
@@ -16,7 +16,6 @@ #include "base/metrics/histogram_macros.h" #include "base/sequence_checker.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/proto/cloud_policy.pb.h" #include "components/policy/proto/device_management_backend.pb.h" @@ -142,8 +141,8 @@ // Start a new Load operation and have us get called back when it is // complete. - base::PostTaskAndReplyWithResult( - background_task_runner().get(), FROM_HERE, + background_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DesktopCloudPolicyStore::LoadAndFilterPolicyFromDisk, policy_path_, key_path_, policy_load_filter_), base::BindOnce(&DesktopCloudPolicyStore::PolicyLoaded,
diff --git a/components/power_bookmarks/OWNERS b/components/power_bookmarks/OWNERS index cce381c..bda0509 100644 --- a/components/power_bookmarks/OWNERS +++ b/components/power_bookmarks/OWNERS
@@ -1,3 +1,2 @@ -fgorski@chromium.org mdjones@chromium.org wylieb@chromium.org
diff --git a/components/prefs/json_pref_store.cc b/components/prefs/json_pref_store.cc index bf57a663..d971184 100644 --- a/components/prefs/json_pref_store.cc +++ b/components/prefs/json_pref_store.cc
@@ -27,7 +27,6 @@ #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/time/default_clock.h" #include "base/values.h" #include "components/prefs/pref_filter.h" @@ -317,9 +316,8 @@ error_delegate_.reset(error_delegate); // Weakly binds the read task so that it doesn't kick in during shutdown. - base::PostTaskAndReplyWithResult( - file_task_runner_.get(), FROM_HERE, - base::BindOnce(&ReadPrefsFromDisk, path_), + file_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadPrefsFromDisk, path_), base::BindOnce(&JsonPrefStore::OnFileRead, AsWeakPtr())); }
diff --git a/components/quirks/quirks_client.cc b/components/quirks/quirks_client.cc index 52638028..543e251 100644 --- a/components/quirks/quirks_client.cc +++ b/components/quirks/quirks_client.cc
@@ -10,7 +10,6 @@ #include "base/json/json_reader.h" #include "base/strings/escape.h" #include "base/strings/stringprintf.h" -#include "base/task/task_runner_util.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/quirks/quirks_manager.h" #include "components/version_info/version_info.h" @@ -164,9 +163,8 @@ return; } - base::PostTaskAndReplyWithResult( - manager_->task_runner(), FROM_HERE, - base::BindOnce(&WriteIccFile, icc_path_, data), + manager_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&WriteIccFile, icc_path_, data), base::BindOnce(&QuirksClient::Shutdown, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/components/quirks/quirks_manager.cc b/components/quirks/quirks_manager.cc index 9cc3fd3..7ca78efa 100644 --- a/components/quirks/quirks_manager.cc +++ b/components/quirks/quirks_manager.cc
@@ -13,7 +13,6 @@ #include "base/path_service.h" #include "base/strings/stringprintf.h" #include "base/task/task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "components/prefs/pref_registry_simple.h" @@ -135,8 +134,8 @@ } std::string name = IdToFileName(product_id); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CheckForIccFile, delegate_->GetDisplayProfileDirectory().Append(name)), base::BindOnce(&QuirksManager::OnIccFilePathRequestCompleted,
diff --git a/components/reporting/metrics/BUILD.gn b/components/reporting/metrics/BUILD.gn index d918aed..c7319cfe 100644 --- a/components/reporting/metrics/BUILD.gn +++ b/components/reporting/metrics/BUILD.gn
@@ -6,9 +6,7 @@ sources = [ "collector_base.cc", "collector_base.h", - "configured_sampler.cc", - "configured_sampler.h", - "event_driven_telemetry_sampler_pool.h", + "event_driven_telemetry_collector_pool.h", "metric_event_observer.h", "metric_event_observer_manager.cc", "metric_event_observer_manager.h", @@ -18,8 +16,6 @@ "metric_report_queue.h", "metric_reporting_controller.cc", "metric_reporting_controller.h", - "multi_samplers_collector.cc", - "multi_samplers_collector.h", "one_shot_collector.cc", "one_shot_collector.h", "periodic_collector.cc", @@ -41,12 +37,10 @@ source_set("unit_tests") { testonly = true sources = [ - "configured_sampler_unittest.cc", "metric_event_observer_manager_unittest.cc", "metric_rate_controller_unittest.cc", "metric_report_queue_unittest.cc", "metric_reporting_controller_unittest.cc", - "multi_samplers_collector_unittest.cc", "one_shot_collector_unittest.cc", "periodic_collector_unittest.cc", "periodic_event_collector_unittest.cc",
diff --git a/components/reporting/metrics/collector_base.cc b/components/reporting/metrics/collector_base.cc index d0e72a5..2053158 100644 --- a/components/reporting/metrics/collector_base.cc +++ b/components/reporting/metrics/collector_base.cc
@@ -21,12 +21,17 @@ CheckOnSequence(); } -void CollectorBase::Collect() { +void CollectorBase::Collect(bool is_event_driven) { DCHECK(base::SequencedTaskRunner::HasCurrentDefault()); CheckOnSequence(); - auto on_collected_cb = base::BindOnce(&CollectorBase::OnMetricDataCollected, - weak_ptr_factory_.GetWeakPtr()); + if (!CanCollect()) { + return; + } + + auto on_collected_cb = + base::BindOnce(&CollectorBase::OnMetricDataCollected, + weak_ptr_factory_.GetWeakPtr(), is_event_driven); sampler_->MaybeCollect( base::BindPostTask(base::SequencedTaskRunner::GetCurrentDefault(), std::move(on_collected_cb)));
diff --git a/components/reporting/metrics/collector_base.h b/components/reporting/metrics/collector_base.h index 166cce2..84d86281a 100644 --- a/components/reporting/metrics/collector_base.h +++ b/components/reporting/metrics/collector_base.h
@@ -25,16 +25,19 @@ virtual ~CollectorBase(); - protected: // Collect metric data provided by `sampler_` asynchronously. - virtual void Collect(); + virtual void Collect(bool is_event_driven); + protected: // Callback executed when metric data is collected. virtual void OnMetricDataCollected( + bool is_event_driven, absl::optional<MetricData> metric_data) = 0; void CheckOnSequence() const; + virtual bool CanCollect() const = 0; + private: SEQUENCE_CHECKER(sequence_checker_);
diff --git a/components/reporting/metrics/configured_sampler.cc b/components/reporting/metrics/configured_sampler.cc deleted file mode 100644 index 6d3e92b..0000000 --- a/components/reporting/metrics/configured_sampler.cc +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/reporting/metrics/configured_sampler.h" - -#include <memory> -#include <string> -#include <utility> - -#include "base/callback_helpers.h" -#include "base/strings/string_piece.h" -#include "components/reporting/metrics/reporting_settings.h" -#include "components/reporting/metrics/sampler.h" - -namespace reporting { - -ConfiguredSampler::ConfiguredSampler(std::unique_ptr<Sampler> sampler, - base::StringPiece enable_setting_path, - bool setting_enabled_default_value, - ReportingSettings* reporting_settings) - : sampler_(std::move(sampler)), - enable_setting_path_(enable_setting_path), - setting_enabled_default_value_(setting_enabled_default_value), - reporting_settings_(reporting_settings) {} - -ConfiguredSampler::~ConfiguredSampler() = default; - -Sampler* ConfiguredSampler::GetSampler() const { - return sampler_.get(); -} - -const std::string& ConfiguredSampler::GetEnableSettingPath() const { - return enable_setting_path_; -} - -bool ConfiguredSampler::GetSettingEnabledDefaultValue() const { - return setting_enabled_default_value_; -} - -bool ConfiguredSampler::IsReportingEnabled() const { - bool enabled = setting_enabled_default_value_; - if (reporting_settings_->PrepareTrustedValues(base::DoNothing())) { - reporting_settings_->GetBoolean(enable_setting_path_, &enabled); - } - return enabled; -} - -} // namespace reporting
diff --git a/components/reporting/metrics/configured_sampler.h b/components/reporting/metrics/configured_sampler.h deleted file mode 100644 index 0682ca7..0000000 --- a/components/reporting/metrics/configured_sampler.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_REPORTING_METRICS_CONFIGURED_SAMPLER_H_ -#define COMPONENTS_REPORTING_METRICS_CONFIGURED_SAMPLER_H_ - -#include <memory> -#include <string> - -#include "base/memory/raw_ptr.h" -#include "base/strings/string_piece_forward.h" -#include "components/reporting/metrics/sampler.h" - -namespace reporting { - -class ReportingSettings; - -// Class to access a Sampler intsance along with its enabling setting path and -// default value. -class ConfiguredSampler { - public: - ConfiguredSampler(std::unique_ptr<Sampler> sampler, - base::StringPiece enable_setting_path, - bool setting_enabled_default_value, - ReportingSettings* reporting_settings); - - ConfiguredSampler(const ConfiguredSampler& other) = delete; - ConfiguredSampler& operator=(const ConfiguredSampler& other) = delete; - - ~ConfiguredSampler(); - - // Return raw pointer to the sampler, ConfiguredSampler should outlive the - // consumer. - Sampler* GetSampler() const; - - // Get reporting setting path for the sampler, ConfiguredSampler should - // outlive the consumer. - const std::string& GetEnableSettingPath() const; - - // Get reporting setting default value if the setting is not set. - bool GetSettingEnabledDefaultValue() const; - - bool IsReportingEnabled() const; - - private: - const std::unique_ptr<Sampler> sampler_; - const std::string enable_setting_path_; - bool setting_enabled_default_value_; - raw_ptr<ReportingSettings> reporting_settings_; -}; - -} // namespace reporting - -#endif // COMPONENTS_REPORTING_METRICS_CONFIGURED_SAMPLER_H_
diff --git a/components/reporting/metrics/configured_sampler_unittest.cc b/components/reporting/metrics/configured_sampler_unittest.cc deleted file mode 100644 index cf916b3..0000000 --- a/components/reporting/metrics/configured_sampler_unittest.cc +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/reporting/metrics/configured_sampler.h" - -#include <memory> -#include <string> -#include <utility> - -#include "base/strings/string_piece.h" -#include "base/test/task_environment.h" -#include "components/reporting/metrics/fakes/fake_reporting_settings.h" -#include "components/reporting/metrics/fakes/fake_sampler.h" -#include "components/reporting/metrics/sampler.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace reporting { -namespace { - -TEST(ConfiguredSamplerTest, Default) { - base::test::SingleThreadTaskEnvironment task_environment; - - static constexpr char enable_setting_path[] = "path"; - std::unique_ptr<Sampler> sampler = std::make_unique<test::FakeSampler>(); - auto* const sampler_ptr = sampler.get(); - test::FakeReportingSettings reporting_settings; - - ConfiguredSampler configured_sampler(std::move(sampler), enable_setting_path, - /*setting_enabled_default_value=*/true, - &reporting_settings); - - EXPECT_THAT(configured_sampler.GetSampler(), testing::Eq(sampler_ptr)); - EXPECT_THAT(configured_sampler.GetEnableSettingPath(), - testing::StrEq(enable_setting_path)); - EXPECT_TRUE(configured_sampler.GetSettingEnabledDefaultValue()); - - // Setting path does not exist, reporting enabled should be - // `setting_enabled_default_value`. - EXPECT_TRUE(configured_sampler.IsReportingEnabled()); - - reporting_settings.SetBoolean(enable_setting_path, false); - reporting_settings.SetIsTrusted(false); - // Setting is set but settings are not trusted, reporting enabled should be - // `setting_enabled_default_value`. - EXPECT_TRUE(configured_sampler.IsReportingEnabled()); - - reporting_settings.SetIsTrusted(true); - // Setting is set and trusted, reporting enabled should be the setting actual - // value. - EXPECT_FALSE(configured_sampler.IsReportingEnabled()); - reporting_settings.SetBoolean(enable_setting_path, true); - EXPECT_TRUE(configured_sampler.IsReportingEnabled()); -} - -} // namespace -} // namespace reporting
diff --git a/components/reporting/metrics/event_driven_telemetry_collector_pool.h b/components/reporting/metrics/event_driven_telemetry_collector_pool.h new file mode 100644 index 0000000..49350945 --- /dev/null +++ b/components/reporting/metrics/event_driven_telemetry_collector_pool.h
@@ -0,0 +1,27 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_REPORTING_METRICS_EVENT_DRIVEN_TELEMETRY_COLLECTOR_POOL_H_ +#define COMPONENTS_REPORTING_METRICS_EVENT_DRIVEN_TELEMETRY_COLLECTOR_POOL_H_ + +#include <vector> + +#include "components/reporting/metrics/collector_base.h" +#include "components/reporting/proto/synced/metric_data.pb.h" + +namespace reporting { + +// Interface for fetching collectors to collect telemetry data on event. +class EventDrivenTelemetryCollectorPool { + public: + virtual ~EventDrivenTelemetryCollectorPool() = default; + + // Get the telemetry collectors associated with `event_type`. + virtual std::vector<CollectorBase*> GetTelemetryCollectors( + MetricEventType event_type) = 0; +}; + +} // namespace reporting + +#endif // COMPONENTS_REPORTING_METRICS_EVENT_DRIVEN_TELEMETRY_COLLECTOR_POOL_H_
diff --git a/components/reporting/metrics/event_driven_telemetry_sampler_pool.h b/components/reporting/metrics/event_driven_telemetry_sampler_pool.h deleted file mode 100644 index ffdc01dd..0000000 --- a/components/reporting/metrics/event_driven_telemetry_sampler_pool.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_REPORTING_METRICS_EVENT_DRIVEN_TELEMETRY_SAMPLER_POOL_H_ -#define COMPONENTS_REPORTING_METRICS_EVENT_DRIVEN_TELEMETRY_SAMPLER_POOL_H_ - -#include <vector> - -#include "components/reporting/metrics/configured_sampler.h" -#include "components/reporting/proto/synced/metric_data.pb.h" - -namespace reporting { - -// Base class for fetching samplers to collect telemetry data on event. -class EventDrivenTelemetrySamplerPool { - public: - virtual ~EventDrivenTelemetrySamplerPool() = default; - - // Get the configured telemetry samplers associated with `event_type`. - virtual std::vector<ConfiguredSampler*> GetTelemetrySamplers( - MetricEventType event_type) = 0; -}; - -} // namespace reporting - -#endif // COMPONENTS_REPORTING_METRICS_EVENT_DRIVEN_TELEMETRY_SAMPLER_POOL_H_
diff --git a/components/reporting/metrics/fakes/BUILD.gn b/components/reporting/metrics/fakes/BUILD.gn index b5b7cd12..cddc93e 100644 --- a/components/reporting/metrics/fakes/BUILD.gn +++ b/components/reporting/metrics/fakes/BUILD.gn
@@ -5,8 +5,8 @@ static_library("test_support") { testonly = true sources = [ - "fake_event_driven_telemetry_sampler_pool.cc", - "fake_event_driven_telemetry_sampler_pool.h", + "fake_event_driven_telemetry_collector_pool.cc", + "fake_event_driven_telemetry_collector_pool.h", "fake_metric_event_observer.cc", "fake_metric_event_observer.h", "fake_metric_report_queue.cc",
diff --git a/components/reporting/metrics/fakes/fake_event_driven_telemetry_collector_pool.cc b/components/reporting/metrics/fakes/fake_event_driven_telemetry_collector_pool.cc new file mode 100644 index 0000000..553e8a7 --- /dev/null +++ b/components/reporting/metrics/fakes/fake_event_driven_telemetry_collector_pool.cc
@@ -0,0 +1,32 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/reporting/metrics/fakes/fake_event_driven_telemetry_collector_pool.h" + +#include <vector> + +#include "components/reporting/metrics/collector_base.h" +#include "components/reporting/proto/synced/metric_data.pb.h" + +namespace reporting::test { + +FakeEventDrivenTelemetryCollectorPool::FakeEventDrivenTelemetryCollectorPool() = + default; + +FakeEventDrivenTelemetryCollectorPool:: + ~FakeEventDrivenTelemetryCollectorPool() = default; + +std::vector<CollectorBase*> +FakeEventDrivenTelemetryCollectorPool::GetTelemetryCollectors( + MetricEventType event_type) { + return event_telemetry_map_.at(event_type); +} + +void FakeEventDrivenTelemetryCollectorPool::AddEventTelemetryCollector( + MetricEventType event_type, + CollectorBase* collector) { + event_telemetry_map_[event_type].push_back(collector); +} + +} // namespace reporting::test
diff --git a/components/reporting/metrics/fakes/fake_event_driven_telemetry_collector_pool.h b/components/reporting/metrics/fakes/fake_event_driven_telemetry_collector_pool.h new file mode 100644 index 0000000..878a437 --- /dev/null +++ b/components/reporting/metrics/fakes/fake_event_driven_telemetry_collector_pool.h
@@ -0,0 +1,43 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_REPORTING_METRICS_FAKES_FAKE_EVENT_DRIVEN_TELEMETRY_COLLECTOR_POOL_H_ +#define COMPONENTS_REPORTING_METRICS_FAKES_FAKE_EVENT_DRIVEN_TELEMETRY_COLLECTOR_POOL_H_ + +#include <vector> + +#include "base/containers/flat_map.h" +#include "components/reporting/metrics/collector_base.h" +#include "components/reporting/metrics/event_driven_telemetry_collector_pool.h" +#include "components/reporting/proto/synced/metric_data.pb.h" + +namespace reporting::test { + +class FakeEventDrivenTelemetryCollectorPool + : public EventDrivenTelemetryCollectorPool { + public: + FakeEventDrivenTelemetryCollectorPool(); + + FakeEventDrivenTelemetryCollectorPool( + const FakeEventDrivenTelemetryCollectorPool& other) = delete; + FakeEventDrivenTelemetryCollectorPool& operator=( + const FakeEventDrivenTelemetryCollectorPool& other) = delete; + + ~FakeEventDrivenTelemetryCollectorPool() override; + + // EventDrivenTelemetryCollectorPool: + std::vector<CollectorBase*> GetTelemetryCollectors( + MetricEventType event_type) override; + + void AddEventTelemetryCollector(MetricEventType event_type, + CollectorBase* collector); + + private: + base::flat_map<MetricEventType, std::vector<CollectorBase*>> + event_telemetry_map_; +}; + +} // namespace reporting::test + +#endif // COMPONENTS_REPORTING_METRICS_FAKES_FAKE_EVENT_DRIVEN_TELEMETRY_COLLECTOR_POOL_H_
diff --git a/components/reporting/metrics/fakes/fake_event_driven_telemetry_sampler_pool.cc b/components/reporting/metrics/fakes/fake_event_driven_telemetry_sampler_pool.cc deleted file mode 100644 index 2263813..0000000 --- a/components/reporting/metrics/fakes/fake_event_driven_telemetry_sampler_pool.cc +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/reporting/metrics/fakes/fake_event_driven_telemetry_sampler_pool.h" - -#include <vector> - -#include "base/containers/flat_map.h" -#include "components/reporting/metrics/configured_sampler.h" -#include "components/reporting/proto/synced/metric_data.pb.h" - -namespace reporting::test { - -FakeEventDrivenTelemetrySamplerPool::FakeEventDrivenTelemetrySamplerPool() = - default; - -FakeEventDrivenTelemetrySamplerPool::~FakeEventDrivenTelemetrySamplerPool() = - default; - -std::vector<ConfiguredSampler*> -FakeEventDrivenTelemetrySamplerPool::GetTelemetrySamplers( - MetricEventType event_type) { - return event_telemetry_map.at(event_type); -} - -void FakeEventDrivenTelemetrySamplerPool::AddEventSampler( - MetricEventType event_type, - ConfiguredSampler* configured_sampler) { - event_telemetry_map[event_type].push_back(configured_sampler); -} - -} // namespace reporting::test
diff --git a/components/reporting/metrics/fakes/fake_event_driven_telemetry_sampler_pool.h b/components/reporting/metrics/fakes/fake_event_driven_telemetry_sampler_pool.h deleted file mode 100644 index bf46837..0000000 --- a/components/reporting/metrics/fakes/fake_event_driven_telemetry_sampler_pool.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_REPORTING_METRICS_FAKES_FAKE_EVENT_DRIVEN_TELEMETRY_SAMPLER_POOL_H_ -#define COMPONENTS_REPORTING_METRICS_FAKES_FAKE_EVENT_DRIVEN_TELEMETRY_SAMPLER_POOL_H_ - -#include <vector> - -#include "base/containers/flat_map.h" -#include "components/reporting/metrics/configured_sampler.h" -#include "components/reporting/metrics/event_driven_telemetry_sampler_pool.h" -#include "components/reporting/proto/synced/metric_data.pb.h" - -namespace reporting::test { - -class FakeEventDrivenTelemetrySamplerPool - : public EventDrivenTelemetrySamplerPool { - public: - FakeEventDrivenTelemetrySamplerPool(); - - FakeEventDrivenTelemetrySamplerPool( - const FakeEventDrivenTelemetrySamplerPool& other) = delete; - FakeEventDrivenTelemetrySamplerPool& operator=( - const FakeEventDrivenTelemetrySamplerPool& other) = delete; - - ~FakeEventDrivenTelemetrySamplerPool() override; - - // EventDrivenTelemetrySamplerPool: - std::vector<ConfiguredSampler*> GetTelemetrySamplers( - MetricEventType event_type) override; - - void AddEventSampler(MetricEventType event_type, - ConfiguredSampler* configured_sampler); - - private: - base::flat_map<MetricEventType, std::vector<ConfiguredSampler*>> - event_telemetry_map; -}; - -} // namespace reporting::test - -#endif // COMPONENTS_REPORTING_METRICS_FAKES_FAKE_EVENT_DRIVEN_TELEMETRY_SAMPLER_POOL_H_
diff --git a/components/reporting/metrics/metric_event_observer_manager.cc b/components/reporting/metrics/metric_event_observer_manager.cc index feb89cf..43c066e 100644 --- a/components/reporting/metrics/metric_event_observer_manager.cc +++ b/components/reporting/metrics/metric_event_observer_manager.cc
@@ -13,14 +13,13 @@ #include "base/task/bind_post_task.h" #include "base/task/sequenced_task_runner.h" #include "base/time/time.h" -#include "components/reporting/metrics/configured_sampler.h" -#include "components/reporting/metrics/event_driven_telemetry_sampler_pool.h" +#include "components/reporting/metrics/collector_base.h" +#include "components/reporting/metrics/event_driven_telemetry_collector_pool.h" #include "components/reporting/metrics/metric_event_observer.h" #include "components/reporting/metrics/metric_report_queue.h" #include "components/reporting/metrics/metric_reporting_controller.h" -#include "components/reporting/metrics/multi_samplers_collector.h" #include "components/reporting/metrics/reporting_settings.h" -#include "components/reporting/metrics/sampler.h" +#include "components/reporting/proto/synced/metric_data.pb.h" namespace reporting { @@ -30,11 +29,11 @@ ReportingSettings* reporting_settings, const std::string& enable_setting_path, bool setting_enabled_default_value, - EventDrivenTelemetrySamplerPool* sampler_pool, + EventDrivenTelemetryCollectorPool* collector_pool, base::TimeDelta init_delay) : event_observer_(std::move(event_observer)), metric_report_queue_(metric_report_queue), - sampler_pool_(sampler_pool) { + collector_pool_(collector_pool) { CHECK(base::SequencedTaskRunner::HasCurrentDefault()); DETACH_FROM_SEQUENCE(sequence_checker_); @@ -86,30 +85,16 @@ if (!is_reporting_enabled_) { return; } - + MetricEventType event_type = metric_data.event_data().type(); metric_data.set_timestamp_ms(base::Time::Now().ToJavaTime()); - - std::vector<ConfiguredSampler*> telemetry_samplers; - if (sampler_pool_) { - telemetry_samplers = - sampler_pool_->GetTelemetrySamplers(metric_data.event_data().type()); - } - auto collect_cb = - base::BindOnce(&MetricEventObserverManager::MergeAndReport, - weak_ptr_factory_.GetWeakPtr(), std::move(metric_data)); - MultiSamplersCollector::CollectAll(telemetry_samplers, std::move(collect_cb)); -} - -void MetricEventObserverManager::MergeAndReport( - MetricData event_data, - absl::optional<MetricData> telemetry_data) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - MetricData metric_data = std::move(event_data); - if (telemetry_data.has_value()) { - metric_data.CheckTypeAndMergeFrom(telemetry_data.value()); - } - metric_report_queue_->Enqueue(std::move(metric_data)); + + if (collector_pool_) { + std::vector<CollectorBase*> telemetry_collectors = + collector_pool_->GetTelemetryCollectors(event_type); + for (auto* telemetry_collector : telemetry_collectors) { + telemetry_collector->Collect(/*is_event_driven=*/true); + } + } } } // namespace reporting
diff --git a/components/reporting/metrics/metric_event_observer_manager.h b/components/reporting/metrics/metric_event_observer_manager.h index 4f2f8cf..eb9c31b 100644 --- a/components/reporting/metrics/metric_event_observer_manager.h +++ b/components/reporting/metrics/metric_event_observer_manager.h
@@ -9,7 +9,6 @@ #include <string> #include <vector> -#include "base/callback.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" @@ -18,7 +17,7 @@ namespace reporting { -class EventDrivenTelemetrySamplerPool; +class EventDrivenTelemetryCollectorPool; class MetricData; class MetricEventObserver; class MetricReportingController; @@ -34,7 +33,7 @@ ReportingSettings* reporting_settings, const std::string& enable_setting_path, bool setting_enabled_default_value, - EventDrivenTelemetrySamplerPool* sampler_pool, + EventDrivenTelemetryCollectorPool* collector_pool, base::TimeDelta init_delay = base::TimeDelta()); MetricEventObserverManager(const MetricEventObserverManager& other) = delete; @@ -50,14 +49,11 @@ void OnEventObserved(MetricData metric_data); - void MergeAndReport(MetricData event_metric_data, - absl::optional<MetricData> telemetry_metric_data); - const std::unique_ptr<MetricEventObserver> event_observer_; const raw_ptr<MetricReportQueue> metric_report_queue_; - const raw_ptr<EventDrivenTelemetrySamplerPool> sampler_pool_; + const raw_ptr<EventDrivenTelemetryCollectorPool> collector_pool_; std::unique_ptr<MetricReportingController> reporting_controller_;
diff --git a/components/reporting/metrics/metric_event_observer_manager_unittest.cc b/components/reporting/metrics/metric_event_observer_manager_unittest.cc index 237a43b..bd692fd9 100644 --- a/components/reporting/metrics/metric_event_observer_manager_unittest.cc +++ b/components/reporting/metrics/metric_event_observer_manager_unittest.cc
@@ -12,31 +12,53 @@ #include "base/test/task_environment.h" #include "base/time/time.h" -#include "components/reporting/metrics/configured_sampler.h" -#include "components/reporting/metrics/fakes/fake_event_driven_telemetry_sampler_pool.h" +#include "components/reporting/metrics/collector_base.h" +#include "components/reporting/metrics/fakes/fake_event_driven_telemetry_collector_pool.h" #include "components/reporting/metrics/fakes/fake_metric_event_observer.h" #include "components/reporting/metrics/fakes/fake_metric_report_queue.h" #include "components/reporting/metrics/fakes/fake_reporting_settings.h" -#include "components/reporting/metrics/fakes/fake_sampler.h" #include "components/reporting/proto/synced/metric_data.pb.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" +using ::testing::_; +using ::testing::Eq; + namespace reporting { namespace { constexpr char kEventEnableSettingPath[] = "event_enable_path"; constexpr base::TimeDelta init_delay = base::Minutes(1); +class MockCollector : public CollectorBase { + public: + MockCollector() : CollectorBase(/*sampler=*/nullptr) {} + + MockCollector(const MockCollector& other) = delete; + MockCollector& operator=(const MockCollector& other) = delete; + + ~MockCollector() override = default; + + MOCK_METHOD(void, Collect, (bool), (override)); + + protected: + MOCK_METHOD(void, + OnMetricDataCollected, + (bool, absl::optional<MetricData>), + (override)); + + MOCK_METHOD(bool, CanCollect, (), (const override)); +}; + class MetricEventObserverManagerTest : public ::testing::Test { public: void SetUp() override { settings_ = std::make_unique<test::FakeReportingSettings>(); event_observer_ = std::make_unique<test::FakeMetricEventObserver>(); metric_report_queue_ = std::make_unique<test::FakeMetricReportQueue>(); - sampler_pool_ = - std::make_unique<test::FakeEventDrivenTelemetrySamplerPool>(); + collector_pool_ = + std::make_unique<test::FakeEventDrivenTelemetryCollectorPool>(); } protected: @@ -46,7 +68,7 @@ std::unique_ptr<test::FakeReportingSettings> settings_; std::unique_ptr<test::FakeMetricEventObserver> event_observer_; std::unique_ptr<test::FakeMetricReportQueue> metric_report_queue_; - std::unique_ptr<test::FakeEventDrivenTelemetrySamplerPool> sampler_pool_; + std::unique_ptr<test::FakeEventDrivenTelemetryCollectorPool> collector_pool_; }; TEST_F(MetricEventObserverManagerTest, InitiallyEnabled) { @@ -56,7 +78,7 @@ MetricEventObserverManager event_manager( std::move(event_observer_), metric_report_queue_.get(), settings_.get(), kEventEnableSettingPath, /*setting_enabled_default_value=*/false, - /*sampler_pool=*/nullptr); + /*collector_pool=*/nullptr); MetricData metric_data; metric_data.mutable_event_data(); @@ -162,7 +184,7 @@ MetricEventObserverManager event_manager( std::move(event_observer_), metric_report_queue_.get(), settings_.get(), kEventEnableSettingPath, /*setting_enabled_default_value=*/false, - /*sampler_pool=*/nullptr); + /*collector_pool=*/nullptr); MetricData metric_data; metric_data.mutable_event_data(); @@ -189,7 +211,7 @@ MetricEventObserverManager event_manager( std::move(event_observer_), metric_report_queue_.get(), settings_.get(), "invalid/path", /*setting_enabled_default_value=*/true, - /*sampler_pool=*/nullptr); + /*collector_pool=*/nullptr); MetricData metric_data; metric_data.mutable_event_data(); @@ -210,7 +232,7 @@ MetricEventObserverManager event_manager( std::move(event_observer_), metric_report_queue_.get(), settings_.get(), "invalid/path", /*setting_enabled_default_value=*/false, - /*sampler_pool=*/nullptr); + /*collector_pool=*/nullptr); MetricData metric_data; metric_data.mutable_event_data(); @@ -224,41 +246,34 @@ TEST_F(MetricEventObserverManagerTest, EventDrivenTelemetry) { settings_->SetBoolean(kEventEnableSettingPath, true); auto* event_observer_ptr = event_observer_.get(); + MetricEventType network_event = + MetricEventType::NETWORK_CONNECTION_STATE_CHANGE; - std::vector<std::string> telemetry_paths = {"path1", "path2", "path3"}; - std::vector<std::unique_ptr<ConfiguredSampler>> configured_samplers; - MetricData telemetry_data[3]; - - telemetry_data[0].mutable_telemetry_data()->mutable_audio_telemetry(); - telemetry_data[1].mutable_telemetry_data()->mutable_peripherals_telemetry(); - telemetry_data[2].mutable_telemetry_data()->mutable_networks_telemetry(); - - for (size_t i = 0; i < telemetry_paths.size(); ++i) { - auto sampler = std::make_unique<test::FakeSampler>(); - sampler->SetMetricData(std::move(telemetry_data[i])); - configured_samplers.push_back(std::make_unique<ConfiguredSampler>( - std::move(sampler), telemetry_paths[i], - /*setting_enabled_default_value=*/false, settings_.get())); - sampler_pool_->AddEventSampler( - MetricEventType::NETWORK_CONNECTION_STATE_CHANGE, - configured_samplers.at(i).get()); - } - settings_->SetBoolean(telemetry_paths[0], true); - // Disable second sampler collection. - settings_->SetBoolean(telemetry_paths[1], false); - settings_->SetBoolean(telemetry_paths[2], true); - + MockCollector network_collector1; + MockCollector network_collector2; + MockCollector usb_collector; + collector_pool_->AddEventTelemetryCollector(network_event, + &network_collector1); + collector_pool_->AddEventTelemetryCollector(network_event, + &network_collector2); + collector_pool_->AddEventTelemetryCollector(MetricEventType::USB_ADDED, + &usb_collector); MetricEventObserverManager event_manager( std::move(event_observer_), metric_report_queue_.get(), settings_.get(), kEventEnableSettingPath, - /*setting_enabled_default_value=*/false, sampler_pool_.get()); + /*setting_enabled_default_value=*/false, collector_pool_.get()); MetricData event_metric_data; - event_metric_data.mutable_event_data()->set_type( - MetricEventType::NETWORK_CONNECTION_STATE_CHANGE); + event_metric_data.mutable_event_data()->set_type(network_event); ASSERT_TRUE(event_observer_ptr->GetReportingEnabled()); + EXPECT_CALL(network_collector1, Collect(_)) + .WillOnce([](bool is_event_driven) { ASSERT_TRUE(is_event_driven); }); + EXPECT_CALL(network_collector2, Collect(_)) + .WillOnce([](bool is_event_driven) { ASSERT_TRUE(is_event_driven); }); + EXPECT_CALL(usb_collector, Collect(_)).Times(0); + event_observer_ptr->RunCallback(std::move(event_metric_data)); task_environment_.RunUntilIdle(); @@ -267,11 +282,7 @@ EXPECT_TRUE(metric_data_reported.has_timestamp_ms()); EXPECT_TRUE(metric_data_reported.has_event_data()); - ASSERT_TRUE(metric_data_reported.has_telemetry_data()); - EXPECT_TRUE(metric_data_reported.telemetry_data().has_audio_telemetry()); - EXPECT_FALSE( - metric_data_reported.telemetry_data().has_peripherals_telemetry()); - EXPECT_TRUE(metric_data_reported.telemetry_data().has_networks_telemetry()); + EXPECT_THAT(metric_data_reported.event_data().type(), Eq(network_event)); EXPECT_TRUE(metric_report_queue_->IsEmpty()); }
diff --git a/components/reporting/metrics/metric_reporting_controller.cc b/components/reporting/metrics/metric_reporting_controller.cc index 84b2dba..07582145 100644 --- a/components/reporting/metrics/metric_reporting_controller.cc +++ b/components/reporting/metrics/metric_reporting_controller.cc
@@ -32,6 +32,11 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } +bool MetricReportingController::IsEnabled() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return setting_enabled_; +} + void MetricReportingController::SetSettingUpdateCb( base::RepeatingClosure on_setting_enabled, base::RepeatingClosure on_setting_disabled) {
diff --git a/components/reporting/metrics/metric_reporting_controller.h b/components/reporting/metrics/metric_reporting_controller.h index 41614990..52a4db25 100644 --- a/components/reporting/metrics/metric_reporting_controller.h +++ b/components/reporting/metrics/metric_reporting_controller.h
@@ -32,6 +32,9 @@ ~MetricReportingController(); + // Whether reporting is currently enabled. + bool IsEnabled() const; + // When called, `on_setting_enabled` will run if the setting is enabled and // nothing will run otherwise, then whenever the setting state changes, the // corresponding callback will run.
diff --git a/components/reporting/metrics/multi_samplers_collector.cc b/components/reporting/metrics/multi_samplers_collector.cc deleted file mode 100644 index 77a5af9..0000000 --- a/components/reporting/metrics/multi_samplers_collector.cc +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <utility> - -#include "base/bind.h" -#include "base/sequence_checker.h" -#include "base/task/bind_post_task.h" -#include "base/task/sequenced_task_runner.h" -#include "components/reporting/metrics/configured_sampler.h" -#include "components/reporting/metrics/multi_samplers_collector.h" -#include "components/reporting/metrics/sampler.h" -#include "third_party/abseil-cpp/absl/types/optional.h" - -namespace reporting { - -// static -void MultiSamplersCollector::CollectAll( - const std::vector<ConfiguredSampler*>& configured_samplers, - OptionalMetricCallback metric_callback) { - auto multi_collector = - base::MakeRefCounted<MultiSamplersCollector>(std::move(metric_callback)); - for (auto* sampler : configured_samplers) { - if (sampler->IsReportingEnabled()) { - multi_collector->Collect(sampler->GetSampler()); - } - } -} - -MultiSamplersCollector::MultiSamplersCollector( - OptionalMetricCallback metric_callback) - : base::RefCountedDeleteOnSequence<MultiSamplersCollector>( - base::SequencedTaskRunner::GetCurrentDefault()), - metric_callback_(std::move(metric_callback)) {} - -void MultiSamplersCollector::Collect(Sampler* sampler) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - auto on_collected_cb = - base::BindOnce(&MultiSamplersCollector::MergeMetricData, this); - sampler->MaybeCollect( - base::BindPostTask(base::SequencedTaskRunner::GetCurrentDefault(), - std::move(on_collected_cb))); -} - -void MultiSamplersCollector::MergeMetricData( - absl::optional<MetricData> new_metric_data) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (!new_metric_data.has_value()) { - return; - } - if (!metric_data_.has_value()) { - metric_data_ = std::move(new_metric_data); - return; - } - - metric_data_->CheckTypeAndMergeFrom(new_metric_data.value()); -} - -MultiSamplersCollector::~MultiSamplersCollector() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - std::move(metric_callback_).Run(std::move(metric_data_)); -} - -} // namespace reporting
diff --git a/components/reporting/metrics/multi_samplers_collector.h b/components/reporting/metrics/multi_samplers_collector.h deleted file mode 100644 index 6aae5d0..0000000 --- a/components/reporting/metrics/multi_samplers_collector.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_REPORTING_METRICS_MULTI_SAMPLERS_COLLECTOR_H_ -#define COMPONENTS_REPORTING_METRICS_MULTI_SAMPLERS_COLLECTOR_H_ - -#include "base/memory/ref_counted_delete_on_sequence.h" -#include "base/sequence_checker.h" -#include "base/task/sequenced_task_runner_helpers.h" -#include "components/reporting/metrics/sampler.h" -#include "components/reporting/proto/synced/metric_data.pb.h" -#include "third_party/abseil-cpp/absl/types/optional.h" - -namespace reporting { - -class ConfiguredSampler; - -// Class to collect data from multiple samplers async. Response callback is -// invoked on destruction. Each sampling callback passed to a sampler will hold -// reference to the class instance, so the final class instance response will -// not be invoked until the class created instance reference is released and -// each callback is done (either by being run or dropped). -class MultiSamplersCollector - : public base::RefCountedDeleteOnSequence<MultiSamplersCollector> { - public: - static void CollectAll( - const std::vector<ConfiguredSampler*>& configured_samplers, - OptionalMetricCallback metric_callback); - - explicit MultiSamplersCollector(OptionalMetricCallback metric_callback); - - MultiSamplersCollector(const MultiSamplersCollector& other) = delete; - MultiSamplersCollector& operator=(const MultiSamplersCollector& other) = - delete; - - void Collect(Sampler* sampler); - - private: - friend class base::RefCountedDeleteOnSequence<MultiSamplersCollector>; - friend class base::DeleteHelper<MultiSamplersCollector>; - - void MergeMetricData(absl::optional<MetricData> new_metric_data); - - ~MultiSamplersCollector(); - - SEQUENCE_CHECKER(sequence_checker_); - - absl::optional<MetricData> metric_data_ GUARDED_BY_CONTEXT(sequence_checker_); - - OptionalMetricCallback metric_callback_; -}; - -} // namespace reporting - -#endif // COMPONENTS_REPORTING_METRICS_MULTI_SAMPLERS_COLLECTOR_H_
diff --git a/components/reporting/metrics/multi_samplers_collector_unittest.cc b/components/reporting/metrics/multi_samplers_collector_unittest.cc deleted file mode 100644 index 667e4dea..0000000 --- a/components/reporting/metrics/multi_samplers_collector_unittest.cc +++ /dev/null
@@ -1,131 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <utility> - -#include "base/memory/scoped_refptr.h" -#include "base/test/task_environment.h" -#include "base/test/test_future.h" -#include "components/reporting/metrics/fakes/fake_sampler.h" -#include "components/reporting/metrics/multi_samplers_collector.h" -#include "components/reporting/proto/synced/metric_data.pb.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/abseil-cpp/absl/types/optional.h" - -namespace reporting { -namespace { - -TEST(MultiSamplersCollectorTest, Default) { - base::test::TaskEnvironment task_environment; - - test::FakeDelayedSampler sampler1; - MetricData metric_data1; - metric_data1.mutable_telemetry_data()->mutable_audio_telemetry(); - sampler1.SetMetricData(std::move(metric_data1)); - - test::FakeDelayedSampler sampler2; - MetricData metric_data2; - metric_data2.mutable_telemetry_data()->mutable_boot_performance_telemetry(); - sampler2.SetMetricData(std::move(metric_data2)); - - base::test::TestFuture<absl::optional<MetricData>> future; - { - auto multi_samplers_collector = - base::MakeRefCounted<MultiSamplersCollector>(future.GetCallback()); - - // Collect data from samplers. - multi_samplers_collector->Collect(&sampler1); - multi_samplers_collector->Collect(&sampler2); - } - sampler2.RunCallback(); - sampler1.RunCallback(); - - absl::optional<MetricData> result = future.Take(); - - ASSERT_TRUE(result.has_value()); - ASSERT_TRUE(result->has_telemetry_data()); - EXPECT_TRUE(result->telemetry_data().has_audio_telemetry()); - EXPECT_TRUE(result->telemetry_data().has_boot_performance_telemetry()); -} - -TEST(MultiSamplersCollectorTest, OneEmptyResult) { - base::test::TaskEnvironment task_environment; - - test::FakeDelayedSampler sampler1; - MetricData metric_data1; - metric_data1.mutable_telemetry_data()->mutable_audio_telemetry(); - sampler1.SetMetricData(std::move(metric_data1)); - - test::FakeDelayedSampler sampler2; - sampler2.SetMetricData(absl::nullopt); - - base::test::TestFuture<absl::optional<MetricData>> future; - { - auto multi_samplers_collector = - base::MakeRefCounted<MultiSamplersCollector>(future.GetCallback()); - - // Collect data from samplers. - multi_samplers_collector->Collect(&sampler1); - multi_samplers_collector->Collect(&sampler2); - } - sampler2.RunCallback(); - sampler1.RunCallback(); - - absl::optional<MetricData> result = future.Take(); - - ASSERT_TRUE(result.has_value()); - ASSERT_TRUE(result->has_telemetry_data()); - EXPECT_TRUE(result->telemetry_data().has_audio_telemetry()); -} - -TEST(MultiSamplersCollectorTest, AllResultsEmpty) { - base::test::TaskEnvironment task_environment; - - test::FakeDelayedSampler sampler1; - sampler1.SetMetricData(absl::nullopt); - - test::FakeDelayedSampler sampler2; - sampler2.SetMetricData(absl::nullopt); - - base::test::TestFuture<absl::optional<MetricData>> future; - { - auto multi_samplers_collector = - base::MakeRefCounted<MultiSamplersCollector>(future.GetCallback()); - - // Collect data from samplers. - multi_samplers_collector->Collect(&sampler1); - multi_samplers_collector->Collect(&sampler2); - } - sampler2.RunCallback(); - sampler1.RunCallback(); - - absl::optional<MetricData> result = future.Take(); - - ASSERT_FALSE(result.has_value()); -} - -TEST(MultiSamplersCollectorTest, CallbackDropped) { - base::test::TaskEnvironment task_environment; - - base::test::TestFuture<absl::optional<MetricData>> future; - { - test::FakeDelayedSampler sampler; - MetricData metric_data; - metric_data.mutable_telemetry_data()->mutable_audio_telemetry(); - sampler.SetMetricData(std::move(metric_data)); - - auto multi_samplers_collector = - base::MakeRefCounted<MultiSamplersCollector>(future.GetCallback()); - - // Collect data from samplers. - multi_samplers_collector->Collect(&sampler); - // `sampler` goes out of scope without running the callback. - } - absl::optional<MetricData> result = future.Take(); - - ASSERT_FALSE(result.has_value()); -} - -} // namespace -} // namespace reporting
diff --git a/components/reporting/metrics/one_shot_collector.cc b/components/reporting/metrics/one_shot_collector.cc index a1c0c8e..7772923 100644 --- a/components/reporting/metrics/one_shot_collector.cc +++ b/components/reporting/metrics/one_shot_collector.cc
@@ -9,6 +9,7 @@ #include "base/check.h" #include "base/functional/bind.h" +#include "base/functional/callback_helpers.h" #include "base/location.h" #include "base/task/sequenced_task_runner.h" #include "base/time/time.h" @@ -64,34 +65,47 @@ OneShotCollector::~OneShotCollector() = default; -void OneShotCollector::Collect() { +void OneShotCollector::Collect(bool is_event_driven) { CheckOnSequence(); - - if (data_collected_) { - return; + if (!is_event_driven) { + if (data_collected_) { + return; + } + // TODO(b/260093529): Should this be set for event driven telemetry + // collection as well? + data_collected_ = true; } - data_collected_ = true; - reporting_controller_.reset(); - CollectorBase::Collect(); + CollectorBase::Collect(is_event_driven); +} + +bool OneShotCollector::CanCollect() const { + return reporting_controller_->IsEnabled(); } void OneShotCollector::OnMetricDataCollected( + bool is_event_driven, absl::optional<MetricData> metric_data) { CheckOnSequence(); - DCHECK(on_data_reported_); + DCHECK(is_event_driven || on_data_reported_); if (!metric_data.has_value()) { return; } metric_data->set_timestamp_ms(base::Time::Now().ToJavaTime()); - metric_report_queue_->Enqueue(std::move(metric_data.value()), - std::move(on_data_reported_)); + if (is_event_driven) { + DCHECK(metric_data->has_telemetry_data()); + metric_data->mutable_telemetry_data()->set_is_event_driven(is_event_driven); + } + metric_report_queue_->Enqueue( + std::move(metric_data.value()), + is_event_driven ? base::DoNothing() : std::move(on_data_reported_)); } void OneShotCollector::SetReportingControllerCb() { CheckOnSequence(); reporting_controller_->SetSettingUpdateCb( - base::BindRepeating(&OneShotCollector::Collect, base::Unretained(this))); + base::BindRepeating(&OneShotCollector::Collect, base::Unretained(this), + /*is_event_driven=*/false)); } } // namespace reporting
diff --git a/components/reporting/metrics/one_shot_collector.h b/components/reporting/metrics/one_shot_collector.h index ca2d4da..4fbbcc88 100644 --- a/components/reporting/metrics/one_shot_collector.h +++ b/components/reporting/metrics/one_shot_collector.h
@@ -53,10 +53,14 @@ ~OneShotCollector() override; - protected: - void Collect() override; + // CollectorBase: + void Collect(bool is_event_driven) override; - void OnMetricDataCollected(absl::optional<MetricData> metric_data) override; + protected: + // CollectorBase: + void OnMetricDataCollected(bool is_event_driven, + absl::optional<MetricData> metric_data) override; + bool CanCollect() const override; private: void SetReportingControllerCb();
diff --git a/components/reporting/metrics/one_shot_collector_unittest.cc b/components/reporting/metrics/one_shot_collector_unittest.cc index f906d1b..9afb0a9 100644 --- a/components/reporting/metrics/one_shot_collector_unittest.cc +++ b/components/reporting/metrics/one_shot_collector_unittest.cc
@@ -12,6 +12,7 @@ #include "base/test/task_environment.h" #include "base/test/test_future.h" #include "base/time/time.h" +#include "components/reporting/metrics/collector_base.h" #include "components/reporting/metrics/fakes/fake_metric_report_queue.h" #include "components/reporting/metrics/fakes/fake_reporting_settings.h" #include "components/reporting/metrics/fakes/fake_sampler.h" @@ -48,7 +49,7 @@ settings_->SetBoolean(kEnableSettingPath, true); MetricData metric_data; - metric_data.mutable_info_data(); + metric_data.mutable_telemetry_data(); sampler_->SetMetricData(std::move(metric_data)); base::test::TestFuture<Status> test_future; @@ -72,7 +73,28 @@ metric_report_queue_->GetMetricDataReported(); EXPECT_TRUE(metric_data_reported.has_timestamp_ms()); - EXPECT_TRUE(metric_data_reported.has_info_data()); + EXPECT_TRUE(metric_data_reported.has_telemetry_data()); + EXPECT_FALSE(metric_data_reported.telemetry_data().has_is_event_driven()); + EXPECT_TRUE(metric_report_queue_->IsEmpty()); + + settings_->SetBoolean(kEnableSettingPath, false); + collector.Collect(/*is_event_driven=*/true); + + // No new data collection, setting is disabled. + EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(1)); + + settings_->SetBoolean(kEnableSettingPath, true); + collector.Collect(/*is_event_driven=*/true); + + // Number of collection calls increased by one, setting is enabled and manual + // collection called. + EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(2)); + + metric_data_reported = metric_report_queue_->GetMetricDataReported(); + + EXPECT_TRUE(metric_data_reported.has_timestamp_ms()); + EXPECT_TRUE(metric_data_reported.has_telemetry_data()); + EXPECT_TRUE(metric_data_reported.telemetry_data().is_event_driven()); EXPECT_TRUE(metric_report_queue_->IsEmpty()); } @@ -81,7 +103,7 @@ settings_->SetBoolean(kEnableSettingPath, true); MetricData metric_data; - metric_data.mutable_info_data(); + metric_data.mutable_telemetry_data(); sampler_->SetMetricData(std::move(metric_data)); base::test::TestFuture<Status> test_future; @@ -96,24 +118,36 @@ // `init_delay` is not elapsed yet. EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(0)); + collector.Collect(/*is_event_driven=*/true); + + // Data manually collected before `init_delay`. + EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(1)); + + MetricData metric_data_reported = + metric_report_queue_->GetMetricDataReported(); + + EXPECT_TRUE(metric_data_reported.has_timestamp_ms()); + EXPECT_TRUE(metric_data_reported.has_telemetry_data()); + EXPECT_TRUE(metric_data_reported.telemetry_data().is_event_driven()); + EXPECT_TRUE(metric_report_queue_->IsEmpty()); + task_environment_.FastForwardBy(init_delay - elapsed); - // Setting is initially enabled, data is being collected. - EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(1)); + // Setting is initially enabled and `init_delay` elapsed, data is collected. + EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(2)); settings_->SetBoolean(kEnableSettingPath, false); settings_->SetBoolean(kEnableSettingPath, true); // No more data should be collected even if the setting was disabled then // re-enabled. - EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(1)); + EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(2)); EXPECT_TRUE(test_future.Wait()); - MetricData metric_data_reported = - metric_report_queue_->GetMetricDataReported(); + metric_data_reported = metric_report_queue_->GetMetricDataReported(); EXPECT_TRUE(metric_data_reported.has_timestamp_ms()); - EXPECT_TRUE(metric_data_reported.has_info_data()); + EXPECT_TRUE(metric_data_reported.has_telemetry_data()); EXPECT_TRUE(metric_report_queue_->IsEmpty()); }
diff --git a/components/reporting/metrics/periodic_collector.cc b/components/reporting/metrics/periodic_collector.cc index 9bda6c5..1b266c3 100644 --- a/components/reporting/metrics/periodic_collector.cc +++ b/components/reporting/metrics/periodic_collector.cc
@@ -8,6 +8,7 @@ #include <string> #include <utility> +#include "base/check.h" #include "base/functional/bind.h" #include "base/location.h" #include "base/sequence_checker.h" @@ -35,7 +36,8 @@ metric_report_queue_(metric_report_queue), rate_controller_(std::make_unique<MetricRateController>( base::BindRepeating(&PeriodicCollector::Collect, - base::Unretained(this)), + base::Unretained(this), + /*is_event_driven=*/false), reporting_settings, rate_setting_path, default_rate, @@ -77,20 +79,29 @@ PeriodicCollector::~PeriodicCollector() = default; void PeriodicCollector::OnMetricDataCollected( + bool is_event_driven, absl::optional<MetricData> metric_data) { CheckOnSequence(); if (!metric_data.has_value()) { return; } + if (is_event_driven) { + DCHECK(metric_data->has_telemetry_data()); + metric_data->mutable_telemetry_data()->set_is_event_driven(is_event_driven); + } metric_data->set_timestamp_ms(base::Time::Now().ToJavaTime()); metric_report_queue_->Enqueue(std::move(metric_data.value())); } +bool PeriodicCollector::CanCollect() const { + return reporting_controller_->IsEnabled(); +} + void PeriodicCollector::StartPeriodicCollection() { CheckOnSequence(); // Do initial collection at startup. - Collect(); + Collect(/*is_event_driven=*/false); rate_controller_->Start(); }
diff --git a/components/reporting/metrics/periodic_collector.h b/components/reporting/metrics/periodic_collector.h index d6931d7..7a2317ba 100644 --- a/components/reporting/metrics/periodic_collector.h +++ b/components/reporting/metrics/periodic_collector.h
@@ -54,7 +54,10 @@ ~PeriodicCollector() override; protected: - void OnMetricDataCollected(absl::optional<MetricData> metric_data) override; + // CollectorBase: + void OnMetricDataCollected(bool is_event_driven, + absl::optional<MetricData> metric_data) override; + bool CanCollect() const override; private: void StartPeriodicCollection();
diff --git a/components/reporting/metrics/periodic_collector_unittest.cc b/components/reporting/metrics/periodic_collector_unittest.cc index 7923889..ab2e959 100644 --- a/components/reporting/metrics/periodic_collector_unittest.cc +++ b/components/reporting/metrics/periodic_collector_unittest.cc
@@ -142,15 +142,26 @@ // collection. EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(0)); - task_environment_.FastForwardBy(init_delay - interval); + collector.Collect(/*is_event_driven=*/true); - // One initial collection when the init delay is elapsed. + // `init_delay` not elapsed but manual collection is triggered. EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(1)); - MetricData metric_data_reported = metric_report_queue_->GetMetricDataReported(); EXPECT_TRUE(metric_data_reported.has_timestamp_ms()); EXPECT_TRUE(metric_data_reported.has_telemetry_data()); + EXPECT_TRUE(metric_data_reported.telemetry_data().is_event_driven()); + EXPECT_TRUE(metric_report_queue_->IsEmpty()); + + task_environment_.FastForwardBy(init_delay - interval); + + // One initial collection when the init delay is elapsed. + EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(2)); + + metric_data_reported = metric_report_queue_->GetMetricDataReported(); + EXPECT_TRUE(metric_data_reported.has_timestamp_ms()); + EXPECT_TRUE(metric_data_reported.has_telemetry_data()); + EXPECT_FALSE(metric_data_reported.telemetry_data().is_event_driven()); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(metric_report_queue_->IsEmpty()); @@ -193,21 +204,41 @@ // Setting is disabled, no data collected. EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(0)); + collector.Collect(/*is_event_driven=*/true); + + // Manual collection is triggered but reporting is disabled. + EXPECT_EQ(sampler_->GetNumCollectCalls(), 0); + settings_->SetBoolean(kEnableSettingPath, true); // One initial collection at policy enablement. EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(1)); - task_environment_.FastForwardBy(interval); - // 1 collection at policy enablement + 1 collection after interval. - EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(2)); - MetricData metric_data_reported = metric_report_queue_->GetMetricDataReported(); EXPECT_TRUE(metric_data_reported.has_timestamp_ms()); EXPECT_TRUE(metric_data_reported.has_telemetry_data()); + EXPECT_FALSE(metric_data_reported.telemetry_data().has_is_event_driven()); + + task_environment_.FastForwardBy(interval / 2); + + collector.Collect(/*is_event_driven=*/true); + + // `interval` not elapsed but manual collection is triggered. + EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(2)); metric_data_reported = metric_report_queue_->GetMetricDataReported(); EXPECT_TRUE(metric_data_reported.has_timestamp_ms()); EXPECT_TRUE(metric_data_reported.has_telemetry_data()); + EXPECT_TRUE(metric_data_reported.telemetry_data().is_event_driven()); + + task_environment_.FastForwardBy(interval / 2); + // 1 collection at policy enablement + 1 manual collection + 1 collection + // after interval. + EXPECT_THAT(sampler_->GetNumCollectCalls(), Eq(3)); + + metric_data_reported = metric_report_queue_->GetMetricDataReported(); + EXPECT_TRUE(metric_data_reported.has_timestamp_ms()); + EXPECT_TRUE(metric_data_reported.has_telemetry_data()); + EXPECT_FALSE(metric_data_reported.telemetry_data().has_is_event_driven()); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(metric_report_queue_->IsEmpty());
diff --git a/components/reporting/metrics/periodic_event_collector.cc b/components/reporting/metrics/periodic_event_collector.cc index 1a54acc0..1ad7dedec 100644 --- a/components/reporting/metrics/periodic_event_collector.cc +++ b/components/reporting/metrics/periodic_event_collector.cc
@@ -29,7 +29,8 @@ event_detector_(std::move(event_detector)), rate_controller_(std::make_unique<MetricRateController>( base::BindRepeating(&PeriodicEventCollector::Collect, - base::Unretained(this)), + base::Unretained(this), + /*is_event_driven=*/false), reporting_settings, rate_setting_path, default_rate, @@ -46,7 +47,7 @@ void PeriodicEventCollector::SetReportingEnabled(bool is_enabled) { if (is_enabled) { // Do initial collection at startup. - Collect(); + Collect(/*is_event_driven=*/false); rate_controller_->Start(); return; } @@ -54,6 +55,7 @@ } void PeriodicEventCollector::OnMetricDataCollected( + bool is_event_driven, absl::optional<MetricData> metric_data) { if (!metric_data.has_value()) { return; @@ -70,4 +72,8 @@ last_collected_data_->mutable_event_data()->set_type(event.value()); on_event_observed_cb_.Run(last_collected_data_.value()); } + +bool PeriodicEventCollector::CanCollect() const { + return true; +} } // namespace reporting
diff --git a/components/reporting/metrics/periodic_event_collector.h b/components/reporting/metrics/periodic_event_collector.h index a2959e4..d84800b 100644 --- a/components/reporting/metrics/periodic_event_collector.h +++ b/components/reporting/metrics/periodic_event_collector.h
@@ -62,7 +62,9 @@ protected: // CollectorBase: - void OnMetricDataCollected(absl::optional<MetricData> metric_data) override; + void OnMetricDataCollected(bool is_event_driven, + absl::optional<MetricData> metric_data) override; + bool CanCollect() const override; private: MetricRepeatingCallback on_event_observed_cb_;
diff --git a/components/safe_browsing/core/browser/db/v4_database.cc b/components/safe_browsing/core/browser/db/v4_database.cc index 61b18f9..f9b14092 100644 --- a/components/safe_browsing/core/browser/db/v4_database.cc +++ b/components/safe_browsing/core/browser/db/v4_database.cc
@@ -15,7 +15,6 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/time/time.h" #include "build/build_config.h" #include "components/safe_browsing/core/common/proto/webui.pb.h" @@ -305,9 +304,8 @@ stores.push_back(std::make_pair(next_store.first, next_store.second.get())); } - base::PostTaskAndReplyWithResult( - db_task_runner_.get(), FROM_HERE, - base::BindOnce(&VerifyChecksums, stores), + db_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&VerifyChecksums, stores), base::BindOnce(&V4Database::OnChecksumVerified, weak_factory_on_io_.GetWeakPtr(), std::move(db_ready_for_updates_callback)));
diff --git a/components/safe_browsing/core/common/features.cc b/components/safe_browsing/core/common/features.cc index a221930b..f7af6d3 100644 --- a/components/safe_browsing/core/common/features.cc +++ b/components/safe_browsing/core/common/features.cc
@@ -86,16 +86,6 @@ "DownloadTailoredWarnings", base::FEATURE_ENABLED_BY_DEFAULT); -BASE_FEATURE(kEnhancedProtection, - "SafeBrowsingEnhancedProtection", - base::FEATURE_ENABLED_BY_DEFAULT); - -#if BUILDFLAG(IS_IOS) -BASE_FEATURE(kEnhancedProtectionPhase2IOS, - "SafeBrowsingEnhancedProtectionPhase2IOS", - base::FEATURE_ENABLED_BY_DEFAULT); -#endif - BASE_FEATURE(kEsbIphBubbleAndCollapseSettings, "EsbIphBubbleAndCollapseSettings", base::FEATURE_DISABLED_BY_DEFAULT); @@ -246,10 +236,6 @@ #endif {&kDelayedWarnings, true}, {&kDownloadBubble, true}, {&kDownloadBubbleV2, true}, {&kDownloadTailoredWarnings, true}, - {&kEnhancedProtection, true}, -#if BUILDFLAG(IS_IOS) - {&kEnhancedProtectionPhase2IOS, true}, -#endif {&kExtensionTelemetry, true}, {&kExtensionTelemetryCookiesGetAllSignal, true}, {&kExtensionTelemetryCookiesGetSignal, true},
diff --git a/components/safe_browsing/core/common/features.h b/components/safe_browsing/core/common/features.h index 9a7181b..fdd6dc3 100644 --- a/components/safe_browsing/core/common/features.h +++ b/components/safe_browsing/core/common/features.h
@@ -80,12 +80,6 @@ // server-side. BASE_DECLARE_FEATURE(kDownloadTailoredWarnings); -// Enables Enhanced Safe Browsing. Launched on all platforms in M106. -BASE_DECLARE_FEATURE(kEnhancedProtection); - -// Phase 2 of Enhanced Safe Browsing changes. -BASE_DECLARE_FEATURE(kEnhancedProtectionPhase2IOS); - // Enables instructional improvements when users are directed to the security // settings page to enable Enhanced Safe Browsing. Enables the In-page help // (IPH) Bubble to be shown when the user is referred from an ESB promotion.
diff --git a/components/search_engines/template_url_prepopulate_data.cc b/components/search_engines/template_url_prepopulate_data.cc index bb2366e..dbd10da 100644 --- a/components/search_engines/template_url_prepopulate_data.cc +++ b/components/search_engines/template_url_prepopulate_data.cc
@@ -43,7 +43,7 @@ &bing, &yahoo, &duckduckgo, - &ecosia, + &yandex_ru, }; // Albania @@ -52,7 +52,7 @@ &bing, &yahoo, &duckduckgo, - &yandex_com, + &yandex_tr, }; // Argentina @@ -68,8 +68,8 @@ const PrepopulatedEngine* const engines_AT[] = { &google, &bing, - &duckduckgo, &yahoo_at, + &duckduckgo, &ecosia, }; @@ -115,7 +115,7 @@ &bing, &yahoo, &duckduckgo, - &yandex_com, + &ecosia, }; // Burundi @@ -151,7 +151,7 @@ &bing, &yahoo_br, &duckduckgo, - &ecosia, + &yandex_com, }; // Belarus @@ -169,7 +169,7 @@ &bing, &yahoo, &duckduckgo, - &ecosia, + &naver, }; // Canada @@ -186,8 +186,8 @@ &google, &bing, &duckduckgo, - &ecosia, &yahoo_ch, + &ecosia, }; // Chile @@ -201,11 +201,11 @@ // China const PrepopulatedEngine* const engines_CN[] = { - &sogou, &baidu, &bing, - &google, + &sogou, &so_360, + &google, }; // Colombia @@ -213,8 +213,8 @@ &google, &bing, &yahoo_co, - &ecosia, &duckduckgo, + &ecosia, }; // Costa Rica @@ -239,9 +239,9 @@ const PrepopulatedEngine* const engines_DE[] = { &google, &bing, - &ecosia, - &duckduckgo, &yahoo_de, + &duckduckgo, + &ecosia, }; // Denmark @@ -275,7 +275,7 @@ const PrepopulatedEngine* const engines_EC[] = { &google, &bing, - &yahoo, + &yahoo_es, &ecosia, &duckduckgo, }; @@ -286,7 +286,7 @@ &bing, &yandex_ru, &duckduckgo, - &yahoo, + &mail_ru, }; // Egypt @@ -320,7 +320,7 @@ const PrepopulatedEngine* const engines_FO[] = { &google, &bing, - &yahoo_dk, + &yahoo_uk, &duckduckgo, &ecosia, }; @@ -364,10 +364,10 @@ // Hong Kong const PrepopulatedEngine* const engines_HK[] = { &google, - &yahoo_hk, &bing, + &yahoo_hk, &baidu, - &duckduckgo, + &so_360, }; // Honduras @@ -383,8 +383,8 @@ const PrepopulatedEngine* const engines_HR[] = { &google, &bing, - &yahoo, &duckduckgo, + &yahoo, &ecosia, }; @@ -400,10 +400,10 @@ // Indonesia const PrepopulatedEngine* const engines_ID[] = { &google, - &yahoo_id, &bing, - &yandex_com, + &yahoo_id, &duckduckgo, + &yandex_com, }; // Ireland @@ -439,7 +439,7 @@ &bing, &yahoo, &yandex_tr, - &duckduckgo, + &petal_search, }; // Iran @@ -447,8 +447,8 @@ &google, &bing, &yahoo, - &ask, &duckduckgo, + &ask, }; // Iceland @@ -483,15 +483,15 @@ &google, &bing, &yahoo, + &petal_search, &duckduckgo, - &yandex_com, }; // Japan const PrepopulatedEngine* const engines_JP[] = { &google, - &yahoo_jp, &bing, + &yahoo_jp, &duckduckgo, &baidu, }; @@ -502,15 +502,15 @@ &bing, &yahoo, &duckduckgo, - &ecosia, + &yandex_com, }; // South Korea const PrepopulatedEngine* const engines_KR[] = { &google, &naver, - &daum, &bing, + &daum, &yahoo, }; @@ -520,7 +520,7 @@ &bing, &yahoo, &duckduckgo, - &yandex_com, + &yandex_tr, }; // Kazakhstan @@ -554,9 +554,9 @@ const PrepopulatedEngine* const engines_LT[] = { &google, &bing, - &yahoo, - &duckduckgo, &yandex_ru, + &duckduckgo, + &yahoo, }; // Luxembourg @@ -582,7 +582,7 @@ &google, &bing, &yahoo, - &yandex_com, + &yandex_tr, &duckduckgo, }; @@ -599,9 +599,9 @@ const PrepopulatedEngine* const engines_MC[] = { &google, &bing, - &duckduckgo, &yahoo_fr, - &ecosia, + &duckduckgo, + &qwant, }; // Moldova @@ -610,15 +610,15 @@ &yandex_ru, &bing, &mail_ru, - &yahoo, + &duckduckgo, }; // Montenegro const PrepopulatedEngine* const engines_ME[] = { &google, &bing, - &yahoo, &yandex_ru, + &yahoo, &duckduckgo, }; @@ -628,7 +628,7 @@ &bing, &yahoo, &duckduckgo, - &yandex_ru, + &yandex_com, }; // Mexico @@ -664,7 +664,7 @@ &bing, &yahoo_nl, &duckduckgo, - &ecosia, + &yandex_ru, }; // Norway @@ -690,8 +690,8 @@ &google, &bing, &yahoo, - &duckduckgo, &petal_search, + &duckduckgo, }; // Panama @@ -716,7 +716,7 @@ const PrepopulatedEngine* const engines_PH[] = { &google, &bing, - &yahoo, + &yahoo_ph, &ecosia, &duckduckgo, }; @@ -795,11 +795,11 @@ // Russia const PrepopulatedEngine* const engines_RU[] = { - &google, &yandex_ru, - &mail_ru, - &bing, + &google, &duckduckgo, + &bing, + &mail_ru, }; // Rwanda @@ -826,7 +826,7 @@ &bing, &yahoo_se, &duckduckgo, - &ecosia, + &yandex_ru, }; // Singapore @@ -834,8 +834,8 @@ &google, &bing, &yahoo_sg, - &duckduckgo, &baidu, + &duckduckgo, }; // Slovenia @@ -853,7 +853,7 @@ &bing, &duckduckgo, &yahoo, - &yandex_com, + &yandex_ru, }; // El Salvador @@ -869,8 +869,8 @@ const PrepopulatedEngine* const engines_SY[] = { &google, &bing, + &yandex_ru, &yahoo, - &yandex_com, &duckduckgo, }; @@ -879,8 +879,8 @@ &google, &bing, &yahoo_th, - &yandex_ru, - &mail_ru, + &naver, + &duckduckgo, }; // Tunisia @@ -907,7 +907,7 @@ &bing, &yahoo, &duckduckgo, - &ecosia, + &yandex_com, }; // Taiwan @@ -925,16 +925,16 @@ &bing, &yahoo, &duckduckgo, - &baidu, + &ecosia, }; // Ukraine const PrepopulatedEngine* const engines_UA[] = { &google, - &yandex_ua, + &yandex_ru, &bing, &duckduckgo, - &yahoo, + &mail_ru, }; // United States @@ -961,16 +961,16 @@ &bing, &yahoo_es, &duckduckgo, - &ecosia, + &yandex_com, }; // Vietnam const PrepopulatedEngine* const engines_VN[] = { &google, &coccoc, - &yahoo, &bing, - &yandex_ru, + &yahoo, + &baidu, }; // Yemen @@ -978,8 +978,8 @@ &google, &bing, &yahoo, - &yandex_com, &duckduckgo, + &yandex_com, }; // South Africa
diff --git a/components/search_provider_logos/logo_service_impl.cc b/components/search_provider_logos/logo_service_impl.cc index 35925c2..08fe154 100644 --- a/components/search_provider_logos/logo_service_impl.cc +++ b/components/search_provider_logos/logo_service_impl.cc
@@ -16,7 +16,6 @@ #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_macros.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/default_clock.h" #include "build/build_config.h" @@ -321,8 +320,8 @@ if (is_idle_) { is_idle_ = false; - base::PostTaskAndReplyWithResult( - cache_task_runner_.get(), FROM_HERE, + cache_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetLogoFromCacheOnFileThread, base::Unretained(logo_cache_.get()), logo_url_, clock_->Now()),
diff --git a/components/services/storage/indexed_db/scopes/leveldb_scopes.cc b/components/services/storage/indexed_db/scopes/leveldb_scopes.cc index bdf17dba..e5bd5fe7 100644 --- a/components/services/storage/indexed_db/scopes/leveldb_scopes.cc +++ b/components/services/storage/indexed_db/scopes/leveldb_scopes.cc
@@ -16,7 +16,6 @@ #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "components/services/storage/indexed_db/leveldb/leveldb_state.h" @@ -234,8 +233,8 @@ ? CleanupScopeTask::CleanupMode::kExecuteCleanupTasks : CleanupScopeTask::CleanupMode::kIgnoreCleanupTasks, max_write_batch_size_bytes_); - base::PostTaskAndReplyWithResult( - cleanup_runner_.get(), FROM_HERE, + cleanup_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CleanupScopeTask::Run, std::move(cleanup_task)), base::BindOnce(&LevelDBScopes::OnCleanupTaskResult, weak_factory_.GetWeakPtr(), base::OnceClosure())); @@ -282,9 +281,8 @@ level_db_, metadata_key_prefix_, scope->scope_id(), CleanupScopeTask::CleanupMode::kExecuteCleanupTasks, max_write_batch_size_bytes_); - base::PostTaskAndReplyWithResult( - cleanup_runner_.get(), FROM_HERE, - base::BindOnce(&CleanupScopeTask::Run, std::move(task)), + cleanup_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CleanupScopeTask::Run, std::move(task)), base::BindOnce(&LevelDBScopes::OnCleanupTaskResult, weak_factory_.GetWeakPtr(), std::move(on_complete))); } @@ -298,9 +296,8 @@ level_db_, metadata_key_prefix_, scope_id, max_write_batch_size_bytes_); if (revert_runner_) { - base::PostTaskAndReplyWithResult( - revert_runner_.get(), FROM_HERE, - base::BindOnce(&RevertScopeTask::Run, std::move(task)), + revert_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&RevertScopeTask::Run, std::move(task)), base::BindOnce(&LevelDBScopes::OnRevertTaskResult, weak_factory_.GetWeakPtr(), scope_id, std::move(locks))); return leveldb::Status::OK(); @@ -332,9 +329,8 @@ level_db_, metadata_key_prefix_, scope_id, CleanupScopeTask::CleanupMode::kIgnoreCleanupTasks, max_write_batch_size_bytes_); - base::PostTaskAndReplyWithResult( - cleanup_runner_.get(), FROM_HERE, - base::BindOnce(&CleanupScopeTask::Run, std::move(task)), + cleanup_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CleanupScopeTask::Run, std::move(task)), base::BindOnce(&LevelDBScopes::OnCleanupTaskResult, weak_factory_.GetWeakPtr(), base::OnceClosure())); }
diff --git a/components/services/storage/service_worker/service_worker_storage.cc b/components/services/storage/service_worker/service_worker_storage.cc index dda0a9d..e7bb1bf 100644 --- a/components/services/storage/service_worker/service_worker_storage.cc +++ b/components/services/storage/service_worker/service_worker_storage.cc
@@ -17,7 +17,6 @@ #include "base/metrics/histogram_functions.h" #include "base/run_loop.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" @@ -278,8 +277,8 @@ RegistrationList* registrations_ptr = registrations.get(); std::vector<ResourceList>* resource_lists_ptr = resource_lists.get(); - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::GetRegistrationsForStorageKey, base::Unretained(database_.get()), key, registrations_ptr, resource_lists_ptr), @@ -340,8 +339,8 @@ auto registrations = std::make_unique<RegistrationList>(); RegistrationList* registrations_ptr = registrations.get(); - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::GetAllRegistrations, base::Unretained(database_.get()), registrations_ptr), base::BindOnce(&ServiceWorkerStorage::DidGetAllRegistrations, @@ -408,8 +407,8 @@ break; } - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::UpdateVersionToActive, base::Unretained(database_.get()), registration_id, key), std::move(callback)); @@ -436,8 +435,8 @@ break; } - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::UpdateLastCheckTime, base::Unretained(database_.get()), registration_id, key, last_update_check_time), @@ -465,8 +464,8 @@ break; } - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::UpdateNavigationPreloadEnabled, base::Unretained(database_.get()), registration_id, key, enable), @@ -494,8 +493,8 @@ break; } - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::UpdateNavigationPreloadHeader, base::Unretained(database_.get()), registration_id, key, value), @@ -523,8 +522,8 @@ break; } - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::UpdateFetchHandlerType, base::Unretained(database_.get()), registration_id, key, type), @@ -697,8 +696,8 @@ DeleteStaleResources(); std::vector<int64_t> resource_ids = {resource_id}; - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::WriteUncommittedResourceIds, base::Unretained(database_.get()), resource_ids), std::move(callback)); @@ -722,8 +721,8 @@ break; } - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::PurgeUncommittedResourceIds, base::Unretained(database_.get()), resource_ids), base::BindOnce(&ServiceWorkerStorage::DidDoomUncommittedResourceIds, @@ -770,8 +769,8 @@ } } - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::WriteUserData, base::Unretained(database_.get()), registration_id, key, std::move(user_data)), @@ -942,8 +941,8 @@ } } - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::DeleteUserData, base::Unretained(database_.get()), registration_id, keys), std::move(callback)); @@ -988,8 +987,8 @@ } } - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::DeleteUserDataByKeyPrefixes, base::Unretained(database_.get()), registration_id, key_prefixes), @@ -1097,8 +1096,8 @@ return; } - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &ServiceWorkerDatabase::DeleteUserDataForAllRegistrationsByKeyPrefix, base::Unretained(database_.get()), key_prefix), @@ -1120,8 +1119,8 @@ expecting_done_with_disk_on_disable_ = false; if (!delete_and_start_over_callback_.is_null()) { // Delete the database on the database thread. - base::PostTaskAndReplyWithResult( - database_task_runner_.get(), FROM_HERE, + database_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ServiceWorkerDatabase::DestroyDatabase, base::Unretained(database_.get())), base::BindOnce(&ServiceWorkerStorage::DidDeleteDatabase,
diff --git a/components/sessions/core/session_service_commands.cc b/components/sessions/core/session_service_commands.cc index af37ac5..f091527 100644 --- a/components/sessions/core/session_service_commands.cc +++ b/components/sessions/core/session_service_commands.cc
@@ -441,7 +441,7 @@ // // This does NOT add any created SessionTabs to SessionWindow.tabs, that is // done by AddTabsToWindows. -bool CreateTabsAndWindows( +void CreateTabsAndWindows( const std::vector<std::unique_ptr<SessionCommand>>& data, IdToSessionTab* tabs, GroupIdToSessionTabGroup* tab_groups, @@ -461,7 +461,7 @@ SessionID::id_type payload[2]; if (!command->GetPayload(payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionID window_id = SessionID::FromSerializedValue(payload[0]); SessionID tab_id = SessionID::FromSerializedValue(payload[1]); @@ -475,7 +475,7 @@ WindowBoundsPayload2 payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionID window_id = SessionID::FromSerializedValue(payload.window_id); GetWindow(window_id, windows) @@ -490,7 +490,7 @@ WindowBoundsPayload3 payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionID window_id = SessionID::FromSerializedValue(payload.window_id); GetWindow(window_id, windows) @@ -504,7 +504,7 @@ TabIndexInWindowPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionID tab_id = SessionID::FromSerializedValue(payload.id); GetTab(tab_id, tabs)->tab_visual_index = payload.index; @@ -516,7 +516,7 @@ ClosedPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } if (command->id() == kCommandTabClosed) tabs->erase(SessionID::FromSerializedValue(payload.id)); @@ -530,7 +530,7 @@ TabNavigationPathPrunedFromBackPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionTab* tab = GetTab(SessionID::FromSerializedValue(payload.id), tabs); @@ -547,7 +547,7 @@ sizeof(prune_front_payload)) || prune_front_payload.index <= 0) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionTab* tab = GetTab( SessionID::FromSerializedValue(prune_front_payload.id), tabs); @@ -564,7 +564,7 @@ if (!command->GetPayload(&payload, sizeof(payload)) || payload.index < 0 || payload.count <= 0) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionTab* tab = GetTab(SessionID::FromSerializedValue(payload.id), tabs); @@ -580,7 +580,7 @@ &navigation, &tab_id)) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionTab* tab = GetTab(tab_id, tabs); auto i = FindClosestNavigationWithIndex(&(tab->navigations), @@ -596,7 +596,7 @@ SelectedNavigationIndexPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } GetTab(SessionID::FromSerializedValue(payload.id), tabs) ->current_navigation_index = payload.index; @@ -607,7 +607,7 @@ SelectedTabInIndexPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } GetWindow(SessionID::FromSerializedValue(payload.id), windows) ->selected_tab_index = payload.index; @@ -618,7 +618,7 @@ WindowTypePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionID window_id = SessionID::FromSerializedValue(payload.id); GetWindow(window_id, windows)->is_constrained = false; @@ -631,7 +631,7 @@ TabGroupPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionTab* session_tab = GetTab(SessionID::FromSerializedValue(payload.tab_id), tabs); @@ -650,7 +650,7 @@ absl::optional<base::Token> group_token = ReadTokenFromPickle(&iter); if (!group_token.has_value()) - return true; + return; SessionTabGroup* group = GetTabGroup( tab_groups::TabGroupId::FromRawToken(group_token.value()), @@ -658,11 +658,11 @@ std::u16string title; if (!iter.ReadString16(&title)) - return true; + return; uint32_t color_int; if (!iter.ReadUInt32(&color_int)) - return true; + return; // The |is_collapsed| boolean was added in M88 to save the collapsed // state, so previous versions may not have this stored. @@ -677,7 +677,7 @@ PinnedStatePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } GetTab(SessionID::FromSerializedValue(payload.tab_id), tabs)->pinned = payload.pinned_state; @@ -688,7 +688,7 @@ SessionID window_id = SessionID::InvalidValue(); std::string app_name; if (!RestoreSetWindowAppNameCommand(*command, &window_id, &app_name)) - return true; + return; GetWindow(window_id, windows)->app_name.swap(app_name); break; @@ -701,7 +701,7 @@ &tab_id, &extension_app_id)) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } GetTab(tab_id, tabs)->extension_app_id.swap(extension_app_id); @@ -715,7 +715,7 @@ *command, &tab_id, &user_agent_override)) { - return true; + return; } SessionTab* tab = GetTab(tab_id, tabs); @@ -731,7 +731,7 @@ if (!RestoreSetTabUserAgentOverrideCommand2( *command, &tab_id, &user_agent_override, &opaque_ua_metadata_override)) { - return true; + return; } SessionTab* tab = GetTab(tab_id, tabs); tab->user_agent_override.ua_string_override = @@ -749,7 +749,7 @@ base::PickleIterator iter(*command_pickle); if (!iter.ReadInt(&command_tab_id) || !iter.ReadString(&session_storage_persistent_id)) - return true; + return; // Associate the session storage back. GetTab(SessionID::FromSerializedValue(command_tab_id), tabs) ->session_storage_persistent_id = session_storage_persistent_id; @@ -760,7 +760,7 @@ ActiveWindowPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } *active_window_id = SessionID::FromSerializedValue(payload); break; @@ -770,7 +770,7 @@ LastActiveTimePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } SessionTab* tab = GetTab(SessionID::FromSerializedValue(payload.tab_id), tabs); @@ -786,7 +786,7 @@ std::string workspace; if (!it.ReadInt(&window_id) || !it.ReadString(&workspace)) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } GetWindow(SessionID::FromSerializedValue(window_id), windows) ->workspace = workspace; @@ -797,7 +797,7 @@ VisibleOnAllWorkspacesPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } GetWindow(SessionID::FromSerializedValue(payload.window_id), windows) ->visible_on_all_workspaces = payload.visible_on_all_workspaces; @@ -812,7 +812,7 @@ if (!it.ReadInt(&tab_id) || !it.ReadString(&guid) || !base::IsValidGUID(guid)) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } GetTab(SessionID::FromSerializedValue(tab_id), tabs)->guid = guid; break; @@ -825,7 +825,7 @@ int size = 0; if (!it.ReadInt(&tab_id) || !it.ReadInt(&size)) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } std::map<std::string, std::string> tab_data; for (int i = 0; i < size; i++) { @@ -833,7 +833,7 @@ std::string value; if (!it.ReadString(&key) || !it.ReadString(&value)) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } tab_data.insert({key, value}); } @@ -849,7 +849,7 @@ std::string extra_data; if (!RestoreAddExtraDataCommand(*command, &tab_id, &key, &extra_data)) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } GetTab(tab_id, tabs)->extra_data[key] = std::move(extra_data); @@ -863,7 +863,7 @@ if (!RestoreAddExtraDataCommand(*command, &window_id, &key, &extra_data)) { DVLOG(1) << "Failed reading command " << command->id(); - return true; + return; } GetWindow(window_id, windows)->extra_data[key] = std::move(extra_data); @@ -874,17 +874,16 @@ SessionID window_id = SessionID::InvalidValue(); std::string title; if (!RestoreSetWindowUserTitleCommand(*command, &window_id, &title)) - return true; + return; GetWindow(window_id, windows)->user_title = title; break; } default: DVLOG(1) << "Failed reading an unknown command " << command->id(); - return true; + return; } } - return true; } template <typename Payload> @@ -1213,12 +1212,20 @@ IdToSessionWindow windows; DVLOG(1) << "RestoreSessionFromCommands " << commands.size(); - if (CreateTabsAndWindows(commands, &tabs, &tab_groups, &windows, - active_window_id)) { - AddTabsToWindows(&tabs, &tab_groups, &windows); - SortTabsBasedOnVisualOrderAndClear(&windows, valid_windows); - UpdateSelectedTabIndex(valid_windows); + CreateTabsAndWindows(commands, &tabs, &tab_groups, &windows, + active_window_id); + AddTabsToWindows(&tabs, &tab_groups, &windows); + SortTabsBasedOnVisualOrderAndClear(&windows, valid_windows); + UpdateSelectedTabIndex(valid_windows); + // After processing, all windows should have at least one tab, and each + // tab should have at least one navigation. +#if DCHECK_IS_ON() + for (const auto& window : *valid_windows) { + DCHECK(!window->tabs.empty()); + for (const auto& tab : window->tabs) + DCHECK(!tab->navigations.empty()); } +#endif // AddTabsToWindows should have processed all the tabs and groups. DCHECK_EQ(0u, tabs.size()); DCHECK_EQ(0u, tab_groups.size());
diff --git a/components/spellcheck/browser/windows_spell_checker.cc b/components/spellcheck/browser/windows_spell_checker.cc index d2cf7de..0275fa4 100644 --- a/components/spellcheck/browser/windows_spell_checker.cc +++ b/components/spellcheck/browser/windows_spell_checker.cc
@@ -23,7 +23,6 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner_thread_mode.h" -#include "base/task/task_runner_util.h" #include "base/threading/thread_task_runner_handle.h" #include "base/win/com_init_util.h" #include "base/win/core_winrt_util.h" @@ -509,8 +508,8 @@ void WindowsSpellChecker::CreateSpellChecker( const std::string& lang_tag, base::OnceCallback<void(bool)> callback) { - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &windows_spell_checker::BackgroundHelper::CreateSpellChecker, base::Unretained(background_helper_.get()), lang_tag), @@ -529,8 +528,8 @@ int document_tag, const std::u16string& text, spellcheck_platform::TextCheckCompleteCallback callback) { - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&windows_spell_checker::BackgroundHelper:: RequestTextCheckForAllLanguages, base::Unretained(background_helper_.get()), document_tag, @@ -541,8 +540,8 @@ void WindowsSpellChecker::GetPerLanguageSuggestions( const std::u16string& word, spellcheck_platform::GetSuggestionsCallback callback) { - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &windows_spell_checker::BackgroundHelper::GetPerLanguageSuggestions, base::Unretained(background_helper_.get()), word), @@ -599,8 +598,8 @@ void WindowsSpellChecker::IsLanguageSupported( const std::string& lang_tag, base::OnceCallback<void(bool)> callback) { - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &windows_spell_checker::BackgroundHelper::IsLanguageSupported, base::Unretained(background_helper_.get()), lang_tag), @@ -609,8 +608,8 @@ void WindowsSpellChecker::RetrieveSpellcheckLanguages( spellcheck_platform::RetrieveSpellcheckLanguagesCompleteCallback callback) { - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &windows_spell_checker::BackgroundHelper::RetrieveSpellcheckLanguages, base::Unretained(background_helper_.get())),
diff --git a/components/storage_monitor/portable_device_watcher_win.cc b/components/storage_monitor/portable_device_watcher_win.cc index fdcca69..8cf07ac 100644 --- a/components/storage_monitor/portable_device_watcher_win.cc +++ b/components/storage_monitor/portable_device_watcher_win.cc
@@ -19,7 +19,6 @@ #include "base/logging.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/win/scoped_co_mem.h" @@ -586,8 +585,8 @@ DCHECK(media_task_runner_); DCHECK_CURRENTLY_ON(content::BrowserThread::UI); Devices* devices = new Devices; - base::PostTaskAndReplyWithResult( - media_task_runner_.get(), FROM_HERE, + media_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&EnumerateAttachedDevicesOnBlockingThread, devices), base::BindOnce(&PortableDeviceWatcherWin::OnDidEnumerateAttachedDevices, weak_ptr_factory_.GetWeakPtr(), base::Owned(devices))); @@ -610,8 +609,8 @@ DCHECK(media_task_runner_); DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DeviceDetails* device_details = new DeviceDetails; - base::PostTaskAndReplyWithResult( - media_task_runner_.get(), FROM_HERE, + media_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&HandleDeviceAttachedEventOnBlockingThread, pnp_device_id, device_details), base::BindOnce(&PortableDeviceWatcherWin::OnDidHandleDeviceAttachEvent,
diff --git a/components/storage_monitor/storage_monitor_chromeos.cc b/components/storage_monitor/storage_monitor_chromeos.cc index ce7c281b..d4fd28fc8 100644 --- a/components/storage_monitor/storage_monitor_chromeos.cc +++ b/components/storage_monitor/storage_monitor_chromeos.cc
@@ -17,7 +17,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/sequenced_task_runner_handle.h" @@ -144,8 +143,8 @@ for (const auto& mount_point : DiskMountManager::GetInstance()->mount_points()) { - base::PostTaskAndReplyWithResult( - blocking_task_runner.get(), FROM_HERE, + blocking_task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MediaStorageUtil::HasDcim, base::FilePath(mount_point.mount_path)), base::BindOnce(&StorageMonitorCros::AddMountedPath,
diff --git a/components/storage_monitor/storage_monitor_linux.cc b/components/storage_monitor/storage_monitor_linux.cc index 8e8dfb6..331fde8 100644 --- a/components/storage_monitor/storage_monitor_linux.cc +++ b/components/storage_monitor/storage_monitor_linux.cc
@@ -28,7 +28,6 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "components/storage_monitor/media_storage_util.h" @@ -258,8 +257,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!mtab_path_.empty()); - base::PostTaskAndReplyWithResult( - mtab_watcher_task_runner_.get(), FROM_HERE, + mtab_watcher_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CreateMtabWatcherLinuxOnMtabWatcherTaskRunner, mtab_path_, base::SequencedTaskRunner::GetCurrentDefault(), base::BindRepeating(&StorageMonitorLinux::UpdateMtab, @@ -416,8 +415,8 @@ if (IsDeviceAlreadyMounted(mount_device)) { HandleDeviceMountedMultipleTimes(mount_device, mount_point); } else { - base::PostTaskAndReplyWithResult( - mounting_task_runner.get(), FROM_HERE, + mounting_task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(get_device_info_callback_, mount_device, mount_point), base::BindOnce(&StorageMonitorLinux::AddNewMount,
diff --git a/components/storage_monitor/volume_mount_watcher_win.cc b/components/storage_monitor/volume_mount_watcher_win.cc index 0e0be836..5459b5cc 100644 --- a/components/storage_monitor/volume_mount_watcher_win.cc +++ b/components/storage_monitor/volume_mount_watcher_win.cc
@@ -25,7 +25,6 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "base/win/scoped_handle.h" @@ -347,8 +346,8 @@ // When VolumeMountWatcherWin is created, the message pumps are not running // so a posted task from the constructor would never run. Therefore, do all // the initializations here. - base::PostTaskAndReplyWithResult( - device_info_task_runner_.get(), FROM_HERE, GetAttachedDevicesCallback(), + device_info_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, GetAttachedDevicesCallback(), base::BindOnce(&VolumeMountWatcherWin::AddDevicesOnUIThread, weak_factory_.GetWeakPtr())); }
diff --git a/components/subresource_filter/content/browser/async_document_subresource_filter.cc b/components/subresource_filter/content/browser/async_document_subresource_filter.cc index 2e29758..89f100c 100644 --- a/components/subresource_filter/content/browser/async_document_subresource_filter.cc +++ b/components/subresource_filter/content/browser/async_document_subresource_filter.cc
@@ -10,7 +10,6 @@ #include "base/callback_helpers.h" #include "base/check_op.h" #include "base/location.h" -#include "base/task/task_runner_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "components/subresource_filter/core/common/memory_mapped_ruleset.h" #include "components/subresource_filter/core/common/scoped_timers.h" @@ -96,8 +95,8 @@ // because a task to delete it can only be posted to (and, therefore, // processed by) |task_runner| after this method returns, hence after the // below task is posted. - base::PostTaskAndReplyWithResult( - task_runner_, FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Core::Initialize, base::Unretained(core_.get()), std::move(params), ruleset_handle->ruleset_.get()), base::BindOnce(&AsyncDocumentSubresourceFilter::OnActivateStateCalculated, @@ -145,8 +144,8 @@ // TODO(pkalinnikov): Think about avoiding copy of |subdocument_url| if it is // too big and won't be allowed anyway (e.g., it's a data: URI). - base::PostTaskAndReplyWithResult( - task_runner_, FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( [](AsyncDocumentSubresourceFilter::Core* core, const GURL& subdocument_url) { @@ -169,8 +168,8 @@ // TODO(pkalinnikov): Think about avoiding copying of |urls| if they are // too big and won't be allowed anyway (e.g. data: URI). - base::PostTaskAndReplyWithResult( - task_runner_, FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&AsyncDocumentSubresourceFilter::Core::GetLoadPolicies, base::Unretained(core_.get()), urls), std::move(result_callback));
diff --git a/components/subresource_filter/content/browser/ruleset_service.cc b/components/subresource_filter/content/browser/ruleset_service.cc index 611ed273..0c7c867a8 100644 --- a/components/subresource_filter/content/browser/ruleset_service.cc +++ b/components/subresource_filter/content/browser/ruleset_service.cc
@@ -16,7 +16,6 @@ #include "base/numerics/safe_conversions.h" #include "base/strings/string_number_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/trace_event/trace_event.h" @@ -443,8 +442,8 @@ const UnindexedRulesetInfo& unindexed_ruleset_info, WriteRulesetCallback success_callback) { DCHECK(!unindexed_ruleset_info.content_version.empty()); - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&RulesetService::IndexAndWriteRuleset, indexed_ruleset_base_dir_, unindexed_ruleset_info), base::BindOnce(&RulesetService::OnWrittenRuleset, AsWeakPtr(),
diff --git a/components/subresource_filter/content/browser/ruleset_service_unittest.cc b/components/subresource_filter/content/browser/ruleset_service_unittest.cc index 3dcafb9..9a7628d 100644 --- a/components/subresource_filter/content/browser/ruleset_service_unittest.cc +++ b/components/subresource_filter/content/browser/ruleset_service_unittest.cc
@@ -25,7 +25,6 @@ #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/task_environment.h" #include "base/test/test_simple_task_runner.h" @@ -113,8 +112,8 @@ // Emulate |VerifiedRulesetDealer::Handle| behaviour: // 1. Open file on task runner. // 2. Reply with result on current thread runner. - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MockRulesetPublisherImpl::OpenRulesetFile, path), std::move(callback)); }
diff --git a/components/subresource_filter/content/browser/verified_ruleset_dealer.cc b/components/subresource_filter/content/browser/verified_ruleset_dealer.cc index 18de21f94..3fb2d73 100644 --- a/components/subresource_filter/content/browser/verified_ruleset_dealer.cc +++ b/components/subresource_filter/content/browser/verified_ruleset_dealer.cc
@@ -14,7 +14,6 @@ #include "base/metrics/histogram_macros.h" #include "base/notreached.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/trace_event/trace_event.h" #include "components/subresource_filter/core/common/indexed_ruleset.h" #include "components/subresource_filter/core/common/memory_mapped_ruleset.h" @@ -119,8 +118,8 @@ // |base::Unretained| is safe here because the |OpenAndSetRulesetFile| task // will be posted before a task to delete the pointer upon destruction of // |this| Handler. - base::PostTaskAndReplyWithResult( - task_runner_, FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&VerifiedRulesetDealer::OpenAndSetRulesetFile, base::Unretained(dealer_.get()), expected_checksum, path), std::move(callback));
diff --git a/components/sync/driver/glue/sync_engine_impl.cc b/components/sync/driver/glue/sync_engine_impl.cc index 20c864d9..dff519be 100644 --- a/components/sync/driver/glue/sync_engine_impl.cc +++ b/components/sync/driver/glue/sync_engine_impl.cc
@@ -16,7 +16,6 @@ #include "base/logging.h" #include "base/metrics/histogram_functions.h" #include "base/rand_util.h" -#include "base/task/task_runner_util.h" #include "build/build_config.h" #include "components/invalidation/impl/invalidation_switches.h" #include "components/invalidation/public/invalidation_handler.h" @@ -383,8 +382,8 @@ void SyncEngineImpl::HasUnsyncedItemsForTest( base::OnceCallback<void(bool)> cb) const { DCHECK(IsInitialized()); - base::PostTaskAndReplyWithResult( - sync_task_runner_.get(), FROM_HERE, + sync_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SyncEngineBackend::HasUnsyncedItemsForTest, backend_), std::move(cb)); }
diff --git a/components/sync/model/model_type_store_impl.cc b/components/sync/model/model_type_store_impl.cc index eaceaf63..bdd858b6 100644 --- a/components/sync/model/model_type_store_impl.cc +++ b/components/sync/model/model_type_store_impl.cc
@@ -11,7 +11,6 @@ #include "base/callback_helpers.h" #include "base/check_op.h" #include "base/location.h" -#include "base/task/task_runner_util.h" #include "components/sync/model/blocking_model_type_store_impl.h" #include "components/sync/model/metadata_batch.h" #include "components/sync/model/model_error.h" @@ -81,8 +80,8 @@ auto reply = base::BindOnce( &ModelTypeStoreImpl::ReadDataDone, weak_ptr_factory_.GetWeakPtr(), std::move(callback), std::move(record_list), std::move(missing_id_list)); - base::PostTaskAndReplyWithResult(backend_task_runner_.get(), FROM_HERE, - std::move(task), std::move(reply)); + backend_task_runner_->PostTaskAndReplyWithResult(FROM_HERE, std::move(task), + std::move(reply)); } void ModelTypeStoreImpl::ReadDataDone(ReadDataCallback callback, @@ -104,8 +103,8 @@ auto reply = base::BindOnce(&ModelTypeStoreImpl::ReadAllDataDone, weak_ptr_factory_.GetWeakPtr(), std::move(callback), std::move(record_list)); - base::PostTaskAndReplyWithResult(backend_task_runner_.get(), FROM_HERE, - std::move(task), std::move(reply)); + backend_task_runner_->PostTaskAndReplyWithResult(FROM_HERE, std::move(task), + std::move(reply)); } void ModelTypeStoreImpl::ReadAllDataDone( @@ -127,8 +126,8 @@ auto reply = base::BindOnce(&ModelTypeStoreImpl::ReadAllMetadataDone, weak_ptr_factory_.GetWeakPtr(), std::move(callback), std::move(metadata_batch)); - base::PostTaskAndReplyWithResult(backend_task_runner_.get(), FROM_HERE, - std::move(task), std::move(reply)); + backend_task_runner_->PostTaskAndReplyWithResult(FROM_HERE, std::move(task), + std::move(reply)); } void ModelTypeStoreImpl::ReadAllMetadataDone( @@ -161,8 +160,8 @@ base::BindOnce(&ModelTypeStoreImpl::ReadAllDataAndPreprocessDone, weak_ptr_factory_.GetWeakPtr(), std::move(completion_on_frontend_sequence_callback)); - base::PostTaskAndReplyWithResult(backend_task_runner_.get(), FROM_HERE, - std::move(task), std::move(reply)); + backend_task_runner_->PostTaskAndReplyWithResult(FROM_HERE, std::move(task), + std::move(reply)); } void ModelTypeStoreImpl::ReadAllDataAndPreprocessDone( @@ -180,8 +179,8 @@ auto reply = base::BindOnce(&ModelTypeStoreImpl::WriteModificationsDone, weak_ptr_factory_.GetWeakPtr(), std::move(callback)); - base::PostTaskAndReplyWithResult(backend_task_runner_.get(), FROM_HERE, - std::move(task), std::move(reply)); + backend_task_runner_->PostTaskAndReplyWithResult(FROM_HERE, std::move(task), + std::move(reply)); } std::unique_ptr<ModelTypeStore::WriteBatch> @@ -201,8 +200,8 @@ auto reply = base::BindOnce(&ModelTypeStoreImpl::WriteModificationsDone, weak_ptr_factory_.GetWeakPtr(), std::move(callback)); - base::PostTaskAndReplyWithResult(backend_task_runner_.get(), FROM_HERE, - std::move(task), std::move(reply)); + backend_task_runner_->PostTaskAndReplyWithResult(FROM_HERE, std::move(task), + std::move(reply)); } void ModelTypeStoreImpl::WriteModificationsDone(
diff --git a/components/sync/model/model_type_store_service_impl.cc b/components/sync/model/model_type_store_service_impl.cc index 565d430..46d43fc 100644 --- a/components/sync/model/model_type_store_service_impl.cc +++ b/components/sync/model/model_type_store_service_impl.cc
@@ -13,7 +13,6 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "components/sync/model/blocking_model_type_store_impl.h" @@ -88,8 +87,8 @@ auto reply = base::BindOnce(&ConstructModelTypeStoreOnFrontendSequence, type, backend_task_runner, std::move(callback)); - base::PostTaskAndReplyWithResult(backend_task_runner.get(), FROM_HERE, - std::move(task), std::move(reply)); + backend_task_runner->PostTaskAndReplyWithResult(FROM_HERE, std::move(task), + std::move(reply)); } } // namespace
diff --git a/components/sync/trusted_vault/standalone_trusted_vault_client.cc b/components/sync/trusted_vault/standalone_trusted_vault_client.cc index 4f165893..7f2c476 100644 --- a/components/sync/trusted_vault/standalone_trusted_vault_client.cc +++ b/components/sync/trusted_vault/standalone_trusted_vault_client.cc
@@ -13,7 +13,6 @@ #include "base/memory/ref_counted.h" #include "base/observer_list.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "components/signin/public/identity_manager/account_info.h" @@ -307,8 +306,8 @@ base::OnceCallback<void(bool)> cb) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(backend_); - base::PostTaskAndReplyWithResult( - backend_task_runner_.get(), FROM_HERE, + backend_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&StandaloneTrustedVaultBackend::MarkLocalKeysAsStale, backend_, account_info), std::move(cb)); @@ -361,8 +360,8 @@ base::OnceCallback<void(const absl::optional<CoreAccountInfo>&)> cb) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(backend_); - base::PostTaskAndReplyWithResult( - backend_task_runner_.get(), FROM_HERE, + backend_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &StandaloneTrustedVaultBackend::GetPrimaryAccountForTesting, backend_), @@ -374,8 +373,8 @@ base::OnceCallback<void(const std::vector<uint8_t>&)> callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(backend_); - base::PostTaskAndReplyWithResult( - backend_task_runner_.get(), FROM_HERE, + backend_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&StandaloneTrustedVaultBackend:: GetLastAddedRecoveryMethodPublicKeyForTesting, backend_),
diff --git a/components/viz/service/display/overlay_processor_surface_control.cc b/components/viz/service/display/overlay_processor_surface_control.cc index 0c54843c..8d80e04 100644 --- a/components/viz/service/display/overlay_processor_surface_control.cc +++ b/components/viz/service/display/overlay_processor_surface_control.cc
@@ -35,6 +35,17 @@ OverlayProcessorSurfaceControl::OverlayProcessorSurfaceControl() : OverlayProcessorUsingStrategy(), use_real_color_space_(features::UseRealVideoColorSpaceForDisplay()) { + // Android webview never sets |frame_sequence_number_| for the overlay + // processor. Android Chrome does set this variable because it does call draw. + // However, it also may not update this variable when displaying an overlay. + // Therefore, our damage tracking for overlays is incorrect and we must ignore + // the thresholding of prioritization. + + // TODO(crbug.com/1358093): We should take issue into account when trying to + // find a replacement for number-of-scanouts. + prioritization_config_.changing_threshold = false; + prioritization_config_.damage_rate_threshold = false; + strategies_.push_back(std::make_unique<OverlayStrategyUnderlay>( this, OverlayStrategyUnderlay::OpaqueMode::AllowTransparentCandidates)); }
diff --git a/components/webapps/browser/android/webapk/webapk_proto_builder.cc b/components/webapps/browser/android/webapk/webapk_proto_builder.cc index 4692287..6f1adc7f 100644 --- a/components/webapps/browser/android/webapk/webapk_proto_builder.cc +++ b/components/webapps/browser/android/webapk/webapk_proto_builder.cc
@@ -11,7 +11,6 @@ #include "base/files/file_util.h" #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "components/version_info/version_info.h" @@ -288,8 +287,8 @@ bool is_manifest_stale, bool is_app_identity_update_supported, base::OnceCallback<void(std::unique_ptr<std::string>)> callback) { - base::PostTaskAndReplyWithResult( - GetBackgroundTaskRunner().get(), FROM_HERE, + GetBackgroundTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&webapps::BuildProtoInBackground, shortcut_info, app_key, primary_icon_data, is_primary_icon_maskable, splash_icon_data, package_name, version,
diff --git a/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc b/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc index 6257a5c..127e9ada 100644 --- a/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc
@@ -26,6 +26,7 @@ #if BUILDFLAG(IS_MAC) constexpr const char kMacAction[]{"mac/action"}; +constexpr const char kMacAttributedString[]{"mac/attributed-string"}; constexpr const char kMacAttributes[]{"mac/attributes"}; constexpr const char kMacSelection[]{"mac/selection"}; constexpr const char kMacTextMarker[]{"mac/textmarker"}; @@ -423,6 +424,29 @@ RunTypedTest<kMacAttributes>("ax-visited.html"); } +IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, AttributedStringDeletion) { + RunTypedTest<kMacAttributedString>("deletion.html"); +} + +IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, AttributedStringInsertion) { + RunTypedTest<kMacAttributedString>("insertion.html"); +} + +IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, AttributedStringMark) { + RunTypedTest<kMacAttributedString>("mark.html"); +} + +IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, + AttributedStringNestedAnnotation) { + RunTypedTest<kMacAttributedString>( + "nested-suggestion-insertion-deletion.html"); +} + +IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, + AttributedStringSuggestion) { + RunTypedTest<kMacAttributedString>("suggestion.html"); +} + IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, ChromeAXNodeId) { RunTypedTest<kMacAttributes>("chrome-ax-node-id.html"); }
diff --git a/content/browser/download/download_manager_impl.cc b/content/browser/download/download_manager_impl.cc index fc78557..eec6081 100644 --- a/content/browser/download/download_manager_impl.cc +++ b/content/browser/download/download_manager_impl.cc
@@ -23,7 +23,6 @@ #include "base/supports_user_data.h" #include "base/synchronization/lock.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "build/build_config.h" #include "components/download/database/in_progress/download_entry.h" @@ -801,8 +800,8 @@ if (!pending_disk_access_query_.insert(download_item->GetId()).second) return; - base::PostTaskAndReplyWithResult( - disk_access_task_runner_.get(), FROM_HERE, + disk_access_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&base::PathExists, download_item->GetTargetFilePath()), base::BindOnce(&DownloadManagerImpl::OnFileExistenceChecked, weak_factory_.GetWeakPtr(), download_item->GetId()));
diff --git a/content/browser/download/mhtml_generation_manager.cc b/content/browser/download/mhtml_generation_manager.cc index 8cc5b74..89a93e7 100644 --- a/content/browser/download/mhtml_generation_manager.cc +++ b/content/browser/download/mhtml_generation_manager.cc
@@ -15,7 +15,6 @@ #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "base/task/task_runner_util.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" #include "base/types/optional_util.h" @@ -355,9 +354,8 @@ if (extra_parts) extra_data_parts_ = extra_parts->parts(); - base::PostTaskAndReplyWithResult( - download::GetDownloadTaskRunner().get(), FROM_HERE, - base::BindOnce(&CreateMHTMLFile, params_.file_path), + download::GetDownloadTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CreateMHTMLFile, params_.file_path), base::BindOnce(&Job::OnFileAvailable, weak_factory_.GetWeakPtr())); } @@ -621,8 +619,8 @@ save_status = mojom::MhtmlSaveStatus::kFileWritingError; // If no previous error occurred the boundary should be sent. - base::PostTaskAndReplyWithResult( - download::GetDownloadTaskRunner().get(), FROM_HERE, + download::GetDownloadTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MHTMLGenerationManager::Job::FinalizeOnFileThread, save_status, mhtml_boundary_marker_, std::move(browser_file_), std::move(extra_data_parts_),
diff --git a/content/browser/download/save_package.cc b/content/browser/download/save_package.cc index cdb2a8b..37d440f 100644 --- a/content/browser/download/save_package.cc +++ b/content/browser/download/save_package.cc
@@ -21,7 +21,6 @@ #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "base/unguessable_token.h" @@ -1391,8 +1390,8 @@ std::string mime_type = static_cast<PageImpl*>(page_.get())->contents_mime_type(); bool can_save_as_complete = CanSaveAsComplete(mime_type); - base::PostTaskAndReplyWithResult( - download::GetDownloadTaskRunner().get(), FROM_HERE, + download::GetDownloadTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SavePackage::CreateDirectoryOnFileThread, title_, page_url_, can_save_as_complete, mime_type, website_save_dir, download_save_dir),
diff --git a/content/browser/font_list_async.cc b/content/browser/font_list_async.cc index 86e679c5..c57cfca 100644 --- a/content/browser/font_list_async.cc +++ b/content/browser/font_list_async.cc
@@ -7,16 +7,15 @@ #include <utility> #include "base/bind.h" -#include "base/task/task_runner_util.h" #include "base/values.h" #include "content/common/font_list.h" namespace content { void GetFontListAsync(base::OnceCallback<void(base::Value::List)> callback) { - base::PostTaskAndReplyWithResult(GetFontListTaskRunner().get(), FROM_HERE, - base::BindOnce(&GetFontList_SlowBlocking), - std::move(callback)); + GetFontListTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetFontList_SlowBlocking), + std::move(callback)); } } // namespace content
diff --git a/content/browser/interest_group/auction_process_manager.cc b/content/browser/interest_group/auction_process_manager.cc index 9d7f97b..fc60a69 100644 --- a/content/browser/interest_group/auction_process_manager.cc +++ b/content/browser/interest_group/auction_process_manager.cc
@@ -10,7 +10,9 @@ #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" +#include "base/metrics/histogram_functions.h" #include "base/task/sequenced_task_runner.h" +#include "base/time/time.h" #include "base/timer/timer.h" #include "build/build_config.h" #include "content/public/browser/browser_context.h" @@ -44,6 +46,7 @@ : render_process_host_(render_process_host), worklet_type_(worklet_type), origin_(origin), + start_time_(base::TimeTicks::Now()), uses_shared_process_(uses_shared_process), auction_process_manager_(auction_process_manager), service_(std::move(service)) { @@ -85,6 +88,8 @@ } void OnLaunchedWithPid(base::ProcessId pid) { + base::UmaHistogramTimes("Ads.InterestGroup.Auction.ProcessLaunchTime", + base::TimeTicks::Now() - start_time_); DCHECK(!pid_.has_value()); pid_ = absl::make_optional<base::ProcessId>(pid); std::vector<base::OnceCallback<void(base::ProcessId)>> waiting_for_pid = @@ -132,6 +137,7 @@ const WorkletType worklet_type_; const url::Origin origin_; + const base::TimeTicks start_time_; bool uses_shared_process_; absl::optional<base::ProcessId> pid_;
diff --git a/content/browser/interest_group/interest_group_auction.cc b/content/browser/interest_group/interest_group_auction.cc index 259892ef..44c1421 100644 --- a/content/browser/interest_group/interest_group_auction.cc +++ b/content/browser/interest_group/interest_group_auction.cc
@@ -620,7 +620,10 @@ // If `new_priority` has a value and is negative, need to record the bidder // as no longer participating in the auction and cancel bid generation. - if (new_priority.has_value() && *new_priority < 0) { + bool bid_filtered = new_priority.has_value() && *new_priority < 0; + UMA_HISTOGRAM_BOOLEAN("Ads.InterestGroup.Auction.BidFiltered", + bid_filtered); + if (bid_filtered) { // Record if there are other bidders, as if there are not, the next call // may delete `this`. bool other_bidders = (num_outstanding_bids_ > 1); @@ -971,6 +974,7 @@ config_(config), parent_(parent), auction_start_time_(auction_start_time), + creation_time_(base::TimeTicks::Now()), subresource_url_builder_(std::make_unique<SubresourceUrlBuilder>( config->direct_from_seller_signals)) { TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("fledge", "auction", trace_id_, @@ -1002,18 +1006,18 @@ switch (*final_auction_result_) { case AuctionResult::kAborted: UMA_HISTOGRAM_MEDIUM_TIMES("Ads.InterestGroup.Auction.AbortTime", - base::Time::Now() - auction_start_time_); + base::TimeTicks::Now() - creation_time_); break; case AuctionResult::kNoBids: case AuctionResult::kAllBidsRejected: UMA_HISTOGRAM_MEDIUM_TIMES( "Ads.InterestGroup.Auction.CompletedWithoutWinnerTime", - base::Time::Now() - auction_start_time_); + base::TimeTicks::Now() - creation_time_); break; case AuctionResult::kSuccess: UMA_HISTOGRAM_MEDIUM_TIMES( "Ads.InterestGroup.Auction.AuctionWithWinnerTime", - base::Time::Now() - auction_start_time_); + base::TimeTicks::Now() - creation_time_); break; default: break; @@ -1630,6 +1634,13 @@ DCHECK(!final_auction_result_); TRACE_EVENT_NESTABLE_ASYNC_END0("fledge", "load_groups_phase", trace_id_); + if (auction_result == AuctionResult::kNoInterestGroups) { + UMA_HISTOGRAM_TIMES("Ads.InterestGroup.Auction.LoadNoGroupsTime", + base::TimeTicks::Now() - creation_time_); + } else { + UMA_HISTOGRAM_TIMES("Ads.InterestGroup.Auction.LoadGroupsTime", + base::TimeTicks::Now() - creation_time_); + } // `final_auction_result_` should only be set to kSuccess when the entire // auction is complete.
diff --git a/content/browser/interest_group/interest_group_auction.h b/content/browser/interest_group/interest_group_auction.h index b47a0c0..d47a7fd 100644 --- a/content/browser/interest_group/interest_group_auction.h +++ b/content/browser/interest_group/interest_group_auction.h
@@ -744,6 +744,8 @@ // The time the auction started. Use a single base time for all Worklets, to // present a more consistent view of the universe. const base::Time auction_start_time_; + // The time when this InterestGroupAuction was created; used for UMA. + const base::TimeTicks creation_time_; // Holds the computed subresource URLs (renderer-supplied prefix + browser // produced suffix).
diff --git a/content/browser/interest_group/interest_group_k_anonymity_manager.cc b/content/browser/interest_group/interest_group_k_anonymity_manager.cc index 58a87357..a586c934 100644 --- a/content/browser/interest_group/interest_group_k_anonymity_manager.cc +++ b/content/browser/interest_group/interest_group_k_anonymity_manager.cc
@@ -11,10 +11,6 @@ namespace content { -std::string KAnonKeyFor(const url::Origin& owner, const std::string& name) { - return owner.GetURL().spec() + '\n' + name; -} - std::string KAnonKeyForAdBid(const blink::InterestGroup& group, const blink::InterestGroup::Ad& ad) { DCHECK(group.ads); @@ -23,7 +19,6 @@ DCHECK(group.bidding_url); return group.owner.GetURL().spec() + '\n' + group.bidding_url.value_or(GURL()).spec() + '\n' + - group.bidding_wasm_helper_url.value_or(GURL()).spec() + '\n' + ad.render_url.spec(); } @@ -32,10 +27,9 @@ DCHECK(group.ads); DCHECK(base::Contains(*group.ads, ad)); DCHECK(group.bidding_url); - return group.owner.GetURL().spec() + '\n' + group.name + '\n' + + return group.owner.GetURL().spec() + '\n' + group.bidding_url.value_or(GURL()).spec() + '\n' + - group.bidding_wasm_helper_url.value_or(GURL()).spec() + '\n' + - ad.render_url.spec(); + ad.render_url.spec() + '\n' + group.name; } InterestGroupKAnonymityManager::InterestGroupKAnonymityManager( @@ -56,21 +50,6 @@ base::Time check_time = base::Time::Now(); base::TimeDelta min_wait = k_anonymity_service_->GetQueryInterval(); - if (!storage_group.name_kanon || - storage_group.name_kanon->last_updated < check_time - min_wait) { - ids_to_query.push_back(KAnonKeyFor(storage_group.interest_group.owner, - storage_group.interest_group.name)); - } - - if (storage_group.interest_group.daily_update_url) { - if (!storage_group.daily_update_url_kanon || - storage_group.daily_update_url_kanon->last_updated < - check_time - min_wait) { - ids_to_query.push_back( - storage_group.interest_group.daily_update_url->spec()); - } - } - for (const auto& ad : storage_group.bidding_ads_kanon) { if (ad.last_updated < check_time - min_wait) { ids_to_query.push_back(ad.key); @@ -112,13 +91,6 @@ } } -void InterestGroupKAnonymityManager::RegisterInterestGroupAsJoined( - const blink::InterestGroup& group) { - RegisterIDAsJoined(KAnonKeyFor(group.owner, group.name)); - if (group.daily_update_url) - RegisterIDAsJoined(group.daily_update_url->spec()); -} - void InterestGroupKAnonymityManager::RegisterAdAsWon( const blink::InterestGroup& group, const blink::InterestGroup::Ad& ad) {
diff --git a/content/browser/interest_group/interest_group_k_anonymity_manager.h b/content/browser/interest_group/interest_group_k_anonymity_manager.h index 472013e..53a55cee 100644 --- a/content/browser/interest_group/interest_group_k_anonymity_manager.h +++ b/content/browser/interest_group/interest_group_k_anonymity_manager.h
@@ -46,11 +46,6 @@ void QueryKAnonymityForInterestGroup( const StorageInterestGroup& storage_group); - // Notify the k-anonymity service that we are joining this interest group. - // Internally this calls RegisterIDAsJoined() for interest group name and - // update URL. - void RegisterInterestGroupAsJoined(const blink::InterestGroup& group); - // Notify the k-anonymity service that this ad won an auction. Internally this // calls RegisterIDAsJoined(). void RegisterAdAsWon(const blink::InterestGroup& group,
diff --git a/content/browser/interest_group/interest_group_k_anonymity_manager_unittest.cc b/content/browser/interest_group/interest_group_k_anonymity_manager_unittest.cc index 628df7a..653fe2b 100644 --- a/content/browser/interest_group/interest_group_k_anonymity_manager_unittest.cc +++ b/content/browser/interest_group/interest_group_k_anonymity_manager_unittest.cc
@@ -150,14 +150,14 @@ manager->JoinInterestGroup(MakeInterestGroup(owner, "foo"), top_frame); auto maybe_group = getGroup(manager.get(), owner, name); ASSERT_TRUE(maybe_group); - EXPECT_EQ(base::Time::Min(), maybe_group->name_kanon->last_updated); + EXPECT_EQ(base::Time::Min(), maybe_group->bidding_ads_kanon[0].last_updated); // k-anonymity update happens here. task_environment().FastForwardBy(base::Minutes(1)); maybe_group = getGroup(manager.get(), owner, name); ASSERT_TRUE(maybe_group); - base::Time last_updated = maybe_group->name_kanon->last_updated; + base::Time last_updated = maybe_group->bidding_ads_kanon[0].last_updated; EXPECT_LE(before_join, last_updated); EXPECT_GT(base::Time::Now(), last_updated); @@ -167,7 +167,7 @@ maybe_group = getGroup(manager.get(), owner, name); ASSERT_TRUE(maybe_group); - EXPECT_EQ(last_updated, maybe_group->name_kanon->last_updated); + EXPECT_EQ(last_updated, maybe_group->bidding_ads_kanon[0].last_updated); task_environment().FastForwardBy(kQueryInterval); @@ -176,59 +176,7 @@ task_environment().RunUntilIdle(); maybe_group = getGroup(manager.get(), owner, name); ASSERT_TRUE(maybe_group); - EXPECT_LT(last_updated, maybe_group->name_kanon->last_updated); -} - -TEST_F(InterestGroupKAnonymityManagerTest, QueueUpdatePerformsJoinSetForGroup) { - const GURL top_frame = GURL("https://www.example.com/foo"); - const url::Origin owner = url::Origin::Create(top_frame); - const std::string name = "foo"; - - std::string group_name_url = "https://www.example.com/\nfoo"; - std::string group_update_url = kUpdateURL; - - auto manager = CreateManager(); - EXPECT_EQ(base::Time::Min(), GetLastReported(manager.get(), group_name_url)); - EXPECT_FALSE(getGroup(manager.get(), owner, name)); - base::Time before_join = base::Time::Now(); - - // JoinInterestGroup should call QueueKAnonymityUpdateForInterestGroup. - manager->JoinInterestGroup(MakeInterestGroup(owner, "foo"), top_frame); - - // k-anonymity update happens here. - task_environment().FastForwardBy(base::Minutes(1)); - - EXPECT_TRUE(getGroup(manager.get(), owner, name)); - - absl::optional<base::Time> group_name_reported = - GetLastReported(manager.get(), group_name_url); - ASSERT_TRUE(group_name_reported); - EXPECT_LE(before_join, group_name_reported); - - absl::optional<base::Time> update_url_reported = - GetLastReported(manager.get(), kUpdateURL); - ASSERT_TRUE(update_url_reported); - EXPECT_LE(before_join, update_url_reported); - - auto maybe_group = getGroup(manager.get(), owner, name); - ASSERT_TRUE(maybe_group); - - manager->QueueKAnonymityUpdateForInterestGroup(*maybe_group); - - // k-anonymity update would happen here. - task_environment().FastForwardBy(base::Minutes(1)); - - // Second update shouldn't change anything. - EXPECT_EQ(group_name_reported, - GetLastReported(manager.get(), group_name_url)); - EXPECT_EQ(update_url_reported, GetLastReported(manager.get(), kUpdateURL)); - - task_environment().FastForwardBy(kJoinInterval); - - // Updated more than GetJoinInterval() ago, so update. - manager->QueueKAnonymityUpdateForInterestGroup(*maybe_group); - task_environment().RunUntilIdle(); - EXPECT_LT(update_url_reported, GetLastReported(manager.get(), kUpdateURL)); + EXPECT_LT(last_updated, maybe_group->bidding_ads_kanon[0].last_updated); } TEST_F(InterestGroupKAnonymityManagerTest, RegisterAdAsWonPerformsJoinSet) { @@ -290,9 +238,12 @@ base::Time start_time = base::Time::Now(); auto manager = CreateManager(/*has_error=*/true); - manager->JoinInterestGroup(MakeInterestGroup(owner, "foo"), top_frame); + blink::InterestGroup g = MakeInterestGroup(owner, "foo"); + + manager->JoinInterestGroup(g, top_frame); // The group *must* exist when JoinInterestGroup returns. ASSERT_TRUE(getGroup(manager.get(), owner, name)); + manager->RegisterAdAsWon(g, g.ads.value()[0]); // k-anonymity update happens here. task_environment().FastForwardBy(base::Minutes(1)); @@ -304,20 +255,21 @@ // When the server is actually implemented we'll need to change the expected // values below. - absl::optional<base::Time> group_name_reported = - GetLastReported(manager.get(), kUpdateURL); - ASSERT_TRUE(group_name_reported); + absl::optional<base::Time> ad_reported = + GetLastAdReported(manager.get(), g, g.ads.value()[0]); + ASSERT_TRUE(ad_reported); // TODO(behamilton): Change this once we expect the server to be stable. - EXPECT_LE(start_time, group_name_reported); + EXPECT_LE(start_time, ad_reported); // EXPECT_EQ(base::Time::Min(), group_name_reported); auto maybe_group = getGroup(manager.get(), owner, name); ASSERT_TRUE(maybe_group); // TODO(behamilton): Change this once we expect the server to be stable. - EXPECT_LE(start_time, maybe_group->name_kanon->last_updated); - // EXPECT_EQ(base::Time::Min(), maybe_group->name_kanon->last_updated); + EXPECT_LE(start_time, maybe_group->bidding_ads_kanon[0].last_updated); + // EXPECT_EQ(base::Time::Min(), + // maybe_group->bidding_ads_kanon[0].last_updated); } class MockAnonymityServiceDelegate : public KAnonymityServiceDelegate {
diff --git a/content/browser/interest_group/interest_group_manager_impl.cc b/content/browser/interest_group/interest_group_manager_impl.cc index f7648b4..db4d8db 100644 --- a/content/browser/interest_group/interest_group_manager_impl.cc +++ b/content/browser/interest_group/interest_group_manager_impl.cc
@@ -327,7 +327,6 @@ void InterestGroupManagerImpl::QueueKAnonymityUpdateForInterestGroup( const StorageInterestGroup& group) { k_anonymity_manager_->QueryKAnonymityForInterestGroup(group); - k_anonymity_manager_->RegisterInterestGroupAsJoined(group.interest_group); } void InterestGroupManagerImpl::UpdateKAnonymity(
diff --git a/content/browser/interest_group/interest_group_storage.cc b/content/browser/interest_group/interest_group_storage.cc index 7cb565d..14242892 100644 --- a/content/browser/interest_group/interest_group_storage.cc +++ b/content/browser/interest_group/interest_group_storage.cc
@@ -1394,21 +1394,6 @@ return interest_group_kanon.Succeeded(); } -bool DoGetInterestGroupNameKAnonymity( - sql::Database& db, - const url::Origin& owner, - const std::string& name, - absl::optional<StorageInterestGroup::KAnonymityData>& output) { - return DoGetKAnonymity(db, KAnonKeyFor(owner, name), output); -} - -bool DoGetURLKAnonymity( - sql::Database& db, - const GURL& url, - absl::optional<StorageInterestGroup::KAnonymityData>& output) { - return DoGetKAnonymity(db, url.spec(), output); -} - bool GetPreviousWins(sql::Database& db, const blink::InterestGroupKey& group_key, base::Time win_time_after, @@ -1536,26 +1521,6 @@ return absl::nullopt; } - if (!DoGetInterestGroupNameKAnonymity(db, group_key.owner, group_key.name, - db_interest_group.name_kanon)) { - // This should only happen if the database was created with an older version - // of the k-anon key for interest group names. Try the old group name. - // TODO(behamilton): Remove this in a new version - if (!DoGetKAnonymity(db, - group_key.owner.GetURL() - .Resolve(base::EscapePath(group_key.name)) - .spec(), - db_interest_group.name_kanon)) - return absl::nullopt; - db_interest_group.name_kanon->key = - KAnonKeyFor(group_key.owner, group_key.name); - } - if (db_interest_group.interest_group.daily_update_url && - !DoGetURLKAnonymity( - db, db_interest_group.interest_group.daily_update_url.value(), - db_interest_group.daily_update_url_kanon)) { - return absl::nullopt; - } if (db_interest_group.interest_group.bidding_url) { if (db_interest_group.interest_group.ads) { for (auto& ad : db_interest_group.interest_group.ads.value()) {
diff --git a/content/browser/interest_group/interest_group_storage_unittest.cc b/content/browser/interest_group/interest_group_storage_unittest.cc index afed2335..6af5f73 100644 --- a/content/browser/interest_group/interest_group_storage_unittest.cc +++ b/content/browser/interest_group/interest_group_storage_unittest.cc
@@ -416,171 +416,6 @@ EXPECT_EQ(0u, origins.size()); } -// Test updating k-anonymity data for interest group names. Uses two Interest -// Groups with similar names, which should not share k-anonymity data, to -// verify database key creation works correctly. -TEST_F(InterestGroupStorageTest, UpdatesInterestGroupNameKAnonymity) { - const url::Origin test_origin = - url::Origin::Create(GURL("https://owner.example.com")); - const std::string name = "name with space"; - const std::string name2 = "name%20with%20space"; - - const std::string key = test_origin.GetURL().spec() + '\n' + name; - const std::string key2 = test_origin.GetURL().spec() + '\n' + name2; - - std::unique_ptr<InterestGroupStorage> storage = CreateStorage(); - - std::vector<StorageInterestGroup> groups = - storage->GetInterestGroupsForOwner(test_origin); - - EXPECT_EQ(0u, groups.size()); - - storage->JoinInterestGroup(NewInterestGroup(test_origin, name), - GURL("https://owner.example.com/join")); - // Add a little delay so groups are returned in a deterministic order. - // Interest groups are returned in descending order based on expiration time. - task_environment().FastForwardBy(base::Microseconds(1)); - storage->JoinInterestGroup(NewInterestGroup(test_origin, name2), - GURL("https://owner.example.com/join")); - - groups = storage->GetInterestGroupsForOwner(test_origin); - - ASSERT_EQ(2u, groups.size()); - EXPECT_EQ(name, groups[1].interest_group.name); - ASSERT_TRUE(groups[1].name_kanon); - EXPECT_EQ(key, groups[1].name_kanon->key); - EXPECT_EQ(false, groups[1].name_kanon->is_k_anonymous); - EXPECT_EQ(base::Time::Min(), groups[1].name_kanon->last_updated); - - EXPECT_EQ(name2, groups[0].interest_group.name); - ASSERT_TRUE(groups[0].name_kanon); - EXPECT_EQ(key2, groups[0].name_kanon->key); - EXPECT_EQ(false, groups[0].name_kanon->is_k_anonymous); - EXPECT_EQ(base::Time::Min(), groups[0].name_kanon->last_updated); - - base::Time update_time = base::Time::Now(); - StorageInterestGroup::KAnonymityData kanon{key, true, update_time}; - storage->UpdateKAnonymity(kanon); - - groups = storage->GetInterestGroupsForOwner(test_origin); - - ASSERT_EQ(2u, groups.size()); - EXPECT_EQ(name, groups[1].interest_group.name); - ASSERT_TRUE(groups[1].name_kanon); - EXPECT_EQ(key, groups[1].name_kanon->key); - EXPECT_EQ(true, groups[1].name_kanon->is_k_anonymous); - EXPECT_EQ(update_time, groups[1].name_kanon->last_updated); - - EXPECT_EQ(name2, groups[0].interest_group.name); - ASSERT_TRUE(groups[0].name_kanon); - EXPECT_EQ(key2, groups[0].name_kanon->key); - EXPECT_EQ(false, groups[0].name_kanon->is_k_anonymous); - EXPECT_EQ(base::Time::Min(), groups[0].name_kanon->last_updated); - - task_environment().FastForwardBy(base::Seconds(1)); - - update_time = base::Time::Now(); - kanon = StorageInterestGroup::KAnonymityData{key, true, update_time}; - storage->UpdateKAnonymity(kanon); - - groups = storage->GetInterestGroupsForOwner(test_origin); - - ASSERT_EQ(2u, groups.size()); - EXPECT_EQ(name, groups[1].interest_group.name); - ASSERT_TRUE(groups[1].name_kanon); - EXPECT_EQ(key, groups[1].name_kanon->key); - EXPECT_EQ(true, groups[1].name_kanon->is_k_anonymous); - EXPECT_EQ(update_time, groups[1].name_kanon->last_updated); - - EXPECT_EQ(name2, groups[0].interest_group.name); - ASSERT_TRUE(groups[0].name_kanon); - EXPECT_EQ(key2, groups[0].name_kanon->key); - EXPECT_EQ(false, groups[0].name_kanon->is_k_anonymous); - EXPECT_EQ(base::Time::Min(), groups[0].name_kanon->last_updated); -} - -// Tests updating the Interest Group Update URL k-anonymity data works and -// is shared for both interest groups if they share the same update URL. -TEST_F(InterestGroupStorageTest, UpdatesInterestGroupUpdateURLKAnonymity) { - GURL daily_update_url("https://owner.example.com/group1Update"); - url::Origin test_origin = url::Origin::Create(daily_update_url); - - std::unique_ptr<InterestGroupStorage> storage = CreateStorage(); - std::vector<StorageInterestGroup> groups = - storage->GetInterestGroupsForOwner(test_origin); - - EXPECT_EQ(0u, groups.size()); - - InterestGroup g = NewInterestGroup(test_origin, "name"); - g.daily_update_url = daily_update_url; - storage->JoinInterestGroup(g, GURL("https://owner.example.com/join")); - - // Add a little delay so groups are returned in a deterministic order. - // Interest groups are returned in descending order based on expiration time. - task_environment().FastForwardBy(base::Microseconds(1)); - - InterestGroup g2 = NewInterestGroup(test_origin, "name2"); - g2.daily_update_url = daily_update_url; - storage->JoinInterestGroup(g2, GURL("https://owner.example.com/join2")); - - groups = storage->GetInterestGroupsForOwner(test_origin); - - ASSERT_EQ(2u, groups.size()); - EXPECT_EQ("name2", groups[0].interest_group.name); - ASSERT_TRUE(groups[0].daily_update_url_kanon); - EXPECT_EQ(daily_update_url, groups[0].daily_update_url_kanon->key); - EXPECT_EQ(false, groups[0].daily_update_url_kanon->is_k_anonymous); - EXPECT_EQ(base::Time::Min(), groups[0].daily_update_url_kanon->last_updated); - - EXPECT_EQ("name", groups[1].interest_group.name); - ASSERT_TRUE(groups[1].daily_update_url_kanon); - EXPECT_EQ(daily_update_url, groups[1].daily_update_url_kanon->key); - EXPECT_EQ(false, groups[1].daily_update_url_kanon->is_k_anonymous); - EXPECT_EQ(base::Time::Min(), groups[1].daily_update_url_kanon->last_updated); - - base::Time update_time = base::Time::Now(); - StorageInterestGroup::KAnonymityData kanon{daily_update_url.spec(), true, - update_time}; - storage->UpdateKAnonymity(kanon); - - groups = storage->GetInterestGroupsForOwner(test_origin); - - ASSERT_EQ(2u, groups.size()); - EXPECT_EQ("name2", groups[0].interest_group.name); - ASSERT_TRUE(groups[0].daily_update_url_kanon); - EXPECT_EQ(daily_update_url, groups[0].daily_update_url_kanon->key); - EXPECT_EQ(true, groups[0].daily_update_url_kanon->is_k_anonymous); - EXPECT_EQ(update_time, groups[0].daily_update_url_kanon->last_updated); - - EXPECT_EQ("name", groups[1].interest_group.name); - ASSERT_TRUE(groups[1].daily_update_url_kanon); - EXPECT_EQ(daily_update_url, groups[1].daily_update_url_kanon->key); - EXPECT_EQ(true, groups[1].daily_update_url_kanon->is_k_anonymous); - EXPECT_EQ(update_time, groups[1].daily_update_url_kanon->last_updated); - - task_environment().FastForwardBy(base::Seconds(1)); - - update_time = base::Time::Now(); - kanon = StorageInterestGroup::KAnonymityData{daily_update_url.spec(), true, - update_time}; - storage->UpdateKAnonymity(kanon); - - groups = storage->GetInterestGroupsForOwner(test_origin); - - ASSERT_EQ(2u, groups.size()); - EXPECT_EQ("name2", groups[0].interest_group.name); - ASSERT_TRUE(groups[0].daily_update_url_kanon); - EXPECT_EQ(daily_update_url, groups[0].daily_update_url_kanon->key); - EXPECT_EQ(true, groups[0].daily_update_url_kanon->is_k_anonymous); - EXPECT_EQ(update_time, groups[0].daily_update_url_kanon->last_updated); - - EXPECT_EQ("name", groups[1].interest_group.name); - ASSERT_TRUE(groups[1].daily_update_url_kanon); - EXPECT_EQ(daily_update_url, groups[1].daily_update_url_kanon->key); - EXPECT_EQ(true, groups[1].daily_update_url_kanon->is_k_anonymous); - EXPECT_EQ(update_time, groups[1].daily_update_url_kanon->last_updated); -} - TEST_F(InterestGroupStorageTest, UpdatesAdKAnonymity) { url::Origin test_origin = url::Origin::Create(GURL("https://owner.example.com")); @@ -700,14 +535,9 @@ KAnonKeyForAdNameReporting(g, g.ads.value()[0]), true, update_kanon_time}; StorageInterestGroup::KAnonymityData ad2_bid_kanon{ KAnonKeyForAdBid(g, g.ad_components.value()[0]), true, update_kanon_time}; - StorageInterestGroup::KAnonymityData update_kanon{daily_update_url.spec(), - true, update_kanon_time}; - StorageInterestGroup::KAnonymityData name_kanon{key, true, update_kanon_time}; storage->UpdateKAnonymity(ad1_bid_kanon); storage->UpdateKAnonymity(ad1_report_kanon); storage->UpdateKAnonymity(ad2_bid_kanon); - storage->UpdateKAnonymity(update_kanon); - storage->UpdateKAnonymity(name_kanon); // Check k-anonymity data was correctly set. std::vector<StorageInterestGroup> groups = @@ -717,10 +547,6 @@ testing::UnorderedElementsAre(ad1_bid_kanon, ad2_bid_kanon)); EXPECT_THAT(groups[0].reporting_ads_kanon, testing::UnorderedElementsAre(ad1_report_kanon)); - ASSERT_TRUE(groups[0].daily_update_url_kanon); - EXPECT_EQ(update_kanon, groups[0].daily_update_url_kanon.value()); - ASSERT_TRUE(groups[0].name_kanon); - EXPECT_EQ(name_kanon, groups[0].name_kanon.value()); // Fast-forward past interest group expiration. task_environment().FastForwardBy(base::Days(2)); @@ -740,10 +566,6 @@ testing::UnorderedElementsAre(ad1_bid_kanon, ad2_bid_kanon)); EXPECT_THAT(groups[0].reporting_ads_kanon, testing::UnorderedElementsAre(ad1_report_kanon)); - ASSERT_TRUE(groups[0].daily_update_url_kanon); - EXPECT_EQ(update_kanon, groups[0].daily_update_url_kanon.value()); - ASSERT_TRUE(groups[0].name_kanon); - EXPECT_EQ(name_kanon, groups[0].name_kanon.value()); // Fast-forward past interest group and kanon value expiration. task_environment().FastForwardBy(InterestGroupStorage::kHistoryLength); @@ -767,19 +589,12 @@ /*is_k_anonymous=*/false, base::Time::Min()}; ad2_bid_kanon = {KAnonKeyForAdBid(g, g.ad_components.value()[0]), /*is_k_anonymous=*/false, base::Time::Min()}; - update_kanon = {daily_update_url.spec(), /*is_k_anonymous=*/false, - base::Time::Min()}; - name_kanon = {key, /*is_k_anonymous=*/false, base::Time::Min()}; groups = storage->GetInterestGroupsForOwner(test_origin); ASSERT_EQ(1u, groups.size()); EXPECT_THAT(groups[0].bidding_ads_kanon, testing::UnorderedElementsAre(ad1_bid_kanon, ad2_bid_kanon)); EXPECT_THAT(groups[0].reporting_ads_kanon, testing::UnorderedElementsAre(ad1_report_kanon)); - ASSERT_TRUE(groups[0].daily_update_url_kanon); - EXPECT_EQ(update_kanon, groups[0].daily_update_url_kanon.value()); - ASSERT_TRUE(groups[0].name_kanon); - EXPECT_EQ(name_kanon, groups[0].name_kanon.value()); } TEST_F(InterestGroupStorageTest, StoresAllFields) { @@ -887,16 +702,24 @@ url::Origin::Create(GURL("https://joinerA.example.com")); const url::Origin joining_originB = url::Origin::Create(GURL("https://joinerB.example.com")); + + GURL ad1_url = GURL("https://owner.example.com/ad1"); + + InterestGroup g1 = NewInterestGroup(owner_originA, "example"); + g1.ads.emplace(); + g1.ads->push_back(blink::InterestGroup::Ad(ad1_url, "metadata1")); + + std::string k_anon_key = KAnonKeyForAdBid(g1, g1.ads.value()[0]); + std::unique_ptr<InterestGroupStorage> storage = CreateStorage(); - storage->JoinInterestGroup(NewInterestGroup(owner_originA, "example"), - joining_originA.GetURL()); + storage->JoinInterestGroup(g1, joining_originA.GetURL()); storage->JoinInterestGroup(NewInterestGroup(owner_originB, "example"), joining_originA.GetURL()); storage->JoinInterestGroup(NewInterestGroup(owner_originC, "example"), joining_originA.GetURL()); storage->JoinInterestGroup(NewInterestGroup(owner_originB, "exampleB"), joining_originB.GetURL()); - storage->UpdateLastKAnonymityReported(KAnonKeyFor(owner_originA, "example")); + storage->UpdateLastKAnonymityReported(k_anon_key); std::vector<url::Origin> origins = storage->GetAllInterestGroupOwners(); EXPECT_THAT(origins, UnorderedElementsAre(owner_originA, owner_originB, @@ -935,13 +758,11 @@ EXPECT_EQ(0u, origins.size()); // DeleteInterestGroupData shouldn't have deleted kanon data. - EXPECT_NE(base::Time::Min(), storage->GetLastKAnonymityReported( - KAnonKeyFor(owner_originA, "example"))); + EXPECT_NE(base::Time::Min(), storage->GetLastKAnonymityReported(k_anon_key)); storage->DeleteAllInterestGroupData(); // DeleteAllInterestGroupData should have deleted *everything*. - EXPECT_EQ(base::Time::Min(), storage->GetLastKAnonymityReported( - KAnonKeyFor(owner_originA, "example"))); + EXPECT_EQ(base::Time::Min(), storage->GetLastKAnonymityReported(k_anon_key)); } // Maintenance should prune the number of interest groups and interest group @@ -1232,20 +1053,11 @@ "bid_count", &auction_worklet::mojom::BiddingBrowserSignals::bid_count, 4)))), - Field("name_kanon", &StorageInterestGroup::name_kanon, - StorageInterestGroup::KAnonymityData{ - "https://owner.example.com/\ngroup1", false, - base::Time::Min()}), - Field("daily_update_url_kanon", - &StorageInterestGroup::daily_update_url_kanon, - StorageInterestGroup::KAnonymityData{ - "https://owner.example.com/update", false, - base::Time::Min()}), Field("bidding_ads_kanon", &StorageInterestGroup::bidding_ads_kanon, testing::UnorderedElementsAre( StorageInterestGroup::KAnonymityData{ "https://owner.example.com/\n" - "https://owner.example.com/bidder.js\n\n" + "https://owner.example.com/bidder.js\n" "https://ads.example.com/1", false, base::Time::Min()})), Field("reporting_ads_kanon", @@ -1253,9 +1065,9 @@ testing::UnorderedElementsAre( StorageInterestGroup::KAnonymityData{ "https://owner.example.com/\n" - "group1\n" - "https://owner.example.com/bidder.js\n\n" - "https://ads.example.com/1", + "https://owner.example.com/bidder.js\n" + "https://ads.example.com/1\n" + "group1", false, base::Time::Min()})), Field("joining_origin", &StorageInterestGroup::joining_origin, url::Origin::Create(GURL("https://publisher.example.com"))), @@ -1324,20 +1136,11 @@ "bid_count", &auction_worklet::mojom::BiddingBrowserSignals::bid_count, 3)))), - Field("name_kanon", &StorageInterestGroup::name_kanon, - StorageInterestGroup::KAnonymityData{ - "https://owner.example.com/\ngroup2", false, - base::Time::Min()}), - Field("daily_update_url_kanon", - &StorageInterestGroup::daily_update_url_kanon, - StorageInterestGroup::KAnonymityData{ - "https://owner.example.com/update", false, - base::Time::Min()}), Field("bidding_ads_kanon", &StorageInterestGroup::bidding_ads_kanon, testing::UnorderedElementsAre( StorageInterestGroup::KAnonymityData{ "https://owner.example.com/\n" - "https://owner.example.com/bidder.js\n\n" + "https://owner.example.com/bidder.js\n" "https://ads.example.com/1", false, base::Time::Min()})), Field("reporting_ads_kanon", @@ -1345,9 +1148,9 @@ testing::UnorderedElementsAre( StorageInterestGroup::KAnonymityData{ "https://owner.example.com/\n" - "group2\n" - "https://owner.example.com/bidder.js\n\n" - "https://ads.example.com/1", + "https://owner.example.com/bidder.js\n" + "https://ads.example.com/1\n" + "group2", false, base::Time::Min()})), Field("joining_origin", &StorageInterestGroup::joining_origin, url::Origin::Create(GURL("https://publisher.example.com"))), @@ -1416,20 +1219,11 @@ "bid_count", &auction_worklet::mojom::BiddingBrowserSignals::bid_count, 4)))), - Field("name_kanon", &StorageInterestGroup::name_kanon, - StorageInterestGroup::KAnonymityData{ - "https://owner.example.com/\ngroup3", false, - base::Time::Min()}), - Field("daily_update_url_kanon", - &StorageInterestGroup::daily_update_url_kanon, - StorageInterestGroup::KAnonymityData{ - "https://owner.example.com/update", false, - base::Time::Min()}), Field("bidding_ads_kanon", &StorageInterestGroup::bidding_ads_kanon, testing::UnorderedElementsAre( StorageInterestGroup::KAnonymityData{ "https://owner.example.com/\n" - "https://owner.example.com/bidder.js\n\n" + "https://owner.example.com/bidder.js\n" "https://ads.example.com/1", false, base::Time::Min()})), Field("reporting_ads_kanon", @@ -1437,9 +1231,9 @@ testing::UnorderedElementsAre( StorageInterestGroup::KAnonymityData{ "https://owner.example.com/\n" - "group3\n" - "https://owner.example.com/bidder.js\n\n" - "https://ads.example.com/1", + "https://owner.example.com/bidder.js\n" + "https://ads.example.com/1\n" + "group3", false, base::Time::Min()})), Field("joining_origin", &StorageInterestGroup::joining_origin, url::Origin::Create(GURL("https://publisher.example.com"))),
diff --git a/content/browser/interest_group/storage_interest_group.h b/content/browser/interest_group/storage_interest_group.h index 4357a7d..ba3408e 100644 --- a/content/browser/interest_group/storage_interest_group.h +++ b/content/browser/interest_group/storage_interest_group.h
@@ -51,8 +51,6 @@ blink::InterestGroup interest_group; auction_worklet::mojom::BiddingBrowserSignalsPtr bidding_browser_signals; - absl::optional<KAnonymityData> name_kanon; - absl::optional<KAnonymityData> daily_update_url_kanon; // Can an ad bid (when k-anonymity is enforced)? std::vector<KAnonymityData> bidding_ads_kanon;
diff --git a/content/browser/renderer_host/media/media_devices_dispatcher_host.cc b/content/browser/renderer_host/media/media_devices_dispatcher_host.cc index a0bb0f7..cf0d5446 100644 --- a/content/browser/renderer_host/media/media_devices_dispatcher_host.cc +++ b/content/browser/renderer_host/media/media_devices_dispatcher_host.cc
@@ -15,7 +15,6 @@ #include "base/run_loop.h" #include "base/task/bind_post_task.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "build/build_config.h" #include "content/browser/media/media_devices_permission_checker.h" #include "content/browser/renderer_host/back_forward_cache_disable.h" @@ -166,8 +165,8 @@ void MediaDevicesDispatcherHost::GetVideoInputCapabilities( GetVideoInputCapabilitiesCallback client_callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(media_stream_manager_->media_devices_manager() ->salt_and_origin_callback(), render_process_id_, render_frame_id_), @@ -181,8 +180,8 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); auto scoped_trace = ScopedMediaStreamTrace::CreateIfEnabled(__func__); - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(media_stream_manager_->media_devices_manager() ->salt_and_origin_callback(), render_process_id_, render_frame_id_), @@ -198,8 +197,8 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); auto scoped_trace = ScopedMediaStreamTrace::CreateIfEnabled(__func__); - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(media_stream_manager_->media_devices_manager() ->salt_and_origin_callback(), render_process_id_, render_frame_id_), @@ -211,8 +210,8 @@ void MediaDevicesDispatcherHost::GetAudioInputCapabilities( GetAudioInputCapabilitiesCallback client_callback) { - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(media_stream_manager_->media_devices_manager() ->salt_and_origin_callback(), render_process_id_, render_frame_id_),
diff --git a/content/browser/renderer_host/media/media_devices_manager.cc b/content/browser/renderer_host/media/media_devices_manager.cc index 0d2a425..732ce2f 100644 --- a/content/browser/renderer_host/media/media_devices_manager.cc +++ b/content/browser/renderer_host/media/media_devices_manager.cc
@@ -20,7 +20,6 @@ #include "base/sequence_checker.h" #include "base/strings/stringprintf.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/threading/thread_checker.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" @@ -446,8 +445,8 @@ request_audio_input_capabilities ? "true" : "false", request_video_input_capabilities ? "true" : "false")); - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(salt_and_origin_callback_, render_process_id, render_frame_id), base::BindOnce(&MediaDevicesManager::CheckPermissionsForEnumerateDevices, @@ -477,8 +476,8 @@ // Fetch the first device_id_salt for this subscriber's frame, to be able to // later detect changes. - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(salt_and_origin_callback_, render_process_id, render_frame_id), base::BindOnce(&MediaDevicesManager::SetSubscriptionLastSeenDeviceIdSalt, @@ -1049,8 +1048,8 @@ for (const auto& subscription : subscriptions_) { const SubscriptionRequest& request = subscription.second; if (request.subscribe_types[static_cast<size_t>(type)]) { - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(salt_and_origin_callback_, request.render_process_id, request.render_frame_id), base::BindOnce(&MediaDevicesManager::OnSaltAndOriginForSubscription,
diff --git a/content/browser/renderer_host/media/media_stream_dispatcher_host.cc b/content/browser/renderer_host/media/media_stream_dispatcher_host.cc index 21676375..4bf332c 100644 --- a/content/browser/renderer_host/media/media_stream_dispatcher_host.cc +++ b/content/browser/renderer_host/media/media_stream_dispatcher_host.cc
@@ -11,7 +11,6 @@ #include "base/check_op.h" #include "base/command_line.h" #include "base/task/bind_post_task.h" -#include "base/task/task_runner_util.h" #include "build/build_config.h" #include "content/browser/renderer_host/media/media_stream_manager.h" #include "content/browser/renderer_host/media/video_capture_manager.h" @@ -227,8 +226,8 @@ base::RepeatingClosure focus_callback = base::BindRepeating(&MediaStreamDispatcherHost::OnWebContentsFocused, weak_factory_.GetWeakPtr()); - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&StartObservingWebContents, render_process_id_, render_frame_id_, std::move(focus_callback)), base::BindOnce(&MediaStreamDispatcherHost::SetWebContentsObserver, @@ -435,8 +434,8 @@ return; } - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &MediaStreamDispatcherHost::GenerateStreamsChecksOnUIThread, /*render_process_id=*/render_process_id_, @@ -545,8 +544,8 @@ return; } - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(salt_and_origin_callback_, render_process_id_, render_frame_id_), base::BindOnce(&MediaStreamDispatcherHost::DoOpenDevice, @@ -701,8 +700,8 @@ // on it", and whether we can/need to specific the destination renderer/frame // in this case. - base::PostTaskAndReplyWithResult( - GetUIThreadTaskRunner({}).get(), FROM_HERE, + GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(salt_and_origin_callback_, render_process_id_, render_frame_id_), base::BindOnce(&MediaStreamDispatcherHost::DoGetOpenDevice,
diff --git a/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.cc b/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.cc index a63c064..6150fa5 100644 --- a/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.cc +++ b/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/public/browser/browser_thread.h" @@ -84,8 +83,8 @@ PP_Time last_access_time, PP_Time last_modified_time) { IPC::Message reply_msg = PpapiPluginMsg_FileRef_TouchReply(); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, BindOnce(&CallTouchFile, path_, last_access_time, last_modified_time), base::BindOnce(&PepperExternalFileRefBackend::DidFinish, weak_factory_.GetWeakPtr(), reply_context, reply_msg)); @@ -107,8 +106,8 @@ int32_t PepperExternalFileRefBackend::Query( ppapi::host::ReplyMessageContext reply_context) { - bool ok = base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, base::BindOnce(&DoGetFileInfo, path_), + bool ok = task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DoGetFileInfo, path_), base::BindOnce( &SendGetFileInfoResults, base::BindOnce(&PepperExternalFileRefBackend::GetMetadataComplete,
diff --git a/content/browser/renderer_host/pepper/pepper_file_system_browser_host.cc b/content/browser/renderer_host/pepper/pepper_file_system_browser_host.cc index 5a2ae50..91fdccaa 100644 --- a/content/browser/renderer_host/pepper/pepper_file_system_browser_host.cc +++ b/content/browser/renderer_host/pepper/pepper_file_system_browser_host.cc
@@ -8,7 +8,6 @@ #include "base/callback.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "content/browser/renderer_host/pepper/pepper_file_io_host.h" #include "content/browser/renderer_host/pepper/quota_reservation.h" #include "content/common/pepper_file_util.h" @@ -299,8 +298,8 @@ base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(root_url_.is_valid()); - base::PostTaskAndReplyWithResult( - file_system_context_->default_file_task_runner(), FROM_HERE, + file_system_context_->default_file_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&QuotaReservation::Create, file_system_context_, root_url_.DeprecatedGetOriginAsURL(), PepperFileSystemTypeToFileSystemType(type_)), @@ -410,11 +409,13 @@ return; } - base::PostTaskAndReplyWithResult( - io_thread_state_->file_system_context()->default_file_task_runner(), - FROM_HERE, - base::BindOnce(&QuotaReservation::OpenFile, quota_reservation_, id, url), - base::BindOnce(RunOpenQuotaCallbackOnUI, std::move(callback))); + io_thread_state_->file_system_context() + ->default_file_task_runner() + ->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce(&QuotaReservation::OpenFile, quota_reservation_, id, + url), + base::BindOnce(RunOpenQuotaCallbackOnUI, std::move(callback))); } void PepperFileSystemBrowserHost::CloseQuotaFile(
diff --git a/content/browser/renderer_host/pepper/pepper_truetype_font_host.cc b/content/browser/renderer_host/pepper/pepper_truetype_font_host.cc index baf9ea5..3e4c2d4 100644 --- a/content/browser/renderer_host/pepper/pepper_truetype_font_host.cc +++ b/content/browser/renderer_host/pepper/pepper_truetype_font_host.cc
@@ -5,7 +5,6 @@ #include "content/browser/renderer_host/pepper/pepper_truetype_font_host.h" #include "base/bind.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "content/browser/renderer_host/pepper/pepper_truetype_font.h" #include "content/public/browser/browser_ppapi_host.h" @@ -34,8 +33,8 @@ {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); SerializedTrueTypeFontDesc* actual_desc = new SerializedTrueTypeFontDesc(desc); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&PepperTrueTypeFont::Initialize, font_, actual_desc), base::BindOnce(&PepperTrueTypeFontHost::OnInitializeComplete, weak_factory_.GetWeakPtr(), base::Owned(actual_desc))); @@ -69,9 +68,8 @@ // Get font data on a thread that allows slow blocking operations. std::vector<uint32_t>* tags = new std::vector<uint32_t>(); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(&PepperTrueTypeFont::GetTableTags, font_, tags), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&PepperTrueTypeFont::GetTableTags, font_, tags), base::BindOnce(&PepperTrueTypeFontHost::OnGetTableTagsComplete, weak_factory_.GetWeakPtr(), base::Owned(tags), context->MakeReplyMessageContext())); @@ -90,8 +88,8 @@ // Get font data on a thread that allows slow blocking operations. std::string* data = new std::string(); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&PepperTrueTypeFont::GetTable, font_, table, offset, max_data_length, data), base::BindOnce(&PepperTrueTypeFontHost::OnGetTableComplete,
diff --git a/content/browser/renderer_host/render_frame_host_impl_browsertest.cc b/content/browser/renderer_host/render_frame_host_impl_browsertest.cc index 951482b..7124659 100644 --- a/content/browser/renderer_host/render_frame_host_impl_browsertest.cc +++ b/content/browser/renderer_host/render_frame_host_impl_browsertest.cc
@@ -6742,7 +6742,7 @@ base::test::ScopedFeatureList scoped_feature_list_; }; -INSTANTIATE_TEST_CASE_P( +INSTANTIATE_TEST_SUITE_P( All, RenderFrameHostImplBrowserTestWithStoragePartitioning, /*third_party_storage_partitioning_enabled*/ testing::Bool());
diff --git a/content/browser/renderer_host/render_frame_host_impl_unittest.cc b/content/browser/renderer_host/render_frame_host_impl_unittest.cc index 57dce6a..d24d362 100644 --- a/content/browser/renderer_host/render_frame_host_impl_unittest.cc +++ b/content/browser/renderer_host/render_frame_host_impl_unittest.cc
@@ -887,7 +887,7 @@ base::test::ScopedFeatureList scoped_feature_list_; }; -INSTANTIATE_TEST_CASE_P( +INSTANTIATE_TEST_SUITE_P( All, RenderFrameHostImplThirdPartyStorageTest, /*third_party_storage_partitioning_enabled*/ testing::Bool());
diff --git a/content/browser/renderer_host/render_widget_host_view_android.cc b/content/browser/renderer_host/render_widget_host_view_android.cc index a5cbb9b..3ae12578 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.cc +++ b/content/browser/renderer_host/render_widget_host_view_android.cc
@@ -24,7 +24,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/thread_task_runner_handle.h" @@ -1935,9 +1934,8 @@ if (!bitmap.drawsNothing()) { auto task_runner = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); - base::PostTaskAndReplyWithResult( - task_runner.get(), FROM_HERE, - base::BindOnce(&CompressAndSaveBitmap, path, bitmap), + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CompressAndSaveBitmap, path, bitmap), base::BindOnce( &base::android::RunStringCallbackAndroid, base::android::ScopedJavaGlobalRef<jobject>(env, callback.obj())));
diff --git a/content/browser/sandbox_support_mac_impl.mm b/content/browser/sandbox_support_mac_impl.mm index 9cfb64c..22a7a6f 100644 --- a/content/browser/sandbox_support_mac_impl.mm +++ b/content/browser/sandbox_support_mac_impl.mm
@@ -5,7 +5,6 @@ #import "content/browser/sandbox_support_mac_impl.h" #include "base/bind.h" -#include "base/task/task_runner_util.h" #import "content/browser/theme_helper_mac.h" #include "content/common/mac/font_loader.h" #include "content/public/browser/browser_task_traits.h" @@ -24,8 +23,8 @@ void SandboxSupportMacImpl::GetSystemColors(GetSystemColorsCallback callback) { auto task_runner = GetUIThreadTaskRunner({}); - base::PostTaskAndReplyWithResult( - task_runner.get(), FROM_HERE, + task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ThemeHelperMac::DuplicateReadOnlyColorMapRegion, base::Unretained(ThemeHelperMac::GetInstance())), std::move(callback));
diff --git a/content/browser/storage_partition_impl_unittest.cc b/content/browser/storage_partition_impl_unittest.cc index ecef21c..f97038fc 100644 --- a/content/browser/storage_partition_impl_unittest.cc +++ b/content/browser/storage_partition_impl_unittest.cc
@@ -250,7 +250,7 @@ static_cast<InterestGroupManagerImpl*>( storage_partition_->GetInterestGroupManager()) ->GetLastKAnonymityReported( - KAnonKeyFor(origin, "Name"), + k_anon_key, base::BindOnce( &RemoveInterestGroupTester::GetLastKAnonymityReportedCallback, base::Unretained(this))); @@ -264,13 +264,19 @@ group.owner = origin; group.name = "Name"; group.expiry = base::Time::Now() + base::Days(30); + group.bidding_url = origin.GetURL().Resolve("/bidding.js"); + group.ads.emplace(); + group.ads->push_back(blink::InterestGroup::Ad( + GURL("https://owner.example.com/ad1"), "metadata")); + InterestGroupManagerImpl* interest_group_manager = static_cast<InterestGroupManagerImpl*>( storage_partition_->GetInterestGroupManager()); interest_group_manager->JoinInterestGroup(group, origin.GetURL()); + // Update the K-anonymity so that we can tell when it gets removed. - interest_group_manager->UpdateLastKAnonymityReported( - KAnonKeyFor(origin, "Name")); + k_anon_key = KAnonKeyForAdBid(group, group.ads.value()[0]); + interest_group_manager->UpdateLastKAnonymityReported(k_anon_key); } private: @@ -288,6 +294,7 @@ bool get_interest_group_success_ = false; bool contains_kanon_ = false; + std::string k_anon_key; AwaitCompletionHelper await_completion_; raw_ptr<StoragePartitionImpl> storage_partition_; };
diff --git a/content/browser/web_package/save_as_web_bundle_job.cc b/content/browser/web_package/save_as_web_bundle_job.cc index 4aca4b63..f2419c5 100644 --- a/content/browser/web_package/save_as_web_bundle_job.cc +++ b/content/browser/web_package/save_as_web_bundle_job.cc
@@ -6,7 +6,6 @@ #include "base/callback.h" #include "base/files/file_path.h" -#include "base/task/task_runner_util.h" #include "components/download/public/common/download_task_runner.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" @@ -55,8 +54,8 @@ : data_decoder_(std::make_unique<data_decoder::DataDecoder>()), snapshots_(std::move(snapshots)), callback_(std::move(callback)) { - base::PostTaskAndReplyWithResult( - download::GetDownloadTaskRunner().get(), FROM_HERE, + download::GetDownloadTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( [](const base::FilePath& file_path) { const uint32_t file_flags =
diff --git a/content/public/renderer/video_encode_accelerator.cc b/content/public/renderer/video_encode_accelerator.cc index cd1d9cd..c44e87f 100644 --- a/content/public/renderer/video_encode_accelerator.cc +++ b/content/public/renderer/video_encode_accelerator.cc
@@ -5,7 +5,6 @@ #include "content/public/renderer/video_encode_accelerator.h" #include "base/bind.h" -#include "base/task/task_runner_util.h" #include "build/build_config.h" #include "content/renderer/render_thread_impl.h" #include "media/video/gpu_video_accelerator_factories.h" @@ -26,8 +25,8 @@ scoped_refptr<base::SequencedTaskRunner> encode_task_runner = gpu_factories->GetTaskRunner(); - base::PostTaskAndReplyWithResult( - encode_task_runner.get(), FROM_HERE, + encode_task_runner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &media::GpuVideoAcceleratorFactories::CreateVideoEncodeAccelerator, base::Unretained(gpu_factories)),
diff --git a/content/renderer/accessibility/ax_tree_distiller.cc b/content/renderer/accessibility/ax_tree_distiller.cc index 157b71e..506490d 100644 --- a/content/renderer/accessibility/ax_tree_distiller.cc +++ b/content/renderer/accessibility/ax_tree_distiller.cc
@@ -39,22 +39,28 @@ ax::mojom::Role::kNavigation, }; +// Find all of the main and article nodes. // TODO(crbug.com/1266555): Replace this with a call to // OneShotAccessibilityTreeSearch. -const ui::AXNode* GetMainNode(const ui::AXNode* root) { +void GetContentRootNodes(const ui::AXNode* root, + std::vector<const ui::AXNode*>* content_root_nodes) { std::queue<const ui::AXNode*> queue; queue.push(root); while (!queue.empty()) { const ui::AXNode* node = queue.front(); queue.pop(); - if (node->GetRole() == ax::mojom::Role::kMain) - return node; + // If a main or article node is found, add it to the list of content root + // nodes and continue. Do not explore children for nested article nodes. + if (node->GetRole() == ax::mojom::Role::kMain || + node->GetRole() == ax::mojom::Role::kArticle) { + content_root_nodes->push_back(node); + continue; + } for (auto iter = node->UnignoredChildrenBegin(); iter != node->UnignoredChildrenEnd(); ++iter) { queue.push(iter.get()); } } - return nullptr; } // Recurse through the root node, searching for content nodes (any node whose @@ -149,12 +155,13 @@ if (!tree.Unserialize(*snapshot_)) NOTREACHED() << tree.error(); - const ui::AXNode* main_node = GetMainNode(tree.root()); - // If this page does not have a main node, this means it is not distillable. - if (!main_node) - return; - - AddContentNodesToVector(main_node, content_node_ids_.get()); + std::vector<const ui::AXNode*> content_root_nodes; + GetContentRootNodes(tree.root(), &content_root_nodes); + for (const ui::AXNode* content_root_node : content_root_nodes) { + AddContentNodesToVector(content_root_node, content_node_ids_.get()); + } + // If this page does not have any content root nodes, do nothing. It is not + // distillable. } void AXTreeDistiller::RunCallback() {
diff --git a/content/renderer/accessibility/ax_tree_distiller_browsertest.cc b/content/renderer/accessibility/ax_tree_distiller_browsertest.cc index a1d13e0..e793c4c 100644 --- a/content/renderer/accessibility/ax_tree_distiller_browsertest.cc +++ b/content/renderer/accessibility/ax_tree_distiller_browsertest.cc
@@ -85,7 +85,7 @@ <body>)HTML", {"Test"}}, /* ----------------------- */ - {"simple_page_with_content", + {"simple_page_with_main", R"HTML(<!doctype html> <body role="main"> <h1>Heading</h1> @@ -95,6 +95,21 @@ <body>)HTML", {"Heading", "Test 1", "Test 2", "Header"}}, /* ----------------------- */ + {"simple_page_with_main_and_article", + R"HTML(<!doctype html> + <body> + <main> + <p>Main</p> + </main> + <div role="article"> + <p>Article 1</p> + </div> + <div role="article"> + <p>Article 2</p> + </div> + <body>)HTML", + {"Main", "Article 1", "Article 2"}}, + /* ----------------------- */ {"simple_page_no_content", R"HTML(<!doctype html> <body> @@ -150,6 +165,24 @@ <p>Some <b>bolded</b> text</p> <body>)HTML", {"Some bolded text"}}, + /* ----------------------- */ + {"simple_page_nested_article", + R"HTML(<!doctype html> + <body> + <div role="main"> + <p>Main</p> + <div role="article"> + <p>Article 1</p> + </div> + </div> + <div role="article"> + <p>Article 2</p> + <div role="article"> + <p>Article 3</p> + </div> + </div> + <body>)HTML", + {"Main", "Article 1", "Article 2", "Article 3"}}, }; TEST_P(AXTreeDistillerTest, DistillsWebPage) {
diff --git a/content/services/auction_worklet/bidder_worklet.cc b/content/services/auction_worklet/bidder_worklet.cc index 92f62511..ad627ee 100644 --- a/content/services/auction_worklet/bidder_worklet.cc +++ b/content/services/auction_worklet/bidder_worklet.cc
@@ -628,6 +628,8 @@ context_recycler = context_recycler_for_origin_group_mode_.get(); reused_context = true; } + base::UmaHistogramBoolean("Ads.InterestGroup.Auction.ContextReused", + reused_context); if (!context_recycler) { fresh_context_recycler = @@ -785,6 +787,8 @@ "generateBid", args, std::move(per_buyer_timeout), errors_out) .ToLocal(&generate_bid_result); TRACE_EVENT_NESTABLE_ASYNC_END0("fledge", "generate_bid", trace_id); + base::UmaHistogramTimes("Ads.InterestGroup.Auction.GenerateBidTime", + base::TimeTicks::Now() - start); if (got_return_value) { context_recycler->set_bid_bindings()->SetBid(
diff --git a/content/services/auction_worklet/seller_worklet.cc b/content/services/auction_worklet/seller_worklet.cc index 6a16dbd..04e832c 100644 --- a/content/services/auction_worklet/seller_worklet.cc +++ b/content/services/auction_worklet/seller_worklet.cc
@@ -521,6 +521,7 @@ base::ScopedClosureRunner cleanup_score_ad_task, ScoreAdCallbackInternal callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(v8_sequence_checker_); + base::TimeTicks start = base::TimeTicks::Now(); TRACE_EVENT_NESTABLE_ASYNC_END0("fledge", "post_v8_task", trace_id); @@ -615,6 +616,8 @@ "scoreAd", args, std::move(seller_timeout), errors_out) .ToLocal(&score_ad_result); TRACE_EVENT_NESTABLE_ASYNC_END0("fledge", "score_ad", trace_id); + base::UmaHistogramTimes("Ads.InterestGroup.Auction.ScoreAdTime", + base::TimeTicks::Now() - start); if (!got_return_value) { // Keep debug loss reports and Private Aggregation API requests since
diff --git a/content/test/data/accessibility/mac/attributed-string/deletion-expected.txt b/content/test/data/accessibility/mac/attributed-string/deletion-expected.txt new file mode 100644 index 0000000..1cb677e --- /dev/null +++ b/content/test/data/accessibility/mac/attributed-string/deletion-expected.txt
@@ -0,0 +1,4 @@ +tr_deletion={anchor: {:2, 0, down}, focus: {:2, 12, down}} +deletion.accessibilityAttributeValue(AXAttributedStringForTextMarkerRange, tr_deletion)='Deleted Text{ + AXIsSuggestedDeletion = 1; +}'
diff --git a/content/test/data/accessibility/mac/attributed-string/deletion.html b/content/test/data/accessibility/mac/attributed-string/deletion.html new file mode 100644 index 0000000..da83783 --- /dev/null +++ b/content/test/data/accessibility/mac/attributed-string/deletion.html
@@ -0,0 +1,7 @@ +<!-- +@SCRIPT: + tr_deletion:= deletion.AXTextMarkerRangeForUIElement(deletion) + deletion.accessibilityAttributeValue(AXAttributedStringForTextMarkerRange, tr_deletion) +--> +<!DOCTYPE html> +<div role="deletion" id="deletion">Deleted Text</div>
diff --git a/content/test/data/accessibility/mac/attributed-string/insertion-expected.txt b/content/test/data/accessibility/mac/attributed-string/insertion-expected.txt new file mode 100644 index 0000000..d3e29ad --- /dev/null +++ b/content/test/data/accessibility/mac/attributed-string/insertion-expected.txt
@@ -0,0 +1,4 @@ +tr_insertion={anchor: {:2, 0, down}, focus: {:2, 13, down}} +insertion.accessibilityAttributeValue(AXAttributedStringForTextMarkerRange, tr_insertion)='Inserted Text{ + AXIsSuggestedInsertion = 1; +}'
diff --git a/content/test/data/accessibility/mac/attributed-string/insertion.html b/content/test/data/accessibility/mac/attributed-string/insertion.html new file mode 100644 index 0000000..4021ac4c --- /dev/null +++ b/content/test/data/accessibility/mac/attributed-string/insertion.html
@@ -0,0 +1,7 @@ +<!-- +@SCRIPT: + tr_insertion:= insertion.AXTextMarkerRangeForUIElement(insertion) + insertion.accessibilityAttributeValue(AXAttributedStringForTextMarkerRange, tr_insertion) +--> +<!DOCTYPE html> +<div role="insertion" id="insertion">Inserted Text</div>
diff --git a/content/test/data/accessibility/mac/attributed-string/mark-expected.txt b/content/test/data/accessibility/mac/attributed-string/mark-expected.txt new file mode 100644 index 0000000..10c3500 --- /dev/null +++ b/content/test/data/accessibility/mac/attributed-string/mark-expected.txt
@@ -0,0 +1,4 @@ +tr_mark={anchor: {:2, 0, down}, focus: {:2, 9, down}} +mark.accessibilityAttributeValue(AXAttributedStringForTextMarkerRange, tr_mark)='Mark Text{ + AXHighlight = 1; +}'
diff --git a/content/test/data/accessibility/mac/attributed-string/mark.html b/content/test/data/accessibility/mac/attributed-string/mark.html new file mode 100644 index 0000000..58d94c7 --- /dev/null +++ b/content/test/data/accessibility/mac/attributed-string/mark.html
@@ -0,0 +1,7 @@ +<!-- +@SCRIPT: + tr_mark:= mark.AXTextMarkerRangeForUIElement(mark) + mark.accessibilityAttributeValue(AXAttributedStringForTextMarkerRange, tr_mark) +--> +<!DOCTYPE html> +<div role="mark" id="mark">Mark Text</div>
diff --git a/content/test/data/accessibility/mac/attributed-string/nested-suggestion-insertion-deletion-expected.txt b/content/test/data/accessibility/mac/attributed-string/nested-suggestion-insertion-deletion-expected.txt new file mode 100644 index 0000000..7231a9d --- /dev/null +++ b/content/test/data/accessibility/mac/attributed-string/nested-suggestion-insertion-deletion-expected.txt
@@ -0,0 +1,8 @@ +tr_suggestion={anchor: {:2, 0, down}, focus: {:2, 37, down}} +suggestion.accessibilityAttributeValue(AXAttributedStringForTextMarkerRange, tr_suggestion)='Suggested Insertion{ + AXIsSuggestedInsertion = 1; + AXIsSuggestion = 1; +}Suggested Deletion{ + AXIsSuggestedDeletion = 1; + AXIsSuggestion = 1; +}'
diff --git a/content/test/data/accessibility/mac/attributed-string/nested-suggestion-insertion-deletion.html b/content/test/data/accessibility/mac/attributed-string/nested-suggestion-insertion-deletion.html new file mode 100644 index 0000000..36a3bb5 --- /dev/null +++ b/content/test/data/accessibility/mac/attributed-string/nested-suggestion-insertion-deletion.html
@@ -0,0 +1,10 @@ +<!-- +@SCRIPT: + tr_suggestion:= suggestion.AXTextMarkerRangeForUIElement(suggestion) + suggestion.accessibilityAttributeValue(AXAttributedStringForTextMarkerRange, tr_suggestion) +--> +<!DOCTYPE html> +<div role="suggestion" id="suggestion"> + <div role="insertion">Suggested Insertion</div> + <div role="deletion">Suggested Deletion</div> +</div>
diff --git a/content/test/data/accessibility/mac/attributed-string/suggestion-expected.txt b/content/test/data/accessibility/mac/attributed-string/suggestion-expected.txt new file mode 100644 index 0000000..3dd5081 --- /dev/null +++ b/content/test/data/accessibility/mac/attributed-string/suggestion-expected.txt
@@ -0,0 +1,4 @@ +tr_suggestion={anchor: {:2, 0, down}, focus: {:2, 15, down}} +suggestion.accessibilityAttributeValue(AXAttributedStringForTextMarkerRange, tr_suggestion)='Suggestion Text{ + AXIsSuggestion = 1; +}'
diff --git a/content/test/data/accessibility/mac/attributed-string/suggestion.html b/content/test/data/accessibility/mac/attributed-string/suggestion.html new file mode 100644 index 0000000..651aefb --- /dev/null +++ b/content/test/data/accessibility/mac/attributed-string/suggestion.html
@@ -0,0 +1,7 @@ +<!-- +@SCRIPT: + tr_suggestion:= suggestion.AXTextMarkerRangeForUIElement(suggestion) + suggestion.accessibilityAttributeValue(AXAttributedStringForTextMarkerRange, tr_suggestion) +--> +<!DOCTYPE html> +<div role="suggestion" id="suggestion">Suggestion Text</div>
diff --git a/content/web_test/browser/leak_detector.cc b/content/web_test/browser/leak_detector.cc index 9d4aa48..aa1168c 100644 --- a/content/web_test/browser/leak_detector.cc +++ b/content/web_test/browser/leak_detector.cc
@@ -77,92 +77,91 @@ blink::mojom::LeakDetectionResultPtr result) { LeakDetectionReport report; report.leaked = false; - base::Value detail(base::Value::Type::DICTIONARY); + base::Value::Dict detail; if (previous_result_ && !result.is_null()) { if (previous_result_->number_of_live_audio_nodes < result->number_of_live_audio_nodes) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append( static_cast<int>(previous_result_->number_of_live_audio_nodes)); list.Append(static_cast<int>(result->number_of_live_audio_nodes)); - detail.SetPath("numberOfLiveAudioNodes", std::move(list)); + detail.Set("numberOfLiveAudioNodes", std::move(list)); } if (previous_result_->number_of_live_documents < result->number_of_live_documents) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append(static_cast<int>(previous_result_->number_of_live_documents)); list.Append(static_cast<int>(result->number_of_live_documents)); - detail.SetPath("numberOfLiveDocuments", std::move(list)); + detail.Set("numberOfLiveDocuments", std::move(list)); } if (previous_result_->number_of_live_nodes < result->number_of_live_nodes) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append(static_cast<int>(previous_result_->number_of_live_nodes)); list.Append(static_cast<int>(result->number_of_live_nodes)); - detail.SetPath("numberOfLiveNodes", std::move(list)); + detail.Set("numberOfLiveNodes", std::move(list)); } if (previous_result_->number_of_live_layout_objects < result->number_of_live_layout_objects) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append( static_cast<int>(previous_result_->number_of_live_layout_objects)); list.Append(static_cast<int>(result->number_of_live_layout_objects)); - detail.SetPath("numberOfLiveLayoutObjects", std::move(list)); + detail.Set("numberOfLiveLayoutObjects", std::move(list)); } // Resources associated with User Agent CSS should be excluded from leak // detection as they are persisted through page navigation. if (previous_result_->number_of_live_resources < (result->number_of_live_resources - result->number_of_live_ua_css_resources)) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append(static_cast<int>(previous_result_->number_of_live_resources)); list.Append(static_cast<int>(result->number_of_live_resources)); - detail.SetPath("numberOfLiveResources", std::move(list)); + detail.Set("numberOfLiveResources", std::move(list)); } if (previous_result_->number_of_live_context_lifecycle_state_observers < result->number_of_live_context_lifecycle_state_observers) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append(static_cast<int>( previous_result_->number_of_live_context_lifecycle_state_observers)); list.Append(static_cast<int>( result->number_of_live_context_lifecycle_state_observers)); - detail.SetPath("numberOfLiveContextLifecycleStateObservers", - std::move(list)); + detail.Set("numberOfLiveContextLifecycleStateObservers", std::move(list)); } if (previous_result_->number_of_live_frames < result->number_of_live_frames) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append(static_cast<int>(previous_result_->number_of_live_frames)); list.Append(static_cast<int>(result->number_of_live_frames)); - detail.SetPath("numberOfLiveFrames", std::move(list)); + detail.Set("numberOfLiveFrames", std::move(list)); } if (previous_result_->number_of_live_v8_per_context_data < result->number_of_live_v8_per_context_data) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append(static_cast<int>( previous_result_->number_of_live_v8_per_context_data)); list.Append(static_cast<int>(result->number_of_live_v8_per_context_data)); - detail.SetPath("numberOfLiveV8PerContextData", std::move(list)); + detail.Set("numberOfLiveV8PerContextData", std::move(list)); } if (previous_result_->number_of_worker_global_scopes < result->number_of_worker_global_scopes) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append( static_cast<int>(previous_result_->number_of_worker_global_scopes)); list.Append(static_cast<int>(result->number_of_worker_global_scopes)); - detail.SetPath("numberOfWorkerGlobalScopes", std::move(list)); + detail.Set("numberOfWorkerGlobalScopes", std::move(list)); } if (previous_result_->number_of_live_resource_fetchers < result->number_of_live_resource_fetchers) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append( static_cast<int>(previous_result_->number_of_live_resource_fetchers)); list.Append(static_cast<int>(result->number_of_live_resource_fetchers)); - detail.SetPath("numberOfLiveResourceFetchers", std::move(list)); + detail.Set("numberOfLiveResourceFetchers", std::move(list)); } } - if (!detail.DictEmpty()) { + if (!detail.empty()) { std::string detail_str; base::JSONWriter::Write(detail, &detail_str); report.detail = detail_str;
diff --git a/dbus/object_manager.cc b/dbus/object_manager.cc index 7f5fb3e..f57167a 100644 --- a/dbus/object_manager.cc +++ b/dbus/object_manager.cc
@@ -12,7 +12,6 @@ #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/strings/stringprintf.h" -#include "base/task/task_runner_util.h" #include "dbus/bus.h" #include "dbus/dbus_statistics.h" #include "dbus/message.h" @@ -40,8 +39,8 @@ // signals from the service. This is important to avoid any race conditions // that might cause us to miss PropertiesChanged signals once all objects are // initialized via GetManagedObjects. - base::PostTaskAndReplyWithResult( - bus->GetDBusTaskRunner(), FROM_HERE, + bus->GetDBusTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ObjectManager::SetupMatchRuleAndFilter, object_manager), base::BindOnce(&ObjectManager::OnSetupMatchRuleAndFilterComplete, object_manager));
diff --git a/dbus/object_proxy.cc b/dbus/object_proxy.cc index 2562205e..efe93279 100644 --- a/dbus/object_proxy.cc +++ b/dbus/object_proxy.cc
@@ -15,7 +15,6 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" -#include "base/task/task_runner_util.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" @@ -250,8 +249,8 @@ bus_->AssertOnOriginThread(); if (bus_->HasDBusThread()) { - base::PostTaskAndReplyWithResult( - bus_->GetDBusTaskRunner(), FROM_HERE, + bus_->GetDBusTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ObjectProxy::ConnectToSignalAndBlock, this, interface_name, signal_name, signal_callback), base::BindOnce(std::move(on_connected_callback), interface_name,
diff --git a/device/vr/openxr/openxr_device.cc b/device/vr/openxr/openxr_device.cc index cbb84f51..328b622 100644 --- a/device/vr/openxr/openxr_device.cc +++ b/device/vr/openxr/openxr_device.cc
@@ -160,16 +160,11 @@ auto on_visibility_state_changed = base::BindRepeating( &OpenXrDevice::OnVisibilityStateChanged, weak_ptr_factory_.GetWeakPtr()); - // OpenXr doesn't need to handle anything when presentation has ended, but - // the mojo interface to call to XRCompositorCommon::RequestSession requires - // a method and cannot take nullptr, so passing in base::DoNothing() - // for on_presentation_ended render_loop_->task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&XRCompositorCommon::RequestSession, - base::Unretained(render_loop_.get()), base::DoNothing(), - std::move(on_visibility_state_changed), std::move(options), - std::move(my_callback))); + FROM_HERE, base::BindOnce(&XRCompositorCommon::RequestSession, + base::Unretained(render_loop_.get()), + std::move(on_visibility_state_changed), + std::move(options), std::move(my_callback))); request_session_callback_ = std::move(callback); } @@ -200,19 +195,29 @@ base::Unretained(this))); } -void OpenXrDevice::OnPresentingControllerMojoConnectionError() { +void OpenXrDevice::ForceEndSession(ExitXrPresentReason reason) { // This method is called when the rendering process exit presents. if (render_loop_) { render_loop_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&XRCompositorCommon::ExitPresent, - base::Unretained(render_loop_.get()), - ExitXrPresentReason::kMojoConnectionError)); + FROM_HERE, + base::BindOnce(&XRCompositorCommon::ExitPresent, + base::Unretained(render_loop_.get()), reason)); } OnExitPresent(); exclusive_controller_receiver_.reset(); } +void OpenXrDevice::OnPresentingControllerMojoConnectionError() { + ForceEndSession(ExitXrPresentReason::kMojoConnectionError); +} + +void OpenXrDevice::ShutdownSession( + mojom::XRRuntime::ShutdownSessionCallback callback) { + ForceEndSession(ExitXrPresentReason::kBrowserShutdown); + std::move(callback).Run(); +} + void OpenXrDevice::SetFrameDataRestricted(bool restricted) { // Presentation sessions can not currently be restricted. NOTREACHED();
diff --git a/device/vr/openxr/openxr_device.h b/device/vr/openxr/openxr_device.h index 064574ae..d4fb26de 100644 --- a/device/vr/openxr/openxr_device.h +++ b/device/vr/openxr/openxr_device.h
@@ -13,6 +13,7 @@ #include "device/vr/public/mojom/vr_service.mojom.h" #include "device/vr/vr_device_base.h" #include "device/vr/vr_export.h" +#include "device/vr/windows/compositor_base.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" @@ -38,6 +39,7 @@ void RequestSession( mojom::XRRuntimeSessionOptionsPtr options, mojom::XRRuntime::RequestSessionCallback callback) override; + void ShutdownSession(mojom::XRRuntime::ShutdownSessionCallback) override; mojo::PendingRemote<mojom::XRCompositorHost> BindCompositorHost(); @@ -52,6 +54,7 @@ void EnsureRenderLoop(); void OnRequestSessionResult(bool result, mojom::XRSessionPtr session); + void ForceEndSession(ExitXrPresentReason reason); void OnPresentingControllerMojoConnectionError(); bool IsArBlendModeSupported();
diff --git a/device/vr/orientation/orientation_device.cc b/device/vr/orientation/orientation_device.cc index 3803a9d..41f7c15 100644 --- a/device/vr/orientation/orientation_device.cc +++ b/device/vr/orientation/orientation_device.cc
@@ -177,6 +177,19 @@ sensor_->Resume(); } +void VROrientationDevice::ShutdownSession( + mojom::XRRuntime::ShutdownSessionCallback callback) { + // We don't actually have enough information here to figure out which session + // is being requested to be terminated. However, since sessions don't get + // exclusive control of the device and we can drive many sessions at once, + // there's not really anything for us to do here except to reply to the + // callback. + // The session will end up getting shutdown via other mechanisms (some of + // its mojom pipes getting torn down during destruction in the other + // processes as a result of continuing the flow here). + std::move(callback).Run(); +} + void VROrientationDevice::EndMagicWindowSession(VROrientationSession* session) { DVLOG(2) << __func__; base::EraseIf(magic_window_sessions_,
diff --git a/device/vr/orientation/orientation_device.h b/device/vr/orientation/orientation_device.h index 173f7d6..f8648945 100644 --- a/device/vr/orientation/orientation_device.h +++ b/device/vr/orientation/orientation_device.h
@@ -49,6 +49,7 @@ void RequestSession( mojom::XRRuntimeSessionOptionsPtr options, mojom::XRRuntime::RequestSessionCallback callback) override; + void ShutdownSession(mojom::XRRuntime::ShutdownSessionCallback) override; // Indicates whether the device was able to connect to orientation events. bool IsAvailable() const { return available_; }
diff --git a/device/vr/test/fake_vr_device.cc b/device/vr/test/fake_vr_device.cc index 73cd8e1..aa66370 100644 --- a/device/vr/test/fake_vr_device.cc +++ b/device/vr/test/fake_vr_device.cc
@@ -22,6 +22,12 @@ std::move(callback).Run(nullptr); } +void FakeVRDevice::ShutdownSession( + mojom::XRRuntime::ShutdownSessionCallback callback) { + OnExitPresent(); + std::move(callback).Run(); +} + void FakeVRDevice::OnPresentingControllerMojoConnectionError() { OnExitPresent(); }
diff --git a/device/vr/test/fake_vr_device.h b/device/vr/test/fake_vr_device.h index 874dc8ba..1f33735 100644 --- a/device/vr/test/fake_vr_device.h +++ b/device/vr/test/fake_vr_device.h
@@ -25,6 +25,8 @@ void RequestSession( mojom::XRRuntimeSessionOptionsPtr options, mojom::XRRuntime::RequestSessionCallback callback) override; + void ShutdownSession( + mojom::XRRuntime::ShutdownSessionCallback callback) override; void SetPose(mojom::VRPosePtr pose) { pose_ = std::move(pose); } void SetFrameDataRestricted(bool restricted) override {}
diff --git a/device/vr/vr_device_base.cc b/device/vr/vr_device_base.cc index a9b40f2..86d96cd 100644 --- a/device/vr/vr_device_base.cc +++ b/device/vr/vr_device_base.cc
@@ -34,16 +34,6 @@ void VRDeviceBase::ResumeTracking() {} -void VRDeviceBase::ShutdownSession(base::OnceClosure on_completed) { - DVLOG(2) << __func__; - // TODO(https://crbug.com/1015594): The default implementation of running the - // callback immediately is backwards compatible, but runtimes should be - // updated to override this, calling the callback at the appropriate time - // after any necessary cleanup has been completed. Once that's done, make this - // method abstract. - std::move(on_completed).Run(); -} - void VRDeviceBase::OnExitPresent() { DVLOG(2) << __func__ << ": !!listener_=" << !!listener_; if (listener_)
diff --git a/device/vr/vr_device_base.h b/device/vr/vr_device_base.h index adf77c2..cf94d49a 100644 --- a/device/vr/vr_device_base.h +++ b/device/vr/vr_device_base.h
@@ -35,7 +35,6 @@ void ListenToDeviceChanges( mojo::PendingAssociatedRemote<mojom::XRRuntimeEventListener> listener) final; - void ShutdownSession(mojom::XRRuntime::ShutdownSessionCallback) override; device::mojom::XRDeviceId GetId() const; device::mojom::XRDeviceDataPtr GetDeviceData() const;
diff --git a/device/vr/vr_device_base_unittest.cc b/device/vr/vr_device_base_unittest.cc index 455a8a5..8ae1a0b 100644 --- a/device/vr/vr_device_base_unittest.cc +++ b/device/vr/vr_device_base_unittest.cc
@@ -34,6 +34,10 @@ void RequestSession( mojom::XRRuntimeSessionOptionsPtr options, mojom::XRRuntime::RequestSessionCallback callback) override {} + void ShutdownSession( + mojom::XRRuntime::ShutdownSessionCallback callback) override { + std::move(callback).Run(); + } }; class StubVRDeviceEventListener : public mojom::XRRuntimeEventListener {
diff --git a/device/vr/windows/compositor_base.cc b/device/vr/windows/compositor_base.cc index 875c909e..594fa7bc 100644 --- a/device/vr/windows/compositor_base.cc +++ b/device/vr/windows/compositor_base.cc
@@ -209,7 +209,6 @@ } void XRCompositorCommon::RequestSession( - base::OnceCallback<void()> on_presentation_ended, base::RepeatingCallback<void(mojom::XRVisibilityState)> on_visibility_state_changed, mojom::XRRuntimeSessionOptionsPtr options, @@ -226,14 +225,13 @@ // XRCompositorCommon::StartRuntimeFinish. We setup BindOnce such that all of // the parameters give to us here in XRCompositorCommon::RequestSession are // passed through to StartRuntimeFinish so that it can finish the job. - StartRuntime(base::BindOnce( - &XRCompositorCommon::StartRuntimeFinish, base::Unretained(this), - std::move(on_presentation_ended), std::move(on_visibility_state_changed), - std::move(options), std::move(callback))); + StartRuntime(base::BindOnce(&XRCompositorCommon::StartRuntimeFinish, + base::Unretained(this), + std::move(on_visibility_state_changed), + std::move(options), std::move(callback))); } void XRCompositorCommon::StartRuntimeFinish( - base::OnceCallback<void()> on_presentation_ended, base::RepeatingCallback<void(mojom::XRVisibilityState)> on_visibility_state_changed, mojom::XRRuntimeSessionOptionsPtr options, @@ -247,12 +245,6 @@ return; } - // If on_presentation_ended_ is not already null, we won't call to notify the - // runtime that that session has completed. This is ok because the XRRuntime - // knows it has requested a new session, and isn't expecting that callback to - // be called. - on_presentation_ended_ = std::move(on_presentation_ended); - on_visibility_state_changed_ = std::move(on_visibility_state_changed); // Queue up a notification to the requester of the current visibility state, @@ -312,6 +304,9 @@ void XRCompositorCommon::ExitPresent(ExitXrPresentReason reason) { TRACE_EVENT_INSTANT1("xr", "ExitPresent", TRACE_EVENT_SCOPE_THREAD, "reason", base::to_underlying(reason)); + if (!is_presenting_) + return; + is_presenting_ = false; webxr_has_pose_ = false; presentation_receiver_.reset(); @@ -336,11 +331,6 @@ task_runner()->PostTask( FROM_HERE, base::BindOnce(&XRCompositorCommon::StopRuntime, base::Unretained(this))); - - if (on_presentation_ended_) { - main_thread_task_runner_->PostTask(FROM_HERE, - std::move(on_presentation_ended_)); - } } void XRCompositorCommon::SetVisibilityState(
diff --git a/device/vr/windows/compositor_base.h b/device/vr/windows/compositor_base.h index 623231e4..ecee2f5 100644 --- a/device/vr/windows/compositor_base.h +++ b/device/vr/windows/compositor_base.h
@@ -42,6 +42,7 @@ kXrEndFrameFailed = 5, kGetFrameAfterSessionEnded = 6, kSubmitFrameFailed = 7, + kBrowserShutdown = 8, }; class XRDeviceAbstraction { @@ -84,12 +85,7 @@ ~XRCompositorCommon() override; - // on_presentation_ended will be called when this the compositor stops - // presenting to the headset. If new session request comes in, only the new - // callback will be called (since we haven't yet stopped presenting to the - // headset). - void RequestSession(base::OnceCallback<void()> on_presentation_ended, - base::RepeatingCallback<void(mojom::XRVisibilityState)> + void RequestSession(base::RepeatingCallback<void(mojom::XRVisibilityState)> on_visibility_state_changed, mojom::XRRuntimeSessionOptionsPtr options, RequestSessionCallback callback); @@ -149,7 +145,6 @@ void StartPendingFrame(); void StartRuntimeFinish( - base::OnceCallback<void()> on_presentation_ended, base::RepeatingCallback<void(mojom::XRVisibilityState)> on_visibility_state_changed, mojom::XRRuntimeSessionOptionsPtr options, @@ -231,7 +226,6 @@ SubmitOverlayTextureCallback overlay_submit_callback_; RequestNotificationOnWebXrSubmittedCallback on_webxr_submitted_; bool webxr_has_pose_ = false; - base::OnceCallback<void()> on_presentation_ended_; base::RepeatingCallback<void(mojom::XRVisibilityState)> on_visibility_state_changed_; mojo::Receiver<mojom::XRPresentationProvider> presentation_receiver_{this};
diff --git a/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc b/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc index 23a250a..3e67741 100644 --- a/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc +++ b/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc
@@ -12,7 +12,6 @@ #include "base/bind.h" #include "base/containers/contains.h" #include "base/containers/cxx20_erase.h" -#include "base/task/task_runner_util.h" #include "base/time/time.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" @@ -128,9 +127,8 @@ }, std::move(source)); - base::PostTaskAndReplyWithResult( - GetExtensionFileTaskRunner().get(), FROM_HERE, - std::move(read_dynamic_rules), + GetExtensionFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(read_dynamic_rules), base::BindOnce( &DeclarativeNetRequestGetDynamicRulesFunction::OnDynamicRulesFetched, this));
diff --git a/extensions/browser/api/system_info/system_info_provider.cc b/extensions/browser/api/system_info/system_info_provider.cc index 8a6b23d..bf282fa 100644 --- a/extensions/browser/api/system_info/system_info_provider.cc +++ b/extensions/browser/api/system_info/system_info_provider.cc
@@ -6,7 +6,6 @@ #include "base/bind.h" #include "base/strings/utf_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "components/storage_monitor/storage_info.h" @@ -87,9 +86,8 @@ PrepareQueryOnUIThread(); // Post the custom query info task to blocking pool for information querying // and reply with OnQueryCompleted. - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(&SystemInfoProvider::QueryInfo, this), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SystemInfoProvider::QueryInfo, this), base::BindOnce(&SystemInfoProvider::OnQueryCompleted, this)); }
diff --git a/extensions/browser/api/system_storage/system_storage_api.cc b/extensions/browser/api/system_storage/system_storage_api.cc index c13f9aaf..6e42a59 100644 --- a/extensions/browser/api/system_storage/system_storage_api.cc +++ b/extensions/browser/api/system_storage/system_storage_api.cc
@@ -5,7 +5,6 @@ #include "extensions/browser/api/system_storage/system_storage_api.h" #include "base/bind.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "content/public/browser/browser_thread.h" @@ -119,8 +118,8 @@ void SystemStorageGetAvailableCapacityFunction::OnStorageMonitorInit( const std::string& transient_id) { - base::PostTaskAndReplyWithResult( - query_runner_.get(), FROM_HERE, + query_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &StorageInfoProvider::GetStorageFreeSpaceFromTransientIdAsync, StorageInfoProvider::Get(), transient_id),
diff --git a/extensions/browser/image_sanitizer.cc b/extensions/browser/image_sanitizer.cc index a5c70e17..46723bb 100644 --- a/extensions/browser/image_sanitizer.cc +++ b/extensions/browser/image_sanitizer.cc
@@ -8,7 +8,6 @@ #include "base/debug/dump_without_crashing.h" #include "base/files/file_util.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "extensions/browser/extension_file_task_runner.h" #include "extensions/common/extension_resource_path_normalizer.h" #include "services/data_decoder/public/cpp/decode_image.h" @@ -118,9 +117,8 @@ // either error to be reported (kImagePathError or kFileReadError). for (const base::FilePath& path : image_paths_) { base::FilePath full_image_path = image_dir_.Append(path); - base::PostTaskAndReplyWithResult( - io_task_runner_.get(), FROM_HERE, - base::BindOnce(&ReadAndDeleteBinaryFile, full_image_path), + io_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadAndDeleteBinaryFile, full_image_path), base::BindOnce(&ImageSanitizer::ImageFileRead, weak_factory_.GetWeakPtr(), path)); } @@ -164,9 +162,8 @@ // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even // though they may originally be .jpg, etc. Figure something out. // http://code.google.com/p/chromium/issues/detail?id=12459 - base::PostTaskAndReplyWithResult( - io_task_runner_.get(), FROM_HERE, - base::BindOnce(&EncodeImage, decoded_image), + io_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&EncodeImage, decoded_image), base::BindOnce(&ImageSanitizer::ImageReencoded, weak_factory_.GetWeakPtr(), image_path)); @@ -185,8 +182,8 @@ } int size = base::checked_cast<int>(image_data.size()); - base::PostTaskAndReplyWithResult( - io_task_runner_.get(), FROM_HERE, + io_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&WriteFile, image_dir_.Append(image_path), std::move(image_data)), base::BindOnce(&ImageSanitizer::ImageWritten, weak_factory_.GetWeakPtr(),
diff --git a/extensions/browser/json_file_sanitizer.cc b/extensions/browser/json_file_sanitizer.cc index 5791e350..7f100d4 100644 --- a/extensions/browser/json_file_sanitizer.cc +++ b/extensions/browser/json_file_sanitizer.cc
@@ -8,7 +8,6 @@ #include "base/files/file_util.h" #include "base/json/json_string_value_serializer.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "extensions/browser/extension_file_task_runner.h" #include "services/data_decoder/public/cpp/data_decoder.h" @@ -71,9 +70,8 @@ json_parser_.BindNewPipeAndPassReceiver()); for (const base::FilePath& path : file_paths_) { - base::PostTaskAndReplyWithResult( - io_task_runner_.get(), FROM_HERE, - base::BindOnce(&ReadAndDeleteTextFile, path), + io_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadAndDeleteTextFile, path), base::BindOnce(&JsonFileSanitizer::JsonFileRead, weak_factory_.GetWeakPtr(), path)); } @@ -115,8 +113,8 @@ } int size = static_cast<int>(json_string.length()); - base::PostTaskAndReplyWithResult( - io_task_runner_.get(), FROM_HERE, + io_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&WriteStringToFile, std::move(json_string), file_path), base::BindOnce(&JsonFileSanitizer::JsonFileWritten, weak_factory_.GetWeakPtr(), file_path, size));
diff --git a/extensions/browser/path_util.cc b/extensions/browser/path_util.cc index 46756bee..0700e03 100644 --- a/extensions/browser/path_util.cc +++ b/extensions/browser/path_util.cc
@@ -8,7 +8,6 @@ #include "base/files/file_util.h" #include "base/path_service.h" #include "base/strings/sys_string_conversions.h" -#include "base/task/task_runner_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "build/build_config.h" #include "extensions/browser/extension_file_task_runner.h" @@ -110,9 +109,8 @@ const base::FilePath& extension_path, int message_id, base::OnceCallback<void(const std::u16string&)> callback) { - base::PostTaskAndReplyWithResult( - GetExtensionFileTaskRunner().get(), FROM_HERE, - base::BindOnce(&base::ComputeDirectorySize, extension_path), + GetExtensionFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&base::ComputeDirectorySize, extension_path), base::BindOnce(&OnDirectorySizeCalculated, message_id, std::move(callback))); }
diff --git a/extensions/browser/sandboxed_unpacker.cc b/extensions/browser/sandboxed_unpacker.cc index e444e64..3c0c308 100644 --- a/extensions/browser/sandboxed_unpacker.cc +++ b/extensions/browser/sandboxed_unpacker.cc
@@ -23,7 +23,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/timer/elapsed_timer.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" @@ -696,8 +695,8 @@ // runner. base::FilePath locales_path = extension_root_.Append(kLocaleFolder); - base::PostTaskAndReplyWithResult( - extensions::GetExtensionFileTaskRunner().get(), FROM_HERE, + extensions::GetExtensionFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GetMessageCatalogPathsToBeSanitized, locales_path), base::BindOnce(&SandboxedUnpacker::SanitizeMessageCatalogs, this)); }
diff --git a/extensions/browser/zipfile_installer.cc b/extensions/browser/zipfile_installer.cc index bee12ea..3dc3ac3e 100644 --- a/extensions/browser/zipfile_installer.cc +++ b/extensions/browser/zipfile_installer.cc
@@ -10,7 +10,6 @@ #include "base/json/json_reader.h" #include "base/path_service.h" #include "base/strings/string_util.h" -#include "base/task/task_runner_util.h" #include "components/services/unzip/content/unzip_service.h" #include "components/services/unzip/public/cpp/unzip.h" #include "components/services/unzip/public/mojom/unzipper.mojom.h" @@ -93,9 +92,8 @@ return; } - base::PostTaskAndReplyWithResult( - io_task_runner_.get(), FROM_HERE, - base::BindOnce(&PrepareAndGetUnzipDir, zip_file), + io_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&PrepareAndGetUnzipDir, zip_file), base::BindOnce(&ZipFileInstaller::Unzip, this)); } @@ -128,8 +126,8 @@ return; } - base::PostTaskAndReplyWithResult( - io_task_runner_.get(), FROM_HERE, + io_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadFileContent, unzip_dir.Append(kManifestFilename)), base::BindOnce(&ZipFileInstaller::ManifestRead, this, unzip_dir)); }
diff --git a/extensions/common/permissions/base_set_operators.h b/extensions/common/permissions/base_set_operators.h index 5ff6d27c..c18204c 100644 --- a/extensions/common/permissions/base_set_operators.h +++ b/extensions/common/permissions/base_set_operators.h
@@ -33,9 +33,14 @@ using Map = std::map<ElementIDType, std::unique_ptr<ElementType>>; - class const_iterator : - public std::iterator<std::input_iterator_tag, const ElementType*> { + class const_iterator { public: + using iterator_category = std::input_iterator_tag; + using value_type = const ElementType*; + using difference_type = std::ptrdiff_t; + using pointer = const ElementType**; + using reference = const ElementType*&; + const_iterator(const typename Map::const_iterator& it) : it_(it) {} const_iterator(const const_iterator& ids_it) : it_(ids_it.it_) {}
diff --git a/extensions/renderer/api/automation/automation_internal_custom_bindings.cc b/extensions/renderer/api/automation/automation_internal_custom_bindings.cc index 1ffbbae..20b2c776 100644 --- a/extensions/renderer/api/automation/automation_internal_custom_bindings.cc +++ b/extensions/renderer/api/automation/automation_internal_custom_bindings.cc
@@ -253,19 +253,6 @@ const base::Value::List& event_args) const { bindings_system_->DispatchEventInContext(event_name, event_args, nullptr, context()); - - if (notify_event_for_testing_.is_null() || - event_name != "automationInternal.onAccessibilityEvent") { - return; - } - // Find the event type within the event_params for the test. - const base::Value::Dict* dict = event_args[0].GetIfDict(); - DCHECK(dict); - const std::string* event_type_string = dict->FindString("eventType"); - DCHECK(event_type_string); - api::automation::EventType event_type = - api::automation::ParseEventType(*event_type_string); - notify_event_for_testing_.Run(event_type); } std::string
diff --git a/extensions/renderer/api/automation/automation_internal_custom_bindings.h b/extensions/renderer/api/automation/automation_internal_custom_bindings.h index 9e28ee1..db536138 100644 --- a/extensions/renderer/api/automation/automation_internal_custom_bindings.h +++ b/extensions/renderer/api/automation/automation_internal_custom_bindings.h
@@ -15,7 +15,6 @@ #include "extensions/common/api/automation.h" #include "extensions/renderer/object_backed_native_handler.h" #include "ipc/ipc_message.h" -#include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/accessibility/ax_enums.mojom-shared.h" #include "ui/accessibility/platform/automation/automation_tree_manager_owner.h" #include "ui/accessibility/platform/automation/automation_v8_bindings.h" @@ -89,8 +88,6 @@ const base::Value::List& event_args) const override; private: - friend class AutomationInternalCustomBindingsTest; - // ObjectBackedNativeHandler overrides: void Invalidate() override; @@ -113,9 +110,6 @@ std::unique_ptr<ui::AutomationV8Bindings> automation_v8_bindings_; - base::RepeatingCallback<void(api::automation::EventType)> - notify_event_for_testing_; - base::WeakPtrFactory<AutomationInternalCustomBindings> weak_ptr_factory_{ this}; };
diff --git a/extensions/renderer/api/automation/automation_internal_custom_bindings_unittests.cc b/extensions/renderer/api/automation/automation_internal_custom_bindings_unittests.cc index 15220aa..da695b2 100644 --- a/extensions/renderer/api/automation/automation_internal_custom_bindings_unittests.cc +++ b/extensions/renderer/api/automation/automation_internal_custom_bindings_unittests.cc
@@ -14,9 +14,6 @@ #include "extensions/renderer/native_extension_bindings_system_test_base.h" #include "extensions/renderer/script_context.h" #include "ui/accessibility/ax_enum_util.h" -#include "ui/accessibility/ax_event_generator.h" -#include "ui/accessibility/ax_tree_id.h" -#include "ui/accessibility/platform/automation/automation_ax_tree_wrapper.h" namespace extensions { @@ -56,367 +53,10 @@ EXPECT_TRUE(availability.is_available()) << availability.message(); } - std::map<ui::AXTreeID, std::unique_ptr<ui::AutomationAXTreeWrapper>>& - GetTreeIDToTreeMap() { - return automation_internal_bindings_->tree_id_to_tree_wrapper_map_; - } - - void SendOnAccessibilityEvents( - const ExtensionMsg_AccessibilityEventBundleParams& event_bundle, - bool is_active_profile) { - automation_internal_bindings_->HandleAccessibilityEvents(event_bundle, - is_active_profile); - } - - bool CallGetFocusInternal(ui::AutomationAXTreeWrapper* top_wrapper, - ui::AutomationAXTreeWrapper** focused_wrapper, - ui::AXNode** focused_node) { - return automation_internal_bindings_->GetFocusInternal( - top_wrapper, focused_wrapper, focused_node); - } - - gfx::Rect CallComputeGlobalNodeBounds(ui::AutomationAXTreeWrapper* wrapper, - ui::AXNode* node) { - return automation_internal_bindings_->ComputeGlobalNodeBounds(wrapper, - node); - } - - std::vector<ui::AXNode*> CallGetRootsOfChildTree(ui::AXNode* node) { - return automation_internal_bindings_->GetRootsOfChildTree(node); - } - - void AddAutomationEventCallback( - base::RepeatingCallback<void(api::automation::EventType)> callback) { - automation_internal_bindings_->notify_event_for_testing_ = - std::move(callback); - } - private: AutomationInternalCustomBindings* automation_internal_bindings_ = nullptr; }; -TEST_F(AutomationInternalCustomBindingsTest, GetDesktop) { - EXPECT_TRUE(GetTreeIDToTreeMap().empty()); - - // A desktop tree. - ExtensionMsg_AccessibilityEventBundleParams bundle; - bundle.updates.emplace_back(); - auto& tree_update = bundle.updates.back(); - tree_update.root_id = 1; - tree_update.nodes.emplace_back(); - auto& node_data = tree_update.nodes.back(); - node_data.role = ax::mojom::Role::kDesktop; - node_data.id = 1; - SendOnAccessibilityEvents(bundle, true /* active profile */); - - ASSERT_EQ(1U, GetTreeIDToTreeMap().size()); - - ui::AutomationAXTreeWrapper* desktop = - GetTreeIDToTreeMap().begin()->second.get(); - ASSERT_TRUE(desktop); - EXPECT_TRUE(desktop->IsDesktopTree()); -} - -TEST_F(AutomationInternalCustomBindingsTest, GetFocusOneTree) { - // A desktop tree with focus on a button. - ExtensionMsg_AccessibilityEventBundleParams bundle; - bundle.updates.emplace_back(); - auto& tree_update = bundle.updates.back(); - tree_update.has_tree_data = true; - tree_update.root_id = 1; - auto& tree_data = tree_update.tree_data; - tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); - tree_data.focus_id = 2; - tree_update.nodes.emplace_back(); - auto& node_data1 = tree_update.nodes.back(); - node_data1.id = 1; - node_data1.role = ax::mojom::Role::kDesktop; - node_data1.child_ids.push_back(2); - tree_update.nodes.emplace_back(); - auto& node_data2 = tree_update.nodes.back(); - node_data2.id = 2; - node_data2.role = ax::mojom::Role::kButton; - bundle.tree_id = tree_data.tree_id; - SendOnAccessibilityEvents(bundle, true /* active profile */); - - ASSERT_EQ(1U, GetTreeIDToTreeMap().size()); - - ui::AutomationAXTreeWrapper* desktop = - GetTreeIDToTreeMap().begin()->second.get(); - ASSERT_TRUE(desktop); - - ui::AutomationAXTreeWrapper* focused_wrapper = nullptr; - ui::AXNode* focused_node = nullptr; - CallGetFocusInternal(desktop, &focused_wrapper, &focused_node); - ASSERT_TRUE(focused_wrapper); - ASSERT_TRUE(focused_node); - EXPECT_EQ(desktop, focused_wrapper); - EXPECT_EQ(ax::mojom::Role::kButton, focused_node->GetRole()); - - // Push an update where we change the focus. - focused_wrapper = nullptr; - focused_node = nullptr; - tree_data.focus_id = 1; - SendOnAccessibilityEvents(bundle, true /* active profile */); - CallGetFocusInternal(desktop, &focused_wrapper, &focused_node); - ASSERT_TRUE(focused_wrapper); - ASSERT_TRUE(focused_node); - EXPECT_EQ(desktop, focused_wrapper); - EXPECT_EQ(ax::mojom::Role::kDesktop, focused_node->GetRole()); - - // Push an update where we change the focus to nothing. - focused_wrapper = nullptr; - focused_node = nullptr; - tree_data.focus_id = 100; - SendOnAccessibilityEvents(bundle, true /* active profile */); - CallGetFocusInternal(desktop, &focused_wrapper, &focused_node); - ASSERT_FALSE(focused_wrapper); - ASSERT_FALSE(focused_node); -} - -TEST_F(AutomationInternalCustomBindingsTest, - GetFocusMultipleTreesChildTreeConstruction) { - // Three trees each with a button and link. - std::vector<ExtensionMsg_AccessibilityEventBundleParams> bundles; - for (int i = 0; i < 3; i++) { - bundles.emplace_back(); - auto& bundle = bundles.back(); - bundle.updates.emplace_back(); - auto& tree_update = bundle.updates.back(); - tree_update.has_tree_data = true; - tree_update.root_id = 1; - auto& tree_data = tree_update.tree_data; - - // This is a point of inconsistency as the mojo representation allows - // updates from multiple trees. - tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); - bundle.tree_id = tree_data.tree_id; - tree_data.focus_id = 2; - tree_update.nodes.emplace_back(); - auto& node_data1 = tree_update.nodes.back(); - node_data1.id = 1; - node_data1.role = ax::mojom::Role::kRootWebArea; - node_data1.child_ids.push_back(2); - node_data1.child_ids.push_back(3); - tree_update.nodes.emplace_back(); - auto& node_data2 = tree_update.nodes.back(); - node_data2.id = 2; - node_data2.role = ax::mojom::Role::kButton; - tree_update.nodes.emplace_back(); - auto& node_data3 = tree_update.nodes.back(); - node_data3.id = 3; - node_data3.role = ax::mojom::Role::kLink; - } - - // Link up the trees so that the first is a parent of the other two using - // child tree id. - ui::AXTreeID tree_0_id = bundles[0].updates[0].tree_data.tree_id; - ui::AXTreeID tree_1_id = bundles[1].updates[0].tree_data.tree_id; - ui::AXTreeID tree_2_id = bundles[2].updates[0].tree_data.tree_id; - bundles[0].updates[0].nodes[1].AddChildTreeId(tree_1_id); - bundles[0].updates[0].nodes[2].AddChildTreeId(tree_2_id); - - for (auto& bundle : bundles) - SendOnAccessibilityEvents(bundle, true /* active profile */); - - ASSERT_EQ(3U, GetTreeIDToTreeMap().size()); - - ui::AutomationAXTreeWrapper* wrapper_0 = - GetTreeIDToTreeMap()[tree_0_id].get(); - ASSERT_TRUE(wrapper_0); - ui::AutomationAXTreeWrapper* wrapper_1 = - GetTreeIDToTreeMap()[tree_1_id].get(); - ASSERT_TRUE(wrapper_1); - ui::AutomationAXTreeWrapper* wrapper_2 = - GetTreeIDToTreeMap()[tree_2_id].get(); - ASSERT_TRUE(wrapper_2); - - ui::AutomationAXTreeWrapper* focused_wrapper = nullptr; - ui::AXNode* focused_node = nullptr; - CallGetFocusInternal(wrapper_0, &focused_wrapper, &focused_node); - ASSERT_TRUE(focused_wrapper); - ASSERT_TRUE(focused_node); - EXPECT_EQ(wrapper_1, focused_wrapper); - EXPECT_EQ(tree_1_id, focused_node->tree()->GetAXTreeID()); - EXPECT_EQ(ax::mojom::Role::kButton, focused_node->GetRole()); - - // Push an update where we change the focus. - focused_wrapper = nullptr; - focused_node = nullptr; - - // The link in wrapper 0 which has a child tree id pointing to wrapper 2. - bundles[0].updates[0].tree_data.focus_id = 3; - SendOnAccessibilityEvents(bundles[0], true /* active profile */); - CallGetFocusInternal(wrapper_0, &focused_wrapper, &focused_node); - ASSERT_TRUE(focused_wrapper); - ASSERT_TRUE(focused_node); - EXPECT_EQ(wrapper_2, focused_wrapper); - EXPECT_EQ(tree_2_id, focused_node->tree()->GetAXTreeID()); - EXPECT_EQ(ax::mojom::Role::kButton, focused_node->GetRole()); -} - -TEST_F(AutomationInternalCustomBindingsTest, - GetFocusMultipleTreesAppIdConstruction) { - // Three trees each with a button and link. - std::vector<ExtensionMsg_AccessibilityEventBundleParams> bundles; - for (int i = 0; i < 3; i++) { - bundles.emplace_back(); - auto& bundle = bundles.back(); - bundle.updates.emplace_back(); - auto& tree_update = bundle.updates.back(); - tree_update.has_tree_data = true; - tree_update.root_id = 1; - auto& tree_data = tree_update.tree_data; - - // This is a point of inconsistency as the mojo representation allows - // updates from ultiple trees. - tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); - bundle.tree_id = tree_data.tree_id; - tree_data.focus_id = 2; - tree_update.nodes.emplace_back(); - auto& node_data1 = tree_update.nodes.back(); - node_data1.id = 1; - node_data1.role = ax::mojom::Role::kRootWebArea; - node_data1.child_ids.push_back(2); - node_data1.child_ids.push_back(3); - tree_update.nodes.emplace_back(); - auto& node_data2 = tree_update.nodes.back(); - node_data2.id = 2; - node_data2.role = ax::mojom::Role::kButton; - tree_update.nodes.emplace_back(); - auto& node_data3 = tree_update.nodes.back(); - node_data3.id = 3; - node_data3.role = ax::mojom::Role::kLink; - } - - // Link up the trees so that the first is a parent of the other two using app - // ids. - ui::AXTreeID tree_0_id = bundles[0].updates[0].tree_data.tree_id; - ui::AXTreeID tree_1_id = bundles[1].updates[0].tree_data.tree_id; - ui::AXTreeID tree_2_id = bundles[2].updates[0].tree_data.tree_id; - auto& wrapper0_button_data = bundles[0].updates[0].nodes[1]; - auto& wrapper0_link_data = bundles[0].updates[0].nodes[2]; - auto& wrapper1_link_data = bundles[1].updates[0].nodes[2]; - auto& wrapper2_button_data = bundles[2].updates[0].nodes[1]; - - // This construction requires the hosting and client nodes annotate with the - // same app id. - wrapper0_button_data.AddStringAttribute( - ax::mojom::StringAttribute::kChildTreeNodeAppId, "app1"); - wrapper1_link_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, - "app1"); - wrapper0_link_data.AddStringAttribute( - ax::mojom::StringAttribute::kChildTreeNodeAppId, "app2"); - wrapper2_button_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, - "app2"); - - for (auto& bundle : bundles) - SendOnAccessibilityEvents(bundle, true /* active profile */); - - ASSERT_EQ(3U, GetTreeIDToTreeMap().size()); - - ui::AutomationAXTreeWrapper* wrapper_0 = - GetTreeIDToTreeMap()[tree_0_id].get(); - ASSERT_TRUE(wrapper_0); - ui::AutomationAXTreeWrapper* wrapper_1 = - GetTreeIDToTreeMap()[tree_1_id].get(); - ASSERT_TRUE(wrapper_1); - ui::AutomationAXTreeWrapper* wrapper_2 = - GetTreeIDToTreeMap()[tree_2_id].get(); - ASSERT_TRUE(wrapper_2); - - ui::AutomationAXTreeWrapper* focused_wrapper = nullptr; - ui::AXNode* focused_node = nullptr; - CallGetFocusInternal(wrapper_0, &focused_wrapper, &focused_node); - ASSERT_TRUE(focused_wrapper); - ASSERT_TRUE(focused_node); - EXPECT_EQ(wrapper_1, focused_wrapper); - EXPECT_EQ(tree_1_id, focused_node->tree()->GetAXTreeID()); - - // This is an interesting inconsistency as this node is technically not in the - // app (which starts at the link in wrapper 1). - EXPECT_EQ(ax::mojom::Role::kButton, focused_node->GetRole()); - - // Push an update where we change the focus. - focused_wrapper = nullptr; - focused_node = nullptr; - - // The link in wrapper 0 which has a child tree id pointing to wrapper 2. - bundles[0].updates[0].tree_data.focus_id = 3; - SendOnAccessibilityEvents(bundles[0], true /* active profile */); - CallGetFocusInternal(wrapper_0, &focused_wrapper, &focused_node); - ASSERT_TRUE(focused_wrapper); - ASSERT_TRUE(focused_node); - EXPECT_EQ(wrapper_2, focused_wrapper); - EXPECT_EQ(tree_2_id, focused_node->tree()->GetAXTreeID()); - EXPECT_EQ(ax::mojom::Role::kButton, focused_node->GetRole()); -} - -TEST_F(AutomationInternalCustomBindingsTest, GetBoundsAppIdConstruction) { - // two trees each with a button. - std::vector<ExtensionMsg_AccessibilityEventBundleParams> bundles; - for (int i = 0; i < 2; i++) { - bundles.emplace_back(); - auto& bundle = bundles.back(); - bundle.updates.emplace_back(); - auto& tree_update = bundle.updates.back(); - tree_update.has_tree_data = true; - tree_update.root_id = 1; - auto& tree_data = tree_update.tree_data; - tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); - bundle.tree_id = tree_data.tree_id; - tree_update.nodes.emplace_back(); - auto& node_data1 = tree_update.nodes.back(); - node_data1.id = 1; - node_data1.role = - i == 0 ? ax::mojom::Role::kDesktop : ax::mojom::Role::kRootWebArea; - node_data1.child_ids.push_back(2); - node_data1.relative_bounds.bounds = gfx::RectF(100, 100, 100, 100); - tree_update.nodes.emplace_back(); - auto& node_data2 = tree_update.nodes.back(); - node_data2.id = 2; - node_data2.role = ax::mojom::Role::kButton; - node_data2.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); - } - - // Link up the trees by app id. - ui::AXTreeID tree_0_id = bundles[0].updates[0].tree_data.tree_id; - ui::AXTreeID tree_1_id = bundles[1].updates[0].tree_data.tree_id; - auto& wrapper0_button_data = bundles[0].updates[0].nodes[1]; - auto& wrapper1_button_data = bundles[1].updates[0].nodes[1]; - - // This construction requires the hosting and client nodes annotate with the - // same app id. - wrapper0_button_data.AddStringAttribute( - ax::mojom::StringAttribute::kChildTreeNodeAppId, "app1"); - wrapper1_button_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, - "app1"); - - wrapper0_button_data.AddFloatAttribute( - ax::mojom::FloatAttribute::kChildTreeScale, 2.0); - - for (auto& bundle : bundles) - SendOnAccessibilityEvents(bundle, true /* active profile */); - - ASSERT_EQ(2U, GetTreeIDToTreeMap().size()); - - ui::AutomationAXTreeWrapper* wrapper_0 = - GetTreeIDToTreeMap()[tree_0_id].get(); - ASSERT_TRUE(wrapper_0); - ui::AutomationAXTreeWrapper* wrapper_1 = - GetTreeIDToTreeMap()[tree_1_id].get(); - ASSERT_TRUE(wrapper_1); - - ui::AXNode* wrapper1_button = wrapper_1->ax_tree()->GetFromId(2); - ASSERT_TRUE(wrapper1_button); - - // The button in wrapper 1 is scaled by .5 (200 * .5). It's root is also - // scaled (100 * .5). In wrapper 0, it is *not* offset by the tree's root - // bounds. - EXPECT_EQ(gfx::Rect(50, 50, 100, 100), - CallComputeGlobalNodeBounds(wrapper_1, wrapper1_button)); -} - TEST_F(AutomationInternalCustomBindingsTest, ActionStringMapping) { for (uint32_t action = static_cast<uint32_t>(ax::mojom::Action::kNone) + 1; action <= static_cast<uint32_t>(ax::mojom::Action::kMaxValue); @@ -428,348 +68,4 @@ } } -TEST_F(AutomationInternalCustomBindingsTest, GetBoundsNestedAppIdConstruction) { - // two trees each with a button and a client node. - std::vector<ExtensionMsg_AccessibilityEventBundleParams> bundles; - for (int i = 0; i < 2; i++) { - bundles.emplace_back(); - auto& bundle = bundles.back(); - bundle.updates.emplace_back(); - auto& tree_update = bundle.updates.back(); - tree_update.has_tree_data = true; - tree_update.root_id = 1; - auto& tree_data = tree_update.tree_data; - tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); - bundle.tree_id = tree_data.tree_id; - tree_update.nodes.emplace_back(); - auto& node_data1 = tree_update.nodes.back(); - node_data1.id = 1; - node_data1.role = - i == 0 ? ax::mojom::Role::kDesktop : ax::mojom::Role::kRootWebArea; - node_data1.child_ids.push_back(2); - node_data1.child_ids.push_back(3); - node_data1.relative_bounds.bounds = gfx::RectF(100, 100, 100, 100); - tree_update.nodes.emplace_back(); - auto& node_data2 = tree_update.nodes.back(); - node_data2.id = 2; - node_data2.role = ax::mojom::Role::kButton; - node_data2.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); - tree_update.nodes.emplace_back(); - auto& node_data3 = tree_update.nodes.back(); - node_data3.id = 3; - node_data3.role = ax::mojom::Role::kClient; - node_data3.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); - } - - // Link up the trees by app id. One button -> child button; client -> child - // root. - ui::AXTreeID tree_0_id = bundles[0].updates[0].tree_data.tree_id; - ui::AXTreeID tree_1_id = bundles[1].updates[0].tree_data.tree_id; - auto& wrapper0_button_data = bundles[0].updates[0].nodes[1]; - auto& wrapper0_client_data = bundles[0].updates[0].nodes[2]; - auto& wrapper1_root_data = bundles[1].updates[0].nodes[0]; - auto& wrapper1_button_data = bundles[1].updates[0].nodes[1]; - - // This construction requires the hosting and client nodes annotate with the - // same app id. - wrapper0_button_data.AddStringAttribute( - ax::mojom::StringAttribute::kChildTreeNodeAppId, "app1"); - wrapper1_button_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, - "app1"); - - wrapper0_button_data.AddFloatAttribute( - ax::mojom::FloatAttribute::kChildTreeScale, 2.0); - - // Adding this app id should not impact the above bounds computation. - wrapper0_client_data.AddStringAttribute( - ax::mojom::StringAttribute::kChildTreeNodeAppId, "lacrosHost"); - wrapper1_root_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, - "lacrosHost"); - - for (auto& bundle : bundles) - SendOnAccessibilityEvents(bundle, true /* active profile */); - - ASSERT_EQ(2U, GetTreeIDToTreeMap().size()); - - ui::AutomationAXTreeWrapper* wrapper_0 = - GetTreeIDToTreeMap()[tree_0_id].get(); - ASSERT_TRUE(wrapper_0); - ui::AutomationAXTreeWrapper* wrapper_1 = - GetTreeIDToTreeMap()[tree_1_id].get(); - ASSERT_TRUE(wrapper_1); - - ui::AXNode* wrapper1_button = wrapper_1->ax_tree()->GetFromId(2); - ASSERT_TRUE(wrapper1_button); - - // The button in wrapper 1 is scaled by .5 (200 * .5). It's root is also - // scaled (100 * .5). In wrapper 0, it is *not* offset by the tree's root - // bounds. - EXPECT_EQ(gfx::Rect(50, 50, 100, 100), - CallComputeGlobalNodeBounds(wrapper_1, wrapper1_button)); - - ui::AXNode* wrapper1_root = wrapper_1->ax_tree()->GetFromId(1); - ASSERT_TRUE(wrapper1_root); - - // Similar to the button, but not scaled. This does not cross an app id - // boundary, so is also offset by the parent tree's root (100 + 100). - EXPECT_EQ(gfx::Rect(200, 200, 100, 100), - CallComputeGlobalNodeBounds(wrapper_1, wrapper1_root)); -} - -TEST_F(AutomationInternalCustomBindingsTest, IgnoredAncestorTrees) { - // Three trees each with a button and link. - std::vector<ExtensionMsg_AccessibilityEventBundleParams> bundles; - for (int i = 0; i < 3; i++) { - bundles.emplace_back(); - auto& bundle = bundles.back(); - bundle.updates.emplace_back(); - auto& tree_update = bundle.updates.back(); - tree_update.has_tree_data = true; - tree_update.root_id = 1; - auto& tree_data = tree_update.tree_data; - - // This is a point of inconsistency as the mojo representation allows - // updates from multiple trees. - tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); - bundle.tree_id = tree_data.tree_id; - tree_data.focus_id = 2; - tree_update.nodes.emplace_back(); - auto& node_data1 = tree_update.nodes.back(); - node_data1.id = 1; - node_data1.role = ax::mojom::Role::kRootWebArea; - node_data1.child_ids.push_back(2); - node_data1.child_ids.push_back(3); - tree_update.nodes.emplace_back(); - auto& node_data2 = tree_update.nodes.back(); - node_data2.id = 2; - node_data2.role = ax::mojom::Role::kButton; - tree_update.nodes.emplace_back(); - auto& node_data3 = tree_update.nodes.back(); - node_data3.id = 3; - node_data3.role = ax::mojom::Role::kLink; - } - - // Link up the trees so that the first is a parent of the second and the - // second a parent of the third. - ui::AXTreeID tree_0_id = bundles[0].updates[0].tree_data.tree_id; - ui::AXTreeID tree_1_id = bundles[1].updates[0].tree_data.tree_id; - ui::AXTreeID tree_2_id = bundles[2].updates[0].tree_data.tree_id; - bundles[0].updates[0].nodes[1].AddChildTreeId(tree_1_id); - - // Make the hosting node ignored. - bundles[0].updates[0].nodes[1].AddState(ax::mojom::State::kInvisible); - - bundles[1].updates[0].nodes[1].AddChildTreeId(tree_2_id); - - for (auto& bundle : bundles) - SendOnAccessibilityEvents(bundle, true /* active profile */); - - ASSERT_EQ(3U, GetTreeIDToTreeMap().size()); - - ui::AutomationAXTreeWrapper* wrapper_0 = - GetTreeIDToTreeMap()[tree_0_id].get(); - ASSERT_TRUE(wrapper_0); - ui::AutomationAXTreeWrapper* wrapper_1 = - GetTreeIDToTreeMap()[tree_1_id].get(); - ASSERT_TRUE(wrapper_1); - ui::AutomationAXTreeWrapper* wrapper_2 = - GetTreeIDToTreeMap()[tree_2_id].get(); - ASSERT_TRUE(wrapper_2); - - // The root tree isn't ignored. - EXPECT_FALSE(wrapper_0->IsTreeIgnored()); - - // However, since the hosting node in |wrapper_0| is ignored, both of the - // descendant trees should be ignored. - EXPECT_TRUE(wrapper_1->IsTreeIgnored()); - EXPECT_TRUE(wrapper_2->IsTreeIgnored()); - - // No longer invisible. - ui::AXNode* button = wrapper_0->ax_tree()->GetFromId(2); - ui::AXNodeData data = button->TakeData(); - data.RemoveState(ax::mojom::State::kInvisible); - button->SetData(data); - - EXPECT_FALSE(wrapper_0->IsTreeIgnored()); - EXPECT_FALSE(wrapper_1->IsTreeIgnored()); - EXPECT_FALSE(wrapper_2->IsTreeIgnored()); -} - -TEST_F(AutomationInternalCustomBindingsTest, - GetMultipleChildRootsAppIdConstruction) { - // Two trees each with a button and a client node. - std::vector<ExtensionMsg_AccessibilityEventBundleParams> bundles; - for (int i = 0; i < 2; i++) { - bundles.emplace_back(); - auto& bundle = bundles.back(); - bundle.updates.emplace_back(); - auto& tree_update = bundle.updates.back(); - tree_update.has_tree_data = true; - tree_update.root_id = 1; - auto& tree_data = tree_update.tree_data; - tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); - bundle.tree_id = tree_data.tree_id; - tree_update.nodes.emplace_back(); - auto& node_data1 = tree_update.nodes.back(); - node_data1.id = 1; - node_data1.role = - i == 0 ? ax::mojom::Role::kDesktop : ax::mojom::Role::kRootWebArea; - node_data1.child_ids.push_back(2); - node_data1.child_ids.push_back(3); - node_data1.relative_bounds.bounds = gfx::RectF(100, 100, 100, 100); - tree_update.nodes.emplace_back(); - auto& node_data2 = tree_update.nodes.back(); - node_data2.id = 2; - node_data2.role = ax::mojom::Role::kButton; - node_data2.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); - tree_update.nodes.emplace_back(); - auto& node_data3 = tree_update.nodes.back(); - node_data3.id = 3; - node_data3.role = ax::mojom::Role::kClient; - node_data3.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); - } - - // Link up the trees by using one app id. Tree 0's client has two children - // from tree 1. - ui::AXTreeID tree_0_id = bundles[0].updates[0].tree_data.tree_id; - ui::AXTreeID tree_1_id = bundles[1].updates[0].tree_data.tree_id; - auto& wrapper0_client_data = bundles[0].updates[0].nodes[2]; - auto& wrapper1_button_data = bundles[1].updates[0].nodes[1]; - auto& wrapper1_client_data = bundles[1].updates[0].nodes[2]; - - // This construction requires the hosting and client nodes annotate with the - // same app id. - wrapper0_client_data.AddStringAttribute( - ax::mojom::StringAttribute::kChildTreeNodeAppId, "app1"); - wrapper1_button_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, - "app1"); - wrapper1_client_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, - "app1"); - - for (auto& bundle : bundles) - SendOnAccessibilityEvents(bundle, true /* active profile */); - - ASSERT_EQ(2U, GetTreeIDToTreeMap().size()); - - ui::AutomationAXTreeWrapper* wrapper_0 = - GetTreeIDToTreeMap()[tree_0_id].get(); - ASSERT_TRUE(wrapper_0); - - ui::AXNode* wrapper0_client = wrapper_0->ax_tree()->GetFromId(3); - ASSERT_TRUE(wrapper0_client); - - std::vector<ui::AXNode*> child_roots = - CallGetRootsOfChildTree(wrapper0_client); - EXPECT_EQ(2U, child_roots.size()); - EXPECT_EQ(tree_1_id, child_roots[0]->tree()->GetAXTreeID()); - EXPECT_EQ(tree_1_id, child_roots[1]->tree()->GetAXTreeID()); - EXPECT_EQ(2, child_roots[0]->id()); - EXPECT_EQ(3, child_roots[1]->id()); -} - -TEST_F(AutomationInternalCustomBindingsTest, FireEventsWithListeners) { - // A simple tree. - ExtensionMsg_AccessibilityEventBundleParams bundle; - bundle.updates.emplace_back(); - auto& tree_update = bundle.updates.back(); - tree_update.has_tree_data = true; - tree_update.root_id = 1; - auto& tree_data = tree_update.tree_data; - tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); - bundle.tree_id = tree_data.tree_id; - tree_update.nodes.emplace_back(); - auto& node_data1 = tree_update.nodes.back(); - node_data1.id = 1; - node_data1.role = ax::mojom::Role::kRootWebArea; - node_data1.child_ids.push_back(2); - node_data1.relative_bounds.bounds = gfx::RectF(100, 100, 100, 100); - tree_update.nodes.emplace_back(); - auto& node_data2 = tree_update.nodes.back(); - node_data2.id = 2; - node_data2.role = ax::mojom::Role::kButton; - node_data2.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); - - // Add a hook for events from automation. - std::vector<api::automation::EventType> events; - AddAutomationEventCallback(base::BindLambdaForTesting( - [&](api::automation::EventType event) { events.push_back(event); })); - - SendOnAccessibilityEvents(bundle, true /* active profile */); - - // We aren't listening for any events yet, but we should still get one that - // gets fired on initial tree creation. - ASSERT_EQ(1U, events.size()); - EXPECT_EQ(api::automation::EVENT_TYPE_NONE, events[0]); - events.clear(); - - // Remove the root node data and don't update tree data. - tree_update.nodes.erase(tree_update.nodes.begin()); - tree_update.has_tree_data = false; - - // Trigger a role change. - tree_update.nodes[0].role = ax::mojom::Role::kSwitch; - SendOnAccessibilityEvents(bundle, true /* active profile */); - - // There should be no events since there are no listeners and this isn't the - // initial tree. - ASSERT_TRUE(events.empty()); - - // Add a role change listener and do trigger the role change again. - auto* wrapper = GetTreeIDToTreeMap()[tree_data.tree_id].get(); - auto* tree = wrapper->ax_tree(); - // The button is id 2. - std::tuple<ax::mojom::Event, ui::AXEventGenerator::Event> event_type( - ax::mojom::Event::kNone, ui::AXEventGenerator::Event::ROLE_CHANGED); - wrapper->EventListenerAdded(event_type, tree->GetFromId(2)); - EXPECT_EQ(1U, wrapper->EventListenerCount()); - EXPECT_TRUE(wrapper->HasEventListener(event_type, tree->GetFromId(2))); - tree_update.nodes[0].role = ax::mojom::Role::kButton; - SendOnAccessibilityEvents(bundle, true /* active profile */); - - // We should now have exactly one event. - ASSERT_EQ(1U, events.size()); - EXPECT_EQ(api::automation::EVENT_TYPE_ROLECHANGED, events[0]); - events.clear(); - - // Now, remove the listener and do the same as above. - wrapper->EventListenerRemoved(event_type, tree->GetFromId(2)); - // We have to add another listener to ensure we don't shut down (no event - // listeners means this renderer closes). - wrapper->EventListenerAdded( - std::tuple<ax::mojom::Event, ui::AXEventGenerator::Event>( - ax::mojom::Event::kLoadComplete, ui::AXEventGenerator::Event::NONE), - tree->GetFromId(1)); - tree_update.nodes[0].role = ax::mojom::Role::kSwitch; - SendOnAccessibilityEvents(bundle, true /* active profile */); - - // We should have no events. - ASSERT_TRUE(events.empty()); - - // Finally, let's fire a non-generated event on the button, but add the - // listener on the root. This will test both non-generated events and - // respecting event listeners on ancestors of the target. - - // First, fire the event without the click listener. - tree_update.nodes.clear(); - bundle.events.emplace_back(); - auto& event = bundle.events.back(); - event.event_type = ax::mojom::Event::kClicked; - event.id = 2; - SendOnAccessibilityEvents(bundle, true /* active profile */); - - // No event. - ASSERT_TRUE(events.empty()); - - // Now, add the click listener to the root, and fire the click event on the - // button. - wrapper->EventListenerAdded( - std::tuple<ax::mojom::Event, ui::AXEventGenerator::Event>( - ax::mojom::Event::kClicked, ui::AXEventGenerator::Event::NONE), - tree->GetFromId(1)); - SendOnAccessibilityEvents(bundle, true /* active profile */); - - ASSERT_EQ(1U, events.size()); - EXPECT_EQ(api::automation::EVENT_TYPE_CLICKED, events[0]); -} - } // namespace extensions
diff --git a/extensions/shell/browser/shell_extension_loader.cc b/extensions/shell/browser/shell_extension_loader.cc index 3ba6ddf9..378c460 100644 --- a/extensions/shell/browser/shell_extension_loader.cc +++ b/extensions/shell/browser/shell_extension_loader.cc
@@ -11,7 +11,6 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "components/services/app_service/public/mojom/types.mojom-shared.h" #include "extensions/browser/extension_file_task_runner.h" #include "extensions/browser/extension_prefs.h" @@ -151,9 +150,8 @@ LoadErrorBehavior load_error_behavior) { CHECK(!path.empty()); - base::PostTaskAndReplyWithResult( - GetExtensionFileTaskRunner().get(), FROM_HERE, - base::BindOnce(&LoadUnpacked, path), + GetExtensionFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadUnpacked, path), base::BindOnce(&ShellExtensionLoader::FinishExtensionReload, weak_factory_.GetWeakPtr(), extension_id)); did_schedule_reload_ = true;
diff --git a/google_apis/calendar/calendar_api_requests.cc b/google_apis/calendar/calendar_api_requests.cc index 927531dc..eee1b5f3 100644 --- a/google_apis/calendar/calendar_api_requests.cc +++ b/google_apis/calendar/calendar_api_requests.cc
@@ -6,7 +6,6 @@ #include <stddef.h> -#include "base/task/task_runner_util.h" #include "base/values.h" #include "net/base/url_util.h" @@ -100,8 +99,8 @@ ApiErrorCode error = GetErrorCode(); switch (error) { case HTTP_SUCCESS: - base::PostTaskAndReplyWithResult( - blocking_task_runner(), FROM_HERE, + blocking_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CalendarApiEventsRequest::Parse, std::move(response_body)), base::BindOnce(&CalendarApiEventsRequest::OnDataParsed,
diff --git a/google_apis/common/base_requests.cc b/google_apis/common/base_requests.cc index fd8c8d6..ea498cfd 100644 --- a/google_apis/common/base_requests.cc +++ b/google_apis/common/base_requests.cc
@@ -16,7 +16,6 @@ #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/values.h" #include "google_apis/common/request_sender.h" #include "google_apis/common/task_util.h" @@ -322,8 +321,8 @@ if (!download_data_->output_file_path.empty()) { DownloadData* download_data_ptr = download_data_.get(); - base::PostTaskAndReplyWithResult( - blocking_task_runner(), FROM_HERE, + blocking_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&UrlFetchRequestBase::WriteFileData, std::string(string_piece), download_data_ptr), base::BindOnce(&UrlFetchRequestBase::OnWriteComplete,
diff --git a/gpu/command_buffer/service/shared_image/compound_image_backing.cc b/gpu/command_buffer/service/shared_image/compound_image_backing.cc index a6c3941..b20ada9 100644 --- a/gpu/command_buffer/service/shared_image/compound_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/compound_image_backing.cc
@@ -601,9 +601,6 @@ gpu_backing_->SetNotRefCounted(); gpu_backing_->SetClearedRect(gfx::Rect(size())); - - // Update peak GPU memory tracking with the new estimated size. - UpdateEstimatedSize(EstimatedSizeForMemTracking()); } } // namespace gpu
diff --git a/gpu/command_buffer/service/shared_image/compound_image_backing_unittest.cc b/gpu/command_buffer/service/shared_image/compound_image_backing_unittest.cc index 7655680..42aebc9 100644 --- a/gpu/command_buffer/service/shared_image/compound_image_backing_unittest.cc +++ b/gpu/command_buffer/service/shared_image/compound_image_backing_unittest.cc
@@ -21,13 +21,9 @@ #include "ui/gfx/buffer_types.h" #include "ui/gl/gl_image.h" -using testing::_; - namespace gpu { namespace { -constexpr int kTestBackingSize = 40000; - class TestSharedImageBackingFactory : public SharedImageBackingFactory { public: // SharedImageBackingFactory implementation. @@ -44,9 +40,9 @@ if (allocations_should_fail_) return nullptr; - return std::make_unique<TestImageBacking>( - mailbox, format, size, color_space, surface_origin, alpha_type, usage, - kTestBackingSize); + return std::make_unique<TestImageBacking>(mailbox, format, size, + color_space, surface_origin, + alpha_type, usage, 0); } std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, @@ -148,7 +144,7 @@ protected: SharedImageManager manager_; TestSharedImageBackingFactory test_factory_; - testing::NiceMock<gles2::MockMemoryTracker> mock_memory_tracker_; + gles2::MockMemoryTracker mock_memory_tracker_; MemoryTypeTracker tracker_{&mock_memory_tracker_}; }; @@ -163,31 +159,17 @@ EXPECT_FALSE(compound_backing->HasAnyRefs()); EXPECT_FALSE(HasGpuBacking(compound_backing)); - // When the compound backing is first registered it will get a reference - // and add shared memory backing size to the memory tracker. - EXPECT_CALL(mock_memory_tracker_, - TrackMemoryAllocatedChange(kTestBackingSize)); - auto factory_rep = manager_.Register(std::move(backing), &tracker_); - testing::Mock::VerifyAndClearExpectations(&mock_memory_tracker_); - // After register compound backing it should have a reference. The GPU // backing should never have any reference as it's owned by the compound // backing and isn't reference counted. EXPECT_TRUE(compound_backing->HasAnyRefs()); EXPECT_FALSE(HasGpuBacking(compound_backing)); - // On overlay access a GPU backing will be allocated and the recorded size - // will increase. - EXPECT_CALL(mock_memory_tracker_, - TrackMemoryAllocatedChange(kTestBackingSize)); - auto overlay_rep = manager_.ProduceOverlay(compound_backing->mailbox(), &tracker_); - testing::Mock::VerifyAndClearExpectations(&mock_memory_tracker_); - auto* gpu_backing = GetGpuBacking(compound_backing); // GPU backing still shouldn't have any references after a wrapped @@ -198,11 +180,6 @@ overlay_rep.reset(); EXPECT_TRUE(compound_backing->HasAnyRefs()); - // When all references are dropped the total size of shared memory and gpu - // backings will be subtracted from memory tracker. - EXPECT_CALL(mock_memory_tracker_, - TrackMemoryAllocatedChange(-kTestBackingSize * 2)); - // All the backings will be destroyed after this point. factory_rep.reset(); }
diff --git a/gpu/command_buffer/service/shared_image/raw_draw_image_backing.cc b/gpu/command_buffer/service/shared_image/raw_draw_image_backing.cc index c73da28..eddef82 100644 --- a/gpu/command_buffer/service/shared_image/raw_draw_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/raw_draw_image_backing.cc
@@ -159,6 +159,15 @@ } } +size_t RawDrawImageBacking::EstimatedSizeForMemTracking() const { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + AutoLock auto_lock(this); + return backend_texture_.isValid() + ? viz::ResourceSizes::UncheckedSizeInBytes<size_t>(size(), + format()) + : 0u; +} + std::unique_ptr<RasterImageRepresentation> RawDrawImageBacking::ProduceRaster( SharedImageManager* manager, MemoryTypeTracker* tracker) { @@ -219,6 +228,9 @@ } promise_texture_ = SkPromiseImageTexture::Make(backend_texture_); + // TODO(crbug.com/1353911): The estimated size recorded with GPU memory + // tracker should be updated after `backend_texture_` is allocated. + auto surface = SkSurface::MakeFromBackendTexture( context_state_->gr_context(), backend_texture_, surface_origin(), final_msaa_count_, sk_color, color_space().ToSkColorSpace(), @@ -249,9 +261,6 @@ surface->resolveMSAA(); } - UpdateEstimatedSize( - viz::ResourceSizes::UncheckedSizeInBytes<size_t>(size(), format())); - return true; }
diff --git a/gpu/command_buffer/service/shared_image/raw_draw_image_backing.h b/gpu/command_buffer/service/shared_image/raw_draw_image_backing.h index f7e45d71..61b1c1a2 100644 --- a/gpu/command_buffer/service/shared_image/raw_draw_image_backing.h +++ b/gpu/command_buffer/service/shared_image/raw_draw_image_backing.h
@@ -39,6 +39,7 @@ base::trace_event::MemoryAllocatorDumpGuid client_guid, base::trace_event::ProcessMemoryDump* pmd, uint64_t client_tracing_id) override; + size_t EstimatedSizeForMemTracking() const override; protected: std::unique_ptr<RasterImageRepresentation> ProduceRaster(
diff --git a/gpu/command_buffer/service/shared_image/shared_image_backing.cc b/gpu/command_buffer/service/shared_image/shared_image_backing.cc index 3881855..abc38725 100644 --- a/gpu/command_buffer/service/shared_image/shared_image_backing.cc +++ b/gpu/command_buffer/service/shared_image/shared_image_backing.cc
@@ -204,25 +204,6 @@ } #endif -void SharedImageBacking::UpdateEstimatedSize(size_t estimated_size_bytes) { - AutoLock auto_lock(this); - - if (estimated_size_bytes == estimated_size_) - return; - - if (!refs_.empty()) { - // Propagate the estimated size the memory tracker. - auto* memory_tracker = refs_[0]->tracker(); - if (estimated_size_ < estimated_size_bytes) { - memory_tracker->TrackMemAlloc(estimated_size_bytes - estimated_size_); - } else { - memory_tracker->TrackMemFree(estimated_size_ - estimated_size_bytes); - } - } - - estimated_size_ = estimated_size_bytes; -} - void SharedImageBacking::SetNotRefCounted() { DCHECK(!HasAnyRefs()); is_ref_counted_ = false;
diff --git a/gpu/command_buffer/service/shared_image/shared_image_backing.h b/gpu/command_buffer/service/shared_image/shared_image_backing.h index a30d11b86..d8d17558 100644 --- a/gpu/command_buffer/service/shared_image/shared_image_backing.h +++ b/gpu/command_buffer/service/shared_image/shared_image_backing.h
@@ -235,9 +235,6 @@ ProduceLegacyOverlay(SharedImageManager* manager, MemoryTypeTracker* tracker); #endif - // Updates the estimated size if memory usage changes after creation. - void UpdateEstimatedSize(size_t estimated_size_bytes); - // Used by subclasses during destruction. bool have_context() const EXCLUSIVE_LOCKS_REQUIRED(lock_); @@ -296,7 +293,7 @@ const GrSurfaceOrigin surface_origin_; const SkAlphaType alpha_type_; const uint32_t usage_; - size_t estimated_size_; + const size_t estimated_size_; bool is_ref_counted_ = true;
diff --git a/gpu/ipc/service/gpu_init.cc b/gpu/ipc/service/gpu_init.cc index 55289de..bcde6af 100644 --- a/gpu/ipc/service/gpu_init.cc +++ b/gpu/ipc/service/gpu_init.cc
@@ -757,8 +757,6 @@ gpu_info_.sandboxed = sandbox_helper_->EnsureSandboxInitialized( watchdog_thread_.get(), &gpu_info_, gpu_preferences_); } - UMA_HISTOGRAM_BOOLEAN("GPU.Sandbox.InitializedSuccessfully", - gpu_info_.sandboxed); init_successful_ = true; #if BUILDFLAG(IS_OZONE)
diff --git a/gpu/vulkan/init/vulkan_factory.cc b/gpu/vulkan/init/vulkan_factory.cc index 827d7f8..6ddbfbe 100644 --- a/gpu/vulkan/init/vulkan_factory.cc +++ b/gpu/vulkan/init/vulkan_factory.cc
@@ -6,6 +6,7 @@ #include "build/build_config.h" #include <memory> +#include <ostream> #if BUILDFLAG(IS_ANDROID) #include "gpu/vulkan/android/vulkan_implementation_android.h"
diff --git a/headless/public/internal/value_conversions.h b/headless/public/internal/value_conversions.h index cf71dd5..1da0bcc4 100644 --- a/headless/public/internal/value_conversions.h +++ b/headless/public/internal/value_conversions.h
@@ -179,7 +179,7 @@ return result; } errors->Push(); - for (const auto& item : value.GetListDeprecated()) + for (const auto& item : value.GetList()) result.push_back(FromValue<T>::Parse(item, errors)); errors->Pop(); return result;
diff --git a/infra/config/generated/builders/ci/android-pie-arm64-rel/properties.json b/infra/config/generated/builders/ci/android-pie-arm64-rel/properties.json index 9ff45d6..5a294a8 100644 --- a/infra/config/generated/builders/ci/android-pie-arm64-rel/properties.json +++ b/infra/config/generated/builders/ci/android-pie-arm64-rel/properties.json
@@ -18,6 +18,7 @@ }, "legacy_chromium_config": { "apply_configs": [ + "download_vr_test_apks", "mb" ], "build_config": "Release",
diff --git a/infra/config/generated/builders/try/android-pie-arm64-rel-compilator/properties.json b/infra/config/generated/builders/try/android-pie-arm64-rel-compilator/properties.json index ef8ab510..048533b5 100644 --- a/infra/config/generated/builders/try/android-pie-arm64-rel-compilator/properties.json +++ b/infra/config/generated/builders/try/android-pie-arm64-rel-compilator/properties.json
@@ -18,6 +18,7 @@ }, "legacy_chromium_config": { "apply_configs": [ + "download_vr_test_apks", "mb" ], "build_config": "Release",
diff --git a/infra/config/generated/builders/try/android-pie-arm64-rel-inverse-fyi/properties.json b/infra/config/generated/builders/try/android-pie-arm64-rel-inverse-fyi/properties.json index 8f54819..e5384ba 100644 --- a/infra/config/generated/builders/try/android-pie-arm64-rel-inverse-fyi/properties.json +++ b/infra/config/generated/builders/try/android-pie-arm64-rel-inverse-fyi/properties.json
@@ -22,6 +22,7 @@ }, "legacy_chromium_config": { "apply_configs": [ + "download_vr_test_apks", "mb" ], "build_config": "Release",
diff --git a/infra/config/generated/builders/try/android-pie-arm64-rel/properties.json b/infra/config/generated/builders/try/android-pie-arm64-rel/properties.json index 8f54819..e5384ba 100644 --- a/infra/config/generated/builders/try/android-pie-arm64-rel/properties.json +++ b/infra/config/generated/builders/try/android-pie-arm64-rel/properties.json
@@ -22,6 +22,7 @@ }, "legacy_chromium_config": { "apply_configs": [ + "download_vr_test_apks", "mb" ], "build_config": "Release",
diff --git a/infra/config/generated/cq-builders.md b/infra/config/generated/cq-builders.md index 4ee338d0..1b76c693 100644 --- a/infra/config/generated/cq-builders.md +++ b/infra/config/generated/cq-builders.md
@@ -481,7 +481,7 @@ * Experiment percentage: 60.0 * [android-arm64-rel](https://ci.chromium.org/p/chromium/builders/try/android-arm64-rel) ([definition](https://cs.chromium.org/search?q=+file:/try/.*\.star$+""android-arm64-rel"")) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+""android-arm64-rel"")) - * Experiment percentage: 50.0 + * Experiment percentage: 100.0 * [android-pie-arm64-coverage-experimental-rel](https://ci.chromium.org/p/chromium/builders/try/android-pie-arm64-coverage-experimental-rel) ([definition](https://cs.chromium.org/search?q=+file:/try/.*\.star$+""android-pie-arm64-coverage-experimental-rel"")) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+""android-pie-arm64-coverage-experimental-rel"")) * Experiment percentage: 3.0 @@ -501,3 +501,6 @@ * [mac12-arm64-rel](https://ci.chromium.org/p/chromium/builders/try/mac12-arm64-rel) ([definition](https://cs.chromium.org/search?q=+file:/try/.*\.star$+""mac12-arm64-rel"")) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+""mac12-arm64-rel"")) * Experiment percentage: 100.0 +* [win-libfuzzer-asan-rel](https://ci.chromium.org/p/chromium/builders/try/win-libfuzzer-asan-rel) ([definition](https://cs.chromium.org/search?q=+file:/try/.*\.star$+""win-libfuzzer-asan-rel"")) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+""win-libfuzzer-asan-rel"")) + * Experiment percentage: 50.0 +
diff --git a/infra/config/generated/luci/commit-queue.cfg b/infra/config/generated/luci/commit-queue.cfg index 7e2b36c..2f3c271 100644 --- a/infra/config/generated/luci/commit-queue.cfg +++ b/infra/config/generated/luci/commit-queue.cfg
@@ -366,7 +366,7 @@ } builders { name: "chromium/try/android-arm64-rel" - experiment_percentage: 50 + experiment_percentage: 100 location_filters { gerrit_host_regexp: ".*" gerrit_project_regexp: ".*" @@ -3660,7 +3660,24 @@ } builders { name: "chromium/try/win-libfuzzer-asan-rel" - includable_only: true + experiment_percentage: 50 + location_filters { + gerrit_host_regexp: ".*" + gerrit_project_regexp: ".*" + path_regexp: "docs/.+" + exclude: true + } + location_filters { + gerrit_host_regexp: ".*" + gerrit_project_regexp: ".*" + path_regexp: "infra/config/.+" + exclude: true + } + location_filters { + gerrit_host_regexp: ".*" + gerrit_project_regexp: ".*" + path_regexp: "infra/config/generated/builders/try/win-libfuzzer-asan-rel/.+" + } } builders { name: "chromium/try/win-official"
diff --git a/infra/config/subprojects/chromium/ci/chromium.android.star b/infra/config/subprojects/chromium/ci/chromium.android.star index 70cf8cbd8..54e4bd6 100644 --- a/infra/config/subprojects/chromium/ci/chromium.android.star +++ b/infra/config/subprojects/chromium/ci/chromium.android.star
@@ -1151,6 +1151,7 @@ chromium_config = builder_config.chromium_config( config = "android", apply_configs = [ + "download_vr_test_apks", "mb", ], build_config = builder_config.build_config.RELEASE,
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.android.star b/infra/config/subprojects/chromium/try/tryserver.chromium.android.star index 8a88aa6c..3476330 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.android.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.android.star
@@ -95,9 +95,8 @@ try_.orchestrator_builder( name = "android-arm64-rel", mirrors = [ - # TODO(crbug.com/1367393): Enable mirroring pie builder. - #"ci/android-pie-arm64-rel", - "ci/Android Release (Nexus 5X)", + "ci/Android Release (Nexus 5X)", # Nexus 5X on Nougat + #"ci/android-pie-arm64-rel", # Pixel 2 on Pie ], description_html = "This builder may trigger tests on multiple Android versions.", try_settings = builder_config.try_settings( @@ -111,7 +110,7 @@ # branch_selector = branches.STANDARD_MILESTONE, main_list_view = "try", tryjob = try_.job( - experiment_percentage = 50, + experiment_percentage = 100, ), experiments = { "chromium_rts.inverted_rts": 100,
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.win.star b/infra/config/subprojects/chromium/try/tryserver.chromium.win.star index 1ef1b3d..3aca1ee 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.win.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.win.star
@@ -65,7 +65,9 @@ main_list_view = "try", os = os.WINDOWS_ANY, # TODO(crbug.com/1351569): Restore to the CQ when its machines are fixed. - #tryjob = try_.job(), + tryjob = try_.job( + experiment_percentage = 50, + ), goma_backend = None, reclient_jobs = reclient.jobs.HIGH_JOBS_FOR_CQ, )
diff --git a/ios/chrome/app/strings/ios_strings.grd b/ios/chrome/app/strings/ios_strings.grd index 02a5d5779..1bbc835 100644 --- a/ios/chrome/app/strings/ios_strings.grd +++ b/ios/chrome/app/strings/ios_strings.grd
@@ -2666,9 +2666,6 @@ <message name="IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_ENHANCED_PROTECTION_ENABLED_DESC" desc="Detail text for the Safe Browsing check if the user has Safe Browsing Standard Protection enabled"> Enhanced protection is on </message> - <message name="IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_STANDARD_PROTECTION_ENABLED_DESC" desc="Detail text for the Safe Browsing check if the user has Safe Browsing Standard Protection enabled"> - Standard protection is on - </message> <message name="IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_STANDARD_PROTECTION_ENABLED_DESC_WITH_ENHANCED_PROTECTION" desc="Detail text for the Safe Browsing check if the user has Safe Browsing Standard Protection enabled"> Standard protection is on. For even more security, use Enhanced protection. </message>
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_STANDARD_PROTECTION_ENABLED_DESC.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_STANDARD_PROTECTION_ENABLED_DESC.png.sha1 deleted file mode 100644 index 7dbd221..0000000 --- a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_STANDARD_PROTECTION_ENABLED_DESC.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -a9c8761216ac75ff1056afb403c62ab53bd789fd \ No newline at end of file
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index a0a99e3..2026c375 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -962,14 +962,6 @@ {"enable-fullscreen-api", flag_descriptions::kEnableFullscreenAPIName, flag_descriptions::kEnableFullscreenAPIDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(web::features::kEnableFullscreenAPI)}, - {"enable-enhanced-safe-browsing", - flag_descriptions::kEnhancedProtectionName, - flag_descriptions::kEnhancedProtectionDescription, flags_ui::kOsIos, - FEATURE_VALUE_TYPE(safe_browsing::kEnhancedProtection)}, - {"enable-enhanced-safe-browsing-phase-2", - flag_descriptions::kEnhancedProtectionPhase2Name, - flag_descriptions::kEnhancedProtectionPhase2Description, flags_ui::kOsIos, - FEATURE_VALUE_TYPE(safe_browsing::kEnhancedProtectionPhase2IOS)}, {"enable-tailored-security-integration", flag_descriptions::kTailoredSecurityIntegrationName, flag_descriptions::kTailoredSecurityIntegrationDescription, @@ -1322,6 +1314,10 @@ flag_descriptions::kTruncateTableViewCellTitleName, flag_descriptions::kTruncateTableViewCellTitleDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(kTruncateTableViewCellTitle)}, + {"default-browser-blue-dot-promo", + flag_descriptions::kDefaultBrowserBlueDotPromoName, + flag_descriptions::kDefaultBrowserBlueDotPromoDescription, + flags_ui::kOsIos, FEATURE_VALUE_TYPE(kDefaultBrowserBlueDotPromo)}, }; bool SkipConditionalFeatureEntry(const flags_ui::FeatureEntry& entry) {
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc index 84de11fa..50270da 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -195,6 +195,11 @@ "When enabled, Credential Provider Extension promo will be " "presented to eligible users."; +const char kDefaultBrowserBlueDotPromoName[] = "Default Browser Blue Dot Promo"; +const char kDefaultBrowserBlueDotPromoDescription[] = + "When enabled, a blue dot default browser promo will be shown to eligible " + "users."; + const char kDefaultBrowserFullscreenPromoExperimentName[] = "Default Browser Fullscreen modal experiment"; const char kDefaultBrowserFullscreenPromoExperimentDescription[] = @@ -327,15 +332,6 @@ "Enable folowing content from web and display Following feed on NTP based " "on sites that users followed."; -const char kEnhancedProtectionName[] = "Enable Enhanced Safe Browsing"; -const char kEnhancedProtectionDescription[] = - "Allows users to opt-in to Enhanced Safe Browsing"; - -const char kEnhancedProtectionPhase2Name[] = - "Enable Enhanced Safe Browsing Phase 2"; -const char kEnhancedProtectionPhase2Description[] = - "Enable additional improvements related to Enhanced Safe Browsing"; - const char kTailoredSecurityIntegrationName[] = "Enable Tailored Security Integration"; const char kTailoredSecurityIntegrationDescription[] =
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h index 06503020..a20c7d90 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
@@ -166,6 +166,11 @@ extern const char kCredentialProviderExtensionPromoName[]; extern const char kCredentialProviderExtensionPromoDescription[]; +// Title and description for the flag to enable the default browser blue dot +// promo. +extern const char kDefaultBrowserBlueDotPromoName[]; +extern const char kDefaultBrowserBlueDotPromoDescription[]; + // Title and description for the flag to show a modified fullscreen modal promo // with a button that would send the users in the Settings.app to update the // default browser. @@ -206,16 +211,6 @@ extern const char kEditPasswordsInSettingsName[]; extern const char kEditPasswordsInSettingsDescription[]; -// Title and description for the flag to enable kEnhancedProtection flag on -// iOS. -extern const char kEnhancedProtectionName[]; -extern const char kEnhancedProtectionDescription[]; - -// Title and description for the flag to enable kEnhancedProtectionPhase2 -// flag on iOS. -extern const char kEnhancedProtectionPhase2Name[]; -extern const char kEnhancedProtectionPhase2Description[]; - // Title and description for the flag to enable kTailoredSecurityIntegration // flag on iOS. extern const char kTailoredSecurityIntegrationName[];
diff --git a/ios/chrome/browser/ntp/new_tab_page_tab_helper.h b/ios/chrome/browser/ntp/new_tab_page_tab_helper.h index c1fc1a0..59a5dfc 100644 --- a/ios/chrome/browser/ntp/new_tab_page_tab_helper.h +++ b/ios/chrome/browser/ntp/new_tab_page_tab_helper.h
@@ -50,13 +50,6 @@ // WebStateObserver callback. void Deactivate(); - // Sometimes the underlying ios/web page used for the NTP (about://newtab) - // takes a long time to load. Loading any page before the newtab is committed - // will leave ios/web in a bad state. See: crbug.com/925304 for more context. - // Remove this when ios/web supports queueing multiple loads during this - // state. - bool IgnoreLoadRequests() const; - // Returns true if an `url` is either chrome://newtab or about://newtab. bool IsNTPURL(const GURL& url); @@ -109,9 +102,6 @@ // Surface. BOOL show_start_surface_ = false; - // `YES` if the NTP's underlying ios/web page is still loading. - BOOL ignore_load_requests_ = NO; - // The default feed type of the next NTP. FeedType next_ntp_feed_type_;
diff --git a/ios/chrome/browser/ntp/new_tab_page_tab_helper.mm b/ios/chrome/browser/ntp/new_tab_page_tab_helper.mm index 4c2a733..8d6f9b9 100644 --- a/ios/chrome/browser/ntp/new_tab_page_tab_helper.mm +++ b/ios/chrome/browser/ntp/new_tab_page_tab_helper.mm
@@ -82,11 +82,6 @@ SetActive(false); } -bool NewTabPageTabHelper::IgnoreLoadRequests() const { - DCHECK(active_); - return ignore_load_requests_; -} - bool NewTabPageTabHelper::IsNTPURL(const GURL& url) { // `url` can be chrome://newtab/ or about://newtab/ depending on where `url` // comes from (the VisibleURL chrome:// from a navigation item or the actual
diff --git a/ios/chrome/browser/policy/browser_dm_token_storage_ios_unittest.mm b/ios/chrome/browser/policy/browser_dm_token_storage_ios_unittest.mm index 27e7bd9..3ba4d7d6 100644 --- a/ios/chrome/browser/policy/browser_dm_token_storage_ios_unittest.mm +++ b/ios/chrome/browser/policy/browser_dm_token_storage_ios_unittest.mm
@@ -13,7 +13,6 @@ #import "base/path_service.h" #import "base/run_loop.h" #import "base/strings/sys_string_conversions.h" -#import "base/task/task_runner_util.h" #import "base/test/scoped_path_override.h" #import "base/test/task_environment.h" #import "components/policy/core/common/policy_loader_ios_constants.h" @@ -120,9 +119,8 @@ storage_delegate.InitClientId()); auto reply = base::BindOnce(&TestStoreDMTokenDelegate::OnDMTokenUpdated, base::Unretained(&callback_delegate)); - base::PostTaskAndReplyWithResult( - storage_delegate.SaveDMTokenTaskRunner().get(), FROM_HERE, - std::move(task), std::move(reply)); + storage_delegate.SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(task), std::move(reply)); callback_delegate.Wait(); ASSERT_TRUE(callback_delegate.WasCalled()); @@ -173,9 +171,8 @@ auto delete_reply = base::BindOnce(&TestStoreDMTokenDelegate::OnDMTokenUpdated, base::Unretained(&delete_callback_delegate)); - base::PostTaskAndReplyWithResult( - storage_delegate.SaveDMTokenTaskRunner().get(), FROM_HERE, - std::move(delete_task), std::move(delete_reply)); + storage_delegate.SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(delete_task), std::move(delete_reply)); delete_callback_delegate.Wait(); ASSERT_TRUE(delete_callback_delegate.WasCalled()); @@ -209,9 +206,8 @@ auto delete_reply = base::BindOnce(&TestStoreDMTokenDelegate::OnDMTokenUpdated, base::Unretained(&callback_delegate)); - base::PostTaskAndReplyWithResult( - storage_delegate.SaveDMTokenTaskRunner().get(), FROM_HERE, - std::move(delete_task), std::move(delete_reply)); + storage_delegate.SaveDMTokenTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(delete_task), std::move(delete_reply)); callback_delegate.Wait(); ASSERT_TRUE(callback_delegate.WasCalled());
diff --git a/ios/chrome/browser/snapshots/snapshot_cache.mm b/ios/chrome/browser/snapshots/snapshot_cache.mm index 003af0b..a10424a 100644 --- a/ios/chrome/browser/snapshots/snapshot_cache.mm +++ b/ios/chrome/browser/snapshots/snapshot_cache.mm
@@ -23,7 +23,6 @@ #import "base/sequence_checker.h" #import "base/strings/sys_string_conversions.h" #import "base/task/sequenced_task_runner.h" -#import "base/task/task_runner_util.h" #import "base/task/thread_pool.h" #import "base/threading/scoped_blocking_call.h" #import "base/time/time.h" @@ -440,8 +439,8 @@ } __weak SnapshotLRUCache* weakLRUCache = _lruCache; - base::PostTaskAndReplyWithResult( - _taskRunner.get(), FROM_HERE, + _taskRunner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadImageForSnapshotIDFromDisk, snapshotID, IMAGE_TYPE_COLOR, _snapshotsScale, _cacheDirectory), base::BindOnce(^(UIImage* image) { @@ -595,8 +594,8 @@ return; __weak SnapshotCache* weakSelf = self; - base::PostTaskAndReplyWithResult( - _taskRunner.get(), FROM_HERE, + _taskRunner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&GreyImageFromCachedImage, _cacheDirectory, snapshotID, _snapshotsScale, image), base::BindOnce(^(UIImage* greyImage) { @@ -660,8 +659,8 @@ } __weak SnapshotCache* weakSelf = self; - base::PostTaskAndReplyWithResult( - _taskRunner.get(), FROM_HERE, + _taskRunner->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadImageForSnapshotIDFromDisk, snapshotID, IMAGE_TYPE_GREYSCALE, _snapshotsScale, _cacheDirectory), base::BindOnce(^(UIImage* image) {
diff --git a/ios/chrome/browser/ui/bubble/bubble_presenter.mm b/ios/chrome/browser/ui/bubble/bubble_presenter.mm index 30a6a2e..d52c4629b 100644 --- a/ios/chrome/browser/ui/bubble/bubble_presenter.mm +++ b/ios/chrome/browser/ui/bubble/bubble_presenter.mm
@@ -176,7 +176,10 @@ } CGPoint discoverFeedHeaderAnchor = [menuButton.superview convertPoint:menuButton.frame.origin toView:nil]; - discoverFeedHeaderAnchor.x += menuButton.frame.size.width / 2; + // Anchor the IPH 1/3 of the way through the button. Anchoring it midway + // doesn't work since the button is too close to the edge, which would cause + // the bubble to bleed out the screen. + discoverFeedHeaderAnchor.x += menuButton.frame.size.width / 3; // If the feature engagement tracker does not consider it valid to display // the tip, then end early to prevent the potential reassignment of the
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_synchronizing.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_synchronizing.h index 232dcf89..3fe2ddf 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_synchronizing.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_synchronizing.h
@@ -21,9 +21,6 @@ - (void)shiftTilesUpWithAnimations:(ProceduralBlock)animations completion: (void (^)(UIViewAnimatingPosition))completion; -// Notifies the collection that its layout has changed and should be -// invalidated. -- (void)invalidateLayout; @end
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm index 93a8af9..393e8c8 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm
@@ -94,8 +94,6 @@ ContentSuggestionsViewController* contentSuggestionsViewController; @property(nonatomic, strong) ContentSuggestionsMediator* contentSuggestionsMediator; -@property(nonatomic, strong) - ContentSuggestionsHeaderSynchronizer* headerCollectionInteractionHandler; @property(nonatomic, strong) ActionSheetCoordinator* alertCoordinator; @property(nonatomic, assign) BOOL contentSuggestionsEnabled; // Authentication Service for the user's signed-in state.
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm index e6b3165..5f22730 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm
@@ -403,8 +403,6 @@ } - (void)loadVoiceSearch:(id)sender { - if ([self.delegate ignoreLoadRequests]) - return; DCHECK(self.voiceSearchIsEnabled); base::RecordAction(UserMetricsAction("MobileNTPMostVisitedVoiceSearch")); UIView* voiceSearchButton = base::mac::ObjCCastStrict<UIView>(sender); @@ -422,16 +420,12 @@ } - (void)fakeTapViewTapped { - if ([self.delegate ignoreLoadRequests]) - return; base::RecordAction(base::UserMetricsAction("MobileFakeViewNTPTapped")); [self logOmniboxAction]; [self focusFakebox]; } - (void)fakeboxTapped { - if ([self.delegate ignoreLoadRequests]) - return; base::RecordAction(base::UserMetricsAction("MobileFakeboxNTPTapped")); [self logOmniboxAction]; [self focusFakebox]; @@ -448,8 +442,6 @@ } - (void)focusFakebox { - if ([self.delegate ignoreLoadRequests]) - return; [self shiftTilesUp]; }
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller_delegate.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller_delegate.h index 00e0335..c8159998 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller_delegate.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller_delegate.h
@@ -19,12 +19,6 @@ // avatar is changed. - (void)registerImageUpdater:(id<UserAccountImageUpdateDelegate>)imageUpdater; -// Returns whether calls that may trigger a URL load are allowed, such as a -// voice search or focusing the omnibox via the fakebox. -// See: crbug.com/925304 for more context. Remove this when ios/web supports -// queueing multiple loads during this state. -- (BOOL)ignoreLoadRequests; - @end #endif // IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_VIEW_CONTROLLER_DELEGATE_H_
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm index 83e1353..77153da 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm
@@ -319,11 +319,6 @@ - (void)openMostVisitedItem:(NSObject*)item atIndex:(NSInteger)mostVisitedIndex { - NewTabPageTabHelper* NTPHelper = - NewTabPageTabHelper::FromWebState(self.webState); - if (NTPHelper && NTPHelper->IgnoreLoadRequests()) - return; - if ([item isKindOfClass:[ContentSuggestionsMostVisitedActionItem class]]) { [self.NTPMetrics recordContentSuggestionsActionForType: IOSContentSuggestionsActionType::kShortcuts];
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm index 1f89cc4..758797d 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_egtest.mm
@@ -454,6 +454,19 @@ @"Fake omnibox width did not animate properly when scrolling."); } +// Tests that the tap gesture recognizer that dismisses the keyboard and +// defocuses the omnibox works. +- (void)testDefocusOmniboxTapWorks { + [self focusFakebox]; + [[EarlGrey selectElementWithMatcher:chrome_test_util::NTPCollectionView()] + performAction:grey_tap()]; + + [ChromeEarlGreyUI waitForAppToIdle]; + // Check the fake omnibox is displayed again at the same position. + [[EarlGrey selectElementWithMatcher:chrome_test_util::FakeOmnibox()] + assertWithMatcher:grey_sufficientlyVisible()]; +} + // Tests that the app doesn't crash when opening multiple tabs. - (void)testOpenMultipleTabs { NSInteger numberOfTabs = 10;
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm index 3f21ce4..950fe6c 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm
@@ -223,10 +223,6 @@ // Opens web page for a menu item in the NTP. - (void)openMenuItemWebPage:(GURL)URL { - NewTabPageTabHelper* NTPHelper = - NewTabPageTabHelper::FromWebState(self.webState); - if (NTPHelper && NTPHelper->IgnoreLoadRequests()) - return; _URLLoader->Load(UrlLoadParams::InCurrentTab(URL)); // TODO(crbug.com/1085419): Add metrics. } @@ -308,15 +304,6 @@ [self updateAccountImage]; } -- (BOOL)ignoreLoadRequests { - NewTabPageTabHelper* NTPHelper = - NewTabPageTabHelper::FromWebState(self.webState); - if (NTPHelper && NTPHelper->IgnoreLoadRequests()) { - return YES; - } - return NO; -} - #pragma mark - SearchEngineObserving - (void)searchEngineChanged {
diff --git a/ios/chrome/browser/ui/first_run/trending_queries_field_trial.cc b/ios/chrome/browser/ui/first_run/trending_queries_field_trial.cc index ca94446b..14b48a3 100644 --- a/ios/chrome/browser/ui/first_run/trending_queries_field_trial.cc +++ b/ios/chrome/browser/ui/first_run/trending_queries_field_trial.cc
@@ -48,13 +48,13 @@ case version_info::Channel::CANARY: case version_info::Channel::DEV: case version_info::Channel::BETA: - weight_by_id[kTrendingQueriesEnabledModuleEnabledID] = 10; - weight_by_id[kTrendingQueriesEnabledMinimalSpacingModuleEnabledID] = 10; + weight_by_id[kTrendingQueriesEnabledModuleEnabledID] = 20; + weight_by_id[kTrendingQueriesEnabledMinimalSpacingModuleEnabledID] = 20; weight_by_id [kTrendingQueriesEnabledMinimalSpacingRemoveHeaderModuleEnabledID] = - 10; - weight_by_id[kTrendingQueriesKeepShortcutsEnabledModuleEnabledID] = 10; - weight_by_id[kTrendingQueriesControlID] = 10; + 20; + weight_by_id[kTrendingQueriesKeepShortcutsEnabledModuleEnabledID] = 20; + weight_by_id[kTrendingQueriesControlID] = 20; break; case version_info::Channel::STABLE: weight_by_id[kTrendingQueriesEnabledModuleEnabledID] = 8;
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm index 489acd00d..afa6c32 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm
@@ -351,15 +351,6 @@ } - (void)focusOmnibox { - // TODO(crbug.com/931284): Temporary workaround for intermediate broken state - // in the NTP. Remove this once crbug.com/899827 is fixed. - if (self.webState) { - NewTabPageTabHelper* NTPHelper = - NewTabPageTabHelper::FromWebState(self.webState); - if (NTPHelper && NTPHelper->IsActive() && NTPHelper->IgnoreLoadRequests()) { - return; - } - } // Dismiss the edit menu. [[UIMenuController sharedMenuController] hideMenu];
diff --git a/ios/chrome/browser/ui/settings/safety_check/safety_check_mediator.mm b/ios/chrome/browser/ui/settings/safety_check/safety_check_mediator.mm index e69314ea..fce485b 100644 --- a/ios/chrome/browser/ui/settings/safety_check/safety_check_mediator.mm +++ b/ios/chrome/browser/ui/settings/safety_check/safety_check_mediator.mm
@@ -440,9 +440,7 @@ break; case SafeBrowsingCheckRowStateSafe: case SafeBrowsingCheckRowStateUnsafe: // Show Safe Browsing settings. - if (base::FeatureList::IsEnabled( - safe_browsing::kEnhancedProtectionPhase2IOS)) - [self.handler showSafeBrowsingPreferencePage]; + [self.handler showSafeBrowsingPreferencePage]; break; } break; @@ -467,15 +465,9 @@ case CheckStartItemType: return YES; case SafeBrowsingItemType: - if (base::FeatureList::IsEnabled( - safe_browsing::kEnhancedProtectionPhase2IOS)) { - return safe_browsing::GetSafeBrowsingState(*self.userPrefService) == - safe_browsing::SafeBrowsingState::STANDARD_PROTECTION || - self.safeBrowsingCheckRowState == - SafeBrowsingCheckRowStateUnsafe; - } else { - return NO; - } + return safe_browsing::GetSafeBrowsingState(*self.userPrefService) == + safe_browsing::SafeBrowsingState::STANDARD_PROTECTION || + self.safeBrowsingCheckRowState == SafeBrowsingCheckRowStateUnsafe; case HeaderItem: case TimestampFooterItem: return NO; @@ -1217,34 +1209,25 @@ [UIColor colorNamed:kGreenColor]; self.safeBrowsingCheckItem.detailText = [self safeBrowsingCheckItemDetailText]; - if (base::FeatureList::IsEnabled( - safe_browsing::kEnhancedProtectionPhase2IOS)) { - if (safe_browsing::GetSafeBrowsingState(*self.userPrefService) == - safe_browsing::SafeBrowsingState::STANDARD_PROTECTION) { - self.safeBrowsingCheckItem.accessoryType = - UITableViewCellAccessoryDisclosureIndicator; - } + if (safe_browsing::GetSafeBrowsingState(*self.userPrefService) == + safe_browsing::SafeBrowsingState::STANDARD_PROTECTION) { + self.safeBrowsingCheckItem.accessoryType = + UITableViewCellAccessoryDisclosureIndicator; } break; } case SafeBrowsingCheckRowStateUnsafe: { - if (base::FeatureList::IsEnabled( - safe_browsing::kEnhancedProtectionPhase2IOS)) { - UIImage* unSafeIconImage = - UseSymbols() - ? DefaultSymbolTemplateWithPointSize( - kWarningFillSymbol, kTrailingSymbolImagePointSize) - : [[UIImage imageNamed:@"settings_unsafe_state"] - imageWithRenderingMode: - UIImageRenderingModeAlwaysTemplate]; - self.safeBrowsingCheckItem.trailingImage = unSafeIconImage; - self.safeBrowsingCheckItem.trailingImageTintColor = - [UIColor colorNamed:kRedColor]; - self.safeBrowsingCheckItem.accessoryType = - UITableViewCellAccessoryDisclosureIndicator; - } else { - self.safeBrowsingCheckItem.infoButtonHidden = NO; - } + UIImage* unSafeIconImage = + UseSymbols() + ? DefaultSymbolTemplateWithPointSize( + kWarningFillSymbol, kTrailingSymbolImagePointSize) + : [[UIImage imageNamed:@"settings_unsafe_state"] + imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + self.safeBrowsingCheckItem.trailingImage = unSafeIconImage; + self.safeBrowsingCheckItem.trailingImageTintColor = + [UIColor colorNamed:kRedColor]; + self.safeBrowsingCheckItem.accessoryType = + UITableViewCellAccessoryDisclosureIndicator; self.safeBrowsingCheckItem.detailText = GetNSString( IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_DISABLED_DESC); break; @@ -1261,13 +1244,8 @@ safe_browsing::GetSafeBrowsingState(*self.userPrefService); switch (safeBrowsingState) { case safe_browsing::SafeBrowsingState::STANDARD_PROTECTION: - if (base::FeatureList::IsEnabled( - safe_browsing::kEnhancedProtectionPhase2IOS)) { - return GetNSString( - IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_STANDARD_PROTECTION_ENABLED_DESC_WITH_ENHANCED_PROTECTION); - } return GetNSString( - IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_STANDARD_PROTECTION_ENABLED_DESC); + IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_STANDARD_PROTECTION_ENABLED_DESC_WITH_ENHANCED_PROTECTION); case safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION: return GetNSString( IDS_IOS_SETTINGS_SAFETY_CHECK_SAFE_BROWSING_ENHANCED_PROTECTION_ENABLED_DESC);
diff --git a/ios/chrome/browser/ui/toolbar/toolbar_mediator.mm b/ios/chrome/browser/ui/toolbar/toolbar_mediator.mm index 5cfa8b0..284d1954 100644 --- a/ios/chrome/browser/ui/toolbar/toolbar_mediator.mm +++ b/ios/chrome/browser/ui/toolbar/toolbar_mediator.mm
@@ -88,6 +88,7 @@ - (void)disconnect { self.webContentAreaOverlayPresenter = nullptr; + self.navigationBrowserAgent = nullptr; if (_webStateList) { _webStateList->RemoveObserver(_webStateListObserver.get()); @@ -253,6 +254,9 @@ if (self.consumer) { [self.consumer setTabCount:_webStateList->count() addedInBackground:NO]; } + } else { + // Clear the web navigation browser agent if the webStateList is nil. + self.navigationBrowserAgent = nil; } } @@ -299,9 +303,12 @@ (web::WebState*)webState { DCHECK(webState); const id<ToolbarConsumer> consumer = self.consumer; - [consumer - setCanGoForward:self.navigationBrowserAgent->CanGoForward(webState)]; - [consumer setCanGoBack:self.navigationBrowserAgent->CanGoBack(webState)]; + WebNavigationBrowserAgent* navigationBrowserAgent = + self.navigationBrowserAgent; + if (navigationBrowserAgent) { + [consumer setCanGoForward:navigationBrowserAgent->CanGoForward(webState)]; + [consumer setCanGoBack:navigationBrowserAgent->CanGoBack(webState)]; + } } // Updates the Share Menu button of the consumer.
diff --git a/ios/chrome/browser/ui/ui_feature_flags.cc b/ios/chrome/browser/ui/ui_feature_flags.cc index 0fe072d..63c6d8d 100644 --- a/ios/chrome/browser/ui/ui_feature_flags.cc +++ b/ios/chrome/browser/ui/ui_feature_flags.cc
@@ -4,6 +4,21 @@ #include "ios/chrome/browser/ui/ui_feature_flags.h" +BASE_FEATURE(kDefaultBrowserBlueDotPromo, + "DefaultBrowserBlueDotPromo", + base::FEATURE_DISABLED_BY_DEFAULT); + +constexpr base::FeatureParam<BlueDotPromoUserGroup>::Option + kBlueDotPromoUserGroupOptions[] = { + {BlueDotPromoUserGroup::kAllDBPromosDisabled, "all-db-promos-disabled"}, + {BlueDotPromoUserGroup::kOnlyBlueDotPromoEnabled, + "only-blue-dot-promo-enabled"}}; + +constexpr base::FeatureParam<BlueDotPromoUserGroup> kBlueDotPromoUserGroupParam{ + &kDefaultBrowserBlueDotPromo, "user-group", + BlueDotPromoUserGroup::kOnlyBlueDotPromoEnabled, + &kBlueDotPromoUserGroupOptions}; + BASE_FEATURE(kExpandedTabStrip, "ExpandedTabStrip", base::FEATURE_DISABLED_BY_DEFAULT);
diff --git a/ios/chrome/browser/ui/ui_feature_flags.h b/ios/chrome/browser/ui/ui_feature_flags.h index 0c058784..4515d930 100644 --- a/ios/chrome/browser/ui/ui_feature_flags.h +++ b/ios/chrome/browser/ui/ui_feature_flags.h
@@ -7,6 +7,20 @@ #include "Availability.h" #include "base/feature_list.h" +#include "base/metrics/field_trial_params.h" + +// Feature flag to enable default browser blue dot promo. +BASE_DECLARE_FEATURE(kDefaultBrowserBlueDotPromo); + +// Enum for blue dot promo user groups (control/experiment) and its param. The +// reason why we need a custom control group is to disable other independent +// default browser promos, which are already shipped. +enum class BlueDotPromoUserGroup { + kAllDBPromosDisabled, + kOnlyBlueDotPromoEnabled, +}; +extern const base::FeatureParam<BlueDotPromoUserGroup> + kBlueDotPromoUserGroupParam; // Feature to open tab switcher after sliding down the toolbar. BASE_DECLARE_FEATURE(kExpandedTabStrip);
diff --git a/ios/chrome/features.gni b/ios/chrome/features.gni index 70b6b61..afd4a11 100644 --- a/ios/chrome/features.gni +++ b/ios/chrome/features.gni
@@ -11,7 +11,7 @@ # Controls whether Chrome links with Lottie.framework or gets the # implementation from its downstream provider. Ignored if Lottie is # not build as a framework. - ios_chrome_links_with_lottie_framework = false + ios_chrome_links_with_lottie_framework = true # Enable MetricKit in Chrome to collect runtime data. ios_enable_metrickit = false
diff --git a/ios/web/navigation/wk_navigation_util_unittest.mm b/ios/web/navigation/wk_navigation_util_unittest.mm index d5688b0a..d8fc6ce 100644 --- a/ios/web/navigation/wk_navigation_util_unittest.mm +++ b/ios/web/navigation/wk_navigation_util_unittest.mm
@@ -166,14 +166,13 @@ &first_index); // Extract session JSON from restoration URL. auto value_with_error = ExtractSessionDict(restore_session_url); + const base::Value::Dict& dict = value_with_error->GetDict(); - base::Value* urls_value = value_with_error->FindKey("urls"); + const base::Value::List* urls_value = dict.FindList("urls"); if (num_items > kMaxSessionSize) { - ASSERT_EQ(kMaxSessionSize, - static_cast<int>(urls_value->GetListDeprecated().size())); + ASSERT_EQ(kMaxSessionSize, static_cast<int>(urls_value->size())); } else { - ASSERT_EQ(num_items, - static_cast<int>(urls_value->GetListDeprecated().size())); + ASSERT_EQ(num_items, static_cast<int>(urls_value->size())); } } } @@ -197,17 +196,16 @@ // Extract session JSON from restoration URL. auto value_with_error = ExtractSessionDict(restore_session_url); ASSERT_TRUE(value_with_error.has_value()); + const base::Value::Dict& dict = value_with_error->GetDict(); // Verify that all titles and URLs are present. - base::Value* titles_value = value_with_error->FindKey("titles"); + const base::Value::List* titles_value = dict.FindList("titles"); ASSERT_TRUE(titles_value); - ASSERT_TRUE(titles_value->is_list()); - ASSERT_EQ(kItemCount, titles_value->GetListDeprecated().size()); + ASSERT_EQ(kItemCount, titles_value->size()); - base::Value* urls_value = value_with_error->FindKey("urls"); + const base::Value::List* urls_value = dict.FindList("urls"); ASSERT_TRUE(urls_value); - ASSERT_TRUE(urls_value->is_list()); - ASSERT_EQ(kItemCount, urls_value->GetListDeprecated().size()); + ASSERT_EQ(kItemCount, urls_value->size()); } // Verifies that large session can be stored in NSURL and that extra items @@ -230,29 +228,24 @@ // Extract session JSON from restoration URL. auto value_with_error = ExtractSessionDict(restore_session_url); ASSERT_TRUE(value_with_error.has_value()); + const base::Value::Dict& dict = value_with_error->GetDict(); // Verify that first kMaxSessionSize titles and URLs are present. - base::Value* titles_value = value_with_error->FindKey("titles"); + const base::Value::List* titles_value = dict.FindList("titles"); ASSERT_TRUE(titles_value); - ASSERT_TRUE(titles_value->is_list()); - ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), - titles_value->GetListDeprecated().size()); - ASSERT_EQ("Test0", titles_value->GetListDeprecated()[0].GetString()); - ASSERT_EQ("Test74", - titles_value->GetListDeprecated()[kMaxSessionSize - 1].GetString()); + ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), titles_value->size()); + ASSERT_EQ("Test0", (*titles_value)[0].GetString()); + ASSERT_EQ("Test74", (*titles_value)[kMaxSessionSize - 1].GetString()); - base::Value* urls_value = value_with_error->FindKey("urls"); + const base::Value::List* urls_value = dict.FindList("urls"); ASSERT_TRUE(urls_value); - ASSERT_TRUE(urls_value->is_list()); - ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), - urls_value->GetListDeprecated().size()); - ASSERT_EQ("http://www.0.com/", - urls_value->GetListDeprecated()[0].GetString()); + ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), urls_value->size()); + ASSERT_EQ("http://www.0.com/", (*urls_value)[0].GetString()); ASSERT_EQ("http://www.74.com/", - urls_value->GetListDeprecated()[kMaxSessionSize - 1].GetString()); + (*urls_value)[kMaxSessionSize - 1].GetString()); // Verify the offset is correct. - ASSERT_EQ(1 - kMaxSessionSize, value_with_error->FindKey("offset")->GetInt()); + ASSERT_EQ(1 - kMaxSessionSize, *dict.FindInt("offset")); } // Verifies that large session can be stored in NSURL and that extra items @@ -275,29 +268,24 @@ // Extract session JSON from restoration URL. auto value_with_error = ExtractSessionDict(restore_session_url); ASSERT_TRUE(value_with_error.has_value()); + const base::Value::Dict& dict = value_with_error->GetDict(); // Verify that last kMaxSessionSize titles and URLs are present. - base::Value* titles_value = value_with_error->FindKey("titles"); + const base::Value::List* titles_value = dict.FindList("titles"); ASSERT_TRUE(titles_value); - ASSERT_TRUE(titles_value->is_list()); - ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), - titles_value->GetListDeprecated().size()); - ASSERT_EQ("Test150", titles_value->GetListDeprecated()[0].GetString()); - ASSERT_EQ("Test224", - titles_value->GetListDeprecated()[kMaxSessionSize - 1].GetString()); + ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), titles_value->size()); + ASSERT_EQ("Test150", (*titles_value)[0].GetString()); + ASSERT_EQ("Test224", (*titles_value)[kMaxSessionSize - 1].GetString()); - base::Value* urls_value = value_with_error->FindKey("urls"); + const base::Value::List* urls_value = dict.FindList("urls"); ASSERT_TRUE(urls_value); - ASSERT_TRUE(urls_value->is_list()); - ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), - urls_value->GetListDeprecated().size()); - ASSERT_EQ("http://www.150.com/", - urls_value->GetListDeprecated()[0].GetString()); + ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), urls_value->size()); + ASSERT_EQ("http://www.150.com/", (*urls_value)[0].GetString()); ASSERT_EQ("http://www.224.com/", - urls_value->GetListDeprecated()[kMaxSessionSize - 1].GetString()); + (*urls_value)[kMaxSessionSize - 1].GetString()); // Verify the offset is correct. - ASSERT_EQ(0, value_with_error->FindKey("offset")->GetInt()); + ASSERT_EQ(0, *dict.FindInt("offset")); } // Verifies that large session can be stored in NSURL and that extra items @@ -321,30 +309,24 @@ // Extract session JSON from restoration URL. auto value_with_error = ExtractSessionDict(restore_session_url); ASSERT_TRUE(value_with_error.has_value()); + const base::Value::Dict& dict = value_with_error->GetDict(); // Verify that last kMaxSessionSize titles and URLs are present. - base::Value* titles_value = value_with_error->FindKey("titles"); + const base::Value::List* titles_value = dict.FindList("titles"); ASSERT_TRUE(titles_value); - ASSERT_TRUE(titles_value->is_list()); - ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), - titles_value->GetListDeprecated().size()); - ASSERT_EQ("Test38", titles_value->GetListDeprecated()[0].GetString()); - ASSERT_EQ("Test112", - titles_value->GetListDeprecated()[kMaxSessionSize - 1].GetString()); + ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), titles_value->size()); + ASSERT_EQ("Test38", (*titles_value)[0].GetString()); + ASSERT_EQ("Test112", (*titles_value)[kMaxSessionSize - 1].GetString()); - base::Value* urls_value = value_with_error->FindKey("urls"); + const base::Value::List* urls_value = dict.FindList("urls"); ASSERT_TRUE(urls_value); - ASSERT_TRUE(urls_value->is_list()); - ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), - urls_value->GetListDeprecated().size()); - ASSERT_EQ("http://www.38.com/", - urls_value->GetListDeprecated()[0].GetString()); + ASSERT_EQ(static_cast<size_t>(kMaxSessionSize), urls_value->size()); + ASSERT_EQ("http://www.38.com/", (*urls_value)[0].GetString()); ASSERT_EQ("http://www.112.com/", - urls_value->GetListDeprecated()[kMaxSessionSize - 1].GetString()); + (*urls_value)[kMaxSessionSize - 1].GetString()); // Verify the offset is correct. - ASSERT_EQ((1 - kMaxSessionSize) / 2, - value_with_error->FindKey("offset")->GetInt()); + ASSERT_EQ((1 - kMaxSessionSize) / 2, *dict.FindInt("offset")); } TEST_F(WKNavigationUtilTest, IsNotRestoreSessionUrl) {
diff --git a/ipc/ipc_mojo_bootstrap.cc b/ipc/ipc_mojo_bootstrap.cc index 2f96b3a..d34be4e43 100644 --- a/ipc/ipc_mojo_bootstrap.cc +++ b/ipc/ipc_mojo_bootstrap.cc
@@ -884,13 +884,17 @@ client->NotifyError(reason); } else { endpoint->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&ChannelAssociatedGroupController:: - NotifyEndpointOfErrorOnEndpointThread, - this, endpoint->id(), - base::UnsafeDanglingUntriaged(endpoint))); + FROM_HERE, + base::BindOnce(&ChannelAssociatedGroupController:: + NotifyEndpointOfErrorOnEndpointThread, + this, endpoint->id(), + // This is safe as `endpoint` is verified to be in + // `endpoints_` (a map with ownership) before use. + base::UnsafeDangling(endpoint))); } } + // `endpoint` might be a dangling ptr and must be checked before dereference. void NotifyEndpointOfErrorOnEndpointThread(mojo::InterfaceId id, Endpoint* endpoint) { base::AutoLock locker(lock_);
diff --git a/media/filters/decoder_selector.cc b/media/filters/decoder_selector.cc index 85dc67d5..e83a9a3 100644 --- a/media/filters/decoder_selector.cc +++ b/media/filters/decoder_selector.cc
@@ -349,10 +349,11 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!status.is_ok()) { - // Note: Don't track this decode status, as it is the result of - // initialization failure. + // Note: Don't track this decode status, as it is the result of decoder + // selection (initialization) failure. MEDIA_LOG(INFO, media_log_) - << "Failed to initialize " << decoder_->GetDecoderType(); + << "Cannot select " << decoder_->GetDecoderType() << " for " + << DemuxerStream::GetTypeName(StreamType) << " decoding"; // Try the next decoder on the list. decoder_ = nullptr;
diff --git a/media/filters/ffmpeg_demuxer.cc b/media/filters/ffmpeg_demuxer.cc index b90cd29..0986f9b 100644 --- a/media/filters/ffmpeg_demuxer.cc +++ b/media/filters/ffmpeg_demuxer.cc
@@ -21,7 +21,6 @@ #include "base/strings/string_util.h" #include "base/sys_byteorder.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" @@ -966,8 +965,8 @@ format_context->max_analyze_duration = 60 * AV_TIME_BASE; // Open the AVFormatContext using our glue layer. - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FFmpegGlue::OpenContext, base::Unretained(glue_.get()), is_local_file_), base::BindOnce(&FFmpegDemuxer::OnOpenContextDone, @@ -1246,8 +1245,8 @@ } // Fully initialize AVFormatContext by parsing the stream a little. - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&avformat_find_stream_info, glue_->format_context(), static_cast<AVDictionary**>(nullptr)), base::BindOnce(&FFmpegDemuxer::OnFindStreamInfoDone, @@ -1771,8 +1770,8 @@ AVPacket* packet_ptr = packet.get(); pending_read_ = true; - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadFrameAndDiscardEmpty, glue_->format_context(), packet_ptr), base::BindOnce(&FFmpegDemuxer::OnReadFrameDone,
diff --git a/media/formats/mp4/hevc.cc b/media/formats/mp4/hevc.cc index 2e17c26..09b2a3f 100644 --- a/media/formats/mp4/hevc.cc +++ b/media/formats/mp4/hevc.cc
@@ -250,30 +250,11 @@ } switch (sei_msg.type) { case H265SEIMessage::kSEIContentLightLevelInfo: - hdr_metadata.max_content_light_level = - sei_msg.content_light_level_info.max_content_light_level; - hdr_metadata.max_frame_average_light_level = - sei_msg.content_light_level_info - .max_picture_average_light_level; + sei_msg.content_light_level_info.PopulateHDRMetadata(hdr_metadata); break; case H265SEIMessage::kSEIMasteringDisplayInfo: { - constexpr auto kChromaDenominator = 50000.0f; - constexpr auto kLumaDenoninator = 10000.0f; - const auto& mdi = sei_msg.mastering_display_info; - // display primaries are in G/B/R order in MDCV SEI. - hdr_metadata.color_volume_metadata.primaries = { - mdi.display_primaries[2][0] / kChromaDenominator, - mdi.display_primaries[2][1] / kChromaDenominator, - mdi.display_primaries[0][0] / kChromaDenominator, - mdi.display_primaries[0][1] / kChromaDenominator, - mdi.display_primaries[1][0] / kChromaDenominator, - mdi.display_primaries[1][1] / kChromaDenominator, - mdi.white_points[0] / kChromaDenominator, - mdi.white_points[1] / kChromaDenominator}; - hdr_metadata.color_volume_metadata.luminance_max = - mdi.max_luminance / kLumaDenoninator; - hdr_metadata.color_volume_metadata.luminance_min = - mdi.min_luminance / kLumaDenoninator; + sei_msg.mastering_display_info.PopulateColorVolumeMetadata( + hdr_metadata.color_volume_metadata); break; } case H265SEIMessage::kSEIAlphaChannelInfo:
diff --git a/media/gpu/android/codec_allocator.cc b/media/gpu/android/codec_allocator.cc index 07d4477..a09f4ac 100644 --- a/media/gpu/android/codec_allocator.cc +++ b/media/gpu/android/codec_allocator.cc
@@ -12,7 +12,6 @@ #include "base/logging.h" #include "base/no_destructor.h" #include "base/ranges/algorithm.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" @@ -114,12 +113,14 @@ // Post creation to the task runner. This may hang on broken platforms; if it // hangs, we will detect it on the next creation request, and future creations // will fallback to software. - base::PostTaskAndReplyWithResult( - std::move(task_runner), FROM_HERE, - base::BindOnce(&CreateMediaCodecInternal, factory_cb_, - std::move(codec_config)), - base::BindOnce(&CodecAllocator::OnCodecCreated, base::Unretained(this), - start_time, std::move(codec_created_cb))); + std::move(task_runner) + ->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce(&CreateMediaCodecInternal, factory_cb_, + std::move(codec_config)), + base::BindOnce(&CodecAllocator::OnCodecCreated, + base::Unretained(this), start_time, + std::move(codec_created_cb))); } void CodecAllocator::ReleaseMediaCodec(std::unique_ptr<MediaCodecBridge> codec,
diff --git a/media/gpu/chromeos/platform_video_frame_utils.cc b/media/gpu/chromeos/platform_video_frame_utils.cc index 602d88b..4e68e75 100644 --- a/media/gpu/chromeos/platform_video_frame_utils.cc +++ b/media/gpu/chromeos/platform_video_frame_utils.cc
@@ -34,6 +34,7 @@ #include "ui/gfx/gpu_memory_buffer.h" #include "ui/gfx/linux/drm_util_linux.h" #include "ui/gfx/linux/gbm_buffer.h" +#include "ui/gfx/linux/gbm_defines.h" #include "ui/gfx/linux/gbm_device.h" #include "ui/gfx/linux/gbm_util.h" #include "ui/gfx/linux/gbm_wrapper.h" @@ -94,6 +95,7 @@ gfx::BufferFormat format, const gfx::Size& size, gfx::NativePixmapHandle handle) { + CHECK_LE(handle.planes.size(), base::checked_cast<size_t>(GBM_MAX_PLANES)); base::AutoLock lock(lock_); if (!gbm_device_) return nullptr;
diff --git a/media/gpu/ipc/service/vda_video_decoder.cc b/media/gpu/ipc/service/vda_video_decoder.cc index 7363323..7663cf3e 100644 --- a/media/gpu/ipc/service/vda_video_decoder.cc +++ b/media/gpu/ipc/service/vda_video_decoder.cc
@@ -705,7 +705,8 @@ EnterErrorState(); return; } - frame->set_hdr_metadata(config_.hdr_metadata()); + frame->set_hdr_metadata(picture.hdr_metadata() ? picture.hdr_metadata() + : config_.hdr_metadata()); output_cb_.Run(std::move(frame)); }
diff --git a/media/gpu/mac/vt_video_decode_accelerator_mac.cc b/media/gpu/mac/vt_video_decode_accelerator_mac.cc index d54cc5c..d28a7c2 100644 --- a/media/gpu/mac/vt_video_decode_accelerator_mac.cc +++ b/media/gpu/mac/vt_video_decode_accelerator_mac.cc
@@ -1431,10 +1431,28 @@ case H265NALU::PREFIX_SEI_NUT: { H265SEIMessage sei_msg; result = hevc_parser_.ParseSEI(&sei_msg); - if (result == H265Parser::kOk && - sei_msg.type == H265SEIMessage::kSEIAlphaChannelInfo && - sei_msg.alpha_channel_info.alpha_channel_cancel_flag == 0) { - has_alpha_ = true; + if (result == H265Parser::kOk) { + switch (sei_msg.type) { + case H265SEIMessage::kSEIAlphaChannelInfo: + if (sei_msg.alpha_channel_info.alpha_channel_cancel_flag == 0) + has_alpha_ = true; + break; + case H265SEIMessage::kSEIMasteringDisplayInfo: + if (!config_.hdr_metadata) + config_.hdr_metadata = gfx::HDRMetadata(); + sei_msg.mastering_display_info.PopulateColorVolumeMetadata( + config_.hdr_metadata->color_volume_metadata); + break; + case H265SEIMessage::kSEIContentLightLevelInfo: { + if (!config_.hdr_metadata) + config_.hdr_metadata = gfx::HDRMetadata(); + sei_msg.content_light_level_info.PopulateHDRMetadata( + config_.hdr_metadata.value()); + break; + } + default: + break; + } } nalus.push_back(nalu); data_size += kNALUHeaderLength + nalu.size; @@ -1562,6 +1580,7 @@ if (frame->is_idr) waiting_for_idr_ = false; + frame->hdr_metadata = config_.hdr_metadata; // If no IDR has been seen yet, skip decoding. Note that Flash sends // configuration changes as a bitstream with only SPS/PPS/VPS; we don't print @@ -2283,6 +2302,8 @@ // we don't need to use them when the image is never bound? Bindings are // typically only created when WebGL is in use. picture.set_read_lock_fences_enabled(true); + if (frame.hdr_metadata) + picture.set_hdr_metadata(frame.hdr_metadata); if (picture_info->uses_shared_images) { for (size_t plane = 0; plane < planes.size(); ++plane) { picture.set_scoped_shared_image(picture_info->scoped_shared_images[plane],
diff --git a/media/gpu/mac/vt_video_decode_accelerator_mac.h b/media/gpu/mac/vt_video_decode_accelerator_mac.h index acc29e70..8d58117 100644 --- a/media/gpu/mac/vt_video_decode_accelerator_mac.h +++ b/media/gpu/mac/vt_video_decode_accelerator_mac.h
@@ -138,6 +138,9 @@ // Decoded image, if decoding was successful. base::ScopedCFTypeRef<CVImageBufferRef> image; + + // Dynamic HDR metadata, if any. + absl::optional<gfx::HDRMetadata> hdr_metadata; }; struct Task {
diff --git a/media/video/h265_parser.cc b/media/video/h265_parser.cc index db9fc1b1c..67f97c7 100644 --- a/media/video/h265_parser.cc +++ b/media/video/h265_parser.cc
@@ -18,6 +18,7 @@ #include "media/base/video_codecs.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" +#include "ui/gfx/hdr_metadata.h" namespace media { @@ -1316,6 +1317,30 @@ } } +void H265SEIContentLightLevelInfo::PopulateHDRMetadata( + gfx::HDRMetadata& hdr_metadata) const { + hdr_metadata.max_content_light_level = max_content_light_level; + hdr_metadata.max_frame_average_light_level = max_picture_average_light_level; +} + +void H265SEIMasteringDisplayInfo::PopulateColorVolumeMetadata( + gfx::ColorVolumeMetadata& color_volume_metadata) const { + constexpr auto kChromaDenominator = 50000.0f; + constexpr auto kLumaDenoninator = 10000.0f; + // display primaries are in G/B/R order in MDCV SEI. + color_volume_metadata.primaries = { + display_primaries[2][0] / kChromaDenominator, + display_primaries[2][1] / kChromaDenominator, + display_primaries[0][0] / kChromaDenominator, + display_primaries[0][1] / kChromaDenominator, + display_primaries[1][0] / kChromaDenominator, + display_primaries[1][1] / kChromaDenominator, + white_points[0] / kChromaDenominator, + white_points[1] / kChromaDenominator}; + color_volume_metadata.luminance_max = max_luminance / kLumaDenoninator; + color_volume_metadata.luminance_min = min_luminance / kLumaDenoninator; +} + H265Parser::Result H265Parser::ParseProfileTierLevel( bool profile_present, int max_num_sub_layers_minus1,
diff --git a/media/video/h265_parser.h b/media/video/h265_parser.h index 7f6540e..c1ef3372a 100644 --- a/media/video/h265_parser.h +++ b/media/video/h265_parser.h
@@ -21,6 +21,11 @@ #include "media/video/h264_parser.h" #include "media/video/h265_nalu_parser.h" +namespace gfx { +struct HDRMetadata; +struct ColorVolumeMetadata; +} // namespace gfx + namespace media { // For explanations of each struct and its members, see H.265 specification @@ -429,6 +434,8 @@ struct MEDIA_EXPORT H265SEIContentLightLevelInfo { uint16_t max_content_light_level; uint16_t max_picture_average_light_level; + + void PopulateHDRMetadata(gfx::HDRMetadata& hdr_metadata) const; }; struct MEDIA_EXPORT H265SEIMasteringDisplayInfo { @@ -441,6 +448,9 @@ uint16_t white_points[2]; uint32_t max_luminance; uint32_t min_luminance; + + void PopulateColorVolumeMetadata( + gfx::ColorVolumeMetadata& color_volume_metadata) const; }; struct MEDIA_EXPORT H265SEIMessage {
diff --git a/media/video/picture.h b/media/video/picture.h index ef3c23d..3e20a7e 100644 --- a/media/video/picture.h +++ b/media/video/picture.h
@@ -128,6 +128,13 @@ // Returns the color space of the picture. const gfx::ColorSpace& color_space() const { return color_space_; } + const absl::optional<gfx::HDRMetadata>& hdr_metadata() const { + return hdr_metadata_; + } + + void set_hdr_metadata(const absl::optional<gfx::HDRMetadata>& hdr_metadata) { + hdr_metadata_ = hdr_metadata; + } // Returns the visible rectangle of the picture. Its size may be smaller // than the size of the PictureBuffer, as it is the only visible part of the @@ -184,6 +191,7 @@ int32_t bitstream_buffer_id_; gfx::Rect visible_rect_; gfx::ColorSpace color_space_; + absl::optional<gfx::HDRMetadata> hdr_metadata_; bool allow_overlay_; bool read_lock_fences_enabled_; bool size_changed_;
diff --git a/media/webrtc/audio_processor_test.cc b/media/webrtc/audio_processor_test.cc index 9f470f5..6ba31d3 100644 --- a/media/webrtc/audio_processor_test.cc +++ b/media/webrtc/audio_processor_test.cc
@@ -438,7 +438,7 @@ } }; -INSTANTIATE_TEST_CASE_P( +INSTANTIATE_TEST_SUITE_P( /*no prefix*/, AudioProcessorDefaultOutputFormatTest, ::testing::Combine(::testing::Bool(),
diff --git a/mojo/core/core_ipcz.cc b/mojo/core/core_ipcz.cc index 1c3888a..751de163 100644 --- a/mojo/core/core_ipcz.cc +++ b/mojo/core/core_ipcz.cc
@@ -129,7 +129,7 @@ auto* data_pipe = ipcz_driver::DataPipe::FromBox(handle); if (data_pipe) { - *signals_state = data_pipe->Flush(); + *signals_state = data_pipe->GetSignals(); return MOJO_RESULT_OK; }
diff --git a/mojo/core/ipcz_driver/data_pipe.cc b/mojo/core/ipcz_driver/data_pipe.cc index 94c4157..06eaced 100644 --- a/mojo/core/ipcz_driver/data_pipe.cc +++ b/mojo/core/ipcz_driver/data_pipe.cc
@@ -47,6 +47,13 @@ // Attempts to put a single (32-bit) integer into the given `portal`. Returns // true if successful, or false to indicate that the peer portal is closed. bool SendPeerUpdate(IpczHandle portal, size_t num_bytes) { + if (num_bytes == 0) { + // Do not send messages for empty reads or writes. This ensures that + // endpoints can reliably infer new (non-zero) data or capacity by the mere + // presence of one or more unread parcels. + return true; + } + const uint32_t num_bytes_checked = base::checked_cast<uint32_t>(num_bytes); const IpczResult result = GetIpczAPI().Put(portal, &num_bytes_checked, sizeof(num_bytes_checked), @@ -104,6 +111,10 @@ continue; } + case IPCZ_RESULT_ALREADY_EXISTS: + // Unlikely: we raced with a flush on another thread. Try again. + continue; + default: // Unexpected behavior. Treat as if closed. return {.num_bytes_changed = 0, .dead = true}; @@ -214,6 +225,7 @@ return MOJO_RESULT_INVALID_ARGUMENT; } + FlushUpdatesFromPeer(); const base::span<const uint8_t> input_bytes = base::make_span(static_cast<const uint8_t*>(elements), num_bytes); scoped_refptr<PortalWrapper> portal; @@ -230,7 +242,6 @@ return MOJO_RESULT_FAILED_PRECONDITION; } - FlushUpdatesFromPeer(); if (flags & MOJO_WRITE_DATA_FLAG_ALL_OR_NONE) { if (!data_.WriteAll(input_bytes)) { return input_bytes.empty() ? MOJO_RESULT_SHOULD_WAIT @@ -257,6 +268,7 @@ MojoResult DataPipe::BeginWriteData(void*& data, uint32_t& num_bytes, MojoBeginWriteDataFlags flags) { + FlushUpdatesFromPeer(); base::AutoLock lock(lock_); if (two_phase_writer_) { return MOJO_RESULT_BUSY; @@ -265,7 +277,6 @@ return MOJO_RESULT_FAILED_PRECONDITION; } - FlushUpdatesFromPeer(); RingBuffer::DirectWriter writer(data_); if (writer.bytes().empty()) { return MOJO_RESULT_SHOULD_WAIT; @@ -327,13 +338,13 @@ return MOJO_RESULT_INVALID_ARGUMENT; } + FlushUpdatesFromPeer(); const base::span<uint8_t> output_bytes = base::make_span(static_cast<uint8_t*>(elements), num_bytes); size_t read_size = num_bytes; scoped_refptr<PortalWrapper> portal; { base::AutoLock lock(lock_); - FlushUpdatesFromPeer(); const size_t data_size = data_.data_size(); if (query) { num_bytes = base::checked_cast<uint32_t>(data_size); @@ -388,6 +399,7 @@ MojoResult DataPipe::BeginReadData(const void*& buffer, uint32_t& buffer_num_bytes) { + FlushUpdatesFromPeer(); base::AutoLock lock(lock_); if (two_phase_reader_) { return MOJO_RESULT_BUSY; @@ -397,7 +409,6 @@ return IPCZ_RESULT_INVALID_ARGUMENT; } - FlushUpdatesFromPeer(); RingBuffer::DirectReader reader(data_); if (reader.bytes().empty()) { return is_peer_closed_ ? MOJO_RESULT_FAILED_PRECONDITION @@ -539,14 +550,24 @@ return endpoint; } -MojoHandleSignalsState DataPipe::Flush() { +MojoHandleSignalsState DataPipe::GetSignals() { MojoHandleSignalsState signals_state = {}; MojoHandleSignals& satisfied = signals_state.satisfied_signals; MojoHandleSignals& satisfiable = signals_state.satisfiable_signals; base::AutoLock lock(lock_); - FlushUpdatesFromPeer(); - satisfiable |= MOJO_HANDLE_SIGNAL_PEER_CLOSED; + IpczPortalStatus status = {.size = sizeof(status)}; + const IpczResult result = GetIpczAPI().QueryPortalStatus( + portal_->handle(), IPCZ_NO_FLAGS, nullptr, &status); + if (result != IPCZ_RESULT_OK) { + return signals_state; + } + + if ((status.flags & IPCZ_PORTAL_STATUS_DEAD) != 0) { + is_peer_closed_ = true; + } + + satisfiable = MOJO_HANDLE_SIGNAL_PEER_CLOSED; if (is_peer_closed_) { satisfied |= MOJO_HANDLE_SIGNAL_PEER_CLOSED; } else { @@ -554,21 +575,32 @@ } if (is_consumer()) { + const bool new_data_available = + has_new_data_ || status.num_local_parcels > 0; + if (new_data_available) { + has_new_data_ = true; + satisfied |= MOJO_HANDLE_SIGNAL_NEW_DATA_READABLE; + satisfiable |= MOJO_HANDLE_SIGNAL_NEW_DATA_READABLE; + } + + const bool any_data_available = new_data_available || data_.data_size() > 0; + if (any_data_available) { + satisfiable |= MOJO_HANDLE_SIGNAL_READABLE; + satisfied |= MOJO_HANDLE_SIGNAL_READABLE; + } + if (!is_peer_closed_) { satisfiable |= MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_NEW_DATA_READABLE; } - if (data_.data_size() > 0) { - satisfiable |= - MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_NEW_DATA_READABLE; - satisfied |= MOJO_HANDLE_SIGNAL_READABLE; - if (has_new_data_) { - satisfied |= MOJO_HANDLE_SIGNAL_NEW_DATA_READABLE; - } - } - } else if (!is_peer_closed_) { + + return signals_state; + } + + DCHECK(is_producer()); + if (!is_peer_closed_) { satisfiable |= MOJO_HANDLE_SIGNAL_WRITABLE; - if (data_.available_capacity() > 0) { + if (data_.available_capacity() > 0 || status.num_local_parcels > 0) { satisfied |= MOJO_HANDLE_SIGNAL_WRITABLE; } } @@ -577,15 +609,20 @@ } void DataPipe::FlushUpdatesFromPeer() { - lock_.AssertAcquired(); - DCHECK(portal_); - if (in_transit_) { - // Once an endpoint has begun serialization we must not read its portal, - // lest we potentially lose updates. - return; + scoped_refptr<PortalWrapper> portal; + { + base::AutoLock lock(lock_); + if (!portal_ || in_transit_) { + // Once an endpoint has begun serialization we must not read its portal, + // lest we potentially lose updates. + return; + } + portal = portal_; } - DrainResult result = DrainPeerUpdates(portal_->handle()); + DrainResult result = DrainPeerUpdates(portal->handle()); + + base::AutoLock lock(lock_); if (result.dead) { is_peer_closed_ = true; }
diff --git a/mojo/core/ipcz_driver/data_pipe.h b/mojo/core/ipcz_driver/data_pipe.h index 64dcb820..237cbae 100644 --- a/mojo/core/ipcz_driver/data_pipe.h +++ b/mojo/core/ipcz_driver/data_pipe.h
@@ -149,14 +149,14 @@ base::span<const uint8_t> data, base::span<PlatformHandle> handles); - // Flushes any incoming control messages and returns a MojoSignalsState to - // reflect the current state of the DataPipe. - MojoHandleSignalsState Flush(); + // Returns Mojo signals to reflect the effective state of this DataPipe and + // its control portal. + MojoHandleSignalsState GetSignals(); private: ~DataPipe() override; - void FlushUpdatesFromPeer() EXCLUSIVE_LOCKS_REQUIRED(lock_); + void FlushUpdatesFromPeer() LOCKS_EXCLUDED(lock_); bool DeserializeRingBuffer(const RingBuffer::SerializedState& state); const EndpointType endpoint_type_;
diff --git a/mojo/core/ipcz_driver/mojo_trap.cc b/mojo/core/ipcz_driver/mojo_trap.cc index 9e584a0..af4456ce 100644 --- a/mojo/core/ipcz_driver/mojo_trap.cc +++ b/mojo/core/ipcz_driver/mojo_trap.cc
@@ -42,14 +42,15 @@ // Translates Mojo signal conditions to equivalent IpczTrapConditions for any // portal used as a data pipe endpoint. Watching data pipes for readability or -// writability is equivalent to watching their control portal for new incoming +// writability is equivalent to watching their control portal for inbound // parcels, since each transaction from the peer elicits such a parcel. void GetConditionsForDataPipeSignals(MojoHandleSignals signals, IpczTrapConditions* conditions) { conditions->flags |= IPCZ_TRAP_DEAD; if (signals & (MOJO_HANDLE_SIGNAL_WRITABLE | MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_NEW_DATA_READABLE)) { - conditions->flags |= IPCZ_TRAP_NEW_LOCAL_PARCEL; + conditions->flags |= IPCZ_TRAP_ABOVE_MIN_LOCAL_PARCELS; + conditions->min_local_parcels = 0; } if (signals & MOJO_HANDLE_SIGNAL_PEER_CLOSED) { conditions->flags |= IPCZ_TRAP_PEER_CLOSED; @@ -85,7 +86,7 @@ bool PopulateEventForDataPipe(DataPipe& pipe, MojoHandleSignals trigger_signals, MojoTrapEvent& event) { - event.signals_state = pipe.Flush(); + event.signals_state = pipe.GetSignals(); return GetEventResultForSignalsState(event.signals_state, trigger_signals, event.result); }
diff --git a/net/base/file_stream_context.cc b/net/base/file_stream_context.cc index 1b092d9..4b883ff 100644 --- a/net/base/file_stream_context.cc +++ b/net/base/file_stream_context.cc
@@ -11,7 +11,6 @@ #include "base/location.h" #include "base/logging.h" #include "base/task/task_runner.h" -#include "base/task/task_runner_util.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" #include "build/build_config.h" @@ -86,8 +85,8 @@ CompletionOnceCallback callback) { DCHECK(!async_in_progress_); - bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + bool posted = task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Context::OpenFileImpl, base::Unretained(this), path, open_flags), base::BindOnce(&Context::OnOpenCompleted, base::Unretained(this), @@ -100,8 +99,8 @@ void FileStream::Context::Close(CompletionOnceCallback callback) { DCHECK(!async_in_progress_); - bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + bool posted = task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Context::CloseFileImpl, base::Unretained(this)), base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), IntToInt64(std::move(callback)))); @@ -119,8 +118,8 @@ return; } - bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + bool posted = task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Context::SeekFileImpl, base::Unretained(this), offset), base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), std::move(callback))); @@ -131,8 +130,8 @@ void FileStream::Context::GetFileInfo(base::File::Info* file_info, CompletionOnceCallback callback) { - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Context::GetFileInfoImpl, base::Unretained(this), base::Unretained(file_info)), base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), @@ -144,8 +143,8 @@ void FileStream::Context::Flush(CompletionOnceCallback callback) { DCHECK(!async_in_progress_); - bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + bool posted = task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Context::FlushFileImpl, base::Unretained(this)), base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), IntToInt64(std::move(callback))));
diff --git a/net/base/file_stream_context_posix.cc b/net/base/file_stream_context_posix.cc index 3a48653b..235fc343 100644 --- a/net/base/file_stream_context_posix.cc +++ b/net/base/file_stream_context_posix.cc
@@ -15,7 +15,6 @@ #include "base/location.h" #include "base/posix/eintr_wrapper.h" #include "base/task/task_runner.h" -#include "base/task/task_runner_util.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" @@ -36,8 +35,8 @@ DCHECK(!async_in_progress_); scoped_refptr<IOBuffer> buf = in_buf; - const bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + const bool posted = task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Context::ReadFileImpl, base::Unretained(this), buf, buf_len), base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), @@ -54,8 +53,8 @@ DCHECK(!async_in_progress_); scoped_refptr<IOBuffer> buf = in_buf; - const bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + const bool posted = task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Context::WriteFileImpl, base::Unretained(this), buf, buf_len), base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this),
diff --git a/net/base/network_change_notifier_win.cc b/net/base/network_change_notifier_win.cc index 35a30c8..f900732 100644 --- a/net/base/network_change_notifier_win.cc +++ b/net/base/network_change_notifier_win.cc
@@ -15,7 +15,6 @@ #include "base/metrics/histogram_macros.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/thread.h" @@ -272,8 +271,8 @@ base::OnceCallback<void(ConnectionType)> reply_callback) const { // Unretained is safe in this call because this object owns the thread and the // thread is stopped in this object's destructor. - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&NetworkChangeNotifierWin::RecomputeCurrentConnectionType), std::move(reply_callback)); }
diff --git a/net/base/url_util.cc b/net/base/url_util.cc index 0aefe495..61b662f 100644 --- a/net/base/url_util.cc +++ b/net/base/url_util.cc
@@ -90,14 +90,13 @@ if (should_keep_param) param_value = base::EscapeQueryParamValue(value.value(), true); - const std::string input = url.query(); + const base::StringPiece input = url.query_piece(); url::Component cursor(0, input.size()); std::string output; url::Component key_range, value_range; while (url::ExtractQueryKeyValue(input.data(), &cursor, &key_range, &value_range)) { - const base::StringPiece key( - input.data() + key_range.begin, key_range.len); + const base::StringPiece key = input.substr(key_range.begin, key_range.len); std::string key_value_pair; // Check |replaced| as only the first pair should be replaced. if (!replaced && key == param_name) { @@ -105,11 +104,10 @@ if (!should_keep_param) continue; - key_value_pair = (param_name + "=" + param_value); - + key_value_pair = param_name + "=" + param_value; } else { - key_value_pair.assign(input, key_range.begin, - value_range.end() - key_range.begin); + key_value_pair = std::string( + input.substr(key_range.begin, value_range.end() - key_range.begin)); } if (!output.empty()) output += "&"; @@ -147,14 +145,14 @@ base::StringPiece QueryIterator::GetKey() const { DCHECK(!at_end_); if (key_.is_nonempty()) - return base::StringPiece(&url_->spec()[key_.begin], key_.len); + return base::StringPiece(url_->spec()).substr(key_.begin, key_.len); return base::StringPiece(); } base::StringPiece QueryIterator::GetValue() const { DCHECK(!at_end_); if (value_.is_nonempty()) - return base::StringPiece(&url_->spec()[value_.begin], value_.len); + return base::StringPiece(url_->spec()).substr(value_.begin, value_.len); return base::StringPiece(); }
diff --git a/net/cert/pki/DEPS b/net/cert/pki/DEPS index c7070b6..db925a4 100644 --- a/net/cert/pki/DEPS +++ b/net/cert/pki/DEPS
@@ -5,20 +5,16 @@ "-base", "+base/base_paths.h", "+base/callback_forward.h", - "+base/compiler_specific.h", "+base/containers/contains.h", "+base/containers/span.h", "+base/files/file_util.h", - "+base/logging.h", "+base/memory/raw_ptr.h", "+base/memory/ref_counted.h", "+base/memory/scoped_refptr.h", "+base/metrics/histogram_functions.h", "+base/numerics/clamped_math.h", "+base/path_service.h", - "+base/ranges/algorithm.h", "+base/stl_util.h", - "+base/strings/string_number_conversions.h", "+base/strings/string_piece.h", "+base/supports_user_data.h", "+base/time/time.h",
diff --git a/net/cert/pki/cert_errors.h b/net/cert/pki/cert_errors.h index 6e783bc..a60bfd0 100644 --- a/net/cert/pki/cert_errors.h +++ b/net/cert/pki/cert_errors.h
@@ -49,7 +49,6 @@ #include <memory> #include <vector> -#include "base/compiler_specific.h" #include "net/base/net_export.h" #include "net/cert/pki/cert_error_id.h" #include "net/cert/pki/parsed_certificate.h"
diff --git a/net/cert/pki/path_builder.cc b/net/cert/pki/path_builder.cc index 164540a..311207d6 100644 --- a/net/cert/pki/path_builder.cc +++ b/net/cert/pki/path_builder.cc
@@ -8,7 +8,6 @@ #include <set> #include <unordered_set> -#include "base/logging.h" #include "base/memory/raw_ptr.h" #include "base/metrics/histogram_functions.h" #include "net/base/net_errors.h"
diff --git a/net/cert/pki/signature_algorithm_unittest.cc b/net/cert/pki/signature_algorithm_unittest.cc index 27870e42..04a8023 100644 --- a/net/cert/pki/signature_algorithm_unittest.cc +++ b/net/cert/pki/signature_algorithm_unittest.cc
@@ -8,7 +8,6 @@ #include "base/containers/span.h" #include "base/files/file_util.h" -#include "base/strings/string_number_conversions.h" #include "net/cert/pem.h" #include "net/der/input.h" #include "net/der/parser.h"
diff --git a/net/cert/pki/string_util.cc b/net/cert/pki/string_util.cc index f384fe7..b538766 100644 --- a/net/cert/pki/string_util.cc +++ b/net/cert/pki/string_util.cc
@@ -4,11 +4,11 @@ #include "net/cert/pki/string_util.h" +#include <algorithm> #include <iomanip> #include <sstream> #include <string> -#include "base/ranges/algorithm.h" #include "third_party/boringssl/src/include/openssl/mem.h" namespace net::string_util { @@ -23,10 +23,10 @@ } bool IsEqualNoCase(std::string_view str1, std::string_view str2) { - return base::ranges::equal(str1, str2, - [](const unsigned char a, const unsigned char b) { - return OPENSSL_tolower(a) == OPENSSL_tolower(b); - }); + return std::equal(str1.begin(), str1.end(), str2.begin(), str2.end(), + [](const unsigned char a, const unsigned char b) { + return OPENSSL_tolower(a) == OPENSSL_tolower(b); + }); } bool EndsWithNoCase(std::string_view str, std::string_view suffix) {
diff --git a/net/cert/pki/verify_certificate_chain.h b/net/cert/pki/verify_certificate_chain.h index 929eb23..fc22eee 100644 --- a/net/cert/pki/verify_certificate_chain.h +++ b/net/cert/pki/verify_certificate_chain.h
@@ -7,7 +7,6 @@ #include <set> -#include "base/compiler_specific.h" #include "net/base/net_export.h" #include "net/cert/pki/cert_errors.h" #include "net/cert/pki/parsed_certificate.h"
diff --git a/net/http/transport_security_persister.cc b/net/http/transport_security_persister.cc index a29d0f0..b0325ea8 100644 --- a/net/http/transport_security_persister.cc +++ b/net/http/transport_security_persister.cc
@@ -18,7 +18,6 @@ #include "base/location.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/values.h" #include "crypto/sha2.h" #include "net/base/features.h" @@ -304,9 +303,8 @@ background_runner_(background_runner) { transport_security_state_->SetDelegate(this); - base::PostTaskAndReplyWithResult( - background_runner_.get(), FROM_HERE, - base::BindOnce(&LoadState, writer_.path()), + background_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&LoadState, writer_.path()), base::BindOnce(&TransportSecurityPersister::CompleteLoad, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/net/socket/transport_client_socket_pool.cc b/net/socket/transport_client_socket_pool.cc index 7ffc650..ca831f7 100644 --- a/net/socket/transport_client_socket_pool.cc +++ b/net/socket/transport_client_socket_pool.cc
@@ -1390,7 +1390,11 @@ base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(&TransportClientSocketPool::InvokeUserCallback, weak_factory_.GetWeakPtr(), - base::UnsafeDanglingUntriaged(handle))); + // This is safe as `handle` is checked against a + // map to verify it's alive before dereference. + // This code path must only be reachable by + // `handle`s that have had Init called. + base::UnsafeDangling(handle))); } void TransportClientSocketPool::InvokeUserCallback(ClientSocketHandle* handle) {
diff --git a/net/ssl/client_cert_store_mac.cc b/net/ssl/client_cert_store_mac.cc index 9fd0aa7..4267793 100644 --- a/net/ssl/client_cert_store_mac.cc +++ b/net/ssl/client_cert_store_mac.cc
@@ -25,7 +25,6 @@ #include "base/ranges/algorithm.h" #include "base/strings/sys_string_conversions.h" #include "base/synchronization/lock.h" -#include "base/task/task_runner_util.h" #include "crypto/mac_security_services_lock.h" #include "net/base/host_port_pair.h" #include "net/cert/pki/extended_key_usage.h" @@ -402,8 +401,8 @@ void ClientCertStoreMac::GetClientCerts(const SSLCertRequestInfo& request, ClientCertListCallback callback) { - base::PostTaskAndReplyWithResult( - GetSSLPlatformKeyTaskRunner().get(), FROM_HERE, + GetSSLPlatformKeyTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, // Caller is responsible for keeping the |request| alive // until the callback is run, so std::cref is safe. base::BindOnce(&GetClientCertsOnBackgroundThread, std::cref(request)),
diff --git a/net/ssl/client_cert_store_win.cc b/net/ssl/client_cert_store_win.cc index f3e600d5..07e5be1 100644 --- a/net/ssl/client_cert_store_win.cc +++ b/net/ssl/client_cert_store_win.cc
@@ -20,7 +20,6 @@ #include "base/numerics/safe_conversions.h" #include "base/scoped_generic.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/win/wincrypt_shim.h" #include "net/cert/x509_util.h" #include "net/cert/x509_util_win.h" @@ -51,8 +50,8 @@ void AcquirePrivateKey(base::OnceCallback<void(scoped_refptr<SSLPrivateKey>)> private_key_callback) override { - base::PostTaskAndReplyWithResult( - key_task_runner_.get(), FROM_HERE, + key_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FetchClientCertPrivateKey, base::Unretained(certificate()), cert_context_.get()), std::move(private_key_callback)); @@ -226,8 +225,8 @@ void ClientCertStoreWin::GetClientCerts(const SSLCertRequestInfo& request, ClientCertListCallback callback) { - base::PostTaskAndReplyWithResult( - GetSSLPlatformKeyTaskRunner().get(), FROM_HERE, + GetSSLPlatformKeyTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, // Caller is responsible for keeping the |request| alive // until the callback is run, so std::cref is safe. base::BindOnce(&ClientCertStoreWin::GetClientCertsWithCertStore,
diff --git a/net/ssl/threaded_ssl_private_key.cc b/net/ssl/threaded_ssl_private_key.cc index 0fe7c8a..e0d5e5e8 100644 --- a/net/ssl/threaded_ssl_private_key.cc +++ b/net/ssl/threaded_ssl_private_key.cc
@@ -11,7 +11,6 @@ #include "base/bind.h" #include "base/location.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/threading/thread_task_runner_handle.h" namespace net { @@ -70,8 +69,8 @@ void ThreadedSSLPrivateKey::Sign(uint16_t algorithm, base::span<const uint8_t> input, SSLPrivateKey::SignCallback callback) { - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ThreadedSSLPrivateKey::Core::Sign, core_, algorithm, std::vector<uint8_t>(input.begin(), input.end())), base::BindOnce(&DoCallback, weak_factory_.GetWeakPtr(),
diff --git a/net/test/embedded_test_server/embedded_test_server.cc b/net/test/embedded_test_server/embedded_test_server.cc index 9ab3ea14..bd996a67 100644 --- a/net/test/embedded_test_server/embedded_test_server.cc +++ b/net/test/embedded_test_server/embedded_test_server.cc
@@ -26,7 +26,6 @@ #include "base/task/current_thread.h" #include "base/task/single_thread_task_executor.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/test/bind.h" #include "base/threading/thread_restrictions.h" #include "crypto/rsa_private_key.h" @@ -1012,8 +1011,8 @@ base::RunLoop run_loop; bool task_result = false; - if (!base::PostTaskAndReplyWithResult( - io_thread_->task_runner().get(), FROM_HERE, std::move(task), + if (!io_thread_->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, std::move(task), base::BindOnce(base::BindLambdaForTesting([&](bool result) { task_result = result; run_loop.Quit();
diff --git a/ppapi/proxy/file_io_resource.cc b/ppapi/proxy/file_io_resource.cc index 914ab0f..23bb8b4 100644 --- a/ppapi/proxy/file_io_resource.cc +++ b/ppapi/proxy/file_io_resource.cc
@@ -8,7 +8,6 @@ #include <utility> #include "base/bind.h" -#include "base/task/task_runner_util.h" #include "ipc/ipc_message.h" #include "ppapi/c/pp_errors.h" #include "ppapi/proxy/ppapi_messages.h" @@ -207,9 +206,8 @@ // For the non-blocking case, post a task to the file thread and add a // completion task to write the result. scoped_refptr<QueryOp> query_op(new QueryOp(file_holder_)); - base::PostTaskAndReplyWithResult( - PpapiGlobals::Get()->GetFileTaskRunner(), FROM_HERE, - base::BindOnce(&FileIOResource::QueryOp::DoWork, query_op), + PpapiGlobals::Get()->GetFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileIOResource::QueryOp::DoWork, query_op), RunWhileLocked(base::BindOnce(&TrackedCallback::Run, callback))); callback->set_completion_task( base::BindOnce(&FileIOResource::OnQueryComplete, this, query_op, info)); @@ -469,9 +467,8 @@ // For the non-blocking case, post a task to the file thread. scoped_refptr<ReadOp> read_op( new ReadOp(file_holder_, offset, bytes_to_read)); - base::PostTaskAndReplyWithResult( - PpapiGlobals::Get()->GetFileTaskRunner(), FROM_HERE, - base::BindOnce(&FileIOResource::ReadOp::DoWork, read_op), + PpapiGlobals::Get()->GetFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileIOResource::ReadOp::DoWork, read_op), RunWhileLocked(base::BindOnce(&TrackedCallback::Run, callback))); callback->set_completion_task(base::BindOnce(&FileIOResource::OnReadComplete, this, read_op, array_output)); @@ -510,9 +507,8 @@ memcpy(copy.get(), buffer, bytes_to_write); scoped_refptr<WriteOp> write_op(new WriteOp( file_holder_, offset, std::move(copy), bytes_to_write, append)); - base::PostTaskAndReplyWithResult( - PpapiGlobals::Get()->GetFileTaskRunner(), FROM_HERE, - base::BindOnce(&FileIOResource::WriteOp::DoWork, write_op), + PpapiGlobals::Get()->GetFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileIOResource::WriteOp::DoWork, write_op), RunWhileLocked(base::BindOnce(&TrackedCallback::Run, callback))); callback->set_completion_task( base::BindOnce(&FileIOResource::OnWriteComplete, this)); @@ -602,9 +598,8 @@ bool append = (open_flags_ & PP_FILEOPENFLAG_APPEND) != 0; scoped_refptr<WriteOp> write_op(new WriteOp( file_holder_, offset, std::move(buffer), bytes_to_write, append)); - base::PostTaskAndReplyWithResult( - PpapiGlobals::Get()->GetFileTaskRunner(), FROM_HERE, - base::BindOnce(&FileIOResource::WriteOp::DoWork, write_op), + PpapiGlobals::Get()->GetFileTaskRunner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileIOResource::WriteOp::DoWork, write_op), RunWhileLocked(base::BindOnce(&TrackedCallback::Run, callback))); callback->set_completion_task( BindOnce(&FileIOResource::OnWriteComplete, this));
diff --git a/remoting/client/chromoting_session.cc b/remoting/client/chromoting_session.cc index c4c577f..51fb812 100644 --- a/remoting/client/chromoting_session.cc +++ b/remoting/client/chromoting_session.cc
@@ -17,7 +17,6 @@ #include "base/logging.h" #include "base/memory/raw_ptr.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/timer/timer.h" #include "components/webrtc/thread_wrapper.h" #include "net/socket/client_socket_factory.h" @@ -696,8 +695,8 @@ // Bind to base::Unretained(core) instead of the WeakPtr so that we can still // get the feedback data after the session is remotely disconnected. - base::PostTaskAndReplyWithResult( - runtime_->network_task_runner().get(), FROM_HERE, + runtime_->network_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Core::GetFeedbackData, base::Unretained(core_.get())), std::move(callback)); }
diff --git a/remoting/client/notification/gstatic_json_fetcher_unittest.cc b/remoting/client/notification/gstatic_json_fetcher_unittest.cc index e4b6812..06fd421 100644 --- a/remoting/client/notification/gstatic_json_fetcher_unittest.cc +++ b/remoting/client/notification/gstatic_json_fetcher_unittest.cc
@@ -12,6 +12,7 @@ #include "base/test/gmock_callback_support.h" #include "base/test/mock_callback.h" #include "base/test/task_environment.h" +#include "base/test/values_test_util.h" #include "base/values.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_error_job.h" @@ -36,20 +37,17 @@ } MATCHER(IsJsonData1, "") { - if (!arg || !arg->is_dict()) { + if (!arg) { return false; } - const base::Value* a = arg->FindKey("a"); - return a && a->is_int() && a->GetInt() == 1; + return *arg == base::test::ParseJson(R"({"a":1})"); } MATCHER(IsJsonData2, "") { - if (!arg || !arg->is_list()) { + if (!arg) { return false; } - auto list = arg->GetListDeprecated(); - return list.size() == 1 && list[0].is_string() && - list[0].GetString() == "123"; + return *arg == base::test::ParseJson(R"(["123"])"); } class TestURLRequestInterceptor : public net::URLRequestInterceptor {
diff --git a/remoting/client/notification/notification_client.cc b/remoting/client/notification/notification_client.cc index a21e21c..b340052c 100644 --- a/remoting/client/notification/notification_client.cc +++ b/remoting/client/notification/notification_client.cc
@@ -76,13 +76,13 @@ })"); template <typename T, typename IsTChecker, typename TGetter> -bool FindKeyAndGet(const base::Value& dict, +bool FindKeyAndGet(const base::Value::Dict& dict, const std::string& key, T* out, IsTChecker is_t_checker, TGetter t_getter, const std::string& type_name) { - const base::Value* value = dict.FindKey(key); + const base::Value* value = dict.Find(key); if (!value) { LOG(WARNING) << "|" << key << "| not found in dictionary."; return false; @@ -95,7 +95,7 @@ return true; } -bool FindKeyAndGet(const base::Value& dict, +bool FindKeyAndGet(const base::Value::Dict& dict, const std::string& key, std::string* out) { const std::string& (base::Value::*get_string_fp)() const = @@ -104,12 +104,16 @@ "string"); } -bool FindKeyAndGet(const base::Value& dict, const std::string& key, int* out) { +bool FindKeyAndGet(const base::Value::Dict& dict, + const std::string& key, + int* out) { return FindKeyAndGet(dict, key, out, &base::Value::is_int, &base::Value::GetInt, "int"); } -bool FindKeyAndGet(const base::Value& dict, const std::string& key, bool* out) { +bool FindKeyAndGet(const base::Value::Dict& dict, + const std::string& key, + bool* out) { return FindKeyAndGet(dict, key, out, &base::Value::is_bool, &base::Value::GetBool, "bool"); } @@ -173,9 +177,10 @@ NotifyFetchFailed(); return; } + + const base::Value::Dict& dict = translations->GetDict(); bool is_translation_found = false; - is_translation_found = - FindKeyAndGet(*translations, locale_, string_to_update); + is_translation_found = FindKeyAndGet(dict, locale_, string_to_update); if (!is_translation_found) { LOG(WARNING) << "Failed to find translation for locale " << locale_ << ". Looking for parent locales instead."; @@ -185,7 +190,7 @@ // Locales returned by GetParentLocales() use "_" instead of "-", which // need to be fixed. std::replace(parent_locale.begin(), parent_locale.end(), '_', '-'); - if (FindKeyAndGet(*translations, parent_locale, string_to_update)) { + if (FindKeyAndGet(dict, parent_locale, string_to_update)) { LOG(WARNING) << "Locale " << parent_locale << " is being used instead."; is_translation_found = true; @@ -199,7 +204,7 @@ << " is found in translations. Falling back to default locale: " << kDefaultLocale; is_translation_found = - FindKeyAndGet(*translations, kDefaultLocale, string_to_update); + FindKeyAndGet(dict, kDefaultLocale, string_to_update); } if (!is_translation_found) { LOG(ERROR) << "Failed to find translation for default locale"; @@ -288,11 +293,12 @@ return; } - for (const auto& rule : rules->GetListDeprecated()) { + for (const auto& rule : rules->GetList()) { std::string message_text_filename; std::string link_text_filename; - auto message = ParseAndMatchRule(rule, user_email, &message_text_filename, - &link_text_filename); + auto message = + ParseAndMatchRule(rule.GetDict(), user_email, &message_text_filename, + &link_text_filename); if (message) { FetchTranslatedTexts(message_text_filename, link_text_filename, @@ -305,7 +311,7 @@ } absl::optional<NotificationMessage> NotificationClient::ParseAndMatchRule( - const base::Value& rule, + const base::Value::Dict& rule, const std::string& user_email, std::string* out_message_text_filename, std::string* out_link_text_filename) {
diff --git a/remoting/client/notification/notification_client.h b/remoting/client/notification/notification_client.h index 720ccef..c454c3f4 100644 --- a/remoting/client/notification/notification_client.h +++ b/remoting/client/notification/notification_client.h
@@ -10,12 +10,9 @@ #include "base/callback_forward.h" #include "base/task/single_thread_task_runner.h" +#include "base/values.h" #include "third_party/abseil-cpp/absl/types/optional.h" -namespace base { -class Value; -} // namespace base - namespace remoting { class JsonFetcher; @@ -67,7 +64,7 @@ // and the rule should apply to the user. |message_text| and |link_text| will // not be set and caller needs to call FetchTranslatedText to fill them up. absl::optional<NotificationMessage> ParseAndMatchRule( - const base::Value& rule, + const base::Value::Dict& rule, const std::string& user_email, std::string* out_message_text_filename, std::string* out_link_text_filename);
diff --git a/remoting/client/notification/notification_client_unittest.cc b/remoting/client/notification/notification_client_unittest.cc index b77e9ce..ff4e538 100644 --- a/remoting/client/notification/notification_client_unittest.cc +++ b/remoting/client/notification/notification_client_unittest.cc
@@ -58,24 +58,24 @@ return Return(ByMove(std::move(t))); } -base::Value CreateDefaultRule() { - base::Value rule(base::Value::Type::DICTIONARY); - rule.SetStringKey("target_platform", "IOS"); - rule.SetStringKey("version", "[75-)"); - rule.SetStringKey("message_id", "test_message"); - rule.SetStringKey("message_text", "message_text.json"); - rule.SetStringKey("link_text", "link_text.json"); - rule.SetStringKey("link_url", "https://example.com/some_link"); - rule.SetIntKey("percent", 100); - rule.SetBoolKey("allow_silence", true); +base::Value::Dict CreateDefaultRule() { + base::Value::Dict rule; + rule.Set("target_platform", "IOS"); + rule.Set("version", "[75-)"); + rule.Set("message_id", "test_message"); + rule.Set("message_text", "message_text.json"); + rule.Set("link_text", "link_text.json"); + rule.Set("link_url", "https://example.com/some_link"); + rule.Set("percent", 100); + rule.Set("allow_silence", true); return rule; } base::Value CreateDefaultTranslations(const std::string& text) { - base::Value translations(base::Value::Type::DICTIONARY); - translations.SetStringKey("en-US", "en-US:" + text); - translations.SetStringKey("zh-CN", "zh-CN:" + text); - return translations; + base::Value::Dict translations; + translations.Set("en-US", "en-US:" + text); + translations.Set("zh-CN", "zh-CN:" + text); + return base::Value(std::move(translations)); } NotificationMessage CreateDefaultNotification() { @@ -111,9 +111,9 @@ }; TEST_F(NotificationClientTest, NoRule) { - base::Value rules(base::Value::Type::LIST); + base::Value::List rules; EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); base::MockCallback<NotificationClient::NotificationCallback> callback; EXPECT_CALL(callback, Run(NoMessage())); @@ -121,10 +121,10 @@ } TEST_F(NotificationClientTest, DefaultRule) { - base::Value rules(base::Value::Type::LIST); + base::Value::List rules; rules.Append(CreateDefaultRule()); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(CreateDefaultTranslations("message"))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json")) @@ -136,12 +136,12 @@ } TEST_F(NotificationClientTest, PlatformNotMatched) { - base::Value rule = CreateDefaultRule(); - rule.SetStringKey("target_platform", "ANDROID"); - base::Value rules(base::Value::Type::LIST); + base::Value::Dict rule = CreateDefaultRule(); + rule.Set("target_platform", "ANDROID"); + base::Value::List rules; rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); base::MockCallback<NotificationClient::NotificationCallback> callback; EXPECT_CALL(callback, Run(NoMessage())); @@ -149,12 +149,12 @@ } TEST_F(NotificationClientTest, VersionNotMatched) { - base::Value rule = CreateDefaultRule(); - rule.SetStringKey("version", "[77-)"); - base::Value rules(base::Value::Type::LIST); + base::Value::Dict rule = CreateDefaultRule(); + rule.Set("version", "[77-)"); + base::Value::List rules; rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); base::MockCallback<NotificationClient::NotificationCallback> callback; EXPECT_CALL(callback, Run(NoMessage())); @@ -162,12 +162,12 @@ } TEST_F(NotificationClientTest, OsVersionNotMatched) { - base::Value rule = CreateDefaultRule(); - rule.SetStringKey("os_version", "(-15.1)"); - base::Value rules(base::Value::Type::LIST); + base::Value::Dict rule = CreateDefaultRule(); + rule.Set("os_version", "(-15.1)"); + base::Value::List rules; rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); base::MockCallback<NotificationClient::NotificationCallback> callback; EXPECT_CALL(callback, Run(NoMessage())); @@ -175,12 +175,12 @@ } TEST_F(NotificationClientTest, OsVersionMatched) { - base::Value rule = CreateDefaultRule(); - rule.SetStringKey("os_version", "[15-)"); - base::Value rules(base::Value::Type::LIST); + base::Value::Dict rule = CreateDefaultRule(); + rule.Set("os_version", "[15-)"); + base::Value::List rules; rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(CreateDefaultTranslations("message"))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json")) @@ -192,12 +192,12 @@ } TEST_F(NotificationClientTest, UserNotSelected) { - base::Value rule = CreateDefaultRule(); - rule.SetIntKey("percent", 0); - base::Value rules(base::Value::Type::LIST); + base::Value::Dict rule = CreateDefaultRule(); + rule.Set("percent", 0); + base::Value::List rules; rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); base::MockCallback<NotificationClient::NotificationCallback> callback; EXPECT_CALL(callback, Run(NoMessage())); @@ -205,14 +205,14 @@ } TEST_F(NotificationClientTest, SecondRuleMatches) { - base::Value rules(base::Value::Type::LIST); - base::Value rule_1 = CreateDefaultRule(); - rule_1.SetStringKey("target_platform", "ANDROID"); - rule_1.SetStringKey("message_text", "message_text_1.json"); + base::Value::List rules; + base::Value::Dict rule_1 = CreateDefaultRule(); + rule_1.Set("target_platform", "ANDROID"); + rule_1.Set("message_text", "message_text_1.json"); rules.Append(std::move(rule_1)); rules.Append(CreateDefaultRule()); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(CreateDefaultTranslations("message"))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json")) @@ -224,13 +224,13 @@ } TEST_F(NotificationClientTest, MultipleMatchingRules_FirstRuleSelected) { - base::Value rules(base::Value::Type::LIST); + base::Value::List rules; rules.Append(CreateDefaultRule()); - base::Value rule_2 = CreateDefaultRule(); - rule_2.SetStringKey("message_text", "message_text_2.json"); + base::Value::Dict rule_2 = CreateDefaultRule(); + rule_2.Set("message_text", "message_text_2.json"); rules.Append(std::move(rule_2)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(CreateDefaultTranslations("message"))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json")) @@ -242,10 +242,10 @@ } TEST_F(NotificationClientTest, TextFilesNotFound) { - base::Value rules(base::Value::Type::LIST); + base::Value::List rules; rules.Append(CreateDefaultRule()); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); base::Value translation = CreateDefaultTranslations("message"); @@ -260,14 +260,14 @@ } TEST_F(NotificationClientTest, TranslationNotFound_FallbackToGenericLanguage) { - base::Value rules(base::Value::Type::LIST); + base::Value::List rules; rules.Append(CreateDefaultRule()); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); base::Value translations = CreateDefaultTranslations("message"); - translations.RemoveKey("zh-CN"); - translations.SetStringKey("zh", "zh:message"); + translations.GetDict().Remove("zh-CN"); + translations.GetDict().Set("zh", "zh:message"); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(std::move(translations))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json")) @@ -281,13 +281,13 @@ } TEST_F(NotificationClientTest, TranslationNotFound_FallbackToEnglish) { - base::Value rules(base::Value::Type::LIST); + base::Value::List rules; rules.Append(CreateDefaultRule()); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); base::Value translations = CreateDefaultTranslations("message"); - translations.RemoveKey("zh-CN"); + translations.GetDict().Remove("zh-CN"); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(std::move(translations))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json")) @@ -304,10 +304,10 @@ GenericLanguageTranslationNotFound_FallbackToEnglish) { Reset(/* should_ignore_dev_messages= */ false, /* test_locale= */ "es"); - base::Value rules(base::Value::Type::LIST); + base::Value::List rules; rules.Append(CreateDefaultRule()); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(CreateDefaultTranslations("message"))); @@ -323,10 +323,10 @@ } TEST_F(NotificationClientTest, NoAvailableTranslation) { - base::Value rules(base::Value::Type::LIST); + base::Value::List rules; rules.Append(CreateDefaultRule()); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(base::Value(base::Value::Type::DICTIONARY))); @@ -339,12 +339,12 @@ } TEST_F(NotificationClientTest, ReleaseBuildsIgnoreDevMessages) { - base::Value rules(base::Value::Type::LIST); - base::Value rule = CreateDefaultRule(); - rule.SetBoolKey("dev_mode", true); + base::Value::List rules; + base::Value::Dict rule = CreateDefaultRule(); + rule.Set("dev_mode", true); rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); base::MockCallback<NotificationClient::NotificationCallback> callback; EXPECT_CALL(callback, Run(NoMessage())); @@ -352,12 +352,12 @@ } TEST_F(NotificationClientTest, ReleaseBuildsDontIgnoreDevMessages) { - base::Value rules(base::Value::Type::LIST); - base::Value rule = CreateDefaultRule(); - rule.SetBoolKey("dev_mode", false); + base::Value::List rules; + base::Value::Dict rule = CreateDefaultRule(); + rule.Set("dev_mode", false); rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(CreateDefaultTranslations("message"))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json")) @@ -371,12 +371,12 @@ TEST_F(NotificationClientTest, DebugBuildsDontIgnoreDevMessages) { Reset(/* should_ignore_dev_messages */ false); - base::Value rules(base::Value::Type::LIST); - base::Value rule = CreateDefaultRule(); - rule.SetBoolKey("dev_mode", true); + base::Value::List rules; + base::Value::Dict rule = CreateDefaultRule(); + rule.Set("dev_mode", true); rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(CreateDefaultTranslations("message"))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json")) @@ -388,12 +388,12 @@ } TEST_F(NotificationClientTest, AllowSilenceNotSet_DefaultToFalse) { - base::Value rules(base::Value::Type::LIST); - base::Value rule = CreateDefaultRule(); - rule.RemoveKey("allow_silence"); + base::Value::List rules; + base::Value::Dict rule = CreateDefaultRule(); + rule.Remove("allow_silence"); rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(CreateDefaultTranslations("message"))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json")) @@ -408,12 +408,12 @@ TEST_F(NotificationClientTest, EmptyUserEmailAndNot100PercentRollout_NoNotification) { - base::Value rules(base::Value::Type::LIST); - base::Value rule = CreateDefaultRule(); - rule.SetIntKey("percent", 99); + base::Value::List rules; + base::Value::Dict rule = CreateDefaultRule(); + rule.Set("percent", 99); rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); base::MockCallback<NotificationClient::NotificationCallback> callback; EXPECT_CALL(callback, Run(NoMessage())); @@ -422,12 +422,12 @@ TEST_F(NotificationClientTest, EmptyUserEmailAnd100PercentRollout_ReturnsNotification) { - base::Value rules(base::Value::Type::LIST); - base::Value rule = CreateDefaultRule(); - rule.SetIntKey("percent", 100); + base::Value::List rules; + base::Value::Dict rule = CreateDefaultRule(); + rule.Set("percent", 100); rules.Append(std::move(rule)); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json")) - .WillOnce(ReturnByMove(std::move(rules))); + .WillOnce(ReturnByMove(base::Value(std::move(rules)))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json")) .WillOnce(ReturnByMove(CreateDefaultTranslations("message"))); EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json"))
diff --git a/remoting/client/software_video_renderer.cc b/remoting/client/software_video_renderer.cc index 53e8620..0e2b540 100644 --- a/remoting/client/software_video_renderer.cc +++ b/remoting/client/software_video_renderer.cc
@@ -14,7 +14,6 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "remoting/base/util.h" #include "remoting/client/client_context.h" #include "remoting/codec/video_decoder.h" @@ -154,8 +153,8 @@ consumer_->AllocateFrame(source_size_); frame->set_dpi(source_dpi_); - base::PostTaskAndReplyWithResult( - decode_task_runner_.get(), FROM_HERE, + decode_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DoDecodeFrame, decoder_.get(), std::move(packet), std::move(frame)), base::BindOnce(&SoftwareVideoRenderer::RenderFrame,
diff --git a/remoting/codec/video_encoder.cc b/remoting/codec/video_encoder.cc index dc4c4394..56aa8d2 100644 --- a/remoting/codec/video_encoder.cc +++ b/remoting/codec/video_encoder.cc
@@ -4,6 +4,8 @@ #include "remoting/codec/video_encoder.h" +#include <ostream> + #include "base/notreached.h" #include "remoting/codec/video_encoder_verbatim.h" #include "remoting/codec/video_encoder_vpx.h"
diff --git a/remoting/host/it2me/it2me_native_messaging_host.cc b/remoting/host/it2me/it2me_native_messaging_host.cc index 89a7e87..ce59647 100644 --- a/remoting/host/it2me/it2me_native_messaging_host.cc +++ b/remoting/host/it2me/it2me_native_messaging_host.cc
@@ -321,9 +321,7 @@ protocol::IceConfig ice_config; base::Value::Dict* ice_config_dict = message.FindDict(kIceConfig); if (ice_config_dict) { - base::Value ice_config_value(std::move(*ice_config_dict)); - ice_config = protocol::IceConfig::Parse( - base::Value::AsDictionaryValue(ice_config_value)); + ice_config = protocol::IceConfig::Parse(*ice_config_dict); } base::Value::Dict policies = policy_watcher_->GetEffectivePolicies();
diff --git a/remoting/host/mac/permission_checker.cc b/remoting/host/mac/permission_checker.cc index cf3418c..05efbaa1 100644 --- a/remoting/host/mac/permission_checker.cc +++ b/remoting/host/mac/permission_checker.cc
@@ -7,7 +7,6 @@ #include <utility> #include "base/bind.h" -#include "base/task/task_runner_util.h" #include "remoting/host/mac/permission_process_utils.h" #include "remoting/host/version.h" @@ -38,16 +37,16 @@ void PermissionChecker::CheckAccessibilityPermission( PermissionWizard::ResultCallback onResult) { - base::PostTaskAndReplyWithResult( - io_task_runner_.get(), FROM_HERE, + io_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(remoting::mac::CheckAccessibilityPermission, mode_), std::move(onResult)); } void PermissionChecker::CheckScreenRecordingPermission( PermissionWizard::ResultCallback onResult) { - base::PostTaskAndReplyWithResult( - io_task_runner_.get(), FROM_HERE, + io_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(remoting::mac::CheckScreenRecordingPermission, mode_), std::move(onResult)); }
diff --git a/remoting/host/security_key/security_key_message_writer_impl_unittest.cc b/remoting/host/security_key/security_key_message_writer_impl_unittest.cc index 45c42518..2ccd7f7 100644 --- a/remoting/host/security_key/security_key_message_writer_impl_unittest.cc +++ b/remoting/host/security_key/security_key_message_writer_impl_unittest.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/run_loop.h" -#include "base/task/task_runner_util.h" #include "base/test/task_environment.h" #include "base/threading/thread.h" #include "remoting/host/security_key/security_key_message.h" @@ -109,8 +108,8 @@ base::test::SingleThreadTaskEnvironment::MainThreadType::IO); base::RunLoop run_loop; - ASSERT_TRUE(base::PostTaskAndReplyWithResult( - reader_thread.task_runner().get(), FROM_HERE, + ASSERT_TRUE(reader_thread.task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&SecurityKeyMessageWriterImplTest::ReadMessage, base::Unretained(this), payload.size()), base::BindOnce(&SecurityKeyMessageWriterImplTest::OnReadComplete,
diff --git a/remoting/protocol/audio_decode_scheduler.cc b/remoting/protocol/audio_decode_scheduler.cc index e022c48..270fa4b 100644 --- a/remoting/protocol/audio_decode_scheduler.cc +++ b/remoting/protocol/audio_decode_scheduler.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/location.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "remoting/codec/audio_decoder.h" #include "remoting/proto/audio.pb.h" #include "remoting/protocol/audio_stub.h" @@ -38,8 +37,8 @@ base::OnceClosure done) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - base::PostTaskAndReplyWithResult( - audio_decode_task_runner_.get(), FROM_HERE, + audio_decode_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&AudioDecoder::Decode, base::Unretained(decoder_.get()), std::move(packet)), base::BindOnce(&AudioDecodeScheduler::ProcessDecodedPacket,
diff --git a/remoting/protocol/ice_config.cc b/remoting/protocol/ice_config.cc index 0c76037..eaba9af4 100644 --- a/remoting/protocol/ice_config.cc +++ b/remoting/protocol/ice_config.cc
@@ -112,9 +112,8 @@ IceConfig::~IceConfig() = default; // static -IceConfig IceConfig::Parse(const base::DictionaryValue& dictionary) { - const base::Value::List* ice_servers_list = - dictionary.GetDict().FindList("iceServers"); +IceConfig IceConfig::Parse(const base::Value::Dict& dictionary) { + const base::Value::List* ice_servers_list = dictionary.FindList("iceServers"); if (!ice_servers_list) { return IceConfig(); } @@ -122,8 +121,7 @@ IceConfig ice_config; // Parse lifetimeDuration field. - const std::string* lifetime_str = - dictionary.FindStringKey("lifetimeDuration"); + const std::string* lifetime_str = dictionary.FindString("lifetimeDuration"); base::TimeDelta lifetime; if (!lifetime_str || !ParseLifetime(*lifetime_str, &lifetime)) { LOG(ERROR) << "Received invalid lifetimeDuration value: " << lifetime_str; @@ -139,24 +137,25 @@ bool errors_found = false; ice_config.max_bitrate_kbps = 0; for (const auto& server : *ice_servers_list) { - if (!server.is_dict()) { + const base::Value::Dict* server_dict = server.GetIfDict(); + if (!server_dict) { errors_found = true; continue; } - const base::Value* urls_list = server.FindListKey("urls"); + const base::Value::List* urls_list = server_dict->FindList("urls"); if (!urls_list) { errors_found = true; continue; } std::string username; - const std::string* maybe_username = server.FindStringKey("username"); + const std::string* maybe_username = server_dict->FindString("username"); if (maybe_username) username = *maybe_username; std::string password; - const std::string* maybe_password = server.FindStringKey("credential"); + const std::string* maybe_password = server_dict->FindString("credential"); if (maybe_password) password = *maybe_password; @@ -164,14 +163,14 @@ // Ideally the bitrate would be stored per ICE server, but it is not // possible (at the application level) to look up which particular // ICE server was used for the P2P connection. - auto new_bitrate_double = server.FindDoubleKey("maxRateKbps"); + auto new_bitrate_double = server_dict->FindDouble("maxRateKbps"); if (new_bitrate_double.has_value()) { ice_config.max_bitrate_kbps = MinimumSpecified(ice_config.max_bitrate_kbps, static_cast<int>(new_bitrate_double.value())); } - for (const auto& url : urls_list->GetListDeprecated()) { + for (const auto& url : *urls_list) { const std::string* url_str = url.GetIfString(); if (!url_str) { errors_found = true; @@ -210,19 +209,20 @@ return IceConfig(); } - if (!json->is_dict()) { + base::Value::Dict* dictionary = json->GetIfDict(); + if (!dictionary) { return IceConfig(); } // Handle the case when the config is wrapped in 'data', i.e. as {'data': { // 'iceServers': {...} }}. - if (!json->FindKey("iceServers")) { - base::Value* data_dictionary = json->FindDictKey("data"); + if (!dictionary->Find("iceServers")) { + base::Value::Dict* data_dictionary = dictionary->FindDict("data"); if (data_dictionary) - return Parse(base::Value::AsDictionaryValue(*data_dictionary)); + return Parse(*data_dictionary); } - return Parse(base::Value::AsDictionaryValue(*json)); + return Parse(*dictionary); } // static
diff --git a/remoting/protocol/ice_config.h b/remoting/protocol/ice_config.h index aa8c6c8..b3f010e9 100644 --- a/remoting/protocol/ice_config.h +++ b/remoting/protocol/ice_config.h
@@ -9,13 +9,10 @@ #include <vector> #include "base/time/time.h" +#include "base/values.h" #include "third_party/webrtc/p2p/base/port_allocator.h" #include "third_party/webrtc/rtc_base/socket_address.h" -namespace base { -class DictionaryValue; -} // namespace base - namespace remoting { namespace apis { @@ -35,7 +32,7 @@ // Parses JSON representation of the config. Returns null config if parsing // fails. - static IceConfig Parse(const base::DictionaryValue& dictionary); + static IceConfig Parse(const base::Value::Dict& dictionary); static IceConfig Parse(const std::string& config_json); static IceConfig Parse(const apis::v1::GetIceConfigResponse& config);
diff --git a/remoting/protocol/video_frame_pump.cc b/remoting/protocol/video_frame_pump.cc index cabe613..ba25804 100644 --- a/remoting/protocol/video_frame_pump.cc +++ b/remoting/protocol/video_frame_pump.cc
@@ -12,7 +12,6 @@ #include "base/callback.h" #include "base/check.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/time/time.h" #include "remoting/base/constants.h" #include "remoting/proto/control.pb.h" @@ -145,8 +144,8 @@ // Even when |frame| is nullptr we still need to post it to the encode thread // to make sure frames are freed in the same order they are received and // that we don't start capturing frame n+2 before frame n is freed. - base::PostTaskAndReplyWithResult( - encode_task_runner_.get(), FROM_HERE, + encode_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&VideoFramePump::EncodeFrame, encoder_.get(), std::move(frame), std::move(captured_frame_timestamps_)), base::BindOnce(&VideoFramePump::OnFrameEncoded,
diff --git a/remoting/test/cyclic_frame_generator.cc b/remoting/test/cyclic_frame_generator.cc index 9bfa3fd..a6722c1 100644 --- a/remoting/test/cyclic_frame_generator.cc +++ b/remoting/test/cyclic_frame_generator.cc
@@ -4,6 +4,8 @@ #include "remoting/test/cyclic_frame_generator.h" +#include <ostream> + #include "base/numerics/safe_conversions.h" #include "base/time/default_tick_clock.h" #include "remoting/test/frame_generator_util.h"
diff --git a/services/device/generic_sensor/platform_sensor_provider_win.cc b/services/device/generic_sensor/platform_sensor_provider_win.cc index 286b5760..5b83ac8 100644 --- a/services/device/generic_sensor/platform_sensor_provider_win.cc +++ b/services/device/generic_sensor/platform_sensor_provider_win.cc
@@ -10,7 +10,6 @@ #include <iomanip> #include "base/bind.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/thread.h" @@ -110,8 +109,8 @@ // Try to create low-level sensors by default. default: { - base::PostTaskAndReplyWithResult( - com_sta_task_runner_.get(), FROM_HERE, + com_sta_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&PlatformSensorProviderWin::CreateSensorReader, base::Unretained(this), type), base::BindOnce(&PlatformSensorProviderWin::SensorReaderCreated,
diff --git a/services/device/generic_sensor/platform_sensor_provider_winrt.cc b/services/device/generic_sensor/platform_sensor_provider_winrt.cc index e557a86c..ca9333a 100644 --- a/services/device/generic_sensor/platform_sensor_provider_winrt.cc +++ b/services/device/generic_sensor/platform_sensor_provider_winrt.cc
@@ -6,7 +6,6 @@ #include <comdef.h> -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "services/device/generic_sensor/gravity_fusion_algorithm_using_accelerometer.h" #include "services/device/generic_sensor/linear_acceleration_fusion_algorithm_using_accelerometer.h" @@ -65,8 +64,8 @@ // Try to create low-level sensors by default. default: { - base::PostTaskAndReplyWithResult( - com_sta_task_runner_.get(), FROM_HERE, + com_sta_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&PlatformSensorProviderWinrt::CreateSensorReader, base::Unretained(this), type), base::BindOnce(&PlatformSensorProviderWinrt::SensorReaderCreated,
diff --git a/services/service_manager/service_process_launcher.cc b/services/service_manager/service_process_launcher.cc index 4d13b9f..d049814 100644 --- a/services/service_manager/service_process_launcher.cc +++ b/services/service_manager/service_process_launcher.cc
@@ -23,7 +23,6 @@ #include "base/sequence_checker.h" #include "base/strings/string_number_conversions.h" #include "base/synchronization/lock.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/threading/thread.h" #include "build/build_config.h" @@ -162,8 +161,8 @@ } state_ = base::WrapRefCounted(new ProcessState); - base::PostTaskAndReplyWithResult( - background_task_runner_.get(), FROM_HERE, + background_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ProcessState::LaunchInBackground, state_, target, sandbox_type, std::move(child_command_line), std::move(handle_passing_info), std::move(channel),
diff --git a/sql/sandboxed_vfs.cc b/sql/sandboxed_vfs.cc index 35c5002..d82281d5 100644 --- a/sql/sandboxed_vfs.cc +++ b/sql/sandboxed_vfs.cc
@@ -6,6 +6,7 @@ #include <algorithm> #include <cstring> +#include <ostream> #include <string> #include <utility> #include <vector>
diff --git a/storage/browser/blob/blob_memory_controller.cc b/storage/browser/blob/blob_memory_controller.cc index 08990f3..9533474 100644 --- a/storage/browser/blob/blob_memory_controller.cc +++ b/storage/browser/blob/blob_memory_controller.cc
@@ -418,8 +418,8 @@ controller_->file_runner_.get())); } // Send file creation task to file thread. - base::PostTaskAndReplyWithResult( - controller_->file_runner_.get(), FROM_HERE, + controller_->file_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CreateEmptyFiles, controller_->blob_storage_dir_, disk_space_function, controller_->file_runner_, std::move(file_paths)), @@ -919,8 +919,8 @@ weak_factory_.GetWeakPtr(), total_items_size)); // Post the file writing task. - base::PostTaskAndReplyWithResult( - file_runner_.get(), FROM_HERE, + file_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&CreateFileAndWriteItems, blob_storage_dir_, disk_space_function_, std::move(page_file_path), file_runner_, std::move(data_for_paging),
diff --git a/storage/browser/file_system/async_file_util_adapter.cc b/storage/browser/file_system/async_file_util_adapter.cc index b3b447d..48f808d 100644 --- a/storage/browser/file_system/async_file_util_adapter.cc +++ b/storage/browser/file_system/async_file_util_adapter.cc
@@ -15,7 +15,6 @@ #include "base/callback.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "components/services/filesystem/public/mojom/types.mojom.h" #include "storage/browser/blob/shareable_file_reference.h" #include "storage/browser/file_system/file_system_context.h" @@ -180,8 +179,8 @@ uint32_t file_flags, CreateOrOpenCallback callback) { FileSystemOperationContext* context_ptr = context.release(); - base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, BindOnce(&FileSystemFileUtil::CreateOrOpen, Unretained(sync_file_util_.get()), context_ptr, url, file_flags), BindOnce(&RunCreateOrOpenCallback, base::Owned(context_ptr), @@ -210,8 +209,8 @@ bool recursive, StatusCallback callback) { FileSystemOperationContext* context_ptr = context.release(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileSystemFileUtil::CreateDirectory, Unretained(sync_file_util_.get()), base::Owned(context_ptr), url, exclusive, recursive), @@ -260,8 +259,8 @@ const base::Time& last_modified_time, StatusCallback callback) { FileSystemOperationContext* context_ptr = context.release(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &FileSystemFileUtil::Touch, Unretained(sync_file_util_.get()), base::Owned(context_ptr), url, last_access_time, last_modified_time), @@ -275,8 +274,8 @@ int64_t length, StatusCallback callback) { FileSystemOperationContext* context_ptr = context.release(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileSystemFileUtil::Truncate, Unretained(sync_file_util_.get()), base::Owned(context_ptr), url, length), @@ -293,8 +292,8 @@ StatusCallback callback) { // TODO(hidehiko): Support progress_callback. FileSystemOperationContext* context_ptr = context.release(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileSystemFileUtil::CopyOrMoveFile, Unretained(sync_file_util_.get()), base::Owned(context_ptr), src_url, dest_url, options, @@ -310,8 +309,8 @@ CopyOrMoveOptionSet options, StatusCallback callback) { FileSystemOperationContext* context_ptr = context.release(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileSystemFileUtil::CopyOrMoveFile, Unretained(sync_file_util_.get()), base::Owned(context_ptr), src_url, dest_url, options, @@ -326,8 +325,8 @@ const FileSystemURL& dest_url, StatusCallback callback) { FileSystemOperationContext* context_ptr = context.release(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileSystemFileUtil::CopyInForeignFile, Unretained(sync_file_util_.get()), base::Owned(context_ptr), src_file_path, dest_url), @@ -340,8 +339,8 @@ const FileSystemURL& url, StatusCallback callback) { FileSystemOperationContext* context_ptr = context.release(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileSystemFileUtil::DeleteFile, Unretained(sync_file_util_.get()), base::Owned(context_ptr), url), @@ -354,8 +353,8 @@ const FileSystemURL& url, StatusCallback callback) { FileSystemOperationContext* context_ptr = context.release(); - const bool success = base::PostTaskAndReplyWithResult( - context_ptr->task_runner(), FROM_HERE, + const bool success = context_ptr->task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&FileSystemFileUtil::DeleteDirectory, Unretained(sync_file_util_.get()), base::Owned(context_ptr), url),
diff --git a/storage/browser/file_system/file_system_context.cc b/storage/browser/file_system/file_system_context.cc index 1f0f8db..a79c46b 100644 --- a/storage/browser/file_system/file_system_context.cc +++ b/storage/browser/file_system/file_system_context.cc
@@ -17,7 +17,6 @@ #include "base/memory/ptr_util.h" #include "base/memory/scoped_refptr.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/types/pass_key.h" #include "components/services/storage/public/cpp/buckets/bucket_info.h" #include "components/services/storage/public/cpp/buckets/constants.h" @@ -568,8 +567,8 @@ return; } - base::PostTaskAndReplyWithResult( - default_file_task_runner(), FROM_HERE, + default_file_task_runner()->PostTaskAndReplyWithResult( + FROM_HERE, // It is safe to pass Unretained(quota_util) since context owns it. base::BindOnce( &FileSystemQuotaUtil::DeleteStorageKeyDataOnFileTaskRunner,
diff --git a/storage/browser/file_system/filesystem_proxy_file_stream_reader.cc b/storage/browser/file_system/filesystem_proxy_file_stream_reader.cc index 876c531b..a785740 100644 --- a/storage/browser/file_system/filesystem_proxy_file_stream_reader.cc +++ b/storage/browser/file_system/filesystem_proxy_file_stream_reader.cc
@@ -13,7 +13,6 @@ #include "base/location.h" #include "base/metrics/histogram_macros.h" #include "base/task/task_runner.h" -#include "base/task/task_runner_util.h" #include "base/types/pass_key.h" #include "net/base/file_stream.h" #include "net/base/io_buffer.h" @@ -104,8 +103,8 @@ int64_t FilesystemProxyFileStreamReader::GetLength( net::Int64CompletionOnceCallback callback) { - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DoGetFileInfo, file_path_, shared_filesystem_proxy_), base::BindOnce( &FilesystemProxyFileStreamReader::DidGetFileInfoForGetLength, @@ -152,8 +151,8 @@ } callback_ = std::move(callback); - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DoOpenFile, file_path_, shared_filesystem_proxy_), base::BindOnce(&FilesystemProxyFileStreamReader::DidOpenFile, weak_factory_.GetWeakPtr()));
diff --git a/storage/browser/file_system/local_file_stream_reader.cc b/storage/browser/file_system/local_file_stream_reader.cc index 7c48e9e..b0f7ede 100644 --- a/storage/browser/file_system/local_file_stream_reader.cc +++ b/storage/browser/file_system/local_file_stream_reader.cc
@@ -16,7 +16,6 @@ #include "base/task/bind_post_task.h" #include "base/task/sequenced_task_runner.h" #include "base/task/task_runner.h" -#include "base/task/task_runner_util.h" #include "base/types/pass_key.h" #include "components/file_access/scoped_file_access_delegate.h" #include "net/base/file_stream.h" @@ -72,8 +71,8 @@ int64_t LocalFileStreamReader::GetLength( net::Int64CompletionOnceCallback callback) { - bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, base::BindOnce(&DoGetFileInfo, file_path_), + bool posted = task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&DoGetFileInfo, file_path_), base::BindOnce(&LocalFileStreamReader::DidGetFileInfoForGetLength, weak_factory_.GetWeakPtr(), std::move(callback))); DCHECK(posted);
diff --git a/storage/browser/quota/quota_manager_impl.cc b/storage/browser/quota/quota_manager_impl.cc index 194692a..3eb3a6a 100644 --- a/storage/browser/quota/quota_manager_impl.cc +++ b/storage/browser/quota/quota_manager_impl.cc
@@ -37,7 +37,6 @@ #include "base/task/bind_post_task.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/thread_annotations.h" #include "base/threading/thread_restrictions.h" @@ -1745,8 +1744,8 @@ return; is_bootstrapping_database_ = true; - base::PostTaskAndReplyWithResult( - db_runner_.get(), FROM_HERE, + db_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&QuotaDatabase::IsBootstrapped, base::Unretained(database_.get())), base::BindOnce(&QuotaManagerImpl::DidGetBootstrapFlag, @@ -2598,8 +2597,8 @@ weak_factory_.GetWeakPtr())); return; } - base::PostTaskAndReplyWithResult( - db_runner_.get(), FROM_HERE, + db_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&QuotaManagerImpl::CallGetVolumeInfo, get_volume_info_fn_, profile_path_), base::BindOnce(&QuotaManagerImpl::DidGetStorageCapacity, @@ -2666,8 +2665,8 @@ db_error_count_ = 0; // Wipe the database before triggering another bootstrap. - base::PostTaskAndReplyWithResult( - db_runner_.get(), FROM_HERE, + db_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&QuotaDatabase::RazeAndReopen, base::Unretained(database_.get())), base::BindOnce(&QuotaManagerImpl::DidRazeForReBootstrap, @@ -2888,8 +2887,8 @@ return; } - base::PostTaskAndReplyWithResult( - db_runner_.get(), from_here, + db_runner_->PostTaskAndReplyWithResult( + from_here, base::BindOnce(std::move(task), base::Unretained(database_.get())), std::move(reply)); } @@ -2917,8 +2916,8 @@ return; } - base::PostTaskAndReplyWithResult( - db_runner_.get(), from_here, + db_runner_->PostTaskAndReplyWithResult( + from_here, base::BindOnce(std::move(task), base::Unretained(database_.get())), std::move(reply)); }
diff --git a/styleguide/c++/c++-features.md b/styleguide/c++/c++-features.md index e17e901..51b646ab 100644 --- a/styleguide/c++/c++-features.md +++ b/styleguide/c++/c++-features.md
@@ -36,7 +36,6 @@ * **C++23:** _Not yet standardized_ * **Abseil:** _Default allowed; see banned/TBD features below_ - * absl::Cleanup: Initially supported February 4, 2021 * absl::AnyInvocable: Initially supported June 20, 2022 * Log library: Initially supported Aug 31, 2022 @@ -1911,24 +1910,6 @@ Overlaps with `base::RepeatingCallback`, `base::OnceCallback`. *** -### Cleanup <sup>[tbd]</sup> - -```c++ -FILE* sink_file = fopen(sink_path, "w"); -auto sink_closer = absl::MakeCleanup([sink_file] { fclose(sink_file); }); -``` - -**Description:** Implements the scope guard idiom, invoking the contained -callback's `operator()() &&` on scope exit. - -**Documentation:** -[cleanup.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/abseil-cpp/absl/cleanup/cleanup.h) - -**Notes:** -*** promo -Similar to `defer` in Golang. -*** - ### Containers <sup>[tbd]</sup> ```c++
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index 8a9aa267..63c0b0f1 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -5748,9 +5748,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "isolate_profile_data": true, "merge": { "args": [], @@ -5762,8 +5762,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [ @@ -5919,9 +5919,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "isolate_profile_data": true, "merge": { "args": [], @@ -5933,8 +5933,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [ @@ -6071,9 +6071,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "isolate_profile_data": true, "merge": { "args": [], @@ -6085,8 +6085,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index d9ef8d46..730b1d1 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -85345,9 +85345,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "isolate_profile_data": true, "merge": { "args": [], @@ -85359,8 +85359,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -85486,9 +85486,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "isolate_profile_data": true, "merge": { "args": [], @@ -85500,8 +85500,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -85613,9 +85613,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "isolate_profile_data": true, "merge": { "args": [], @@ -85627,8 +85627,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -86961,9 +86961,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -86974,8 +86974,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [ @@ -87132,9 +87132,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -87145,8 +87145,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [ @@ -87284,9 +87284,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -87297,8 +87297,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [ @@ -88822,9 +88822,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -88835,8 +88835,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [ @@ -88993,9 +88993,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -89006,8 +89006,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [ @@ -89145,9 +89145,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -89158,8 +89158,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [ @@ -89931,9 +89931,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -89944,8 +89944,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index f3eb8a6..7d4302f5 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -18614,11 +18614,11 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "isolate_profile_data": true, "merge": { "args": [], @@ -18630,8 +18630,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [ @@ -18799,11 +18799,11 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "isolate_profile_data": true, "merge": { "args": [], @@ -18815,8 +18815,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [ @@ -18961,11 +18961,11 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots" ], - "description": "Run with ash-chrome version 110.0.5445.0", + "description": "Run with ash-chrome version 110.0.5446.0", "isolate_profile_data": true, "merge": { "args": [], @@ -18977,8 +18977,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5445.0", - "revision": "version:110.0.5445.0" + "location": "lacros_version_skew_tests_v110.0.5446.0", + "revision": "version:110.0.5446.0" } ], "dimension_sets": [
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index e7b2ee4a..091f977 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -7036,7 +7036,8 @@ 'lacros_all_tast_tests': { 'variants': [ 'LACROS_JACUZZI', - ] + ], + 'ci_only': True, }, },
diff --git a/testing/buildbot/variants.pyl b/testing/buildbot/variants.pyl index 76bb2369..551f2256 100644 --- a/testing/buildbot/variants.pyl +++ b/testing/buildbot/variants.pyl
@@ -22,16 +22,16 @@ }, 'LACROS_VERSION_SKEW_CANARY': { 'args': [ - '--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5445.0/test_ash_chrome', + '--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5446.0/test_ash_chrome', ], - 'description': 'Run with ash-chrome version 110.0.5445.0', + 'description': 'Run with ash-chrome version 110.0.5446.0', 'identifier': 'Lacros version skew testing ash canary', 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/linux-ash-chromium/x86_64/ash.zip', - 'location': 'lacros_version_skew_tests_v110.0.5445.0', - 'revision': 'version:110.0.5445.0', + 'location': 'lacros_version_skew_tests_v110.0.5446.0', + 'revision': 'version:110.0.5446.0', }, ], },
diff --git a/testing/rust_gtest_interop/rust_gtest_interop.rs b/testing/rust_gtest_interop/rust_gtest_interop.rs index 44efe95..40e42c1c 100644 --- a/testing/rust_gtest_interop/rust_gtest_interop.rs +++ b/testing/rust_gtest_interop/rust_gtest_interop.rs
@@ -63,26 +63,6 @@ #[doc(hidden)] pub struct OpaqueTestingTest(u8); -/// Implements casting from a `&mut OpaqueTestingTest` to a `&mut T` when `T: TestSuite`. -/// Implementing TestSuite for a Rust type `T` promises that `T` is an FFI wrapper around a C++ -/// class which subclasses `testing::Test`, which makes this casting okay. -impl<T: TestSuite> AsMut<T> for OpaqueTestingTest { - fn as_mut(&mut self) -> &mut T { - // SAFETY: This horrible casting situation is okay because: - // 1) The Rust type is a wrapper around a C++ type. It's repr(C) and we can cast to the Rust - // type. - // 2) OpaqueTestingTest is a placeholder pointer to represent `testing::Test` which is the - // base class of the C++ type the Rust type is wrapping. - // 3) So this acts as a C++ downcast to the C++ type, and then a cast to the Rust wrapper - // type. - // 4) We've been given a &mut reference, and we reborrow it. The reborrow sits higher on the - // "borrow stack" and will be discarded first as well. - // 5) C++ wrapper types are not Unpin because C++ types are not Unpin, so the type we're - // casting to won't be moved by Rust incorrectly. - unsafe { &mut *(self as *mut OpaqueTestingTest as *mut T) } - } -} - #[doc(hidden)] pub trait TestResult { fn into_error_message(self) -> Option<String>;
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index ecd8a10b..cc55ff10 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -3058,7 +3058,8 @@ { "name": "Enabled", "enable_features": [ - "CompositeBGColorAnimation" + "CompositeBGColorAnimation", + "NativePaintUsesCompositorPriority" ] } ] @@ -4473,6 +4474,26 @@ ] } ], + "ExtensionTelemetryCookiesSignalStudy": [ + { + "platforms": [ + "chromeos", + "chromeos_lacros", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "SafeBrowsingExtensionTelemetryCookiesGetAllSignal", + "SafeBrowsingExtensionTelemetryCookiesGetSignal" + ] + } + ] + } + ], "ExtensionTelemetryStudyPersistence": [ { "platforms": [ @@ -4555,6 +4576,24 @@ ] } ], + "FeedPerformanceStudy": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "Enabled", + "params": { + "useIncrementalMount": "false" + }, + "enable_features": [ + "FeedPerformanceStudy" + ] + } + ] + } + ], "FeedPositionAndroid": [ { "platforms": [ @@ -5362,19 +5401,40 @@ ], "experiments": [ { - "name": "Enabled", + "name": "Full Color", "enable_features": [ "AutofillBrandingIOS" ] }, { - "name": "Enabled (Monotone)", + "name": "Full Color - Profile Icon Disabled", + "enable_features": [ + "AutofillBrandingIOS" + ], + "disable_features": [ + "AutofillUseConsistentPopupSettingsIcons" + ] + }, + { + "name": "Monotone", "params": { "ios-autofill-branding-monotones": "true" }, "enable_features": [ "AutofillBrandingIOS" ] + }, + { + "name": "Monotone - Profile Icon Disabled", + "params": { + "ios-autofill-branding-monotones": "true" + }, + "enable_features": [ + "AutofillBrandingIOS" + ], + "disable_features": [ + "AutofillUseConsistentPopupSettingsIcons" + ] } ] }
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index aeefbd4..a84695c 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -805,7 +805,7 @@ // the delay. BASE_FEATURE(kDelayFirstParkingOfStrings, "DelayFirstParkingOfStrings", - base::FEATURE_DISABLED_BY_DEFAULT); + base::FEATURE_ENABLED_BY_DEFAULT); bool ParkableStringsUseSnappy() { return base::FeatureList::IsEnabled(kUseSnappyForParkableStrings); @@ -879,12 +879,6 @@ "LoadingTasksUnfreezable", base::FEATURE_ENABLED_BY_DEFAULT); -// Controls how max frame rates are enforced in MediaStreamTracks. -// TODO(crbug.com/1152307): Remove in M91. -BASE_FEATURE(kMediaStreamTrackUseConfigMaxFrameRate, - "MediaStreamTrackUseConfigMaxFrameRate", - base::FEATURE_DISABLED_BY_DEFAULT); - // When enabled, the SubresourceFilter receives calls from the ResourceLoader // to perform additional checks against any aliases found from DNS CNAME records // for the requested URL.
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index 976045a..a78b06c8 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -364,9 +364,6 @@ BLINK_COMMON_EXPORT BASE_DECLARE_FEATURE(kTargetBlankImpliesNoOpener); -BLINK_COMMON_EXPORT BASE_DECLARE_FEATURE( - kMediaStreamTrackUseConfigMaxFrameRate); - // Performs additional SubresourceFilter checks when CNAME aliases are found // for the host of a requested URL. BLINK_COMMON_EXPORT BASE_DECLARE_FEATURE(
diff --git a/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.h b/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.h index a526d704..ef09af37 100644 --- a/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.h +++ b/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.h
@@ -38,8 +38,7 @@ class MutableCSSPropertyValueSet; class StyleSheetContents; -class CORE_EXPORT AbstractPropertySetCSSStyleDeclaration - : public CSSStyleDeclaration { +class AbstractPropertySetCSSStyleDeclaration : public CSSStyleDeclaration { public: virtual Element* ParentElement() const { return nullptr; } StyleSheetContents* ContextStyleSheet() const;
diff --git a/third_party/blink/renderer/core/css/css_style_declaration.cc b/third_party/blink/renderer/core/css/css_style_declaration.cc index 0cfd79e..d4c5b47 100644 --- a/third_party/blink/renderer/core/css/css_style_declaration.cc +++ b/third_party/blink/renderer/core/css/css_style_declaration.cc
@@ -37,7 +37,6 @@ #include "third_party/blink/renderer/core/css/css_property_names.h" #include "third_party/blink/renderer/core/css/css_style_declaration.h" #include "third_party/blink/renderer/core/css/css_value.h" -#include "third_party/blink/renderer/core/css/known_exposed_properties.h" #include "third_party/blink/renderer/core/css/parser/css_parser.h" #include "third_party/blink/renderer/core/css/properties/css_property.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" @@ -144,14 +143,7 @@ ParseCSSPropertyID(execution_context, name); if (unresolved_property == CSSPropertyID::kVariable) unresolved_property = CSSPropertyID::kInvalid; - // Only cache known-exposed properties (i.e. properties without any - // associated runtime flag). This is because the web-exposure of properties - // that are not known-exposed can change dynamically, for example when - // different ExecutionContexts are provided with different origin trial - // settings. - if (kKnownExposedProperties.Has(unresolved_property)) { - map.insert(name, unresolved_property); - } + map.insert(name, unresolved_property); DCHECK(!IsValidCSSPropertyID(unresolved_property) || CSSProperty::Get(ResolveCSSPropertyID(unresolved_property)) .IsWebExposed(execution_context));
diff --git a/third_party/blink/renderer/core/css/css_style_declaration_test.cc b/third_party/blink/renderer/core/css/css_style_declaration_test.cc index 854a533a..ae3e8c4e 100644 --- a/third_party/blink/renderer/core/css/css_style_declaration_test.cc +++ b/third_party/blink/renderer/core/css/css_style_declaration_test.cc
@@ -5,18 +5,11 @@ #include "third_party/blink/renderer/core/css/css_style_declaration.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/renderer/bindings/core/v8/script_value.h" -#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" -#include "third_party/blink/renderer/core/css/css_computed_style_declaration.h" -#include "third_party/blink/renderer/core/css/css_property_value_set.h" #include "third_party/blink/renderer/core/css/css_rule_list.h" #include "third_party/blink/renderer/core/css/css_style_rule.h" #include "third_party/blink/renderer/core/css/css_test_helpers.h" -#include "third_party/blink/renderer/core/css/property_set_css_style_declaration.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/execution_context/security_context.h" -#include "third_party/blink/renderer/platform/bindings/v8_binding.h" -#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" namespace blink { @@ -60,47 +53,4 @@ EXPECT_FALSE(exception_state.HadException()); } -// CSSStyleDeclaration has a cache which maps e.g. backgroundPositionY to -// its associated CSSPropertyID. -// -// See CssPropertyInfo in css_style_declaration.cc. -TEST(CSSStyleDeclarationTest, ExposureCacheLeak) { - V8TestingScope v8_testing_scope; - - auto* property_value_set = MakeGarbageCollected<MutableCSSPropertyValueSet>( - CSSParserMode::kHTMLStandardMode); - auto* style = MakeGarbageCollected<PropertySetCSSStyleDeclaration>( - v8_testing_scope.GetExecutionContext(), *property_value_set); - - ScriptState* script_state = v8_testing_scope.GetScriptState(); - v8::Isolate* isolate = v8_testing_scope.GetIsolate(); - - ScriptValue normal(isolate, V8String(isolate, "normal")); - - DummyExceptionStateForTesting exception_state; - - { - ScopedOriginTrialsSampleAPIForTest scoped_feature(true); - EXPECT_TRUE( - style->NamedPropertyQuery("originTrialTestProperty", exception_state)); - EXPECT_EQ(NamedPropertySetterResult::kIntercepted, - style->AnonymousNamedSetter(script_state, - "originTrialTestProperty", normal)); - EXPECT_EQ("normal", style->AnonymousNamedGetter("originTrialTestProperty")); - } - - { - ScopedOriginTrialsSampleAPIForTest scoped_feature(false); - // Now that the feature is disabled, 'originTrialTestProperty' must not - // be usable just because it was enabled and accessed previously. - EXPECT_FALSE( - style->NamedPropertyQuery("originTrialTestProperty", exception_state)); - EXPECT_EQ(NamedPropertySetterResult::kDidNotIntercept, - style->AnonymousNamedSetter(script_state, - "originTrialTestProperty", normal)); - EXPECT_EQ(g_null_atom, - style->AnonymousNamedGetter("originTrialTestProperty")); - } -} - } // namespace blink
diff --git a/third_party/blink/renderer/core/css/property_set_css_style_declaration.h b/third_party/blink/renderer/core/css/property_set_css_style_declaration.h index 4a8dcc5e..0c820fd 100644 --- a/third_party/blink/renderer/core/css/property_set_css_style_declaration.h +++ b/third_party/blink/renderer/core/css/property_set_css_style_declaration.h
@@ -32,7 +32,7 @@ class MutableCSSPropertyValueSet; -class CORE_EXPORT PropertySetCSSStyleDeclaration +class PropertySetCSSStyleDeclaration : public AbstractPropertySetCSSStyleDeclaration { public: PropertySetCSSStyleDeclaration(ExecutionContext* execution_context,
diff --git a/third_party/blink/renderer/core/dom/abort_signal_test.cc b/third_party/blink/renderer/core/dom/abort_signal_test.cc index 7962363..cb92ebb 100644 --- a/third_party/blink/renderer/core/dom/abort_signal_test.cc +++ b/third_party/blink/renderer/core/dom/abort_signal_test.cc
@@ -141,17 +141,17 @@ EXPECT_EQ(count, GetParam() == TestType::kRemoveEnabled ? 0 : 1); } -INSTANTIATE_TEST_CASE_P(, - AbortSignalTest, - testing::Values(TestType::kRemoveEnabled, - TestType::kRemoveDisabled), - [](const testing::TestParamInfo<TestType>& info) { - switch (info.param) { - case TestType::kRemoveEnabled: - return "RemoveEnabled"; - case TestType::kRemoveDisabled: - return "RemoveDisabled"; - } - }); +INSTANTIATE_TEST_SUITE_P(, + AbortSignalTest, + testing::Values(TestType::kRemoveEnabled, + TestType::kRemoveDisabled), + [](const testing::TestParamInfo<TestType>& info) { + switch (info.param) { + case TestType::kRemoveEnabled: + return "RemoveEnabled"; + case TestType::kRemoveDisabled: + return "RemoveDisabled"; + } + }); } // namespace blink
diff --git a/third_party/blink/renderer/core/editing/finder/find_buffer.h b/third_party/blink/renderer/core/editing/finder/find_buffer.h index 0c4c056..7a8425c 100644 --- a/third_party/blink/renderer/core/editing/finder/find_buffer.h +++ b/third_party/blink/renderer/core/editing/finder/find_buffer.h
@@ -78,11 +78,16 @@ const String& search_text, const blink::FindOptions options); - class CORE_EXPORT Iterator - : public std::iterator<std::forward_iterator_tag, BufferMatchResult> { + class CORE_EXPORT Iterator { STACK_ALLOCATED(); public: + using iterator_category = std::forward_iterator_tag; + using value_type = BufferMatchResult; + using difference_type = std::ptrdiff_t; + using pointer = BufferMatchResult*; + using reference = BufferMatchResult&; + Iterator() = default; Iterator(const FindBuffer& find_buffer, TextSearcherICU* text_searcher,
diff --git a/third_party/blink/renderer/core/editing/markers/document_marker.h b/third_party/blink/renderer/core/editing/markers/document_marker.h index 4712a5d..26ad6bb 100644 --- a/third_party/blink/renderer/core/editing/markers/document_marker.h +++ b/third_party/blink/renderer/core/editing/markers/document_marker.h
@@ -61,9 +61,14 @@ kCustomHighlight = 1 << kCustomHighlightMarkerIndex }; - class MarkerTypesIterator - : public std::iterator<std::forward_iterator_tag, MarkerType> { + class MarkerTypesIterator { public: + using iterator_category = std::forward_iterator_tag; + using value_type = MarkerType; + using difference_type = std::ptrdiff_t; + using pointer = MarkerType*; + using reference = MarkerType&; + explicit MarkerTypesIterator(unsigned marker_types) : remaining_types_(marker_types) {} MarkerTypesIterator(const MarkerTypesIterator& other) = default;
diff --git a/third_party/blink/renderer/core/editing/text_offset_mapping.h b/third_party/blink/renderer/core/editing/text_offset_mapping.h index 731f66c..1d28948 100644 --- a/third_party/blink/renderer/core/editing/text_offset_mapping.h +++ b/third_party/blink/renderer/core/editing/text_offset_mapping.h
@@ -96,11 +96,16 @@ STACK_ALLOCATED(); public: - class CORE_EXPORT Iterator - : public std::iterator<std::input_iterator_tag, InlineContents> { + class CORE_EXPORT Iterator { STACK_ALLOCATED(); public: + using iterator_category = std::input_iterator_tag; + using value_type = InlineContents; + using difference_type = std::ptrdiff_t; + using pointer = InlineContents*; + using reference = InlineContents&; + explicit Iterator(const InlineContents& current) : current_(current) {} Iterator() = default; @@ -133,11 +138,16 @@ STACK_ALLOCATED(); public: - class CORE_EXPORT Iterator - : public std::iterator<std::forward_iterator_tag, InlineContents> { + class CORE_EXPORT Iterator { STACK_ALLOCATED(); public: + using iterator_category = std::forward_iterator_tag; + using value_type = InlineContents; + using difference_type = std::ptrdiff_t; + using pointer = InlineContents*; + using reference = InlineContents&; + explicit Iterator(const InlineContents& current) : current_(current) {} Iterator() = default;
diff --git a/third_party/blink/renderer/core/html/forms/html_form_control_element.cc b/third_party/blink/renderer/core/html/forms/html_form_control_element.cc index e254b9c..cee7313 100644 --- a/third_party/blink/renderer/core/html/forms/html_form_control_element.cc +++ b/third_party/blink/renderer/core/html/forms/html_form_control_element.cc
@@ -391,12 +391,14 @@ // not a triggering element, then the light dismiss code will hide the // popover and set focus to the previously focused element, then the // normal focus management code will reset focus to the clicked control. - bool can_show = !popover.element->popoverOpen() && - (popover.action == PopoverTriggerAction::kToggle || - popover.action == PopoverTriggerAction::kShow); - bool can_hide = popover.element->popoverOpen() && - (popover.action == PopoverTriggerAction::kToggle || - popover.action == PopoverTriggerAction::kHide); + bool can_show = + popover.element->IsPopoverReady(PopoverTriggerAction::kShow) && + (popover.action == PopoverTriggerAction::kToggle || + popover.action == PopoverTriggerAction::kShow); + bool can_hide = + popover.element->IsPopoverReady(PopoverTriggerAction::kHide) && + (popover.action == PopoverTriggerAction::kToggle || + popover.action == PopoverTriggerAction::kHide); if (event.type() == event_type_names::kDOMActivate && (!Form() || !IsSuccessfulSubmitButton())) { if (can_hide) {
diff --git a/third_party/blink/renderer/core/html/html_element.cc b/third_party/blink/renderer/core/html/html_element.cc index 8fb15ca2..32c6427 100644 --- a/third_party/blink/renderer/core/html/html_element.cc +++ b/third_party/blink/renderer/core/html/html_element.cc
@@ -1242,20 +1242,55 @@ return false; } +const char* HTMLElement::IsPopoverNotReady( + PopoverTriggerAction action, + DOMExceptionCode& exception_code) const { + DCHECK(RuntimeEnabledFeatures::HTMLPopoverAttributeEnabled( + GetDocument().GetExecutionContext())); + DCHECK_NE(action, PopoverTriggerAction::kNone); + DCHECK_NE(action, PopoverTriggerAction::kToggle); + if (!HasPopoverAttribute()) { + exception_code = DOMExceptionCode::kNotSupportedError; + return "Not supported on elements that do not have a valid value for the " + "'popover' attribute"; + } + exception_code = DOMExceptionCode::kInvalidStateError; + if (!isConnected()) { + return "Invalid on disconnected popover elements"; + } + if (action == PopoverTriggerAction::kShow && popoverOpen()) { + return "Invalid on already-showing popover elements"; + } + if (action == PopoverTriggerAction::kHide && + GetPopoverData()->visibilityState() != PopoverVisibilityState::kShowing) { + // Important to check that visibility is not kShowing (rather than + // popoverOpen()), because a hide transition might have been started on this + // popover already, and we don't want to allow a double-hide. + return "Invalid on popover elements that aren't already showing"; + } + if (action == PopoverTriggerAction::kShow && IsA<HTMLDialogElement>(this) && + hasAttribute(html_names::kOpenAttr)) { + return "The dialog is already open as a dialog, and therefore cannot be " + "opened as a popover."; + } + if (action == PopoverTriggerAction::kShow && + Fullscreen::IsFullscreenElement(*this)) { + return "This element is already in fullscreen mode, and therefore cannot " + "be " + "opened as a popover."; + } + return nullptr; +} + +bool HTMLElement::IsPopoverReady(PopoverTriggerAction action) const { + DOMExceptionCode exception_code; + return !IsPopoverNotReady(action, exception_code); +} + void HTMLElement::togglePopover(ExceptionState& exception_state) { DCHECK(RuntimeEnabledFeatures::HTMLPopoverAttributeEnabled( GetDocument().GetExecutionContext())); - if (!HasPopoverAttribute()) { - return exception_state.ThrowDOMException( - DOMExceptionCode::kNotSupportedError, - "Not supported on elements that do not have a valid value for the " - "'popover' attribute"); - } else if (!isConnected()) { - return exception_state.ThrowDOMException( - DOMExceptionCode::kInvalidStateError, - "Invalid disconnected popover elements"); - } - if (popoverOpen()) { + if (HasPopoverAttribute() && popoverOpen()) { hidePopover(exception_state); } else { showPopover(exception_state); @@ -1273,28 +1308,10 @@ void HTMLElement::showPopover(ExceptionState& exception_state) { DCHECK(RuntimeEnabledFeatures::HTMLPopoverAttributeEnabled( GetDocument().GetExecutionContext())); - if (!HasPopoverAttribute()) { - return exception_state.ThrowDOMException( - DOMExceptionCode::kNotSupportedError, - "Not supported on elements that do not have a valid value for the " - "'popover' attribute"); - } - if (popoverOpen() || !isConnected()) { - return exception_state.ThrowDOMException( - DOMExceptionCode::kInvalidStateError, - "Invalid on already-showing or disconnected popover elements"); - } - if (IsA<HTMLDialogElement>(this) && hasAttribute(html_names::kOpenAttr)) { - return exception_state.ThrowDOMException( - DOMExceptionCode::kInvalidStateError, - "The dialog is already open as a dialog, and therefore cannot be " - "opened as a popover."); - } - if (Fullscreen::IsFullscreenElement(*this)) { - return exception_state.ThrowDOMException( - DOMExceptionCode::kInvalidStateError, - "This element is already in fullscreen mode, and therefore cannot be " - "opened as a popover."); + DOMExceptionCode exception_code; + if (auto* error = + IsPopoverNotReady(PopoverTriggerAction::kShow, exception_code)) { + return exception_state.ThrowDOMException(exception_code, error); } // Fire the popovershow event (bubbles, cancelable). @@ -1419,19 +1436,10 @@ void HTMLElement::hidePopover(ExceptionState& exception_state) { DCHECK(RuntimeEnabledFeatures::HTMLPopoverAttributeEnabled( GetDocument().GetExecutionContext())); - if (!HasPopoverAttribute()) { - return exception_state.ThrowDOMException( - DOMExceptionCode::kNotSupportedError, - "Not supported on elements that do not have a valid value for the " - "'popover' attribute"); - } else if (GetPopoverData()->visibilityState() != - PopoverVisibilityState::kShowing) { - // Important to check that visibility is not kShowing (rather than - // popoverOpen()), because a hide transition might have been started on this - // popover already, and we don't want to allow a double-hide. - return exception_state.ThrowDOMException( - DOMExceptionCode::kInvalidStateError, - "Invalid on popover elements that aren't already showing"); + DOMExceptionCode exception_code; + if (auto* error = + IsPopoverNotReady(PopoverTriggerAction::kHide, exception_code)) { + return exception_state.ThrowDOMException(exception_code, error); } HidePopoverInternal(HidePopoverFocusBehavior::kFocusPreviousElement, HidePopoverForcingLevel::kHideAfterAnimations);
diff --git a/third_party/blink/renderer/core/html/html_element.h b/third_party/blink/renderer/core/html/html_element.h index 0200d59f..9a4aeb69 100644 --- a/third_party/blink/renderer/core/html/html_element.h +++ b/third_party/blink/renderer/core/html/html_element.h
@@ -219,6 +219,9 @@ bool HasPopoverAttribute() const; PopoverValueType PopoverType() const; bool popoverOpen() const; + const char* IsPopoverNotReady(PopoverTriggerAction action, + DOMExceptionCode& exception_code) const; + bool IsPopoverReady(PopoverTriggerAction action) const; void togglePopover(ExceptionState& exception_state); void showPopover(ExceptionState& exception_state); void hidePopover(ExceptionState& exception_state);
diff --git a/third_party/blink/renderer/core/layout/layout_box.h b/third_party/blink/renderer/core/layout/layout_box.h index 0f96c0bd..2df6c79 100644 --- a/third_party/blink/renderer/core/layout/layout_box.h +++ b/third_party/blink/renderer/core/layout/layout_box.h
@@ -1281,9 +1281,14 @@ wtf_size_t IndexOf(const NGPhysicalBoxFragment& fragment) const; bool Contains(const NGPhysicalBoxFragment& fragment) const; - class CORE_EXPORT Iterator : public std::iterator<std::forward_iterator_tag, - NGPhysicalBoxFragment> { + class CORE_EXPORT Iterator { public: + using iterator_category = std::forward_iterator_tag; + using value_type = NGPhysicalBoxFragment; + using difference_type = std::ptrdiff_t; + using pointer = NGPhysicalBoxFragment*; + using reference = NGPhysicalBoxFragment&; + explicit Iterator(const NGLayoutResultList::const_iterator& iterator) : iterator_(iterator) {}
diff --git a/third_party/blink/renderer/core/style/style_fetched_image.cc b/third_party/blink/renderer/core/style/style_fetched_image.cc index 1d4ae45..98c1651 100644 --- a/third_party/blink/renderer/core/style/style_fetched_image.cc +++ b/third_party/blink/renderer/core/style/style_fetched_image.cc
@@ -124,7 +124,7 @@ multiplier /= image_->DevicePixelRatioHeaderValue(); } if (auto* svg_image = DynamicTo<SVGImage>(image)) { - return ImageSizeForSVGImage(svg_image, multiplier, default_object_size); + return ImageSizeForSVGImage(*svg_image, multiplier, default_object_size); } respect_orientation = ForceOrientationIfNecessary(respect_orientation); gfx::SizeF size(image->Size(respect_orientation));
diff --git a/third_party/blink/renderer/core/style/style_fetched_image_set.cc b/third_party/blink/renderer/core/style/style_fetched_image_set.cc index d37ee98..2ce90eaa 100644 --- a/third_party/blink/renderer/core/style/style_fetched_image_set.cc +++ b/third_party/blink/renderer/core/style/style_fetched_image_set.cc
@@ -108,7 +108,7 @@ RespectImageOrientationEnum respect_orientation) const { Image* image = best_fit_image_->GetImage(); if (auto* svg_image = DynamicTo<SVGImage>(image)) { - return ImageSizeForSVGImage(svg_image, multiplier, default_object_size); + return ImageSizeForSVGImage(*svg_image, multiplier, default_object_size); } respect_orientation = ForceOrientationIfNecessary(respect_orientation); gfx::SizeF natural_size(image->Size(respect_orientation));
diff --git a/third_party/blink/renderer/core/style/style_image.cc b/third_party/blink/renderer/core/style/style_image.cc index 632f8ea..1531db7 100644 --- a/third_party/blink/renderer/core/style/style_image.cc +++ b/third_party/blink/renderer/core/style/style_image.cc
@@ -5,36 +5,32 @@ #include "third_party/blink/renderer/core/style/style_image.h" #include "third_party/blink/renderer/core/svg/graphics/svg_image.h" -#include "third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h" -#include "third_party/blink/renderer/platform/geometry/layout_size.h" namespace blink { -gfx::SizeF StyleImage::ApplyZoom(const gfx::SizeF& size, - float multiplier) const { - if (multiplier == 1.0f || !HasIntrinsicSize()) +gfx::SizeF StyleImage::ApplyZoom(const gfx::SizeF& size, float multiplier) { + if (multiplier == 1.0f) return size; - float width = size.width() * multiplier; - float height = size.height() * multiplier; + gfx::SizeF scaled_size = gfx::ScaleSize(size, multiplier); // Don't let images that have a width/height >= 1 shrink below 1 when zoomed. if (size.width() > 0) - width = std::max(1.0f, width); + scaled_size.set_width(std::max(1.0f, scaled_size.width())); if (size.height() > 0) - height = std::max(1.0f, height); + scaled_size.set_height(std::max(1.0f, scaled_size.height())); - return gfx::SizeF(width, height); + return scaled_size; } gfx::SizeF StyleImage::ImageSizeForSVGImage( - SVGImage* svg_image, + const SVGImage& svg_image, float multiplier, - const gfx::SizeF& default_object_size) const { + const gfx::SizeF& default_object_size) { gfx::SizeF unzoomed_default_object_size = gfx::ScaleSize(default_object_size, 1 / multiplier); - return ApplyZoom(svg_image->ConcreteObjectSize(unzoomed_default_object_size), + return ApplyZoom(svg_image.ConcreteObjectSize(unzoomed_default_object_size), multiplier); }
diff --git a/third_party/blink/renderer/core/style/style_image.h b/third_party/blink/renderer/core/style/style_image.h index 143b43c8..72709e8d 100644 --- a/third_party/blink/renderer/core/style/style_image.h +++ b/third_party/blink/renderer/core/style/style_image.h
@@ -184,10 +184,10 @@ virtual bool IsEqual(const StyleImage&) const = 0; - gfx::SizeF ApplyZoom(const gfx::SizeF&, float multiplier) const; - gfx::SizeF ImageSizeForSVGImage(SVGImage*, - float multiplier, - const gfx::SizeF& default_object_size) const; + static gfx::SizeF ApplyZoom(const gfx::SizeF&, float multiplier); + static gfx::SizeF ImageSizeForSVGImage(const SVGImage&, + float multiplier, + const gfx::SizeF& default_object_size); }; } // namespace blink
diff --git a/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc b/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc index 28316342c4..2e159d5a 100644 --- a/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc +++ b/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc
@@ -558,23 +558,15 @@ cached_min_ = kInvalidCachedTime; } else if (name == svg_names::kMaxAttr) { cached_max_ = kInvalidCachedTime; + } else if (SVGURIReference::IsKnownAttribute(name)) { + // TODO(fs): Could be smarter here when 'href' is specified and 'xlink:href' + // is changed. + BuildPendingResource(); } else { SVGElement::ParseAttribute(params); } } -void SVGSMILElement::SvgAttributeChanged( - const SvgAttributeChangedParams& params) { - if (SVGURIReference::IsKnownAttribute(params.name)) { - // TODO(fs): Could be smarter here when 'href' is specified and 'xlink:href' - // is changed. - SVGElement::InvalidationGuard invalidation_guard(this); - BuildPendingResource(); - return; - } - SVGElement::SvgAttributeChanged(params); -} - bool SVGSMILElement::IsPresentationAttribute( const QualifiedName& attr_name) const { // Don't map 'fill' to the 'fill' property for animation elements.
diff --git a/third_party/blink/renderer/core/svg/animation/svg_smil_element.h b/third_party/blink/renderer/core/svg/animation/svg_smil_element.h index befe7fa..ec273feb 100644 --- a/third_party/blink/renderer/core/svg/animation/svg_smil_element.h +++ b/third_party/blink/renderer/core/svg/animation/svg_smil_element.h
@@ -82,7 +82,6 @@ ~SVGSMILElement() override; void ParseAttribute(const AttributeModificationParams&) override; - void SvgAttributeChanged(const SvgAttributeChangedParams&) override; InsertionNotificationRequest InsertedInto(ContainerNode&) override; void RemovedFrom(ContainerNode&) override;
diff --git a/third_party/blink/renderer/modules/badging/navigator_badge.cc b/third_party/blink/renderer/modules/badging/navigator_badge.cc index f18bfeb..7e69f3d 100644 --- a/third_party/blink/renderer/modules/badging/navigator_badge.cc +++ b/third_party/blink/renderer/modules/badging/navigator_badge.cc
@@ -7,12 +7,12 @@ #include "build/build_config.h" #include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" -#include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/navigator.h" #include "third_party/blink/renderer/core/workers/worker_navigator.h" #include "third_party/blink/renderer/platform/bindings/exception_code.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" namespace blink { @@ -36,42 +36,52 @@ // static ScriptPromise NavigatorBadge::setAppBadge(ScriptState* script_state, - Navigator& /*navigator*/) { - return SetAppBadgeHelper(script_state, mojom::blink::BadgeValue::NewFlag(0)); -} - -// static -ScriptPromise NavigatorBadge::setAppBadge(ScriptState* script_state, - WorkerNavigator& /*navigator*/) { - return SetAppBadgeHelper(script_state, mojom::blink::BadgeValue::NewFlag(0)); -} - -// static -ScriptPromise NavigatorBadge::setAppBadge(ScriptState* script_state, Navigator& /*navigator*/, - uint64_t content) { - return SetAppBadgeHelper(script_state, - mojom::blink::BadgeValue::NewNumber(content)); + ExceptionState& exception_state) { + return SetAppBadgeHelper(script_state, mojom::blink::BadgeValue::NewFlag(0), + exception_state); } // static ScriptPromise NavigatorBadge::setAppBadge(ScriptState* script_state, WorkerNavigator& /*navigator*/, - uint64_t content) { + ExceptionState& exception_state) { + return SetAppBadgeHelper(script_state, mojom::blink::BadgeValue::NewFlag(0), + exception_state); +} + +// static +ScriptPromise NavigatorBadge::setAppBadge(ScriptState* script_state, + Navigator& /*navigator*/, + uint64_t content, + ExceptionState& exception_state) { return SetAppBadgeHelper(script_state, - mojom::blink::BadgeValue::NewNumber(content)); + mojom::blink::BadgeValue::NewNumber(content), + exception_state); +} + +// static +ScriptPromise NavigatorBadge::setAppBadge(ScriptState* script_state, + WorkerNavigator& /*navigator*/, + uint64_t content, + ExceptionState& exception_state) { + return SetAppBadgeHelper(script_state, + mojom::blink::BadgeValue::NewNumber(content), + exception_state); } // static ScriptPromise NavigatorBadge::clearAppBadge(ScriptState* script_state, - Navigator& /*navigator*/) { - return ClearAppBadgeHelper(script_state); + Navigator& /*navigator*/, + ExceptionState& exception_state) { + return ClearAppBadgeHelper(script_state, exception_state); } // static ScriptPromise NavigatorBadge::clearAppBadge(ScriptState* script_state, - WorkerNavigator& /*navigator*/) { - return ClearAppBadgeHelper(script_state); + WorkerNavigator& /*navigator*/, + ExceptionState& exception_state) { + return ClearAppBadgeHelper(script_state, exception_state); } void NavigatorBadge::Trace(Visitor* visitor) const { @@ -81,15 +91,16 @@ // static ScriptPromise NavigatorBadge::SetAppBadgeHelper( ScriptState* script_state, - mojom::blink::BadgeValuePtr badge_value) { + mojom::blink::BadgeValuePtr badge_value, + ExceptionState& exception_state) { if (badge_value->is_number() && badge_value->get_number() == 0) - return ClearAppBadgeHelper(script_state); + return ClearAppBadgeHelper(script_state, exception_state); if (!IsAllowed(script_state)) { - return ScriptPromise::RejectWithDOMException( - script_state, MakeGarbageCollected<DOMException>( - DOMExceptionCode::kNotAllowedError, - "The badge API is not allowed in this context")); + exception_state.ThrowDOMException( + DOMExceptionCode::kNotAllowedError, + "The badge API is not allowed in this context"); + return ScriptPromise(); } #if !BUILDFLAG(IS_ANDROID) @@ -99,12 +110,14 @@ } // static -ScriptPromise NavigatorBadge::ClearAppBadgeHelper(ScriptState* script_state) { +ScriptPromise NavigatorBadge::ClearAppBadgeHelper( + ScriptState* script_state, + ExceptionState& exception_state) { if (!IsAllowed(script_state)) { - return ScriptPromise::RejectWithDOMException( - script_state, MakeGarbageCollected<DOMException>( - DOMExceptionCode::kNotAllowedError, - "The badge API is not allowed in this context")); + exception_state.ThrowDOMException( + DOMExceptionCode::kNotAllowedError, + "The badge API is not allowed in this context"); + return ScriptPromise(); } #if !BUILDFLAG(IS_ANDROID)
diff --git a/third_party/blink/renderer/modules/badging/navigator_badge.h b/third_party/blink/renderer/modules/badging/navigator_badge.h index fff90e1a..8eedadea 100644 --- a/third_party/blink/renderer/modules/badging/navigator_badge.h +++ b/third_party/blink/renderer/modules/badging/navigator_badge.h
@@ -12,6 +12,8 @@ #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { + +class ExceptionState; class Navigator; class ScriptPromise; class WorkerNavigator; @@ -25,24 +27,34 @@ explicit NavigatorBadge(ExecutionContext*); // Badge IDL interface. - static ScriptPromise setAppBadge(ScriptState*, Navigator&); - static ScriptPromise setAppBadge(ScriptState*, WorkerNavigator&); - - static ScriptPromise setAppBadge(ScriptState*, Navigator&, uint64_t content); + static ScriptPromise setAppBadge(ScriptState*, Navigator&, ExceptionState&); static ScriptPromise setAppBadge(ScriptState*, WorkerNavigator&, - uint64_t content); + ExceptionState&); - static ScriptPromise clearAppBadge(ScriptState*, Navigator&); - static ScriptPromise clearAppBadge(ScriptState*, WorkerNavigator&); + static ScriptPromise setAppBadge(ScriptState*, + Navigator&, + uint64_t content, + ExceptionState&); + static ScriptPromise setAppBadge(ScriptState*, + WorkerNavigator&, + uint64_t content, + ExceptionState&); + + static ScriptPromise clearAppBadge(ScriptState*, Navigator&, ExceptionState&); + static ScriptPromise clearAppBadge(ScriptState*, + WorkerNavigator&, + ExceptionState&); void Trace(Visitor*) const override; private: static ScriptPromise SetAppBadgeHelper( ScriptState* script_state, - mojom::blink::BadgeValuePtr badge_value); - static ScriptPromise ClearAppBadgeHelper(ScriptState* script_state); + mojom::blink::BadgeValuePtr badge_value, + ExceptionState& exception_state); + static ScriptPromise ClearAppBadgeHelper(ScriptState* script_state, + ExceptionState& exception_state); // Returns true if using the Badging API is allowed in this context. static bool IsAllowed(ScriptState* script_state);
diff --git a/third_party/blink/renderer/modules/badging/navigator_badge.idl b/third_party/blink/renderer/modules/badging/navigator_badge.idl index 75c58400..ec1b035c 100644 --- a/third_party/blink/renderer/modules/badging/navigator_badge.idl +++ b/third_party/blink/renderer/modules/badging/navigator_badge.idl
@@ -7,9 +7,9 @@ SecureContext, ImplementedAs=NavigatorBadge ] partial interface Navigator { - [CallWith=ScriptState, MeasureAs=BadgeSet] + [CallWith=ScriptState, MeasureAs=BadgeSet, RaisesException] Promise<void> setAppBadge(optional [EnforceRange] unsigned long long contents); - [CallWith=ScriptState, MeasureAs=BadgeClear] + [CallWith=ScriptState, MeasureAs=BadgeClear, RaisesException] Promise<void> clearAppBadge(); -}; \ No newline at end of file +};
diff --git a/third_party/blink/renderer/modules/badging/worker_navigator_badge.idl b/third_party/blink/renderer/modules/badging/worker_navigator_badge.idl index dffba30f..4fd1c27 100644 --- a/third_party/blink/renderer/modules/badging/worker_navigator_badge.idl +++ b/third_party/blink/renderer/modules/badging/worker_navigator_badge.idl
@@ -7,9 +7,9 @@ SecureContext, ImplementedAs=NavigatorBadge ] partial interface WorkerNavigator { - [Exposed=ServiceWorker, CallWith=ScriptState, MeasureAs=BadgeSet] + [Exposed=ServiceWorker, CallWith=ScriptState, MeasureAs=BadgeSet, RaisesException] Promise<void> setAppBadge(optional [EnforceRange] unsigned long long contents); - [Exposed=ServiceWorker, CallWith=ScriptState, MeasureAs=BadgeClear] + [Exposed=ServiceWorker, CallWith=ScriptState, MeasureAs=BadgeClear, RaisesException] Promise<void> clearAppBadge(); };
diff --git a/third_party/blink/renderer/modules/credentialmanagement/identity_credential.cc b/third_party/blink/renderer/modules/credentialmanagement/identity_credential.cc index f9c13a8..7a361f52 100644 --- a/third_party/blink/renderer/modules/credentialmanagement/identity_credential.cc +++ b/third_party/blink/renderer/modules/credentialmanagement/identity_credential.cc
@@ -81,7 +81,9 @@ WTF::String error = "Refused to connect to '" + provider_url.ElidedString() + - "' because it violates the document's Content Security Policy."; + "' because it violates the document (" + + resolver->GetExecutionContext()->GetSecurityOrigin()->ToString() + + ") Content Security Policy."; resolver->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kNetworkError, error)); return true;
diff --git a/third_party/blink/renderer/modules/locks/lock_manager.cc b/third_party/blink/renderer/modules/locks/lock_manager.cc index 4d88abd..ea17cf8 100644 --- a/third_party/blink/renderer/modules/locks/lock_manager.cc +++ b/third_party/blink/renderer/modules/locks/lock_manager.cc
@@ -351,34 +351,27 @@ CheckStorageAccessAllowed( context, resolver, - WTF::BindOnce(&LockManager::RequestImpl, WrapWeakPersistent(this), - WrapPersistent(resolver), WrapPersistent(options), name, - WrapPersistent(callback), mode)); + resolver->WrapCallbackInScriptScope(WTF::BindOnce( + &LockManager::RequestImpl, WrapWeakPersistent(this), + WrapPersistent(options), name, WrapPersistent(callback), mode))); // 12. Return promise. return promise; } -void LockManager::RequestImpl(ScriptPromiseResolver* resolver, - const LockOptions* options, +void LockManager::RequestImpl(const LockOptions* options, const String& name, V8LockGrantedCallback* callback, - mojom::blink::LockMode mode) { + mojom::blink::LockMode mode, + ScriptPromiseResolver* resolver) { ExecutionContext* context = resolver->GetExecutionContext(); - - if (!resolver->GetExecutionContext() || - resolver->GetExecutionContext()->IsContextDestroyed()) { - return; - } - if (!service_.is_bound()) { context->GetBrowserInterfaceBroker().GetInterface( service_.BindNewPipeAndPassReceiver( context->GetTaskRunner(TaskType::kMiscPlatformAPI))); if (!service_.is_bound()) { - resolver->Reject( - MakeGarbageCollected<DOMException>(DOMExceptionCode::kAbortError)); + resolver->RejectWithDOMException(DOMExceptionCode::kAbortError, ""); } } if (!observer_.is_bound()) { @@ -387,8 +380,7 @@ context->GetTaskRunner(TaskType::kMiscPlatformAPI))); if (!observer_.is_bound()) { - resolver->Reject( - MakeGarbageCollected<DOMException>(DOMExceptionCode::kAbortError)); + resolver->RejectWithDOMException(DOMExceptionCode::kAbortError, ""); } } @@ -450,26 +442,20 @@ CheckStorageAccessAllowed( context, resolver, - WTF::BindOnce(&LockManager::QueryImpl, WrapWeakPersistent(this), - WrapPersistent(resolver))); + resolver->WrapCallbackInScriptScope( + WTF::BindOnce(&LockManager::QueryImpl, WrapWeakPersistent(this)))); return promise; } void LockManager::QueryImpl(ScriptPromiseResolver* resolver) { ExecutionContext* context = resolver->GetExecutionContext(); - - if (!resolver->GetScriptState()->ContextIsValid()) { - return; - } - if (!service_.is_bound()) { context->GetBrowserInterfaceBroker().GetInterface( service_.BindNewPipeAndPassReceiver( context->GetTaskRunner(TaskType::kMiscPlatformAPI))); if (!service_.is_bound()) { - resolver->Reject( - MakeGarbageCollected<DOMException>(DOMExceptionCode::kAbortError)); + resolver->RejectWithDOMException(DOMExceptionCode::kAbortError, ""); } }
diff --git a/third_party/blink/renderer/modules/locks/lock_manager.h b/third_party/blink/renderer/modules/locks/lock_manager.h index fbccc5e..3fdc6bd 100644 --- a/third_party/blink/renderer/modules/locks/lock_manager.h +++ b/third_party/blink/renderer/modules/locks/lock_manager.h
@@ -80,11 +80,11 @@ bool IsPendingRequest(LockRequestImpl*); void QueryImpl(ScriptPromiseResolver* resolver); - void RequestImpl(ScriptPromiseResolver* resolver, - const LockOptions* options, + void RequestImpl(const LockOptions* options, const String& name, V8LockGrantedCallback* callback, - mojom::blink::LockMode mode); + mojom::blink::LockMode mode, + ScriptPromiseResolver* resolver); // Query the ContentSettingsClient to ensure access is allowed from // this context. This invokes an asynchronous IPC call.
diff --git a/third_party/blink/renderer/modules/mediastream/user_media_client_test.cc b/third_party/blink/renderer/modules/mediastream/user_media_client_test.cc index 2774c92..88ebf39d 100644 --- a/third_party/blink/renderer/modules/mediastream/user_media_client_test.cc +++ b/third_party/blink/renderer/modules/mediastream/user_media_client_test.cc
@@ -1685,6 +1685,6 @@ // Run tests with a separate queue for display capture requests (GetParam() == // true) and without (GetParam() == false) , corresponding to if // kSplitUserMediaQueues is enabled or not. -INSTANTIATE_TEST_CASE_P(/*no prefix*/, UserMediaClientTest, ::testing::Bool()); +INSTANTIATE_TEST_SUITE_P(/*no prefix*/, UserMediaClientTest, ::testing::Bool()); } // namespace blink
diff --git a/third_party/blink/renderer/modules/mediastream/video_track_adapter.cc b/third_party/blink/renderer/modules/mediastream/video_track_adapter.cc index d7b879c..73f24a6 100644 --- a/third_party/blink/renderer/modules/mediastream/video_track_adapter.cc +++ b/third_party/blink/renderer/modules/mediastream/video_track_adapter.cc
@@ -482,11 +482,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(video_sequence_checker_); // Do not drop frames if max frame rate hasn't been specified. - if (settings_.max_frame_rate() == 0.0f || - (base::FeatureList::IsEnabled( - features::kMediaStreamTrackUseConfigMaxFrameRate) && - source_frame_rate > 0 && - source_frame_rate <= settings_.max_frame_rate())) { + if (settings_.max_frame_rate() == 0.0f) { last_time_stamp_ = frame.timestamp(); return false; }
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string_test.cc b/third_party/blink/renderer/platform/bindings/parkable_string_test.cc index c67364f..c35e181b 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string_test.cc +++ b/third_party/blink/renderer/platform/bindings/parkable_string_test.cc
@@ -88,8 +88,16 @@ if (base::FeatureList::IsEnabled(features::kCompressParkableStrings)) { EXPECT_GT(task_environment_.GetPendingMainThreadTaskCount(), 0u); } - task_environment_.FastForwardBy( - base::Seconds(ParkableStringManager::kAgingIntervalInSeconds)); + + if (base::FeatureList::IsEnabled(features::kDelayFirstParkingOfStrings) && + !first_aging_done_) { + task_environment_.FastForwardBy( + ParkableStringManager::kFirstParkingDelay); + first_aging_done_ = true; + } else { + task_environment_.FastForwardBy( + base::Seconds(ParkableStringManager::kAgingIntervalInSeconds)); + } } void WaitForDelayedParking() { @@ -154,6 +162,7 @@ } } + bool first_aging_done_ = false; base::test::ScopedFeatureList scoped_feature_list_; base::test::TaskEnvironment task_environment_; }; @@ -994,6 +1003,27 @@ parkable.Impl()->age_for_testing()); } +TEST_P(ParkableStringTest, NoPrematureAging) { + ParkableString parkable(MakeLargeString().ReleaseImpl()); + EXPECT_EQ(ParkableStringImpl::Age::kYoung, + parkable.Impl()->age_for_testing()); + + // What would be a premature aging depends on |kDelayFirstParkingOfStrings|. + // Under the feature the regular aging interval is not enough. + if (base::FeatureList::IsEnabled(features::kDelayFirstParkingOfStrings)) { + task_environment_.FastForwardBy( + base::Seconds(ParkableStringManager::kAgingIntervalInSeconds)); + } else { + // Outside of the feature use half the regular aging interval. + task_environment_.FastForwardBy( + base::Seconds(ParkableStringManager::kAgingIntervalInSeconds / 2)); + } + + // Since not enough time elapsed not aging was done. + EXPECT_EQ(ParkableStringImpl::Age::kYoung, + parkable.Impl()->age_for_testing()); +} + TEST_P(ParkableStringTest, OldStringsAreParked) { ParkableString parkable(MakeLargeString().ReleaseImpl()); EXPECT_EQ(ParkableStringImpl::Age::kYoung,
diff --git a/third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h b/third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h index 36376f2..0638bb8 100644 --- a/third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h +++ b/third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h
@@ -44,7 +44,9 @@ // copied, and moved. static constexpr bool kCanInitializeWithMemset = true; static constexpr bool kCanClearUnusedSlotsWithMemset = true; - static constexpr bool kCanCopyWithMemcpy = true; + // v8::TracedReference assumes that references uniquely point to an internal + // node. + static constexpr bool kCanCopyWithMemcpy = false; static constexpr bool kCanMoveWithMemcpy = true; // TraceWrapperV8Reference supports concurrent tracing.
diff --git a/third_party/blink/renderer/platform/graphics/paint/display_item_list.h b/third_party/blink/renderer/platform/graphics/paint/display_item_list.h index 51a9dc9..8d2cd52 100644 --- a/third_party/blink/renderer/platform/graphics/paint/display_item_list.h +++ b/third_party/blink/renderer/platform/graphics/paint/display_item_list.h
@@ -42,11 +42,16 @@ // Declares itself as a forward iterator, but also supports a few more // things. The whole random access iterator interface is a bit much. template <typename BaseIterator, typename ItemType> - class IteratorWrapper - : public std::iterator<std::forward_iterator_tag, ItemType> { + class IteratorWrapper { DISALLOW_NEW(); public: + using iterator_category = std::forward_iterator_tag; + using value_type = ItemType; + using difference_type = std::ptrdiff_t; + using pointer = ItemType*; + using reference = ItemType&; + IteratorWrapper() = default; explicit IteratorWrapper(const BaseIterator& it) : it_(it) {}
diff --git a/third_party/blink/renderer/platform/media/web_media_player_impl.cc b/third_party/blink/renderer/platform/media/web_media_player_impl.cc index 38fadf3..a50a427 100644 --- a/third_party/blink/renderer/platform/media/web_media_player_impl.cc +++ b/third_party/blink/renderer/platform/media/web_media_player_impl.cc
@@ -27,7 +27,6 @@ #include "base/strings/stringprintf.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/trace_event.h" @@ -3413,8 +3412,8 @@ // to cycle the media thread before we destroy `demuxer_`. In this case skip // collection of the demuxer memory stats. if (demuxer_ && !IsNetworkStateError(network_state_)) { - base::PostTaskAndReplyWithResult( - media_task_runner_.get(), FROM_HERE, + media_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&Demuxer::GetMemoryUsage, base::Unretained(demuxer_.get())), base::BindOnce(&WebMediaPlayerImpl::FinishMemoryUsageReport,
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 9280d3a..3124eba 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -2271,7 +2271,7 @@ // User-Agent string. name: "ReduceUserAgentAndroidVersionDeviceModel", depends_on: ["ReduceUserAgentMinorVersion"], - status: {"Android": "experimental"}, + status: {"Android": "stable"}, base_feature: "ReduceUserAgentAndroidVersionDeviceModel", }, // If enabled, the minor version of the User-Agent string will be reduced.
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc index d235150..144b399 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc
@@ -3807,7 +3807,7 @@ EXPECT_EQ(UseCase::kCompositorGesture, CurrentUseCase()); } -INSTANTIATE_TEST_CASE_P( +INSTANTIATE_TEST_SUITE_P( , CompositorTQPolicyDuringThreadedScrollTest, testing::Values(
diff --git a/third_party/blink/renderer/platform/wtf/text/base64_test.cc b/third_party/blink/renderer/platform/wtf/text/base64_test.cc index f7f93a3..02cb777 100644 --- a/third_party/blink/renderer/platform/wtf/text/base64_test.cc +++ b/third_party/blink/renderer/platform/wtf/text/base64_test.cc
@@ -66,6 +66,7 @@ {"abc&", {}}, {"abcde", {}}, {"a", {}}, + {"=", {}}, // Empty string should yield an empty result. {"", {}}, @@ -113,6 +114,7 @@ {"abc&", {}}, {"abcde", {}}, {"a", {}}, + {"=", {}}, // Empty string should yield an empty result. {"", {}},
diff --git a/third_party/blink/tools/blinkpy/w3c/gerrit.py b/third_party/blink/tools/blinkpy/w3c/gerrit.py index 4755ad2..da9caf0e8 100644 --- a/third_party/blink/tools/blinkpy/w3c/gerrit.py +++ b/third_party/blink/tools/blinkpy/w3c/gerrit.py
@@ -5,6 +5,7 @@ import base64 import json import logging +from datetime import datetime from requests.exceptions import HTTPError from blinkpy.common.net.network_transaction import NetworkTimeout @@ -148,6 +149,13 @@ return self._data['status'] @property + def updated(self): + # Timestamps are given in UTC and have the format "'yyyy-mm-dd hh:mm:ss.fffffffff'" + # where "'ffffffffff'" represents nanoseconds. + return datetime.strptime(self._data['updated'][:-10], + '%Y-%m-%d %H:%M:%S') + + @property def messages(self): return self._data['messages']
diff --git a/third_party/blink/tools/blinkpy/w3c/pr_cleanup_tool.py b/third_party/blink/tools/blinkpy/w3c/pr_cleanup_tool.py index a205c07..28f15e9f 100644 --- a/third_party/blink/tools/blinkpy/w3c/pr_cleanup_tool.py +++ b/third_party/blink/tools/blinkpy/w3c/pr_cleanup_tool.py
@@ -1,12 +1,9 @@ """Cleans up PRs that correspond to abandoned CLs in Gerrit.""" -import argparse import logging +from datetime import datetime, timedelta -from blinkpy.common.system.log_utils import configure_logging -from blinkpy.w3c.wpt_github import WPTGitHub -from blinkpy.w3c.gerrit import GerritAPI, GerritError -from blinkpy.w3c.common import (read_credentials) +from blinkpy.w3c.gerrit import GerritError _log = logging.getLogger(__name__) @@ -14,96 +11,60 @@ class PrCleanupTool(object): def __init__(self, host): self.host = host - self.wpt_github = None - self.gerrit = None - def main(self, argv=None): - """Closes all PRs that are abandoned in Gerrit.""" - options = self.parse_args(argv) - log_level = logging.DEBUG if options.verbose else logging.INFO - configure_logging(logging_level=log_level, include_time=True) - credentials = read_credentials(self.host, options.credentials_json) - gh_user = credentials.get('GH_USER') - gh_token = credentials.get('GH_TOKEN') - if not gh_user or not gh_token: - _log.error('You have not set your GitHub credentials. This ' - 'script may fail with a network error when making ' - 'an API request to GitHub.') - _log.error('See https://chromium.googlesource.com/chromium/src' - '/+/master/docs/testing/web_platform_tests.md' - '#GitHub-credentials for instructions on how to set ' - 'your credentials up.') - return False - - gr_user = credentials['GERRIT_USER'] - gr_token = credentials['GERRIT_TOKEN'] - if not gr_user or not gr_token: - _log.warning('You have not set your Gerrit credentials. This ' - 'script may fail with a network error when making ' - 'an API request to Gerrit.') - - self.wpt_github = self.wpt_github or WPTGitHub(self.host, gh_user, - gh_token) - self.gerrit = self.gerrit or GerritAPI(self.host, gr_user, gr_token) - pull_requests = self.retrieve_all_prs() + def run(self, wpt_github, gerrit): + """Closes all PRs that are abandoned two weeks ago in Gerrit.""" + _log.info( + "Close exported PRs where the corresponding CLs have been abandoned." + ) + pull_requests = self.retrieve_all_prs(wpt_github) + past = datetime.utcnow() - timedelta(days=14) for pull_request in pull_requests: if pull_request.state != 'open': continue - change_id = self.wpt_github.extract_metadata( - 'Change-Id: ', pull_request.body) + change_id = wpt_github.extract_metadata('Change-Id: ', + pull_request.body) if not change_id: continue try: - cl = self.gerrit.query_cl(change_id) + cl = gerrit.query_cl(change_id) except GerritError as e: _log.error('Could not query change_id %s: %s', change_id, str(e)) continue cl_status = cl.status - if cl_status == 'ABANDONED': + if cl_status == 'ABANDONED' and cl.updated < past: comment = 'Close this PR because the Chromium CL has been abandoned.' - self.log_affected_pr_details(pull_request, comment) - self.close_pr_and_delete_branch(pull_request.number, comment) + self.log_affected_pr_details(wpt_github, pull_request, comment) + self.close_pr_and_delete_branch(wpt_github, + pull_request.number, comment) elif cl_status == 'MERGED' and (not cl.is_exportable()): comment = 'Close this PR because the Chromium CL does not have exportable changes.' - self.log_affected_pr_details(pull_request, comment) - self.close_pr_and_delete_branch(pull_request.number, comment) + self.log_affected_pr_details(wpt_github, pull_request, comment) + self.close_pr_and_delete_branch(wpt_github, + pull_request.number, comment) return True - def parse_args(self, argv): - parser = argparse.ArgumentParser() - parser.description = __doc__ - parser.add_argument( - '-v', - '--verbose', - action='store_true', - help='log extra details that may be helpful when debugging') - parser.add_argument( - '--credentials-json', - help='A JSON file with GitHub credentials, ' - 'generally not necessary on developer machines') - return parser.parse_args(argv) - - def retrieve_all_prs(self): + def retrieve_all_prs(self, wpt_github): """Retrieves last 1000 PRs.""" - return self.wpt_github.all_pull_requests() + return wpt_github.all_pull_requests() - def close_pr_and_delete_branch(self, pull_request_number, comment): + def close_pr_and_delete_branch(self, wpt_github, pull_request_number, + comment): """Closes a PR with a comment and delete the corresponding branch.""" - self.wpt_github.add_comment(pull_request_number, comment) - self.wpt_github.update_pr(pull_request_number, state='closed') - branch = self.wpt_github.get_pr_branch(pull_request_number) - self.wpt_github.delete_remote_branch(branch) + wpt_github.add_comment(pull_request_number, comment) + wpt_github.update_pr(pull_request_number, state='closed') + branch = wpt_github.get_pr_branch(pull_request_number) + wpt_github.delete_remote_branch(branch) - def log_affected_pr_details(self, pull_request, comment): + def log_affected_pr_details(self, wpt_github, pull_request, comment): """Logs details of an affected PR.""" _log.info(comment) _log.info('https://github.com/web-platform-tests/wpt/pull/%s', pull_request.number) _log.info( - self.wpt_github.extract_metadata('Reviewed-on: ', - pull_request.body)) + wpt_github.extract_metadata('Reviewed-on: ', pull_request.body))
diff --git a/third_party/blink/tools/blinkpy/w3c/pr_cleanup_tool_unittest.py b/third_party/blink/tools/blinkpy/w3c/pr_cleanup_tool_unittest.py index e542d7d7..a79a27a3 100644 --- a/third_party/blink/tools/blinkpy/w3c/pr_cleanup_tool_unittest.py +++ b/third_party/blink/tools/blinkpy/w3c/pr_cleanup_tool_unittest.py
@@ -24,78 +24,108 @@ })) self.host = host - def test_main_successful_close_abandoned_cl(self): - pr_cleanup = PrCleanupTool(self.host) - pr_cleanup.wpt_github = MockWPTGitHub(pull_requests=[ - PullRequest( - title='title1', - number=1234, - body='Change-Id: 88', - state='open', - labels=[]), + def test_successful_close_abandoned_cl(self): + wpt_github = MockWPTGitHub(pull_requests=[ + PullRequest(title='title1', + number=1234, + body='Change-Id: 88', + state='open', + labels=[]), ]) - pr_cleanup.gerrit = MockGerritAPI() - pr_cleanup.gerrit.cl = MockGerritCL( - data={ - 'change_id': 'I001', - 'subject': 'subject', - '_number': 1234, - 'status': 'ABANDONED', - 'current_revision': '1', - 'has_review_started': True, - 'revisions': { - '1': { - 'commit_with_footers': 'a commit with footers' - } - }, - 'owner': { - 'email': 'test@chromium.org' - }, + gerrit = MockGerritAPI() + pr_cleanup = PrCleanupTool(self.host) + gerrit.cl = MockGerritCL(data={ + 'change_id': 'I001', + 'subject': 'subject', + '_number': 1234, + 'status': 'ABANDONED', + 'updated': '2022-10-15 15:17:50.000000000', + 'current_revision': '1', + 'has_review_started': True, + 'revisions': { + '1': { + 'commit_with_footers': 'a commit with footers' + } }, - api=pr_cleanup.gerrit) - pr_cleanup.main(['--credentials-json', '/tmp/credentials.json']) - self.assertEqual(pr_cleanup.gerrit.cls_queried, ['88']) - self.assertEqual(pr_cleanup.wpt_github.calls, [ + 'owner': { + 'email': 'test@chromium.org' + }, + }, + api=gerrit) + pr_cleanup.run(wpt_github, gerrit) + self.assertEqual(gerrit.cls_queried, ['88']) + self.assertEqual(wpt_github.calls, [ 'all_pull_requests', 'add_comment "Close this PR because the Chromium CL has been abandoned."', 'update_pr', 'get_pr_branch', 'delete_remote_branch' ]) - def test_main_successful_close_no_exportable_changes(self): - pr_cleanup = PrCleanupTool(self.host) - pr_cleanup.wpt_github = MockWPTGitHub(pull_requests=[ - PullRequest( - title='title1', - number=1234, - body='Change-Id: 99', - state='open', - labels=[]), + def test_not_close_pr_for_abandoned_cl(self): + wpt_github = MockWPTGitHub(pull_requests=[ + PullRequest(title='title1', + number=1234, + body='Change-Id: 88', + state='open', + labels=[]), ]) - pr_cleanup.gerrit = MockGerritAPI() - pr_cleanup.gerrit.cl = MockGerritCL( - data={ - 'change_id': 'I001', - 'subject': 'subject', - '_number': 1234, - 'status': 'MERGED', - 'current_revision': '1', - 'has_review_started': True, - 'revisions': { - '1': { - 'commit_with_footers': 'a commit with footers', - 'files': { - RELATIVE_WEB_TESTS + 'foo/bar.html': '', - } - } - }, - 'owner': { - 'email': 'test@chromium.org' - }, + gerrit = MockGerritAPI() + pr_cleanup = PrCleanupTool(self.host) + gerrit.cl = MockGerritCL(data={ + 'change_id': 'I001', + 'subject': 'subject', + '_number': 1234, + 'status': 'ABANDONED', + 'updated': '2222-10-15 15:17:50.000000000', + 'current_revision': '1', + 'has_review_started': True, + 'revisions': { + '1': { + 'commit_with_footers': 'a commit with footers' + } }, - api=pr_cleanup.gerrit) - pr_cleanup.main(['--credentials-json', '/tmp/credentials.json']) - self.assertEqual(pr_cleanup.gerrit.cls_queried, ['99']) - self.assertEqual(pr_cleanup.wpt_github.calls, [ + 'owner': { + 'email': 'test@chromium.org' + }, + }, + api=gerrit) + pr_cleanup.run(wpt_github, gerrit) + self.assertEqual(gerrit.cls_queried, ['88']) + self.assertEqual(wpt_github.calls, ['all_pull_requests']) + + def test_successful_close_no_exportable_changes(self): + wpt_github = MockWPTGitHub(pull_requests=[ + PullRequest(title='title1', + number=1234, + body='Change-Id: 99', + state='open', + labels=[]), + ]) + gerrit = MockGerritAPI() + pr_cleanup = PrCleanupTool(self.host) + gerrit.cl = MockGerritCL(data={ + 'change_id': 'I001', + 'subject': 'subject', + '_number': 1234, + 'status': 'MERGED', + 'updated': '2022-10-15 15:17:50.000000000', + 'current_revision': '1', + 'has_review_started': True, + 'revisions': { + '1': { + 'commit_with_footers': 'a commit with footers', + 'files': { + RELATIVE_WEB_TESTS + 'foo/bar.html': '', + } + } + }, + 'owner': { + 'email': 'test@chromium.org' + }, + }, + api=gerrit) + pr_cleanup.run(wpt_github, gerrit) + self.assertEqual(gerrit.cls_queried, ['99']) + self.assertEqual(wpt_github.calls, [ 'all_pull_requests', 'add_comment "Close this PR because the Chromium' ' CL does not have exportable changes."', 'update_pr', @@ -103,34 +133,33 @@ ]) def test_query_cl_raise_exception(self): - pr_cleanup = PrCleanupTool(self.host) - pr_cleanup.wpt_github = MockWPTGitHub(pull_requests=[ - PullRequest( - title='title1', - number=1234, - body='Change-Id: 88', - state='open', - labels=[]), + wpt_github = MockWPTGitHub(pull_requests=[ + PullRequest(title='title1', + number=1234, + body='Change-Id: 88', + state='open', + labels=[]), ]) - pr_cleanup.gerrit = MockGerritAPI(raise_error=True) - pr_cleanup.gerrit.cl = MockGerritCL( - data={ - 'change_id': 'I001', - 'subject': 'subject', - '_number': 1234, - 'status': 'ABANDONED', - 'current_revision': '1', - 'has_review_started': True, - 'revisions': { - '1': { - 'commit_with_footers': 'a commit with footers' - } - }, - 'owner': { - 'email': 'test@chromium.org' - }, + gerrit = MockGerritAPI(raise_error=True) + pr_cleanup = PrCleanupTool(self.host) + gerrit.cl = MockGerritCL(data={ + 'change_id': 'I001', + 'subject': 'subject', + '_number': 1234, + 'status': 'ABANDONED', + 'updated': '2022-10-15 15:17:50.000000000', + 'current_revision': '1', + 'has_review_started': True, + 'revisions': { + '1': { + 'commit_with_footers': 'a commit with footers' + } }, - api=pr_cleanup.gerrit) - pr_cleanup.main(['--credentials-json', '/tmp/credentials.json']) - self.assertEqual(pr_cleanup.gerrit.cls_queried, ['88']) - self.assertEqual(pr_cleanup.wpt_github.calls, ['all_pull_requests']) + 'owner': { + 'email': 'test@chromium.org' + }, + }, + api=gerrit) + pr_cleanup.run(wpt_github, gerrit) + self.assertEqual(gerrit.cls_queried, ['88']) + self.assertEqual(wpt_github.calls, ['all_pull_requests'])
diff --git a/third_party/blink/tools/blinkpy/w3c/test_exporter.py b/third_party/blink/tools/blinkpy/w3c/test_exporter.py index fb9667a..6aea41e 100644 --- a/third_party/blink/tools/blinkpy/w3c/test_exporter.py +++ b/third_party/blink/tools/blinkpy/w3c/test_exporter.py
@@ -7,8 +7,6 @@ import logging from blinkpy.common.system.log_utils import configure_logging -from blinkpy.w3c.local_wpt import LocalWPT -from blinkpy.w3c.chromium_exportable_commits import exportable_commits_over_last_n_commits from blinkpy.w3c.common import ( CHANGE_ID_FOOTER, WPT_GH_URL, @@ -17,9 +15,12 @@ PROVISIONAL_PR_LABEL, read_credentials, ) -from blinkpy.w3c.gerrit import GerritAPI, GerritCL, GerritError -from blinkpy.w3c.wpt_github import WPTGitHub, MergeError +from blinkpy.w3c.chromium_exportable_commits import exportable_commits_over_last_n_commits from blinkpy.w3c.export_notifier import ExportNotifier +from blinkpy.w3c.gerrit import GerritAPI, GerritCL, GerritError +from blinkpy.w3c.local_wpt import LocalWPT +from blinkpy.w3c.pr_cleanup_tool import PrCleanupTool +from blinkpy.w3c.wpt_github import WPTGitHub, MergeError _log = logging.getLogger(__name__) @@ -27,6 +28,7 @@ class TestExporter(object): def __init__(self, host): self.host = host + self.pr_cleaner = PrCleanupTool(self.host) self.wpt_github = None self.gerrit = None self.dry_run = False @@ -66,6 +68,10 @@ self.host, credentials['GERRIT_USER'], credentials['GERRIT_TOKEN']) self.local_wpt = self.local_wpt or LocalWPT(self.host, credentials['GH_TOKEN']) + + if not self.dry_run: + self.pr_cleaner.run(self.wpt_github, self.gerrit) + self.local_wpt.fetch() _log.info('Searching for exportable in-flight CLs.')
diff --git a/third_party/blink/tools/blinkpy/w3c/test_exporter_unittest.py b/third_party/blink/tools/blinkpy/w3c/test_exporter_unittest.py index 30b5139..3930ffb 100644 --- a/third_party/blink/tools/blinkpy/w3c/test_exporter_unittest.py +++ b/third_party/blink/tools/blinkpy/w3c/test_exporter_unittest.py
@@ -89,6 +89,7 @@ MockChromiumCommit( self.host, position='refs/heads/main@{#3}', change_id='I003', subject='subject 3', body='body 3'), ], []) + test_exporter.pr_cleaner.run = lambda x, y: None success = test_exporter.main( ['--credentials-json', '/tmp/credentials.json']) @@ -171,6 +172,7 @@ MockChromiumCommit( self.host, position='refs/heads/main@{#458479}', change_id='I0147'), ], []) + test_exporter.pr_cleaner.run = lambda x, y: None success = test_exporter.main( ['--credentials-json', '/tmp/credentials.json']) @@ -256,6 +258,7 @@ self.host, subject='subject', body='body', change_id=None)), ] + test_exporter.pr_cleaner.run = lambda x, y: None test_exporter.main(['--credentials-json', '/tmp/credentials.json']) self.assertEqual(test_exporter.wpt_github.calls, [ @@ -312,6 +315,7 @@ api=test_exporter.gerrit, chromium_commit=MockChromiumCommit(self.host)) ] + test_exporter.pr_cleaner.run = lambda x, y: None success = test_exporter.main( ['--credentials-json', '/tmp/credentials.json']) @@ -359,6 +363,7 @@ api=test_exporter.gerrit, chromium_commit=MockChromiumCommit(self.host)) ] + test_exporter.pr_cleaner.run = lambda x, y: None test_exporter.main(['--credentials-json', '/tmp/credentials.json']) self.assertEqual(test_exporter.wpt_github.calls, [ @@ -382,6 +387,7 @@ test_exporter.get_exportable_commits = lambda: ([ MockChromiumCommit(self.host, change_id='decafbad'), ], []) test_exporter.gerrit = MockGerritAPI() + test_exporter.pr_cleaner.run = lambda x, y: None success = test_exporter.main( ['--credentials-json', '/tmp/credentials.json']) @@ -408,6 +414,7 @@ test_exporter.get_exportable_commits = lambda: ([ MockChromiumCommit(self.host, change_id='decafbad'), ], []) test_exporter.gerrit = MockGerritAPI() + test_exporter.pr_cleaner.run = lambda x, y: None success = test_exporter.main( ['--credentials-json', '/tmp/credentials.json']) @@ -450,6 +457,7 @@ api=test_exporter.gerrit, chromium_commit=MockChromiumCommit(self.host)) ] + test_exporter.pr_cleaner.run = lambda x, y: None success = test_exporter.main( ['--credentials-json', '/tmp/credentials.json']) @@ -467,6 +475,7 @@ test_exporter.get_exportable_commits = lambda: ([], []) test_exporter.gerrit = MockGerritAPI() test_exporter.gerrit.query_exportable_open_cls = raise_gerrit_error + test_exporter.pr_cleaner.run = lambda x, y: None success = test_exporter.main( ['--credentials-json', '/tmp/credentials.json']) @@ -486,6 +495,7 @@ test_exporter.get_exportable_commits = lambda: ( [], ['There was an error with the rutabaga.']) test_exporter.gerrit = MockGerritAPI() + test_exporter.pr_cleaner.run = lambda x, y: None success = test_exporter.main( ['--credentials-json', '/tmp/credentials.json'])
diff --git a/third_party/blink/tools/wpt_cleanup.py b/third_party/blink/tools/wpt_cleanup.py deleted file mode 100755 index ac089ae2..0000000 --- a/third_party/blink/tools/wpt_cleanup.py +++ /dev/null
@@ -1,19 +0,0 @@ -#!/usr/bin/env vpython3 -# Copyright 2017 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -"""Pushes changes to web-platform-tests inside Chromium to the upstream repo.""" - -from blinkpy.common.host import Host -from blinkpy.w3c.pr_cleanup_tool import PrCleanupTool - - -def main(): - host = Host() - exporter = PrCleanupTool(host) - success = exporter.main() - host.exit(0 if success else 1) - - -if __name__ == '__main__': - main()
diff --git a/third_party/blink/web_tests/LeakExpectations b/third_party/blink/web_tests/LeakExpectations index 8b3d678..563f8bb 100644 --- a/third_party/blink/web_tests/LeakExpectations +++ b/third_party/blink/web_tests/LeakExpectations
@@ -61,6 +61,9 @@ # This has been marked as Skip in the TestExpectations file. crbug.com/1385278 [ Linux ] external/wpt/resource-timing/iframe-failed-commit.html [ Skip ] +# Tests frequently cause ci builder step failure +crbug.com/1393081 [ Linux ] virtual/view-transition/external/wpt/css/css-view-transitions/input-blocked-when-rendering-suppressed.html [ Failure ] + ########################################################################### # WARNING: Memory leaks must be fixed asap. Sheriff is expected to revert # # culprit CLs instead of suppressing the leaks. If you have any question, #
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 8a3f43d..d0e6059b 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -8145,10 +8145,12 @@ # Sheriff 2022-11-28 crbug.com/1393567 external/wpt/screen-orientation/hidden_document.html [ Failure Pass Timeout ] crbug.com/1393985 [ Mac11-arm64 ] virtual/expose-lcp-render-time/external/wpt/performance-timeline/cross-origin-non-tao-image.sub.html [ Failure Pass ] -crbug.com/1290077 [ Mac11-arm64 ] virtual/gpu/fast/canvas/canvas-drawImage-live-video.html [ Failure Pass Timeout ] -crbug.com/1290077 [ Mac11-arm64 ] virtual/oopr-canvas2d/fast/canvas/canvas-drawImage-live-video.html [ Failure Pass Timeout ] +crbug.com/1290077 [ Mac11-arm64 ] virtual/gpu/fast/canvas/canvas-drawImage-live-video.html [ Failure Pass Timeout ] +crbug.com/1290077 [ Mac11-arm64 ] virtual/oopr-canvas2d/fast/canvas/canvas-drawImage-live-video.html [ Failure Pass Timeout ] +crbug.com/1290077 [ Mac11-arm64 ] fast/canvas/canvas-drawImage-live-video.html [ Pass Timeout ] crbug.com/1393995 fast/dom/shadow/import-rule-in-shadow-tree-needs-document-style-recalc.html [ Failure Pass ] crbug.com/1379180 fast/events/event-hit-testing-fallback-to-iframe.html [ Failure Pass ] +crbug.com/1394041 [ Mac11-arm64 ] virtual/gpu-rasterization/images/2-dht.html [ Failure Pass ] # Temporarily disable test to land devtools-frontend change crrev/c/4057666 crbug.com/1385379 http/tests/devtools/elements/styles-4/styles-invalid-color-values.js [ Failure Pass ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index db562049..f99e1e15 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -1528,7 +1528,7 @@ ], "exclusive_tests": "ALL", "args": [ - "--enable-blink-features=SpeculationRulesPrefetchProxy,SpeculationRulesFetchFromHeader,SpeculationRulesReferrerPolicyKey", + "--enable-blink-features=SpeculationRulesPrefetchProxy,SpeculationRulesFetchFromHeader,SpeculationRulesReferrerPolicyKey,SpeculationRulesDocumentRules", "--enable-features=SpeculationRulesPrefetchProxy,PrefetchUseContentRefactor", "--bypass-prefetch-proxy-for-host=not-web-platform.test", "--isolated-prerender-allow-all-domains"
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index c9ae081..5005cfc 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -226378,6 +226378,19 @@ {} ] ], + "number-input-vertical-overflow.html": [ + "dfd8100a01eb339da2b7ae1536a344ecce37f21d", + [ + null, + [ + [ + "/css/css-writing-modes/forms/number-input-vertical-overflow-ref.html", + "==" + ] + ], + {} + ] + ], "progress-appearance-native-horizontal.optional.html": [ "ad7d2aa4479b3d8dfe927b2b9d08c854f721737c", [ @@ -274185,10 +274198,6 @@ "ff88b1e74a951b77458340de03b91d177302543e", [] ], - "position-fallback-tree-scoped-expected.txt": [ - "789f12eac0eae063422bcad9ab237705e0ebb214", - [] - ], "reference": { "anchor-scroll-fixedpos-ref.html": [ "e73354df72dac33f7a94eaef445e80ec61e3976a", @@ -317802,6 +317811,10 @@ ] } }, + "number-input-vertical-overflow-ref.html": [ + "ad1ecc35ee913a2850bf42ed0e66397f30d19315", + [] + ], "range-input-painting-ref.html": [ "650a8139ca6cc13403957c2b68e8ef954cd80058", [] @@ -323739,26 +323752,6 @@ [] ], "experimental-features": { - "document-domain": { - "resources": { - "document-domain-disabled.html": [ - "124ee143eee08b46b7effdb25e81cde65a1c16a8", - [] - ], - "document-domain-disabled.html.headers": [ - "57b46a600c0f4d5790767b74828a0ef56a34ba59", - [] - ], - "document-domain-enabled.html": [ - "fe03af0dbbe5dbb559b647a9fd2976b8035835b3", - [] - ], - "document-domain-enabled.html.headers": [ - "89ccbe756dfb39e50e8894eb791ee7626f18f59c", - [] - ] - } - }, "layout-animations-disabled-tentative.html.headers": [ "745da550ee5162cffcdf3913a37efa6d355ca47e", [] @@ -329209,6 +329202,24 @@ ] } }, + "credentials": { + "authentication-redirection.any-expected.txt": [ + "9fb8be1b5efe80a8fccb8de5c10f0b544ebf308e", + [] + ], + "authentication-redirection.any.serviceworker-expected.txt": [ + "89eb9a1166f7d668a4cfb1b7f926a42b611eb6f3", + [] + ], + "authentication-redirection.any.sharedworker-expected.txt": [ + "9fb8be1b5efe80a8fccb8de5c10f0b544ebf308e", + [] + ], + "authentication-redirection.any.worker-expected.txt": [ + "9fb8be1b5efe80a8fccb8de5c10f0b544ebf308e", + [] + ] + }, "headers": { "headers-basic.any.js.ini": [ "20c0ac2dfe559676f717546d157341969bfe58fd", @@ -329606,6 +329617,10 @@ "76519fa8cc27abe9841b35f0f428207120f098e1", [] ], + "dump-authorization-header.py": [ + "a651aeb4e8b9238383af5ec8ecb5e3820e081881", + [] + ], "echo-content.h2.py": [ "0be3ece4a5ff32acd963e64b253cd99039615873", [] @@ -385306,6 +385321,22 @@ "73108401708f3c14a757a21e2c9554a869bc120c", [] ], + "xhr-authorization-redirect.any-expected.txt": [ + "9fb8be1b5efe80a8fccb8de5c10f0b544ebf308e", + [] + ], + "xhr-authorization-redirect.any.serviceworker-expected.txt": [ + "b1c0db934ea04dcd6f8ad9b4f5cda23364a310c8", + [] + ], + "xhr-authorization-redirect.any.sharedworker-expected.txt": [ + "9fb8be1b5efe80a8fccb8de5c10f0b544ebf308e", + [] + ], + "xhr-authorization-redirect.any.worker-expected.txt": [ + "9fb8be1b5efe80a8fccb8de5c10f0b544ebf308e", + [] + ], "xmlhttprequest-sync-block-defer-scripts-subframe.html": [ "be46a12b6f716f659e702e34cef36d8f2bd8b495", [] @@ -419053,7 +419084,7 @@ ] ], "position-fallback-tree-scoped.html": [ - "5b5c25f1030113bc6a8aaf68d4e977170e0b899f", + "955c3a7c1bd5b5be97356ec4535ba85a075e9042", [ null, {} @@ -426093,6 +426124,20 @@ {} ] ], + "font-variant-alternates-invalid.html": [ + "baf35acb8a11d8d5319712b68191529f175d895b", + [ + null, + {} + ] + ], + "font-variant-alternates-valid.html": [ + "43cc6f52448f3cdf745a7d241d70671b99474f6d", + [ + null, + {} + ] + ], "font-variant-caps-computed.html": [ "01b890df205a1dd6914c3e83bc50aaa061f70a0c", [ @@ -445975,6 +446020,15 @@ {} ] ], + "text-input-vertical-overflow-no-scroll.html": [ + "c288d6472c62e7119ce315a690cf38c639ee6828", + [ + null, + { + "testdriver": true + } + ] + ], "textarea-rows-cols-sizing.html": [ "8cd9c27d36cba2f6c7a1863c3d1c95d1c3b97320", [ @@ -451878,15 +451932,6 @@ }, "document-policy": { "experimental-features": { - "document-domain": { - "document-domain.tentative.sub.html": [ - "65de95c9a3899a884b9ccb47a626701799950bfa", - [ - null, - {} - ] - ] - }, "document-write.tentative.html": [ "551703c6f56b74856e2b7b465760fc57c2fe95dc", [ @@ -476617,6 +476662,69 @@ } ] ], + "authentication-redirection.any.js": [ + "b6376368116e76270d489493350e4226293bb8da", + [ + "fetch/api/credentials/authentication-redirection.any.html", + { + "script_metadata": [ + [ + "global", + "window,worker" + ], + [ + "script", + "/common/get-host-info.sub.js" + ] + ] + } + ], + [ + "fetch/api/credentials/authentication-redirection.any.serviceworker.html", + { + "script_metadata": [ + [ + "global", + "window,worker" + ], + [ + "script", + "/common/get-host-info.sub.js" + ] + ] + } + ], + [ + "fetch/api/credentials/authentication-redirection.any.sharedworker.html", + { + "script_metadata": [ + [ + "global", + "window,worker" + ], + [ + "script", + "/common/get-host-info.sub.js" + ] + ] + } + ], + [ + "fetch/api/credentials/authentication-redirection.any.worker.html", + { + "script_metadata": [ + [ + "global", + "window,worker" + ], + [ + "script", + "/common/get-host-info.sub.js" + ] + ] + } + ] + ], "cookies.any.js": [ "de30e477655c2851873e75a34019f30644679ac1", [ @@ -493651,13 +493759,6 @@ {} ] ], - "document_domain_feature_policy.tentative.sub.html": [ - "e50e5e1657f11cc8484d864080e2c8e2b2a1922a", - [ - null, - {} - ] - ], "document_domain_setter.html": [ "25395283411203ca9d15a00513cfd23425c32b58", [ @@ -634152,6 +634253,69 @@ {} ] ], + "xhr-authorization-redirect.any.js": [ + "e9a4db44f7238117cab3027d5d88859f83fc63fc", + [ + "xhr/xhr-authorization-redirect.any.html", + { + "script_metadata": [ + [ + "global", + "window,worker" + ], + [ + "script", + "/common/get-host-info.sub.js" + ] + ] + } + ], + [ + "xhr/xhr-authorization-redirect.any.serviceworker.html", + { + "script_metadata": [ + [ + "global", + "window,worker" + ], + [ + "script", + "/common/get-host-info.sub.js" + ] + ] + } + ], + [ + "xhr/xhr-authorization-redirect.any.sharedworker.html", + { + "script_metadata": [ + [ + "global", + "window,worker" + ], + [ + "script", + "/common/get-host-info.sub.js" + ] + ] + } + ], + [ + "xhr/xhr-authorization-redirect.any.worker.html", + { + "script_metadata": [ + [ + "global", + "window,worker" + ], + [ + "script", + "/common/get-host-info.sub.js" + ] + ] + } + ] + ], "xhr-timeout-longtask.any.js": [ "161713104aefcf8a195e9c7c120bfcddb3f89b92", [
diff --git a/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/number-input-vertical-overflow-ref.html b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/number-input-vertical-overflow-ref.html new file mode 100644 index 0000000..ad1ecc3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/number-input-vertical-overflow-ref.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<title>Reference: Number input in vertical writing mode with long value does not cause ink overflow</title> +<p>Number input with long value does not cause ink overflow</p> +<style> + input { + writing-mode: vertical-lr; + appearance: none; + inline-size: 10em; + } +</style> +<input type="number">
diff --git a/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/number-input-vertical-overflow.html b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/number-input-vertical-overflow.html new file mode 100644 index 0000000..dfd8100 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/number-input-vertical-overflow.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<link rel="author" title="Tim Nguyen" href="https://github.com/nt1m"> +<link rel="help" href="https://html.spec.whatwg.org/#the-input-element"> +<link rel="help" href="https://drafts.csswg.org/css-writing-modes-4/#block-flow"> +<title>Number input in vertical writing mode with long value does not cause ink overflow</title> +<meta charset="utf-8"> +<link rel="match" href="number-input-vertical-overflow-ref.html"> +<style> + input { + writing-mode: vertical-lr; + color: transparent; + appearance: none; + inline-size: 10em; + } +</style> +<p>Number input with long value does not cause ink overflow</p> +<input type="number" value="11111111111111111111111111111111111">
diff --git a/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/text-input-vertical-overflow-no-scroll.html b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/text-input-vertical-overflow-no-scroll.html new file mode 100644 index 0000000..c288d64 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/text-input-vertical-overflow-no-scroll.html
@@ -0,0 +1,67 @@ +<!doctype html> +<link rel="author" title="Tim Nguyen" href="https://github.com/nt1m"> +<link rel="help" href="https://html.spec.whatwg.org/#the-input-element"> +<link rel="help" href="https://drafts.csswg.org/css-writing-modes-4/#block-flow"> +<title>Test that typing lots of characters inside vertical text inputs doesn't cause scroll position changes</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> + +<style> + .spacer { + height: 100vh; + } + input { font-family: monospace; } +</style> + +<div class="spacer"></div> +<input id="testInput"> +<div class="spacer"></div> + +<script> +for (const inputType of ["text", "password", "search", "number"]) { + testInput.type = inputType; + for (const writingMode of ["vertical-lr", "vertical-rl", "sideways-lr", "sideways-rl"]) { + if (!CSS.supports("writing-mode", writingMode)) + continue; + promise_test(async t => { + assert_true( + document.documentElement.scrollHeight > document.documentElement.clientHeight, + "Page is scrollable" + ); + testInput.style.writingMode = writingMode; + document.documentElement.scrollTop = 0; + t.add_cleanup(() => { + document.documentElement.scrollTop = 0; + testInput.value = ""; + }); + + // Align input to the bottom edge + testInput.scrollIntoView({block: "end", inline: "nearest"}); + + assert_true( + document.documentElement.scrollTop > 0, + "Successfully scrolled" + ); + + const oldScrollTop = document.documentElement.scrollTop; + + const numCharsToOverflow = document.documentElement.clientHeight / parseInt(getComputedStyle(testInput).fontSize); + const value = "1".repeat(numCharsToOverflow); + + await test_driver.click(testInput); + + assert_true(testInput.matches(":focus"), "input is focused"); + + await test_driver.send_keys(testInput, value); + + assert_equals( + document.documentElement.scrollTop, + oldScrollTop, + "Typing lots of characters in input did not cause scrolling" + ); + }, `input[type=${inputType}] in ${writingMode}: typing characters in input should not cause the page to scroll`); + } +} +</script>
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any-expected.txt b/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any-expected.txt new file mode 100644 index 0000000..9fb8be1b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS getAuthorizationHeaderValue - no redirection +PASS getAuthorizationHeaderValue - same origin redirection +FAIL getAuthorizationHeaderValue - cross origin redirection assert_equals: expected "none" but got "Basic dXNlcjpwYXNz" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.js b/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.js new file mode 100644 index 0000000..b6376368 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.js
@@ -0,0 +1,26 @@ +// META: global=window,worker +// META: script=/common/get-host-info.sub.js + +const authorizationValue = "Basic " + btoa("user:pass"); +async function getAuthorizationHeaderValue(url) +{ + const headers = { "Authorization": authorizationValue}; + const requestInit = {"headers": headers}; + const response = await fetch(url, requestInit); + return response.text(); +} + +promise_test(async test => { + const result = await getAuthorizationHeaderValue("/fetch/api/resources/dump-authorization-header.py"); + assert_equals(result, authorizationValue); +}, "getAuthorizationHeaderValue - no redirection"); + +promise_test(async test => { + const result = await getAuthorizationHeaderValue("/fetch/api/resources/redirect.py?location=" + encodeURIComponent("/fetch/api/resources/dump-authorization-header.py")); + assert_equals(result, authorizationValue); +}, "getAuthorizationHeaderValue - same origin redirection"); + +promise_test(async (test) => { + const result = await getAuthorizationHeaderValue(get_host_info().HTTP_REMOTE_ORIGIN + "/fetch/api/resources/redirect.py?allow_headers=Authorization&location=" + encodeURIComponent(get_host_info().HTTP_ORIGIN + "/fetch/api/resources/dump-authorization-header.py")); + assert_equals(result, "none"); +}, "getAuthorizationHeaderValue - cross origin redirection");
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.serviceworker-expected.txt b/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.serviceworker-expected.txt new file mode 100644 index 0000000..89eb9a1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.serviceworker-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS getAuthorizationHeaderValue - no redirection +PASS getAuthorizationHeaderValue - same origin redirection +FAIL getAuthorizationHeaderValue - cross origin redirection promise_test: Unhandled rejection with value: object "TypeError: Failed to fetch" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.sharedworker-expected.txt b/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.sharedworker-expected.txt new file mode 100644 index 0000000..9fb8be1b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.sharedworker-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS getAuthorizationHeaderValue - no redirection +PASS getAuthorizationHeaderValue - same origin redirection +FAIL getAuthorizationHeaderValue - cross origin redirection assert_equals: expected "none" but got "Basic dXNlcjpwYXNz" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.worker-expected.txt new file mode 100644 index 0000000..9fb8be1b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fetch/api/credentials/authentication-redirection.any.worker-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS getAuthorizationHeaderValue - no redirection +PASS getAuthorizationHeaderValue - same origin redirection +FAIL getAuthorizationHeaderValue - cross origin redirection assert_equals: expected "none" but got "Basic dXNlcjpwYXNz" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/resources/dump-authorization-header.py b/third_party/blink/web_tests/external/wpt/fetch/api/resources/dump-authorization-header.py new file mode 100644 index 0000000..a651aeb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fetch/api/resources/dump-authorization-header.py
@@ -0,0 +1,14 @@ +def main(request, response): + headers = [(b"Content-Type", "text/html"), + (b"Cache-Control", b"no-cache")] + + if b"Origin" in request.headers: + headers.append((b"Access-Control-Allow-Origin", request.headers.get(b"Origin", b""))) + headers.append((b"Access-Control-Allow-Credentials", b"true")) + else: + headers.append((b"Access-Control-Allow-Origin", b"*")) + headers.append((b"Access-Control-Allow-Headers", b'Authorization')) + + if b"authorization" in request.headers: + return 200, headers, request.headers.get(b"Authorization") + return 200, headers, "none"
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/popovers/popover-top-layer-combinations.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/popovers/popover-top-layer-combinations.tentative.html index d4529b9e..0e04f304 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/popovers/popover-top-layer-combinations.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/popovers/popover-top-layer-combinations.tentative.html
@@ -6,19 +6,18 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-actions.js"></script> <script src="/resources/testdriver-vendor.js"></script> <script src="resources/popover-utils.js"></script> +<button id=visible>Visible button</button> <div id=examples> <dialog popover>Popover Dialog</dialog> <dialog popover open style="top:50px;">Open Non-modal Popover Dialog</dialog> - <dialog popover=manual defaultopen style="top:100px;">Defaultopen Popover Dialog</dialog> - <dialog popover=manual defaultopen open style="top:150px;">Defaultopen and Open Popover Dialog</dialog> <div popover class=fullscreen>Fullscreen Popover</div> <dialog popover class=fullscreen>Fullscreen Popover Dialog</dialog> <dialog popover open class=fullscreen style="top:200px;">Fullscreen Open Non-modal Popover Dialog</dialog> </div> -<button id=visible>Visible button</button> <style> [popover] { @@ -26,15 +25,19 @@ top:0; left:0; } + [popover].fullscreen.visible { + display:block; + } </style> <script> -showDefaultopenPopoversOnLoad(); const isDialog = (ex) => ex instanceof HTMLDialogElement; const isFullscreen = (ex) => ex.classList.contains('fullscreen'); function ensureIsOpenPopover(ex,message) { // Because :open will eventually support <dialog>, this does extra work to - // verify we're dealing with an :open Popover. + // verify we're dealing with an :open Popover. Note that this will also throw + // if this is an element with the `popover` attribute that has been made + // visible via an explicit `display:block` style rule. message = message || 'Error'; assert_true(ex.matches(':open'),`${message}: Popover doesn\'t match :open`); assert_false(ex.matches(':closed'),`${message}: Popover matches :closed`); @@ -47,23 +50,13 @@ examples.forEach(ex => { promise_test(async (t) => { t.add_cleanup(() => ex.remove()); + // Test initial conditions if (ex.hasAttribute('open')) { assert_true(isDialog(ex)); assert_true(isElementVisible(ex),'Open dialog should be visible by default'); - } else if (ex.hasAttribute('defaultopen')) { - ensureIsOpenPopover(ex,'defaultopen should open the popover on load'); - assert_true(isElementVisible(ex),'Popover with defaultopen should be visible by default'); - } - if (isElementVisible(ex)) { - // ex is already open (defaultopen or open dialog) assert_throws_dom("InvalidStateError",() => ex.showPopover(),'Calling showPopover on an already-showing element should throw InvalidStateError'); - if (ex.hasAttribute('open')) { - assert_true(isDialog(ex)); - ex.removeAttribute('open'); - assert_false(isElementVisible(ex),'Removing the open attribute should hide the dialog'); - } else { - ex.hidePopover(); // Should not throw - } + ex.removeAttribute('open'); + assert_false(isElementVisible(ex),'Removing the open attribute should hide the dialog'); } else { ex.showPopover(); // Should not throw ensureIsOpenPopover(ex,'showPopover should work'); @@ -74,24 +67,24 @@ // Start with popover, try the other API ex.showPopover(); + ensureIsOpenPopover(ex); let tested_something=false; if (isDialog(ex)) { tested_something=true; - ensureIsOpenPopover(ex); assert_throws_dom("InvalidStateError",() => ex.showModal(),'Calling showModal() on an already-showing Popover should throw InvalidStateError'); assert_throws_dom("InvalidStateError",() => ex.show(),'Calling show() on an already-showing Popover should throw InvalidStateError'); } if (isFullscreen(ex)) { tested_something=true; let requestSucceeded = false; - await blessTopLayer(ex) - .then(() => ex.requestFullscreen()) + await blessTopLayer(ex); + await ex.requestFullscreen() .then(() => {requestSucceeded = true;}) // We should not hit this. .catch((exception) => { // This exception is expected. assert_equals(exception.name,'TypeError',`Invalid exception from requestFullscreen() (${exception.message})`); }); - assert_false(requestSucceeded,'requestFullscreen() should not succeed when the element is an already-showing Popover'); + assert_false(requestSucceeded,'requestFullscreen() should not succeed when the element is an already-showing Popover'); } assert_true(tested_something); ensureIsOpenPopover(ex); @@ -111,14 +104,46 @@ assert_false(ex.hasAttribute('open')); } else if (isFullscreen(ex)) { let requestSucceeded = false; - await blessTopLayer(visible) - .then(() => ex.requestFullscreen()) - .then(() => { - assert_throws_dom("InvalidStateError",() => ex.showPopover(),'Calling showPopover() on an already-fullscreen element should throw InvalidStateError'); - }); + await blessTopLayer(visible); + await ex.requestFullscreen() + .then(() => { + assert_throws_dom("InvalidStateError",() => ex.showPopover(),'Calling showPopover() on an already-fullscreen element should throw InvalidStateError'); + }); await document.exitFullscreen() .then(() => assert_true(true)); } + + // Finally, try invoking these combined popovers via a declarative invoker + const button = document.createElement('button'); + t.add_cleanup(() => button.remove()); + document.body.appendChild(button); + assert_equals(ex.id,''); + ex.id = 'popover-id'; + button.popoverToggleTarget = ex.id; + assert_true(ex.matches(':closed')); + await clickOn(button); + ensureIsOpenPopover(ex,'Invoking element should be able to invoke all popovers'); + ex.hidePopover(); + if (isDialog(ex)) { + ex.showModal(); + assert_true(ex.hasAttribute('open')); + } else if (isFullscreen(ex)) { + // Popover fullscreen isn't visible by default, so explicitly add + // display:block, so that calls to "clickOn" can succeed. + ex.classList.add('visible'); + await blessTopLayer(visible); + await ex.requestFullscreen(); + } else { + assert_unreached('Not a dialog or fullscreen'); + } + ex.appendChild(button); // Add button to the element, so it's visible to click + await clickOn(button); + assert_true(ex.matches(':closed'),'The invoker click should have failed on the already-open dialog/fullscreen'); + if (isDialog(ex)) { + ex.close(); + } else { + await document.exitFullscreen() + } }, `Popover combination: ${ex.textContent}`); }); }));
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/document-rules.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/document-rules.https.html new file mode 100644 index 0000000..a5030f69 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/document-rules.https.html
@@ -0,0 +1,136 @@ +<!DOCTYPE html> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> +<script src="/common/dispatcher/dispatcher.js"></script> +<script src="resources/utils.sub.js"></script> +<script src="/common/subset-tests-by-key.js"></script> + +<meta name="variant" content="?include=defaultPredicate"> +<meta name="variant" content="?include=hrefMatches"> +<meta name="variant" content="?include=and"> +<meta name="variant" content="?include=or"> +<meta name="variant" content="?include=not"> +<meta name="variant" content="?include=invalidPredicate"> +<meta name="variant" content="?include=linkInShadowTree"> + +<body> +<script> + subsetTestByKey('defaultPredicate', promise_test, async t => { + assert_implements(HTMLScriptElement.supports('speculationrules'), + 'Speculation Rules not supported'); + + const url = getPrefetchUrl(); + addLink(url); + insertDocumentRule(); + await new Promise(resolve => t.step_timeout(resolve, 2000)); + + assert_equals(await isUrlPrefetched(url), 1); + }, 'test document rule with no predicate'); + + subsetTestByKey('hrefMatches', promise_test, async t => { + assert_implements(HTMLScriptElement.supports('speculationrules'), + 'Speculation Rules not supported'); + + insertDocumentRule({ href_matches: '*\\?uuid=*&foo=bar' }); + + const url_1 = getPrefetchUrl({foo: 'bar'}); + addLink(url_1); + const url_2 = getPrefetchUrl({foo: 'buzz'}); + addLink(url_2) + await new Promise(resolve => t.step_timeout(resolve, 2000)); + + assert_equals(await isUrlPrefetched(url_1), 1); + assert_equals(await isUrlPrefetched(url_2), 0); + }, 'test href_matches document rule'); + + subsetTestByKey('and', promise_test, async t => { + assert_implements(HTMLScriptElement.supports('speculationrules'), + 'Speculation Rules not supported'); + + insertDocumentRule({ + 'and': [ + { href_matches: '*\\?*foo=bar*' }, + { href_matches: '*\\?*fizz=buzz*' }] + }); + + const url_1 = getPrefetchUrl({foo: 'bar'}); + const url_2 = getPrefetchUrl({fizz: 'buzz'}); + const url_3 = getPrefetchUrl({foo: 'bar', fizz: 'buzz'}); + [url_1, url_2, url_3].forEach(url => addLink(url)); + await new Promise(resolve => t.step_timeout(resolve, 2000)); + + assert_equals(await isUrlPrefetched(url_1), 0); + assert_equals(await isUrlPrefetched(url_2), 0); + assert_equals(await isUrlPrefetched(url_3), 1); + }, 'test document rule with conjunction predicate'); + + subsetTestByKey('or', promise_test, async t => { + assert_implements(HTMLScriptElement.supports('speculationrules'), + 'Speculation Rules not supported'); + + insertDocumentRule({ + 'or': [ + { href_matches: '*\\?*foo=bar*' }, + { href_matches: '*\\?*fizz=buzz*' }] + }); + + const url_1 = getPrefetchUrl({ foo: 'buzz' }); + const url_2 = getPrefetchUrl({ fizz: 'buzz' }); + const url_3 = getPrefetchUrl({ foo: 'bar'}); + [url_1, url_2, url_3].forEach(url => addLink(url)); + await new Promise(resolve => t.step_timeout(resolve, 2000)); + + assert_equals(await isUrlPrefetched(url_1), 0); + assert_equals(await isUrlPrefetched(url_2), 1); + assert_equals(await isUrlPrefetched(url_3), 1); + }, 'test document rule with disjunction predicate'); + + subsetTestByKey('not', promise_test, async t => { + assert_implements(HTMLScriptElement.supports('speculationrules'), + "Speculation Rules not supported"); + + insertDocumentRule({ not: { href_matches: '*\\?uuid=*&foo=bar' } }); + + const url_1 = getPrefetchUrl({foo: 'bar'}); + addLink(url_1); + const url_2 = getPrefetchUrl({foo: 'buzz'}); + addLink(url_2) + await new Promise(resolve => t.step_timeout(resolve, 2000)); + + assert_equals(await isUrlPrefetched(url_1), 0); + assert_equals(await isUrlPrefetched(url_2), 1); + }, 'test document rule with negation predicate'); + + subsetTestByKey('invalidPredicate', promise_test, async t => { + assert_implements(HTMLScriptElement.supports('speculationrules'), + 'Speculation Rules not supported'); + + const url = getPrefetchUrl(); + addLink(url); + insertDocumentRule({invalid: 'predicate'}); + await new Promise(resolve => t.step_timeout(resolve, 2000)); + + assert_equals(await isUrlPrefetched(url), 0); + }, 'invalid predicate should not throw error or start prefetch'); + + subsetTestByKey('linkInShadowTree', promise_test, async t => { + assert_implements(HTMLScriptElement.supports('speculationrules'), + 'Speculation Rules not supported'); + + insertDocumentRule(); + + // Create shadow root. + const shadowHost = document.createElement('div'); + document.body.appendChild(shadowHost); + const shadowRoot = shadowHost.attachShadow({mode: 'open'}); + + const url = getPrefetchUrl(); + addLink(url, shadowRoot); + await new Promise(resolve => t.step_timeout(resolve, 2000)); + + assert_equals(await isUrlPrefetched(url), 1); + }, 'test that matching link in a shadow tree is prefetched'); + +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/referrer-policy-from-rules.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/referrer-policy-from-rules.https.html index 01e32ba..ce3db0f9 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/referrer-policy-from-rules.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/referrer-policy-from-rules.https.html
@@ -6,7 +6,8 @@ <meta name="variant" content="?2-2"> <meta name="variant" content="?3-3"> <meta name="variant" content="?4-4"> -<meta name="variant" content="?5-last"> +<meta name="variant" content="?5-5"> +<meta name="variant" content="?6-last"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -38,6 +39,25 @@ assert_implements(HTMLScriptElement.supports('speculationrules'), "Speculation Rules not supported"); const agent = await spawnWindow(t); + const next_url = agent.getExecutorURL({ page: 2 }); + await agent.execute_script((url) => { + const a = addLink(url); + a.referrerPolicy = 'no-referrer'; + insertDocumentRule(undefined, { referrer_policy: 'strict-origin' }); + }, [next_url]); + await new Promise(resolve => t.step_timeout(resolve, 2000)); + await agent.navigate(next_url); + + const headers = await agent.getRequestHeaders(); + assert_prefetched(headers, 'must be prefetched'); + const expected_referrer = next_url.origin + '/'; + assert_equals(headers.referer, expected_referrer, 'must send the origin as the referrer'); +}, 'with "strict-origin" referrer policy in rule set override "no-referrer" of link'); + +subsetTest(promise_test, async t => { + assert_implements(HTMLScriptElement.supports('speculationrules'), "Speculation Rules not supported"); + + const agent = await spawnWindow(t); await agent.setReferrerPolicy("unsafe-url"); const nextURL = agent.getExecutorURL({ page: 2 });
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/referrer-policy.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/referrer-policy.https.html index aaeae16..1987d2e 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/referrer-policy.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/referrer-policy.https.html
@@ -4,7 +4,8 @@ <!--Split test cases due to the use of timeouts in speculation rules test utilities.--> <meta name="variant" content="?1-1"> <meta name="variant" content="?2-2"> -<meta name="variant" content="?3-last"> +<meta name="variant" content="?3-3"> +<meta name="variant" content="?4-last"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -63,4 +64,25 @@ assert_equals(headers.referer, '', "must send no referrer"); }, 'with "no-referrer" referrer policy'); +subsetTest(promise_test, async t => { + assert_implements(HTMLScriptElement.supports('speculationrules'), "Speculation Rules not supported"); + + const agent = await spawnWindow(t); + await agent.setReferrerPolicy("no-referrer"); + + const next_url = agent.getExecutorURL({ page: 2 }); + await agent.execute_script((url) => { + const a = addLink(url); + a.referrerPolicy = 'strict-origin'; + insertDocumentRule(); + }, [next_url]); + await new Promise(resolve => t.step_timeout(resolve, 2000)); + await agent.navigate(next_url); + + const headers = await agent.getRequestHeaders(); + const expected_referrer = next_url.origin + '/'; + assert_prefetched(headers, 'must be prefetched'); + assert_equals(headers.referer, expected_referrer); +}, 'with "strict-origin" link referrer policy overriding "no-referrer" of referring page'); + </script>
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/resources/utils.sub.js b/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/resources/utils.sub.js index f532f35..b29dd6bb 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/resources/utils.sub.js +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prefetch/resources/utils.sub.js
@@ -96,14 +96,17 @@ } } +// Produces a URL with a UUID which will record when it's prefetched. +// |extra_params| can be specified to add extra search params to the generated +// URL. +function getPrefetchUrl(extra_params={}) { + let params = new URLSearchParams({ uuid: token(), ...extra_params }); + return new URL(`prefetch.py?${params}`, SR_PREFETCH_UTILS_URL); +} + // Produces n URLs with unique UUIDs which will record when they are prefetched. function getPrefetchUrlList(n) { - let urls = []; - for (let i=0; i<n; i++) { - let params = new URLSearchParams({uuid: token()}); - urls.push(new URL(`prefetch.py?${params}`, SR_PREFETCH_UTILS_URL)); - } - return urls; + return Array.from({ length: n }, () => getPrefetchUrl()); } function getRedirectUrl() { @@ -132,6 +135,28 @@ document.head.appendChild(script); } +// Creates and appends <a href=|href|> to |insertion point|. If +// |insertion_point| is not specified, document.body is used. +function addLink(href, insertion_point=document.body) { + const a = document.createElement('a'); + a.href = href; + insertion_point.appendChild(a); + return a; +} + +// Inserts a prefetch document rule with |predicate|. |predicate| can be +// undefined, in which case the default predicate will be used (i.e. all links +// in document will match). +function insertDocumentRule(predicate, extra_options={}) { + insertSpeculationRules({ + prefetch: [{ + source: 'document', + where: predicate, + ...extra_options + }] + }); +} + function assert_prefetched (requestHeaders, description) { assert_in_array(requestHeaders.purpose, ["", "prefetch"], "The vendor-specific header Purpose, if present, must be 'prefetch'."); assert_equals(requestHeaders.sec_purpose, "prefetch", description);
diff --git a/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any-expected.txt b/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any-expected.txt new file mode 100644 index 0000000..9fb8be1b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS getAuthorizationHeaderValue - no redirection +PASS getAuthorizationHeaderValue - same origin redirection +FAIL getAuthorizationHeaderValue - cross origin redirection assert_equals: expected "none" but got "Basic dXNlcjpwYXNz" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.js b/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.js new file mode 100644 index 0000000..e9a4db4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.js
@@ -0,0 +1,28 @@ +// META: global=window,worker +// META: script=/common/get-host-info.sub.js + +const authorizationValue = "Basic " + btoa("user:pass"); +function getAuthorizationHeaderValue(url) +{ + var client = new XMLHttpRequest(); + client.open("GET", url, false); + client.setRequestHeader("Authorization", authorizationValue); + const promise = new Promise(resolve => client.onloadend = () => resolve(client.responseText)); + client.send(); + return promise; +} + +promise_test(async test => { + const result = await getAuthorizationHeaderValue("/fetch/api/resources/dump-authorization-header.py"); + assert_equals(result, authorizationValue); +}, "getAuthorizationHeaderValue - no redirection"); + +promise_test(async test => { + const result = await getAuthorizationHeaderValue("/fetch/api/resources/redirect.py?location=" + encodeURIComponent("/fetch/api/resources/dump-authorization-header.py")); + assert_equals(result, authorizationValue); +}, "getAuthorizationHeaderValue - same origin redirection"); + +promise_test(async (test) => { + const result = await getAuthorizationHeaderValue(get_host_info().HTTP_REMOTE_ORIGIN + "/fetch/api/resources/redirect.py?allow_headers=Authorization&location=" + encodeURIComponent(get_host_info().HTTP_ORIGIN + "/fetch/api/resources/dump-authorization-header.py")); + assert_equals(result, "none"); +}, "getAuthorizationHeaderValue - cross origin redirection");
diff --git a/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.serviceworker-expected.txt b/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.serviceworker-expected.txt new file mode 100644 index 0000000..b1c0db93 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.serviceworker-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +FAIL getAuthorizationHeaderValue - no redirection promise_test: Unhandled rejection with value: object "ReferenceError: XMLHttpRequest is not defined" +FAIL getAuthorizationHeaderValue - same origin redirection promise_test: Unhandled rejection with value: object "ReferenceError: XMLHttpRequest is not defined" +FAIL getAuthorizationHeaderValue - cross origin redirection promise_test: Unhandled rejection with value: object "ReferenceError: XMLHttpRequest is not defined" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.sharedworker-expected.txt b/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.sharedworker-expected.txt new file mode 100644 index 0000000..9fb8be1b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.sharedworker-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS getAuthorizationHeaderValue - no redirection +PASS getAuthorizationHeaderValue - same origin redirection +FAIL getAuthorizationHeaderValue - cross origin redirection assert_equals: expected "none" but got "Basic dXNlcjpwYXNz" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.worker-expected.txt new file mode 100644 index 0000000..9fb8be1b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/xhr/xhr-authorization-redirect.any.worker-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS getAuthorizationHeaderValue - no redirection +PASS getAuthorizationHeaderValue - same origin redirection +FAIL getAuthorizationHeaderValue - cross origin redirection assert_equals: expected "none" but got "Basic dXNlcjpwYXNz" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/virtual/expose-lcp-render-time/external/wpt/performance-timeline/cross-origin-non-tao-image.sub-expected.txt b/third_party/blink/web_tests/platform/mac-mac11-arm64/virtual/expose-lcp-render-time/external/wpt/performance-timeline/cross-origin-non-tao-image.sub-expected.txt new file mode 100644 index 0000000..d411c04 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac11-arm64/virtual/expose-lcp-render-time/external/wpt/performance-timeline/cross-origin-non-tao-image.sub-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL lcp and fcp assert_approx_equals: expected 70.79999999981374 +/- 0.001 but got 72.399 +Harness: the test ran to completion. +
diff --git a/third_party/ipcz/src/ipcz/portal.cc b/third_party/ipcz/src/ipcz/portal.cc index 270b747..14357e7 100644 --- a/third_party/ipcz/src/ipcz/portal.cc +++ b/third_party/ipcz/src/ipcz/portal.cc
@@ -12,6 +12,7 @@ #include "ipcz/local_router_link.h" #include "ipcz/operation_context.h" #include "ipcz/router.h" +#include "ipcz/trap_event_dispatcher.h" #include "third_party/abseil-cpp/absl/types/span.h" #include "util/log.h" #include "util/ref_counted.h" @@ -237,13 +238,14 @@ IpczResult Portal::CommitGet(size_t num_data_bytes_consumed, absl::Span<IpczHandle> handles) { + TrapEventDispatcher dispatcher; absl::MutexLock lock(&mutex_); if (!in_two_phase_get_) { return IPCZ_RESULT_FAILED_PRECONDITION; } - IpczResult result = - router_->CommitGetNextIncomingParcel(num_data_bytes_consumed, handles); + IpczResult result = router_->CommitGetNextIncomingParcel( + num_data_bytes_consumed, handles, dispatcher); if (result == IPCZ_RESULT_OK) { in_two_phase_get_ = false; }
diff --git a/third_party/ipcz/src/ipcz/router.cc b/third_party/ipcz/src/ipcz/router.cc index 63b0bb6..ea05b2a 100644 --- a/third_party/ipcz/src/ipcz/router.cc +++ b/third_party/ipcz/src/ipcz/router.cc
@@ -494,10 +494,11 @@ return IPCZ_RESULT_OK; } -IpczResult Router::CommitGetNextIncomingParcel(size_t num_data_bytes_consumed, - absl::Span<IpczHandle> handles) { +IpczResult Router::CommitGetNextIncomingParcel( + size_t num_data_bytes_consumed, + absl::Span<IpczHandle> handles, + TrapEventDispatcher& dispatcher) { const OperationContext context{OperationContext::kAPICall}; - TrapEventDispatcher dispatcher; { absl::MutexLock lock(&mutex_); if (inward_edge_) {
diff --git a/third_party/ipcz/src/ipcz/router.h b/third_party/ipcz/src/ipcz/router.h index 9da6073..78c9f25678 100644 --- a/third_party/ipcz/src/ipcz/router.h +++ b/third_party/ipcz/src/ipcz/router.h
@@ -27,6 +27,7 @@ class NodeLink; class RemoteRouterLink; struct RouterLinkState; +class TrapEventDispatcher; // The Router is the main primitive responsible for routing parcels between ipcz // portals. This class is thread-safe. @@ -164,7 +165,8 @@ // consuming some (possibly all) bytes and handles from that parcel. Once a // parcel is fully consumed, it's removed from the inbound queue. IpczResult CommitGetNextIncomingParcel(size_t num_data_bytes_consumed, - absl::Span<IpczHandle> handles); + absl::Span<IpczHandle> handles, + TrapEventDispatcher& dispatcher); // Attempts to install a new trap on this Router, to invoke `handler` as soon // as one or more conditions in `conditions` is met. This method effectively
diff --git a/third_party/ipcz/src/reference_drivers/random.cc b/third_party/ipcz/src/reference_drivers/random.cc index 83c0e6f..e228466 100644 --- a/third_party/ipcz/src/reference_drivers/random.cc +++ b/third_party/ipcz/src/reference_drivers/random.cc
@@ -45,7 +45,7 @@ namespace { -#if defined(OS_POSIX) +#if defined(OS_POSIX) && !BUILDFLAG(IS_MAC) void RandomBytesFromDevUrandom(absl::Span<uint8_t> destination) { static int urandom_fd = [] { for (;;) { @@ -92,12 +92,8 @@ } } #elif BUILDFLAG(IS_MAC) - if (__builtin_available(macOS 10.12, *)) { - const bool ok = getentropy(destination.data(), destination.size()) == 0; - ABSL_ASSERT(ok); - } else { - RandomBytesFromDevUrandom(destination); - } + const bool ok = getentropy(destination.data(), destination.size()) == 0; + ABSL_ASSERT(ok); #elif BUILDFLAG(IS_IOS) RandomBytesFromDevUrandom(destination); #elif BUILDFLAG(IS_NACL)
diff --git a/third_party/modp_b64/modp_b64.cc b/third_party/modp_b64/modp_b64.cc index 2901a8f..9be5820 100644 --- a/third_party/modp_b64/modp_b64.cc +++ b/third_party/modp_b64/modp_b64.cc
@@ -117,10 +117,11 @@ size_t modp_b64_decode(char* dest, const char* src, size_t len, ModpDecodePolicy policy) { - if (len == 0 || - (len = do_decode_padding(src, len, policy)) == MODP_B64_ERROR) { + if (len != 0) + len = do_decode_padding(src, len, policy); + + if (len == 0 || len == MODP_B64_ERROR) return len; - } size_t i; int leftover = len % 4;
diff --git a/third_party/mozilla/LICENSE b/third_party/mozilla/LICENSE index 961b0cf..ce36906 100644 --- a/third_party/mozilla/LICENSE +++ b/third_party/mozilla/LICENSE
@@ -1,35 +1,32 @@ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 2002 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ +Version: MPL 1.1/GPL 2.0/LGPL 2.1 + +The contents of this file are subject to the Mozilla Public License Version +1.1 (the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at +http://www.mozilla.org/MPL/ + +Software distributed under the License is distributed on an "AS IS" basis, +WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +for the specific language governing rights and limitations under the +License. + +The Original Code is mozilla.org code. + +The Initial Developer of the Original Code is +Netscape Communications Corporation. +Portions created by the Initial Developer are Copyright (C) 2002 +the Initial Developer. All Rights Reserved. + +Contributor(s): + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the MPL, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the MPL, the GPL or the LGPL.
diff --git a/third_party/rust/clap/v3/README.chromium b/third_party/rust/clap/v3/README.chromium index b0075bf..9b6e3632 100644 --- a/third_party/rust/clap/v3/README.chromium +++ b/third_party/rust/clap/v3/README.chromium
@@ -4,3 +4,4 @@ Version: 3.1.12 Security Critical: no License: Apache 2.0 +Revision: d805c6031de73b6cab7e5f7afa9632aab273ed10
diff --git a/tools/browserbench-webdriver/browserbench.py b/tools/browserbench-webdriver/browserbench.py index 5234ae2..8cd8114d 100644 --- a/tools/browserbench-webdriver/browserbench.py +++ b/tools/browserbench-webdriver/browserbench.py
@@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +from enum import Enum from optparse import OptionParser from selenium import webdriver @@ -22,6 +23,14 @@ MAX_ATTEMPTS = 6 +class Channel(Enum): + UNKNOWN = 1 + CANARY = 2 + DEV = 3 + BETA = 4 + STABLE = 5 + + class BrowserBench(object): def __init__(self, name, version): # Log more information to help identify failures. @@ -33,6 +42,7 @@ self._browser = None self._driver = None self._is_120 = BrowserBench._IsDisplayRefreshRate120() + self._channel = Channel.UNKNOWN @staticmethod def _IsDisplayRefreshRate120(): @@ -41,23 +51,33 @@ # string Hz = 120 then display is at 120. This likely isn't right if there # are multiple displays, but it's good enough for the lab where we only # have devices with a single display. - windowserver_output = subprocess.run(["defaults", "read", - WS_DISPLAY_LIST_PATH], - capture_output=True) - return windowserver_output.stdout.decode('utf-8').find('Hz = 120') != -1 + try: + windowserver_output = subprocess.run(["defaults", "read", + WS_DISPLAY_LIST_PATH], + capture_output=True) + return windowserver_output.stdout.decode('utf-8').find('Hz = 120') != -1 + except Exception as e: + logging.warning('Determining refresh rated generated exception, ' + 'assuming 60hz and continuing', exc_info=True) + return False + @staticmethod - def _CreateChromeDriver(optargs): + def _CreateChromeDriver(optargs, channel): options = webdriver.ChromeOptions() - options.add_argument('enable-benchmarking') + args = ['enable-benchmarking' , 'no-first-run'] if optargs.arguments: for arg in optargs.arguments.split(','): - options.add_argument(arg) - else: - # If no arguments were given, enable field trial config and no first run. - # These ensure a consistent set of flags. - options.add_argument('--no-first-run') - options.add_argument('--enable-field-trial-config') + args.append(arg) + + if channel != Channel.STABLE: + args.append('--enable-field-trial-config') + logging.info('Using field trial config for non-stable channel') + + for arg in args: + options.add_argument(arg) + + logging.info(f'Chrome arguments {args}') if optargs.chrome_path: options.binary_location = optargs.chrome_path @@ -108,9 +128,9 @@ return version.strip() @staticmethod - def _CreateDriver(optargs): + def _CreateDriver(optargs, channel): if optargs.browser == 'chrome': - return BrowserBench._CreateChromeDriver(optargs) + return BrowserBench._CreateChromeDriver(optargs, channel) elif optargs.browser == 'safari' or optargs.browser == 'stp': for i in range(0, 10): try: @@ -148,9 +168,9 @@ logging.warning('Not handling kill of chrome, if this is hit and test ' 'fails, implement it') - def _CreateDriverAndRun(self, optargs): + def _CreateDriverAndRun(self, optargs, channel): logging.info('Creating Driver') - self._driver = BrowserBench._CreateDriver(optargs) + self._driver = BrowserBench._CreateDriver(optargs, channel) if not self._driver: raise Exception('failed to create driver') self._driver.set_window_size(900, 780) @@ -280,6 +300,17 @@ assert len(pairs) % 2 == 0 for i in range(0, len(pairs), 2): extra_key_values[pairs[i]] = pairs[i + 1] + if 'channel' in extra_key_values: + if extra_key_values['channel'].lower() == 'canary': + self._channel = Channel.CANARY + elif extra_key_values['channel'].lower() == 'dev': + self._channel = Channel.DEV + elif extra_key_values['channel'].lower() == 'beta': + self._channel = Channel.BETA + elif extra_key_values['channel'].lower() == 'stable': + self._channel = Channel.STABLE + else: + logging.warning('Unknown channel') self.UpdateParseArgs(optargs) @@ -291,7 +322,7 @@ while not measurements and run_count < MAX_ATTEMPTS: run_count += 1 try: - measurements = self._CreateDriverAndRun(optargs) + measurements = self._CreateDriverAndRun(optargs, self._channel) break except Exception as e: if run_count < MAX_ATTEMPTS:
diff --git a/tools/crates/gnrt/download.rs b/tools/crates/gnrt/download.rs index f84a063b1..0b8ea40 100644 --- a/tools/crates/gnrt/download.rs +++ b/tools/crates/gnrt/download.rs
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::fs; use std::io::{Read, Write}; use std::process::{self, ExitCode}; @@ -84,7 +85,26 @@ .find(|(allowed_license, _)| &cargo.package.license == *allowed_license) .expect("License in downloaded Cargo.toml is not in ALLOWED_LICENSES"); - let readme = gen_readme_chromium_text(&cargo, readme_license, security); + let vcs_path = crate_path.join(".cargo_vcs_info.json"); + let vcs_contents = match fs::read_to_string(&vcs_path) { + Ok(s) => serde_json::from_str(&s).unwrap(), + Err(_) => None, + }; + let githash: Option<&str> = vcs_contents.as_ref().and_then(|v| { + use serde_json::Value::*; + match v { + Object(map) => match map.get("git") { + Some(Object(map)) => match map.get("sha1") { + Some(String(s)) => Some(&s[..]), + _ => None, + }, + _ => None, + }, + _ => None, + } + }); + + let readme = gen_readme_chromium_text(&cargo, readme_license, githash, security); std::fs::write(build_path.join("README.chromium"), readme) .expect("Failed to write README.chromium"); @@ -94,12 +114,15 @@ } /// Generate the contents of the README.chromium file. -fn gen_readme_chromium_text(manifest: &CargoManifest, license: &str, security: bool) -> String { - let security = if security { - "yes" - } else { - "no" - }; +fn gen_readme_chromium_text( + manifest: &CargoManifest, + license: &str, + githash: Option<&str>, + security: bool, +) -> String { + let security = if security { "yes" } else { "no" }; + + let revision = githash.map_or_else(String::new, |s| format!("Revision: {s}\n")); format!( "Name: {crate_name}\n\ @@ -107,7 +130,8 @@ Description: {description}\n\ Version: {version}\n\ Security Critical: {security}\n\ - License: {license}\n", + License: {license}\n\ + {revision}", crate_name = manifest.package.name, url = format!("{}/{}", CRATES_IO_VIEW_URL, manifest.package.name), description = manifest.package.description.as_ref().unwrap_or(&"".to_string()),
diff --git a/tools/git/README b/tools/git/README.md similarity index 91% rename from tools/git/README rename to tools/git/README.md index 77cc47325..dddcd34 100644 --- a/tools/git/README +++ b/tools/git/README.md
@@ -3,12 +3,12 @@ post-checkout and post-merge ============================ These hooks warn you about DEPS modifications so you will remember -to run "gclient sync". +to run `gclient sync`. To install these Git hooks, create symlinks like so: - ln -s $(pwd)/post-checkout $(git rev-parse --git-dir)/hooks - ln -s $(pwd)/post-merge $(git rev-parse --git-dir)/hooks + ln -s $(pwd)/post-checkout $(git rev-parse --git-dir)/hooks + ln -s $(pwd)/post-merge $(git rev-parse --git-dir)/hooks git-graph ========= @@ -17,7 +17,6 @@ suggest_owners ============== - A script to suggest new owners for subdirectories in a git repo based on commit count to the relevant subdirectory. @@ -50,4 +49,3 @@ --dir-commit-limit DIR_COMMIT_LIMIT Merge directories with less than this number of commits into their parent directory. (default: 100) -
diff --git a/tools/git/for-all-touched-files.py b/tools/git/for-all-touched-files.py index 5ed40c9..0578c04 100755 --- a/tools/git/for-all-touched-files.py +++ b/tools/git/for-all-touched-files.py
@@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # Copyright 2011 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. @@ -22,8 +22,6 @@ %prog -t "~~BINGO~~" "echo I modified ~~BINGO~~" """ -from __future__ import print_function - import optparse import os import subprocess
diff --git a/tools/git/git-diff-ide.py b/tools/git/git-diff-ide.py index 3a0a315..58f858c 100755 --- a/tools/git/git-diff-ide.py +++ b/tools/git/git-diff-ide.py
@@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # Copyright 2012 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. @@ -18,8 +18,6 @@ %prog HEAD """ -from __future__ import print_function - import subprocess import sys
diff --git a/tools/git/git-utils.sh b/tools/git/git-utils.sh index fb89c5b2..1f7976c 100755 --- a/tools/git/git-utils.sh +++ b/tools/git/git-utils.sh
@@ -4,7 +4,7 @@ # found in the LICENSE file. TPUT=$(which tput 2>/dev/null) -if test -x "$TPUT" && $TPUT setaf 1 >/dev/null ; then +if test -x "$TPUT" && $TPUT setaf 1 >/dev/null; then RED="$($TPUT setaf 1)" NORMAL="$($TPUT op)" else
diff --git a/tools/git/post-checkout b/tools/git/post-checkout index 9facdd4..d8f4c4d 100755 --- a/tools/git/post-checkout +++ b/tools/git/post-checkout
@@ -3,12 +3,12 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -script=$(readlink $0) -source $(dirname ${script:-$0})/git-utils.sh +script="$(readlink $0)" +source "$(dirname ${script:-$0})/git-utils.sh" -old_ref=$1 # Previous HEAD. -new_ref=$2 # Current HEAD. -branch_switch=$3 # Whether we switched branches. +old_ref="$1" # Previous HEAD. +new_ref="$2" # Current HEAD. +branch_switch="$3" # Whether we switched branches. if [ $old_ref == $new_ref ]; then if ! git diff-index --quiet HEAD $(git rev-parse --show-cdup)DEPS; then
diff --git a/tools/git/post-merge b/tools/git/post-merge index 8af0555..f3fc157 100755 --- a/tools/git/post-merge +++ b/tools/git/post-merge
@@ -3,8 +3,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -script=$(readlink $0) -source $(dirname ${script:-$0})/git-utils.sh +script="$(readlink $0)" +source "$(dirname ${script:-$0})/git-utils.sh" if git diff-tree ORIG_HEAD HEAD | grep -qs $'\tDEPS$'; then warn "DEPS has changed; you probably need to re-run gclient sync."
diff --git a/tools/mac/power/benchmark.py b/tools/mac/power/benchmark.py index 19bc9c6..3fbd54b 100755 --- a/tools/mac/power/benchmark.py +++ b/tools/mac/power/benchmark.py
@@ -13,9 +13,9 @@ from driver import DriverContext import scenarios import browsers +import plug import utils - def IterScenarios( scenario_names: typing.List[str], browser_driver_factory: typing.Callable[[], browsers.BrowserDriver], @@ -79,6 +79,15 @@ default=False, help='Print verbose output.') + # If an ip is provided for the Kasa switch it needs to be fully set up + # (see plug.py). It will be used to keep the machine charged between + # scenarios. + parser.add_argument( + "--kasa_switch_ip", + required=False, + help="IP address of the kasa power switch controlling the current device." + ) + parser.add_argument('--extra-command-line', dest='extra_command_line', action='store') @@ -96,6 +105,10 @@ output_dir = os.path.join("output", datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) + kasa_plug_controller = None + if args.kasa_switch_ip: + kasa_plug_controller = plug.get_plug_controller(args.kasa_switch_ip) + logging.info(f'Outputing results in {os.path.abspath(output_dir)}') with DriverContext(output_dir, args.power_sampler) as driver: driver.CheckEnv(not args.no_checks) @@ -118,6 +131,9 @@ BrowserFactory, meet_meeting_id=args.meet_meeting_id): + if kasa_plug_controller: + kasa_plug_controller.charge_to(80) + if args.tracing_mode: logging.info(f'Tracing scenario {scenario.name} ...') driver.Trace(scenario)
diff --git a/tools/mac/power/plug.py b/tools/mac/power/plug.py index 2c24ca1..c031122 100755 --- a/tools/mac/power/plug.py +++ b/tools/mac/power/plug.py
@@ -36,11 +36,16 @@ self.strip = SmartStrip(kasa_switch_ip) self.loop.run_until_complete(self.strip.update()) + self.closed = False + + def __del__(self): + self.close() + def turn_on(self, device: str): """Turns the plug for |device| to the on position """ - for plug in strip.children: + for plug in self.strip.children: if plug.alias == device: self.loop.run_until_complete(plug.turn_on()) return @@ -49,7 +54,7 @@ def turn_off(self, device: str): """Turns the plug for |device| to the off position """ - for plug in strip.children: + for plug in self.strip.children: if plug.alias == device: self.loop.run_until_complete(plug.turn_off()) return @@ -63,7 +68,7 @@ device = os.uname()[1].split('.')[0] print(f"Plugging in {device}...") - turn_on(device) + self.turn_on(device) battery = psutil.sensors_battery() while not battery.power_plugged: @@ -77,8 +82,8 @@ battery = psutil.sensors_battery() time.sleep(10) - turn_off(device) print(f"Unplugging {device}...") + self.turn_off(device) battery = psutil.sensors_battery() while battery.power_plugged: battery = psutil.sensors_battery() @@ -88,9 +93,16 @@ def close(self): """Closes the message loop. """ + if self.closed: + return + self.closed = True self.loop.close() +def get_plug_controller(ip: str): + return KasaPlugController(ip) + + if __name__ == "__main__": parser = argparse.ArgumentParser( description='Controls kasa power switch connected to this device.') @@ -98,10 +110,11 @@ required=True, help="IP address of the kasa power switch.") parser.add_argument("--charge_level", + type=int, required=True, help="Desired charge level.") args = parser.parse_args() kasa_plug_controller = KasaPlugController(args.kasa_switch_ip) - kasa.plug_controller.charge_to(args.charge_level) + kasa_plug_controller.charge_to(args.charge_level) kasa_plug_controller.close()
diff --git a/tools/mac/power/power_sampler/battery_sampler.h b/tools/mac/power/power_sampler/battery_sampler.h index da29d9d1..949204f 100644 --- a/tools/mac/power/power_sampler/battery_sampler.h +++ b/tools/mac/power/power_sampler/battery_sampler.h
@@ -6,6 +6,7 @@ #define TOOLS_MAC_POWER_POWER_SAMPLER_BATTERY_SAMPLER_H_ #include <stdint.h> +#include <cstdint> #include <memory> #include "base/mac/scoped_ioobject.h" @@ -57,9 +58,11 @@ int64_t voltage_mv; int64_t current_capacity_mah; int64_t max_capacity_mah; + int64_t update_time_seconds_since_epoch; }; using MaybeGetBatteryDataFn = absl::optional<BatteryData> (*)(io_service_t power_source); + using GetSecondsSinceEpochFn = int64_t (*)(); // TODO(siggi): It'd be possible to test the data extraction part of this // function by splitting it in two and passing it a dictionary to @@ -76,9 +79,11 @@ static std::unique_ptr<BatterySampler> CreateImpl( MaybeGetBatteryDataFn maybe_get_battery_data_fn, + GetSecondsSinceEpochFn get_seconds_since_epoch_fn, base::mac::ScopedIOObject<io_service_t> power_source); BatterySampler(MaybeGetBatteryDataFn maybe_get_battery_data_fn, + GetSecondsSinceEpochFn get_seconds_since_epoch_fn, base::mac::ScopedIOObject<io_service_t> power_source, BatteryData initial_battery_data); @@ -87,6 +92,7 @@ const BatteryData& battery_data); const MaybeGetBatteryDataFn maybe_get_battery_data_fn_; + const GetSecondsSinceEpochFn get_seconds_since_epoch_fn_; const base::mac::ScopedIOObject<io_service_t> power_source_; // To compute the average power consumed between non-identical
diff --git a/tools/mac/power/power_sampler/battery_sampler.mm b/tools/mac/power/power_sampler/battery_sampler.mm index af1e3e9..80f76f9 100644 --- a/tools/mac/power/power_sampler/battery_sampler.mm +++ b/tools/mac/power/power_sampler/battery_sampler.mm
@@ -7,6 +7,7 @@ #import <Foundation/Foundation.h> #include <IOKit/IOKitLib.h> #include <IOKit/ps/IOPSKeys.h> +#include <cstdint> #include "base/logging.h" #include "base/mac/foundation_util.h" @@ -56,7 +57,12 @@ if (power_source == IO_OBJECT_NULL) return nullptr; - return CreateImpl(MaybeGetBatteryData, std::move(power_source)); + auto get_seconds_since_epoch_fn = []() -> int64_t { + return (base::Time::Now() - base::Time::UnixEpoch()).InSeconds(); + }; + + return CreateImpl(MaybeGetBatteryData, get_seconds_since_epoch_fn, + std::move(power_source)); } std::string BatterySampler::GetName() { @@ -70,6 +76,7 @@ ret.emplace("current_capacity", "Ah"); ret.emplace("max_capacity", "Ah"); ret.emplace("avg_power", "W"); + ret.emplace("sample_age", "s"); return ret; } @@ -103,6 +110,8 @@ sample.emplace("voltage", new_data.voltage_mv / 1000.0); sample.emplace("current_capacity", new_data.current_capacity_mah / 1000.0); sample.emplace("max_capacity", new_data.max_capacity_mah / 1000.0); + sample.emplace("sample_age", get_seconds_since_epoch_fn_() - + new_data.update_time_seconds_since_epoch); // Store the battery state only if the consumed capacity is different from the // initial state. If the consumed capacity is identical to the initial state, @@ -138,6 +147,8 @@ GetValueAsSInt64(dict, CFSTR("AppleRawCurrentCapacity")); absl::optional<SInt64> max_capacity_mah = GetValueAsSInt64(dict, CFSTR("AppleRawMaxCapacity")); + absl::optional<SInt64> update_time = + GetValueAsSInt64(dict, CFSTR("UpdateTime")); if (!external_connected.has_value() || !voltage_mv.has_value() || !current_capacity_mah.has_value() || !max_capacity_mah.has_value()) { @@ -147,7 +158,8 @@ BatteryData data{.external_connected = external_connected.value(), .voltage_mv = voltage_mv.value(), .current_capacity_mah = current_capacity_mah.value(), - .max_capacity_mah = max_capacity_mah.value()}; + .max_capacity_mah = max_capacity_mah.value(), + .update_time_seconds_since_epoch = update_time.value()}; return data; } @@ -192,21 +204,25 @@ // static std::unique_ptr<BatterySampler> BatterySampler::CreateImpl( MaybeGetBatteryDataFn maybe_get_battery_data_fn, + GetSecondsSinceEpochFn get_seconds_since_epoch_fn, base::mac::ScopedIOObject<io_service_t> power_source) { // Validate that we can work with this source. auto battery_data = maybe_get_battery_data_fn(power_source.get()); if (!battery_data.has_value()) return nullptr; - return base::WrapUnique(new BatterySampler( - maybe_get_battery_data_fn, std::move(power_source), *battery_data)); + return base::WrapUnique( + new BatterySampler(maybe_get_battery_data_fn, get_seconds_since_epoch_fn, + std::move(power_source), *battery_data)); } BatterySampler::BatterySampler( MaybeGetBatteryDataFn maybe_get_battery_data_fn, + GetSecondsSinceEpochFn get_seconds_since_epoch_fn, base::mac::ScopedIOObject<io_service_t> power_source, BatteryData initial_battery_data) : maybe_get_battery_data_fn_(maybe_get_battery_data_fn), + get_seconds_since_epoch_fn_(get_seconds_since_epoch_fn), power_source_(std::move(power_source)), initial_consumed_mah_(initial_battery_data.max_capacity_mah - initial_battery_data.current_capacity_mah) {}
diff --git a/tools/mac/power/power_sampler/battery_sampler_unittest.cc b/tools/mac/power/power_sampler/battery_sampler_unittest.cc index 039f593..d13f81c 100644 --- a/tools/mac/power/power_sampler/battery_sampler_unittest.cc +++ b/tools/mac/power/power_sampler/battery_sampler_unittest.cc
@@ -4,6 +4,7 @@ #include "tools/mac/power/power_sampler/battery_sampler.h" +#include <cstdint> #include <memory> #include <IOKit/IOKitLib.h> @@ -36,6 +37,10 @@ battery_data_ = battery_data; } + static void set_seconds_since_epoch(int64_t seconds_since_epoch) { + seconds_since_epoch_ = seconds_since_epoch; + } + // The gmock *ElementsAre* matchers are too exacting for the double values // in our samples, but this poor man's substitute will do for our needs. template <size_t N> @@ -62,15 +67,21 @@ return battery_data_; } + static int64_t GetSecondsSinceEpoch() { return seconds_since_epoch_; } + static absl::optional<BatteryData> battery_data_; + static int64_t seconds_since_epoch_; }; absl::optional<BatterySamplerTest::BatteryData> BatterySamplerTest::battery_data_; +int64_t BatterySamplerTest::seconds_since_epoch_; + // static std::unique_ptr<BatterySampler> TestBatterySampler::CreateForTesting() { return BatterySampler::CreateImpl(BatterySamplerTest::GetStaticBatteryData, + BatterySamplerTest::GetSecondsSinceEpoch, base::mac::ScopedIOObject<io_service_t>()); } @@ -99,7 +110,8 @@ std::make_pair("voltage", "V"), std::make_pair("current_capacity", "Ah"), std::make_pair("max_capacity", "Ah"), - std::make_pair("avg_power", "W"))); + std::make_pair("avg_power", "W"), + std::make_pair("sample_age", "s"))); } TEST_F(BatterySamplerTest, MaybeComputeAvgPowerConsumption) { @@ -152,9 +164,10 @@ .external_connected = true, .voltage_mv = 11100, // 11.1V. .current_capacity_mah = 2001, // 2.001 Ah remaining. - .max_capacity_mah = 5225 // Corresponds to 58Wh/11.1V in mAh. - }; + .max_capacity_mah = 5225, // Corresponds to 58Wh/11.1V in mAh. + .update_time_seconds_since_epoch = 42}; set_battery_data(battery_data); + set_seconds_since_epoch(43); std::unique_ptr<BatterySampler> sampler( TestBatterySampler::CreateForTesting()); @@ -168,10 +181,13 @@ ExpectSampleMatchesArray(datums, {std::make_pair("external_connected", true), std::make_pair("voltage", 11.1), std::make_pair("current_capacity", 2.001), - std::make_pair("max_capacity", 5.225)}); + std::make_pair("max_capacity", 5.225), + std::make_pair("sample_age", 1)}); battery_data.current_capacity_mah -= 1; + battery_data.update_time_seconds_since_epoch = 44; set_battery_data(battery_data); + set_seconds_since_epoch(46); constexpr base::TimeDelta kOneMinute = base::Minutes(1); now += kOneMinute; @@ -180,23 +196,29 @@ // sample is identical to the initial state. Since the consumed capacity in // this sample is different than the initial state, it will be considered for // a power estimate in a future sample. - ExpectSampleMatchesArray(datums, {std::make_pair("external_connected", true), - std::make_pair("voltage", 11.1), - std::make_pair("current_capacity", 2), - std::make_pair("max_capacity", 5.225)}); + ExpectSampleMatchesArray( + datums, + {std::make_pair("external_connected", true), + std::make_pair("voltage", 11.1), std::make_pair("current_capacity", 2), + std::make_pair("max_capacity", 5.225), std::make_pair("sample_age", 2)}); battery_data.voltage_mv = 11200; // 11.2V. + battery_data.update_time_seconds_since_epoch = 47; set_battery_data(battery_data); + set_seconds_since_epoch(48); now += kOneMinute; datums = sampler->GetSample(now); // So long as there's no current consumption, there's no power estimate. - ExpectSampleMatchesArray(datums, {std::make_pair("external_connected", true), - std::make_pair("voltage", 11.2), - std::make_pair("current_capacity", 2), - std::make_pair("max_capacity", 5.225)}); + ExpectSampleMatchesArray( + datums, + {std::make_pair("external_connected", true), + std::make_pair("voltage", 11.2), std::make_pair("current_capacity", 2), + std::make_pair("max_capacity", 5.225), std::make_pair("sample_age", 1)}); battery_data.current_capacity_mah -= 1; + battery_data.update_time_seconds_since_epoch = 49; set_battery_data(battery_data); + set_seconds_since_epoch(49); now += kOneMinute; datums = sampler->GetSample(now); @@ -211,7 +233,8 @@ std::make_pair("voltage", 11.2), std::make_pair("current_capacity", 1.999), std::make_pair("max_capacity", 5.225), - std::make_pair("avg_power", expected_power_w)}); + std::make_pair("avg_power", expected_power_w), + std::make_pair("sample_age", 0)}); } } // namespace power_sampler
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 9870f25..b95c261 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -36700,6 +36700,15 @@ <int value="1221" label="Pairing Succeeded: Already Paired"/> </enum> +<enum name="FastPairGattConnectionSteps"> + <int value="0" label="Connection started"/> + <int value="1" label="Connection ready"/> + <int value="2" label="Found key-based pairing characteristic"/> + <int value="3" + label="Notifications enabled for key-bard pairing characteristic"/> + <int value="4" label="Connection established"/> +</enum> + <enum name="FastPairHandshakeFailureReason"> <int value="0" label="Failed to initialize GATT connection"/> <int value="1" label="Failed to create FastPairDataEncryptor"/> @@ -61536,6 +61545,8 @@ <int value="559695461" label="UseChimeAndroidSdk:enabled"/> <int value="559903013" label="AutofillEnableMerchantOptOutErrorDialog:enabled"/> + <int value="560953355" + label="ExtractRelatedSearchesFromPrefetchedZPSResponse:disabled"/> <int value="561374433" label="SCTAuditing:disabled"/> <int value="561951500" label="GlobalMediaControlsCastStartStop:enabled"/> <int value="562111126" label="SidePanelBorder:enabled"/> @@ -63608,6 +63619,8 @@ <int value="1803465156" label="enable-zero-suggest-most-visited"/> <int value="1803470125" label="SyncUSSSessions:enabled"/> <int value="1803914892" label="TemporaryUnexpireFlagsM76:enabled"/> + <int value="1805859042" + label="ExtractRelatedSearchesFromPrefetchedZPSResponse:enabled"/> <int value="1806220475" label="IgnoreSyncEncryptionKeysLongMissing:disabled"/> <int value="1806450300" label="WebUsbDeviceDetection:enabled"/> <int value="1807088829"
diff --git a/tools/metrics/histograms/metadata/accessibility/histograms.xml b/tools/metrics/histograms/metadata/accessibility/histograms.xml index f8ff3ac..5f8905c9 100644 --- a/tools/metrics/histograms/metadata/accessibility/histograms.xml +++ b/tools/metrics/histograms/metadata/accessibility/histograms.xml
@@ -1160,7 +1160,7 @@ </histogram> <histogram name="Accessibility.InactiveTime" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>aleventhal@chromium.org</owner> <owner>abigailbklein@chromium.org</owner> <owner>janewman@microsoft.com</owner> @@ -1561,7 +1561,7 @@ <histogram name="Accessibility.Performance.BrowserAccessibilityManager::OnAccessibilityEvents" - units="ms" expires_after="2023-03-26"> + units="ms" expires_after="2023-05-27"> <owner>aleventhal@chromium.org</owner> <owner>chrome-a11y-core@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/android/histograms.xml b/tools/metrics/histograms/metadata/android/histograms.xml index 4c45ffa..b8c30c5 100644 --- a/tools/metrics/histograms/metadata/android/histograms.xml +++ b/tools/metrics/histograms/metadata/android/histograms.xml
@@ -1467,7 +1467,7 @@ </histogram> <histogram name="Android.DragDrop.FromWebContent.DropInWebContent.Duration" - units="ms" expires_after="2023-03-19"> + units="ms" expires_after="2023-05-27"> <owner>wenyufu@chromium.org</owner> <owner>clank-large-form-factors@google.com</owner> <summary> @@ -1580,7 +1580,7 @@ </histogram> <histogram name="Android.DragDrop.Image.Size" units="KB" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>shuyng@google.com</owner> <owner>clank-large-form-factors@google.com</owner> <summary> @@ -1591,7 +1591,7 @@ </histogram> <histogram name="Android.DragDrop.Image.UriCreatedInterval" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>shuyng@google.com</owner> <owner>clank-large-form-factors@google.com</owner> <summary> @@ -1720,7 +1720,7 @@ </histogram> <histogram name="Android.FontLookup.Blink.DLFontsLatencySuccess2" - units="microseconds" expires_after="2023-03-19"> + units="microseconds" expires_after="2023-05-27"> <owner>drott@chromium.org</owner> <owner>layout-dev@chromium.org</owner> <summary> @@ -3854,7 +3854,7 @@ </histogram> <histogram name="Android.WebView.Callback.Counts" enum="WebViewCallbackType" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>ntfschr@chromium.org</owner> <owner>src/android_webview/OWNERS</owner> <summary>Records the invocation count of WebView callbacks.</summary> @@ -3892,7 +3892,7 @@ </histogram> <histogram name="Android.WebView.ComponentUpdater.GetFilesResult" - enum="WebViewComponentUpdaterGetFilesResult" expires_after="2023-03-19"> + enum="WebViewComponentUpdaterGetFilesResult" expires_after="2023-05-27"> <owner>hazems@chromium.org</owner> <owner>src/android_webview/OWNERS</owner> <summary> @@ -4277,7 +4277,7 @@ </histogram> <histogram name="Android.WebView.Gfx.HardwareDrawType" - enum="WebViewDrawAndSubmissionType" expires_after="2023-03-19"> + enum="WebViewDrawAndSubmissionType" expires_after="2023-05-27"> <owner>vasilyt@chromium.org</owner> <owner>boliu@chromium.org</owner> <summary> @@ -4289,7 +4289,7 @@ </histogram> <histogram name="Android.WebView.InputStreamTime" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>jam@chromium.org</owner> <owner>cduvall@chromium.org</owner> <summary> @@ -4327,7 +4327,7 @@ </histogram> <histogram name="Android.WebView.Metrics.PackagesAllowList.RecordStatus" - enum="AppPackageNameLoggingRuleStatus" expires_after="2023-03-19"> + enum="AppPackageNameLoggingRuleStatus" expires_after="2023-05-27"> <owner>hazems@chromium.org</owner> <owner>src/android_webview/OWNERS</owner> <summary> @@ -4341,7 +4341,7 @@ <histogram name="Android.WebView.Metrics.PackagesAllowList.ResultReceivingDelay" - units="ms" expires_after="2023-03-19"> + units="ms" expires_after="2023-05-27"> <owner>hazems@chromium.org</owner> <owner>src/android_webview/OWNERS</owner> <summary> @@ -4748,7 +4748,7 @@ </histogram> <histogram name="Android.WebView.SecureCookieAction" enum="SecureCookieAction" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>ntfschr@chromium.org</owner> <owner>src/android_webview/OWNERS</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/apps/histograms.xml b/tools/metrics/histograms/metadata/apps/histograms.xml index 3bbdd4d2..89650499 100644 --- a/tools/metrics/histograms/metadata/apps/histograms.xml +++ b/tools/metrics/histograms/metadata/apps/histograms.xml
@@ -1400,7 +1400,7 @@ </histogram> <histogram name="Apps.AppListFolderOpened" enum="AppListFolderOpened" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>mmourgos@chromium.org</owner> <owner>tbarzic@chromium.org</owner> <owner>newcomer@chromium.org</owner> @@ -1474,7 +1474,7 @@ </histogram> <histogram name="Apps.AppListPageSwitcherSource" - enum="AppListPageSwitcherSource" expires_after="2023-03-26"> + enum="AppListPageSwitcherSource" expires_after="2023-05-27"> <owner>tbarzic@chromium.org</owner> <owner>newcomer@chromium.org</owner> <owner>mmourgos@chromium.org</owner> @@ -1498,7 +1498,7 @@ </histogram> <histogram name="Apps.AppListPlayStoreQueryState" - enum="AppListPlayStoreQueryState" expires_after="2023-03-19"> + enum="AppListPlayStoreQueryState" expires_after="2023-05-27"> <owner>hejq@chromium.org</owner> <summary>The state of a Play Store app search request.</summary> </histogram> @@ -1891,7 +1891,7 @@ </histogram> <histogram name="Apps.CreateShortcutIcon.Linux.Result" - enum="WebAppCreateShortcutIconLinuxResult" expires_after="2023-03-19"> + enum="WebAppCreateShortcutIconLinuxResult" expires_after="2023-05-27"> <owner>estade@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -1909,7 +1909,7 @@ </histogram> <histogram name="Apps.CreateShortcuts.Mac.Result" - enum="WebAppCreateShortcutMacResult" expires_after="2023-03-19"> + enum="WebAppCreateShortcutMacResult" expires_after="2023-05-27"> <owner>phillis@chromium.org</owner> <owner>cmumford@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/ash/histograms.xml b/tools/metrics/histograms/metadata/ash/histograms.xml index a95e776..ad2da078 100644 --- a/tools/metrics/histograms/metadata/ash/histograms.xml +++ b/tools/metrics/histograms/metadata/ash/histograms.xml
@@ -2218,7 +2218,7 @@ </histogram> <histogram name="Ash.DeviceActiveClient.StateCount" - enum="DeviceActiveClientState" expires_after="2023-03-19"> + enum="DeviceActiveClientState" expires_after="2023-05-27"> <owner>hirthanan@google.com</owner> <owner>chromeos-data-team@google.com</owner> <summary> @@ -2229,7 +2229,7 @@ </histogram> <histogram name="Ash.DeviceActiveController.PsmDeviceActiveSecretIsSet" - enum="BooleanSuccess" expires_after="2023-03-19"> + enum="BooleanSuccess" expires_after="2023-05-27"> <owner>hirthanan@google.com</owner> <owner>chromeos-data-team@google.com</owner> <summary>Whether the PSM derived active secret is set (non empty).</summary> @@ -2918,7 +2918,7 @@ </histogram> <histogram name="Ash.MessageCenter.Scroll.PresentationTime" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>leandre@chromium.org</owner> <owner>cros-status-area-eng@google.com</owner> <summary> @@ -3055,7 +3055,7 @@ </histogram> <histogram name="Ash.Notification.ClearAllVisible.AnimationSmoothness" - units="%" expires_after="2023-03-19"> + units="%" expires_after="2023-05-27"> <owner>leandre@chromium.org</owner> <owner>cros-status-area-eng@google.com</owner> <summary> @@ -3076,7 +3076,7 @@ </histogram> <histogram name="Ash.Notification.ExpandOrCollapse.AnimationSmoothness" - units="%" expires_after="2023-03-26"> + units="%" expires_after="2023-05-27"> <owner>leandre@chromium.org</owner> <owner>cros-status-area-eng@google.com</owner> <summary> @@ -3110,7 +3110,7 @@ </histogram> <histogram name="Ash.Notification.MoveDown.AnimationSmoothness" units="%" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>leandre@chromium.org</owner> <owner>cros-status-area-eng@google.com</owner> <summary> @@ -4643,7 +4643,7 @@ </histogram> <histogram name="Ash.SplitViewResize.PresentationTime{SplitViewResizeModes}" - units="ms" expires_after="2022-10-26"> + units="ms" expires_after="2023-11-18"> <owner>amusbach@chromium.org</owner> <owner>xdai@chromium.org</owner> <owner>omrilio@chromium.org</owner> @@ -4668,7 +4668,7 @@ </histogram> <histogram name="Ash.StatusArea.TrayBackgroundView.BounceIn" units="%" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>leandre@chromium.org</owner> <owner>cros-status-area-eng@google.com</owner> <summary> @@ -4680,7 +4680,7 @@ </histogram> <histogram name="Ash.StatusArea.TrayBackgroundView.FadeIn" units="%" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>leandre@chromium.org</owner> <owner>cros-status-area-eng@google.com</owner> <summary> @@ -4692,7 +4692,7 @@ </histogram> <histogram name="Ash.StatusArea.TrayBackgroundView.Hide" units="%" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>leandre@chromium.org</owner> <owner>cros-status-area-eng@google.com</owner> <summary> @@ -4721,7 +4721,7 @@ </histogram> <histogram name="Ash.StatusArea.TrayItemView.Hide" units="%" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>leandre@chromium.org</owner> <owner>cros-status-area-eng@google.com</owner> <summary> @@ -4732,7 +4732,7 @@ </histogram> <histogram name="Ash.StatusArea.TrayItemView.Show" units="%" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>leandre@chromium.org</owner> <owner>cros-status-area-eng@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/autofill/histograms.xml b/tools/metrics/histograms/metadata/autofill/histograms.xml index babf4b7..b86da56d 100644 --- a/tools/metrics/histograms/metadata/autofill/histograms.xml +++ b/tools/metrics/histograms/metadata/autofill/histograms.xml
@@ -905,6 +905,10 @@ <histogram name="Autofill.CardUnmaskAuthenticationSelectionDialog.Shown" enum="BooleanShown" expires_after="2023-04-16"> + <obsolete> + Deprecated in M109. Subsumed by + Autofill.CardUnmaskAuthenticationSelectionDialog.Shown2. + </obsolete> <owner>siyua@chromium.org</owner> <owner>jsaul@google.com</owner> <owner>siashah@chromium.org</owner> @@ -915,6 +919,20 @@ </summary> </histogram> +<histogram name="Autofill.CardUnmaskAuthenticationSelectionDialog.Shown2" + units="challenge_options" expires_after="2023-04-16"> + <owner>siyua@chromium.org</owner> + <owner>jsaul@google.com</owner> + <owner>siashah@chromium.org</owner> + <owner>vinnypersky@google.com</owner> + <summary> + On every show of the card unmask challenge option selection dialog, this + histogram records a count (with a maximum of 10) for the number of challenge + options that were shown. This dialog is shown when a user needs to select a + challenge option to authenticate a card for payments autofill. + </summary> +</histogram> + <histogram name="Autofill.CardUploadDecisionMetric" enum="AutofillCardUploadDecisionMetric" expires_after="2023-04-23"> <owner>jsaul@google.com</owner> @@ -2952,7 +2970,7 @@ </histogram> <histogram name="Autofill.ProfileImport.InaccessibleFieldsRemoved.ByFieldType" - enum="AutofillSettingsVisibleTypes" expires_after="2023-03-19"> + enum="AutofillSettingsVisibleTypes" expires_after="2023-05-27"> <owner>fleimgruber@google.com</owner> <owner>chrome-autofill-team@google.com</owner> <summary> @@ -2962,7 +2980,7 @@ </histogram> <histogram name="Autofill.ProfileImport.InaccessibleFieldsRemoved.Total" - enum="Boolean" expires_after="2023-03-19"> + enum="Boolean" expires_after="2023-05-27"> <owner>fleimgruber@google.com</owner> <owner>chrome-autofill-team@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/background/histograms.xml b/tools/metrics/histograms/metadata/background/histograms.xml index 4279fa64..123faa62 100644 --- a/tools/metrics/histograms/metadata/background/histograms.xml +++ b/tools/metrics/histograms/metadata/background/histograms.xml
@@ -280,7 +280,7 @@ </histogram> <histogram name="BackgroundSync.Event.OneShotResultPattern" - enum="BackgroundSyncResultPattern" expires_after="2023-03-19"> + enum="BackgroundSyncResultPattern" expires_after="2023-05-27"> <owner>nator@chromium.org</owner> <owner>rayankans@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/blink/histograms.xml b/tools/metrics/histograms/metadata/blink/histograms.xml index b8413173..6b7167bf 100644 --- a/tools/metrics/histograms/metadata/blink/histograms.xml +++ b/tools/metrics/histograms/metadata/blink/histograms.xml
@@ -125,7 +125,7 @@ </histogram> <histogram name="Blink.Animation.CompositedAnimationFailureReason" - enum="CompositorAnimationsFailureReason" expires_after="2023-03-19"> + enum="CompositorAnimationsFailureReason" expires_after="2023-05-27"> <owner>smcgruer@chromium.org</owner> <owner>animations-dev@chromium.org</owner> <summary> @@ -601,7 +601,7 @@ </histogram> <histogram base="true" name="Blink.CompositingCommit.UpdateTime" - units="microseconds" expires_after="2023-03-26"> + units="microseconds" expires_after="2023-05-27"> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePreFCPSuffixes" --> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePostFCPSuffixes" --> @@ -1875,7 +1875,7 @@ </histogram> <histogram base="true" name="Blink.Layout.UpdateTime" units="microseconds" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePreFCPSuffixes" --> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePostFCPSuffixes" --> @@ -2016,7 +2016,7 @@ </histogram> <histogram base="true" name="Blink.MainFrame.UpdateTime" units="microseconds" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePreFCPSuffixes" --> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePostFCPSuffixes" --> @@ -2252,7 +2252,7 @@ </histogram> <histogram base="true" name="Blink.Paint.UpdateTime" units="microseconds" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePreFCPSuffixes" --> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePostFCPSuffixes" --> @@ -2276,7 +2276,7 @@ </histogram> <histogram base="true" name="Blink.ParseStyleSheet.UpdateTime" - units="microseconds" expires_after="2023-03-26"> + units="microseconds" expires_after="2023-05-27"> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePreFCPSuffixes" --> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePostFCPSuffixes" --> @@ -2331,7 +2331,7 @@ </histogram> <histogram base="true" name="Blink.PrePaint.UpdateTime" units="microseconds" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePreFCPSuffixes" --> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePostFCPSuffixes" --> @@ -3332,9 +3332,10 @@ </histogram> <histogram name="Blink.VisibleBeforeLoaded.LazyLoadImages.AboveTheFold" - enum="NQEEffectiveConnectionType" expires_after="2022-05-01"> + enum="NQEEffectiveConnectionType" expires_after="2023-09-01"> <owner>sclittle@chromium.org</owner> <owner>rajendrant@chromium.org</owner> + <owner>pdr@chromium.org</owner> <summary> Records the effective connection type whenever a lazily loaded image that was initially above the fold becomes visible before it finishes loading. @@ -3342,9 +3343,10 @@ </histogram> <histogram name="Blink.VisibleBeforeLoaded.LazyLoadImages.BelowTheFold" - enum="NQEEffectiveConnectionType" expires_after="2023-04-16"> + enum="NQEEffectiveConnectionType" expires_after="2023-09-01"> <owner>sclittle@chromium.org</owner> <owner>rajendrant@chromium.org</owner> + <owner>pdr@chromium.org</owner> <summary> Records the effective connection type whenever a lazily loaded image that was initially below the fold becomes visible before it finishes loading.
diff --git a/tools/metrics/histograms/metadata/browser/histograms.xml b/tools/metrics/histograms/metadata/browser/histograms.xml index f5e4b21..7694836 100644 --- a/tools/metrics/histograms/metadata/browser/histograms.xml +++ b/tools/metrics/histograms/metadata/browser/histograms.xml
@@ -285,7 +285,7 @@ </histogram> <histogram name="Browser.PaintPreview.Player.CompositorProcessStartedCorrectly" - enum="BooleanSuccess" expires_after="2023-03-19"> + enum="BooleanSuccess" expires_after="2023-05-27"> <owner>ckitagawa@chromium.org</owner> <owner>fredmello@chromium.org</owner> <owner>chrome-fdt@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/chrome/histograms.xml b/tools/metrics/histograms/metadata/chrome/histograms.xml index 2a39f5b..f51b3c4 100644 --- a/tools/metrics/histograms/metadata/chrome/histograms.xml +++ b/tools/metrics/histograms/metadata/chrome/histograms.xml
@@ -23,7 +23,7 @@ <histograms> <histogram name="Chrome.KAnonymityService.JoinSet.Action" - enum="KAnonymityServiceJoinSetAction" expires_after="2023-03-26"> + enum="KAnonymityServiceJoinSetAction" expires_after="2023-05-27"> <owner>behamilton@google.com</owner> <owner>pauljensen@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/chromeos/histograms.xml b/tools/metrics/histograms/metadata/chromeos/histograms.xml index e72f045..ada2f0a3 100644 --- a/tools/metrics/histograms/metadata/chromeos/histograms.xml +++ b/tools/metrics/histograms/metadata/chromeos/histograms.xml
@@ -918,6 +918,18 @@ </token> </histogram> +<histogram name="ChromeOS.FastPair.GattConnection" + enum="FastPairGattConnectionSteps" expires_after="2023-06-01"> + <owner>jackshira@chromium.org</owner> + <owner>chromeos-cross-device-eng@google.com</owner> + <summary> + Records each sucessful step in the GATT Connection flow. These steps are: on + connection start, on connection ready, on key-based characteristic found, on + notifications enabled for the key-based pairing characteristic, and on + connection established. + </summary> +</histogram> + <histogram name="ChromeOS.FastPair.SubsequentPairing" enum="FastPairSubsequentSuccessFunnelEvent" expires_after="2023-06-01"> <owner>jackshira@chromium.org</owner> @@ -1265,7 +1277,7 @@ </histogram> <histogram name="ChromeOS.Intents.LinkCapturingEvent2" - enum="LinkCapturingEvent" expires_after="2023-05-14"> + enum="LinkCapturingEvent" expires_after="2023-05-27"> <owner>vpao@google.com</owner> <owner>chromeos-apps-foundation-team@google.com</owner> <summary> @@ -1665,7 +1677,7 @@ </histogram> <histogram name="ChromeOS.PlatformVerification.Result2" - enum="ChromeOSPlatformVerificationResult2" expires_after="2023-03-19"> + enum="ChromeOSPlatformVerificationResult2" expires_after="2023-05-27"> <owner>erikchen@chromium.org</owner> <owner>cros-hwsec+uma@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/commerce/histograms.xml b/tools/metrics/histograms/metadata/commerce/histograms.xml index 66d6576..cc7dc0a2 100644 --- a/tools/metrics/histograms/metadata/commerce/histograms.xml +++ b/tools/metrics/histograms/metadata/commerce/histograms.xml
@@ -54,7 +54,7 @@ </histogram> <histogram name="Commerce.Carts.ExtractionElapsedTime" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>wychen@chromium.org</owner> <owner>yuezhanggg@chromium.org</owner> <owner>chrome-shopping@google.com</owner> @@ -67,7 +67,7 @@ </histogram> <histogram name="Commerce.Carts.ExtractionExecutionTime" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>wychen@chromium.org</owner> <owner>yuezhanggg@chromium.org</owner> <owner>chrome-shopping@google.com</owner> @@ -80,7 +80,7 @@ </histogram> <histogram name="Commerce.Carts.ExtractionLongestTaskTime" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>wychen@chromium.org</owner> <owner>yuezhanggg@chromium.org</owner> <owner>chrome-shopping@google.com</owner> @@ -103,7 +103,7 @@ </histogram> <histogram name="Commerce.Carts.ExtractionTotalTasksTime" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>wychen@chromium.org</owner> <owner>yuezhanggg@chromium.org</owner> <owner>chrome-shopping@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/compositing/histograms.xml b/tools/metrics/histograms/metadata/compositing/histograms.xml index 1f8e616..6630741 100644 --- a/tools/metrics/histograms/metadata/compositing/histograms.xml +++ b/tools/metrics/histograms/metadata/compositing/histograms.xml
@@ -40,7 +40,7 @@ </histogram> <histogram name="Compositing.Browser.LayersUpdateTime" units="microseconds" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>schenney@chromium.org</owner> <owner>animations-dev@chromium.org</owner> <summary> @@ -402,7 +402,7 @@ <histogram name="Compositing.Display.OverlayProcessorUsingStrategy.CheckOverlaySupportCallCount" - units="units" expires_after="2023-03-26"> + units="units" expires_after="2023-05-27"> <owner>khaslett@chromium.org</owner> <owner>kylechar@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/cookie/histograms.xml b/tools/metrics/histograms/metadata/cookie/histograms.xml index 4b9759b..c1f2e6b 100644 --- a/tools/metrics/histograms/metadata/cookie/histograms.xml +++ b/tools/metrics/histograms/metadata/cookie/histograms.xml
@@ -93,7 +93,7 @@ </histogram> <histogram name="Cookie.CookiePrefix" enum="CookiePrefix" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>estark@chromium.org</owner> <summary> Number of times a cookie was set with a name prefixed by @@ -165,7 +165,7 @@ </histogram> <histogram name="Cookie.CookieSourceScheme" enum="CookieSourceScheme" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>estark@chromium.org</owner> <summary> For each cookie added to the store, record whether its source URL has a
diff --git a/tools/metrics/histograms/metadata/cras/histograms.xml b/tools/metrics/histograms/metadata/cras/histograms.xml index 49cae0ec..2c3e55d 100644 --- a/tools/metrics/histograms/metadata/cras/histograms.xml +++ b/tools/metrics/histograms/metadata/cras/histograms.xml
@@ -34,7 +34,7 @@ </histogram> <histogram name="Cras.A2dp20msFailureOverStream" units="units" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>hychao@chromium.org</owner> <owner>chromeos-audio@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/cros/histograms.xml b/tools/metrics/histograms/metadata/cros/histograms.xml index 2bb5aaba..5e900c0 100644 --- a/tools/metrics/histograms/metadata/cros/histograms.xml +++ b/tools/metrics/histograms/metadata/cros/histograms.xml
@@ -184,7 +184,7 @@ </histogram> <histogram name="CrosDisksClient.FormatTime" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>austinct@chromium.org</owner> <owner>src/ui/file_manager/OWNERS</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/cros_ml/histograms.xml b/tools/metrics/histograms/metadata/cros_ml/histograms.xml index d1b5b6cd..652d8ff 100644 --- a/tools/metrics/histograms/metadata/cros_ml/histograms.xml +++ b/tools/metrics/histograms/metadata/cros_ml/histograms.xml
@@ -168,7 +168,7 @@ </histogram> <histogram name="MachineLearningService.PeakTotalMemoryKb" units="KB" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>alanlxl@chromium.org</owner> <owner>amoylan@chromium.org</owner> <owner>honglinyu@chromium.org</owner> @@ -227,7 +227,7 @@ </histogram> <histogram name="MachineLearningService.TotalMemoryKb" units="KB" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>alanlxl@chromium.org</owner> <owner>amoylan@chromium.org</owner> <owner>honglinyu@chromium.org</owner> @@ -252,7 +252,7 @@ <histogram name="MachineLearningService.WebPlatformHandwritingModel.LoadModelResult.Event" enum="MachineLearningServiceLoadHandwritingModelResultEvent" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>amoylan@chromium.org</owner> <owner>alanlxl@chromium.org</owner> <owner>charleszhao@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/crostini/histograms.xml b/tools/metrics/histograms/metadata/crostini/histograms.xml index 86283e22..cd3a4ea 100644 --- a/tools/metrics/histograms/metadata/crostini/histograms.xml +++ b/tools/metrics/histograms/metadata/crostini/histograms.xml
@@ -103,7 +103,7 @@ </histogram> <histogram name="Crostini.Backup" enum="CrostiniExportContainerResult" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>davidmunro@google.com</owner> <owner>clumptini@google.com</owner> <summary>Result of crostini backup.</summary> @@ -180,7 +180,7 @@ </histogram> <histogram name="Crostini.DiskResize.Result" enum="CrostiniDiskImageStatus" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>davidmunro@google.com</owner> <owner>clumptini@google.com</owner> <summary> @@ -247,7 +247,7 @@ </histogram> <histogram name="Crostini.FilesystemCorruption" enum="CorruptionStates" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>sidereal@google.com</owner> <owner>davidmunro@google.com</owner> <owner>clumptini@google.com</owner> @@ -402,7 +402,7 @@ </histogram> <histogram name="Crostini.SetupResult" enum="CrostiniSetupResult" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>davidmunro@google.com</owner> <owner>clumptini@google.com</owner> <summary> @@ -472,7 +472,7 @@ </histogram> <histogram name="Crostini.Stability" enum="GuestOsFailureClasses" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>davidmunro@google.com</owner> <owner>clumptini@google.com</owner> <summary> @@ -552,7 +552,7 @@ </histogram> <histogram name="Crostini.UninstallResult" enum="CrostiniUninstallResult" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>davidmunro@google.com</owner> <owner>clumptini@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/custom_tabs/histograms.xml b/tools/metrics/histograms/metadata/custom_tabs/histograms.xml index d26727f..a7ec56c4 100644 --- a/tools/metrics/histograms/metadata/custom_tabs/histograms.xml +++ b/tools/metrics/histograms/metadata/custom_tabs/histograms.xml
@@ -564,7 +564,7 @@ </histogram> <histogram name="CustomTabs.WarmupStateOnLaunch" enum="WarmupStateOnLaunch" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>lizeb@chromium.org</owner> <summary> Recorded only on Android. Reports whether warmup() has been called when a
diff --git a/tools/metrics/histograms/metadata/disk/histograms.xml b/tools/metrics/histograms/metadata/disk/histograms.xml index 910087d3..b17708b5 100644 --- a/tools/metrics/histograms/metadata/disk/histograms.xml +++ b/tools/metrics/histograms/metadata/disk/histograms.xml
@@ -125,7 +125,7 @@ </histogram> <histogram name="DiskCache.0.Error" enum="DiskCacheError" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>wfh@chromium.org</owner> <owner>src/net/disk_cache/OWNERS</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/enterprise/histograms.xml b/tools/metrics/histograms/metadata/enterprise/histograms.xml index 462e8fd8..f95424e 100644 --- a/tools/metrics/histograms/metadata/enterprise/histograms.xml +++ b/tools/metrics/histograms/metadata/enterprise/histograms.xml
@@ -1147,6 +1147,16 @@ </summary> </histogram> +<histogram name="Enterprise.Dlp.Errors.FilesPolicySetup" enum="Boolean" + expires_after="2023-06-01"> + <owner>accorsi@google.com</owner> + <owner>chromeos-dlp@google.com</owner> + <summary> + Recorded when an error occurs during the Data Leak Prevention files policy + setup. + </summary> +</histogram> + <histogram name="Enterprise.Dlp.Errors.ReportQueueNotReady" enum="Boolean" expires_after="2023-06-01"> <owner>accorsi@google.com</owner> @@ -2653,7 +2663,7 @@ </histogram> <histogram name="Enterprise.VpdUpdateStatus" units="units" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>igorcov@chromium.org</owner> <owner>tnagel@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/event/histograms.xml b/tools/metrics/histograms/metadata/event/histograms.xml index 2ea3ac7..1deda44 100644 --- a/tools/metrics/histograms/metadata/event/histograms.xml +++ b/tools/metrics/histograms/metadata/event/histograms.xml
@@ -821,7 +821,7 @@ </histogram> <histogram name="Event.Latency.ScrollBegin.Wheel.TimeToScrollUpdateSwapBegin4" - units="microseconds" expires_after="2023-03-19"> + units="microseconds" expires_after="2023-05-27"> <owner>flackr@chromium.org</owner> <summary> NOTE: This metric is deprecated in favor of @@ -1001,7 +1001,7 @@ </histogram> <histogram name="Event.Latency.ScrollUpdate.JankyDurationPercentage" units="%" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>ddrone@google.com</owner> <owner>chrometto-team@google.com</owner> <summary> @@ -1574,7 +1574,7 @@ </histogram> <histogram name="Event.Latency.ScrollUpdate.Wheel.TimeToScrollUpdateSwapBegin4" - units="microseconds" expires_after="2023-03-19"> + units="microseconds" expires_after="2023-05-27"> <owner>flackr@chromium.org</owner> <summary> NOTE: This metric is deprecated in favor of
diff --git a/tools/metrics/histograms/metadata/extensions/histograms.xml b/tools/metrics/histograms/metadata/extensions/histograms.xml index 10184ef..862491164 100644 --- a/tools/metrics/histograms/metadata/extensions/histograms.xml +++ b/tools/metrics/histograms/metadata/extensions/histograms.xml
@@ -124,7 +124,7 @@ </histogram> <histogram name="Extensions.ActiveScriptController.DeniedExtensions" - units="Extension Count" expires_after="2023-03-26"> + units="Extension Count" expires_after="2023-05-27"> <owner>rdevlin.cronin@chromium.org</owner> <owner>extensions-core@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/families/histograms.xml b/tools/metrics/histograms/metadata/families/histograms.xml index 6a965131..b41b770 100644 --- a/tools/metrics/histograms/metadata/families/histograms.xml +++ b/tools/metrics/histograms/metadata/families/histograms.xml
@@ -628,7 +628,7 @@ </histogram> <histogram name="SupervisedUsers.ExtensionInstallDialog" - enum="SupervisedUserExtensionInstallDialog" expires_after="2023-03-26"> + enum="SupervisedUserExtensionInstallDialog" expires_after="2023-05-27"> <owner>tobyhuang@chromium.org</owner> <owner>agawronska@chromium.org</owner> <owner>danan@chromium.org</owner> @@ -660,7 +660,7 @@ </histogram> <histogram name="SupervisedUsers.ExtensionsMayRequestPermissions" - enum="BooleanEnabled" expires_after="2023-03-26"> + enum="BooleanEnabled" expires_after="2023-05-27"> <owner>tobyhuang@chromium.org</owner> <owner>cros-families-eng@google.com</owner> <summary> @@ -757,7 +757,7 @@ </histogram> <histogram name="Supervision.ParentAccessCode.Action" - enum="ParentAccessCodeAction" expires_after="2023-03-26"> + enum="ParentAccessCodeAction" expires_after="2023-05-27"> <owner>agawronska@chromium.org</owner> <owner>cros-families-eng@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/feature_engagement/histograms.xml b/tools/metrics/histograms/metadata/feature_engagement/histograms.xml index ff12f3ff..cbd69d68 100644 --- a/tools/metrics/histograms/metadata/feature_engagement/histograms.xml +++ b/tools/metrics/histograms/metadata/feature_engagement/histograms.xml
@@ -266,7 +266,7 @@ </variants> <histogram name="InProductHelp.Config.ParsingEvent" enum="ConfigParsingEvent" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>nyquist@chromium.org</owner> <summary> Records if in-product help configuration is parsed correctly, and the
diff --git a/tools/metrics/histograms/metadata/gpu/histograms.xml b/tools/metrics/histograms/metadata/gpu/histograms.xml index a951f14c..ee2d155 100644 --- a/tools/metrics/histograms/metadata/gpu/histograms.xml +++ b/tools/metrics/histograms/metadata/gpu/histograms.xml
@@ -1334,16 +1334,6 @@ </summary> </histogram> -<histogram name="GPU.Sandbox.InitializedSuccessfully" enum="BooleanSuccess" - expires_after="2020-08-30"> - <owner>vmiura@chromium.org</owner> - <owner>wfh@chromium.org</owner> - <summary> - Whether or not the GPU sandbox properly initialized. Failures are typically - platform- and driver-specific (e.g. driver creating threads on Linux). - </summary> -</histogram> - <histogram name="GPU.Scheduler.TaskDependencyTime" units="microseconds" expires_after="2022-08-07"> <owner>berlu@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/histogram_suffixes_list.xml b/tools/metrics/histograms/metadata/histogram_suffixes_list.xml index 3eea233..f3b85e02 100644 --- a/tools/metrics/histograms/metadata/histogram_suffixes_list.xml +++ b/tools/metrics/histograms/metadata/histogram_suffixes_list.xml
@@ -2102,20 +2102,6 @@ <affected-histogram name="FirstUserAction.BackgroundTimeNewTask"/> </histogram_suffixes> -<histogram_suffixes name="FreedesktopNotificationCapabilitiesId" separator="."> - <suffix name="ActionIcons" label="action-icons capability"/> - <suffix name="Actions" label="actions capability"/> - <suffix name="Body" label="body capability"/> - <suffix name="BodyHyperlinks" label="body-hyperlinks capability"/> - <suffix name="BodyImages" label="body-images capability"/> - <suffix name="BodyMarkup" label="body-markup capability"/> - <suffix name="IconMulti" label="icon-multi capability"/> - <suffix name="IconStatic" label="icon-static capability"/> - <suffix name="Persistence" label="persistence capability"/> - <suffix name="Sound" label="sound capability"/> - <affected-histogram name="Notifications.Freedesktop.Capabilities"/> -</histogram_suffixes> - <histogram_suffixes name="FromGWS" separator="_"> <suffix name="FromGWS" label="Only page loads that are a result of a navigation from a web
diff --git a/tools/metrics/histograms/metadata/input/histograms.xml b/tools/metrics/histograms/metadata/input/histograms.xml index 10ec50fa..9beb2fc 100644 --- a/tools/metrics/histograms/metadata/input/histograms.xml +++ b/tools/metrics/histograms/metadata/input/histograms.xml
@@ -1364,7 +1364,7 @@ </histogram> <histogram name="InputMethod.VirtualKeyboard.InitLatency.KeyboardShownLongTail" - units="ms" expires_after="2023-03-19"> + units="ms" expires_after="2023-05-27"> <owner>jopalmer@chromium.org</owner> <owner>essential-inputs-team@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/ios/histograms.xml b/tools/metrics/histograms/metadata/ios/histograms.xml index e7c98d5..f31e1987 100644 --- a/tools/metrics/histograms/metadata/ios/histograms.xml +++ b/tools/metrics/histograms/metadata/ios/histograms.xml
@@ -222,7 +222,7 @@ </histogram> <histogram name="IOS.CredentialExtension.ConsentVerifiedCount" units="count" - expires_after="2022-12-11"> + expires_after="2023-06-11"> <owner>ginnyhuang@chromium.org</owner> <owner>bling-team@google.com</owner> <summary> @@ -233,7 +233,7 @@ </histogram> <histogram name="IOS.CredentialExtension.CopyPasswordCount" units="count" - expires_after="2022-12-11"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -244,7 +244,7 @@ </histogram> <histogram name="IOS.CredentialExtension.CopyURLCount" units="count" - expires_after="2022-12-11"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -255,7 +255,7 @@ </histogram> <histogram name="IOS.CredentialExtension.CopyUsernameCount" units="count" - expires_after="2022-12-11"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -266,7 +266,7 @@ </histogram> <histogram name="IOS.CredentialExtension.DisplayCount" units="count" - expires_after="2023-04-16"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -277,7 +277,7 @@ </histogram> <histogram name="IOS.CredentialExtension.FetchPasswordFailure" units="count" - expires_after="2022-12-11"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -288,7 +288,7 @@ </histogram> <histogram name="IOS.CredentialExtension.FetchPasswordNilArgument" - units="count" expires_after="2022-12-11"> + units="count" expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -309,7 +309,7 @@ </histogram> <histogram name="IOS.CredentialExtension.KeychainSavePasswordFailureCount" - units="count" expires_after="2022-12-11"> + units="count" expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>rkgibson@google.com</owner> <summary> @@ -321,7 +321,7 @@ <histogram name="IOS.CredentialExtension.NewCredentialUsername" enum="IOSCredentialProviderNewCredentialUsername" - expires_after="2022-12-11"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>rkgibson@google.com</owner> <summary> @@ -332,7 +332,7 @@ </histogram> <histogram name="IOS.CredentialExtension.PasswordCreated" - enum="IOSCredentialProviderPasswordCreated" expires_after="2022-12-11"> + enum="IOSCredentialProviderPasswordCreated" expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>rkgibson@google.com</owner> <summary> @@ -342,7 +342,7 @@ </histogram> <histogram name="IOS.CredentialExtension.PasswordUseCount" units="count" - expires_after="2023-04-16"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -353,7 +353,7 @@ </histogram> <histogram name="IOS.CredentialExtension.QuickPasswordUseCount" units="count" - expires_after="2023-04-16"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -364,7 +364,7 @@ </histogram> <histogram name="IOS.CredentialExtension.ReauthCount" units="count" - expires_after="2023-04-16"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -375,7 +375,7 @@ </histogram> <histogram name="IOS.CredentialExtension.SaveCredentialFailureCount" - units="count" expires_after="2022-12-11"> + units="count" expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>rkgibson@google.com</owner> <summary> @@ -386,7 +386,7 @@ </histogram> <histogram name="IOS.CredentialExtension.SearchCount" units="count" - expires_after="2022-12-11"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -399,7 +399,7 @@ <histogram name="IOS.CredentialExtension.Service.Error.ReplaceCredentialIdentitiesWithIdentities" enum="iOSCredentialIdentityStoreErrorForReporting" - expires_after="2022-12-11"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary> @@ -409,7 +409,7 @@ </histogram> <histogram name="IOS.CredentialExtension.ShowPasswordCount" units="count" - expires_after="2023-04-23"> + expires_after="2023-06-11"> <owner>rkgibson@chromium.org</owner> <owner>djean@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/language/histograms.xml b/tools/metrics/histograms/metadata/language/histograms.xml index 38e22b7..a046dbe 100644 --- a/tools/metrics/histograms/metadata/language/histograms.xml +++ b/tools/metrics/histograms/metadata/language/histograms.xml
@@ -209,7 +209,7 @@ </histogram> <histogram name="LanguageSettings.PageImpression" - enum="LanguageSettingsPageType" expires_after="2023-03-19"> + enum="LanguageSettingsPageType" expires_after="2023-05-27"> <owner>googleo@chromium.org</owner> <owner>chrome-language@google.com</owner> <summary> @@ -378,7 +378,7 @@ </histogram> <histogram name="LanguageUsage.UI.Android.OverrideLanguage" - enum="LocaleCodeISO639" expires_after="2023-03-19"> + enum="LocaleCodeISO639" expires_after="2023-05-27"> <owner>perrier@chromium.org</owner> <owner>chrome-language@google.com</owner> <summary> @@ -392,7 +392,7 @@ <histogram name="LanguageUsage.UI.Android.OverrideLanguage.IsSystemLanguage" enum="LanguageUsage.UI.Android.OverrideLanguage.IsSystemLanguage" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>perrier@chromium.org</owner> <owner>chrome-language@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/login/histograms.xml b/tools/metrics/histograms/metadata/login/histograms.xml index 3a96317..1502356 100644 --- a/tools/metrics/histograms/metadata/login/histograms.xml +++ b/tools/metrics/histograms/metadata/login/histograms.xml
@@ -311,7 +311,7 @@ </histogram> <histogram name="Login.SessionExitType" enum="LoginSessionExitType" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>iby@chromium.org</owner> <summary> Tracks whether a ChromeOS user was logged out because Chrome repeatedly
diff --git a/tools/metrics/histograms/metadata/media/histograms.xml b/tools/metrics/histograms/metadata/media/histograms.xml index 9cdfec9..825f6a9 100644 --- a/tools/metrics/histograms/metadata/media/histograms.xml +++ b/tools/metrics/histograms/metadata/media/histograms.xml
@@ -579,7 +579,7 @@ </histogram> <histogram name="Media.Audio.InputStartupSuccessMac" enum="BooleanSuccess" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>henrika@chromium.org</owner> <owner>webrtc-audio@google.com</owner> <summary> @@ -853,7 +853,7 @@ </histogram> <histogram name="Media.Audio.Render.FramesRequested" units="frames" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>guidou@chromium.org</owner> <owner>olka@chromium.org</owner> <summary> @@ -868,7 +868,7 @@ </histogram> <histogram name="Media.Audio.Render.GetSourceDataTime.WebRTC" - units="microseconds" expires_after="2023-03-19"> + units="microseconds" expires_after="2023-05-27"> <owner>guidou@chromium.org</owner> <owner>olka@chromium.org</owner> <summary> @@ -1004,7 +1004,7 @@ <histogram name="Media.Audio.Render.SinkCache.GetOutputDeviceInfoCacheUtilization" - enum="GetOutputDeviceInfoCacheHit" expires_after="2023-03-19"> + enum="GetOutputDeviceInfoCacheHit" expires_after="2023-05-27"> <owner>guidou@chromium.org</owner> <owner>olka@chromium.org</owner> <summary> @@ -1491,7 +1491,7 @@ </histogram> <histogram name="Media.AudioOutputStreamProxy.StreamFormat" - enum="AudioOutputProxyStreamFormat" expires_after="2023-03-26"> + enum="AudioOutputProxyStreamFormat" expires_after="2023-05-27"> <owner>olka@chromium.org</owner> <owner>tguilbert@chromium.org</owner> <summary> @@ -1548,7 +1548,7 @@ </histogram> <histogram name="Media.AudioRendererMissedDeadline" units="%" - expires_after="2023-05-14"> + expires_after="2023-05-27"> <owner>dalecurtis@chromium.org</owner> <owner>olka@chromium.org</owner> <summary> @@ -2180,7 +2180,7 @@ <summary>The result from an attempt to load a library CDM.</summary> </histogram> -<histogram name="Media.EME.CdmLoadTime" units="ms" expires_after="2023-03-19"> +<histogram name="Media.EME.CdmLoadTime" units="ms" expires_after="2023-05-27"> <owner>xhwang@chromium.org</owner> <owner>media-dev@chromium.org</owner> <summary>The time spent to load a library CDM.</summary> @@ -2564,7 +2564,7 @@ </histogram> <histogram name="Media.EME.Widevine.VideoCapability.HasEmptyRobustness" - enum="BooleanEmpty" expires_after="2023-03-19"> + enum="BooleanEmpty" expires_after="2023-05-27"> <owner>xhwang@chromium.org</owner> <owner>media-dev@chromium.org</owner> <summary> @@ -3239,7 +3239,7 @@ </histogram> <histogram name="Media.MeanTimeBetweenRebuffers" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>dalecurtis@chromium.org</owner> <summary> The total watch time (see Media.WatchTime) of a given playback divided by @@ -4239,7 +4239,7 @@ </histogram> <histogram name="Media.RtcLowLatencyVideoRenderer.MaxSizeDropQueueCount" - units="count" expires_after="2023-03-26"> + units="count" expires_after="2023-05-27"> <owner>kron@chromium.org</owner> <owner>webrtc-video@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/mobile/histograms.xml b/tools/metrics/histograms/metadata/mobile/histograms.xml index 8f4bf83..7fb886f 100644 --- a/tools/metrics/histograms/metadata/mobile/histograms.xml +++ b/tools/metrics/histograms/metadata/mobile/histograms.xml
@@ -936,7 +936,7 @@ </histogram> <histogram name="MobileFre.Progress" enum="MobileFreProgress" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>bsazonov@chromium.org</owner> <owner>msarda@chromium.org</owner> <owner>droger@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/net/histograms.xml b/tools/metrics/histograms/metadata/net/histograms.xml index 78dfc3c..ed3c83d9 100644 --- a/tools/metrics/histograms/metadata/net/histograms.xml +++ b/tools/metrics/histograms/metadata/net/histograms.xml
@@ -47,7 +47,7 @@ <variant name="SubresourceRedirectThrottle"/> </variants> -<histogram name="HttpCache.AccessToDone" units="ms" expires_after="2023-03-19"> +<histogram name="HttpCache.AccessToDone" units="ms" expires_after="2023-05-27"> <owner>morlovich@chromium.org</owner> <owner>yhirano@chromium.org</owner> <summary> @@ -197,7 +197,7 @@ </histogram> <histogram name="Net.AlternateProtocolUsage" enum="AlternateProtocolUsage" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>dschinazi@chromium.org</owner> <owner>src/net/OWNERS</owner> <summary> @@ -2718,7 +2718,7 @@ </histogram> <histogram name="Net.QuicSession.ConnectionCloseErrorCodeClient" - enum="QuicErrorCodes" expires_after="2023-03-19"> + enum="QuicErrorCodes" expires_after="2023-05-27"> <owner>dschinazi@chromium.org</owner> <owner>src/net/quic/OWNERS</owner> <summary> @@ -2738,7 +2738,7 @@ </histogram> <histogram name="Net.QuicSession.ConnectionCloseErrorCodeServer" - enum="QuicErrorCodes" expires_after="2023-03-19"> + enum="QuicErrorCodes" expires_after="2023-05-27"> <owner>dschinazi@chromium.org</owner> <owner>src/net/quic/OWNERS</owner> <summary> @@ -2978,7 +2978,7 @@ </histogram> <histogram name="Net.QuicSession.EncryptionEstablishedTime" - units="Milliseconds" expires_after="2023-03-19"> + units="Milliseconds" expires_after="2023-05-27"> <owner>fayang@chromium.org</owner> <owner>src/net/quic/OWNERS</owner> <summary> @@ -3452,7 +3452,7 @@ </histogram> <histogram name="Net.QuicSession.PacketRetransmitsPerMille" units="permille" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>dschinazi@chromium.org</owner> <owner>src/net/quic/OWNERS</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/new_tab_page/histograms.xml b/tools/metrics/histograms/metadata/new_tab_page/histograms.xml index a54fc21..ac243136 100644 --- a/tools/metrics/histograms/metadata/new_tab_page/histograms.xml +++ b/tools/metrics/histograms/metadata/new_tab_page/histograms.xml
@@ -958,7 +958,7 @@ </summary> </histogram> -<histogram name="NewTabPage.LoadTime" units="ms" expires_after="2023-03-19"> +<histogram name="NewTabPage.LoadTime" units="ms" expires_after="2023-05-27"> <owner>tiborg@chromium.org</owner> <owner>yyushkina@chromium.org</owner> <owner>chrome-desktop-ntp@google.com</owner> @@ -1064,7 +1064,7 @@ </histogram> <histogram name="NewTabPage.Modules.DataRequest" enum="NtpModules" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>danpeng@google.com</owner> <owner>tiborg@chromium.org</owner> <owner>yyushkina@chromium.org</owner> @@ -1219,7 +1219,7 @@ </histogram> <histogram name="NewTabPage.Modules.Impression" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>danpeng@google.com</owner> <owner>tiborg@chromium.org</owner> <owner>yyushkina@chromium.org</owner> @@ -1234,7 +1234,7 @@ </histogram> <histogram name="NewTabPage.Modules.ImpressionRatio" units="perdecage" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>danpeng@google.com</owner> <owner>tiborg@chromium.org</owner> <owner>chrome-desktop-ntp@google.com</owner> @@ -1267,7 +1267,7 @@ </histogram> <histogram name="NewTabPage.Modules.LoadDuration" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>danpeng@google.com</owner> <owner>tiborg@chromium.org</owner> <owner>chrome-desktop-ntp@google.com</owner> @@ -1277,7 +1277,7 @@ </histogram> <histogram name="NewTabPage.Modules.Loaded" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>danpeng@google.com</owner> <owner>tiborg@chromium.org</owner> <owner>yyushkina@chromium.org</owner> @@ -1564,7 +1564,7 @@ </histogram> <histogram name="NewTabPage.Promos.RequestLatency2" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>danpeng@google.com</owner> <owner>tiborg@chromium.org</owner> <owner>yyushkina@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/notifications/histograms.xml b/tools/metrics/histograms/metadata/notifications/histograms.xml index 7cd9d06..6d11596 100644 --- a/tools/metrics/histograms/metadata/notifications/histograms.xml +++ b/tools/metrics/histograms/metadata/notifications/histograms.xml
@@ -455,27 +455,6 @@ </summary> </histogram> -<histogram base="true" name="Notifications.Freedesktop.Capabilities" - enum="BooleanSupported" expires_after="M90"> -<!-- Name completed by histogram_suffixes name="FreedesktopNotificationCapabilitiesId" --> - - <owner>thomasanderson@chromium.org</owner> - <summary> - Whether the notification server supports the capability in question. (Linux - only) Logged when the proxy to /org/Freedesktop/Notifications is set up - successfully, which happens at most once on startup. - </summary> -</histogram> - -<histogram name="Notifications.Linux.BridgeInitializationStatus" - enum="LinuxNotificationBridgeStatusCode" expires_after="M77"> - <owner>thomasanderson@chromium.org</owner> - <summary> - The status code for initializing NotificationPlatformBridgeLinux. (Linux - only) Logged on each start up. - </summary> -</histogram> - <histogram name="Notifications.LoadProfileResult" enum="BooleanSuccess" expires_after="2022-04-17"> <owner>knollr@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/omnibox/histograms.xml b/tools/metrics/histograms/metadata/omnibox/histograms.xml index 34588dd5..940ac59 100644 --- a/tools/metrics/histograms/metadata/omnibox/histograms.xml +++ b/tools/metrics/histograms/metadata/omnibox/histograms.xml
@@ -130,7 +130,7 @@ </histogram> <histogram name="Omnibox.AnswerParseSuccess" enum="BooleanSuccess" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>jdonnelly@chromium.org</owner> <owner>chrome-omnibox-team@google.com</owner> <summary> @@ -334,7 +334,7 @@ </histogram> <histogram name="Omnibox.CharTypedToRepaintLatency" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>jdonnelly@chromium.org</owner> <owner>mpearson@chromium.org</owner> <owner>asvitkine@chromium.org</owner> @@ -546,7 +546,7 @@ </histogram> <histogram name="Omnibox.DocumentSuggest.RequestTime.Interrupted" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>manukh@chromium.org</owner> <owner>jdonnelly@chromium.org</owner> <summary> @@ -729,7 +729,7 @@ </histogram> <histogram name="Omnibox.FocusToOpenTimeAnyPopupState3" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>jdonnelly@chromium.org</owner> <owner>mpearson@chromium.org</owner> <owner>chrome-omnibox-team@google.com</owner> @@ -1218,7 +1218,7 @@ <token key="OmniboxProvider" variants="OmniboxProviders"/> </histogram> -<histogram name="Omnibox.QueryTime2" units="ms" expires_after="2023-03-19"> +<histogram name="Omnibox.QueryTime2" units="ms" expires_after="2023-05-27"> <owner>jdonnelly@chromium.org</owner> <owner>mpearson@chromium.org</owner> <owner>chrome-omnibox-team@google.com</owner> @@ -1811,7 +1811,7 @@ <histogram name="Omnibox.SuggestionUsed.Search.NavigationToFirstContentfulPaint" - units="ms" expires_after="2023-03-19"> + units="ms" expires_after="2023-05-27"> <owner>jdonnelly@chromium.org</owner> <owner>mpearson@chromium.org</owner> <owner>chrome-omnibox-team@google.com</owner> @@ -1940,7 +1940,7 @@ </histogram> <histogram name="Omnibox.SuggestRequest.Success.GoogleResponseTime" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>mpearson@chromium.org</owner> <owner>jdonnelly@chromium.org</owner> <owner>cch@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/optimization/histograms.xml b/tools/metrics/histograms/metadata/optimization/histograms.xml index 1b31412..541c43c 100644 --- a/tools/metrics/histograms/metadata/optimization/histograms.xml +++ b/tools/metrics/histograms/metadata/optimization/histograms.xml
@@ -960,7 +960,7 @@ <histogram name="OptimizationGuide.PredictionManager.DownloadServiceAvailabilityBlockedFetch" - enum="BooleanBlocked" expires_after="2023-03-19"> + enum="BooleanBlocked" expires_after="2023-05-27"> <owner>sophiechang@chromium.org</owner> <owner>mcrouse@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/others/histograms.xml b/tools/metrics/histograms/metadata/others/histograms.xml index 529dd19..c2bddd6 100644 --- a/tools/metrics/histograms/metadata/others/histograms.xml +++ b/tools/metrics/histograms/metadata/others/histograms.xml
@@ -425,6 +425,21 @@ </summary> </histogram> +<histogram name="Ads.InterestGroup.Auction.BidFiltered" enum="Boolean" + expires_after="2023-10-31"> + <owner>pauljensen@chromium.org</owner> + <owner>privacy-sandbox-dev@chromium.org</owner> + <summary> + True if the trusted bidding signals specified a per-interest-group + priorityVector whose sparse dot product with the browser generated + prioritySignals was negative, indicating the generateBid() should not be + invoked. + + See https://github.com/WICG/turtledove/blob/main/FLEDGE.md for the latest + version of the FLEDGE explainer. + </summary> +</histogram> + <histogram name="Ads.InterestGroup.Auction.CompletedWithoutWinnerTime" units="ms" expires_after="2023-07-31"> <owner>mmenke@chromium.org</owner> @@ -441,6 +456,20 @@ </summary> </histogram> +<histogram name="Ads.InterestGroup.Auction.ContextReused" enum="Boolean" + expires_after="2023-10-31"> + <owner>pauljensen@chromium.org</owner> + <owner>privacy-sandbox-dev@chromium.org</owner> + <summary> + True if the browser can reuse an existing context when calling generateBid() + whose corresponding interest group has the executionMode set to + groupByOrigin. + + See https://github.com/WICG/turtledove/blob/main/FLEDGE.md for the latest + version of the FLEDGE explainer. + </summary> +</histogram> + <histogram name="Ads.InterestGroup.Auction.DirectFromSellerSignals.RequestType" enum="DirectFromSellerSignalsRequestType" expires_after="2023-07-31"> <owner>caraitto@chromium.org</owner> @@ -483,6 +512,19 @@ </summary> </histogram> +<histogram name="Ads.InterestGroup.Auction.GenerateBidTime" units="ms" + expires_after="2023-10-31"> + <owner>pauljensen@chromium.org</owner> + <owner>privacy-sandbox-dev@chromium.org</owner> + <summary> + The length of time it took to initialize the context and arguments, and + evaluate generateBid() once. + + See https://github.com/WICG/turtledove/blob/main/FLEDGE.md for the latest + version of the FLEDGE explainer. + </summary> +</histogram> + <histogram name="Ads.InterestGroup.Auction.GroupFreshness.{Type}" units="minutes" expires_after="2023-07-31"> <owner>caraitto@chromium.org</owner> @@ -505,6 +547,34 @@ </token> </histogram> +<histogram name="Ads.InterestGroup.Auction.LoadGroupsTime" units="ms" + expires_after="2023-10-31"> + <owner>pauljensen@chromium.org</owner> + <owner>privacy-sandbox-dev@chromium.org</owner> + <summary> + The length of time it took to start a FLEDGE auction and complete loading + the interest groups that should participate in the auction; only recorded + when at least one interest group was loaded. + + See https://github.com/WICG/turtledove/blob/main/FLEDGE.md for the latest + version of the FLEDGE explainer. + </summary> +</histogram> + +<histogram name="Ads.InterestGroup.Auction.LoadNoGroupsTime" units="ms" + expires_after="2023-10-31"> + <owner>pauljensen@chromium.org</owner> + <owner>privacy-sandbox-dev@chromium.org</owner> + <summary> + The length of time it took to start a FLEDGE auction and complete loading + the interest groups that should participate in the auction; only recorded + when no interest groups were loaded. + + See https://github.com/WICG/turtledove/blob/main/FLEDGE.md for the latest + version of the FLEDGE explainer. + </summary> +</histogram> + <histogram name="Ads.InterestGroup.Auction.NumAuctionsPerPage" units="auctions" expires_after="2023-07-31"> <owner>caraitto@chromium.org</owner> @@ -607,6 +677,18 @@ </summary> </histogram> +<histogram name="Ads.InterestGroup.Auction.ProcessLaunchTime" units="ms" + expires_after="2023-10-31"> + <owner>pauljensen@chromium.org</owner> + <owner>privacy-sandbox-dev@chromium.org</owner> + <summary> + The length of time it took to launch a process to execute FLEDGE worklets. + + See https://github.com/WICG/turtledove/blob/main/FLEDGE.md for the latest + version of the FLEDGE explainer. + </summary> +</histogram> + <histogram name="Ads.InterestGroup.Auction.Result" enum="AuctionResult" expires_after="2023-07-31"> <owner>mmenke@chromium.org</owner> @@ -620,6 +702,19 @@ </summary> </histogram> +<histogram name="Ads.InterestGroup.Auction.ScoreAdTime" units="ms" + expires_after="2023-10-31"> + <owner>pauljensen@chromium.org</owner> + <owner>privacy-sandbox-dev@chromium.org</owner> + <summary> + The length of time it took to initialize the context and arguments, and + evaluate scoreAd() once. + + See https://github.com/WICG/turtledove/blob/main/FLEDGE.md for the latest + version of the FLEDGE explainer. + </summary> +</histogram> + <histogram name="Ads.InterestGroup.Auction.TimeSinceLastAuctionPerPage" units="ms" expires_after="2023-07-31"> <owner>caraitto@chromium.org</owner> @@ -3196,7 +3291,7 @@ </histogram> <histogram name="ContextMenu.Shown" enum="BooleanPresent" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>mpearson@chromium.org</owner> <owner>twellington@chromium.org</owner> <owner>clank-app-team@google.com</owner> @@ -6551,7 +6646,7 @@ <histogram name="Feedback.HappinessTrackingSurvey.ShouldShowSurveyReason" enum="HappinessTrackingSurveyShouldShowSurveyReasons" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>sauski@google.com</owner> <owner>msramek@chromium.org</owner> <summary> @@ -7348,7 +7443,7 @@ </histogram> <histogram base="true" name="Hwsec.Attestation.Status" - enum="HwsecAttestationOpsStatus" expires_after="2023-03-19"> + enum="HwsecAttestationOpsStatus" expires_after="2023-05-27"> <!-- Name completed by histogram_suffixes name="AttestationOps" --> <owner>garryxiao@chromium.org</owner> @@ -11592,7 +11687,7 @@ </histogram> <histogram name="RenderViewContextMenu.OpenLinkAsProfile" enum="OpenLinkAs" - expires_after="2023-03-23"> + expires_after="2023-05-27"> <owner>gabolvr@google.com</owner> <owner>droger@chromium.org</owner> <summary> @@ -12163,7 +12258,7 @@ </summary> </histogram> -<histogram name="SB2.RemoteCall.Elapsed" units="ms" expires_after="2023-03-26"> +<histogram name="SB2.RemoteCall.Elapsed" units="ms" expires_after="2023-05-27"> <owner>vakh@chromium.org</owner> <owner>chrome-counter-abuse-alerts@google.com</owner> <summary> @@ -12405,7 +12500,7 @@ </histogram> <histogram name="SBIRS.UploadResult" enum="ReportProcessingResult" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>caitkp@google.com</owner> <summary> The result of an attempted report upload by the safe browsing incident @@ -13026,7 +13121,7 @@ </histogram> <histogram name="SignedExchange.LoadResult2" enum="SignedExchangeLoadResult" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>ksakamoto@chromium.org</owner> <owner>webpackage-dev@chromium.org</owner> <summary> @@ -13575,7 +13670,7 @@ </histogram> <histogram base="true" name="Spellcheck.Windows.SpellcheckRequestDuration" - units="ms" expires_after="2023-03-19"> + units="ms" expires_after="2023-05-27"> <owner>gujen@google.com</owner> <owner>chrome-language@google.com</owner> <summary> @@ -14816,7 +14911,7 @@ </histogram> <histogram name="Uptime.ChromeExecToLoginPromptVisibleAfterLogout" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>alemate@chromium.org</owner> <owner>cros-oac@google.com</owner> <owner>xiyuan@chromium.org</owner> @@ -15571,7 +15666,7 @@ </histogram> <histogram name="WebFont.BlankTextShownTime" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>kenjibaheux@chromium.org</owner> <owner>ksakamoto@chromium.org</owner> <summary> @@ -15679,7 +15774,7 @@ </histogram> <histogram name="WebFont.HadBlankText" enum="BooleanHadBlankText" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>kenjibaheux@chromium.org</owner> <owner>ksakamoto@chromium.org</owner> <summary> @@ -15713,7 +15808,7 @@ </histogram> <histogram name="WebFont.LocalFontUsed" enum="BooleanUsage" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>hajimehoshi@chromium.org</owner> <owner>kenjibaheux@chromium.org</owner> <owner>kouhei@chromium.org</owner> @@ -16184,7 +16279,7 @@ </histogram> <histogram name="WrenchMenu.TimeToAction" units="units" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>ainslie@chromium.org</owner> <owner>edwardjung@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/password/histograms.xml b/tools/metrics/histograms/metadata/password/histograms.xml index 3ee3a31e..d7ba57f 100644 --- a/tools/metrics/histograms/metadata/password/histograms.xml +++ b/tools/metrics/histograms/metadata/password/histograms.xml
@@ -877,7 +877,7 @@ </histogram> <histogram name="PasswordManager.AutomaticChange.ForSitesWithScripts" - enum="PasswordCheckResolutionAction" expires_after="2023-03-26"> + enum="PasswordCheckResolutionAction" expires_after="2023-05-27"> <owner>kolos@chromium.org</owner> <owner>battre@chromium.org</owner> <summary> @@ -1133,7 +1133,7 @@ </histogram> <histogram name="PasswordManager.CanUseBiometricsMac" enum="BooleanSuccess" - expires_after="M112"> + expires_after="2023-05-27"> <owner>vsemeniuk@google.com</owner> <owner>kazinova@google.com</owner> <owner>sygiet@google.com</owner> @@ -1773,7 +1773,7 @@ </histogram> <histogram name="PasswordManager.IsSyncPasswordHashSaved" - enum="IsSyncPasswordHashSaved" expires_after="2023-03-19"> + enum="IsSyncPasswordHashSaved" expires_after="2023-05-27"> <owner>vakh@chromium.org</owner> <owner>chrome-counter-abuse-alerts@google.com</owner> <summary> @@ -2227,7 +2227,7 @@ </histogram> <histogram name="PasswordManager.PasswordDropdownShown" - enum="PasswordDropdownState" expires_after="2023-03-26"> + enum="PasswordDropdownState" expires_after="2023-05-27"> <owner>kazinova@google.com</owner> <owner>vasilii@chromium.org</owner> <summary>Logs the state of the password dropdown when it's shown.</summary>
diff --git a/tools/metrics/histograms/metadata/payment/histograms.xml b/tools/metrics/histograms/metadata/payment/histograms.xml index b4a02ea7..e0faad18 100644 --- a/tools/metrics/histograms/metadata/payment/histograms.xml +++ b/tools/metrics/histograms/metadata/payment/histograms.xml
@@ -37,7 +37,7 @@ </histogram> <histogram name="PaymentRequest.CheckoutFunnel" - enum="PaymentRequestCheckoutFunnelSteps" expires_after="2023-03-19"> + enum="PaymentRequestCheckoutFunnelSteps" expires_after="2023-05-27"> <owner>rouslan@chromium.org</owner> <owner>web-payments-team@google.com</owner> <summary> @@ -250,7 +250,7 @@ </histogram> <histogram name="PaymentRequest.TransactionAmount.Completed" - enum="PaymentRequestTransactionSize" expires_after="2023-03-19"> + enum="PaymentRequestTransactionSize" expires_after="2023-05-27"> <owner>rouslan@chromium.org</owner> <owner>web-payments-team@google.com</owner> <summary> @@ -260,7 +260,7 @@ </histogram> <histogram name="PaymentRequest.TransactionAmount.Triggered" - enum="PaymentRequestTransactionSize" expires_after="2023-03-19"> + enum="PaymentRequestTransactionSize" expires_after="2023-05-27"> <owner>rouslan@chromium.org</owner> <owner>web-payments-team@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/platform/histograms.xml b/tools/metrics/histograms/metadata/platform/histograms.xml index 08c6ee15..a47ca63 100644 --- a/tools/metrics/histograms/metadata/platform/histograms.xml +++ b/tools/metrics/histograms/metadata/platform/histograms.xml
@@ -924,7 +924,7 @@ </summary> </histogram> -<histogram name="Platform.Memory.ARC" units="MiB" expires_after="2023-03-19"> +<histogram name="Platform.Memory.ARC" units="MiB" expires_after="2023-05-27"> <!-- Name completed by histogram_suffixes name="ProcessMemoryType" --> <owner>bgeffon@chromium.org</owner> @@ -1549,7 +1549,7 @@ </histogram> <histogram name="Platform.TPM.FirmwareUpdate.Result" - enum="TPMFirmwareUpdateResult" expires_after="2023-03-19"> + enum="TPMFirmwareUpdateResult" expires_after="2023-05-27"> <owner>mnissler@chromium.org</owner> <owner>cros-hwsec+uma@chromium.org</owner> <summary>Status of a complete TPM firmware update attempt.</summary>
diff --git a/tools/metrics/histograms/metadata/power/histograms.xml b/tools/metrics/histograms/metadata/power/histograms.xml index d37dcad..4e74ffb 100644 --- a/tools/metrics/histograms/metadata/power/histograms.xml +++ b/tools/metrics/histograms/metadata/power/histograms.xml
@@ -538,7 +538,7 @@ </histogram> <histogram name="Power.AdaptiveChargingBatteryPercentageOnUnplug" units="%" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>dbasehore@chromium.org</owner> <owner>chromeos-platform-power@google.com</owner> <summary> @@ -671,7 +671,7 @@ </histogram> <histogram name="Power.AdaptiveChargingMinutesToFull" units="minutes" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>dbasehore@chromium.org</owner> <owner>chromeos-platform-power@google.com</owner> <summary> @@ -1922,7 +1922,7 @@ </token> </histogram> -<histogram base="true" name="Power.Mac" units="mW" expires_after="2023-03-19"> +<histogram base="true" name="Power.Mac" units="mW" expires_after="2023-05-27"> <owner>olivierli@chromium.org</owner> <owner>markchang@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/printing/histograms.xml b/tools/metrics/histograms/metadata/printing/histograms.xml index 83f8005..b4bef15 100644 --- a/tools/metrics/histograms/metadata/printing/histograms.xml +++ b/tools/metrics/histograms/metadata/printing/histograms.xml
@@ -138,7 +138,7 @@ </histogram> <histogram name="Printing.CUPS.JobDuration.JobDone" units="ms" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>bmgordon@chromium.org</owner> <owner>project-bolton@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/profile/histograms.xml b/tools/metrics/histograms/metadata/profile/histograms.xml index 5e0bde3..2f5ac4c 100644 --- a/tools/metrics/histograms/metadata/profile/histograms.xml +++ b/tools/metrics/histograms/metadata/profile/histograms.xml
@@ -802,7 +802,7 @@ </histogram> <histogram name="ProfilePicker.StartupTime.BeforeCreation" units="ms" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>alexilin@chromium.org</owner> <owner>dgn@chromium.org</owner> <owner>chrome-signin-team@google.com</owner> @@ -825,7 +825,7 @@ </histogram> <histogram name="ProfilePicker.StartupTime.FirstPaint.FromApplicationStart" - units="ms" expires_after="2023-03-26"> + units="ms" expires_after="2023-05-27"> <owner>alexilin@chromium.org</owner> <owner>dgn@chromium.org</owner> <owner>chrome-signin-team@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/renderer/histograms.xml b/tools/metrics/histograms/metadata/renderer/histograms.xml index 76683ea..952b4750 100644 --- a/tools/metrics/histograms/metadata/renderer/histograms.xml +++ b/tools/metrics/histograms/metadata/renderer/histograms.xml
@@ -353,7 +353,7 @@ </histogram> <histogram name="Renderer.Font.Shaping.DomContentLoaded" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>tkent@chromium.org</owner> <owner>kojii@chromium.org</owner> <owner>yosin@chromium.org</owner> @@ -366,7 +366,7 @@ </histogram> <histogram name="Renderer.Font.Shaping.FCP" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>tkent@chromium.org</owner> <owner>kojii@chromium.org</owner> <owner>yosin@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/safe_browsing/histograms.xml b/tools/metrics/histograms/metadata/safe_browsing/histograms.xml index ed664ab..34b0632 100644 --- a/tools/metrics/histograms/metadata/safe_browsing/histograms.xml +++ b/tools/metrics/histograms/metadata/safe_browsing/histograms.xml
@@ -1298,7 +1298,7 @@ </histogram> <histogram name="SafeBrowsing.RT.GetCacheResult" - enum="SafeBrowsingRTLookupResponseVerdictType" expires_after="2023-03-19"> + enum="SafeBrowsingRTLookupResponseVerdictType" expires_after="2023-05-27"> <owner>xinghuilu@chromium.org</owner> <owner>chrome-counter-abuse-alerts@google.com</owner> <summary> @@ -1856,7 +1856,7 @@ </histogram> <histogram name="SafeBrowsing.V4GetHash.Network.Result" - enum="CombinedHttpResponseAndNetErrorCode" expires_after="2023-03-19"> + enum="CombinedHttpResponseAndNetErrorCode" expires_after="2023-05-27"> <owner>vakh@google.com</owner> <owner>kcarattini@google.com</owner> <owner>chrome-counter-abuse-alerts@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/sb_client/histograms.xml b/tools/metrics/histograms/metadata/sb_client/histograms.xml index 09de8a3..3116932 100644 --- a/tools/metrics/histograms/metadata/sb_client/histograms.xml +++ b/tools/metrics/histograms/metadata/sb_client/histograms.xml
@@ -35,7 +35,7 @@ </variants> <histogram name="SBClientDownload.CheckDownloadStats" - enum="SBClientDownloadCheckDownloadStats" expires_after="2023-03-19"> + enum="SBClientDownloadCheckDownloadStats" expires_after="2023-05-27"> <owner>vakh@chromium.org</owner> <owner>chrome-counter-abuse-alerts@google.com</owner> <owner>mattm@chromium.org</owner> @@ -734,7 +734,7 @@ </histogram> <histogram name="SBClientPhishing.LocalModelDetectsPhishing" - enum="BooleanIsPhishing" expires_after="2023-03-19"> + enum="BooleanIsPhishing" expires_after="2023-05-27"> <owner>drubery@chromium.org</owner> <owner>chrome-counter-abuse-alerts@google.com</owner> <summary> @@ -774,7 +774,7 @@ </histogram> <histogram name="SBClientPhishing.ModelDynamicUpdateSuccess" - enum="BooleanSuccess" expires_after="2023-03-19"> + enum="BooleanSuccess" expires_after="2023-05-27"> <owner>drubery@chromium.org</owner> <owner>chrome-counter-abuse-alerts@google.com</owner> <summary> @@ -823,7 +823,7 @@ </histogram> <histogram name="SBClientPhishing.PhishingDetectorResult" - enum="ClientSidePhishingResult" expires_after="2023-03-19"> + enum="ClientSidePhishingResult" expires_after="2023-05-27"> <owner>drubery@chromium.org</owner> <owner>chrome-counter-abuse-alerts@google.com</owner> <summary> @@ -883,7 +883,7 @@ </histogram> <histogram name="SBClientPhishing.ServerModelDetectsPhishing" - enum="BooleanIsPhishing" expires_after="2023-03-19"> + enum="BooleanIsPhishing" expires_after="2023-05-27"> <owner>drubery@chromium.org</owner> <owner>chrome-counter-abuse-alerts@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/segmentation_platform/histograms.xml b/tools/metrics/histograms/metadata/segmentation_platform/histograms.xml index 4de26b8f..f8bf99f 100644 --- a/tools/metrics/histograms/metadata/segmentation_platform/histograms.xml +++ b/tools/metrics/histograms/metadata/segmentation_platform/histograms.xml
@@ -120,7 +120,7 @@ <histogram name="SegmentationPlatform.AdaptiveToolbar.SegmentSelection.Computed" - enum="AdaptiveToolbarButtonVariant" expires_after="2023-03-21"> + enum="AdaptiveToolbarButtonVariant" expires_after="2023-05-27"> <owner>shaktisahu@chromium.org</owner> <owner>chrome-segmentation-platform@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/service/histograms.xml b/tools/metrics/histograms/metadata/service/histograms.xml index 9aa0331..dd96315 100644 --- a/tools/metrics/histograms/metadata/service/histograms.xml +++ b/tools/metrics/histograms/metadata/service/histograms.xml
@@ -387,7 +387,7 @@ </histogram> <histogram name="ServiceWorker.FetchEvent.MainResource.Status" - enum="ServiceWorkerStatusCode" expires_after="2023-03-19"> + enum="ServiceWorkerStatusCode" expires_after="2023-05-27"> <owner>wanderview@chromium.org</owner> <owner>asamidoi@chromium.org</owner> <owner>chrome-worker@google.com</owner> @@ -411,7 +411,7 @@ </histogram> <histogram name="ServiceWorker.FetchEvent.Subresource.Status" - enum="ServiceWorkerStatusCode" expires_after="2023-03-19"> + enum="ServiceWorkerStatusCode" expires_after="2023-05-27"> <owner>wanderview@chromium.org</owner> <owner>asamidoi@chromium.org</owner> <owner>chrome-worker@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/settings/histograms.xml b/tools/metrics/histograms/metadata/settings/histograms.xml index 082db63..09bebf8 100644 --- a/tools/metrics/histograms/metadata/settings/histograms.xml +++ b/tools/metrics/histograms/metadata/settings/histograms.xml
@@ -278,7 +278,7 @@ </histogram> <histogram name="Settings.PrivacyGuide.EntryExit" - enum="SettingsPrivacyGuideInteractions" expires_after="2023-03-19"> + enum="SettingsPrivacyGuideInteractions" expires_after="2023-05-27"> <owner>harrisonsean@chromium.org</owner> <owner>rainhard@chromium.org</owner> <owner>chrome-friendly-settings@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/signin/histograms.xml b/tools/metrics/histograms/metadata/signin/histograms.xml index 450d0263..ef4c62ef 100644 --- a/tools/metrics/histograms/metadata/signin/histograms.xml +++ b/tools/metrics/histograms/metadata/signin/histograms.xml
@@ -1023,7 +1023,7 @@ </histogram> <histogram name="Signin.SigninCompletedAccessPoint" enum="SigninAccessPoint" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>msarda@chromium.org</owner> <owner>bsazonov@chromium.org</owner> <owner>droger@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/startup/histograms.xml b/tools/metrics/histograms/metadata/startup/histograms.xml index 654cde0..b06b25a 100644 --- a/tools/metrics/histograms/metadata/startup/histograms.xml +++ b/tools/metrics/histograms/metadata/startup/histograms.xml
@@ -68,7 +68,7 @@ </histogram> <histogram name="Startup.Android.Cold.FirstPaintOccurredPreForeground" - enum="Boolean" expires_after="2023-03-19"> + enum="Boolean" expires_after="2023-05-27"> <owner>blundell@chromium.org</owner> <owner>yfriedman@chromium.org</owner> <summary> @@ -784,7 +784,7 @@ </histogram> <histogram name="Startup.MobileSessionStartAction" - enum="MobileSessionStartAction" expires_after="2023-03-26"> + enum="MobileSessionStartAction" expires_after="2023-05-27"> <owner>thegreenfrog@chromium.org</owner> <owner>olivierrobin@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/subresource/histograms.xml b/tools/metrics/histograms/metadata/subresource/histograms.xml index fd385124..9b5ae1c 100644 --- a/tools/metrics/histograms/metadata/subresource/histograms.xml +++ b/tools/metrics/histograms/metadata/subresource/histograms.xml
@@ -23,7 +23,7 @@ <histograms> <histogram name="SubresourceFilter.Actions2" enum="SubresourceFilterActions2" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>alexmt@chromium.org</owner> <owner>chrome-ads-histograms@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/sync/histograms.xml b/tools/metrics/histograms/metadata/sync/histograms.xml index b2af8bb6..860e1a61 100644 --- a/tools/metrics/histograms/metadata/sync/histograms.xml +++ b/tools/metrics/histograms/metadata/sync/histograms.xml
@@ -519,7 +519,7 @@ </histogram> <histogram name="Sync.IncomingInvalidationStatus" - enum="SyncIncomingInvalidationStatus" expires_after="2023-03-19"> + enum="SyncIncomingInvalidationStatus" expires_after="2023-05-27"> <owner>rushans@google.com</owner> <owner>treib@chromium.org</owner> <component>Services>Sync</component> @@ -624,7 +624,7 @@ </summary> </histogram> -<histogram name="Sync.Local.FileSizeKB" units="KB" expires_after="2023-03-19"> +<histogram name="Sync.Local.FileSizeKB" units="KB" expires_after="2023-05-27"> <owner>igorruvinov@chromium.org</owner> <owner>pastarmovj@chromium.org</owner> <component>Services>Sync</component> @@ -1037,7 +1037,7 @@ </histogram> <histogram name="Sync.PostedClientToServerMessageLatency" units="ms" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>mastiz@chromium.org</owner> <component>Services>Sync</component> <summary> @@ -1075,7 +1075,7 @@ </histogram> <histogram name="Sync.PostedGetUpdatesOrigin" enum="SyncGetUpdatesOrigin" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>mastiz@chromium.org</owner> <owner>rushans@google.com</owner> <component>Services>Sync</component> @@ -1343,7 +1343,7 @@ </histogram> <histogram name="Sync.TrustedVaultAccessTokenFetchSuccess" enum="Boolean" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>mmoskvitin@google.com</owner> <owner>mastiz@chromium.org</owner> <component>Services>Sync</component>
diff --git a/tools/metrics/histograms/metadata/tab/histograms.xml b/tools/metrics/histograms/metadata/tab/histograms.xml index 1a658e4c..483fd43 100644 --- a/tools/metrics/histograms/metadata/tab/histograms.xml +++ b/tools/metrics/histograms/metadata/tab/histograms.xml
@@ -2481,7 +2481,7 @@ </summary> </histogram> -<histogram name="Tabs.TabState.LoadTime" units="ms" expires_after="2023-03-19"> +<histogram name="Tabs.TabState.LoadTime" units="ms" expires_after="2023-05-27"> <owner>yusufo@chromium.org</owner> <owner>nyquist@chromium.org</owner> <owner>dtrainor@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/translate/histograms.xml b/tools/metrics/histograms/metadata/translate/histograms.xml index 2bdb3b15..e841592 100644 --- a/tools/metrics/histograms/metadata/translate/histograms.xml +++ b/tools/metrics/histograms/metadata/translate/histograms.xml
@@ -97,7 +97,7 @@ </histogram> <histogram name="Translate.BubbleUiEvent" enum="TranslateBubbleUiEvent" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>groby@google.com</owner> <owner>chrome-language@google.com</owner> <summary>Tracks UI events related to the Full Page Translate bubble.</summary> @@ -147,7 +147,7 @@ </histogram> <histogram name="Translate.CompactInfobar.Event" enum="TranslateCompactUIEvent" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>megjablon@google.com</owner> <owner>chrome-language@google.com</owner> <summary>Various user actions performed in the translate infobar.</summary> @@ -267,7 +267,7 @@ </histogram> <histogram name="Translate.HrefHint.Status" enum="HrefTranslateStatus" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>sclittle@google.com</owner> <owner>megjablon@google.com</owner> <owner>chrome-language@google.com</owner> @@ -291,7 +291,7 @@ </histogram> <histogram name="Translate.InitiationStatus.v2" - enum="TranslateInitiationStatus" expires_after="2023-03-19"> + enum="TranslateInitiationStatus" expires_after="2023-05-27"> <owner>megjablon@google.com</owner> <owner>chrome-language@google.com</owner> <summary> @@ -312,7 +312,7 @@ </histogram> <histogram name="Translate.LanguageDetection.LanguageVerification" - enum="TranslateLanguageVerification" expires_after="2023-03-19"> + enum="TranslateLanguageVerification" expires_after="2023-05-27"> <owner>megjablon@google.com</owner> <owner>chrome-language@google.com</owner> <summary> @@ -799,7 +799,7 @@ </histogram> <histogram name="Translate.ShowErrorUI" enum="TranslateError" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>megjablon@google.com</owner> <owner>chrome-language@google.com</owner> <summary> @@ -824,7 +824,7 @@ </histogram> <histogram name="Translate.SourceLanguage" enum="LocaleCodeISO639" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>megjablon@google.com</owner> <owner>chrome-language@google.com</owner> <summary> @@ -855,7 +855,7 @@ </histogram> <histogram name="Translate.Translate" enum="BooleanTranslate" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>megjablon@google.com</owner> <owner>chrome-language@google.com</owner> <summary> @@ -957,7 +957,7 @@ </histogram> <histogram name="Translate.Translation.Status" enum="TranslationStatus" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>megjablon@google.com</owner> <owner>chrome-language@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/v8/histograms.xml b/tools/metrics/histograms/metadata/v8/histograms.xml index cc0e6aa..7afb67af 100644 --- a/tools/metrics/histograms/metadata/v8/histograms.xml +++ b/tools/metrics/histograms/metadata/v8/histograms.xml
@@ -1046,7 +1046,7 @@ </summary> </histogram> -<histogram name="V8.GCFinalizeMC" units="ms" expires_after="2023-03-26"> +<histogram name="V8.GCFinalizeMC" units="ms" expires_after="2023-05-27"> <owner>mlippautz@chromium.org</owner> <owner>hpayer@chromium.org</owner> <owner>v8-memory-sheriffs@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/variations/histograms.xml b/tools/metrics/histograms/metadata/variations/histograms.xml index 7a6c33e..1878b1c 100644 --- a/tools/metrics/histograms/metadata/variations/histograms.xml +++ b/tools/metrics/histograms/metadata/variations/histograms.xml
@@ -190,7 +190,7 @@ </histogram> <histogram name="Variations.Headers.ExperimentCount" units="units" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>asvitkine@chromium.org</owner> <owner>rkaplow@chromium.org</owner> <owner>src/base/metrics/OWNERS</owner> @@ -490,7 +490,7 @@ </histogram> <histogram name="Variations.SeedFreshness" units="minutes" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>asvitkine@chromium.org</owner> <owner>rkaplow@chromium.org</owner> <owner>src/base/metrics/OWNERS</owner> @@ -535,7 +535,7 @@ </histogram> <histogram name="Variations.SeedLoadResult" enum="VariationsSeedLoadResult" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>asvitkine@chromium.org</owner> <owner>rkaplow@chromium.org</owner> <owner>src/base/metrics/OWNERS</owner> @@ -560,7 +560,7 @@ </histogram> <histogram name="Variations.SeedStoreResult" enum="VariationsSeedStoreResult" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>asvitkine@chromium.org</owner> <owner>rkaplow@chromium.org</owner> <owner>src/base/metrics/OWNERS</owner> @@ -571,7 +571,7 @@ </histogram> <histogram name="Variations.SeedUsage" enum="VariationsSeedUsage" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>caitlinfischer@google.com</owner> <owner>src/base/metrics/OWNERS</owner> <summary> @@ -647,7 +647,7 @@ </histogram> <histogram name="Variations.StoreSeed.Time" units="ms" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>asvitkine@chromium.org</owner> <owner>src/base/metrics/OWNERS</owner> <summary> @@ -690,7 +690,7 @@ </histogram> <histogram name="Variations.UserChannel" enum="UserChannels" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>asvitkine@chromium.org</owner> <owner>rkaplow@chromium.org</owner> <owner>src/base/metrics/OWNERS</owner>
diff --git a/tools/metrics/histograms/metadata/web_rtc/histograms.xml b/tools/metrics/histograms/metadata/web_rtc/histograms.xml index 83931d0..11f9ae9 100644 --- a/tools/metrics/histograms/metadata/web_rtc/histograms.xml +++ b/tools/metrics/histograms/metadata/web_rtc/histograms.xml
@@ -273,7 +273,7 @@ </histogram> <histogram name="WebRTC.Audio.ApmCaptureOutputLevelAverageRms" - units="dBFS (negated)" expires_after="2023-03-19"> + units="dBFS (negated)" expires_after="2023-05-27"> <owner>peah@chromium.org</owner> <summary> This histogram reports the average RMS of the signal in the output of @@ -285,7 +285,7 @@ </histogram> <histogram name="WebRTC.Audio.ApmCaptureOutputLevelPeakRms" - units="dBFS (negated)" expires_after="2023-03-19"> + units="dBFS (negated)" expires_after="2023-05-27"> <owner>peah@chromium.org</owner> <summary> This histogram reports the peak RMS of the signal in the output of WebRTC's @@ -358,7 +358,7 @@ </histogram> <histogram name="WebRTC.Audio.AverageExcessBufferDelayMs" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>hlundin@chromium.org</owner> <owner>gustaf@chromium.org</owner> <summary> @@ -383,7 +383,7 @@ </histogram> <histogram name="WebRTC.Audio.DelayedPacketOutageEventsPerMinute" - units="events/minute" expires_after="2023-03-19"> + units="events/minute" expires_after="2023-05-27"> <owner>hlundin@chromium.org</owner> <summary> Counts the number of delayed packet outage events per minute. The range is @@ -394,7 +394,7 @@ </histogram> <histogram name="WebRTC.Audio.EchoCanceller.BufferDelay" units="Blocks/2" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>peah@chromium.org</owner> <owner>saza@chromium.org</owner> <summary> @@ -634,7 +634,7 @@ </histogram> <histogram name="WebRTC.Audio.Encoder.CodecType" enum="WebRtcAudioCodecs" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>aleloi@chromium.org</owner> <summary> Histogram of audio codec usage. Every sample corresponds to 5 seconds of @@ -680,7 +680,7 @@ </histogram> <histogram name="WebRTC.Audio.ReceiverDeviceDelayMs" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>hlundin@chromium.org</owner> <summary> The sound card's buffering delay for the receiving side. Sampled once every @@ -689,7 +689,7 @@ </histogram> <histogram name="WebRTC.Audio.ReceiverJitterBufferDelayMs" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>hlundin@chromium.org</owner> <summary> The jitter buffer delay for the receiving side. Sampled once every 10 ms @@ -710,7 +710,7 @@ </histogram> <histogram name="WebRTC.Audio.TargetBitrateInKbps" units="kbps" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>hlundin@chromium.org</owner> <summary> The target bitrate in kbps that the audio codec should try to produce on @@ -774,7 +774,7 @@ </histogram> <histogram name="WebRTC.BWE.InitialBandwidthEstimate" units="kbps" - expires_after="2023-03-26"> + expires_after="2023-05-27"> <owner>holmer@chromium.org</owner> <summary>The bandwidth estimate 2 seconds into a WebRTC call.</summary> </histogram> @@ -892,7 +892,7 @@ </histogram> <histogram name="WebRTC.BWE.RampUpTimeTo2000kbpsInMs" units="ms" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>holmer@chromium.org</owner> <summary> The time it takes the estimated bandwidth to reach 2000 kbps from the first @@ -930,7 +930,7 @@ </histogram> <histogram name="WebRTC.Call.BitrateReceivedInKbps" units="kbps" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>holmer@chromium.org</owner> <summary> Average total bitrate received during a call (audio + video + RTCP), counted @@ -958,7 +958,7 @@ </histogram> <histogram name="WebRTC.Call.PacerBitrateInKbps" units="kbps" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>holmer@chromium.org</owner> <summary> Average pacer bitrate during a call, counted from first packet sent until @@ -1002,7 +1002,7 @@ </histogram> <histogram name="WebRTC.Call.VideoBitrateReceivedInKbps" units="kbps" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>holmer@chromium.org</owner> <summary> Average video bitrate received during a call, counted from first packet
diff --git a/tools/metrics/histograms/metadata/webapps/histograms.xml b/tools/metrics/histograms/metadata/webapps/histograms.xml index c1a6f196..509d1158 100644 --- a/tools/metrics/histograms/metadata/webapps/histograms.xml +++ b/tools/metrics/histograms/metadata/webapps/histograms.xml
@@ -62,7 +62,7 @@ </histogram> <histogram name="AppBanners.InstallableStatusCode" enum="InstallableStatusCode" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>dominickn@chromium.org</owner> <owner>pjmclachlan@google.com</owner> <summary> @@ -75,7 +75,7 @@ </histogram> <histogram name="AppBanners.InstallEvent" enum="AppBannersInstallEvent" - expires_after="2023-03-19"> + expires_after="2023-05-27"> <owner>dominickn@chromium.org</owner> <owner>pjmclachlan@google.com</owner> <owner>pcovell@google.com</owner> @@ -1066,6 +1066,21 @@ <summary>Records the result of shortcut creation for PWA.</summary> </histogram> +<histogram name="WebApp.Shortcuts.Update.Result" enum="BooleanSuccess" + expires_after="2023-12-16"> + <owner>camdenking@google.com</owner> + <owner>desktop-pwas-team@google.com</owner> + <summary> + The result of updating shortcuts for an installed PWA. Shortcuts are usually + the icon in the operating system signifying the app or extension as an OS + entity (e.g. on Mac, it's the .app file). Updating shortcuts occurs when an + app is updated through the manifest update mechanism, when the Mac + architecture changes, the shortcut version number has been updated, and when + the user denies use of protocol handlers or file handlers, which occurs on + launch of those respective features. + </summary> +</histogram> + <histogram name="WebApp.ShortcutsMenuRegistration.Result" enum="BooleanSuccess" expires_after="2023-09-10"> <owner>dibyapal@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/xr/histograms.xml b/tools/metrics/histograms/metadata/xr/histograms.xml index 0d5b3ed4..14a97b2 100644 --- a/tools/metrics/histograms/metadata/xr/histograms.xml +++ b/tools/metrics/histograms/metadata/xr/histograms.xml
@@ -75,7 +75,7 @@ </summary> </histogram> -<histogram name="XR.RuntimeUsed" enum="XRDeviceId" expires_after="2023-01-07"> +<histogram name="XR.RuntimeUsed" enum="XRDeviceId" expires_after="2024-01-07"> <owner>alcooper@chromium.org</owner> <owner>xr-dev@chromium.org</owner> <summary>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 7b338649..e6b2b46d 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -6,15 +6,15 @@ }, "win": { "hash": "a9ae080a553abd2b39f574f81afb8bfdadee9eb3", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/c08e444ccf161bcd4877ec6add8f75a446187137/trace_processor_shell.exe" + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/1af6f10d7c0429403e0f7ad4429a0023bb70c763/trace_processor_shell.exe" }, "linux_arm": { "hash": "6373f26144aad58f230d11d6a91efda5a09c9873", "full_remote_path": "perfetto-luci-artifacts/v31.0/linux-arm/trace_processor_shell" }, "mac": { - "hash": "07337673499510fd49cb1d8b8b656cf4905afb81", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/5f99acc936816759400c8ce5e4ee1cee2fc0633e/trace_processor_shell" + "hash": "01d68bd5aee0af9d9d4f1aa1399eeb4f94f27958", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/1af6f10d7c0429403e0f7ad4429a0023bb70c763/trace_processor_shell" }, "mac_arm64": { "hash": "5f47ee79e59d00bf3889d30ca52315522c158040", @@ -22,7 +22,7 @@ }, "linux": { "hash": "d4b785b5f6bfb57ebe334fafd151986aa3021d4d", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/3c96d773ed3715d277b4488470da2bd32db55c52/trace_processor_shell" + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/1af6f10d7c0429403e0f7ad4429a0023bb70c763/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/tools/perf/page_sets/ad_frames.py b/tools/perf/page_sets/ad_frames.py index ffe2264..5c56d61 100644 --- a/tools/perf/page_sets/ad_frames.py +++ b/tools/perf/page_sets/ad_frames.py
@@ -32,8 +32,6 @@ '--enable-privacy-sandbox-ads-apis', '--expose-internals-for-testing', '--disk-cache-dir=/dev/null', - '--media-cache-size=0', - '--disk-cache-size=0', ], cache_temperature=cache_temperature_module.COLD)
diff --git a/tools/rust/README.md b/tools/rust/README.md index 879e763..c9e2f0e9 100644 --- a/tools/rust/README.md +++ b/tools/rust/README.md
@@ -12,7 +12,7 @@ Like with Clang, Chromium uses bleeding edge Rust tooling. We track the upstream projects' latest development as closely as possible. However, Chromium cannot use official Rust builds for various reasons which require us to match the Rust -LLVM backend version with the Clang we use. +LLVM backend version with the Clang we use. It would not be reasonable to build the tooling for every Chromium build, so we build it centrally (with the scripts here) and distribute it for all to use @@ -93,6 +93,15 @@ This step is not strictly necessary since the CI tooling will catch any errors. But the CI build process is slow and this can save some time. +To fetch the new Rust sources, and avoid errors during `gclient sync`: +1. Ensure your `.gclient` file has `checkout_rust_toolchain_deps` set to `True`, +but avoid setting `use_rust` to `True`. The latter will try to download the +compiled rustc but as you've just updated the version there is no compiled rustc +to download so it will fail. +1. Additionally, to aid in testing, turn off rust support in GN, with +`enable_rust = false`, since it requires the presence of a Rust toolchain, but +building the toolchain destroys your local toolchain until the build succeeds. + Running this will do a full build and provide a local toolchain that works for the host machine, albeit not the same as the CI-provided one: @@ -231,4 +240,3 @@ `//build/rust/tests/BUILD.gn`, but they should still be built and run before rolling Crubit. TODO(https://crbug.com/1329611): Rephrase this paragraph after Crubit is built and tested on the bots. -
diff --git a/tools/rust/config.toml.template b/tools/rust/config.toml.template index 98afa54a..e7b8302 100644 --- a/tools/rust/config.toml.template +++ b/tools/rust/config.toml.template
@@ -29,6 +29,10 @@ locked-deps = true vendor = true +# We enable profiler so that PGO and coverage build options are available +# with the rust compiler we build. +profiler = true + target = ["x86_64-unknown-linux-gnu"] [install]
diff --git a/ui/accessibility/BUILD.gn b/ui/accessibility/BUILD.gn index 416b489c..0c93ce8 100644 --- a/ui/accessibility/BUILD.gn +++ b/ui/accessibility/BUILD.gn
@@ -318,7 +318,27 @@ ] if (enable_extensions) { - sources += [ "platform/automation/automation_api_util_unittest.cc" ] + sources += [ + "platform/automation/automation_api_util_unittest.cc", + "platform/automation/automation_tree_manager_owner_unittest.cc", + ] + public_deps = [ "//gin" ] + configs += [ + "//tools/v8_context_snapshot:use_v8_context_snapshot", + "//v8:external_startup_data", + ] + + if (is_fuchsia) { + # TODO(https://crbug.com/1185811): Investigate removing the requirement for + # job_policy_ambient_mark_vmo_exec for the sake of V8's allocator in tests. + test_runner_shard = "//build/config/fuchsia/test/elf_test_ambient_exec_runner.shard.test-cml" + + additional_manifest_fragments = [ + "//build/config/fuchsia/test/mark_vmo_executable.shard.test-cml", + "//build/config/fuchsia/test/network.shard.test-cml", + "//third_party/fuchsia-sdk/sdk/pkg/vulkan/client.shard.cml", + ] + } } if (is_fuchsia) {
diff --git a/ui/accessibility/ax_node.h b/ui/accessibility/ax_node.h index febdc99..7668077 100644 --- a/ui/accessibility/ax_node.h +++ b/ui/accessibility/ax_node.h
@@ -17,6 +17,7 @@ #include "base/containers/queue.h" #include "base/containers/stack.h" #include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" @@ -38,7 +39,7 @@ class AXTree; // This class is used to represent a node in an accessibility tree (`AXTree`). -class AX_EXPORT AXNode final { +class AX_EXPORT AXNode final : public base::SupportsWeakPtr<AXNode> { public: // Replacement character used to represent an embedded (or, additionally for // text navigation, an empty) object. Part of the Unicode Standard.
diff --git a/ui/accessibility/ax_position.h b/ui/accessibility/ax_position.h index 074e35a..8cb6674 100644 --- a/ui/accessibility/ax_position.h +++ b/ui/accessibility/ax_position.h
@@ -237,8 +237,8 @@ static AXPositionInstance CreateNullPosition() { AXPositionInstance new_position(new AXPositionType()); - new_position->Initialize(AXPositionKind::NULL_POSITION, AXTreeIDUnknown(), - kInvalidAXNodeID, INVALID_INDEX, INVALID_OFFSET, + new_position->Initialize(AXPositionKind::NULL_POSITION, nullptr, + INVALID_INDEX, INVALID_OFFSET, ax::mojom::TextAffinity::kDownstream); return new_position; } @@ -250,8 +250,7 @@ DCHECK_NE(anchor.id(), kInvalidAXNodeID); AXPositionInstance new_position(new AXPositionType()); - new_position->Initialize(AXPositionKind::TREE_POSITION, - anchor.tree()->GetAXTreeID(), anchor.id(), + new_position->Initialize(AXPositionKind::TREE_POSITION, &anchor, child_index, INVALID_OFFSET, ax::mojom::TextAffinity::kDownstream); return new_position; @@ -282,8 +281,7 @@ DCHECK_NE(anchor.id(), kInvalidAXNodeID); AXPositionInstance new_position(new AXPositionType()); - new_position->Initialize(AXPositionKind::TEXT_POSITION, - anchor.tree()->GetAXTreeID(), anchor.id(), + new_position->Initialize(AXPositionKind::TEXT_POSITION, &anchor, INVALID_INDEX, text_offset, affinity); return new_position; } @@ -343,12 +341,12 @@ result.kind = kind_; // A tree ID can be serialized as a 32-byte string. - std::string tree_id_string = tree_id_.ToString(); + std::string tree_id_string = GetTreeID().ToString(); DCHECK_LE(tree_id_string.size(), 32U); strncpy(result.tree_id, tree_id_string.c_str(), 32); result.tree_id[32] = 0; - result.anchor_id = anchor_id_; + result.anchor_id = GetAnchorID(); result.child_index = child_index_; result.text_offset = text_offset_; result.affinity = affinity_; @@ -381,8 +379,8 @@ } else { str_child_index = base::NumberToString(child_index_); } - str = "TreePosition tree_id=" + tree_id_.ToString() + - " anchor_id=" + base::NumberToString(anchor_id_) + + str = "TreePosition tree_id=" + GetTreeID().ToString() + + " anchor_id=" + base::NumberToString(GetAnchorID()) + " child_index=" + str_child_index; break; } @@ -393,7 +391,7 @@ } else { str_text_offset = base::NumberToString(text_offset_); } - str = "TextPosition anchor_id=" + base::NumberToString(anchor_id_) + + str = "TextPosition anchor_id=" + base::NumberToString(GetAnchorID()) + " text_offset=" + str_text_offset + " affinity=" + ui::ToString(static_cast<ax::mojom::TextAffinity>(affinity_)); break; @@ -443,10 +441,11 @@ } AXPositionKind kind() const { return kind_; } - AXTreeID tree_id() const { return tree_id_; } - AXNodeID anchor_id() const { return anchor_id_; } - AXTreeManager* GetManager() const { return AXTreeManager::FromID(tree_id()); } + // Deprecated. + // TODO(crbug.com/1362839): replace on GetTreeID()/GetAnchorID(). + AXTreeID tree_id() const { return GetTreeID(); } + AXNodeID anchor_id() const { return GetAnchorID(); } // Returns true if this position is within an "empty object", i.e. within a // node that should contribute no text to the accessibility tree's text @@ -521,15 +520,18 @@ return !node.GetChildCountCrossingTreeBoundary() || IsEmptyObject(node); } - AXNode* GetAnchor() const { - if (tree_id_ == AXTreeIDUnknown() || anchor_id_ == kInvalidAXNodeID) - return nullptr; + AXNode* GetAnchor() const { return anchor_.get(); } + AXTree* GetTree() const { return anchor_ ? anchor_->tree() : nullptr; } + AXTreeManager* GetManager() const { + return anchor_ ? anchor_->GetManager() : nullptr; + } - const AXTreeManager* manager = GetManager(); - if (manager) - return manager->GetNode(anchor_id()); - - return nullptr; + AXNodeID GetAnchorID() const { + return anchor_ ? anchor_->id() : kInvalidAXNodeID; + } + AXTreeID GetTreeID() const { + DCHECK(!anchor_ || anchor_->tree()); + return anchor_ ? anchor_->tree()->GetAXTreeID() : AXTreeIDUnknown(); } int GetAnchorSiblingCount() const { @@ -650,9 +652,7 @@ bool IsValid() const { switch (kind_) { case AXPositionKind::NULL_POSITION: - return tree_id_ == AXTreeIDUnknown() && - anchor_id_ == kInvalidAXNodeID && - child_index_ == INVALID_INDEX && + return !GetAnchor() && child_index_ == INVALID_INDEX && text_offset_ == INVALID_OFFSET && affinity_ == ax::mojom::TextAffinity::kDownstream; case AXPositionKind::TREE_POSITION: @@ -2338,7 +2338,7 @@ ->CreatePositionAtStartOfAnchor(); if (IsTextPosition()) root_position = root_position->AsTextPosition(); - DCHECK_EQ(root_position->tree_id_, tree_id_) + DCHECK_EQ(root_position->GetTree(), GetTree()) << "`CreatePositionAtStartOfAXTree` should not cross any tree " "boundaries, neither return the null position."; return root_position; @@ -4257,8 +4257,7 @@ void swap(AXPosition& other) { std::swap(kind_, other.kind_); - std::swap(tree_id_, other.tree_id_); - std::swap(anchor_id_, other.anchor_id_); + std::swap(anchor_, other.anchor_); std::swap(child_index_, other.child_index_); std::swap(text_offset_, other.text_offset_); std::swap(affinity_, other.affinity_); @@ -4401,9 +4400,7 @@ protected: AXPosition() - : kind_(AXPositionKind::NULL_POSITION), - tree_id_(AXTreeIDUnknown()), - anchor_id_(kInvalidAXNodeID), + : anchor_(nullptr), child_index_(INVALID_INDEX), text_offset_(INVALID_OFFSET), affinity_(ax::mojom::TextAffinity::kDownstream) {} @@ -4411,8 +4408,7 @@ // We explicitly don't copy any cached members. AXPosition(const AXPosition& other) : kind_(other.kind_), - tree_id_(other.tree_id_), - anchor_id_(other.anchor_id_), + anchor_(other.anchor_), child_index_(other.child_index_), text_offset_(other.text_offset_), affinity_(other.affinity_), @@ -4482,17 +4478,21 @@ int text_offset, ax::mojom::TextAffinity affinity) { kind_ = kind; - tree_id_ = tree_id; - anchor_id_ = anchor_id; child_index_ = child_index; text_offset_ = text_offset; affinity_ = affinity; + AXTreeManager* manager = AXTreeManager::FromID(tree_id); + if (manager) { + AXNode* anchor = manager->GetNode(anchor_id); + if (anchor) + anchor_ = anchor->AsWeakPtr(); + } + if (!IsValid()) { // Reset to the null position. kind_ = AXPositionKind::NULL_POSITION; - tree_id_ = AXTreeIDUnknown(); - anchor_id_ = kInvalidAXNodeID; + anchor_ = nullptr; child_index_ = INVALID_INDEX; text_offset_ = INVALID_OFFSET; affinity_ = ax::mojom::TextAffinity::kDownstream; @@ -4500,28 +4500,22 @@ } void Initialize(AXPositionKind kind, - AXTreeID tree_id, - AXNodeID anchor_id, + const AXNode* anchor, int child_index, int text_offset, ax::mojom::TextAffinity affinity) { kind_ = kind; - tree_id_ = tree_id; - anchor_id_ = anchor_id; child_index_ = child_index; text_offset_ = text_offset; affinity_ = affinity; - // TODO(accessibility) Consider using WeakPtr<AXTree> instead of an - // AXTreeID, which would be both faster and easier to use in combination - // with AXTreeSnapshotter, which does not use AXTreeManager to cache - // AXTreeIDs in a map. - SANITIZER_CHECK(GetManager() || kind_ == AXPositionKind::NULL_POSITION) - << "Tree manager required, tree_id = " << tree_id.ToString() - << " is unknown = " << (tree_id == AXTreeIDUnknown()); - SANITIZER_CHECK(GetAnchor() || kind_ == AXPositionKind::NULL_POSITION) - << "Creating a position without an anchor is disallowed:\n" - << ToDebugString(); + if (kind_ != AXPositionKind::NULL_POSITION) { + DCHECK(anchor); + SANITIZER_CHECK(anchor->GetManager()) + << "Creating a position without a tree manager is disallowed:\n" + << ToDebugString(); + anchor_ = const_cast<AXNode*>(anchor)->AsWeakPtr(); + } // TODO(accessibility) Remove this line and let the below IsValid() // assertion get triggered instead. We shouldn't be creating test positions @@ -5574,12 +5568,8 @@ return text_position; } - AXPositionKind kind_; - // TODO(crbug.com/1362839): use weak pointers for the AXTree, so that - // AXPosition can be used without AXTreeManager support (and also faster than - // the slow AXTreeID). - AXTreeID tree_id_; - AXNodeID anchor_id_; + AXPositionKind kind_ = AXPositionKind::NULL_POSITION; + base::WeakPtr<AXNode> anchor_; // For text positions, |child_index_| is initially set to |-1| and only // computed on demand. The same with tree positions and |text_offset_|.
diff --git a/ui/accessibility/platform/automation/automation_tree_manager_owner.h b/ui/accessibility/platform/automation/automation_tree_manager_owner.h index 8272d1d..0d250cd9 100644 --- a/ui/accessibility/platform/automation/automation_tree_manager_owner.h +++ b/ui/accessibility/platform/automation/automation_tree_manager_owner.h
@@ -17,12 +17,6 @@ #include "ui/gfx/geometry/point.h" #include "v8/include/v8-isolate.h" -// TODO(crbug.com/1357889): Remove this after migrating test logic to -// ui/accessibility. -namespace extensions { -class AutomationInternalCustomBindingsTest; -} - namespace ui { class AutomationV8Bindings; @@ -170,7 +164,7 @@ void SetDesktopTreeId(AXTreeID tree_id) { desktop_tree_id_ = tree_id; } protected: - friend class extensions::AutomationInternalCustomBindingsTest; + friend class AutomationTreeManagerOwnerTest; void OnAccessibilityEvents(const ui::AXTreeID& tree_id, const std::vector<AXEvent>& events,
diff --git a/ui/accessibility/platform/automation/automation_tree_manager_owner_unittest.cc b/ui/accessibility/platform/automation/automation_tree_manager_owner_unittest.cc new file mode 100644 index 0000000..17d801c --- /dev/null +++ b/ui/accessibility/platform/automation/automation_tree_manager_owner_unittest.cc
@@ -0,0 +1,891 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/accessibility/platform/automation/automation_tree_manager_owner.h" + +#include <memory> + +#include "base/test/bind.h" +#include "base/test/task_environment.h" +#include "gin/array_buffer.h" +#include "gin/public/context_holder.h" +#include "gin/public/isolate_holder.h" +#include "gin/v8_initializer.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/accessibility/ax_enum_util.h" +#include "ui/accessibility/platform/automation/automation_v8_bindings.h" +#include "ui/accessibility/platform/automation/automation_v8_router.h" +#include "v8/include/v8-context.h" +#include "v8/include/v8-template.h" + +namespace ui { + +// Tests will be run against this class which overrides +// AutomationTreeManagerOwner. +class FakeAutomationTreeManagerOwner : public AutomationTreeManagerOwner { + public: + FakeAutomationTreeManagerOwner() = default; + FakeAutomationTreeManagerOwner(const FakeAutomationTreeManagerOwner&) = + delete; + FakeAutomationTreeManagerOwner& operator=( + const FakeAutomationTreeManagerOwner&) = delete; + ~FakeAutomationTreeManagerOwner() override = default; + + // AutomationTreeManagerOwner: + AutomationV8Bindings* GetAutomationV8Bindings() const override { + return automation_v8_bindings_; + } + + void NotifyTreeEventListenersChanged() override {} + + // For testing: + void SetAutomationV8Bindings(AutomationV8Bindings* bindings) { + automation_v8_bindings_ = bindings; + } + + private: + AutomationV8Bindings* automation_v8_bindings_ = nullptr; +}; + +// A skeleton AutomationV8Router implementation for use by a test. +// Starts V8 when constructed. Does not construct a context and will +// fail the test if GetContext() is called. +class FakeAutomationV8Router : public AutomationV8Router { + public: + FakeAutomationV8Router() { + if (!gin::IsolateHolder::Initialized()) { +#ifdef V8_USE_EXTERNAL_STARTUP_DATA + gin::V8Initializer::LoadV8Snapshot(); +#endif + gin::IsolateHolder::Initialize( + gin::IsolateHolder::kNonStrictMode, + gin::ArrayBufferAllocator::SharedInstance()); + } + isolate_holder_ = std::make_unique<gin::IsolateHolder>( + base::ThreadTaskRunnerHandle::Get(), gin::IsolateHolder::kSingleThread, + gin::IsolateHolder::IsolateType::kUtility); + } + FakeAutomationV8Router(const FakeAutomationV8Router&) = delete; + FakeAutomationV8Router& operator=(const FakeAutomationV8Router&) = delete; + virtual ~FakeAutomationV8Router() = default; + + // AutomationV8Router: + void ThrowInvalidArgumentsException(bool is_fatal = true) const override {} + + v8::Isolate* GetIsolate() const override { + return isolate_holder_->isolate(); + } + + v8::Local<v8::Context> GetContext() const override { + DCHECK(context_holder_) << "V8 context was not initialized for this test."; + return context_holder_->context(); + } + + void StartCachingAccessibilityTrees() override {} + + void StopCachingAccessibilityTrees() override {} + + TreeChangeObserverFilter ParseTreeChangeObserverFilter( + const std::string& filter) const override { + return TreeChangeObserverFilter::kAllTreeChanges; + } + + std::string GetMarkerTypeString(ax::mojom::MarkerType type) const override { + return ui::ToString(type); + } + + std::string GetFocusedStateString() const override { return "focused"; } + + std::string GetOffscreenStateString() const override { return "offscreen"; } + + std::string GetLocalizedStringForImageAnnotationStatus( + ax::mojom::ImageAnnotationStatus status) const override { + return ui::ToString(status); + } + + std::string GetTreeChangeTypeString( + ax::mojom::Mutation change_type) const override { + return ui::ToString(change_type); + } + + std::string GetEventTypeString( + const std::tuple<ax::mojom::Event, AXEventGenerator::Event>& event_type) + const override { + std::string first = ui::ToString(std::get<0>(event_type)); + std::string second = ui::ToString(std::get<1>(event_type)); + return first + " " + second; + } + + void RouteHandlerFunction(const std::string& name, + scoped_refptr<V8HandlerFunctionWrapper> + handler_function_wrapper) override {} + + void DispatchEvent(const std::string& event_name, + const base::Value::List& event_args) const override { + if (!notify_event_ || + event_name != "automationInternal.onAccessibilityEvent") + return; + + const base::Value::Dict* dict = event_args[0].GetIfDict(); + DCHECK(dict); + const std::string* event_type_string = dict->FindString("eventType"); + DCHECK(event_type_string); + notify_event_.Run(*event_type_string); + } + + // For tests. + void AddEventCallback( + base::RepeatingCallback<void(const std::string&)> callback) { + notify_event_ = std::move(callback); + } + + private: + std::unique_ptr<gin::IsolateHolder> isolate_holder_; + std::unique_ptr<gin::ContextHolder> context_holder_; + base::RepeatingCallback<void(const std::string&)> notify_event_; +}; + +// Tests for AutomationTreeManagerOwner. +class AutomationTreeManagerOwnerTest : public testing::Test { + public: + AutomationTreeManagerOwnerTest() = default; + AutomationTreeManagerOwnerTest(const AutomationTreeManagerOwnerTest&) = + delete; + AutomationTreeManagerOwnerTest& operator=( + const AutomationTreeManagerOwnerTest&) = delete; + ~AutomationTreeManagerOwnerTest() override = default; + + void SetUp() override { + tree_manager_owner_ = std::make_unique<FakeAutomationTreeManagerOwner>(); + router_ = std::make_unique<FakeAutomationV8Router>(); + bindings_ = std::make_unique<AutomationV8Bindings>( + tree_manager_owner_.get(), router_.get()); + tree_manager_owner_->SetAutomationV8Bindings(bindings_.get()); + } + + protected: + std::map<ui::AXTreeID, std::unique_ptr<ui::AutomationAXTreeWrapper>>& + GetTreeIDToTreeMap() { + return tree_manager_owner_->tree_id_to_tree_wrapper_map_; + } + + void SendOnAccessibilityEvents(const ui::AXTreeID& tree_id, + const std::vector<ui::AXTreeUpdate>& updates, + const gfx::Point& mouse_location, + const std::vector<ui::AXEvent>& events) { + tree_manager_owner_->OnAccessibilityEvents(tree_id, events, updates, + mouse_location, true); + } + + bool CallGetFocusInternal(ui::AutomationAXTreeWrapper* top_wrapper, + ui::AutomationAXTreeWrapper** focused_wrapper, + ui::AXNode** focused_node) { + return tree_manager_owner_->GetFocusInternal(top_wrapper, focused_wrapper, + focused_node); + } + + gfx::Rect CallComputeGlobalNodeBounds(ui::AutomationAXTreeWrapper* wrapper, + ui::AXNode* node) { + return tree_manager_owner_->ComputeGlobalNodeBounds(wrapper, node); + } + + std::vector<ui::AXNode*> CallGetRootsOfChildTree(ui::AXNode* node) { + return tree_manager_owner_->GetRootsOfChildTree(node); + } + + void AddEventCallback( + base::RepeatingCallback<void(const std::string&)> callback) { + router_->AddEventCallback(std::move(callback)); + } + + private: + std::unique_ptr<FakeAutomationV8Router> router_; + std::unique_ptr<AutomationV8Bindings> bindings_; + std::unique_ptr<FakeAutomationTreeManagerOwner> tree_manager_owner_; + base::test::TaskEnvironment task_environment_; +}; + +TEST_F(AutomationTreeManagerOwnerTest, GetDesktop) { + EXPECT_TRUE(GetTreeIDToTreeMap().empty()); + + std::vector<ui::AXTreeUpdate> updates; + updates.emplace_back(); + auto& tree_update = updates.back(); + auto& tree_data = tree_update.tree_data; + tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + tree_update.root_id = 1; + tree_update.nodes.emplace_back(); + auto& node_data = tree_update.nodes.back(); + node_data.role = ax::mojom::Role::kDesktop; + node_data.id = 1; + std::vector<ui::AXEvent> events; + SendOnAccessibilityEvents(tree_data.tree_id, updates, gfx::Point(), events); + + ASSERT_EQ(1U, GetTreeIDToTreeMap().size()); + + ui::AutomationAXTreeWrapper* desktop = + GetTreeIDToTreeMap().begin()->second.get(); + ASSERT_TRUE(desktop); + EXPECT_TRUE(desktop->IsDesktopTree()); +} + +TEST_F(AutomationTreeManagerOwnerTest, GetFocusOneTree) { + // A desktop tree with focus on a button. + std::vector<ui::AXTreeUpdate> updates; + updates.emplace_back(); + auto& tree_update = updates.back(); + tree_update.has_tree_data = true; + tree_update.root_id = 1; + auto& tree_data = tree_update.tree_data; + tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + tree_data.focus_id = 2; + tree_update.nodes.emplace_back(); + auto& node_data1 = tree_update.nodes.back(); + node_data1.id = 1; + node_data1.role = ax::mojom::Role::kDesktop; + node_data1.child_ids.push_back(2); + tree_update.nodes.emplace_back(); + auto& node_data2 = tree_update.nodes.back(); + node_data2.id = 2; + node_data2.role = ax::mojom::Role::kButton; + std::vector<ui::AXEvent> events; + SendOnAccessibilityEvents(tree_data.tree_id, updates, gfx::Point(), events); + + ASSERT_EQ(1U, GetTreeIDToTreeMap().size()); + + ui::AutomationAXTreeWrapper* desktop = + GetTreeIDToTreeMap().begin()->second.get(); + ASSERT_TRUE(desktop); + + ui::AutomationAXTreeWrapper* focused_wrapper = nullptr; + ui::AXNode* focused_node = nullptr; + CallGetFocusInternal(desktop, &focused_wrapper, &focused_node); + ASSERT_TRUE(focused_wrapper); + ASSERT_TRUE(focused_node); + EXPECT_EQ(desktop, focused_wrapper); + EXPECT_EQ(ax::mojom::Role::kButton, focused_node->GetRole()); + + // Push an update where we change the focus. + focused_wrapper = nullptr; + focused_node = nullptr; + tree_data.focus_id = 1; + SendOnAccessibilityEvents(tree_data.tree_id, updates, gfx::Point(), events); + CallGetFocusInternal(desktop, &focused_wrapper, &focused_node); + ASSERT_TRUE(focused_wrapper); + ASSERT_TRUE(focused_node); + EXPECT_EQ(desktop, focused_wrapper); + EXPECT_EQ(ax::mojom::Role::kDesktop, focused_node->GetRole()); + + // Push an update where we change the focus to nothing. + focused_wrapper = nullptr; + focused_node = nullptr; + tree_data.focus_id = 100; + SendOnAccessibilityEvents(tree_data.tree_id, updates, gfx::Point(), events); + CallGetFocusInternal(desktop, &focused_wrapper, &focused_node); + ASSERT_FALSE(focused_wrapper); + ASSERT_FALSE(focused_node); +} + +TEST_F(AutomationTreeManagerOwnerTest, + GetFocusMultipleTreesChildTreeConstruction) { + // Three trees each with a button and link. + std::vector<std::vector<ui::AXTreeUpdate>> updates_list; + for (int i = 0; i < 3; i++) { + std::vector<ui::AXTreeUpdate>& updates = updates_list.emplace_back(); + updates.emplace_back(); + auto& tree_update = updates.back(); + tree_update.has_tree_data = true; + tree_update.root_id = 1; + auto& tree_data = tree_update.tree_data; + + // This is a point of inconsistency as the mojo representation allows + // updates from multiple trees. + tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + tree_data.focus_id = 2; + tree_update.nodes.emplace_back(); + auto& node_data1 = tree_update.nodes.back(); + node_data1.id = 1; + node_data1.role = ax::mojom::Role::kRootWebArea; + node_data1.child_ids.push_back(2); + node_data1.child_ids.push_back(3); + tree_update.nodes.emplace_back(); + auto& node_data2 = tree_update.nodes.back(); + node_data2.id = 2; + node_data2.role = ax::mojom::Role::kButton; + tree_update.nodes.emplace_back(); + auto& node_data3 = tree_update.nodes.back(); + node_data3.id = 3; + node_data3.role = ax::mojom::Role::kLink; + } + + // Link up the trees so that the first is a parent of the other two using + // child tree id. + ui::AXTreeID tree_0_id = updates_list[0][0].tree_data.tree_id; + ui::AXTreeID tree_1_id = updates_list[1][0].tree_data.tree_id; + ui::AXTreeID tree_2_id = updates_list[2][0].tree_data.tree_id; + updates_list[0][0].nodes[1].AddChildTreeId(tree_1_id); + updates_list[0][0].nodes[2].AddChildTreeId(tree_2_id); + + std::vector<ui::AXEvent> empty_events; + for (auto& updates : updates_list) { + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, + gfx::Point(), empty_events); + } + + ASSERT_EQ(3U, GetTreeIDToTreeMap().size()); + + ui::AutomationAXTreeWrapper* wrapper_0 = + GetTreeIDToTreeMap()[tree_0_id].get(); + ASSERT_TRUE(wrapper_0); + ui::AutomationAXTreeWrapper* wrapper_1 = + GetTreeIDToTreeMap()[tree_1_id].get(); + ASSERT_TRUE(wrapper_1); + ui::AutomationAXTreeWrapper* wrapper_2 = + GetTreeIDToTreeMap()[tree_2_id].get(); + ASSERT_TRUE(wrapper_2); + + ui::AutomationAXTreeWrapper* focused_wrapper = nullptr; + ui::AXNode* focused_node = nullptr; + CallGetFocusInternal(wrapper_0, &focused_wrapper, &focused_node); + ASSERT_TRUE(focused_wrapper); + ASSERT_TRUE(focused_node); + EXPECT_EQ(wrapper_1, focused_wrapper); + EXPECT_EQ(tree_1_id, focused_node->tree()->GetAXTreeID()); + EXPECT_EQ(ax::mojom::Role::kButton, focused_node->GetRole()); + + // Push an update where we change the focus. + focused_wrapper = nullptr; + focused_node = nullptr; + + // The link in wrapper 0 which has a child tree id pointing to wrapper 2. + updates_list[0][0].tree_data.focus_id = 3; + SendOnAccessibilityEvents(updates_list[0][0].tree_data.tree_id, + updates_list[0], gfx::Point(), empty_events); + CallGetFocusInternal(wrapper_0, &focused_wrapper, &focused_node); + ASSERT_TRUE(focused_wrapper); + ASSERT_TRUE(focused_node); + EXPECT_EQ(wrapper_2, focused_wrapper); + EXPECT_EQ(tree_2_id, focused_node->tree()->GetAXTreeID()); + EXPECT_EQ(ax::mojom::Role::kButton, focused_node->GetRole()); +} + +TEST_F(AutomationTreeManagerOwnerTest, GetFocusMultipleTreesAppIdConstruction) { + // Three trees each with a button and link. + std::vector<std::vector<ui::AXTreeUpdate>> updates_list; + for (int i = 0; i < 3; i++) { + std::vector<ui::AXTreeUpdate>& updates = updates_list.emplace_back(); + updates.emplace_back(); + auto& tree_update = updates.back(); + tree_update.has_tree_data = true; + tree_update.root_id = 1; + auto& tree_data = tree_update.tree_data; + + // This is a point of inconsistency as the mojo representation allows + // updates from ultiple trees. + tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + tree_data.focus_id = 2; + tree_update.nodes.emplace_back(); + auto& node_data1 = tree_update.nodes.back(); + node_data1.id = 1; + node_data1.role = ax::mojom::Role::kRootWebArea; + node_data1.child_ids.push_back(2); + node_data1.child_ids.push_back(3); + tree_update.nodes.emplace_back(); + auto& node_data2 = tree_update.nodes.back(); + node_data2.id = 2; + node_data2.role = ax::mojom::Role::kButton; + tree_update.nodes.emplace_back(); + auto& node_data3 = tree_update.nodes.back(); + node_data3.id = 3; + node_data3.role = ax::mojom::Role::kLink; + } + + // Link up the trees so that the first is a parent of the other two using app + // ids. + ui::AXTreeID tree_0_id = updates_list[0][0].tree_data.tree_id; + ui::AXTreeID tree_1_id = updates_list[1][0].tree_data.tree_id; + ui::AXTreeID tree_2_id = updates_list[2][0].tree_data.tree_id; + auto& wrapper0_button_data = updates_list[0][0].nodes[1]; + auto& wrapper0_link_data = updates_list[0][0].nodes[2]; + auto& wrapper1_link_data = updates_list[1][0].nodes[2]; + auto& wrapper2_button_data = updates_list[2][0].nodes[1]; + + // This construction requires the hosting and client nodes annotate with the + // same app id. + wrapper0_button_data.AddStringAttribute( + ax::mojom::StringAttribute::kChildTreeNodeAppId, "app1"); + wrapper1_link_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, + "app1"); + wrapper0_link_data.AddStringAttribute( + ax::mojom::StringAttribute::kChildTreeNodeAppId, "app2"); + wrapper2_button_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, + "app2"); + + std::vector<ui::AXEvent> empty_events; + for (auto& updates : updates_list) { + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, + gfx::Point(), empty_events); + } + + ASSERT_EQ(3U, GetTreeIDToTreeMap().size()); + + ui::AutomationAXTreeWrapper* wrapper_0 = + GetTreeIDToTreeMap()[tree_0_id].get(); + ASSERT_TRUE(wrapper_0); + ui::AutomationAXTreeWrapper* wrapper_1 = + GetTreeIDToTreeMap()[tree_1_id].get(); + ASSERT_TRUE(wrapper_1); + ui::AutomationAXTreeWrapper* wrapper_2 = + GetTreeIDToTreeMap()[tree_2_id].get(); + ASSERT_TRUE(wrapper_2); + + ui::AutomationAXTreeWrapper* focused_wrapper = nullptr; + ui::AXNode* focused_node = nullptr; + CallGetFocusInternal(wrapper_0, &focused_wrapper, &focused_node); + ASSERT_TRUE(focused_wrapper); + ASSERT_TRUE(focused_node); + EXPECT_EQ(wrapper_1, focused_wrapper); + EXPECT_EQ(tree_1_id, focused_node->tree()->GetAXTreeID()); + + // This is an interesting inconsistency as this node is technically not in the + // app (which starts at the link in wrapper 1). + EXPECT_EQ(ax::mojom::Role::kButton, focused_node->GetRole()); + + // Push an update where we change the focus. + focused_wrapper = nullptr; + focused_node = nullptr; + + // The link in wrapper 0 which has a child tree id pointing to wrapper 2. + updates_list[0][0].tree_data.focus_id = 3; + SendOnAccessibilityEvents(updates_list[0][0].tree_data.tree_id, + updates_list[0], gfx::Point(), empty_events); + CallGetFocusInternal(wrapper_0, &focused_wrapper, &focused_node); + ASSERT_TRUE(focused_wrapper); + ASSERT_TRUE(focused_node); + EXPECT_EQ(wrapper_2, focused_wrapper); + EXPECT_EQ(tree_2_id, focused_node->tree()->GetAXTreeID()); + EXPECT_EQ(ax::mojom::Role::kButton, focused_node->GetRole()); +} + +TEST_F(AutomationTreeManagerOwnerTest, GetBoundsAppIdConstruction) { + // two trees each with a button. + std::vector<std::vector<ui::AXTreeUpdate>> updates_list; + for (int i = 0; i < 2; i++) { + std::vector<ui::AXTreeUpdate>& updates = updates_list.emplace_back(); + updates.emplace_back(); + auto& tree_update = updates.back(); + tree_update.has_tree_data = true; + tree_update.root_id = 1; + auto& tree_data = tree_update.tree_data; + tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + tree_update.nodes.emplace_back(); + auto& node_data1 = tree_update.nodes.back(); + node_data1.id = 1; + node_data1.role = + i == 0 ? ax::mojom::Role::kDesktop : ax::mojom::Role::kRootWebArea; + node_data1.child_ids.push_back(2); + node_data1.relative_bounds.bounds = gfx::RectF(100, 100, 100, 100); + tree_update.nodes.emplace_back(); + auto& node_data2 = tree_update.nodes.back(); + node_data2.id = 2; + node_data2.role = ax::mojom::Role::kButton; + node_data2.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); + } + + // Link up the trees by app id. + ui::AXTreeID tree_0_id = updates_list[0][0].tree_data.tree_id; + ui::AXTreeID tree_1_id = updates_list[1][0].tree_data.tree_id; + auto& wrapper0_button_data = updates_list[0][0].nodes[1]; + auto& wrapper1_button_data = updates_list[1][0].nodes[1]; + + // This construction requires the hosting and client nodes annotate with the + // same app id. + wrapper0_button_data.AddStringAttribute( + ax::mojom::StringAttribute::kChildTreeNodeAppId, "app1"); + wrapper1_button_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, + "app1"); + + wrapper0_button_data.AddFloatAttribute( + ax::mojom::FloatAttribute::kChildTreeScale, 2.0); + + std::vector<ui::AXEvent> empty_events; + for (auto& updates : updates_list) { + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, + gfx::Point(), empty_events); + } + + ASSERT_EQ(2U, GetTreeIDToTreeMap().size()); + + ui::AutomationAXTreeWrapper* wrapper_0 = + GetTreeIDToTreeMap()[tree_0_id].get(); + ASSERT_TRUE(wrapper_0); + ui::AutomationAXTreeWrapper* wrapper_1 = + GetTreeIDToTreeMap()[tree_1_id].get(); + ASSERT_TRUE(wrapper_1); + + ui::AXNode* wrapper1_button = wrapper_1->ax_tree()->GetFromId(2); + ASSERT_TRUE(wrapper1_button); + + // The button in wrapper 1 is scaled by .5 (200 * .5). It's root is also + // scaled (100 * .5). In wrapper 0, it is *not* offset by the tree's root + // bounds. + EXPECT_EQ(gfx::Rect(50, 50, 100, 100), + CallComputeGlobalNodeBounds(wrapper_1, wrapper1_button)); +} + +TEST_F(AutomationTreeManagerOwnerTest, GetBoundsNestedAppIdConstruction) { + // two trees each with a button and a client node. + std::vector<std::vector<ui::AXTreeUpdate>> updates_list; + for (int i = 0; i < 2; i++) { + std::vector<ui::AXTreeUpdate>& updates = updates_list.emplace_back(); + updates.emplace_back(); + auto& tree_update = updates.back(); + tree_update.has_tree_data = true; + tree_update.root_id = 1; + auto& tree_data = tree_update.tree_data; + tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + tree_update.nodes.emplace_back(); + auto& node_data1 = tree_update.nodes.back(); + node_data1.id = 1; + node_data1.role = + i == 0 ? ax::mojom::Role::kDesktop : ax::mojom::Role::kRootWebArea; + node_data1.child_ids.push_back(2); + node_data1.child_ids.push_back(3); + node_data1.relative_bounds.bounds = gfx::RectF(100, 100, 100, 100); + tree_update.nodes.emplace_back(); + auto& node_data2 = tree_update.nodes.back(); + node_data2.id = 2; + node_data2.role = ax::mojom::Role::kButton; + node_data2.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); + tree_update.nodes.emplace_back(); + auto& node_data3 = tree_update.nodes.back(); + node_data3.id = 3; + node_data3.role = ax::mojom::Role::kClient; + node_data3.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); + } + + // Link up the trees by app id. One button -> child button; client -> child + // root. + ui::AXTreeID tree_0_id = updates_list[0][0].tree_data.tree_id; + ui::AXTreeID tree_1_id = updates_list[1][0].tree_data.tree_id; + auto& wrapper0_button_data = updates_list[0][0].nodes[1]; + auto& wrapper0_client_data = updates_list[0][0].nodes[2]; + auto& wrapper1_root_data = updates_list[1][0].nodes[0]; + auto& wrapper1_button_data = updates_list[1][0].nodes[1]; + + // This construction requires the hosting and client nodes annotate with the + // same app id. + wrapper0_button_data.AddStringAttribute( + ax::mojom::StringAttribute::kChildTreeNodeAppId, "app1"); + wrapper1_button_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, + "app1"); + + wrapper0_button_data.AddFloatAttribute( + ax::mojom::FloatAttribute::kChildTreeScale, 2.0); + + // Adding this app id should not impact the above bounds computation. + wrapper0_client_data.AddStringAttribute( + ax::mojom::StringAttribute::kChildTreeNodeAppId, "lacrosHost"); + wrapper1_root_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, + "lacrosHost"); + + std::vector<ui::AXEvent> empty_events; + for (auto& updates : updates_list) { + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, + gfx::Point(), empty_events); + } + + ASSERT_EQ(2U, GetTreeIDToTreeMap().size()); + + ui::AutomationAXTreeWrapper* wrapper_0 = + GetTreeIDToTreeMap()[tree_0_id].get(); + ASSERT_TRUE(wrapper_0); + ui::AutomationAXTreeWrapper* wrapper_1 = + GetTreeIDToTreeMap()[tree_1_id].get(); + ASSERT_TRUE(wrapper_1); + + ui::AXNode* wrapper1_button = wrapper_1->ax_tree()->GetFromId(2); + ASSERT_TRUE(wrapper1_button); + + // The button in wrapper 1 is scaled by .5 (200 * .5). It's root is also + // scaled (100 * .5). In wrapper 0, it is *not* offset by the tree's root + // bounds. + EXPECT_EQ(gfx::Rect(50, 50, 100, 100), + CallComputeGlobalNodeBounds(wrapper_1, wrapper1_button)); + + ui::AXNode* wrapper1_root = wrapper_1->ax_tree()->GetFromId(1); + ASSERT_TRUE(wrapper1_root); + + // Similar to the button, but not scaled. This does not cross an app id + // boundary, so is also offset by the parent tree's root (100 + 100). + EXPECT_EQ(gfx::Rect(200, 200, 100, 100), + CallComputeGlobalNodeBounds(wrapper_1, wrapper1_root)); +} + +TEST_F(AutomationTreeManagerOwnerTest, IgnoredAncestorTrees) { + // Three trees each with a button and link. + std::vector<std::vector<ui::AXTreeUpdate>> updates_list; + for (int i = 0; i < 3; i++) { + std::vector<ui::AXTreeUpdate>& updates = updates_list.emplace_back(); + updates.emplace_back(); + auto& tree_update = updates.back(); + tree_update.has_tree_data = true; + tree_update.root_id = 1; + auto& tree_data = tree_update.tree_data; + + // This is a point of inconsistency as the mojo representation allows + // updates from multiple trees. + tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + tree_data.focus_id = 2; + tree_update.nodes.emplace_back(); + auto& node_data1 = tree_update.nodes.back(); + node_data1.id = 1; + node_data1.role = ax::mojom::Role::kRootWebArea; + node_data1.child_ids.push_back(2); + node_data1.child_ids.push_back(3); + tree_update.nodes.emplace_back(); + auto& node_data2 = tree_update.nodes.back(); + node_data2.id = 2; + node_data2.role = ax::mojom::Role::kButton; + tree_update.nodes.emplace_back(); + auto& node_data3 = tree_update.nodes.back(); + node_data3.id = 3; + node_data3.role = ax::mojom::Role::kLink; + } + + // Link up the trees so that the first is a parent of the second and the + // second a parent of the third. + ui::AXTreeID tree_0_id = updates_list[0][0].tree_data.tree_id; + ui::AXTreeID tree_1_id = updates_list[1][0].tree_data.tree_id; + ui::AXTreeID tree_2_id = updates_list[2][0].tree_data.tree_id; + updates_list[0][0].nodes[1].AddChildTreeId(tree_1_id); + + // Make the hosting node ignored. + updates_list[0][0].nodes[1].AddState(ax::mojom::State::kInvisible); + + updates_list[1][0].nodes[1].AddChildTreeId(tree_2_id); + + std::vector<ui::AXEvent> empty_events; + for (auto& updates : updates_list) { + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, + gfx::Point(), empty_events); + } + + ASSERT_EQ(3U, GetTreeIDToTreeMap().size()); + + ui::AutomationAXTreeWrapper* wrapper_0 = + GetTreeIDToTreeMap()[tree_0_id].get(); + ASSERT_TRUE(wrapper_0); + ui::AutomationAXTreeWrapper* wrapper_1 = + GetTreeIDToTreeMap()[tree_1_id].get(); + ASSERT_TRUE(wrapper_1); + ui::AutomationAXTreeWrapper* wrapper_2 = + GetTreeIDToTreeMap()[tree_2_id].get(); + ASSERT_TRUE(wrapper_2); + + // The root tree isn't ignored. + EXPECT_FALSE(wrapper_0->IsTreeIgnored()); + + // However, since the hosting node in |wrapper_0| is ignored, both of the + // descendant trees should be ignored. + EXPECT_TRUE(wrapper_1->IsTreeIgnored()); + EXPECT_TRUE(wrapper_2->IsTreeIgnored()); + + // No longer invisible. + ui::AXNode* button = wrapper_0->ax_tree()->GetFromId(2); + ui::AXNodeData data = button->TakeData(); + data.RemoveState(ax::mojom::State::kInvisible); + button->SetData(data); + + EXPECT_FALSE(wrapper_0->IsTreeIgnored()); + EXPECT_FALSE(wrapper_1->IsTreeIgnored()); + EXPECT_FALSE(wrapper_2->IsTreeIgnored()); +} + +TEST_F(AutomationTreeManagerOwnerTest, GetMultipleChildRootsAppIdConstruction) { + // Two trees each with a button and a client node. + std::vector<std::vector<ui::AXTreeUpdate>> updates_list; + for (int i = 0; i < 2; i++) { + std::vector<ui::AXTreeUpdate>& updates = updates_list.emplace_back(); + updates.emplace_back(); + auto& tree_update = updates.back(); + tree_update.has_tree_data = true; + tree_update.root_id = 1; + auto& tree_data = tree_update.tree_data; + tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + tree_update.nodes.emplace_back(); + auto& node_data1 = tree_update.nodes.back(); + node_data1.id = 1; + node_data1.role = + i == 0 ? ax::mojom::Role::kDesktop : ax::mojom::Role::kRootWebArea; + node_data1.child_ids.push_back(2); + node_data1.child_ids.push_back(3); + node_data1.relative_bounds.bounds = gfx::RectF(100, 100, 100, 100); + tree_update.nodes.emplace_back(); + auto& node_data2 = tree_update.nodes.back(); + node_data2.id = 2; + node_data2.role = ax::mojom::Role::kButton; + node_data2.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); + tree_update.nodes.emplace_back(); + auto& node_data3 = tree_update.nodes.back(); + node_data3.id = 3; + node_data3.role = ax::mojom::Role::kClient; + node_data3.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); + } + + // Link up the trees by using one app id. Tree 0's client has two children + // from tree 1. + ui::AXTreeID tree_0_id = updates_list[0][0].tree_data.tree_id; + ui::AXTreeID tree_1_id = updates_list[1][0].tree_data.tree_id; + auto& wrapper0_client_data = updates_list[0][0].nodes[2]; + auto& wrapper1_button_data = updates_list[1][0].nodes[1]; + auto& wrapper1_client_data = updates_list[1][0].nodes[2]; + + // This construction requires the hosting and client nodes annotate with the + // same app id. + wrapper0_client_data.AddStringAttribute( + ax::mojom::StringAttribute::kChildTreeNodeAppId, "app1"); + wrapper1_button_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, + "app1"); + wrapper1_client_data.AddStringAttribute(ax::mojom::StringAttribute::kAppId, + "app1"); + + std::vector<ui::AXEvent> empty_events; + for (auto& updates : updates_list) { + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, + gfx::Point(), empty_events); + } + + ASSERT_EQ(2U, GetTreeIDToTreeMap().size()); + + ui::AutomationAXTreeWrapper* wrapper_0 = + GetTreeIDToTreeMap()[tree_0_id].get(); + ASSERT_TRUE(wrapper_0); + + ui::AXNode* wrapper0_client = wrapper_0->ax_tree()->GetFromId(3); + ASSERT_TRUE(wrapper0_client); + + std::vector<ui::AXNode*> child_roots = + CallGetRootsOfChildTree(wrapper0_client); + EXPECT_EQ(2U, child_roots.size()); + EXPECT_EQ(tree_1_id, child_roots[0]->tree()->GetAXTreeID()); + EXPECT_EQ(tree_1_id, child_roots[1]->tree()->GetAXTreeID()); + EXPECT_EQ(2, child_roots[0]->id()); + EXPECT_EQ(3, child_roots[1]->id()); +} + +TEST_F(AutomationTreeManagerOwnerTest, FireEventsWithListeners) { + // A simple tree. + std::vector<ui::AXTreeUpdate> updates; + updates.emplace_back(); + auto& tree_update = updates.back(); + tree_update.has_tree_data = true; + tree_update.root_id = 1; + auto& tree_data = tree_update.tree_data; + tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + tree_update.nodes.emplace_back(); + auto& node_data1 = tree_update.nodes.back(); + node_data1.id = 1; + node_data1.role = ax::mojom::Role::kRootWebArea; + node_data1.child_ids.push_back(2); + node_data1.relative_bounds.bounds = gfx::RectF(100, 100, 100, 100); + tree_update.nodes.emplace_back(); + auto& node_data2 = tree_update.nodes.back(); + node_data2.id = 2; + node_data2.role = ax::mojom::Role::kButton; + node_data2.relative_bounds.bounds = gfx::RectF(0, 0, 200, 200); + + // Add a hook for events from automation. + // Event names are the concatenation of the ax::mojom::Event string and the + // generated event string. + std::vector<std::string> events; + AddEventCallback(base::BindLambdaForTesting( + [&](const std::string& event) { events.push_back(event); })); + + std::vector<ui::AXEvent> ax_events; + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, gfx::Point(), + ax_events); + + // We aren't listening for any events yet, but we should still get one that + // gets fired on initial tree creation. + ASSERT_EQ(1U, events.size()); + EXPECT_EQ("none none", events[0]); + events.clear(); + + // Remove the root node data and don't update tree data. + tree_update.nodes.erase(tree_update.nodes.begin()); + tree_update.has_tree_data = false; + + // Trigger a role change. + tree_update.nodes[0].role = ax::mojom::Role::kSwitch; + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, gfx::Point(), + ax_events); + + // There should be no events since there are no listeners and this isn't the + // initial tree. + ASSERT_TRUE(events.empty()); + + // Add a role change listener and do trigger the role change again. + auto* wrapper = GetTreeIDToTreeMap()[tree_data.tree_id].get(); + auto* tree = wrapper->ax_tree(); + // The button is id 2. + std::tuple<ax::mojom::Event, ui::AXEventGenerator::Event> event_type( + ax::mojom::Event::kNone, ui::AXEventGenerator::Event::ROLE_CHANGED); + wrapper->EventListenerAdded(event_type, tree->GetFromId(2)); + EXPECT_EQ(1U, wrapper->EventListenerCount()); + EXPECT_TRUE(wrapper->HasEventListener(event_type, tree->GetFromId(2))); + tree_update.nodes[0].role = ax::mojom::Role::kButton; + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, gfx::Point(), + ax_events); + + // We should now have exactly one event. + ASSERT_EQ(1U, events.size()); + EXPECT_EQ("none roleChanged", events[0]); + events.clear(); + + // Now, remove the listener and do the same as above. + wrapper->EventListenerRemoved(event_type, tree->GetFromId(2)); + // We have to add another listener to ensure we don't shut down (no event + // listeners means this renderer closes). + wrapper->EventListenerAdded( + std::tuple<ax::mojom::Event, ui::AXEventGenerator::Event>( + ax::mojom::Event::kLoadComplete, ui::AXEventGenerator::Event::NONE), + tree->GetFromId(1)); + tree_update.nodes[0].role = ax::mojom::Role::kSwitch; + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, gfx::Point(), + ax_events); + + // We should have no events. + ASSERT_TRUE(events.empty()); + + // Finally, let's fire a non-generated event on the button, but add the + // listener on the root. This will test both non-generated events and + // respecting event listeners on ancestors of the target. + + // First, fire the event without the click listener. + tree_update.nodes.clear(); + ax_events.emplace_back(); + auto& event = ax_events.back(); + event.event_type = ax::mojom::Event::kClicked; + event.id = 2; + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, gfx::Point(), + ax_events); + + // No event. + ASSERT_TRUE(events.empty()); + + // Now, add the click listener to the root, and fire the click event on the + // button. + wrapper->EventListenerAdded( + std::tuple<ax::mojom::Event, ui::AXEventGenerator::Event>( + ax::mojom::Event::kClicked, ui::AXEventGenerator::Event::NONE), + tree->GetFromId(1)); + SendOnAccessibilityEvents(updates[0].tree_data.tree_id, updates, gfx::Point(), + ax_events); + + ASSERT_EQ(1U, events.size()); + EXPECT_EQ("clicked none", events[0]); +} + +} // namespace ui
diff --git a/ui/accessibility/platform/ax_platform_node_cocoa.mm b/ui/accessibility/platform/ax_platform_node_cocoa.mm index 491e45ea..11bbc9e2 100644 --- a/ui/accessibility/platform/ax_platform_node_cocoa.mm +++ b/ui/accessibility/platform/ax_platform_node_cocoa.mm
@@ -198,6 +198,20 @@ return [NSStringFromSelector(selector) hasPrefix:@"setAccessibility"]; } +void CollectAncestorRoles( + const ui::AXNode& node, + std::map<ui::AXNodeID, std::set<ax::mojom::Role>>& out_ancestor_roles) { + if (out_ancestor_roles.contains(node.id())) + return; + out_ancestor_roles[node.id()] = {node.GetRole()}; + if (!node.GetParent()) + return; + CollectAncestorRoles(*node.GetParent(), out_ancestor_roles); + out_ancestor_roles[node.id()].insert( + out_ancestor_roles[node.GetParent()->id()].begin(), + out_ancestor_roles[node.GetParent()->id()].end()); +} + } // namespace @interface AXPlatformNodeCocoa (Private) @@ -711,20 +725,22 @@ return has_image_semantics; } -- (void)addMisspelledTextAttributes:(const AXRange&)axRange - toString: - (NSMutableAttributedString*)attributedString { +- (void)addTextAnnotationsIn:(const AXRange*)axRange + to:(NSMutableAttributedString*)attributedString { int anchorStartOffset = 0; + std::map<ui::AXNodeID, std::set<ax::mojom::Role>> ancestor_roles; + [attributedString beginEditing]; - for (const AXRange& leafTextRange : axRange) { + for (const AXRange& leafTextRange : *axRange) { DCHECK(!leafTextRange.IsNull()); DCHECK_EQ(leafTextRange.anchor()->GetAnchor(), leafTextRange.focus()->GetAnchor()) << "An anchor range should only span a single object."; ui::AXNode* anchor = leafTextRange.focus()->GetAnchor(); - DCHECK(anchor) << "A non-null position should have a non-null anchor node."; + + // Add misspelling information const std::vector<int32_t>& markerTypes = anchor->GetIntListAttribute(ax::mojom::IntListAttribute::kMarkerTypes); const std::vector<int>& markerStarts = @@ -753,7 +769,36 @@ range:NSMakeRange(misspellingStart, misspellingLength)]; } - anchorStartOffset += leafTextRange.GetText().length(); + // Add annotation information + int leafTextLength = leafTextRange.GetText().length(); + DCHECK_LE(static_cast<unsigned long>(anchorStartOffset + leafTextLength), + [attributedString length]); + NSRange leafRange = NSMakeRange(anchorStartOffset, leafTextLength); + + CollectAncestorRoles(*anchor, ancestor_roles); + + if (ancestor_roles[anchor->id()].contains(ax::mojom::Role::kMark)) { + [attributedString addAttribute:@"AXHighlight" value:@YES range:leafRange]; + } + if (ancestor_roles[anchor->id()].contains(ax::mojom::Role::kSuggestion)) { + [attributedString addAttribute:@"AXIsSuggestion" + value:@YES + range:leafRange]; + } + if (ancestor_roles[anchor->id()].contains( + ax::mojom::Role::kContentDeletion)) { + [attributedString addAttribute:@"AXIsSuggestedDeletion" + value:@YES + range:leafRange]; + } + if (ancestor_roles[anchor->id()].contains( + ax::mojom::Role::kContentInsertion)) { + [attributedString addAttribute:@"AXIsSuggestedInsertion" + value:@YES + range:leafRange]; + } + + anchorStartOffset += leafTextLength; } [attributedString endEditing]; } @@ -1845,7 +1890,7 @@ AXRange axRange(_node->GetDelegate()->CreateTextPositionAt(0), _node->GetDelegate()->CreateTextPositionAt( static_cast<int>(textContent.length()))); - [self addMisspelledTextAttributes:axRange toString:attributedTextContent]; + [self addTextAnnotationsIn:&axRange to:attributedTextContent]; } return [attributedTextContent attributedSubstringFromRange:range]; @@ -1863,8 +1908,8 @@ NSMutableAttributedString* attributedText = [[[NSMutableAttributedString alloc] initWithString:text] autorelease]; // Currently, we only decorate the attributed string with misspelling - // information. - [self addMisspelledTextAttributes:axRange toString:attributedText]; + // and annotation information. + [self addTextAnnotationsIn:&axRange to:attributedText]; return attributedText; }
diff --git a/ui/accessibility/platform/inspect/ax_inspect_utils.cc b/ui/accessibility/platform/inspect/ax_inspect_utils.cc index e0a064d..f0b56de 100644 --- a/ui/accessibility/platform/inspect/ax_inspect_utils.cc +++ b/ui/accessibility/platform/inspect/ax_inspect_utils.cc
@@ -54,7 +54,7 @@ // List: exposed as [value1, ..., valueN]; if (value.is_list()) { std::string output; - for (const auto& item : value.GetListDeprecated()) { + for (const auto& item : value.GetList()) { if (!output.empty()) { output += ", "; } @@ -70,7 +70,7 @@ const std::string orderedkey_prefix(kOrderedKeyPrefixDictAttr); std::string output; - for (auto item : value.DictItems()) { + for (auto item : value.GetDict()) { if (!output.empty()) { output += ", "; }
diff --git a/ui/accessibility/platform/inspect/ax_inspect_utils_unittest.cc b/ui/accessibility/platform/inspect/ax_inspect_utils_unittest.cc index 7367d10..e3e25f36 100644 --- a/ui/accessibility/platform/inspect/ax_inspect_utils_unittest.cc +++ b/ui/accessibility/platform/inspect/ax_inspect_utils_unittest.cc
@@ -32,34 +32,37 @@ } TEST(AXInspectUtilsTest, FormatList) { - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append("item1"); list.Append("item2"); - EXPECT_EQ(AXFormatValue(list), std::string("['item1', 'item2']")); + EXPECT_EQ(AXFormatValue(base::Value(std::move(list))), + std::string("['item1', 'item2']")); } TEST(AXInspectUtilsTest, FormatDict) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringPath("anchor", AXMakeConst("textbox")); - dict.SetIntPath("offset", 2); - dict.SetStringPath("affinity", AXMakeConst("down")); - EXPECT_EQ(AXFormatValue(dict), + base::Value::Dict dict; + dict.Set("anchor", AXMakeConst("textbox")); + dict.Set("offset", 2); + dict.Set("affinity", AXMakeConst("down")); + EXPECT_EQ(AXFormatValue(base::Value(std::move(dict))), std::string("{affinity: down, anchor: textbox, offset: 2}")); } TEST(AXInspectUtilsTest, FormatSet) { - base::Value set(base::Value::Type::DICTIONARY); - set.SetStringPath(AXMakeSetKey("index1_anchor"), AXMakeConst(":1")); - set.SetIntPath(AXMakeSetKey("index2_offset"), 2); - set.SetStringPath(AXMakeSetKey("index3_affinity"), AXMakeConst("down")); - EXPECT_EQ(AXFormatValue(set), std::string("{:1, 2, down}")); + base::Value::Dict set; + set.Set(AXMakeSetKey("index1_anchor"), AXMakeConst(":1")); + set.Set(AXMakeSetKey("index2_offset"), 2); + set.Set(AXMakeSetKey("index3_affinity"), AXMakeConst("down")); + EXPECT_EQ(AXFormatValue(base::Value(std::move(set))), + std::string("{:1, 2, down}")); } TEST(AXInspectUtilsTest, FormatOrderedDict) { - base::Value ordered_dict(base::Value::Type::DICTIONARY); - ordered_dict.SetIntPath(AXMakeOrderedKey("w", 0), 40); - ordered_dict.SetIntPath(AXMakeOrderedKey("h", 1), 30); - EXPECT_EQ(AXFormatValue(ordered_dict), std::string("{w: 40, h: 30}")); + base::Value::Dict ordered_dict; + ordered_dict.Set(AXMakeOrderedKey("w", 0), 40); + ordered_dict.Set(AXMakeOrderedKey("h", 1), 30); + EXPECT_EQ(AXFormatValue(base::Value(std::move(ordered_dict))), + std::string("{w: 40, h: 30}")); } } // namespace ui
diff --git a/ui/base/resource/data_pack.cc b/ui/base/resource/data_pack.cc index 12e5483..74069c9 100644 --- a/ui/base/resource/data_pack.cc +++ b/ui/base/resource/data_pack.cc
@@ -5,8 +5,11 @@ #include "ui/base/resource/data_pack.h" #include <errno.h> + #include <algorithm> +#include <memory> #include <set> +#include <string> #include <utility> #include "base/command_line.h"
diff --git a/ui/base/resource/data_pack_unittest.cc b/ui/base/resource/data_pack_unittest.cc index f706e834..25b33b8 100644 --- a/ui/base/resource/data_pack_unittest.cc +++ b/ui/base/resource/data_pack_unittest.cc
@@ -7,6 +7,8 @@ #include <stddef.h> #include <stdint.h> +#include <map> +#include <string> #include <utility> #include "base/files/file.h"
diff --git a/ui/base/resource/data_pack_with_resource_sharing_lacros.cc b/ui/base/resource/data_pack_with_resource_sharing_lacros.cc index 0455212..3827d38 100644 --- a/ui/base/resource/data_pack_with_resource_sharing_lacros.cc +++ b/ui/base/resource/data_pack_with_resource_sharing_lacros.cc
@@ -5,8 +5,11 @@ #include "ui/base/resource/data_pack_with_resource_sharing_lacros.h" #include <algorithm> +#include <map> +#include <memory> #include <unordered_map> #include <utility> +#include <vector> #include "base/bind.h" #include "base/command_line.h"
diff --git a/ui/base/resource/data_pack_with_resource_sharing_lacros.h b/ui/base/resource/data_pack_with_resource_sharing_lacros.h index ecd40a4..ffd4586 100644 --- a/ui/base/resource/data_pack_with_resource_sharing_lacros.h +++ b/ui/base/resource/data_pack_with_resource_sharing_lacros.h
@@ -5,6 +5,8 @@ #ifndef UI_BASE_RESOURCE_DATA_PACK_WITH_RESOURCE_SHARING_LACROS_H_ #define UI_BASE_RESOURCE_DATA_PACK_WITH_RESOURCE_SHARING_LACROS_H_ +#include <map> +#include <memory> #include <vector> #include "base/files/file_path.h"
diff --git a/ui/base/resource/data_pack_with_resource_sharing_lacros_unittest.cc b/ui/base/resource/data_pack_with_resource_sharing_lacros_unittest.cc index a60f236d..2302ec5 100644 --- a/ui/base/resource/data_pack_with_resource_sharing_lacros_unittest.cc +++ b/ui/base/resource/data_pack_with_resource_sharing_lacros_unittest.cc
@@ -7,6 +7,7 @@ #include <filesystem> #include <map> #include <string> +#include <utility> #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h"
diff --git a/ui/base/resource/mock_resource_bundle_delegate.h b/ui/base/resource/mock_resource_bundle_delegate.h index ff9fb7dc1..da582028 100644 --- a/ui/base/resource/mock_resource_bundle_delegate.h +++ b/ui/base/resource/mock_resource_bundle_delegate.h
@@ -5,6 +5,8 @@ #ifndef UI_BASE_RESOURCE_MOCK_RESOURCE_BUNDLE_DELEGATE_H_ #define UI_BASE_RESOURCE_MOCK_RESOURCE_BUNDLE_DELEGATE_H_ +#include <string> + #include "testing/gmock/include/gmock/gmock.h" #include "ui/base/resource/resource_bundle.h"
diff --git a/ui/base/resource/resource_bundle.cc b/ui/base/resource/resource_bundle.cc index d5d08750..a013ab3 100644 --- a/ui/base/resource/resource_bundle.cc +++ b/ui/base/resource/resource_bundle.cc
@@ -6,7 +6,8 @@ #include <stdint.h> -#include <limits> +#include <string> +#include <tuple> #include <utility> #include <vector>
diff --git a/ui/base/resource/resource_bundle_android.cc b/ui/base/resource/resource_bundle_android.cc index 582326e..0d41e91 100644 --- a/ui/base/resource/resource_bundle_android.cc +++ b/ui/base/resource/resource_bundle_android.cc
@@ -4,6 +4,8 @@ #include "ui/base/resource/resource_bundle_android.h" +#include <memory> +#include <string> #include <utility> #include "base/android/apk_assets.h"
diff --git a/ui/base/resource/resource_bundle_lacros.cc b/ui/base/resource/resource_bundle_lacros.cc index b932dc5..eb19633e 100644 --- a/ui/base/resource/resource_bundle_lacros.cc +++ b/ui/base/resource/resource_bundle_lacros.cc
@@ -4,6 +4,10 @@ #include "ui/base/resource/resource_bundle.h" +#include <memory> +#include <string> +#include <utility> + #include "base/command_line.h" #include "base/files/file_util.h" #include "base/logging.h"
diff --git a/ui/base/resource/resource_bundle_unittest.cc b/ui/base/resource/resource_bundle_unittest.cc index 555ce0d..16d168a 100644 --- a/ui/base/resource/resource_bundle_unittest.cc +++ b/ui/base/resource/resource_bundle_unittest.cc
@@ -6,9 +6,11 @@ #include <stddef.h> #include <stdint.h> -#include <string.h> +#include <algorithm> +#include <map> #include <string> +#include <vector> #include "base/base_paths.h" #include "base/big_endian.h"
diff --git a/ui/base/resource/resource_bundle_win.cc b/ui/base/resource/resource_bundle_win.cc index 8c0ac6a..cbe84cb 100644 --- a/ui/base/resource/resource_bundle_win.cc +++ b/ui/base/resource/resource_bundle_win.cc
@@ -6,6 +6,8 @@ #include <windows.h> +#include <memory> + #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "skia/ext/image_operations.h"
diff --git a/ui/base/resource/resource_data_dll_win.h b/ui/base/resource/resource_data_dll_win.h index cae9a2d..35e2b76d 100644 --- a/ui/base/resource/resource_data_dll_win.h +++ b/ui/base/resource/resource_data_dll_win.h
@@ -8,6 +8,9 @@ #include <windows.h> #include <stdint.h> +#include <memory> +#include <vector> + #include "ui/base/resource/resource_handle.h" namespace ui {
diff --git a/ui/base/resource/resource_handle.h b/ui/base/resource/resource_handle.h index 1412f23..5a162a2 100644 --- a/ui/base/resource/resource_handle.h +++ b/ui/base/resource/resource_handle.h
@@ -7,6 +7,8 @@ #include <stdint.h> +#include <vector> + #include "base/strings/string_piece.h" #include "ui/base/resource/data_pack_export.h" #include "ui/base/resource/resource_scale_factor.h"
diff --git a/ui/base/resource/scoped_startup_resource_bundle.cc b/ui/base/resource/scoped_startup_resource_bundle.cc index 42a1b21..4ec9d6c 100644 --- a/ui/base/resource/scoped_startup_resource_bundle.cc +++ b/ui/base/resource/scoped_startup_resource_bundle.cc
@@ -4,13 +4,13 @@ #include "ui/base/resource/scoped_startup_resource_bundle.h" +#include <string> + #include "base/command_line.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_switches.h" -#include "base/logging.h" - namespace ui { ScopedStartupResourceBundle::ScopedStartupResourceBundle() {
diff --git a/ui/events/fuchsia/fakes/pointer_event_utility.cc b/ui/events/fuchsia/fakes/pointer_event_utility.cc index 6c8bf75f..af10a597 100644 --- a/ui/events/fuchsia/fakes/pointer_event_utility.cc +++ b/ui/events/fuchsia/fakes/pointer_event_utility.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "ui/events/fuchsia/fakes/pointer_event_utility.h" +#include <zircon/types.h> #include <utility> namespace ui { @@ -11,18 +12,18 @@ namespace { -fup::ViewParameters CreateViewParameters( - std::array<std::array<float, 2>, 2> view, - std::array<std::array<float, 2>, 2> viewport, - std::array<float, 9> transform) { +fup::ViewParameters CreateViewParameters(gfx::RectF view, + gfx::RectF viewport, + std::array<float, 9> transform) { fup::ViewParameters params; fuchsia::ui::pointer::Rectangle view_rect; - view_rect.min = view[0]; - view_rect.max = view[1]; + view_rect.min = {view.x(), view.y()}; + view_rect.max = {view.bottom_right().x(), view.bottom_right().y()}; params.view = view_rect; fuchsia::ui::pointer::Rectangle viewport_rect; - viewport_rect.min = viewport[0]; - viewport_rect.max = viewport[1]; + viewport_rect.min = {viewport.x(), viewport.y()}; + viewport_rect.max = {viewport.bottom_right().x(), + viewport.bottom_right().y()}; params.viewport = viewport_rect; params.viewport_to_view_transform = transform; return params; @@ -33,138 +34,212 @@ TouchEventBuilder::~TouchEventBuilder() = default; -TouchEventBuilder& TouchEventBuilder::AddTime(zx_time_t time) { +TouchEventBuilder& TouchEventBuilder::SetTime(zx::time time) { time_ = time; return *this; } -TouchEventBuilder& TouchEventBuilder::AddSample(fup::TouchInteractionId id, - fup::EventPhase phase, - std::array<float, 2> position) { - sample_ = absl::make_optional<fup::TouchPointerSample>(); - sample_->set_interaction(id); - sample_->set_phase(phase); - sample_->set_position_in_viewport(position); +TouchEventBuilder& TouchEventBuilder::IncrementTime() { + static zx::time incrementing_time(0); + incrementing_time += zx::nsec(1111789u); + time_ = incrementing_time; return *this; } -TouchEventBuilder& TouchEventBuilder::AddViewParameters( - std::array<std::array<float, 2>, 2> view, - std::array<std::array<float, 2>, 2> viewport, +TouchEventBuilder& TouchEventBuilder::SetId( + fuchsia::ui::pointer::TouchInteractionId id) { + id_ = id; + return *this; +} + +TouchEventBuilder& TouchEventBuilder::SetPhase( + fuchsia::ui::pointer::EventPhase phase) { + phase_ = phase; + return *this; +} + +TouchEventBuilder& TouchEventBuilder::SetPosition(gfx::PointF position) { + position_ = position; + return *this; +} + +TouchEventBuilder& TouchEventBuilder::SetView(gfx::RectF view) { + view_ = view; + return *this; +} + +TouchEventBuilder& TouchEventBuilder::SetViewport(gfx::RectF viewport) { + viewport_ = viewport; + return *this; +} + +TouchEventBuilder& TouchEventBuilder::SetTransform( std::array<float, 9> transform) { - params_ = CreateViewParameters(std::move(view), std::move(viewport), - std::move(transform)); + transform_ = transform; return *this; } -TouchEventBuilder& TouchEventBuilder::AddResult( - fup::TouchInteractionResult result) { - result_ = result; +TouchEventBuilder& TouchEventBuilder::SetTouchInteractionStatus( + fup::TouchInteractionStatus touch_interaction_status) { + touch_interaction_status_ = touch_interaction_status; return *this; } -fup::TouchEvent TouchEventBuilder::Build() { +TouchEventBuilder& TouchEventBuilder::WithoutSample() { + include_sample_ = false; + return *this; +} + +fup::TouchPointerSample TouchEventBuilder::BuildSample() const { + fup::TouchPointerSample sample; + sample.set_interaction(id_); + sample.set_phase(phase_); + sample.set_position_in_viewport({position_.x(), position_.y()}); + return sample; +} + +fup::TouchInteractionResult TouchEventBuilder::BuildResult() const { + return {id_, touch_interaction_status_.value()}; +} + +fup::TouchEvent TouchEventBuilder::Build() const { fup::TouchEvent event; - if (time_) { - event.set_timestamp(time_.value()); + event.set_timestamp(time_.get()); + event.set_view_parameters(CreateViewParameters(view_, viewport_, transform_)); + if (include_sample_) { + event.set_pointer_sample(BuildSample()); } - if (params_) { - event.set_view_parameters(std::move(params_.value())); - } - if (sample_) { - event.set_pointer_sample(std::move(sample_.value())); - } - if (result_) { - event.set_interaction_result(std::move(result_.value())); + if (touch_interaction_status_) { + event.set_interaction_result(BuildResult()); } event.set_trace_flow_id(123); return event; } -std::vector<fup::TouchEvent> TouchEventBuilder::BuildAsVector() { - std::vector<fup::TouchEvent> events; - events.emplace_back(Build()); - return events; -} - MouseEventBuilder::MouseEventBuilder() = default; MouseEventBuilder::~MouseEventBuilder() = default; -MouseEventBuilder& MouseEventBuilder::AddTime(zx_time_t time) { +MouseEventBuilder& MouseEventBuilder::SetTime(zx::time time) { time_ = time; return *this; } -MouseEventBuilder& MouseEventBuilder::AddSample( - uint32_t id, - std::array<float, 2> position, - std::vector<uint8_t> pressed_buttons, - std::array<int64_t, 2> scroll, - std::array<int64_t, 2> scroll_in_physical_pixel, - bool is_precision_scroll) { - sample_ = absl::make_optional<fup::MousePointerSample>(); - sample_->set_device_id(id); - if (!pressed_buttons.empty()) { - sample_->set_pressed_buttons(pressed_buttons); - } - sample_->set_position_in_viewport(position); - if (scroll[0] != 0) { - sample_->set_scroll_h(scroll[0]); - } - if (scroll[1] != 0) { - sample_->set_scroll_v(scroll[1]); - } - if (scroll_in_physical_pixel[0] != 0) { - sample_->set_scroll_h_physical_pixel(scroll_in_physical_pixel[0]); - } - if (scroll_in_physical_pixel[1] != 0) { - sample_->set_scroll_v_physical_pixel(scroll_in_physical_pixel[1]); - } - sample_->set_is_precision_scroll(is_precision_scroll); +MouseEventBuilder& MouseEventBuilder::IncrementTime() { + static zx::time incrementing_time(0u); + incrementing_time += zx::nsec(1111789u); + time_ = incrementing_time; return *this; } -MouseEventBuilder& MouseEventBuilder::AddViewParameters( - std::array<std::array<float, 2>, 2> view, - std::array<std::array<float, 2>, 2> viewport, +MouseEventBuilder& MouseEventBuilder::SetDeviceId(uint32_t device_id) { + device_id_ = device_id; + return *this; +} + +MouseEventBuilder& MouseEventBuilder::SetView(gfx::RectF view) { + view_ = view; + return *this; +} + +MouseEventBuilder& MouseEventBuilder::SetViewport(gfx::RectF viewport) { + viewport_ = viewport; + return *this; +} + +MouseEventBuilder& MouseEventBuilder::SetTransform( std::array<float, 9> transform) { - params_ = CreateViewParameters(std::move(view), std::move(viewport), - std::move(transform)); + transform_ = transform; return *this; } -MouseEventBuilder& MouseEventBuilder::AddMouseDeviceInfo( - uint32_t id, - std::vector<uint8_t> buttons) { - device_info_ = absl::make_optional<fup::MouseDeviceInfo>(); - device_info_->set_id(id); - device_info_->set_buttons(buttons); +MouseEventBuilder& MouseEventBuilder::SetButtons(std::vector<uint8_t> buttons) { + buttons_ = buttons; return *this; } -fup::MouseEvent MouseEventBuilder::Build() { +MouseEventBuilder& MouseEventBuilder::SetPosition(gfx::PointF position) { + position_ = position; + return *this; +} + +MouseEventBuilder& MouseEventBuilder::SetPressedButtons( + std::vector<uint8_t> pressed_buttons) { + pressed_buttons_ = pressed_buttons; + return *this; +} + +MouseEventBuilder& MouseEventBuilder::SetScroll(Scroll scroll) { + scroll_ = scroll; + return *this; +} + +MouseEventBuilder& MouseEventBuilder::SetScrollInPhysicalPixel( + Scroll scroll_in_physical_pixel) { + scroll_in_physical_pixel_ = scroll_in_physical_pixel; + return *this; +} + +MouseEventBuilder& MouseEventBuilder::SetIsPrecisionScroll( + bool is_precision_scroll) { + is_precision_scroll_ = is_precision_scroll; + return *this; +} + +MouseEventBuilder& MouseEventBuilder::WithoutDeviceInfo() { + include_device_info_ = false; + return *this; +} + +MouseEventBuilder& MouseEventBuilder::WithoutViewParameters() { + include_view_parameters_ = false; + return *this; +} + +fup::MousePointerSample MouseEventBuilder::MouseEventBuilder::BuildSample() + const { + fup::MousePointerSample sample; + sample.set_device_id(device_id_); + if (!pressed_buttons_.empty()) { + sample.set_pressed_buttons(pressed_buttons_); + } + sample.set_position_in_viewport({position_.x(), position_.y()}); + if (scroll_.horizontal != 0) { + sample.set_scroll_h(scroll_.horizontal); + } + if (scroll_.vertical != 0) { + sample.set_scroll_v(scroll_.vertical); + } + if (scroll_in_physical_pixel_.horizontal != 0) { + sample.set_scroll_h_physical_pixel(scroll_in_physical_pixel_.horizontal); + } + if (scroll_in_physical_pixel_.vertical != 0) { + sample.set_scroll_v_physical_pixel(scroll_in_physical_pixel_.vertical); + } + sample.set_is_precision_scroll(is_precision_scroll_); + return sample; +} + +fup::MouseDeviceInfo MouseEventBuilder::BuildDeviceInfo() const { + fup::MouseDeviceInfo device_info; + device_info.set_id(device_id_); + device_info.set_buttons(buttons_); + return device_info; +} + +fup::MouseEvent MouseEventBuilder::Build() const { fup::MouseEvent event; - if (time_) { - event.set_timestamp(time_.value()); + event.set_timestamp(time_.get()); + if (include_view_parameters_) { + event.set_view_parameters( + CreateViewParameters(view_, viewport_, transform_)); } - if (params_) { - event.set_view_parameters(std::move(params_.value())); - } - if (sample_) { - event.set_pointer_sample(std::move(sample_.value())); - } - if (device_info_) { - event.set_device_info(std::move(device_info_.value())); + event.set_pointer_sample(BuildSample()); + if (include_device_info_) { + event.set_device_info(BuildDeviceInfo()); } event.set_trace_flow_id(123); return event; } -std::vector<fup::MouseEvent> MouseEventBuilder::BuildAsVector() { - std::vector<fup::MouseEvent> events; - events.emplace_back(Build()); - return events; -} - } // namespace ui
diff --git a/ui/events/fuchsia/fakes/pointer_event_utility.h b/ui/events/fuchsia/fakes/pointer_event_utility.h index 0d84b4e5..bf5cf9e 100644 --- a/ui/events/fuchsia/fakes/pointer_event_utility.h +++ b/ui/events/fuchsia/fakes/pointer_event_utility.h
@@ -6,6 +6,8 @@ #define UI_EVENTS_FUCHSIA_FAKES_POINTER_EVENT_UTILITY_H_ #include <fuchsia/ui/pointer/cpp/fidl.h> +#include <ui/gfx/geometry/point_f.h> +#include <ui/gfx/geometry/rect_f.h> #include <zircon/types.h> #include <array> @@ -14,6 +16,16 @@ #include "third_party/abseil-cpp/absl/types/optional.h" +namespace { +constexpr gfx::RectF kRect(0, 0, 20, 20); +constexpr std::array<float, 9> kIdentity = {1, 0, 0, 0, 1, 0, 0, 0, 1}; +constexpr fuchsia::ui::pointer::TouchInteractionId kIxnOne = { + .device_id = 1u, + .pointer_id = 1u, + .interaction_id = 2u}; +constexpr uint32_t kMouseDeviceId = 123; +} // namespace + namespace ui { // A helper class for crafting a fuchsia.ui.pointer.TouchEvent table. @@ -22,25 +34,42 @@ TouchEventBuilder(); ~TouchEventBuilder(); - TouchEventBuilder& AddTime(zx_time_t time); - TouchEventBuilder& AddSample(fuchsia::ui::pointer::TouchInteractionId id, - fuchsia::ui::pointer::EventPhase phase, - std::array<float, 2> position); - TouchEventBuilder& AddViewParameters( - std::array<std::array<float, 2>, 2> view, - std::array<std::array<float, 2>, 2> viewport, - std::array<float, 9> transform); - TouchEventBuilder& AddResult( - fuchsia::ui::pointer::TouchInteractionResult result); + TouchEventBuilder& SetTime(zx::time time); + TouchEventBuilder& IncrementTime(); + TouchEventBuilder& SetId(fuchsia::ui::pointer::TouchInteractionId id); + TouchEventBuilder& SetPhase(fuchsia::ui::pointer::EventPhase phase); + TouchEventBuilder& SetPosition(gfx::PointF position); + TouchEventBuilder& SetView(gfx::RectF view); + TouchEventBuilder& SetViewport(gfx::RectF viewport); + TouchEventBuilder& SetTransform(std::array<float, 9> transform); + TouchEventBuilder& SetTouchInteractionStatus( + fuchsia::ui::pointer::TouchInteractionStatus touch_interaction_status); - fuchsia::ui::pointer::TouchEvent Build(); - std::vector<fuchsia::ui::pointer::TouchEvent> BuildAsVector(); + TouchEventBuilder& WithoutSample(); + + fuchsia::ui::pointer::TouchEvent Build() const; private: - absl::optional<zx_time_t> time_; - absl::optional<fuchsia::ui::pointer::ViewParameters> params_; - absl::optional<fuchsia::ui::pointer::TouchPointerSample> sample_; - absl::optional<fuchsia::ui::pointer::TouchInteractionResult> result_; + fuchsia::ui::pointer::TouchPointerSample BuildSample() const; + fuchsia::ui::pointer::TouchInteractionResult BuildResult() const; + + zx::time time_{1u}; + fuchsia::ui::pointer::TouchInteractionId id_ = kIxnOne; + fuchsia::ui::pointer::EventPhase phase_ = + fuchsia::ui::pointer::EventPhase::ADD; + gfx::PointF position_ = {10.f, 10.f}; + gfx::RectF view_ = kRect; + gfx::RectF viewport_ = kRect; + std::array<float, 9> transform_ = kIdentity; + absl::optional<fuchsia::ui::pointer::TouchInteractionStatus> + touch_interaction_status_; + + bool include_sample_ = true; +}; + +struct Scroll { + int64_t horizontal; + int64_t vertical; }; // A helper class for crafting a fuchsia.ui.pointer.MouseEvent table. @@ -49,28 +78,43 @@ MouseEventBuilder(); ~MouseEventBuilder(); - MouseEventBuilder& AddTime(zx_time_t time); - MouseEventBuilder& AddSample(uint32_t id, - std::array<float, 2> position, - std::vector<uint8_t> pressed_buttons, - std::array<int64_t, 2> scroll, - std::array<int64_t, 2> scroll_in_physical_pixel, - bool is_precision_scroll); - MouseEventBuilder& AddViewParameters( - std::array<std::array<float, 2>, 2> view, - std::array<std::array<float, 2>, 2> viewport, - std::array<float, 9> transform); - MouseEventBuilder& AddMouseDeviceInfo(uint32_t id, - std::vector<uint8_t> buttons); + MouseEventBuilder& SetTime(zx::time time); + MouseEventBuilder& IncrementTime(); + MouseEventBuilder& SetDeviceId(uint32_t device_id); + MouseEventBuilder& SetView(gfx::RectF view); + MouseEventBuilder& SetViewport(gfx::RectF viewport); + MouseEventBuilder& SetTransform(std::array<float, 9> transform); + MouseEventBuilder& SetButtons(std::vector<uint8_t> buttons); + MouseEventBuilder& SetPosition(gfx::PointF position); + MouseEventBuilder& SetPressedButtons(std::vector<uint8_t> pressed_buttons); + MouseEventBuilder& SetScroll(Scroll scroll); + MouseEventBuilder& SetScrollInPhysicalPixel(Scroll scroll_in_physical_pixel); + MouseEventBuilder& SetIsPrecisionScroll(bool is_precision_scroll); - fuchsia::ui::pointer::MouseEvent Build(); - std::vector<fuchsia::ui::pointer::MouseEvent> BuildAsVector(); + MouseEventBuilder& WithoutDeviceInfo(); + MouseEventBuilder& WithoutViewParameters(); + + fuchsia::ui::pointer::MouseEvent Build() const; private: - absl::optional<zx_time_t> time_; - absl::optional<fuchsia::ui::pointer::ViewParameters> params_; - absl::optional<fuchsia::ui::pointer::MousePointerSample> sample_; - absl::optional<fuchsia::ui::pointer::MouseDeviceInfo> device_info_; + fuchsia::ui::pointer::MousePointerSample BuildSample() const; + fuchsia::ui::pointer::ViewParameters BuildViewParameters() const; + fuchsia::ui::pointer::MouseDeviceInfo BuildDeviceInfo() const; + + zx::time time_{1u}; + uint32_t device_id_ = kMouseDeviceId; + gfx::RectF view_ = kRect; + gfx::RectF viewport_ = kRect; + std::array<float, 9> transform_ = kIdentity; + std::vector<uint8_t> buttons_ = {0, 1, 2}; + gfx::PointF position_ = {0, 0}; + std::vector<uint8_t> pressed_buttons_ = {}; + Scroll scroll_ = {.horizontal = 0, .vertical = 0}; + Scroll scroll_in_physical_pixel_ = {.horizontal = 0, .vertical = 0}; + bool is_precision_scroll_ = false; + + bool include_device_info_ = true; + bool include_view_parameters_ = true; }; } // namespace ui
diff --git a/ui/events/fuchsia/pointer_events_handler_unittest.cc b/ui/events/fuchsia/pointer_events_handler_unittest.cc index 93fd191..59512d0 100644 --- a/ui/events/fuchsia/pointer_events_handler_unittest.cc +++ b/ui/events/fuchsia/pointer_events_handler_unittest.cc
@@ -14,7 +14,6 @@ #include <memory> #include <vector> -#include "base/logging.h" #include "base/test/bind.h" #include "base/test/task_environment.h" #include "testing/gtest/include/gtest/gtest.h" @@ -25,23 +24,21 @@ #include "ui/events/fuchsia/fakes/fake_touch_source.h" #include "ui/events/fuchsia/fakes/pointer_event_utility.h" #include "ui/events/types/event_type.h" +#include "ui/gfx/geometry/rect_f.h" namespace ui { namespace { namespace fup = fuchsia::ui::pointer; -constexpr std::array<std::array<float, 2>, 2> kRect = {{{0, 0}, {20, 20}}}; -constexpr std::array<float, 9> kIdentity = {1, 0, 0, 0, 1, 0, 0, 0, 1}; -constexpr fup::TouchInteractionId kIxnOne = {.device_id = 1u, - .pointer_id = 1u, - .interaction_id = 2u}; -constexpr uint32_t kMouseDeviceId = 123; - -constexpr std::array<int64_t, 2> kNoScrollDelta = {0, 0}; -constexpr std::array<int64_t, 2> kNoScrollInPhysicalPixelDelta = {0, 0}; -const bool kNotPrecisionScroll = false; -const bool kPrecisionScroll = true; +// Builds a vector of move-only values. +template <typename T, class... Args> +std::vector<T> MakeVector(Args&&... args) { + std::vector<T> output; + output.reserve(sizeof...(Args)); + ((output.emplace_back(std::forward<Args>(args))), ...); + return output; +} // Fixture to exercise the implementation for fuchsia.ui.pointer.TouchSource and // fuchsia.ui.pointer.MouseSource. @@ -77,14 +74,10 @@ [&events](Event* event) { events.push_back(event->Clone()); })); RunLoopUntilIdle(); // Server gets watch call. - std::vector<fup::TouchEvent> touch_events = + std::vector touch_events = MakeVector<fup::TouchEvent>( TouchEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .AddResult({.interaction = kIxnOne, - .status = fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .Build()); touch_source_->ScheduleCallback(std::move(touch_events)); RunLoopUntilIdle(); @@ -93,14 +86,8 @@ EXPECT_EQ(events[0]->AsTouchEvent()->pointer_details().pointer_type, EventPointerType::kTouch); - std::vector<fup::MouseEvent> mouse_events = - MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0}, kNoScrollDelta, - kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + std::vector mouse_events = MakeVector<fup::MouseEvent>( + MouseEventBuilder().SetPressedButtons({0}).Build()); mouse_source_->ScheduleCallback(std::move(mouse_events)); RunLoopUntilIdle(); @@ -118,14 +105,11 @@ })); RunLoopUntilIdle(); // Server gets watch call. - std::vector<fup::TouchEvent> events = + std::vector events = MakeVector<fup::TouchEvent>( TouchEventBuilder() - .AddTime(1111789u /* in nanoseconds */) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .AddResult({.interaction = kIxnOne, - .status = fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + .SetTime(zx::time{1111783u}) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -142,18 +126,10 @@ })); RunLoopUntilIdle(); // Server gets watch call. - // Fuchsia button press -> Chrome ET_MOUSE_PRESSED and EF_RIGHT_MOUSE_BUTTON - std::vector<fup::MouseEvent> events = - MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0 /*button id*/}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, - {2 /*first button id*/, 0 /*second button id*/, - 1 /*third button id*/}) - .BuildAsVector(); + // Fuchsia button press -> Chrome ET_MOUSE_PRESSED and + // EF_RIGHT_MOUSE_BUTTON + std::vector events = MakeVector<fup::MouseEvent>( + MouseEventBuilder().SetPressedButtons({0}).SetButtons({2, 0, 1}).Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -164,12 +140,11 @@ // Keep Fuchsia button press -> Chrome ET_MOUSE_DRAGGED and // EF_RIGHT_MOUSE_BUTTON - events = MouseEventBuilder() - .AddTime(1111789u) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0 /*button id*/}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .BuildAsVector(); + events = MakeVector<fup::MouseEvent>(MouseEventBuilder() + .SetPressedButtons({0}) + .WithoutViewParameters() + .WithoutDeviceInfo() + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -179,11 +154,11 @@ mouse_events.clear(); // Release Fuchsia button -> Chrome ET_MOUSE_RELEASED - events = MouseEventBuilder() - .AddTime(1111789u) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, kNoScrollDelta, - kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) - .BuildAsVector(); + events = MakeVector<fup::MouseEvent>(MouseEventBuilder() + .SetPressedButtons({}) + .WithoutViewParameters() + .WithoutDeviceInfo() + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -193,18 +168,17 @@ mouse_events.clear(); // Release Fuchsia button -> Chrome ET_MOUSE_MOVED - events = MouseEventBuilder() - .AddTime(1111789u) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, kNoScrollDelta, - kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) - .BuildAsVector(); + events = MakeVector<fup::MouseEvent>(MouseEventBuilder() + .SetPressedButtons({}) + .WithoutViewParameters() + .WithoutDeviceInfo() + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_EQ(mouse_events.size(), 1u); EXPECT_EQ(mouse_events[0].type(), ET_MOUSE_MOVED); EXPECT_EQ(mouse_events[0].flags(), EF_NONE); - mouse_events.clear(); } TEST_F(PointerEventsHandlerTest, Phase_ChromeMouseEventFlagsAreSynthesized) { @@ -216,14 +190,8 @@ RunLoopUntilIdle(); // Server gets watch call. // Fuchsia button press -> Chrome ET_MOUSE_PRESSED and EF_RIGHT_MOUSE_BUTTON - std::vector<fup::MouseEvent> events = - MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0}, kNoScrollDelta, - kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {2, 0, 1}) - .BuildAsVector(); + std::vector events = MakeVector<fup::MouseEvent>( + MouseEventBuilder().SetPressedButtons({0}).SetButtons({2, 0, 1}).Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -234,11 +202,11 @@ // Switch Fuchsia button press -> Chrome ET_MOUSE_DRAGGED and // EF_LEFT_MOUSE_BUTTON - events = MouseEventBuilder() - .AddTime(1111789u) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {2}, kNoScrollDelta, - kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) - .BuildAsVector(); + events = MakeVector<fup::MouseEvent>(MouseEventBuilder() + .SetPressedButtons({2}) + .WithoutViewParameters() + .WithoutDeviceInfo() + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -247,7 +215,6 @@ EXPECT_EQ(mouse_events[0].flags(), EF_LEFT_MOUSE_BUTTON); EXPECT_EQ(mouse_events[1].type(), ET_MOUSE_RELEASED); EXPECT_EQ(mouse_events[1].flags(), EF_RIGHT_MOUSE_BUTTON); - mouse_events.clear(); } TEST_F(PointerEventsHandlerTest, Phase_ChromeMouseEventFlagCombo) { @@ -260,14 +227,8 @@ // Fuchsia button press -> Chrome ET_MOUSE_PRESSED on EF_LEFT_MOUSE_BUTTON // and EF_RIGHT_MOUSE_BUTTON - std::vector<fup::MouseEvent> events = - MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0, 1}, kNoScrollDelta, - kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + std::vector events = MakeVector<fup::MouseEvent>( + MouseEventBuilder().SetPressedButtons({0, 1}).Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -276,7 +237,6 @@ EXPECT_EQ(mouse_events[0].flags(), EF_LEFT_MOUSE_BUTTON); EXPECT_EQ(mouse_events[1].type(), ET_MOUSE_PRESSED); EXPECT_EQ(mouse_events[1].flags(), EF_RIGHT_MOUSE_BUTTON); - mouse_events.clear(); } TEST_F(PointerEventsHandlerTest, ChromeMouseEventDoubleClick) { @@ -287,43 +247,12 @@ })); RunLoopUntilIdle(); // Server gets watch call. - std::vector<fup::MouseEvent> events; - // Press - events.push_back(MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .Build()); - // Release - events.push_back(MouseEventBuilder() - .AddTime(2111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .Build()); - // Press - events.push_back(MouseEventBuilder() - .AddTime(3111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .Build()); - // Release - events.push_back(MouseEventBuilder() - .AddTime(4111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .Build()); + std::vector events = MakeVector<fup::MouseEvent>( + MouseEventBuilder().SetPressedButtons({0}).IncrementTime().Build(), + MouseEventBuilder().SetPressedButtons({}).IncrementTime().Build(), + MouseEventBuilder().SetPressedButtons({0}).IncrementTime().Build(), + MouseEventBuilder().SetPressedButtons({}).IncrementTime().Build()); + mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -346,56 +275,35 @@ })); RunLoopUntilIdle(); // Server gets watch call. - std::vector<fup::MouseEvent> events; - // Press left and right button. - events.push_back(MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0, 1}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .Build()); - // drag with left, right button pressing. - events.push_back(MouseEventBuilder() - .AddTime(1111790u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {11.f, 10.f}, {0, 1}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .Build()); - // right button up. - events.push_back(MouseEventBuilder() - .AddTime(1111791u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {11.f, 10.f}, {0}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .Build()); - // drag with left button pressing. - events.push_back(MouseEventBuilder() - .AddTime(1111792u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {11.f, 11.f}, {0}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .Build()); - // left button up. - events.push_back(MouseEventBuilder() - .AddTime(11117913u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {11.f, 11.f}, {}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .Build()); - // mouse move. - events.push_back(MouseEventBuilder() - .AddTime(1111794u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {12.f, 11.f}, {}, - kNoScrollDelta, kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .Build()); + std::vector events = MakeVector<fup::MouseEvent>( + // Press left and right button. + MouseEventBuilder() + .SetPosition({10.f, 10.f}) + .SetPressedButtons({0, 1}) + .IncrementTime() + .Build(), + // drag with left, right button pressing. + MouseEventBuilder() + .SetPosition({11.f, 10.f}) + .SetPressedButtons({0, 1}) + .IncrementTime() + .Build(), + // right button up. + MouseEventBuilder() + .SetPosition({11.f, 10.f}) + .SetPressedButtons({0}) + .IncrementTime() + .Build(), + // drag with left button pressing. + MouseEventBuilder() + .SetPosition({11.f, 11.f}) + .SetPressedButtons({0}) + .IncrementTime() + .Build(), + // left button up. + MouseEventBuilder().SetPosition({11.f, 11.f}).IncrementTime().Build(), + // mouse move. + MouseEventBuilder().SetPosition({12.f, 11.f}).IncrementTime().Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -416,7 +324,6 @@ EXPECT_EQ(mouse_events[5].flags(), EF_LEFT_MOUSE_BUTTON); EXPECT_EQ(mouse_events[6].type(), ET_MOUSE_MOVED); EXPECT_EQ(mouse_events[6].flags(), 0); - mouse_events.clear(); } TEST_F(PointerEventsHandlerTest, MouseWheelEvent) { @@ -429,14 +336,8 @@ RunLoopUntilIdle(); // Server gets watch call. // receive a vertical scroll - std::vector<fup::MouseEvent> events = - MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {0, 1}, - kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + std::vector events = MakeVector<fup::MouseEvent>( + MouseEventBuilder().SetScroll({0, 1}).Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -448,13 +349,8 @@ mouse_events.clear(); // receive a horizontal scroll - events = MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {1, 0}, - kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + events = MakeVector<fup::MouseEvent>( + MouseEventBuilder().SetScroll({1, 0}).Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -463,7 +359,6 @@ EXPECT_EQ(mouse_events[0].flags(), EF_NONE); EXPECT_EQ(mouse_events[0].AsMouseWheelEvent()->x_offset(), 120); EXPECT_EQ(mouse_events[0].AsMouseWheelEvent()->y_offset(), 0); - mouse_events.clear(); } TEST_F(PointerEventsHandlerTest, MouseWheelEventDeltaInPhysicalPixel) { @@ -476,14 +371,11 @@ RunLoopUntilIdle(); // Server gets watch call. // receive a vertical scroll - std::vector<fup::MouseEvent> events = - MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {0, 1}, {0, 100}, - kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + std::vector events = + MakeVector<fup::MouseEvent>(MouseEventBuilder() + .SetScroll({0, 1}) + .SetScrollInPhysicalPixel({0, 100}) + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -495,13 +387,10 @@ mouse_events.clear(); // receive a horizontal scroll - events = MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {1, 0}, {100, 0}, - kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + events = MakeVector<fup::MouseEvent>(MouseEventBuilder() + .SetScroll({1, 0}) + .SetScrollInPhysicalPixel({100, 0}) + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -510,7 +399,6 @@ EXPECT_EQ(mouse_events[0].flags(), EF_NONE); EXPECT_EQ(mouse_events[0].AsMouseWheelEvent()->x_offset(), 100); EXPECT_EQ(mouse_events[0].AsMouseWheelEvent()->y_offset(), 0); - mouse_events.clear(); } TEST_F(PointerEventsHandlerTest, ScrollEventDeltaInPhysicalPixel) { @@ -523,14 +411,12 @@ RunLoopUntilIdle(); // Server gets watch call. // receive a vertical scroll - std::vector<fup::MouseEvent> events = - MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {0, 1}, {0, 100}, - kPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + std::vector events = + MakeVector<fup::MouseEvent>(MouseEventBuilder() + .SetScroll({0, 1}) + .SetScrollInPhysicalPixel({0, 100}) + .SetIsPrecisionScroll(true) + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -542,13 +428,11 @@ mouse_events.clear(); // receive a horizontal scroll - events = MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, {1, 0}, {100, 0}, - kPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + events = MakeVector<fup::MouseEvent>(MouseEventBuilder() + .SetScroll({1, 0}) + .SetScrollInPhysicalPixel({100, 0}) + .SetIsPrecisionScroll(true) + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -557,7 +441,6 @@ EXPECT_EQ(mouse_events[0].flags(), EF_NONE); EXPECT_EQ(mouse_events[0].AsScrollEvent()->x_offset(), 100); EXPECT_EQ(mouse_events[0].AsScrollEvent()->y_offset(), 0); - mouse_events.clear(); } TEST_F(PointerEventsHandlerTest, ScrollEventDeltaInPhysicalPixelNoTickDelta) { @@ -570,14 +453,11 @@ RunLoopUntilIdle(); // Server gets watch call. // receive a vertical scroll - std::vector<fup::MouseEvent> events = - MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, kNoScrollDelta, {0, 100}, - kPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + std::vector events = + MakeVector<fup::MouseEvent>(MouseEventBuilder() + .SetScrollInPhysicalPixel({0, 100}) + .SetIsPrecisionScroll(true) + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -589,13 +469,10 @@ mouse_events.clear(); // receive a horizontal scroll - events = MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {}, kNoScrollDelta, - {100, 0}, kPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + events = MakeVector<fup::MouseEvent>(MouseEventBuilder() + .SetScrollInPhysicalPixel({100, 0}) + .SetIsPrecisionScroll(true) + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -604,7 +481,6 @@ EXPECT_EQ(mouse_events[0].flags(), EF_NONE); EXPECT_EQ(mouse_events[0].AsScrollEvent()->x_offset(), 100); EXPECT_EQ(mouse_events[0].AsScrollEvent()->y_offset(), 0); - mouse_events.clear(); } TEST_F(PointerEventsHandlerTest, MouseWheelEventWithButtonPressed) { @@ -624,24 +500,14 @@ })); RunLoopUntilIdle(); // Server gets watch call. - // left button down - std::vector<fup::MouseEvent> events = + std::vector events = MakeVector<fup::MouseEvent>( + MouseEventBuilder().SetPressedButtons({0}).IncrementTime().Build(), + // receive a vertical scroll with pressed button MouseEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0}, kNoScrollDelta, - kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); - - // receive a vertical scroll with pressed button - events.push_back(MouseEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0}, {0, 1}, - kNoScrollInPhysicalPixelDelta, - kNotPrecisionScroll) - .Build()); + .SetPressedButtons({0}) + .SetScroll({0, 1}) + .IncrementTime() + .Build()); mouse_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -653,8 +519,6 @@ EXPECT_EQ(mouse_events[1]->flags(), EF_LEFT_MOUSE_BUTTON); EXPECT_EQ(mouse_events[1]->AsMouseWheelEvent()->x_offset(), 0); EXPECT_EQ(mouse_events[1]->AsMouseWheelEvent()->y_offset(), 120); - - mouse_events.clear(); } TEST_F(PointerEventsHandlerTest, MouseWheelEventWithButtonDownBundled) { @@ -675,14 +539,8 @@ RunLoopUntilIdle(); // Server gets watch call. // left button down and a vertical scroll bundled. - std::vector<fup::MouseEvent> events = - MouseEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kMouseDeviceId, {10.f, 10.f}, {0}, {0, 1}, - kNoScrollInPhysicalPixelDelta, kNotPrecisionScroll) - .AddMouseDeviceInfo(kMouseDeviceId, {0, 1, 2}) - .BuildAsVector(); + std::vector events = MakeVector<fup::MouseEvent>( + MouseEventBuilder().SetPressedButtons({0}).SetScroll({0, 1}).Build()); mouse_source_->ScheduleCallback(std::move(events)); @@ -695,8 +553,6 @@ EXPECT_EQ(mouse_events[1]->flags(), EF_LEFT_MOUSE_BUTTON); EXPECT_EQ(mouse_events[1]->AsMouseWheelEvent()->x_offset(), 0); EXPECT_EQ(mouse_events[1]->AsMouseWheelEvent()->y_offset(), 120); - - mouse_events.clear(); } TEST_F(PointerEventsHandlerTest, Phase_ChromeTouchEventTypesAreSynthesized) { @@ -708,14 +564,11 @@ RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD -> Chrome ET_TOUCH_PRESSED - std::vector<fup::TouchEvent> events = + std::vector events = MakeVector<fup::TouchEvent>( TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .AddResult({.interaction = kIxnOne, - .status = fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + .SetTime(zx::time{1111000u}) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -724,10 +577,10 @@ touch_events.clear(); // Fuchsia CHANGE -> Chrome ET_TOUCH_MOVED - events = TouchEventBuilder() - .AddTime(2222000u) - .AddSample(kIxnOne, fup::EventPhase::CHANGE, {10.f, 10.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{2222000u}) + .SetPhase(fup::EventPhase::CHANGE) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -736,16 +589,15 @@ touch_events.clear(); // Fuchsia REMOVE -> Chrome ET_TOUCH_RELEASED - events = TouchEventBuilder() - .AddTime(3333000u) - .AddSample(kIxnOne, fup::EventPhase::REMOVE, {10.f, 10.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{3333000u}) + .SetPhase(fup::EventPhase::REMOVE) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_EQ(touch_events.size(), 1u); EXPECT_EQ(touch_events[0].type(), ET_TOUCH_RELEASED); - touch_events.clear(); } TEST_F(PointerEventsHandlerTest, Phase_FuchsiaCancelBecomesChromeCancel) { @@ -757,14 +609,11 @@ RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD -> Chrome ET_TOUCH_PRESSED - std::vector<fup::TouchEvent> events = + std::vector events = MakeVector<fup::TouchEvent>( TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .AddResult({.interaction = kIxnOne, - .status = fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + .SetTime(zx::time{1111000u}) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -773,16 +622,15 @@ touch_events.clear(); // Fuchsia CANCEL -> Chrome CANCEL - events = TouchEventBuilder() - .AddTime(2222000u) - .AddSample(kIxnOne, fup::EventPhase::CANCEL, {10.f, 10.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{2222000u}) + .SetPhase(fup::EventPhase::CANCEL) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_EQ(touch_events.size(), 1u); EXPECT_EQ(touch_events[0].type(), ET_TOUCH_CANCELLED); - touch_events.clear(); } TEST_F(PointerEventsHandlerTest, Coordinates_CorrectMapping) { @@ -796,16 +644,14 @@ // Fuchsia ADD event, with a view parameter that maps the viewport identically // to the view. Then the center point of the viewport should map to the center // of the view, (10.f, 10.f). - std::vector<fup::TouchEvent> events = + std::vector events = MakeVector<fup::TouchEvent>( TouchEventBuilder() - .AddTime(2222000u) - .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, - /*viewport*/ {{{0, 0}, {20, 20}}}, - /*matrix*/ {1, 0, 0, 0, 1, 0, 0, 0, 1}) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .AddResult({.interaction = kIxnOne, - .status = fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + .SetTime(zx::time{2222000u}) + .SetView(gfx::RectF(0, 0, 20, 20)) + .SetViewport(gfx::RectF(0, 0, 20, 20)) + .SetTransform({1, 0, 0, 0, 1, 0, 0, 0, 1}) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -817,13 +663,15 @@ // Fuchsia CHANGE event, with a view parameter that translates the viewport by // (10, 10) within the view. Then the minimal point in the viewport (its // origin) should map to the center of the view, (10.f, 10.f). - events = TouchEventBuilder() - .AddTime(2222000u) - .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, - /*viewport*/ {{{0, 0}, {20, 20}}}, - /*matrix*/ {1, 0, 0, 0, 1, 0, 10, 10, 1}) - .AddSample(kIxnOne, fup::EventPhase::CHANGE, {0.f, 0.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>( + TouchEventBuilder() + .SetTime(zx::time{2222000u}) + .SetView(gfx::RectF(0, 0, 20, 20)) + .SetViewport(gfx::RectF(0, 0, 20, 20)) + .SetTransform({1, 0, 0, 0, 1, 0, 10, 10, 1}) + .SetPhase(fup::EventPhase::CHANGE) + .SetPosition({0.f, 0.f}) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -835,20 +683,21 @@ // Fuchsia CHANGE event, with a view parameter that scales the viewport by // (0.5, 0.5) within the view. Then the maximal point in the viewport should // map to the center of the view, (10.f, 10.f). - events = TouchEventBuilder() - .AddTime(2222000u) - .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, - /*viewport*/ {{{0, 0}, {20, 20}}}, - /*matrix*/ {0.5f, 0, 0, 0, 0.5f, 0, 0, 0, 1}) - .AddSample(kIxnOne, fup::EventPhase::CHANGE, {20.f, 20.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>( + TouchEventBuilder() + .SetTime(zx::time{2222000u}) + .SetView(gfx::RectF(0, 0, 20, 20)) + .SetViewport(gfx::RectF(0, 0, 20, 20)) + .SetTransform({0.5f, 0, 0, 0, 0.5f, 0, 0, 0, 1}) + .SetPhase(fup::EventPhase::CHANGE) + .SetPosition({20.f, 20.f}) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); ASSERT_EQ(touch_events.size(), 1u); EXPECT_EQ(touch_events[0].location_f().x(), 10.f); EXPECT_EQ(touch_events[0].location_f().y(), 10.f); - touch_events.clear(); } TEST_F(PointerEventsHandlerTest, Coordinates_PressedEventClampedToView) { @@ -861,14 +710,11 @@ })); RunLoopUntilIdle(); // Server gets watch call. - std::vector<fup::TouchEvent> events = + std::vector events = MakeVector<fup::TouchEvent>( TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, kSmallDiscrepancy}) - .AddResult({.interaction = kIxnOne, - .status = fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + .SetPosition({10.f, kSmallDiscrepancy}) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -898,40 +744,27 @@ })); RunLoopUntilIdle(); // Server gets watch call. - // Fuchsia view parameter only. Empty response. - std::vector<fup::TouchEvent> events = - TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .BuildAsVector(); + std::vector events = MakeVector<fup::TouchEvent>( + // Fuchsia view parameter only. Empty response. + TouchEventBuilder().WithoutSample().Build(), - // Fuchsia ptr 1 ADD sample. Yes response. - fup::TouchEvent e1 = + // Fuchsia ptr 1 ADD sample. Yes response. TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample({.device_id = 0u, .pointer_id = 1u, .interaction_id = 3u}, - fup::EventPhase::ADD, {10.f, 10.f}) - .Build(); - events.emplace_back(std::move(e1)); + .SetId({.device_id = 0u, .pointer_id = 1u, .interaction_id = 3u}) + .SetPosition({10.f, 10.f}) + .Build(), - // Fuchsia ptr 2 ADD sample. Yes response. - fup::TouchEvent e2 = + // Fuchsia ptr 2 ADD sample. Yes response. TouchEventBuilder() - .AddTime(1111000u) - .AddSample({.device_id = 0u, .pointer_id = 2u, .interaction_id = 3u}, - fup::EventPhase::ADD, {5.f, 5.f}) - .Build(); - events.emplace_back(std::move(e2)); + .SetId({.device_id = 0u, .pointer_id = 2u, .interaction_id = 3u}) + .SetPosition({5.f, 5.f}) + .Build(), - // Fuchsia ptr 3 ADD sample. Yes response. - fup::TouchEvent e3 = + // Fuchsia ptr 3 ADD sample. Yes response. TouchEventBuilder() - .AddTime(1111000u) - .AddSample({.device_id = 0u, .pointer_id = 3u, .interaction_id = 3u}, - fup::EventPhase::ADD, {1.f, 1.f}) - .Build(); - events.emplace_back(std::move(e3)); + .SetId({.device_id = 0u, .pointer_id = 3u, .interaction_id = 3u}) + .SetPosition({1.f, 1.f}) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -958,12 +791,8 @@ RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD, no grant result - buffer it. - std::vector<fup::TouchEvent> events = - TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .BuildAsVector(); + std::vector events = MakeVector<fup::TouchEvent>( + TouchEventBuilder().SetTime(zx::time{1111000u}).Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -971,10 +800,10 @@ touch_events.clear(); // Fuchsia CHANGE, no grant result - buffer it. - events = TouchEventBuilder() - .AddTime(2222000u) - .AddSample(kIxnOne, fup::EventPhase::CHANGE, {10.f, 10.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{2222000u}) + .SetPhase(fup::EventPhase::CHANGE) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -982,10 +811,12 @@ touch_events.clear(); // Fuchsia result: ownership granted. Buffered pointers released. - events = TouchEventBuilder() - .AddTime(3333000u) - .AddResult({kIxnOne, fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>( + TouchEventBuilder() + .SetTime(zx::time{3333000u}) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .WithoutSample() + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -995,10 +826,10 @@ touch_events.clear(); // Fuchsia CHANGE, grant result - release immediately. - events = TouchEventBuilder() - .AddTime(/* in nanoseconds */ 4444000u) - .AddSample(kIxnOne, fup::EventPhase::CHANGE, {10.f, 10.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{4444000u}) + .SetPhase(fup::EventPhase::CHANGE) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1018,12 +849,11 @@ RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD, no grant result - buffer it. - std::vector<fup::TouchEvent> events = - TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .BuildAsVector(); + std::vector events = + MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{1111000u}) + .SetPhase(fup::EventPhase::ADD) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1031,10 +861,10 @@ touch_events.clear(); // Fuchsia CHANGE, no grant result - buffer it. - events = TouchEventBuilder() - .AddTime(2222000u) - .AddSample(kIxnOne, fup::EventPhase::CHANGE, {10.f, 10.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{2222000u}) + .SetPhase(fup::EventPhase::CHANGE) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1042,11 +872,12 @@ touch_events.clear(); // Fuchsia CHANGE, with grant result - release buffered events. - events = TouchEventBuilder() - .AddTime(3333000u) - .AddSample(kIxnOne, fup::EventPhase::CHANGE, {10.f, 10.f}) - .AddResult({kIxnOne, fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>( + TouchEventBuilder() + .SetTime(zx::time{3333000u}) + .SetPhase(fup::EventPhase::CHANGE) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1072,13 +903,12 @@ RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD, with grant result - release immediately. - std::vector<fup::TouchEvent> events = + std::vector events = MakeVector<fup::TouchEvent>( TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .AddResult({kIxnOne, fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + .SetTime(zx::time{1111000u}) + .SetPhase(fup::EventPhase::ADD) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1087,10 +917,10 @@ touch_events.clear(); // Fuchsia CHANGE, after grant result - release immediately. - events = TouchEventBuilder() - .AddTime(2222000u) - .AddSample(kIxnOne, fup::EventPhase::CHANGE, {10.f, 10.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{2222000u}) + .SetPhase(fup::EventPhase::CHANGE) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1108,12 +938,11 @@ RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD, no grant result - buffer it. - std::vector<fup::TouchEvent> events = - TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .BuildAsVector(); + std::vector events = + MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{1111000u}) + .SetPhase(fup::EventPhase::ADD) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1121,10 +950,10 @@ touch_events.clear(); // Fuchsia CHANGE, no grant result - buffer it. - events = TouchEventBuilder() - .AddTime(2222000u) - .AddSample(kIxnOne, fup::EventPhase::CHANGE, {10.f, 10.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{2222000u}) + .SetPhase(fup::EventPhase::CHANGE) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1132,10 +961,12 @@ touch_events.clear(); // Fuchsia result: ownership denied. Buffered pointers deleted. - events = TouchEventBuilder() - .AddTime(3333000u) - .AddResult({kIxnOne, fup::TouchInteractionStatus::DENIED}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>( + TouchEventBuilder() + .SetTime(zx::time{3333000u}) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::DENIED) + .WithoutSample() + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1152,12 +983,11 @@ RunLoopUntilIdle(); // Server gets watch call. // Fuchsia ADD, no grant result - buffer it. - std::vector<fup::TouchEvent> events = - TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .BuildAsVector(); + std::vector events = + MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{1111000u}) + .SetPhase(fup::EventPhase::ADD) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1165,10 +995,10 @@ touch_events.clear(); // Fuchsia CHANGE, no grant result - buffer it. - events = TouchEventBuilder() - .AddTime(2222000u) - .AddSample(kIxnOne, fup::EventPhase::CHANGE, {10.f, 10.f}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{2222000u}) + .SetPhase(fup::EventPhase::CHANGE) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1176,11 +1006,12 @@ touch_events.clear(); // Fuchsia result: ownership denied. Buffered pointers deleted. - events = TouchEventBuilder() - .AddTime(3333000u) - .AddSample(kIxnOne, fup::EventPhase::CANCEL, {10.f, 10.f}) - .AddResult({kIxnOne, fup::TouchInteractionStatus::DENIED}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>( + TouchEventBuilder() + .SetTime(zx::time{3333000u}) + .SetPhase(fup::EventPhase::CANCEL) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::DENIED) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1200,18 +1031,17 @@ .device_id = 1u, .pointer_id = 2u, .interaction_id = 2u}; // Fuchsia ptr1 ADD and ptr2 ADD, no grant result for either - buffer them. - std::vector<fup::TouchEvent> events = - TouchEventBuilder() - .AddTime(1111000u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fup::EventPhase::ADD, {10.f, 10.f}) - .BuildAsVector(); - fup::TouchEvent ptr2 = - TouchEventBuilder() - .AddTime(1111000u) - .AddSample(kIxnTwo, fup::EventPhase::ADD, {15.f, 15.f}) - .Build(); - events.emplace_back(std::move(ptr2)); + std::vector events = + MakeVector<fup::TouchEvent>(TouchEventBuilder() + .SetTime(zx::time{1111000u}) + .SetPhase(fup::EventPhase::ADD) + .Build(), + TouchEventBuilder() + .SetTime(zx::time{1111000u}) + .SetId(kIxnTwo) + .SetPhase(fup::EventPhase::ADD) + .SetPosition({15.f, 15.f}) + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1219,10 +1049,13 @@ touch_events.clear(); // Server grants win to pointer 2. - events = TouchEventBuilder() - .AddTime(2222000u) - .AddResult({kIxnTwo, fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>( + TouchEventBuilder() + .SetTime(zx::time{2222000u}) + .SetId(kIxnTwo) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .WithoutSample() + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle(); @@ -1232,10 +1065,12 @@ touch_events.clear(); // Server grants win to pointer 1. - events = TouchEventBuilder() - .AddTime(3333000u) - .AddResult({kIxnOne, fup::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + events = MakeVector<fup::TouchEvent>( + TouchEventBuilder() + .SetTime(zx::time{3333000u}) + .SetTouchInteractionStatus(fup::TouchInteractionStatus::GRANTED) + .WithoutSample() + .Build()); touch_source_->ScheduleCallback(std::move(events)); RunLoopUntilIdle();
diff --git a/ui/events/gesture_detection/gesture_touch_uma_histogram.cc b/ui/events/gesture_detection/gesture_touch_uma_histogram.cc index e6108758..c2afb41 100644 --- a/ui/events/gesture_detection/gesture_touch_uma_histogram.cc +++ b/ui/events/gesture_detection/gesture_touch_uma_histogram.cc
@@ -4,6 +4,8 @@ #include "ui/events/gesture_detection/gesture_touch_uma_histogram.h" +#include <ostream> + #include "base/metrics/histogram_macros.h" #include "base/notreached.h"
diff --git a/ui/events/ozone/device/device_manager_manual.cc b/ui/events/ozone/device/device_manager_manual.cc index 379c72b..65871a1 100644 --- a/ui/events/ozone/device/device_manager_manual.cc +++ b/ui/events/ozone/device/device_manager_manual.cc
@@ -11,7 +11,6 @@ #include "base/logging.h" #include "base/observer_list.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/thread_pool.h" #include "ui/events/ozone/device/device_event.h" #include "ui/events/ozone/device/device_event_observer.h" @@ -64,8 +63,8 @@ } void DeviceManagerManual::StartWatching() { - base::PostTaskAndReplyWithResult( - blocking_task_runner_.get(), FROM_HERE, + blocking_task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce( &base::FilePathWatcher::Watch, base::Unretained(watcher_.get()), base::FilePath(kDevInput), base::FilePathWatcher::Type::kNonRecursive,
diff --git a/ui/gfx/color_conversion_sk_filter_cache.cc b/ui/gfx/color_conversion_sk_filter_cache.cc index 4a489d1..d15aa88 100644 --- a/ui/gfx/color_conversion_sk_filter_cache.cc +++ b/ui/gfx/color_conversion_sk_filter_cache.cc
@@ -100,6 +100,8 @@ float dst_max_luminance_relative, bool enable_tone_mapping, GrDirectContext* context) { + DCHECK(image); + DCHECK(target_color_space); sk_sp<SkColorSpace> image_sk_color_space = image->refColorSpace(); if (!image_sk_color_space) return image->makeColorSpace(target_color_space, context);
diff --git a/ui/gfx/image/image.cc b/ui/gfx/image/image.cc index cdb0f1a..f03a3534 100644 --- a/ui/gfx/image/image.cc +++ b/ui/gfx/image/image.cc
@@ -6,6 +6,7 @@ #include <algorithm> #include <map> +#include <ostream> #include <utility> #include <vector>
diff --git a/ui/gl/BUILD.gn b/ui/gl/BUILD.gn index 0a44499..666e2c2 100644 --- a/ui/gl/BUILD.gn +++ b/ui/gl/BUILD.gn
@@ -636,12 +636,6 @@ "//third_party/mesa_headers", ] - # TODO(https://crbug.com/789065): this must be moved to Ozone. - if (ozone_platform_x11) { - sources += [ "gl_context_glx_unittest.cc" ] - deps += [ "//ui/gfx/x" ] - } - if (is_win) { deps += [ "//media/base/win:test_support" ] libs = [ "dxguid.lib" ]
diff --git a/ui/gl/gl_context_glx_unittest.cc b/ui/gl/gl_context_glx_unittest.cc deleted file mode 100644 index a929c42..0000000 --- a/ui/gl/gl_context_glx_unittest.cc +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/gl/gl_context_glx.h" - -#include "base/memory/scoped_refptr.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/x/connection.h" -#include "ui/gfx/x/future.h" -#include "ui/gfx/x/xproto.h" -#include "ui/gl/gl_bindings.h" -#include "ui/gl/gl_surface_glx_x11.h" -#include "ui/gl/init/gl_factory.h" -#include "ui/gl/test/gl_image_test_support.h" - -namespace gl { - -#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \ - defined(THREAD_SANITIZER) -// https://crbug.com/830653 -#define MAYBE_DoNotDestroyOnFailedMakeCurrent \ - DISABLED_DoNotDestroyOnFailedMakeCurrent -#else -#define MAYBE_DoNotDestroyOnFailedMakeCurrent DoNotDestroyOnFailedMakeCurrent -#endif - -TEST(GLContextGLXTest, MAYBE_DoNotDestroyOnFailedMakeCurrent) { - auto* connection = x11::Connection::Get(); - ASSERT_TRUE(connection && connection->Ready()); - - auto xwindow = connection->GenerateId<x11::Window>(); - connection->CreateWindow({ - .wid = xwindow, - .parent = connection->default_root(), - .width = 10, - .height = 10, - .c_class = x11::WindowClass::InputOutput, - .background_pixmap = x11::Pixmap::None, - .override_redirect = x11::Bool32(true), - }); - - connection->MapWindow({xwindow}); - // Since this window is override-redirect, syncing is sufficient - // to ensure the map is complete. - connection->Sync(); - - GLImageTestSupport::InitializeGL(absl::nullopt); - auto surface = gl::InitializeGLSurface(base::MakeRefCounted<GLSurfaceGLXX11>( - static_cast<gfx::AcceleratedWidget>(xwindow))); - scoped_refptr<GLContext> context = - gl::init::CreateGLContext(nullptr, surface.get(), GLContextAttribs()); - - // Verify that MakeCurrent() is successful. - ASSERT_TRUE(context->GetHandle()); - ASSERT_TRUE(context->MakeCurrent(surface.get())); - EXPECT_TRUE(context->GetHandle()); - - context->ReleaseCurrent(surface.get()); - connection->DestroyWindow({xwindow}); - // Since this window is override-redirect, syncing is sufficient - // to ensure the window is destroyed and unmapped. - connection->Sync(); - ASSERT_TRUE(connection->Ready()); - - if (context->MakeCurrent(surface.get())) { - // With some drivers, MakeCurrent() does not fail for an already-destroyed - // window. In those cases, override the glx api to force MakeCurrent() to - // fail. - context->ReleaseCurrent(surface.get()); - auto real_fn = g_driver_glx.fn.glXMakeContextCurrentFn; - g_driver_glx.fn.glXMakeContextCurrentFn = - [](Display* display, GLXDrawable drawable, GLXDrawable read, - GLXContext context) -> int { return 0; }; - EXPECT_FALSE(context->MakeCurrent(surface.get())); - g_driver_glx.fn.glXMakeContextCurrentFn = real_fn; - } - // At this point, MakeCurrent() failed. Make sure the GLContextGLX still was - // not destroyed. - ASSERT_TRUE(context->GetHandle()); - surface = nullptr; - connection->Sync(); - connection->events().clear(); -} - -} // namespace gl
diff --git a/ui/gl/gl_image_native_pixmap_unittest.cc b/ui/gl/gl_image_native_pixmap_unittest.cc index df01dca..dc65e52 100644 --- a/ui/gl/gl_image_native_pixmap_unittest.cc +++ b/ui/gl/gl_image_native_pixmap_unittest.cc
@@ -32,17 +32,6 @@ template <gfx::BufferFormat format> class GLImageNativePixmapTestDelegate : public GLImageTestDelegateBase { public: - absl::optional<GLImplementationParts> GetPreferedGLImplementation() - const override { -#if BUILDFLAG(IS_WIN) - return absl::optional<GLImplementationParts>(GLImplementationParts( - kGLImplementationEGLANGLE, ANGLEImplementation::kNone)); -#else - return absl::optional<GLImplementationParts>( - GLImplementationParts(kGLImplementationEGLGLES2)); -#endif - } - bool SkipTest(GLDisplay* display) const override { GLDisplayEGL* display_egl = static_cast<GLDisplayEGL*>(display); if (!display_egl->ext->b_EGL_MESA_image_dma_buf_export) {
diff --git a/ui/ozone/platform/flatland/flatland_window_unittest.cc b/ui/ozone/platform/flatland/flatland_window_unittest.cc index b1c1b5b..7a581ca 100644 --- a/ui/ozone/platform/flatland/flatland_window_unittest.cc +++ b/ui/ozone/platform/flatland/flatland_window_unittest.cc
@@ -156,20 +156,13 @@ EXPECT_EQ(event->AsTouchEvent()->location_f().y(), kLocationY); event_received = true; }); - constexpr std::array<std::array<float, 2>, 2> kRect = {{{0, 0}, {20, 20}}}; - constexpr std::array<float, 9> kIdentity = {1, 0, 0, 0, 1, 0, 0, 0, 1}; - constexpr fuchsia::ui::pointer::TouchInteractionId kIxnOne = { - .device_id = 1u, .pointer_id = 1u, .interaction_id = 2u}; - std::vector<fuchsia::ui::pointer::TouchEvent> events = + std::vector<fuchsia::ui::pointer::TouchEvent> events; + events.push_back( TouchEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fuchsia::ui::pointer::EventPhase::ADD, - {kLocationX, kLocationY}) - .AddResult( - {.interaction = kIxnOne, - .status = fuchsia::ui::pointer::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + .SetPosition({kLocationX, kLocationY}) + .SetTouchInteractionStatus( + fuchsia::ui::pointer::TouchInteractionStatus::GRANTED) + .Build()); fake_touch_source_.ScheduleCallback(std::move(events)); task_environment_.RunUntilIdle(); EXPECT_TRUE(event_received); @@ -189,16 +182,13 @@ EXPECT_EQ(event->AsTouchEvent()->location_f().y(), kLocationY * kDPR); event_received = true; }); - events = + events.clear(); + events.push_back( TouchEventBuilder() - .AddTime(1111789u) - .AddViewParameters(kRect, kRect, kIdentity) - .AddSample(kIxnOne, fuchsia::ui::pointer::EventPhase::ADD, - {kLocationX, kLocationY}) - .AddResult( - {.interaction = kIxnOne, - .status = fuchsia::ui::pointer::TouchInteractionStatus::GRANTED}) - .BuildAsVector(); + .SetPosition({kLocationX, kLocationY}) + .SetTouchInteractionStatus( + fuchsia::ui::pointer::TouchInteractionStatus::GRANTED) + .Build()); fake_touch_source_.ScheduleCallback(std::move(events)); task_environment_.RunUntilIdle(); EXPECT_TRUE(event_received);
diff --git a/ui/ozone/platform/wayland/test/test_selection_device_manager.cc b/ui/ozone/platform/wayland/test/test_selection_device_manager.cc index c32c8f7..17c7731 100644 --- a/ui/ozone/platform/wayland/test/test_selection_device_manager.cc +++ b/ui/ozone/platform/wayland/test/test_selection_device_manager.cc
@@ -16,7 +16,6 @@ #include "base/logging.h" #include "base/notreached.h" #include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "ui/ozone/platform/wayland/test/server_object.h" @@ -106,9 +105,8 @@ // 2. Schedule the ReadDataOnWorkerThread task. The result of read // operation will be then passed in to the callback requested by the caller. - base::PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(&ReadDataOnWorkerThread, std::move(read_fd)), + task_runner_->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&ReadDataOnWorkerThread, std::move(read_fd)), std::move(callback)); }
diff --git a/ui/ozone/platform/x11/BUILD.gn b/ui/ozone/platform/x11/BUILD.gn index 898f285..bd3c0c8 100644 --- a/ui/ozone/platform/x11/BUILD.gn +++ b/ui/ozone/platform/x11/BUILD.gn
@@ -16,8 +16,6 @@ "client_native_pixmap_factory_x11.h", "gl_egl_utility_x11.cc", "gl_egl_utility_x11.h", - "gl_ozone_glx.cc", - "gl_ozone_glx.h", "gl_surface_egl_readback_x11.cc", "gl_surface_egl_readback_x11.h", "hit_test_x11.cc",
diff --git a/ui/ozone/platform/x11/gl_ozone_glx.cc b/ui/ozone/platform/x11/gl_ozone_glx.cc deleted file mode 100644 index f8de6c9..0000000 --- a/ui/ozone/platform/x11/gl_ozone_glx.cc +++ /dev/null
@@ -1,139 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/x11/gl_ozone_glx.h" - -#include "base/command_line.h" -#include "build/build_config.h" -#include "ui/gl/gl_context.h" -#include "ui/gl/gl_context_glx.h" -#include "ui/gl/gl_gl_api_implementation.h" -#include "ui/gl/gl_glx_api_implementation.h" -#include "ui/gl/gl_surface_glx_x11.h" -#include "ui/gl/gl_utils.h" -#include "ui/ozone/platform/x11/native_pixmap_glx_binding.h" - -namespace ui { - -namespace { - -#if BUILDFLAG(IS_OPENBSD) -const char kGLLibraryName[] = "libGL.so"; -#else -const char kGLLibraryName[] = "libGL.so.1"; -#endif - -} // namespace - -gl::GLDisplay* GLOzoneGLX::InitializeGLOneOffPlatform( - uint64_t system_device_id) { - // TODO(https://crbug.com/1251724): GLSurfaceGLX::InitializeOneOff() - // should take |system_device_id| and return a GLDisplayX11. - if (!gl::GLSurfaceGLX::InitializeOneOff()) { - LOG(ERROR) << "GLSurfaceGLX::InitializeOneOff failed."; - return nullptr; - } - return gl::GetDisplayX11(system_device_id); -} - -bool GLOzoneGLX::InitializeStaticGLBindings( - const gl::GLImplementationParts& implementation) { - base::NativeLibrary library = nullptr; - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - - if (command_line->HasSwitch(switches::kTestGLLib)) - library = gl::LoadLibraryAndPrintError( - command_line->GetSwitchValueASCII(switches::kTestGLLib).c_str()); - - if (!library) - library = gl::LoadLibraryAndPrintError(kGLLibraryName); - - if (!library) - return false; - - gl::GLGetProcAddressProc get_proc_address = - reinterpret_cast<gl::GLGetProcAddressProc>( - base::GetFunctionPointerFromNativeLibrary(library, - "glXGetProcAddress")); - if (!get_proc_address) { - LOG(ERROR) << "glxGetProcAddress not found."; - base::UnloadNativeLibrary(library); - return false; - } - - gl::SetGLGetProcAddressProc(get_proc_address); - gl::AddGLNativeLibrary(library); - gl::SetGLImplementation(gl::kGLImplementationDesktopGL); - - gl::InitializeStaticGLBindingsGL(); - gl::InitializeStaticGLBindingsGLX(); - - return true; -} - -void GLOzoneGLX::SetDisabledExtensionsPlatform( - const std::string& disabled_extensions) { - gl::SetDisabledExtensionsGLX(disabled_extensions); -} - -bool GLOzoneGLX::InitializeExtensionSettingsOneOffPlatform( - gl::GLDisplay* display) { - return gl::InitializeExtensionSettingsOneOffGLX(); -} - -void GLOzoneGLX::ShutdownGL(gl::GLDisplay* display) { - gl::ClearBindingsGL(); - gl::ClearBindingsGLX(); -} - -bool GLOzoneGLX::CanImportNativePixmap() { - return false; -} - -std::unique_ptr<NativePixmapGLBinding> GLOzoneGLX::ImportNativePixmap( - scoped_refptr<gfx::NativePixmap> pixmap, - gfx::BufferFormat plane_format, - gfx::BufferPlane plane, - gfx::Size plane_size, - const gfx::ColorSpace& color_space, - GLenum target, - GLuint texture_id) { - return NativePixmapGLXBinding::Create(pixmap, plane_format, plane, plane_size, - target, texture_id); -} - -bool GLOzoneGLX::GetGLWindowSystemBindingInfo( - const gl::GLVersionInfo& gl_info, - gl::GLWindowSystemBindingInfo* info) { - return gl::GetGLWindowSystemBindingInfoGLX(gl_info, info); -} - -scoped_refptr<gl::GLContext> GLOzoneGLX::CreateGLContext( - gl::GLShareGroup* share_group, - gl::GLSurface* compatible_surface, - const gl::GLContextAttribs& attribs) { - return gl::InitializeGLContext(new gl::GLContextGLX(share_group), - compatible_surface, attribs); -} - -scoped_refptr<gl::GLSurface> GLOzoneGLX::CreateViewGLSurface( - gl::GLDisplay* display, - gfx::AcceleratedWidget window) { - return gl::InitializeGLSurface(new gl::GLSurfaceGLXX11(window)); -} - -scoped_refptr<gl::GLSurface> GLOzoneGLX::CreateSurfacelessViewGLSurface( - gl::GLDisplay* display, - gfx::AcceleratedWidget window) { - return nullptr; -} - -scoped_refptr<gl::GLSurface> GLOzoneGLX::CreateOffscreenGLSurface( - gl::GLDisplay* display, - const gfx::Size& size) { - return gl::InitializeGLSurface(new gl::UnmappedNativeViewGLSurfaceGLX(size)); -} - -} // namespace ui
diff --git a/ui/ozone/platform/x11/gl_ozone_glx.h b/ui/ozone/platform/x11/gl_ozone_glx.h deleted file mode 100644 index c036b3a8..0000000 --- a/ui/ozone/platform/x11/gl_ozone_glx.h +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_X11_GL_OZONE_GLX_H_ -#define UI_OZONE_PLATFORM_X11_GL_OZONE_GLX_H_ - -#include "ui/gl/gl_implementation.h" -#include "ui/ozone/public/gl_ozone.h" - -namespace ui { - -class GLOzoneGLX : public GLOzone { - public: - GLOzoneGLX() {} - - GLOzoneGLX(const GLOzoneGLX&) = delete; - GLOzoneGLX& operator=(const GLOzoneGLX&) = delete; - - ~GLOzoneGLX() override {} - - gl::GLDisplay* InitializeGLOneOffPlatform(uint64_t system_device_id) override; - bool InitializeStaticGLBindings( - const gl::GLImplementationParts& implementation) override; - void SetDisabledExtensionsPlatform( - const std::string& disabled_extensions) override; - bool InitializeExtensionSettingsOneOffPlatform( - gl::GLDisplay* display) override; - void ShutdownGL(gl::GLDisplay* display) override; - bool CanImportNativePixmap() override; - std::unique_ptr<NativePixmapGLBinding> ImportNativePixmap( - scoped_refptr<gfx::NativePixmap> pixmap, - gfx::BufferFormat plane_format, - gfx::BufferPlane plane, - gfx::Size plane_size, - const gfx::ColorSpace& color_space, - GLenum target, - GLuint texture_id) override; - bool GetGLWindowSystemBindingInfo( - const gl::GLVersionInfo& gl_info, - gl::GLWindowSystemBindingInfo* info) override; - scoped_refptr<gl::GLContext> CreateGLContext( - gl::GLShareGroup* share_group, - gl::GLSurface* compatible_surface, - const gl::GLContextAttribs& attribs) override; - scoped_refptr<gl::GLSurface> CreateViewGLSurface( - gl::GLDisplay* display, - gfx::AcceleratedWidget window) override; - scoped_refptr<gl::GLSurface> CreateSurfacelessViewGLSurface( - gl::GLDisplay* display, - gfx::AcceleratedWidget window) override; - scoped_refptr<gl::GLSurface> CreateOffscreenGLSurface( - gl::GLDisplay* display, - const gfx::Size& size) override; -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_X11_GL_OZONE_GLX_H_
diff --git a/ui/ozone/platform/x11/x11_surface_factory.cc b/ui/ozone/platform/x11/x11_surface_factory.cc index d38941d..d0cf654 100644 --- a/ui/ozone/platform/x11/x11_surface_factory.cc +++ b/ui/ozone/platform/x11/x11_surface_factory.cc
@@ -18,7 +18,6 @@ #include "ui/ozone/common/egl_util.h" #include "ui/ozone/common/gl_ozone_egl.h" #include "ui/ozone/common/native_pixmap_egl_binding.h" -#include "ui/ozone/platform/x11/gl_ozone_glx.h" #include "ui/ozone/platform/x11/gl_surface_egl_readback_x11.h" #include "ui/ozone/platform/x11/native_pixmap_egl_x11_binding.h" #include "ui/ozone/platform/x11/x11_canvas_surface.h" @@ -123,8 +122,7 @@ X11SurfaceFactory::X11SurfaceFactory( std::unique_ptr<x11::Connection> connection) - : glx_implementation_(std::make_unique<GLOzoneGLX>()), - egl_implementation_(std::make_unique<GLOzoneEGLX11>()), + : egl_implementation_(std::make_unique<GLOzoneEGLX11>()), connection_(std::move(connection)) {} X11SurfaceFactory::~X11SurfaceFactory() = default; @@ -132,7 +130,6 @@ std::vector<gl::GLImplementationParts> X11SurfaceFactory::GetAllowedGLImplementations() { return std::vector<gl::GLImplementationParts>{ - gl::GLImplementationParts(gl::kGLImplementationDesktopGL), gl::GLImplementationParts(gl::kGLImplementationEGLGLES2), gl::GLImplementationParts(gl::kGLImplementationEGLANGLE), gl::GLImplementationParts(gl::ANGLEImplementation::kSwiftShader)}; @@ -141,8 +138,6 @@ GLOzone* X11SurfaceFactory::GetGLOzone( const gl::GLImplementationParts& implementation) { switch (implementation.gl) { - case gl::kGLImplementationDesktopGL: - return glx_implementation_.get(); case gl::kGLImplementationEGLGLES2: case gl::kGLImplementationEGLANGLE: return egl_implementation_.get();
diff --git a/ui/ozone/platform/x11/x11_surface_factory.h b/ui/ozone/platform/x11/x11_surface_factory.h index 49ac851..3a44950 100644 --- a/ui/ozone/platform/x11/x11_surface_factory.h +++ b/ui/ozone/platform/x11/x11_surface_factory.h
@@ -57,7 +57,6 @@ gfx::NativePixmapHandle handle) override; private: - std::unique_ptr<GLOzone> glx_implementation_; std::unique_ptr<GLOzone> egl_implementation_; std::unique_ptr<x11::Connection> connection_;
diff --git a/ui/views/accessibility/view_accessibility.cc b/ui/views/accessibility/view_accessibility.cc index 0235363..d3791ee 100644 --- a/ui/views/accessibility/view_accessibility.cc +++ b/ui/views/accessibility/view_accessibility.cc
@@ -544,6 +544,11 @@ custom_data_.AddIntAttribute(ax::mojom::IntAttribute::kSetSize, set_size); } +void ViewAccessibility::ClearPosInSetOverride() { + custom_data_.RemoveIntAttribute(ax::mojom::IntAttribute::kPosInSet); + custom_data_.RemoveIntAttribute(ax::mojom::IntAttribute::kSetSize); +} + void ViewAccessibility::OverrideNextFocus(Widget* widget) { if (widget) next_focus_ = widget->GetWeakPtr();
diff --git a/ui/views/accessibility/view_accessibility.h b/ui/views/accessibility/view_accessibility.h index 517d81e2..993ececb 100644 --- a/ui/views/accessibility/view_accessibility.h +++ b/ui/views/accessibility/view_accessibility.h
@@ -218,6 +218,7 @@ // // Note that |pos_in_set| is one-based, i.e. it starts from 1 not 0. void OverridePosInSet(int pos_in_set, int set_size); + void ClearPosInSetOverride(); // Override the next or previous focused widget. Some assistive technologies, // such as screen readers, may utilize this information to transition focus
diff --git a/ui/views/controls/menu/menu_controller.cc b/ui/views/controls/menu/menu_controller.cc index 98091f3..b26a30ea 100644 --- a/ui/views/controls/menu/menu_controller.cc +++ b/ui/views/controls/menu/menu_controller.cc
@@ -78,10 +78,20 @@ using ui::OSExchangeData; +DEFINE_UI_CLASS_PROPERTY_TYPE(std::vector<views::ViewTracker>*) + namespace views { namespace { +// The menu controller manages the AX index attributes inside menu items. This +// property maintains a vector of menu children that were last assigned such +// attributes by MenuController::SetSelectionIndices() so that the controller +// can update them if children change via MenuController::MenuChildrenChanged(). +DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(std::vector<views::ViewTracker>, + kOrderedMenuChildren, + nullptr) + #if BUILDFLAG(IS_MAC) bool AcceleratorShouldCancelMenu(const ui::Accelerator& accelerator) { // Since AcceleratorShouldCancelMenu() is called quite early in key @@ -2256,6 +2266,10 @@ // Menu shouldn't be updated during drag operation. DCHECK(!active_mouse_view_tracker_->view()); + // If needed, refresh the AX index assignments. + if (item->GetProperty(kOrderedMenuChildren)) + SetSelectionIndices(item); + // If the current item or pending item is a descendant of the item // that changed, move the selection back to the changed item. const MenuItemView* ancestor = state_.item; @@ -2816,6 +2830,14 @@ } void MenuController::SetSelectionIndices(MenuItemView* parent) { + if (parent->GetProperty(kOrderedMenuChildren)) { + // Clear any old AX index assignments. + for (ViewTracker& item : *(parent->GetProperty(kOrderedMenuChildren))) { + if (item.view()) + item.view()->GetViewAccessibility().ClearPosInSetOverride(); + } + } + std::vector<View*> ordering; SubmenuView* const submenu = parent->GetSubmenu(); @@ -2835,6 +2857,10 @@ ordering.push_back(item); } + parent->SetProperty(kOrderedMenuChildren, + std::make_unique<std::vector<ViewTracker>>( + ordering.begin(), ordering.end())); + if (ordering.empty()) return;
diff --git a/ui/views/controls/menu/menu_controller_unittest.cc b/ui/views/controls/menu/menu_controller_unittest.cc index 878f267..23db180 100644 --- a/ui/views/controls/menu/menu_controller_unittest.cc +++ b/ui/views/controls/menu/menu_controller_unittest.cc
@@ -3182,6 +3182,69 @@ EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize)); } +TEST_F(MenuControllerTest, SetSelectionIndices_ChildrenChanged) { +#if BUILDFLAG(IS_WIN) + // TODO(crbug.com/1286137): This test is consistently failing on Win11. + if (base::win::OSInfo::GetInstance()->version() >= + base::win::Version::WIN11) { + GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater"; + } +#endif + AddButtonMenuItems(/*single_child=*/false); + MenuItemView* const item1 = menu_item()->GetSubmenu()->GetMenuItemAt(0); + MenuItemView* item2 = menu_item()->GetSubmenu()->GetMenuItemAt(1); + MenuItemView* const item3 = menu_item()->GetSubmenu()->GetMenuItemAt(2); + MenuItemView* const item4 = menu_item()->GetSubmenu()->GetMenuItemAt(3); + MenuItemView* const item5 = menu_item()->GetSubmenu()->GetMenuItemAt(4); + Button* const button1 = Button::AsButton(item5->children()[0]); + Button* const button2 = Button::AsButton(item5->children()[1]); + Button* const button3 = Button::AsButton(item5->children()[2]); + OpenMenu(menu_item()); + + auto expect_coordinates = [](View* v, absl::optional<int> pos, + absl::optional<int> size) { + ui::AXNodeData data; + v->GetViewAccessibility().GetAccessibleNodeData(&data); + if (pos.has_value()) { + EXPECT_EQ(pos.value(), + data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet)); + } else { + EXPECT_FALSE(data.HasIntAttribute(ax::mojom::IntAttribute::kPosInSet)); + } + if (size.has_value()) { + EXPECT_EQ(size.value(), + data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize)); + } else { + EXPECT_FALSE(data.HasIntAttribute(ax::mojom::IntAttribute::kSetSize)); + } + }; + + expect_coordinates(item1, 1, 7); + expect_coordinates(item2, 2, 7); + expect_coordinates(item3, 3, 7); + expect_coordinates(item4, 4, 7); + expect_coordinates(button1, 5, 7); + expect_coordinates(button2, 6, 7); + expect_coordinates(button3, 7, 7); + + // Simulate a menu model update. + item1->SetEnabled(false); + button1->SetEnabled(false); + MenuItemView* item6 = menu_item()->AppendMenuItem(6, u"Six"); + menu_item()->RemoveMenuItem(item2); + item2 = nullptr; + MenuChildrenChanged(menu_item()); + + // Verify that disabled menu items no longer have PosInSet or SetSize. + expect_coordinates(item1, absl::nullopt, absl::nullopt); + expect_coordinates(button1, absl::nullopt, absl::nullopt); + expect_coordinates(item3, 1, 5); + expect_coordinates(item4, 2, 5); + expect_coordinates(button2, 3, 5); + expect_coordinates(button3, 4, 5); + expect_coordinates(item6, 5, 5); +} + // Tests that a menu opened asynchronously, will notify its // MenuControllerDelegate when accessibility performs a do default action. TEST_F(MenuControllerTest, AccessibilityDoDefaultCallsAccept) {
diff --git a/ui/webui/resources/cr_components/help_bubble/help_bubble_mixin.ts b/ui/webui/resources/cr_components/help_bubble/help_bubble_mixin.ts index 7bf7b0e8..403b458 100644 --- a/ui/webui/resources/cr_components/help_bubble/help_bubble_mixin.ts +++ b/ui/webui/resources/cr_components/help_bubble/help_bubble_mixin.ts
@@ -117,10 +117,21 @@ * * * See README.md for full instructions. + * + * This method can be called multiple times to re-register the + * nativeId to a new element/selector. If the help bubble is already + * showing, the registration will fail and return null. If successful, + * this method returns the new controller. */ registerHelpBubble(nativeId: string, trackable: Trackable): - HelpBubbleController { - assert(!this.helpBubbleControllerById_.has(nativeId)); + HelpBubbleController|null { + if (this.helpBubbleControllerById_.has(nativeId)) { + const ctrl = this.helpBubbleControllerById_.get(nativeId); + if (ctrl && ctrl.isShowing()) { + return null; + } + this.unregisterHelpBubble(nativeId); + } const controller = new HelpBubbleController(nativeId, this.shadowRoot!); controller.track(trackable); @@ -135,6 +146,35 @@ } /** + * Unregisters a help bubble nativeId. + * + * This method will remove listeners, hide the help bubble if + * showing, and forget the nativeId. + */ + unregisterHelpBubble(nativeId: string): void { + const ctrl = this.helpBubbleControllerById_.get(nativeId); + if (ctrl && ctrl.hasAnchor()) { + this.onAnchorVisibilityChanged_(ctrl.getAnchor()!, false); + this.unobserveControllerAnchor_(ctrl); + } + this.helpBubbleControllerById_.delete(nativeId); + } + + private observeControllerAnchor_(controller: HelpBubbleController) { + assert(this.helpBubbleAnchorObserver_); + const anchor = controller.getAnchor(); + assert(anchor, 'Help bubble does not have anchor'); + this.helpBubbleAnchorObserver_.observe(anchor); + } + + private unobserveControllerAnchor_(controller: HelpBubbleController) { + assert(this.helpBubbleAnchorObserver_); + const anchor = controller.getAnchor(); + assert(anchor, 'Help bubble does not have anchor'); + this.helpBubbleAnchorObserver_.unobserve(anchor); + } + + /** * Returns whether any help bubble is currently showing in this * component. */ @@ -171,10 +211,14 @@ /** * Returns whether a help bubble can be shown * This requires: + * - the mixin is tracking this controller * - the controller is in a state to be shown, e.g. `.canShow()` * - no other showing bubbles are anchored to the same element */ canShowHelpBubble(controller: HelpBubbleController): boolean { + if (!this.helpBubbleControllerById_.has(controller.getNativeId())) { + return false; + } if (!controller.canShow()) { return false; } @@ -265,6 +309,9 @@ return true; } + /** + * This event is emitted by the mojo router + */ private onAnchorVisibilityChanged_( target: HTMLElement, isVisible: boolean) { const nativeId = target.dataset['nativeId']; @@ -281,13 +328,6 @@ /** * This event is emitted by the mojo router */ - private observeControllerAnchor_(controller: HelpBubbleController) { - assert(this.helpBubbleAnchorObserver_); - const anchor = controller.getAnchor(); - assert(anchor, 'Help bubble does not have anchor'); - this.helpBubbleAnchorObserver_.observe(anchor); - } - private onShowHelpBubble_(params: HelpBubbleParams): void { if (!this.helpBubbleControllerById_.has(params.nativeIdentifier)) { // Identifier not handled by this mixin. @@ -365,10 +405,12 @@ export interface HelpBubbleMixinInterface { registerHelpBubble(nativeId: string, trackable: Trackable): - HelpBubbleController; + HelpBubbleController|null; + unregisterHelpBubble(nativeId: string): void; isHelpBubbleShowing(): boolean; isHelpBubbleShowingForTesting(id: string): boolean; getHelpBubbleForTesting(id: string): HelpBubbleElement|null; + canShowHelpBubble(controller: HelpBubbleController): boolean; showHelpBubble(controller: HelpBubbleController, params: HelpBubbleParams): void; hideHelpBubble(nativeId: string): boolean;