diff --git a/BUILD.gn b/BUILD.gn index 309939b..7291569 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -1029,6 +1029,7 @@ "//testing/buildbot/filters:blink_web_tests_filter", "//third_party/blink/public:blink_devtools_frontend_resources_files", "//third_party/blink/public/mojom:mojom_platform_js_data_deps", + "//third_party/blink/renderer/core/script:js_files_for_web_tests", "//third_party/mesa_headers", "//tools/imagediff", ]
diff --git a/DEPS b/DEPS index 0fc4269..5a1b8b2 100644 --- a/DEPS +++ b/DEPS
@@ -142,11 +142,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': 'abb5a315af45cdfc13fbe71265e8630041f8d845', + 'skia_revision': '4e6a4416e5df9dd16d2d39172511a6d45cc86e35', # 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': 'ffcc6abeb7796e08165267d860887e8fe865f233', + 'v8_revision': 'e545aee43105b9d8278377f25c4b23a62a1282c5', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -154,7 +154,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '69e46a186bb75d4e1120cd671c31e187b22741d0', + 'angle_revision': '8db211bc8d28156af958549c0d8a2669db87936a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -162,14 +162,14 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': '5fcd7aab39b8afacd2260b4f0448a6ef7efe02fd', + 'pdfium_revision': '9231ac5e1c6884555571fa2541fcbc10ff97a180', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. # # Note this revision should be updated with # third_party/boringssl/roll_boringssl.py, not roll-dep. - 'boringssl_revision': 'cfcb0060e8b8fba92d275fa4ac27d369890ea9bf', + 'boringssl_revision': '09050cb498336655883157c6e6055db9e5542857', # 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. @@ -205,7 +205,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '5cc5f6ebf6015e0b69d04148f07aa33abe8a4b76', + 'catapult_revision': '3efcccc6e77a54776a37f796183aa92c575060b5', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -261,7 +261,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'spv_tools_revision': '0c4feb643b89d1792b02f7cbef315e9d95633bd7', + 'spv_tools_revision': '5081512502df32b38a38712adb0d8c1b23bb1c2e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -481,7 +481,7 @@ }, 'src/ios/third_party/material_components_ios/src': { - 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + '2801e6969bfd9d3e14e7496624ca3355225148df', + 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + 'a53be27c2404cae287275a99d88cd76d997ceab5', 'condition': 'checkout_ios', }, @@ -806,7 +806,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'a9ca4d92eba0effcf4cab93d6d8e6019696321d3', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '9ec162df61d3ff15a3913c5f616d5de538b82369', 'condition': 'checkout_linux', }, @@ -831,7 +831,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '3b07526aec5572513374e26191e83d367a6e1f7b', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '78dec0421b6903c0d260d51aff69d6b7ebf09781', 'src/third_party/devtools-node-modules': Var('chromium_git') + '/external/github.com/ChromeDevTools/devtools-node-modules' + '@' + Var('devtools_node_modules_revision'), @@ -900,7 +900,7 @@ }, 'src/third_party/glslang/src': - Var('chromium_git') + '/external/github.com/KhronosGroup/glslang.git' + '@' + '8aa9a7bb8f74869ab9cfd2c9bd51cef1741004e7', + Var('chromium_git') + '/external/github.com/KhronosGroup/glslang.git' + '@' + 'c538b5d796fb24dd418fdd650c7f76e56bcc3dd8', 'src/third_party/google_toolbox_for_mac/src': { 'url': Var('chromium_git') + '/external/github.com/google/google-toolbox-for-mac.git' + '@' + Var('google_toolbox_for_mac_revision'), @@ -1191,7 +1191,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'be75ef60754c71b59dfdce43ece95f77aaed93ab', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '67a281286c52bd9eb4158d0d66c33acb162e67d9', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1359,7 +1359,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '91350f8ecf9ab2922ee062c114e4a759f24bd8d0', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '41300af8768cdbd9cd1785b3ecb0767ca6a43aba', + Var('webrtc_git') + '/src.git' + '@' + 'ca160215c9d1f3fdb26cef072c01f12cd8b02fe6', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1400,7 +1400,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@9b7fc04d3edb6ecbb43ab899d269a90d749cecf5', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@3bf592f177c2a2dc1b7629b1853a7a04f7d06516', 'condition': 'checkout_src_internal', },
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index fda251c5..e005b27 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -1007,7 +1007,7 @@ r'.*_ios\.(cc|h)$', r'^net[\\/].*\.(cc|h)$', r'.*[\\/]tools[\\/].*\.(cc|h)$', - r'^fuchsia/engine/web_engine_debug_integration_test\.cc$', + r'^fuchsia/engine/test_devtools_list_fetcher\.cc$', ), ), (
diff --git a/android_webview/browser/aw_content_browser_client.cc b/android_webview/browser/aw_content_browser_client.cc index 0c1fe766..7108a196 100644 --- a/android_webview/browser/aw_content_browser_client.cc +++ b/android_webview/browser/aw_content_browser_client.cc
@@ -1103,6 +1103,24 @@ return true; } +void AwContentBrowserClient::WillCreateURLLoaderFactoryForAppCacheSubresource( + int render_process_id, + network::mojom::URLLoaderFactoryPtrInfo* factory_ptr_info) { + DCHECK(base::FeatureList::IsEnabled(network::features::kNetworkService)); + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + auto proxied_ptr_info = std::move(*factory_ptr_info); + network::mojom::URLLoaderFactoryRequest factory_request = + mojo::MakeRequest(factory_ptr_info); + + base::PostTaskWithTraits( + FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&AwProxyingURLLoaderFactory::CreateProxy, + render_process_id, std::move(factory_request), + std::move(proxied_ptr_info), + nullptr /* AwInterceptedRequestHandler */)); +} + uint32_t AwContentBrowserClient::GetWebSocketOptions( content::RenderFrameHost* frame) { uint32_t options = network::mojom::kWebSocketOptionNone;
diff --git a/android_webview/browser/aw_content_browser_client.h b/android_webview/browser/aw_content_browser_client.h index 40b503d..1adc645 100644 --- a/android_webview/browser/aw_content_browser_client.h +++ b/android_webview/browser/aw_content_browser_client.h
@@ -241,6 +241,9 @@ network::mojom::URLLoaderFactoryRequest* factory_request, network::mojom::TrustedURLLoaderHeaderClientPtrInfo* header_client, bool* bypass_redirect_checks) override; + void WillCreateURLLoaderFactoryForAppCacheSubresource( + int render_process_id, + network::mojom::URLLoaderFactoryPtrInfo* factory_ptr_info) override; uint32_t GetWebSocketOptions(content::RenderFrameHost* frame) override; bool WillCreateRestrictedCookieManager( content::BrowserContext* browser_context,
diff --git a/android_webview/browser/net/aw_url_request_context_getter.cc b/android_webview/browser/net/aw_url_request_context_getter.cc index b5a47ad5..95c7541 100644 --- a/android_webview/browser/net/aw_url_request_context_getter.cc +++ b/android_webview/browser/net/aw_url_request_context_getter.cc
@@ -247,7 +247,7 @@ file_net_log_observer_ = net::FileNetLogObserver::CreateUnbounded( net_log_path, std::move(constants_dict)); file_net_log_observer_->StartObserving(net_log_, - net::NetLogCaptureMode::Default()); + net::NetLogCaptureMode::kDefault); } }
diff --git a/android_webview/common/aw_switches.cc b/android_webview/common/aw_switches.cc index d25da65..b0366d1 100644 --- a/android_webview/common/aw_switches.cc +++ b/android_webview/common/aw_switches.cc
@@ -10,10 +10,6 @@ const char kWebViewSandboxedRenderer[] = "webview-sandboxed-renderer"; -// used to enable safebrowsing functionality in webview -const char kWebViewEnableSafeBrowsingSupport[] = - "webview-enable-safebrowsing-support"; - // used to disable safebrowsing functionality in webview const char kWebViewDisableSafeBrowsingSupport[] = "webview-disable-safebrowsing-support";
diff --git a/android_webview/common/aw_switches.h b/android_webview/common/aw_switches.h index cef6970..d0156c0 100644 --- a/android_webview/common/aw_switches.h +++ b/android_webview/common/aw_switches.h
@@ -9,7 +9,6 @@ extern const char kWebViewLogJsConsoleMessages[]; extern const char kWebViewSandboxedRenderer[]; -extern const char kWebViewEnableSafeBrowsingSupport[]; extern const char kWebViewDisableSafeBrowsingSupport[]; extern const char kWebViewEnableSharedImage[]; extern const char kWebViewEnableVulkan[];
diff --git a/android_webview/java/src/org/chromium/android_webview/AwSwitches.java b/android_webview/java/src/org/chromium/android_webview/AwSwitches.java index e3c9193..f8989743 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwSwitches.java +++ b/android_webview/java/src/org/chromium/android_webview/AwSwitches.java
@@ -17,11 +17,6 @@ // Native switch kWebViewSandboxedRenderer. public static final String WEBVIEW_SANDBOXED_RENDERER = "webview-sandboxed-renderer"; - // Enables safebrowsing functionality in webview. - // Native switch kWebViewEnableSafeBrowsingSupport. - public static final String WEBVIEW_ENABLE_SAFEBROWSING_SUPPORT = - "webview-enable-safebrowsing-support"; - // Disables safebrowsing functionality in webview. // Native switch kWebViewDisableSafeBrowsingSupport. public static final String WEBVIEW_DISABLE_SAFEBROWSING_SUPPORT =
diff --git a/android_webview/lib/aw_main_delegate.cc b/android_webview/lib/aw_main_delegate.cc index d70107b..e0929a1 100644 --- a/android_webview/lib/aw_main_delegate.cc +++ b/android_webview/lib/aw_main_delegate.cc
@@ -204,6 +204,10 @@ // Network service for WebView is still being evaluated. Once enabled // by default the following line can be deleted. features.DisableIfNotSet(network::features::kNetworkService); + + // TODO(https://crbug.com/963653): SmsReceiver is not yet supported on + // WebView. + features.DisableIfNotSet(features::kSmsReceiver); } android_webview::RegisterPathProvider();
diff --git a/android_webview/tools/system_webview_shell/test/data/webexposed/not-webview-exposed.txt b/android_webview/tools/system_webview_shell/test/data/webexposed/not-webview-exposed.txt index 4d7e2ce..569f99e3 100644 --- a/android_webview/tools/system_webview_shell/test/data/webexposed/not-webview-exposed.txt +++ b/android_webview/tools/system_webview_shell/test/data/webexposed/not-webview-exposed.txt
@@ -54,12 +54,14 @@ getter remote # crbug.com/521319 # permissions API (crbug.com/490120), presentation API (crbug.com/521319), -# share API (crbug.com/765923), custom scheme handlers (crbug.com/589502) -# and media session API (crbug.com/925997) are not supported in webview. +# share API (crbug.com/765923), custom scheme handlers (crbug.com/589502), +# media session API (crbug.com/925997), and sms API (crbug.com/963653) +# are not supported in webview. interface Navigator getter mediaSession # crbug.com/925997 getter permissions # crbug.com/490120 getter presentation # crbug.com/521319 + getter sms # crbug.com/963653 method registerProtocolHandler # crbug.com/589502 method unregisterProtocolHandler # crbug.com/589502 method share # crbug.com/765923 @@ -68,6 +70,10 @@ interface MediaMetadata interface MediaSession +# SMS API is disabled in Android WebView, (crbug.com/963653) +interface SMS +interface SMSReceiver + # notifications not yet supported in webview, crbug.com/551446 interface ServiceWorkerRegistration : EventTarget getter pushManager
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index f5d3487b..11baf96 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -82,7 +82,6 @@ "wm/splitview/split_view_controller.h", "wm/tablet_mode/tablet_mode_browser_window_drag_delegate.h", "wm/tablet_mode/tablet_mode_controller.h", - "wm/tablet_mode/tablet_mode_observer.h", "wm/tablet_mode/tablet_mode_window_drag_controller.h", "wm/tablet_mode/tablet_mode_window_drag_delegate.h", "wm/window_positioner.h", @@ -1127,6 +1126,8 @@ "wm/overview/overview_delegate.h", "wm/overview/overview_grid.cc", "wm/overview/overview_grid.h", + "wm/overview/overview_highlight_controller.cc", + "wm/overview/overview_highlight_controller.h", "wm/overview/overview_item.cc", "wm/overview/overview_item.h", "wm/overview/overview_observer.h", @@ -1520,6 +1521,8 @@ "//chromeos/dbus", "//chromeos/dbus/biod", "//chromeos/dbus/power", + "//chromeos/services/network_config/public/cpp:manifest", + "//chromeos/services/network_config/public/cpp:test_support", "//chromeos/system", "//components/discardable_memory/public/interfaces", "//components/services/font:lib", @@ -1640,7 +1643,6 @@ "keyboard/keyboard_controller_impl_unittest.cc", "keyboard/virtual_keyboard_controller_unittest.cc", "keyboard/virtual_keyboard_unittest.cc", - "kiosk_next/kiosk_next_shell_controller_unittest.cc", "kiosk_next/kiosk_next_shell_test_util.cc", "kiosk_next/kiosk_next_shell_test_util.h", "kiosk_next/mock_kiosk_next_shell_client.cc",
diff --git a/ash/accelerometer/accelerometer_reader.cc b/ash/accelerometer/accelerometer_reader.cc index 10a76de..cd99f380 100644 --- a/ash/accelerometer/accelerometer_reader.cc +++ b/ash/accelerometer/accelerometer_reader.cc
@@ -10,9 +10,9 @@ #include <string> #include <vector> +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/shell.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/bind.h" #include "base/files/file_enumerator.h" #include "base/files/file_util.h"
diff --git a/ash/accessibility/accessibility_controller_impl.h b/ash/accessibility/accessibility_controller_impl.h index 1d64890..3a065c9a 100644 --- a/ash/accessibility/accessibility_controller_impl.h +++ b/ash/accessibility/accessibility_controller_impl.h
@@ -10,8 +10,8 @@ #include "ash/ash_export.h" #include "ash/public/cpp/accessibility_controller.h" #include "ash/public/cpp/ash_constants.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/session/session_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" #include "base/observer_list.h" #include "base/time/time.h"
diff --git a/ash/accessibility/accessibility_layer.cc b/ash/accessibility/accessibility_layer.cc index 230d4ba..5f37048 100644 --- a/ash/accessibility/accessibility_layer.cc +++ b/ash/accessibility/accessibility_layer.cc
@@ -52,9 +52,12 @@ ui::Layer* root_layer = root_window->layer(); layer_ = std::make_unique<ui::Layer>(ui::LAYER_TEXTURED); layer_->set_name(layer_name); - layer_->set_delegate(this); layer_->SetFillsBoundsOpaquely(false); root_layer->Add(layer_.get()); + // Adding |layer_| to |root_layer| will trigger a DeviceScaleFactorChanged. + // AccessibilityFocusRingControllerImpl doesn't need to react to this + // initial DSF change, so set the delegate after Add(). + layer_->set_delegate(this); } // Keep moving it to the top in case new layers have been added
diff --git a/ash/app_list/BUILD.gn b/ash/app_list/BUILD.gn index 8e140d5..ccc17dc 100644 --- a/ash/app_list/BUILD.gn +++ b/ash/app_list/BUILD.gn
@@ -108,7 +108,6 @@ "//ash/assistant/util", "//ash/keyboard/ui", "//ash/public/cpp/app_list/vector_icons", - "//ash/public/cpp/vector_icons", "//ash/resources/vector_icons", "//ash/strings", "//base",
diff --git a/ash/app_list/app_list_controller_impl.cc b/ash/app_list/app_list_controller_impl.cc index a74ba69..c3f38bd 100644 --- a/ash/app_list/app_list_controller_impl.cc +++ b/ash/app_list/app_list_controller_impl.cc
@@ -588,6 +588,10 @@ return model_->state_fullscreen(); } +void AppListControllerImpl::OnShelfAlignmentChanged(aura::Window* root_window) { + DismissAppList(); +} + void AppListControllerImpl::OnShellDestroying() { // Stop observing at the beginning of ~Shell to avoid unnecessary work during // Shell shutdown.
diff --git a/ash/app_list/app_list_controller_impl.h b/ash/app_list/app_list_controller_impl.h index c1fcdfe..7a587c1 100644 --- a/ash/app_list/app_list_controller_impl.h +++ b/ash/app_list/app_list_controller_impl.h
@@ -25,13 +25,13 @@ #include "ash/public/cpp/assistant/default_voice_interaction_observer.h" #include "ash/public/cpp/keyboard/keyboard_controller_observer.h" #include "ash/public/cpp/shelf_types.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/public/cpp/wallpaper_controller_observer.h" #include "ash/public/interfaces/voice_interaction_controller.mojom.h" #include "ash/session/session_observer.h" #include "ash/shell_observer.h" #include "ash/wm/mru_window_tracker.h" #include "ash/wm/overview/overview_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/observer_list.h" #include "components/sync/model/string_ordinal.h" @@ -216,6 +216,7 @@ void NotifyAppListTargetVisibilityChanged(bool visible); // ShellObserver: + void OnShelfAlignmentChanged(aura::Window* root_window) override; void OnShellDestroying() override; // OverviewObserver:
diff --git a/ash/app_list/app_list_controller_impl_unittest.cc b/ash/app_list/app_list_controller_impl_unittest.cc index 4a29505..1137eb6 100644 --- a/ash/app_list/app_list_controller_impl_unittest.cc +++ b/ash/app_list/app_list_controller_impl_unittest.cc
@@ -16,6 +16,7 @@ #include "ash/ime/test_ime_controller_client.h" #include "ash/keyboard/keyboard_controller_impl.h" #include "ash/public/cpp/presentation_time_recorder.h" +#include "ash/public/cpp/shelf_types.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" @@ -105,6 +106,23 @@ DISALLOW_COPY_AND_ASSIGN(AppListControllerImplTest); }; +// Tests that the AppList hides when shelf alignment changes. This necessary +// because the AppList is shown with certain assumptions based on shelf +// orientation. +TEST_F(AppListControllerImplTest, AppListHiddenWhenShelfAlignmentChanges) { + Shelf* const shelf = AshTestBase::GetPrimaryShelf(); + shelf->SetAlignment(ash::ShelfAlignment::SHELF_ALIGNMENT_BOTTOM); + + const std::vector<ash::ShelfAlignment> alignments( + {SHELF_ALIGNMENT_LEFT, SHELF_ALIGNMENT_RIGHT, SHELF_ALIGNMENT_BOTTOM}); + for (ash::ShelfAlignment alignment : alignments) { + ShowAppListNow(); + EXPECT_TRUE(Shell::Get()->app_list_controller()->presenter()->IsVisible()); + shelf->SetAlignment(alignment); + EXPECT_EQ(AppListViewState::kClosed, GetAppListView()->app_list_state()); + } +} + // Hide the expand arrow view in tablet mode when there is no activatable window // (see https://crbug.com/923089). TEST_F(AppListControllerImplTest, UpdateExpandArrowViewVisibility) {
diff --git a/ash/app_list/app_list_presenter_delegate_unittest.cc b/ash/app_list/app_list_presenter_delegate_unittest.cc index cb04194..c7a43dd0 100644 --- a/ash/app_list/app_list_presenter_delegate_unittest.cc +++ b/ash/app_list/app_list_presenter_delegate_unittest.cc
@@ -290,6 +290,32 @@ ->is_search_box_active()); } +// Tests that the SearchBox activation is reset after the AppList is hidden with +// no animation from FULLSCREEN_SEARCH. +TEST_F(AppListPresenterDelegateZeroStateTest, + SideShelfAppListResetsSearchBoxActivationOnClose) { + // Set the shelf to one side, then show the AppList and activate the + // searchbox. + SetShelfAlignment(ShelfAlignment::SHELF_ALIGNMENT_RIGHT); + GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId()); + GetEventGenerator()->GestureTapAt(GetPointInsideSearchbox()); + ASSERT_TRUE(GetAppListTestHelper() + ->GetAppListView() + ->search_box_view() + ->is_search_box_active()); + + // Dismiss the AppList using the controller, this is the same way we dismiss + // the AppList when a SearchResult is launched, and skips the + // FULLSCREEN_SEARCH -> FULLSCREEN_ALL_APPS transition. + Shell::Get()->app_list_controller()->DismissAppList(); + + // Test that the search box is not active. + EXPECT_FALSE(GetAppListTestHelper() + ->GetAppListView() + ->search_box_view() + ->is_search_box_active()); +} + // Verifies that tapping on the search box in tablet mode with animation and // zero state enabled should not bring Chrome crash (https://crbug.com/958267). TEST_F(AppListPresenterDelegateZeroStateTest, ClickSearchBoxInTabletMode) { @@ -1407,7 +1433,7 @@ GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId()); GetAppListTestHelper()->CheckState(AppListViewState::kPeeking); - // Drag AppListView upward by mouse. Before moving the mouse, AppListItems + // Drag AppListView upward by mouse. Before moving the mouse, AppsGridView // should be invisible. const gfx::Point start_point = GetAppListView()->GetBoundsInScreen().origin(); ui::test::EventGenerator* generator = GetEventGenerator(); @@ -1418,13 +1444,53 @@ ->contents_view() ->GetAppsContainerView() ->apps_grid_view(); - EXPECT_FALSE(apps_grid_view->view_model()->view_at(0)->GetVisible()); + EXPECT_FALSE(apps_grid_view->GetVisible()); // Verifies that the AppListView state after mouse drag should be // FullscreenAllApps. generator->MoveMouseBy(0, -start_point.y()); generator->ReleaseLeftButton(); GetAppListTestHelper()->CheckState(AppListViewState::kFullscreenAllApps); + EXPECT_TRUE(apps_grid_view->GetVisible()); +} + +// Verifies that mouse dragging AppListView causes to change the opacity. +TEST_F(AppListPresenterDelegateHomeLauncherTest, MouseDragAppListItemOpacity) { + std::unique_ptr<app_list::AppListItem> item( + new app_list::AppListItem("fake id")); + Shell::Get()->app_list_controller()->GetModel()->AddItem(std::move(item)); + + GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId()); + GetAppListTestHelper()->CheckState(AppListViewState::kPeeking); + + // Drag AppListView by mouse. Before moving the mouse, each AppListItem + // doesn't have its own layer. + const gfx::Point start_point = GetAppListView()->GetBoundsInScreen().origin(); + ui::test::EventGenerator* generator = GetEventGenerator(); + generator->MoveMouseTo(start_point); + generator->PressLeftButton(); + app_list::AppsGridView* apps_grid_view = GetAppListView() + ->app_list_main_view() + ->contents_view() + ->GetAppsContainerView() + ->apps_grid_view(); + views::View* item_view = apps_grid_view->view_model()->view_at(0); + EXPECT_FALSE(item_view->layer()); + + // Drags the mouse a bit above (twice as shelf's height). This should show the + // item vaguely. + const int shelf_height = + GetPrimaryShelf()->GetShelfViewForTesting()->height(); + generator->MoveMouseBy(0, -shelf_height * 2); + EXPECT_TRUE(item_view->layer()); + EXPECT_LE(0.f, item_view->layer()->opacity()); + EXPECT_GT(1.f, item_view->layer()->opacity()); + + // Finishes the drag to expand the app-list. Now the app-list item should be + // fully visible and does not need layer anymore. + generator->MoveMouseTo(start_point.x(), 0); + generator->ReleaseLeftButton(); + EXPECT_FALSE(item_view->layer()); } // Tests that the app list is shown automatically when the tablet mode is on.
diff --git a/ash/app_list/views/app_list_main_view.cc b/ash/app_list/views/app_list_main_view.cc index ae56668..d03b1e0 100644 --- a/ash/app_list/views/app_list_main_view.cc +++ b/ash/app_list/views/app_list_main_view.cc
@@ -85,9 +85,6 @@ AddChildView(contents_view_); search_box_view_->set_contents_view(contents_view_); - - // Clear the old query and start search. - search_box_view_->ClearSearch(); } void AppListMainView::ShowAppListWhenReady() {
diff --git a/ash/app_list/views/app_list_view.cc b/ash/app_list/views/app_list_view.cc index 5a1e47e..a53afef 100644 --- a/ash/app_list/views/app_list_view.cc +++ b/ash/app_list/views/app_list_view.cc
@@ -1004,11 +1004,6 @@ if (target_state == ash::AppListViewState::kHalf) return; - if (target_state == ash::AppListViewState::kClosed) { - app_list_main_view_->contents_view()->CancelDrag(); - return; - } - if (GetAppsContainerView()->IsInFolderView()) GetAppsContainerView()->ResetForShowApps(); @@ -1023,6 +1018,11 @@ pagination_model->SelectPage(0, false /* animate */); } } + if (target_state == ash::AppListViewState::kClosed && is_side_shelf_) { + // Reset the search box to be shown again. This is done after the animation + // is complete normally, but there is no animation when |is_side_shelf_|. + search_box_view_->ClearSearchAndDeactivateSearchBox(); + } } void AppListView::ConvertAppListStateToFullscreenEquivalent(
diff --git a/ash/app_list/views/apps_grid_view.cc b/ash/app_list/views/apps_grid_view.cc index beba1be..a7e05dd 100644 --- a/ash/app_list/views/apps_grid_view.cc +++ b/ash/app_list/views/apps_grid_view.cc
@@ -445,11 +445,6 @@ ClearDragState(); layer()->SetOpacity(1.0f); SetVisible(true); - // Set all views to visible in case they weren't made visible again by an - // incomplete animation. - for (int i = 0; i < view_model_.view_size(); ++i) { - view_model_.view_at(i)->SetVisible(true); - } // The number of non-page-break-items should be the same as item views. int item_count = 0; @@ -1000,10 +995,7 @@ const bool fullscreen_apps_in_drag = app_list_state == ash::AppListViewState::kFullscreenAllApps || is_in_drag; - for (int i = 0; i < view_model_.view_size(); ++i) { - AppListItemView* view = GetItemViewAt(i); - view->SetVisible(fullscreen_apps_in_drag); - } + SetVisible(fullscreen_apps_in_drag); } bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) { @@ -1971,10 +1963,6 @@ void AppsGridView::UpdateOpacity() { if (view_structure_.pages().empty()) return; - const int selected_page = pagination_model_.selected_page(); - auto current_page = view_structure_.pages()[selected_page]; - if (current_page.empty()) - return; // Updates the opacity of the apps in current page. The opacity of the app // starting at 0.f when the ceterline of the app is |kAllAppsOpacityStartPx| @@ -1984,11 +1972,15 @@ const bool should_restore_opacity = !app_list_view->is_in_drag() && (app_list_view->app_list_state() != ash::AppListViewState::kClosed); - float opacity = 1.f; - if (!should_restore_opacity) { - gfx::Rect view_bounds = current_page[0]->bounds(); + const int selected_page = pagination_model_.selected_page(); + auto current_page = view_structure_.pages()[selected_page]; + float centerline_above_work_area = 0.f; + float opacity = 0.f; + for (size_t i = 0; i < current_page.size(); i += cols_) { + AppListItemView* item_view = current_page[i]; + gfx::Rect view_bounds = item_view->bounds(); views::View::ConvertRectToScreen(this, &view_bounds); - float centerline_above_work_area = std::max<float>( + centerline_above_work_area = std::max<float>( app_list_view->GetScreenBottom() - view_bounds.CenterPoint().y(), 0.f); const float start_px = AppListConfig::instance().all_apps_opacity_start_px(); @@ -1998,9 +1990,27 @@ start_px), 0.f), 1.0f); + + opacity = should_restore_opacity ? 1.0f : opacity; + + const bool has_change = + ((opacity == 1.0f || opacity == 0.f) && item_view->layer()) || + (!item_view->layer() || opacity != item_view->layer()->opacity()); + if (!has_change) + continue; + + const size_t end_index = std::min(current_page.size() - 1, i + cols_ - 1); + for (size_t j = i; j <= end_index; ++j) { + if (current_page[j] != drag_view_) { + if (opacity == 1.0f) { + current_page[j]->DestroyLayer(); + } else { + current_page[j]->EnsureLayer(); + current_page[j]->layer()->SetOpacity(opacity); + } + } + } } - if (opacity != layer()->opacity()) - layer()->SetOpacity(opacity); } bool AppsGridView::HandleScrollFromAppListView(const gfx::Vector2d& offset, @@ -2564,12 +2574,6 @@ int model_index = GetTargetModelIndexFromItemIndex(index); view_model_.Add(view, model_index); AddChildViewAt(view, model_index); - - // Ensure that AppListItems that are added to the AppListItemList are not - // shown while in PEEKING. The visibility of the app icons will be updated - // on drag/animation from PEEKING. - view->SetVisible(model_->state_fullscreen() != - ash::AppListViewState::kPeeking); } if (!folder_delegate_)
diff --git a/ash/app_list/views/apps_grid_view.h b/ash/app_list/views/apps_grid_view.h index 5d94a6cc..5f012b9 100644 --- a/ash/app_list/views/apps_grid_view.h +++ b/ash/app_list/views/apps_grid_view.h
@@ -681,7 +681,7 @@ // This can be NULL. Only grid views inside folders have a folder delegate. AppsGridViewFolderDelegate* folder_delegate_ = nullptr; - ash::PaginationModel pagination_model_; + ash::PaginationModel pagination_model_{this}; // Must appear after |pagination_model_|. std::unique_ptr<ash::PaginationController> pagination_controller_;
diff --git a/ash/app_list/views/contents_view.cc b/ash/app_list/views/contents_view.cc index 0124008..7c8472f 100644 --- a/ash/app_list/views/contents_view.cc +++ b/ash/app_list/views/contents_view.cc
@@ -137,6 +137,9 @@ GetAppsContainerView()->UpdateSuggestionChips(); ActivePageChanged(); + + // Hide the search results initially. + ShowSearchResults(false); } void ContentsView::ResetForShow() {
diff --git a/ash/app_list/views/contents_view.h b/ash/app_list/views/contents_view.h index c97a09a..9c9a30c 100644 --- a/ash/app_list/views/contents_view.h +++ b/ash/app_list/views/contents_view.h
@@ -308,7 +308,7 @@ int page_before_assistant_ = 0; // Manages the pagination for the launcher pages. - ash::PaginationModel pagination_model_; + ash::PaginationModel pagination_model_{this}; // If true, SetActiveState immediately. bool set_active_state_without_animation_ = false;
diff --git a/ash/app_list/views/horizontal_page_container.h b/ash/app_list/views/horizontal_page_container.h index 2fad9ca..009c421 100644 --- a/ash/app_list/views/horizontal_page_container.h +++ b/ash/app_list/views/horizontal_page_container.h
@@ -77,7 +77,7 @@ gfx::Vector2d GetOffsetForPageIndex(int index) const; // Manages the pagination for the horizontal pages. - ash::PaginationModel pagination_model_; + ash::PaginationModel pagination_model_{this}; // Must appear after |pagination_model_|. std::unique_ptr<ash::PaginationController> pagination_controller_;
diff --git a/ash/app_list/views/search_box_view.cc b/ash/app_list/views/search_box_view.cc index 25a91bd..bb3e608 100644 --- a/ash/app_list/views/search_box_view.cc +++ b/ash/app_list/views/search_box_view.cc
@@ -24,8 +24,8 @@ #include "ash/public/cpp/app_list/app_list_config.h" #include "ash/public/cpp/app_list/app_list_features.h" #include "ash/public/cpp/app_list/vector_icons/vector_icons.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "ash/public/cpp/wallpaper_types.h" +#include "ash/resources/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h"
diff --git a/ash/app_list/views/search_result_list_view.cc b/ash/app_list/views/search_result_list_view.cc index 3a4fa016..32923c00 100644 --- a/ash/app_list/views/search_result_list_view.cc +++ b/ash/app_list/views/search_result_list_view.cc
@@ -16,7 +16,7 @@ #include "ash/public/cpp/app_list/app_list_config.h" #include "ash/public/cpp/app_list/app_list_features.h" #include "ash/public/cpp/app_list/vector_icons/vector_icons.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" +#include "ash/resources/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/time/time.h" #include "ui/events/event.h"
diff --git a/ash/display/display_configuration_observer.h b/ash/display/display_configuration_observer.h index 25833a72..e50dfe7 100644 --- a/ash/display/display_configuration_observer.h +++ b/ash/display/display_configuration_observer.h
@@ -7,7 +7,7 @@ #include "ash/ash_export.h" #include "ash/display/window_tree_host_manager.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/weak_ptr.h"
diff --git a/ash/display/screen_orientation_controller.cc b/ash/display/screen_orientation_controller.cc index 62dafdc..6587087 100644 --- a/ash/display/screen_orientation_controller.cc +++ b/ash/display/screen_orientation_controller.cc
@@ -6,8 +6,6 @@ #include "ash/accelerometer/accelerometer_reader.h" #include "ash/accelerometer/accelerometer_types.h" -#include "ash/home_screen/home_screen_controller.h" -#include "ash/home_screen/home_screen_delegate.h" #include "ash/public/cpp/app_types.h" #include "ash/public/cpp/ash_switches.h" #include "ash/shell.h" @@ -610,28 +608,14 @@ MruWindowTracker::WindowList mru_windows( shell->mru_window_tracker()->BuildMruWindowList(kActiveDesk)); - bool has_visible_window = false; for (auto* window : mru_windows) { if (!window->TargetVisibility()) continue; - has_visible_window = true; + if (ApplyLockForWindowIfPossible(window)) return; } - // No visible MRU window means that the home screen might be showing. Check - // if it has an orientation lock. - if (!has_visible_window) { - DCHECK(shell->home_screen_controller()->IsHomeScreenAvailable()); - const aura::Window* home_screen_window = - shell->home_screen_controller()->delegate()->GetHomeScreenWindow(); - if (home_screen_window && - shell->activation_client()->GetActiveWindow() == home_screen_window && - ApplyLockForWindowIfPossible(home_screen_window)) { - return; - } - } - LockRotationToOrientation(user_locked_orientation_); }
diff --git a/ash/display/screen_orientation_controller.h b/ash/display/screen_orientation_controller.h index aff856d..7e5a09f 100644 --- a/ash/display/screen_orientation_controller.h +++ b/ash/display/screen_orientation_controller.h
@@ -12,8 +12,8 @@ #include "ash/ash_export.h" #include "ash/display/display_configuration_controller.h" #include "ash/display/window_tree_host_manager.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/shell_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" #include "base/observer_list.h" #include "ui/aura/window_observer.h"
diff --git a/ash/display/screen_orientation_controller_unittest.cc b/ash/display/screen_orientation_controller_unittest.cc index ce5daf6..4642631 100644 --- a/ash/display/screen_orientation_controller_unittest.cc +++ b/ash/display/screen_orientation_controller_unittest.cc
@@ -11,11 +11,7 @@ #include "ash/accelerometer/accelerometer_types.h" #include "ash/display/screen_orientation_controller.h" #include "ash/display/screen_orientation_controller_test_api.h" -#include "ash/home_screen/home_screen_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_test_util.h" -#include "ash/kiosk_next/mock_kiosk_next_shell_client.h" #include "ash/public/cpp/app_types.h" -#include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_switches.h" #include "ash/shell.h" #include "ash/system/screen_layout_observer.h" @@ -28,7 +24,6 @@ #include "ash/wm/window_state.h" #include "base/command_line.h" #include "base/macros.h" -#include "base/test/scoped_feature_list.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/compositor/layer_type.h" @@ -754,207 +749,4 @@ EXPECT_EQ(display::Display::ROTATE_270, GetCurrentInternalDisplayRotation()); } -// Test fixture for Kiosk Next Home's rotation lock. -class ScreenOrientationControllerKioskNextTest - : public ScreenOrientationControllerTest { - public: - ScreenOrientationControllerKioskNextTest() = default; - ~ScreenOrientationControllerKioskNextTest() override = default; - - // AshTestBase: - void SetUp() override { - base::CommandLine::ForCurrentProcess()->AppendSwitch( - ::switches::kUseFirstDisplayAsInternal); - scoped_feature_list_.InitAndEnableFeature(features::kKioskNextShell); - - set_start_session(false); - AshTestBase::SetUp(); - - client_ = std::make_unique<MockKioskNextShellClient>(); - } - - void TearDown() override { - client_.reset(); - home_screen_window_.reset(); - AshTestBase::TearDown(); - } - - protected: - aura::Window* CreateHomeScreenWindow() { - home_screen_window_.reset(CreateAppWindowInShellWithId(0)); - ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(), - ash::kShellWindowId_HomeScreenContainer) - ->AddChild(home_screen_window_.get()); - return home_screen_window_.get(); - } - - private: - std::unique_ptr<MockKioskNextShellClient> client_; - base::test::ScopedFeatureList scoped_feature_list_; - - std::unique_ptr<aura::Window> home_screen_window_; - - DISALLOW_COPY_AND_ASSIGN(ScreenOrientationControllerKioskNextTest); -}; - -// Tests that the home screen can be inverted but not rotated to portrait. -TEST_F(ScreenOrientationControllerKioskNextTest, - LandscapeOrientationAllowsRotation) { - LogInKioskNextUser(GetSessionControllerClient()); - aura::Window* home_screen_window = CreateHomeScreenWindow(); - - Shell::Get()->activation_client()->ActivateWindow(home_screen_window); - - // The home screen window is rotation-locked to landscape. - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); - EXPECT_TRUE(RotationLocked()); - - // Inverse of orientation is allowed. - TriggerLidUpdate(gfx::Vector3dF(0.0f, kMeanGravity, 0.0f)); - EXPECT_EQ(display::Display::ROTATE_180, GetCurrentInternalDisplayRotation()); - - // Display rotations in between are not allowed. - TriggerLidUpdate(gfx::Vector3dF(kMeanGravity, 0.0f, 0.0f)); - EXPECT_EQ(display::Display::ROTATE_180, GetCurrentInternalDisplayRotation()); - TriggerLidUpdate(gfx::Vector3dF(-kMeanGravity, 0.0f, 0.0f)); - EXPECT_EQ(display::Display::ROTATE_180, GetCurrentInternalDisplayRotation()); -} - -// Tests that app windows outside of the home screen follow normal orientation -// rules. -TEST_F(ScreenOrientationControllerKioskNextTest, - ActiveWindowChangesUpdateOrientation) { - LogInKioskNextUser(GetSessionControllerClient()); - aura::Window* home_screen_window = CreateHomeScreenWindow(); - Shell::Get()->activation_client()->ActivateWindow(home_screen_window); - - // The home screen window is rotation-locked to landscape. - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); - - std::unique_ptr<aura::Window> child_window = CreateControlWindow(); - std::unique_ptr<aura::Window> focus_window(CreateAppWindowInShellWithId(0)); - - // The rotation is unlocked when an app window is opened. - AddWindowAndActivateParent(child_window.get(), focus_window.get()); - EXPECT_FALSE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); - TriggerLidUpdate(gfx::Vector3dF(-kMeanGravity, 0.0f, 0.0f)); - EXPECT_EQ(display::Display::ROTATE_90, GetCurrentInternalDisplayRotation()); - - // The rotation becomes locked again when returning to Home. - Shell::Get()->home_screen_controller()->GoHome( - display::Display::InternalDisplayId()); - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); -} - -TEST_F(ScreenOrientationControllerKioskNextTest, - ActiveWindowChangesUpdateLock) { - LogInKioskNextUser(GetSessionControllerClient()); - aura::Window* home_screen_window = CreateHomeScreenWindow(); - Shell::Get()->activation_client()->ActivateWindow(home_screen_window); - - // The home screen window is rotation-locked to landscape. - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); - - std::unique_ptr<aura::Window> child_window = CreateControlWindow(); - std::unique_ptr<aura::Window> focus_window(CreateAppWindowInShellWithId(0)); - - // An app window can specify its own lock. - Lock(child_window.get(), OrientationLockType::kPortrait); - AddWindowAndActivateParent(child_window.get(), focus_window.get()); - EXPECT_EQ(display::Display::ROTATE_270, GetCurrentInternalDisplayRotation()); - EXPECT_TRUE(RotationLocked()); - - // The rotation returns to landscape when returning to Home. - Shell::Get()->home_screen_controller()->GoHome( - display::Display::InternalDisplayId()); - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); -} - -// Tests that the active window removing a rotation lock doesn't affect the home -// screen window's lock. -TEST_F(ScreenOrientationControllerKioskNextTest, - ActiveWindowRemovesUpdateLock) { - LogInKioskNextUser(GetSessionControllerClient()); - aura::Window* home_screen_window = CreateHomeScreenWindow(); - Shell::Get()->activation_client()->ActivateWindow(home_screen_window); - - // The home screen window is rotation-locked to landscape. - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); - - std::unique_ptr<aura::Window> child_window = CreateControlWindow(); - std::unique_ptr<aura::Window> focus_window(CreateAppWindowInShellWithId(0)); - - // An app window can specify its own lock. - Lock(child_window.get(), OrientationLockType::kLandscape); - AddWindowAndActivateParent(child_window.get(), focus_window.get()); - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); - TriggerLidUpdate(gfx::Vector3dF(kMeanGravity, 0.0f, 0.0f)); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); - - // Returning home preserves the home screen lock, even after the previously - // active window drops its lock. - Shell::Get()->home_screen_controller()->GoHome( - display::Display::InternalDisplayId()); - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); - - Unlock(child_window.get()); - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); -} - -// Tests that a user rotation lock doesn't override the home screen window's -// orientation lock. -TEST_F(ScreenOrientationControllerKioskNextTest, UserRotationLock) { - LogInKioskNextUser(GetSessionControllerClient()); - aura::Window* home_screen_window = CreateHomeScreenWindow(); - ::wm::ActivationClient* activation_client = Shell::Get()->activation_client(); - activation_client->ActivateWindow(home_screen_window); - - std::unique_ptr<aura::Window> child_window = CreateControlWindow(); - std::unique_ptr<aura::Window> focus_window(CreateAppWindowInShellWithId(0)); - - // The rotation is unlocked when an app window is opened. - AddWindowAndActivateParent(child_window.get(), focus_window.get()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); - EXPECT_FALSE(RotationLocked()); - TriggerLidUpdate(gfx::Vector3dF(-kMeanGravity, 0.0f, 0.0f)); - EXPECT_EQ(display::Display::ROTATE_90, GetCurrentInternalDisplayRotation()); - - // The user can lock the rotation. - SetUserRotationLocked(true); - EXPECT_TRUE(UserRotationLocked()); - EXPECT_TRUE(RotationLocked()); - - // Rotating the screen doesn't update the orientation while locked. - TriggerLidUpdate(gfx::Vector3dF(0.0f, kMeanGravity, 0.0f)); - EXPECT_EQ(display::Display::ROTATE_90, GetCurrentInternalDisplayRotation()); - - // The rotation returns to landscape when returning to Home. - Shell::Get()->home_screen_controller()->GoHome( - display::Display::InternalDisplayId()); - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); - - // The user rotation lock applies again when re-activating an app window. - activation_client->ActivateWindow(focus_window.get()); - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_90, GetCurrentInternalDisplayRotation()); - - // Removing the user rotation lock doesn't affect Home. - Shell::Get()->home_screen_controller()->GoHome( - display::Display::InternalDisplayId()); - SetUserRotationLocked(false); - EXPECT_FALSE(UserRotationLocked()); - EXPECT_TRUE(RotationLocked()); - EXPECT_EQ(display::Display::ROTATE_0, GetCurrentInternalDisplayRotation()); -} - } // namespace ash
diff --git a/ash/frame/caption_buttons/frame_size_button_unittest.cc b/ash/frame/caption_buttons/frame_size_button_unittest.cc index 6962098..4e40cce 100644 --- a/ash/frame/caption_buttons/frame_size_button_unittest.cc +++ b/ash/frame/caption_buttons/frame_size_button_unittest.cc
@@ -37,7 +37,7 @@ bool CanMaximize() const override { return true; } bool CanMinimize() const override { return true; } - ash::FrameCaptionButtonContainerView* caption_button_container() { + FrameCaptionButtonContainerView* caption_button_container() { return caption_button_container_; } @@ -75,7 +75,7 @@ } // Not owned. - ash::FrameCaptionButtonContainerView* caption_button_container_; + FrameCaptionButtonContainerView* caption_button_container_; bool resizable_; DISALLOW_COPY_AND_ASSIGN(TestWidgetDelegate); @@ -125,7 +125,7 @@ TestWidgetDelegate* delegate = new TestWidgetDelegate(resizable_); window_state_ = - ash::wm::GetWindowState(CreateWidget(delegate)->GetNativeWindow()); + wm::GetWindowState(CreateWidget(delegate)->GetNativeWindow()); FrameCaptionButtonContainerView::TestApi test( delegate->caption_button_container()); @@ -137,8 +137,8 @@ close_button_ = test.close_button(); } - ash::wm::WindowState* window_state() { return window_state_; } - const ash::wm::WindowState* window_state() const { return window_state_; } + wm::WindowState* window_state() { return window_state_; } + const wm::WindowState* window_state() const { return window_state_; } views::FrameCaptionButton* minimize_button() { return minimize_button_; } views::FrameCaptionButton* size_button() { return size_button_; } @@ -146,7 +146,7 @@ private: // Not owned. - ash::wm::WindowState* window_state_; + wm::WindowState* window_state_; views::FrameCaptionButton* minimize_button_; views::FrameCaptionButton* size_button_; views::FrameCaptionButton* close_button_;
diff --git a/ash/frame/header_view.h b/ash/frame/header_view.h index fa88f6e2..456a55a5 100644 --- a/ash/frame/header_view.h +++ b/ash/frame/header_view.h
@@ -10,7 +10,7 @@ #include "ash/ash_export.h" #include "ash/public/cpp/frame_header.h" #include "ash/public/cpp/immersive/immersive_fullscreen_controller_delegate.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "base/macros.h" #include "base/scoped_observer.h" #include "third_party/skia/include/core/SkColor.h"
diff --git a/ash/frame/non_client_frame_view_ash.cc b/ash/frame/non_client_frame_view_ash.cc index 323cce96..33b15a70 100644 --- a/ash/frame/non_client_frame_view_ash.cc +++ b/ash/frame/non_client_frame_view_ash.cc
@@ -15,12 +15,12 @@ #include "ash/public/cpp/frame_utils.h" #include "ash/public/cpp/immersive/immersive_fullscreen_controller.h" #include "ash/public/cpp/immersive/immersive_fullscreen_controller_delegate.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/public/cpp/window_properties.h" #include "ash/shell.h" #include "ash/wm/overview/overview_controller.h" #include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "ash/wm/window_state.h" #include "ash/wm/window_state_delegate.h" #include "ash/wm/window_state_observer.h" @@ -125,8 +125,7 @@ ImmersiveFullscreenController::EnableForWidget(widget_, false); if (window_state->IsFullscreen() && - window_state->window()->GetProperty( - ash::kImmersiveImpliedByFullscreen)) { + window_state->window()->GetProperty(kImmersiveImpliedByFullscreen)) { ImmersiveFullscreenController::EnableForWidget(widget_, true); } } @@ -282,8 +281,8 @@ void NonClientFrameViewAsh::SetFrameColors(SkColor active_frame_color, SkColor inactive_frame_color) { aura::Window* frame_window = frame_->GetNativeWindow(); - frame_window->SetProperty(ash::kFrameActiveColorKey, active_frame_color); - frame_window->SetProperty(ash::kFrameInactiveColorKey, inactive_frame_color); + frame_window->SetProperty(kFrameActiveColorKey, active_frame_color); + frame_window->SetProperty(kFrameInactiveColorKey, inactive_frame_color); } void NonClientFrameViewAsh::SetCaptionButtonModel( @@ -431,11 +430,11 @@ } SkColor NonClientFrameViewAsh::GetActiveFrameColorForTest() const { - return frame_->GetNativeWindow()->GetProperty(ash::kFrameActiveColorKey); + return frame_->GetNativeWindow()->GetProperty(kFrameActiveColorKey); } SkColor NonClientFrameViewAsh::GetInactiveFrameColorForTest() const { - return frame_->GetNativeWindow()->GetProperty(ash::kFrameInactiveColorKey); + return frame_->GetNativeWindow()->GetProperty(kFrameInactiveColorKey); } void NonClientFrameViewAsh::UpdateHeaderView() {
diff --git a/ash/frame/non_client_frame_view_ash_unittest.cc b/ash/frame/non_client_frame_view_ash_unittest.cc index f4cf307..11c9cc4 100644 --- a/ash/frame/non_client_frame_view_ash_unittest.cc +++ b/ash/frame/non_client_frame_view_ash_unittest.cc
@@ -373,7 +373,7 @@ auto* delegate = new TestWidgetConstraintsDelegate; std::unique_ptr<views::Widget> widget = CreateTestWidget(delegate); - auto* frame_view = static_cast<ash::NonClientFrameViewAsh*>( + auto* frame_view = static_cast<NonClientFrameViewAsh*>( widget->non_client_view()->frame_view()); auto* header_view = frame_view->GetHeaderView(); ASSERT_TRUE(widget->IsMaximized()); @@ -485,7 +485,7 @@ // Turn immersive off, and make sure that header view is invisible // in fullscreen. widget->SetFullscreen(true); - ash::ImmersiveFullscreenController::EnableForWidget(widget.get(), false); + ImmersiveFullscreenController::EnableForWidget(widget.get(), false); EXPECT_FALSE(header_view->in_immersive_mode()); EXPECT_FALSE(header_view->GetVisible()); widget->SetFullscreen(false); @@ -536,8 +536,8 @@ } // namespace TEST_F(NonClientFrameViewAshTest, BackButton) { - ash::AcceleratorControllerImpl* controller = - ash::Shell::Get()->accelerator_controller(); + AcceleratorControllerImpl* controller = + Shell::Get()->accelerator_controller(); std::unique_ptr<TestButtonModel> model = std::make_unique<TestButtonModel>(); TestButtonModel* model_ptr = model.get(); @@ -847,8 +847,8 @@ views::NonClientFrameView* CreateNonClientFrameView( views::Widget* widget) override { if (custom_) { - ash::wm::WindowState* window_state = - ash::wm::GetWindowState(widget->GetNativeWindow()); + wm::WindowState* window_state = + wm::GetWindowState(widget->GetNativeWindow()); window_state->SetDelegate(std::make_unique<wm::WindowStateDelegate>()); } return TestWidgetConstraintsDelegate::CreateNonClientFrameView(widget); @@ -863,19 +863,18 @@ } // namespace // Verify that NonClientFrameViewAsh updates the active color based on the -// ash::kFrameActiveColorKey window property. +// kFrameActiveColorKey window property. TEST_P(NonClientFrameViewAshFrameColorTest, kFrameActiveColorKey) { TestWidgetDelegate* delegate = new TestWidgetDelegate(GetParam()); std::unique_ptr<views::Widget> widget = CreateTestWidget(delegate); SkColor active_color = - widget->GetNativeWindow()->GetProperty(ash::kFrameActiveColorKey); + widget->GetNativeWindow()->GetProperty(kFrameActiveColorKey); constexpr SkColor new_color = SK_ColorWHITE; EXPECT_NE(active_color, new_color); - widget->GetNativeWindow()->SetProperty(ash::kFrameActiveColorKey, new_color); - active_color = - widget->GetNativeWindow()->GetProperty(ash::kFrameActiveColorKey); + widget->GetNativeWindow()->SetProperty(kFrameActiveColorKey, new_color); + active_color = widget->GetNativeWindow()->GetProperty(kFrameActiveColorKey); EXPECT_EQ(active_color, new_color); EXPECT_EQ(new_color, delegate->non_client_frame_view()->GetActiveFrameColorForTest()); @@ -887,47 +886,44 @@ ->caption_button_container()); ui::DrawWaiterForTest::WaitForCommit(widget->GetLayer()->GetCompositor()); gfx::ImageSkia original_icon_image = test_api.size_button()->icon_image(); - widget->GetNativeWindow()->SetProperty(ash::kFrameActiveColorKey, - SK_ColorBLACK); + widget->GetNativeWindow()->SetProperty(kFrameActiveColorKey, SK_ColorBLACK); ui::DrawWaiterForTest::WaitForCommit(widget->GetLayer()->GetCompositor()); EXPECT_FALSE(original_icon_image.BackedBySameObjectAs( test_api.size_button()->icon_image())); } // Verify that NonClientFrameViewAsh updates the inactive color based on the -// ash::kFrameInactiveColorKey window property. +// kFrameInactiveColorKey window property. TEST_P(NonClientFrameViewAshFrameColorTest, KFrameInactiveColor) { TestWidgetDelegate* delegate = new TestWidgetDelegate(GetParam()); std::unique_ptr<views::Widget> widget = CreateTestWidget(delegate); SkColor active_color = - widget->GetNativeWindow()->GetProperty(ash::kFrameInactiveColorKey); + widget->GetNativeWindow()->GetProperty(kFrameInactiveColorKey); constexpr SkColor new_color = SK_ColorWHITE; EXPECT_NE(active_color, new_color); - widget->GetNativeWindow()->SetProperty(ash::kFrameInactiveColorKey, - new_color); - active_color = - widget->GetNativeWindow()->GetProperty(ash::kFrameInactiveColorKey); + widget->GetNativeWindow()->SetProperty(kFrameInactiveColorKey, new_color); + active_color = widget->GetNativeWindow()->GetProperty(kFrameInactiveColorKey); EXPECT_EQ(active_color, new_color); EXPECT_EQ(new_color, delegate->non_client_frame_view()->GetInactiveFrameColorForTest()); } // Verify that NonClientFrameViewAsh updates the active color based on the -// ash::kFrameActiveColorKey window property. +// kFrameActiveColorKey window property. TEST_P(NonClientFrameViewAshFrameColorTest, WideFrameInitialColor) { TestWidgetDelegate* delegate = new TestWidgetDelegate(GetParam()); std::unique_ptr<views::Widget> widget = CreateTestWidget(delegate); aura::Window* window = widget->GetNativeWindow(); - SkColor active_color = window->GetProperty(ash::kFrameActiveColorKey); - SkColor inactive_color = window->GetProperty(ash::kFrameInactiveColorKey); + SkColor active_color = window->GetProperty(kFrameActiveColorKey); + SkColor inactive_color = window->GetProperty(kFrameInactiveColorKey); constexpr SkColor new_active_color = SK_ColorWHITE; constexpr SkColor new_inactive_color = SK_ColorBLACK; EXPECT_NE(active_color, new_active_color); EXPECT_NE(inactive_color, new_inactive_color); - window->SetProperty(ash::kFrameActiveColorKey, new_active_color); - window->SetProperty(ash::kFrameInactiveColorKey, new_inactive_color); + window->SetProperty(kFrameActiveColorKey, new_active_color); + window->SetProperty(kFrameInactiveColorKey, new_inactive_color); std::unique_ptr<WideFrameView> wide_frame_view = std::make_unique<WideFrameView>(widget.get());
diff --git a/ash/frame/wide_frame_view.h b/ash/frame/wide_frame_view.h index ea97cdf..a577b5e 100644 --- a/ash/frame/wide_frame_view.h +++ b/ash/frame/wide_frame_view.h
@@ -31,24 +31,23 @@ // the target widget because ImmersiveFullscreenController is not owned by // NonClientFrameViewAsh. Investigate if we integrate this into // NonClientFrameViewAsh. -class ASH_EXPORT WideFrameView - : public views::WidgetDelegateView, - public aura::WindowObserver, - public display::DisplayObserver, - public ash::ImmersiveFullscreenControllerDelegate, - public OverviewObserver { +class ASH_EXPORT WideFrameView : public views::WidgetDelegateView, + public aura::WindowObserver, + public display::DisplayObserver, + public ImmersiveFullscreenControllerDelegate, + public OverviewObserver { public: explicit WideFrameView(views::Widget* target); ~WideFrameView() override; // Initialize |immersive_fullscreen_controller| so that the controller reveals // and |hides_header_| in immersive mode. - void Init(ash::ImmersiveFullscreenController* controller); + void Init(ImmersiveFullscreenController* controller); // Set the caption model for caption buttions on this frame. - void SetCaptionButtonModel(std::unique_ptr<ash::CaptionButtonModel> mode); + void SetCaptionButtonModel(std::unique_ptr<CaptionButtonModel> mode); - ash::HeaderView* header_view() { return header_view_; } + HeaderView* header_view() { return header_view_; } private: static gfx::Rect GetFrameBounds(views::Widget* target); @@ -67,7 +66,7 @@ void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; - // ash::ImmersiveFullscreenControllerDelegate: + // ImmersiveFullscreenControllerDelegate: void OnImmersiveRevealStarted() override; void OnImmersiveRevealEnded() override; void OnImmersiveFullscreenEntered() override; @@ -79,14 +78,14 @@ void OnOverviewModeStarting() override; void OnOverviewModeEnded() override; - ash::HeaderView* GetTargetHeaderView(); + HeaderView* GetTargetHeaderView(); // The target widget this frame will control. views::Widget* target_; std::unique_ptr<views::Widget> widget_; - ash::HeaderView* header_view_ = nullptr; + HeaderView* header_view_ = nullptr; DISALLOW_COPY_AND_ASSIGN(WideFrameView); };
diff --git a/ash/home_screen/home_launcher_gesture_handler.h b/ash/home_screen/home_launcher_gesture_handler.h index cb62c2f4..cb143ae 100644 --- a/ash/home_screen/home_launcher_gesture_handler.h +++ b/ash/home_screen/home_launcher_gesture_handler.h
@@ -10,8 +10,8 @@ #include "ash/ash_export.h" #include "ash/home_screen/home_screen_delegate.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" #include "base/optional.h" #include "base/scoped_observer.h"
diff --git a/ash/keyboard/virtual_keyboard_controller.h b/ash/keyboard/virtual_keyboard_controller.h index 7f92c87..ac21844 100644 --- a/ash/keyboard/virtual_keyboard_controller.h +++ b/ash/keyboard/virtual_keyboard_controller.h
@@ -10,8 +10,8 @@ #include "ash/ash_export.h" #include "ash/bluetooth_devices_observer.h" #include "ash/public/cpp/keyboard/keyboard_controller_observer.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/session/session_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" #include "ui/base/ime/chromeos/public/interfaces/ime_keyset.mojom.h" #include "ui/events/devices/input_device_event_observer.h"
diff --git a/ash/kiosk_next/kiosk_next_shell_controller_unittest.cc b/ash/kiosk_next/kiosk_next_shell_controller_unittest.cc deleted file mode 100644 index bfb966a..0000000 --- a/ash/kiosk_next/kiosk_next_shell_controller_unittest.cc +++ /dev/null
@@ -1,93 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" - -#include <memory> - -#include "ash/kiosk_next/kiosk_next_shell_observer.h" -#include "ash/kiosk_next/kiosk_next_shell_test_util.h" -#include "ash/kiosk_next/mock_kiosk_next_shell_client.h" -#include "ash/public/cpp/ash_features.h" -#include "ash/shell.h" -#include "ash/test/ash_test_base.h" -#include "base/test/metrics/histogram_tester.h" -#include "base/test/scoped_feature_list.h" - -namespace ash { -namespace { - -KioskNextShellControllerImpl* GetKioskNextShellController() { - return Shell::Get()->kiosk_next_shell_controller(); -} - -class MockKioskNextShellObserver : public KioskNextShellObserver { - public: - MockKioskNextShellObserver() = default; - ~MockKioskNextShellObserver() override = default; - - MOCK_METHOD0(OnKioskNextEnabled, void()); - - private: - DISALLOW_COPY_AND_ASSIGN(MockKioskNextShellObserver); -}; - -class KioskNextShellControllerTest : public AshTestBase { - public: - KioskNextShellControllerTest() = default; - - ~KioskNextShellControllerTest() override = default; - - void SetUp() override { - set_start_session(false); - AshTestBase::SetUp(); - client_ = std::make_unique<MockKioskNextShellClient>(); - scoped_feature_list_.InitAndEnableFeature(features::kKioskNextShell); - } - - void TearDown() override { - client_.reset(); - AshTestBase::TearDown(); - } - - protected: - std::unique_ptr<MockKioskNextShellClient> client_; - base::test::ScopedFeatureList scoped_feature_list_; - base::HistogramTester histogram_tester_; - - private: - DISALLOW_COPY_AND_ASSIGN(KioskNextShellControllerTest); -}; - -// Ensures that KioskNextShell is not enabled when conditions are not met. -TEST_F(KioskNextShellControllerTest, TestKioskNextNotEnabled) { - // No user has logged in yet. - EXPECT_FALSE(GetKioskNextShellController()->IsEnabled()); - - SimulateUserLogin("primary_user1@test.com"); - - // KioskNextShell is not enabled for regular users by default. - EXPECT_FALSE(GetKioskNextShellController()->IsEnabled()); -} - -// Ensures that KioskNextShell is enabled when conditions are met. -// Ensures that LaunchKioskNextShell is called when KioskNextUser logs in. -TEST_F(KioskNextShellControllerTest, TestKioskNextLaunchShellWhenEnabled) { - EXPECT_CALL(*client_, LaunchKioskNextShell(::testing::_)).Times(1); - LogInKioskNextUser(GetSessionControllerClient()); - EXPECT_TRUE(GetKioskNextShellController()->IsEnabled()); - histogram_tester_.ExpectUniqueSample("KioskNextShell.Launched", true, 1); -} - -// Ensures that observers are notified when KioskNextUser logs in. -TEST_F(KioskNextShellControllerTest, TestKioskNextObserverNotification) { - auto observer = std::make_unique<MockKioskNextShellObserver>(); - GetKioskNextShellController()->AddObserver(observer.get()); - EXPECT_CALL(*observer, OnKioskNextEnabled).Times(1); - LogInKioskNextUser(GetSessionControllerClient()); - GetKioskNextShellController()->RemoveObserver(observer.get()); -} - -} // namespace -} // namespace ash
diff --git a/ash/login/ui/parent_access_view.h b/ash/login/ui/parent_access_view.h index 176db90..559c1fa 100644 --- a/ash/login/ui/parent_access_view.h +++ b/ash/login/ui/parent_access_view.h
@@ -8,8 +8,8 @@ #include <string> #include "ash/ash_export.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/callback.h" #include "base/macros.h" #include "base/optional.h"
diff --git a/ash/multi_device_setup/multi_device_notification_presenter.cc b/ash/multi_device_setup/multi_device_notification_presenter.cc index 46edd07..622373b28 100644 --- a/ash/multi_device_setup/multi_device_notification_presenter.cc +++ b/ash/multi_device_setup/multi_device_notification_presenter.cc
@@ -9,7 +9,7 @@ #include "ash/public/cpp/notification_utils.h" #include "ash/public/cpp/system_tray_client.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" +#include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" @@ -262,14 +262,14 @@ MultiDeviceNotificationPresenter::CreateNotification( const base::string16& title, const base::string16& message) { - return ash::CreateSystemNotification( + return CreateSystemNotification( message_center::NotificationType::NOTIFICATION_TYPE_SIMPLE, kNotificationId, title, message, base::string16() /* display_source */, GURL() /* origin_url */, message_center::NotifierId(message_center::NotifierType::SYSTEM_COMPONENT, kNotifierMultiDevice), message_center::RichNotificationData(), nullptr /* delegate */, - ash::kNotificationMultiDeviceSetupIcon, + kNotificationMultiDeviceSetupIcon, message_center::SystemNotificationWarningLevel::NORMAL); }
diff --git a/ash/multi_user/multi_user_window_manager_impl.h b/ash/multi_user/multi_user_window_manager_impl.h index a116d49..312c919a 100644 --- a/ash/multi_user/multi_user_window_manager_impl.h +++ b/ash/multi_user/multi_user_window_manager_impl.h
@@ -10,8 +10,8 @@ #include "ash/ash_export.h" #include "ash/public/cpp/multi_user_window_manager.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/session/session_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/containers/flat_map.h" #include "base/macros.h" #include "base/observer_list.h"
diff --git a/ash/public/cpp/BUILD.gn b/ash/public/cpp/BUILD.gn index 4dd0ee1..0ac40e53 100644 --- a/ash/public/cpp/BUILD.gn +++ b/ash/public/cpp/BUILD.gn
@@ -191,7 +191,7 @@ "system_tray_focus_observer.h", "tablet_mode.cc", "tablet_mode.h", - "tablet_mode_toggle_observer.h", + "tablet_mode_observer.h", "toast_data.cc", "toast_data.h", "toast_manager.cc", @@ -308,6 +308,7 @@ "//testing/gtest", "//ui/aura:test_support", "//ui/gfx:test_support", + "//ui/views:test_support", ] }
diff --git a/ash/public/cpp/menu_struct_mojom_traits.h b/ash/public/cpp/menu_struct_mojom_traits.h deleted file mode 100644 index 3abe6627..0000000 --- a/ash/public/cpp/menu_struct_mojom_traits.h +++ /dev/null
@@ -1,124 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ASH_PUBLIC_CPP_MENU_STRUCT_MOJOM_TRAITS_H_ -#define ASH_PUBLIC_CPP_MENU_STRUCT_MOJOM_TRAITS_H_ - -#include "ash/public/cpp/ash_public_export.h" -#include "ash/public/interfaces/menu.mojom-shared.h" -#include "ui/base/models/menu_model.h" -#include "ui/base/models/menu_separator_types.h" - -namespace mojo { - -template <> -struct EnumTraits<ash::mojom::MenuItemType, ui::MenuModel::ItemType> { - static ash::mojom::MenuItemType ToMojom(ui::MenuModel::ItemType input) { - switch (input) { - case ui::MenuModel::TYPE_COMMAND: - return ash::mojom::MenuItemType::COMMAND; - case ui::MenuModel::TYPE_CHECK: - return ash::mojom::MenuItemType::CHECK; - case ui::MenuModel::TYPE_RADIO: - return ash::mojom::MenuItemType::RADIO; - case ui::MenuModel::TYPE_SEPARATOR: - return ash::mojom::MenuItemType::SEPARATOR; - case ui::MenuModel::TYPE_BUTTON_ITEM: - NOTREACHED() << "TYPE_BUTTON_ITEM is not yet supported."; - return ash::mojom::MenuItemType::COMMAND; - case ui::MenuModel::TYPE_SUBMENU: - return ash::mojom::MenuItemType::SUBMENU; - case ui::MenuModel::TYPE_ACTIONABLE_SUBMENU: - return ash::mojom::MenuItemType::ACTIONABLE_SUBMENU; - case ui::MenuModel::TYPE_HIGHLIGHTED: - NOTREACHED() << "TYPE_HIGHLIGHTED is not yet supported"; - return ash::mojom::MenuItemType::COMMAND; - } - NOTREACHED(); - return ash::mojom::MenuItemType::COMMAND; - } - - static bool FromMojom(ash::mojom::MenuItemType input, - ui::MenuModel::ItemType* out) { - switch (input) { - case ash::mojom::MenuItemType::COMMAND: - *out = ui::MenuModel::TYPE_COMMAND; - return true; - case ash::mojom::MenuItemType::CHECK: - *out = ui::MenuModel::TYPE_CHECK; - return true; - case ash::mojom::MenuItemType::RADIO: - *out = ui::MenuModel::TYPE_RADIO; - return true; - case ash::mojom::MenuItemType::SEPARATOR: - *out = ui::MenuModel::TYPE_SEPARATOR; - return true; - case ash::mojom::MenuItemType::SUBMENU: - *out = ui::MenuModel::TYPE_SUBMENU; - return true; - case ash::mojom::MenuItemType::ACTIONABLE_SUBMENU: - *out = ui::MenuModel::TYPE_ACTIONABLE_SUBMENU; - return true; - } - NOTREACHED(); - return false; - } -}; - -template <> -struct EnumTraits<ash::mojom::MenuSeparatorType, ui::MenuSeparatorType> { - static ash::mojom::MenuSeparatorType ToMojom(ui::MenuSeparatorType input) { - switch (input) { - case ui::MenuSeparatorType::NORMAL_SEPARATOR: - return ash::mojom::MenuSeparatorType::NORMAL_SEPARATOR; - case ui::MenuSeparatorType::DOUBLE_SEPARATOR: - return ash::mojom::MenuSeparatorType::DOUBLE_SEPARATOR; - case ui::MenuSeparatorType::UPPER_SEPARATOR: - return ash::mojom::MenuSeparatorType::UPPER_SEPARATOR; - case ui::MenuSeparatorType::LOWER_SEPARATOR: - return ash::mojom::MenuSeparatorType::LOWER_SEPARATOR; - case ui::MenuSeparatorType::SPACING_SEPARATOR: - return ash::mojom::MenuSeparatorType::SPACING_SEPARATOR; - case ui::MenuSeparatorType::VERTICAL_SEPARATOR: - return ash::mojom::MenuSeparatorType::VERTICAL_SEPARATOR; - case ui::MenuSeparatorType::PADDED_SEPARATOR: - return ash::mojom::MenuSeparatorType::PADDED_SEPARATOR; - } - NOTREACHED(); - return ash::mojom::MenuSeparatorType::NORMAL_SEPARATOR; - } - - static bool FromMojom(ash::mojom::MenuSeparatorType input, - ui::MenuSeparatorType* out) { - switch (input) { - case ash::mojom::MenuSeparatorType::NORMAL_SEPARATOR: - *out = ui::MenuSeparatorType::NORMAL_SEPARATOR; - return true; - case ash::mojom::MenuSeparatorType::DOUBLE_SEPARATOR: - *out = ui::MenuSeparatorType::DOUBLE_SEPARATOR; - return true; - case ash::mojom::MenuSeparatorType::UPPER_SEPARATOR: - *out = ui::MenuSeparatorType::UPPER_SEPARATOR; - return true; - case ash::mojom::MenuSeparatorType::LOWER_SEPARATOR: - *out = ui::MenuSeparatorType::LOWER_SEPARATOR; - return true; - case ash::mojom::MenuSeparatorType::SPACING_SEPARATOR: - *out = ui::MenuSeparatorType::SPACING_SEPARATOR; - return true; - case ash::mojom::MenuSeparatorType::VERTICAL_SEPARATOR: - *out = ui::MenuSeparatorType::VERTICAL_SEPARATOR; - return true; - case ash::mojom::MenuSeparatorType::PADDED_SEPARATOR: - *out = ui::MenuSeparatorType::PADDED_SEPARATOR; - return true; - } - NOTREACHED(); - return false; - } -}; - -} // namespace mojo - -#endif // ASH_PUBLIC_CPP_MENU_STRUCT_MOJOM_TRAITS_H_
diff --git a/ash/public/cpp/pagination/pagination_model.cc b/ash/public/cpp/pagination/pagination_model.cc index 86260dc..6fb47d0ec 100644 --- a/ash/public/cpp/pagination/pagination_model.cc +++ b/ash/public/cpp/pagination/pagination_model.cc
@@ -16,8 +16,9 @@ constexpr int kPageTransitionDurationDampening = 3; } // namespace -PaginationModel::PaginationModel() - : total_pages_(-1), +PaginationModel::PaginationModel(views::View* view) + : views::AnimationDelegateViews(view), + total_pages_(-1), selected_page_(-1), transition_(-1, 0), pending_selected_page_(-1),
diff --git a/ash/public/cpp/pagination/pagination_model.h b/ash/public/cpp/pagination/pagination_model.h index 0e0f69aa..bc0449e 100644 --- a/ash/public/cpp/pagination/pagination_model.h +++ b/ash/public/cpp/pagination/pagination_model.h
@@ -12,18 +12,19 @@ #include "base/macros.h" #include "base/observer_list.h" #include "base/time/time.h" -#include "ui/gfx/animation/animation_delegate.h" +#include "ui/views/animation/animation_delegate_views.h" namespace gfx { class SlideAnimation; } + namespace ash { class PaginationModelObserver; // A simple pagination model that consists of two numbers: the total pages and // the currently selected page. The model is a single selection model that at // the most one page can become selected at any time. -class ASH_PUBLIC_EXPORT PaginationModel : public gfx::AnimationDelegate { +class ASH_PUBLIC_EXPORT PaginationModel : public views::AnimationDelegateViews { public: // Holds info for transition animation and touch scroll. struct Transition { @@ -45,7 +46,7 @@ double progress; }; - PaginationModel(); + explicit PaginationModel(views::View* owner_view); ~PaginationModel() override; void SetTotalPages(int total_pages);
diff --git a/ash/public/cpp/pagination/pagination_model_unittest.cc b/ash/public/cpp/pagination/pagination_model_unittest.cc index e8d0f22..9106eeb 100644 --- a/ash/public/cpp/pagination/pagination_model_unittest.cc +++ b/ash/public/cpp/pagination/pagination_model_unittest.cc
@@ -11,8 +11,7 @@ #include "base/macros.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" -#include "base/test/scoped_task_environment.h" -#include "testing/gtest/include/gtest/gtest.h" +#include "ui/views/test/widget_test.h" namespace ash { namespace test { @@ -112,23 +111,26 @@ DISALLOW_COPY_AND_ASSIGN(TestPaginationModelObserver); }; -class PaginationModelTest : public testing::Test { +class PaginationModelTest : public views::test::WidgetTest { public: - PaginationModelTest() - : scoped_task_environment_( - base::test::ScopedTaskEnvironment::MainThreadType::UI) {} - ~PaginationModelTest() override {} + PaginationModelTest() = default; + ~PaginationModelTest() override = default; // testing::Test overrides: void SetUp() override { - pagination_.SetTotalPages(5); - pagination_.SetTransitionDurations(1, 1); - observer_.set_model(&pagination_); - pagination_.AddObserver(&observer_); + views::test::WidgetTest::SetUp(); + widget_.reset(CreateTopLevelPlatformWidget()); + pagination_ = std::make_unique<PaginationModel>(widget_->GetContentsView()); + pagination_->SetTotalPages(5); + pagination_->SetTransitionDurations(1, 1); + observer_.set_model(pagination_.get()); + pagination_->AddObserver(&observer_); } void TearDown() override { - pagination_.RemoveObserver(&observer_); + pagination_->RemoveObserver(&observer_); observer_.set_model(NULL); + widget_.reset(); + views::test::WidgetTest::TearDown(); } protected: @@ -137,27 +139,29 @@ int expected_transition_start, int expected_transition_end) { observer_.set_expected_page_selection(0); - pagination_.SelectPage(start_page, false /* animate */); + pagination_->SelectPage(start_page, /*animate=*/false); observer_.Reset(); observer_.set_expected_page_selection(expected_selection); observer_.set_expected_transition_start(expected_transition_start); observer_.set_expected_transition_end(expected_transition_end); } - PaginationModel pagination_; + PaginationModel* pagination() { return pagination_.get(); } + TestPaginationModelObserver observer_; private: - base::test::ScopedTaskEnvironment scoped_task_environment_; + WidgetAutoclosePtr widget_; + std::unique_ptr<PaginationModel> pagination_; DISALLOW_COPY_AND_ASSIGN(PaginationModelTest); }; TEST_F(PaginationModelTest, SelectPage) { - pagination_.SelectPage(2, false /* animate */); - pagination_.SelectPage(4, false /* animate */); - pagination_.SelectPage(3, false /* animate */); - pagination_.SelectPage(1, false /* animate */); + pagination()->SelectPage(2, /*animate=*/false); + pagination()->SelectPage(4, /*animate=*/false); + pagination()->SelectPage(3, /*animate=*/false); + pagination()->SelectPage(1, /*animate=*/false); EXPECT_EQ(0, observer_.transition_start_count()); EXPECT_EQ(0, observer_.transition_end_count()); @@ -165,17 +169,17 @@ EXPECT_EQ(std::string("2 4 3 1"), observer_.selected_pages()); // Nothing happens if select the same page. - pagination_.SelectPage(1, false /* animate */); + pagination()->SelectPage(1, /*animate=*/false); EXPECT_EQ(4, observer_.selection_count()); EXPECT_EQ(std::string("2 4 3 1"), observer_.selected_pages()); } TEST_F(PaginationModelTest, IsValidPageRelative) { - pagination_.SelectPage(0, false /*animate*/); - ASSERT_FALSE(pagination_.IsValidPageRelative(-1)); - ASSERT_FALSE(pagination_.IsValidPageRelative(5)); - ASSERT_TRUE(pagination_.IsValidPageRelative(1)); - ASSERT_TRUE(pagination_.IsValidPageRelative(4)); + pagination()->SelectPage(0, false /*animate*/); + ASSERT_FALSE(pagination()->IsValidPageRelative(-1)); + ASSERT_FALSE(pagination()->IsValidPageRelative(5)); + ASSERT_TRUE(pagination()->IsValidPageRelative(1)); + ASSERT_TRUE(pagination()->IsValidPageRelative(4)); } TEST_F(PaginationModelTest, SelectPageAnimated) { @@ -183,7 +187,7 @@ // One transition. SetStartPageAndExpects(kStartPage, 1, 0, 0); - pagination_.SelectPage(1, true /* animate */); + pagination()->SelectPage(1, /*animate=*/true); base::RunLoop().Run(); EXPECT_EQ(1, observer_.transition_start_count()); EXPECT_EQ(1, observer_.transition_end_count()); @@ -192,8 +196,8 @@ // Two transitions in a row. SetStartPageAndExpects(kStartPage, 2, 0, 0); - pagination_.SelectPage(1, true /* animate */); - pagination_.SelectPage(3, true /* animate */); + pagination()->SelectPage(1, /*animate=*/true); + pagination()->SelectPage(3, /*animate=*/true); base::RunLoop().Run(); EXPECT_EQ(2, observer_.transition_start_count()); EXPECT_EQ(2, observer_.transition_end_count()); @@ -202,8 +206,8 @@ // Transition to same page twice and only one should happen. SetStartPageAndExpects(kStartPage, 1, 0, 0); - pagination_.SelectPage(1, true /* animate */); - pagination_.SelectPage(1, true /* animate */); // Ignored. + pagination()->SelectPage(1, /*animate=*/true); + pagination()->SelectPage(1, /*animate=*/true); // Ignored. base::RunLoop().Run(); EXPECT_EQ(1, observer_.transition_start_count()); EXPECT_EQ(1, observer_.transition_end_count()); @@ -212,10 +216,10 @@ // More than two transitions and only the first and last would happen. SetStartPageAndExpects(kStartPage, 2, 0, 0); - pagination_.SelectPage(1, true /* animate */); - pagination_.SelectPage(3, true /* animate */); // Ignored - pagination_.SelectPage(4, true /* animate */); // Ignored - pagination_.SelectPage(2, true /* animate */); + pagination()->SelectPage(1, /*animate=*/true); + pagination()->SelectPage(3, /*animate=*/true); // Ignored + pagination()->SelectPage(4, /*animate=*/true); // Ignored + pagination()->SelectPage(2, /*animate=*/true); base::RunLoop().Run(); EXPECT_EQ(2, observer_.transition_start_count()); EXPECT_EQ(2, observer_.transition_end_count()); @@ -227,10 +231,10 @@ // one will be reversed by the kStart transition and the second one will be // finished. SetStartPageAndExpects(kStartPage, 1, 0, 0); - pagination_.SelectPage(1, true /* animate */); - pagination_.SelectPage(2, true /* animate */); // Ignored - pagination_.SelectPage(kStartPage, true /* animate */); - pagination_.SelectPage(3, true /* animate */); + pagination()->SelectPage(1, /*animate=*/true); + pagination()->SelectPage(2, /*animate=*/true); // Ignored + pagination()->SelectPage(kStartPage, /*animate=*/true); + pagination()->SelectPage(3, /*animate=*/true); base::RunLoop().Run(); EXPECT_EQ(std::string("3"), observer_.selected_pages()); } @@ -240,37 +244,37 @@ // Scroll to the next page (negative delta) and finish it. SetStartPageAndExpects(kStartPage, 1, 0, 0); - pagination_.StartScroll(); - pagination_.UpdateScroll(-0.1); - EXPECT_EQ(kStartPage + 1, pagination_.transition().target_page); - pagination_.EndScroll(false); // Finish transition + pagination()->StartScroll(); + pagination()->UpdateScroll(-0.1); + EXPECT_EQ(kStartPage + 1, pagination()->transition().target_page); + pagination()->EndScroll(false); // Finish transition base::RunLoop().Run(); EXPECT_EQ(1, observer_.selection_count()); // Scroll to the previous page (positive delta) and finish it. SetStartPageAndExpects(kStartPage, 1, 0, 0); - pagination_.StartScroll(); - pagination_.UpdateScroll(0.1); - EXPECT_EQ(kStartPage - 1, pagination_.transition().target_page); - pagination_.EndScroll(false); // Finish transition + pagination()->StartScroll(); + pagination()->UpdateScroll(0.1); + EXPECT_EQ(kStartPage - 1, pagination()->transition().target_page); + pagination()->EndScroll(false); // Finish transition base::RunLoop().Run(); EXPECT_EQ(1, observer_.selection_count()); // Scroll to the next page (negative delta) and cancel it. SetStartPageAndExpects(kStartPage, 0, 1, 0); - pagination_.StartScroll(); - pagination_.UpdateScroll(-0.1); - EXPECT_EQ(kStartPage + 1, pagination_.transition().target_page); - pagination_.EndScroll(true); // Cancel transition + pagination()->StartScroll(); + pagination()->UpdateScroll(-0.1); + EXPECT_EQ(kStartPage + 1, pagination()->transition().target_page); + pagination()->EndScroll(true); // Cancel transition base::RunLoop().Run(); EXPECT_EQ(0, observer_.selection_count()); // Scroll to the previous page (position delta) and cancel it. SetStartPageAndExpects(kStartPage, 0, 1, 0); - pagination_.StartScroll(); - pagination_.UpdateScroll(0.1); - EXPECT_EQ(kStartPage - 1, pagination_.transition().target_page); - pagination_.EndScroll(true); // Cancel transition + pagination()->StartScroll(); + pagination()->UpdateScroll(0.1); + EXPECT_EQ(kStartPage - 1, pagination()->transition().target_page); + pagination()->EndScroll(true); // Cancel transition base::RunLoop().Run(); EXPECT_EQ(0, observer_.selection_count()); } @@ -281,46 +285,46 @@ // Scroll to the next page (negative delta) with a transition in the same // direction. SetStartPageAndExpects(kStartPage, 1, 0, 0); - pagination_.SetTransition(PaginationModel::Transition(kStartPage + 1, 0.5)); - pagination_.StartScroll(); - pagination_.UpdateScroll(-0.1); - EXPECT_EQ(kStartPage + 1, pagination_.transition().target_page); - EXPECT_EQ(0.6, pagination_.transition().progress); - pagination_.EndScroll(false); + pagination()->SetTransition(PaginationModel::Transition(kStartPage + 1, 0.5)); + pagination()->StartScroll(); + pagination()->UpdateScroll(-0.1); + EXPECT_EQ(kStartPage + 1, pagination()->transition().target_page); + EXPECT_EQ(0.6, pagination()->transition().progress); + pagination()->EndScroll(false); base::RunLoop().Run(); EXPECT_EQ(1, observer_.selection_count()); // Scroll to the next page (negative delta) with a transition in a different // direction. SetStartPageAndExpects(kStartPage, 0, 1, 0); - pagination_.SetTransition(PaginationModel::Transition(kStartPage - 1, 0.5)); - pagination_.StartScroll(); - pagination_.UpdateScroll(-0.1); - EXPECT_EQ(kStartPage - 1, pagination_.transition().target_page); - EXPECT_EQ(0.4, pagination_.transition().progress); - pagination_.EndScroll(true); + pagination()->SetTransition(PaginationModel::Transition(kStartPage - 1, 0.5)); + pagination()->StartScroll(); + pagination()->UpdateScroll(-0.1); + EXPECT_EQ(kStartPage - 1, pagination()->transition().target_page); + EXPECT_EQ(0.4, pagination()->transition().progress); + pagination()->EndScroll(true); // Scroll to the previous page (positive delta) with a transition in the same // direction. SetStartPageAndExpects(kStartPage, 1, 0, 0); - pagination_.SetTransition(PaginationModel::Transition(kStartPage - 1, 0.5)); - pagination_.StartScroll(); - pagination_.UpdateScroll(0.1); - EXPECT_EQ(kStartPage - 1, pagination_.transition().target_page); - EXPECT_EQ(0.6, pagination_.transition().progress); - pagination_.EndScroll(false); + pagination()->SetTransition(PaginationModel::Transition(kStartPage - 1, 0.5)); + pagination()->StartScroll(); + pagination()->UpdateScroll(0.1); + EXPECT_EQ(kStartPage - 1, pagination()->transition().target_page); + EXPECT_EQ(0.6, pagination()->transition().progress); + pagination()->EndScroll(false); base::RunLoop().Run(); EXPECT_EQ(1, observer_.selection_count()); // Scroll to the previous page (positive delta) with a transition in a // different direction. SetStartPageAndExpects(kStartPage, 0, 1, 0); - pagination_.SetTransition(PaginationModel::Transition(kStartPage + 1, 0.5)); - pagination_.StartScroll(); - pagination_.UpdateScroll(0.1); - EXPECT_EQ(kStartPage + 1, pagination_.transition().target_page); - EXPECT_EQ(0.4, pagination_.transition().progress); - pagination_.EndScroll(true); + pagination()->SetTransition(PaginationModel::Transition(kStartPage + 1, 0.5)); + pagination()->StartScroll(); + pagination()->UpdateScroll(0.1); + EXPECT_EQ(kStartPage + 1, pagination()->transition().target_page); + EXPECT_EQ(0.4, pagination()->transition().progress); + pagination()->EndScroll(true); } TEST_F(PaginationModelTest, LongScroll) { @@ -329,31 +333,31 @@ // Scroll to the next page (negative delta) with a transition in the same // direction. And scroll enough to change page twice. SetStartPageAndExpects(kStartPage, 2, 0, 0); - pagination_.SetTransition(PaginationModel::Transition(kStartPage + 1, 0.5)); - pagination_.StartScroll(); - pagination_.UpdateScroll(-0.1); - EXPECT_EQ(kStartPage + 1, pagination_.transition().target_page); - EXPECT_EQ(0.6, pagination_.transition().progress); - pagination_.UpdateScroll(-0.5); + pagination()->SetTransition(PaginationModel::Transition(kStartPage + 1, 0.5)); + pagination()->StartScroll(); + pagination()->UpdateScroll(-0.1); + EXPECT_EQ(kStartPage + 1, pagination()->transition().target_page); + EXPECT_EQ(0.6, pagination()->transition().progress); + pagination()->UpdateScroll(-0.5); EXPECT_EQ(1, observer_.selection_count()); - pagination_.UpdateScroll(-0.5); - EXPECT_EQ(kStartPage + 2, pagination_.transition().target_page); - pagination_.EndScroll(false); + pagination()->UpdateScroll(-0.5); + EXPECT_EQ(kStartPage + 2, pagination()->transition().target_page); + pagination()->EndScroll(false); base::RunLoop().Run(); EXPECT_EQ(2, observer_.selection_count()); // Scroll to the next page (negative delta) with a transition in a different // direction. And scroll enough to revert it and switch page once. SetStartPageAndExpects(kStartPage, 1, 0, 0); - pagination_.SetTransition(PaginationModel::Transition(kStartPage - 1, 0.5)); - pagination_.StartScroll(); - pagination_.UpdateScroll(-0.1); - EXPECT_EQ(kStartPage - 1, pagination_.transition().target_page); - EXPECT_EQ(0.4, pagination_.transition().progress); - pagination_.UpdateScroll(-0.5); // This clears the transition. - pagination_.UpdateScroll(-0.5); // This starts a new transition. - EXPECT_EQ(kStartPage + 1, pagination_.transition().target_page); - pagination_.EndScroll(false); + pagination()->SetTransition(PaginationModel::Transition(kStartPage - 1, 0.5)); + pagination()->StartScroll(); + pagination()->UpdateScroll(-0.1); + EXPECT_EQ(kStartPage - 1, pagination()->transition().target_page); + EXPECT_EQ(0.4, pagination()->transition().progress); + pagination()->UpdateScroll(-0.5); // This clears the transition. + pagination()->UpdateScroll(-0.5); // This starts a new transition. + EXPECT_EQ(kStartPage + 1, pagination()->transition().target_page); + pagination()->EndScroll(false); base::RunLoop().Run(); EXPECT_EQ(1, observer_.selection_count()); @@ -361,31 +365,31 @@ // Scroll to the previous page (positive delta) with a transition in the same // direction. And scroll enough to change page twice. SetStartPageAndExpects(kStartPage, 2, 0, 0); - pagination_.SetTransition(PaginationModel::Transition(kStartPage - 1, 0.5)); - pagination_.StartScroll(); - pagination_.UpdateScroll(0.1); - EXPECT_EQ(kStartPage - 1, pagination_.transition().target_page); - EXPECT_EQ(0.6, pagination_.transition().progress); - pagination_.UpdateScroll(0.5); + pagination()->SetTransition(PaginationModel::Transition(kStartPage - 1, 0.5)); + pagination()->StartScroll(); + pagination()->UpdateScroll(0.1); + EXPECT_EQ(kStartPage - 1, pagination()->transition().target_page); + EXPECT_EQ(0.6, pagination()->transition().progress); + pagination()->UpdateScroll(0.5); EXPECT_EQ(1, observer_.selection_count()); - pagination_.UpdateScroll(0.5); - EXPECT_EQ(kStartPage - 2, pagination_.transition().target_page); - pagination_.EndScroll(false); + pagination()->UpdateScroll(0.5); + EXPECT_EQ(kStartPage - 2, pagination()->transition().target_page); + pagination()->EndScroll(false); base::RunLoop().Run(); EXPECT_EQ(2, observer_.selection_count()); // Scroll to the previous page (positive delta) with a transition in a // different direction. And scroll enough to revert it and switch page once. SetStartPageAndExpects(kStartPage, 1, 0, 0); - pagination_.SetTransition(PaginationModel::Transition(kStartPage + 1, 0.5)); - pagination_.StartScroll(); - pagination_.UpdateScroll(0.1); - EXPECT_EQ(kStartPage + 1, pagination_.transition().target_page); - EXPECT_EQ(0.4, pagination_.transition().progress); - pagination_.UpdateScroll(0.5); // This clears the transition. - pagination_.UpdateScroll(0.5); // This starts a new transition. - EXPECT_EQ(kStartPage - 1, pagination_.transition().target_page); - pagination_.EndScroll(false); + pagination()->SetTransition(PaginationModel::Transition(kStartPage + 1, 0.5)); + pagination()->StartScroll(); + pagination()->UpdateScroll(0.1); + EXPECT_EQ(kStartPage + 1, pagination()->transition().target_page); + EXPECT_EQ(0.4, pagination()->transition().progress); + pagination()->UpdateScroll(0.5); // This clears the transition. + pagination()->UpdateScroll(0.5); // This starts a new transition. + EXPECT_EQ(kStartPage - 1, pagination()->transition().target_page); + pagination()->EndScroll(false); base::RunLoop().Run(); EXPECT_EQ(1, observer_.selection_count()); } @@ -396,68 +400,68 @@ // Scroll to next page then revert the scroll and make sure transition // progress 0 is fired when previous scroll is cleared. SetStartPageAndExpects(kStartPage, 0, 0, 0); - pagination_.StartScroll(); - pagination_.UpdateScroll(-0.1); + pagination()->StartScroll(); + pagination()->UpdateScroll(-0.1); int target_page = kStartPage + 1; - EXPECT_EQ(target_page, pagination_.transition().target_page); + EXPECT_EQ(target_page, pagination()->transition().target_page); observer_.set_transition_page(target_page); - pagination_.UpdateScroll(0.2); // This clears the transition. + pagination()->UpdateScroll(0.2); // This clears the transition. EXPECT_EQ(1, observer_.transition_start_count()); - pagination_.EndScroll(true); // Cancel transition. + pagination()->EndScroll(true); // Cancel transition. // Similar to above but in the other direction. SetStartPageAndExpects(kStartPage, 0, 0, 0); - pagination_.StartScroll(); - pagination_.UpdateScroll(0.1); + pagination()->StartScroll(); + pagination()->UpdateScroll(0.1); target_page = kStartPage - 1; - EXPECT_EQ(target_page, pagination_.transition().target_page); + EXPECT_EQ(target_page, pagination()->transition().target_page); observer_.set_transition_page(target_page); - pagination_.UpdateScroll(-0.2); // This clears the transition. + pagination()->UpdateScroll(-0.2); // This clears the transition. EXPECT_EQ(1, observer_.transition_start_count()); - pagination_.EndScroll(true); // Cancel transition. + pagination()->EndScroll(true); // Cancel transition. } TEST_F(PaginationModelTest, SelectedPageIsLost) { - pagination_.SetTotalPages(2); + pagination()->SetTotalPages(2); // The selected page is set to 0 once the total number of pages are set. - EXPECT_EQ(0, pagination_.selected_page()); + EXPECT_EQ(0, pagination()->selected_page()); - pagination_.SelectPage(1, false /* animate */); - EXPECT_EQ(1, pagination_.selected_page()); + pagination()->SelectPage(1, /*animate=*/false); + EXPECT_EQ(1, pagination()->selected_page()); // The selected page is unchanged if it's still valid. - pagination_.SetTotalPages(3); - EXPECT_EQ(1, pagination_.selected_page()); - pagination_.SetTotalPages(2); - EXPECT_EQ(1, pagination_.selected_page()); + pagination()->SetTotalPages(3); + EXPECT_EQ(1, pagination()->selected_page()); + pagination()->SetTotalPages(2); + EXPECT_EQ(1, pagination()->selected_page()); // But if the currently selected_page exceeds the total number of pages, // it automatically switches to the last page. - pagination_.SetTotalPages(1); - EXPECT_EQ(0, pagination_.selected_page()); + pagination()->SetTotalPages(1); + EXPECT_EQ(0, pagination()->selected_page()); } TEST_F(PaginationModelTest, SelectPageRelativeBeginning) { // Test starts with 5 pages. Select Page 1. - pagination_.SelectPage(1, false); + pagination()->SelectPage(1, false); - pagination_.SelectPageRelative(-1, false); - EXPECT_EQ(0, pagination_.selected_page()); + pagination()->SelectPageRelative(-1, false); + EXPECT_EQ(0, pagination()->selected_page()); } TEST_F(PaginationModelTest, SelectPageRelativeMiddle) { // Test starts with 5 pages. Select page 2. - pagination_.SelectPage(2, false); + pagination()->SelectPage(2, false); - pagination_.SelectPageRelative(-1, false); - EXPECT_EQ(1, pagination_.selected_page()); + pagination()->SelectPageRelative(-1, false); + EXPECT_EQ(1, pagination()->selected_page()); - pagination_.SelectPageRelative(1, false); - EXPECT_EQ(2, pagination_.selected_page()); + pagination()->SelectPageRelative(1, false); + EXPECT_EQ(2, pagination()->selected_page()); } } // namespace test
diff --git a/ash/public/cpp/tablet_mode.cc b/ash/public/cpp/tablet_mode.cc index a0e5be2..3f3fa798 100644 --- a/ash/public/cpp/tablet_mode.cc +++ b/ash/public/cpp/tablet_mode.cc
@@ -26,4 +26,26 @@ g_instance = nullptr; } +TabletMode::Waiter::Waiter(bool enable) : enable_(enable) { + TabletMode::Get()->AddObserver(this); +} + +TabletMode::Waiter::~Waiter() { + TabletMode::Get()->RemoveObserver(this); +} + +void TabletMode::Waiter::Wait() { + run_loop_.Run(); +} + +void TabletMode::Waiter::OnTabletModeStarted() { + if (enable_) + run_loop_.QuitWhenIdle(); +} + +void TabletMode::Waiter::OnTabletModeEnded() { + if (!enable_) + run_loop_.QuitWhenIdle(); +} + } // namespace ash
diff --git a/ash/public/cpp/tablet_mode.h b/ash/public/cpp/tablet_mode.h index 9f71113c..7cfeae3 100644 --- a/ash/public/cpp/tablet_mode.h +++ b/ash/public/cpp/tablet_mode.h
@@ -6,20 +6,39 @@ #define ASH_PUBLIC_CPP_TABLET_MODE_H_ #include "ash/public/cpp/ash_public_export.h" +#include "ash/public/cpp/tablet_mode_observer.h" +#include "base/run_loop.h" namespace ash { -class TabletModeToggleObserver; - // An interface implemented by Ash that allows Chrome to be informed of changes // to tablet mode state. class ASH_PUBLIC_EXPORT TabletMode { public: + // Helper class to wait until the tablet mode transition is complete. + class Waiter : public TabletModeObserver { + public: + explicit Waiter(bool enable); + ~Waiter() override; + + void Wait(); + + // TabletModeObserver: + void OnTabletModeStarted() override; + void OnTabletModeEnded() override; + + private: + bool enable_; + base::RunLoop run_loop_; + + DISALLOW_COPY_AND_ASSIGN(Waiter); + }; + // Returns the singleton instance. static TabletMode* Get(); - virtual void SetTabletModeToggleObserver( - TabletModeToggleObserver* observer) = 0; + virtual void AddObserver(TabletModeObserver* observer) = 0; + virtual void RemoveObserver(TabletModeObserver* observer) = 0; // Returns true if the system is in tablet mode. virtual bool InTabletMode() const = 0;
diff --git a/ash/wm/tablet_mode/tablet_mode_observer.h b/ash/public/cpp/tablet_mode_observer.h similarity index 84% rename from ash/wm/tablet_mode/tablet_mode_observer.h rename to ash/public/cpp/tablet_mode_observer.h index bcf7a45e..99a60cf0 100644 --- a/ash/wm/tablet_mode/tablet_mode_observer.h +++ b/ash/public/cpp/tablet_mode_observer.h
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_WM_TABLET_MODE_TABLET_MODE_OBSERVER_H_ -#define ASH_WM_TABLET_MODE_TABLET_MODE_OBSERVER_H_ +#ifndef ASH_PUBLIC_CPP_TABLET_MODE_OBSERVER_H_ +#define ASH_PUBLIC_CPP_TABLET_MODE_OBSERVER_H_ -#include "ash/ash_export.h" +#include "ash/public/cpp/ash_public_export.h" namespace ash { // Used to observe tablet mode changes inside ash. Exported for tests. // NOTE: Code in chrome should use TabletModeClientObserver. -class ASH_EXPORT TabletModeObserver { +class ASH_PUBLIC_EXPORT TabletModeObserver { public: // Called when the tablet mode is about to start. virtual void OnTabletModeStarting() {} @@ -42,4 +42,4 @@ } // namespace ash -#endif // ASH_WM_TABLET_MODE_TABLET_MODE_OBSERVER_H_ +#endif // ASH_PUBLIC_CPP_TABLET_MODE_OBSERVER_H_
diff --git a/ash/public/cpp/tablet_mode_toggle_observer.h b/ash/public/cpp/tablet_mode_toggle_observer.h deleted file mode 100644 index 4bd0d200..0000000 --- a/ash/public/cpp/tablet_mode_toggle_observer.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ASH_PUBLIC_CPP_TABLET_MODE_TOGGLE_OBSERVER_H_ -#define ASH_PUBLIC_CPP_TABLET_MODE_TOGGLE_OBSERVER_H_ - -#include "ash/public/cpp/ash_public_export.h" - -namespace ash { - -// A simplified observer which allows Ash to inform Chrome when tablet mode has -// been enabled or disabled. -class ASH_PUBLIC_EXPORT TabletModeToggleObserver { - public: - // Fired after the tablet mode has been toggled. - virtual void OnTabletModeToggled(bool enabled) = 0; - - protected: - virtual ~TabletModeToggleObserver() = default; -}; - -} // namespace ash - -#endif // ASH_PUBLIC_CPP_TABLET_MODE_TOGGLE_OBSERVER_H_
diff --git a/ash/public/cpp/test/shell_test_api.h b/ash/public/cpp/test/shell_test_api.h index fb0610b..daa84c8 100644 --- a/ash/public/cpp/test/shell_test_api.h +++ b/ash/public/cpp/test/shell_test_api.h
@@ -63,8 +63,12 @@ // password dialog). bool IsSystemModalWindowOpen(); - // Enables or disables the tablet mode. - void SetTabletModeEnabledForTest(bool enable); + // Enables or disables the tablet mode. TabletMode switch can be + // asynchronous, and this will wait until the transition is complete + // by default. Set |wait_for_completion| to false if you do not want + // to wait. + void SetTabletModeEnabledForTest(bool enable, + bool wait_for_completion = true); // Enables the keyboard and associates it with the primary root window // controller. In tablet mode, enables the virtual keyboard.
diff --git a/ash/public/cpp/vector_icons/BUILD.gn b/ash/public/cpp/vector_icons/BUILD.gn index e9fd7e6a..38281b02 100644 --- a/ash/public/cpp/vector_icons/BUILD.gn +++ b/ash/public/cpp/vector_icons/BUILD.gn
@@ -9,40 +9,15 @@ icon_directory = "." icons = [ - "assistant.icon", - "assistant_mic.icon", "notification_assistant.icon", - "notification_captive_portal.icon", - "notification_battery.icon", - "notification_cellular_alert.icon", - "notification_download.icon", - "notification_end_of_support.icon", - "window_control_dezoom.icon", - "window_control_back.icon", - "window_control_menu.icon", - "window_control_zoom.icon", - "notification_family_link.icon", - "notification_google.icon", - "notification_image.icon", - "notification_installed.icon", - "notification_linux.icon", - "notification_messages.icon", - "notification_mobile_data.icon", - "notification_mobile_data_off.icon", - "notification_multi_device_setup.icon", - "notification_play_prism.icon", - "notification_plugin_vm.icon", - "notification_printing.icon", - "notification_printing_done.icon", - "notification_printing_warning.icon", - "notification_settings.icon", - "notification_storage_full.icon", "notification_supervised_user.icon", - "notification_vpn.icon", "notification_warning.icon", - "notification_wifi_off.icon", + "window_control_back.icon", + "window_control_dezoom.icon", "window_control_left_snapped.icon", + "window_control_menu.icon", "window_control_right_snapped.icon", + "window_control_zoom.icon", ] }
diff --git a/ash/public/cpp/vector_icons/notification_play_prism.icon b/ash/public/cpp/vector_icons/notification_play_prism.icon deleted file mode 100644 index 3f3f637..0000000 --- a/ash/public/cpp/vector_icons/notification_play_prism.icon +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -CANVAS_DIMENSIONS, 96, -MOVE_TO, 77.08f, 44.91f, -R_LINE_TO, -10.88f, -6.35f, -LINE_TO, 56.04f, 49, -R_LINE_TO, 10.17f, 10.44f, -R_LINE_TO, 10.88f, -6.35f, -CUBIC_TO, 79.04f, 51.96f, 80, 50.5f, 80, 49, -R_CUBIC_TO, 0, -1.5f, -0.96f, -2.96f, -2.92f, -4.09f, -CLOSE, -MOVE_TO, 22.08f, 14.13f, -R_LINE_TO, 29.94f, 30.74f, -R_LINE_TO, 9.07f, -9.31f, -LINE_TO, 23.04f, 13.44f, -R_CUBIC_TO, -0.25f, -0.15f, -0.5f, -0.26f, -0.75f, -0.37f, -R_CUBIC_TO, -0.6f, -0.25f, -1.07f, 0.18f, -0.53f, 0.77f, -R_CUBIC_TO, 0.11f, 0.07f, 0.21f, 0.18f, 0.32f, 0.29f, -CLOSE, -R_MOVE_TO, 0, 69.74f, -R_LINE_TO, -0.28f, 0.29f, -R_CUBIC_TO, -0.53f, 0.55f, -0.07f, 1.02f, 0.53f, 0.77f, -R_CUBIC_TO, 0.25f, -0.11f, 0.5f, -0.22f, 0.75f, -0.37f, -R_LINE_TO, 38.01f, -22.13f, -R_LINE_TO, -9.07f, -9.31f, -CUBIC_TO_SHORTHAND, 26.42f, 79.45f, 22.08f, 83.87f, -CLOSE, -MOVE_TO, 48, 49, -LINE_TO, 17.35f, 17.53f, -R_CUBIC_TO, -0.67f, -0.69f, -1.35f, -0.26f, -1.35f, 0.69f, -V_LINE_TO, 79.78f, -R_CUBIC_TO, 0, 0.95f, 0.68f, 1.39f, 1.35f, 0.7f, -LINE_TO, 48, 49, -CLOSE
diff --git a/ash/public/cpp/vector_icons/notification_settings.icon b/ash/public/cpp/vector_icons/notification_settings.icon deleted file mode 100644 index 133f039..0000000 --- a/ash/public/cpp/vector_icons/notification_settings.icon +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -CANVAS_DIMENSIONS, 24, -MOVE_TO, 19.63f, 12.98f, -R_CUBIC_TO, 0.04f, -0.32f, 0.07f, -0.64f, 0.07f, -0.97f, -R_CUBIC_TO, 0, -0.33f, -0.03f, -0.65f, -0.07f, -0.97f, -R_LINE_TO, 2.17f, -1.65f, -R_CUBIC_TO, 0.2f, -0.15f, 0.25f, -0.42f, 0.12f, -0.64f, -R_LINE_TO, -2.06f, -3.46f, -R_CUBIC_TO, -0.13f, -0.21f, -0.39f, -0.3f, -0.63f, -0.21f, -R_LINE_TO, -2.56f, 1, -R_CUBIC_TO, -0.53f, -0.39f, -1.11f, -0.73f, -1.74f, -0.98f, -R_LINE_TO, -0.38f, -2.65f, -R_CUBIC_TO, -0.05f, -0.23f, -0.26f, -0.42f, -0.51f, -0.42f, -R_H_LINE_TO, -4.11f, -R_CUBIC_TO, -0.26f, 0, -0.47f, 0.19f, -0.51f, 0.42f, -R_LINE_TO, -0.38f, 2.65f, -R_CUBIC_TO, -0.63f, 0.26f, -1.21f, 0.59f, -1.74f, 0.99f, -LINE_TO, 4.75f, 5.05f, -R_CUBIC_TO, -0.23f, -0.08f, -0.5f, 0, -0.63f, 0.22f, -LINE_TO, 2.07f, 8.73f, -R_CUBIC_TO, -0.13f, 0.22f, -0.07f, 0.49f, 0.12f, 0.64f, -R_LINE_TO, 2.17f, 1.66f, -R_CUBIC_TO, -0.04f, 0.32f, -0.07f, 0.65f, -0.07f, 0.98f, -R_CUBIC_TO, 0, 0.33f, 0.03f, 0.66f, 0.07f, 0.98f, -LINE_TO, 2.19f, 14.63f, -R_CUBIC_TO, -0.19f, 0.15f, -0.25f, 0.42f, -0.12f, 0.64f, -R_LINE_TO, 2.06f, 3.47f, -R_CUBIC_TO, 0.13f, 0.22f, 0.4f, 0.31f, 0.63f, 0.22f, -R_LINE_TO, 2.56f, -1, -R_CUBIC_TO, 0.53f, 0.4f, 1.11f, 0.73f, 1.74f, 0.99f, -R_LINE_TO, 0.39f, 2.65f, -R_CUBIC_TO, 0.04f, 0.24f, 0.25f, 0.42f, 0.51f, 0.42f, -R_H_LINE_TO, 4.11f, -R_CUBIC_TO, 0.26f, 0, 0.47f, -0.18f, 0.51f, -0.42f, -R_LINE_TO, 0.38f, -2.65f, -R_CUBIC_TO, 0.63f, -0.25f, 1.21f, -0.58f, 1.74f, -0.98f, -R_LINE_TO, 2.56f, 1, -R_CUBIC_TO, 0.23f, 0.09f, 0.5f, 0, 0.63f, -0.21f, -R_LINE_TO, 2.06f, -3.46f, -R_CUBIC_TO, 0.13f, -0.21f, 0.07f, -0.48f, -0.12f, -0.64f, -R_LINE_TO, -2.17f, -1.65f, -CLOSE, -MOVE_TO, 12, 15, -R_CUBIC_TO, -1.66f, 0, -3, -1.34f, -3, -3, -R_CUBIC_TO, 0, -1.66f, 1.34f, -3, 3, -3, -R_CUBIC_TO, 1.66f, 0, 3, 1.34f, 3, 3, -R_CUBIC_TO, 0, 1.66f, -1.34f, 3, -3, 3, -CLOSE
diff --git a/ash/public/cpp/vector_icons/notification_warning.icon b/ash/public/cpp/vector_icons/notification_warning.icon index 146fa3c..a4b57e6 100644 --- a/ash/public/cpp/vector_icons/notification_warning.icon +++ b/ash/public/cpp/vector_icons/notification_warning.icon
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// Similar to warning.icon, but uses a circle in place of a triangle. CANVAS_DIMENSIONS, 96, MOVE_TO, 48, 8, R_CUBIC_TO, 22.08f, 0, 40, 17.92f, 40, 40,
diff --git a/ash/resources/vector_icons/BUILD.gn b/ash/resources/vector_icons/BUILD.gn index bcc1d565..d732c83 100644 --- a/ash/resources/vector_icons/BUILD.gn +++ b/ash/resources/vector_icons/BUILD.gn
@@ -10,6 +10,8 @@ icons = [ "always_show_shelf.icon", + "assistant.icon", + "assistant_mic.icon", "auto_hide.icon", "autoclick.icon", "autoclick_close.icon", @@ -95,6 +97,7 @@ "notification_keyboard.icon", "notification_low_power_charger.icon", "notification_monitor_warning.icon", + "notification_multi_device_setup.icon", "notification_screen.icon", "notification_screenshare.icon", "notification_sms_sync.icon", @@ -102,6 +105,8 @@ "notification_timer.icon", "overview_window_close.icon", "overview_drop_target_plus.icon", + "overflow_shelf_left.icon", + "overflow_shelf_right.icon", "palette_action_capture_region.icon", "palette_action_capture_screen.icon", "palette_action_create_note.icon",
diff --git a/ash/public/cpp/vector_icons/assistant.icon b/ash/resources/vector_icons/assistant.icon similarity index 100% rename from ash/public/cpp/vector_icons/assistant.icon rename to ash/resources/vector_icons/assistant.icon
diff --git a/ash/public/cpp/vector_icons/assistant_mic.icon b/ash/resources/vector_icons/assistant_mic.icon similarity index 100% rename from ash/public/cpp/vector_icons/assistant_mic.icon rename to ash/resources/vector_icons/assistant_mic.icon
diff --git a/ash/public/cpp/vector_icons/notification_multi_device_setup.icon b/ash/resources/vector_icons/notification_multi_device_setup.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_multi_device_setup.icon rename to ash/resources/vector_icons/notification_multi_device_setup.icon
diff --git a/ash/resources/vector_icons/overflow_shelf_left.icon b/ash/resources/vector_icons/overflow_shelf_left.icon new file mode 100644 index 0000000..52e7fab --- /dev/null +++ b/ash/resources/vector_icons/overflow_shelf_left.icon
@@ -0,0 +1,12 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +CANVAS_DIMENSIONS, 20, +MOVE_TO, 13.34f, 13.83f, +LINE_TO, 12.07f, 15, +LINE_TO, 6.67f, 10, +R_LINE_TO, 5.4f, -5, +R_LINE_TO, 1.27f, 1.18f, +LINE_TO, 9.22f, 10, +CLOSE
diff --git a/ash/resources/vector_icons/overflow_shelf_right.icon b/ash/resources/vector_icons/overflow_shelf_right.icon new file mode 100644 index 0000000..8ad5d61 --- /dev/null +++ b/ash/resources/vector_icons/overflow_shelf_right.icon
@@ -0,0 +1,12 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +CANVAS_DIMENSIONS, 20, +MOVE_TO, 6.67f, 13.83f, +LINE_TO, 10.79f, 10, +LINE_TO, 6.67f, 6.18f, +LINE_TO, 7.94f, 5, +R_LINE_TO, 5.4f, 5, +R_LINE_TO, -5.4f, 5, +CLOSE
diff --git a/ash/shelf/default_shelf_view.cc b/ash/shelf/default_shelf_view.cc index 03ee3fe..42b7d633 100644 --- a/ash/shelf/default_shelf_view.cc +++ b/ash/shelf/default_shelf_view.cc
@@ -56,13 +56,13 @@ // button. int GetSizeOfAppIcons(int count, bool with_overflow) { if (count == 0) - return with_overflow ? kShelfControlSize : 0; + return with_overflow ? ShelfConstants::control_size() : 0; - const int app_size = count * kShelfButtonSize; + const int app_size = count * ShelfConstants::button_size(); int overflow_size = 0; int total_padding = ShelfConstants::button_spacing() * (count - 1); if (with_overflow) { - overflow_size += kShelfControlSize; + overflow_size += ShelfConstants::control_size(); total_padding += kMarginBetweenAppsAndOverflow; } return app_size + total_padding + overflow_size; @@ -81,24 +81,27 @@ if (is_overflow_mode()) return; + const int control_size = ShelfConstants::control_size(); + const int button_size = ShelfConstants::button_size(); const int button_spacing = ShelfConstants::button_spacing(); + int x = shelf()->PrimaryAxisValue(button_spacing, 0); int y = shelf()->PrimaryAxisValue(0, button_spacing); - GetBackButton()->set_ideal_bounds(gfx::Rect( - x, y, shelf()->PrimaryAxisValue(kShelfControlSize, kShelfButtonSize), - shelf()->PrimaryAxisValue(kShelfButtonSize, kShelfControlSize))); + GetBackButton()->set_ideal_bounds( + gfx::Rect(x, y, shelf()->PrimaryAxisValue(control_size, button_size), + shelf()->PrimaryAxisValue(button_size, control_size))); // If we are not in tablet mode, the home button will get placed on top of // the (invisible) back button. if (IsTabletModeEnabled()) { - x = shelf()->PrimaryAxisValue(x + kShelfControlSize + button_spacing, x); - y = shelf()->PrimaryAxisValue(y, y + kShelfControlSize + button_spacing); + x = shelf()->PrimaryAxisValue(x + control_size + button_spacing, x); + y = shelf()->PrimaryAxisValue(y, y + control_size + button_spacing); } - GetHomeButton()->set_ideal_bounds(gfx::Rect( - x, y, shelf()->PrimaryAxisValue(kShelfControlSize, kShelfButtonSize), - shelf()->PrimaryAxisValue(kShelfButtonSize, kShelfControlSize))); + GetHomeButton()->set_ideal_bounds( + gfx::Rect(x, y, shelf()->PrimaryAxisValue(control_size, button_size), + shelf()->PrimaryAxisValue(button_size, control_size))); } void DefaultShelfView::Init() { @@ -181,7 +184,7 @@ } else { padding_for_centering = kShelfButtonSpacing + - (IsTabletModeEnabled() ? 2 : 1) * kShelfControlSize + + (IsTabletModeEnabled() ? 2 : 1) * ShelfConstants::control_size() + kAppIconGroupMargin + (available_size_for_app_icons - icons_size) / 2; } @@ -199,11 +202,13 @@ continue; } - view_model()->set_ideal_bounds( - i, gfx::Rect(x, y, kShelfButtonSize, kShelfButtonSize)); + const int button_size = ShelfConstants::button_size(); - x = shelf()->PrimaryAxisValue(x + kShelfButtonSize + button_spacing, x); - y = shelf()->PrimaryAxisValue(y, y + kShelfButtonSize + button_spacing); + view_model()->set_ideal_bounds(i, + gfx::Rect(x, y, button_size, button_size)); + + x = shelf()->PrimaryAxisValue(x + button_size + button_spacing, x); + y = shelf()->PrimaryAxisValue(y, y + button_size + button_spacing); if (i == separator_index) { // Place the separator halfway between the two icons it separates, @@ -262,16 +267,17 @@ const int button_spacing = ShelfConstants::button_spacing(); // "Secondary" as in "orthogonal to the shelf primary axis". const int control_secondary_padding = - (ShelfConstants::shelf_size() - kShelfControlSize) / 2; + (ShelfConstants::shelf_size() - ShelfConstants::control_size()) / 2; const int back_and_app_list_background_size = - kShelfControlSize + - (IsTabletModeEnabled() ? kShelfControlSize + button_spacing : 0); + ShelfConstants::control_size() + + (IsTabletModeEnabled() ? ShelfConstants::control_size() + button_spacing + : 0); back_and_app_list_background_->SetBounds( shelf()->PrimaryAxisValue(button_spacing, control_secondary_padding), shelf()->PrimaryAxisValue(control_secondary_padding, button_spacing), shelf()->PrimaryAxisValue(back_and_app_list_background_size, - kShelfControlSize), - shelf()->PrimaryAxisValue(kShelfControlSize, + ShelfConstants::control_size()), + shelf()->PrimaryAxisValue(ShelfConstants::control_size(), back_and_app_list_background_size)); } @@ -287,7 +293,7 @@ // Subtract space already allocated to the home button, and the back // button if applicable. return shelf()->PrimaryAxisValue(width(), height()) - kShelfButtonSpacing - - (IsTabletModeEnabled() ? 2 : 1) * kShelfControlSize - + (IsTabletModeEnabled() ? 2 : 1) * ShelfConstants::control_size() - 2 * kAppIconGroupMargin; }
diff --git a/ash/shelf/home_button.cc b/ash/shelf/home_button.cc index caaaffc..9e017d10 100644 --- a/ash/shelf/home_button.cc +++ b/ash/shelf/home_button.cc
@@ -131,8 +131,8 @@ // Increase clickable area for the button from // (kShelfControlSize x kShelfButtonSize) to // (kShelfButtonSize x kShelfButtonSize). - int left_offset = button_bounds.width() - kShelfButtonSize; - int bottom_offset = button_bounds.height() - kShelfButtonSize; + int left_offset = button_bounds.width() - ShelfConstants::button_size(); + int bottom_offset = button_bounds.height() - ShelfConstants::button_size(); button_bounds.Inset(gfx::Insets(0, left_offset, bottom_offset, 0)); return button_bounds.Intersects(rect); }
diff --git a/ash/shelf/home_button_controller.h b/ash/shelf/home_button_controller.h index d9cff5f..ef8979f 100644 --- a/ash/shelf/home_button_controller.h +++ b/ash/shelf/home_button_controller.h
@@ -9,9 +9,9 @@ #include "ash/app_list/app_list_controller_observer.h" #include "ash/public/cpp/assistant/default_voice_interaction_observer.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/public/interfaces/voice_interaction_controller.mojom.h" #include "ash/session/session_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" namespace base {
diff --git a/ash/shelf/kiosk_next_shelf_view.cc b/ash/shelf/kiosk_next_shelf_view.cc index ac21bd5e..46f25af 100644 --- a/ash/shelf/kiosk_next_shelf_view.cc +++ b/ash/shelf/kiosk_next_shelf_view.cc
@@ -134,7 +134,7 @@ void KioskNextShelfView::CalculateIdealBounds() { DCHECK(shelf()->IsHorizontalAlignment()); DCHECK_EQ(0, model()->item_count()); - DCHECK_GE(kShelfSize, kKioskNextShelfControlHeightDp); + DCHECK_GE(ShelfConstants::shelf_size(), kKioskNextShelfControlHeightDp); // TODO(https://crbug.com/965690): Button spacing might be relative to shelf // width. Reevaluate this piece once visual spec is available. @@ -146,7 +146,7 @@ shelf_widget()->GetWindowBoundsInScreen().width(); int x = total_shelf_width / 2 - kKioskNextShelfControlWidthDp - control_buttons_spacing / 2; - int y = (kShelfSize - kKioskNextShelfControlHeightDp) / 2; + int y = (ShelfConstants::shelf_size() - kKioskNextShelfControlHeightDp) / 2; GetBackButton()->set_ideal_bounds(gfx::Rect( x, y, kKioskNextShelfControlWidthDp, kKioskNextShelfControlHeightDp));
diff --git a/ash/shelf/overflow_bubble_view.cc b/ash/shelf/overflow_bubble_view.cc index 26b1f8c8..a450873 100644 --- a/ash/shelf/overflow_bubble_view.cc +++ b/ash/shelf/overflow_bubble_view.cc
@@ -7,6 +7,7 @@ #include <algorithm> #include "ash/public/cpp/shell_window_ids.h" +#include "ash/resources/vector_icons/vector_icons.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_constants.h" #include "ash/shelf/shelf_view.h" @@ -17,13 +18,20 @@ #include "ui/display/screen.h" #include "ui/events/event.h" #include "ui/gfx/geometry/insets.h" +#include "ui/gfx/image/image_skia_operations.h" +#include "ui/gfx/paint_vector_icon.h" +#include "ui/gfx/scoped_canvas.h" #include "ui/views/widget/widget.h" namespace ash { namespace { -// Padding at the two ends of the bubble. -constexpr int kEndPadding = 16; +// Padding at the two ends of the shelf in overflow mode. +constexpr int kEndPadding = 4; + +// Padding between the end of the shelf in overview mode and the arrow button +// (if any). +constexpr int kDistanceToArrowButton = kShelfButtonSpacing; // Distance between overflow bubble and the main shelf. constexpr int kDistanceToMainShelf = 4; @@ -31,14 +39,110 @@ // Minimum margin around the bubble so that it doesn't hug the screen edges. constexpr int kMinimumMargin = 8; +// Size of the arrow button. +constexpr int kArrowButtonSize = kShelfControlSize; + +// Sum of the shelf button size and the gap between shelf buttons. +constexpr int kUnit = kShelfButtonSize + kShelfButtonSpacing; + } // namespace +//////////////////////////////////////////////////////////////////////////////// +// ScrollArrowView + +OverflowBubbleView::ScrollArrowView::ScrollArrowView( + ArrowType arrow_type, + bool is_horizontal_alignment) + : arrow_type_(arrow_type), + is_horizontal_alignment_(is_horizontal_alignment) { + SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); +} + +void OverflowBubbleView::ScrollArrowView::OnPaint(gfx::Canvas* canvas) { + gfx::ImageSkia img = CreateVectorIcon( + arrow_type_ == LEFT ? kOverflowShelfLeftIcon : kOverflowShelfRightIcon, + SK_ColorWHITE); + + if (!is_horizontal_alignment_) { + img = gfx::ImageSkiaOperations::CreateRotatedImage( + img, SkBitmapOperations::ROTATION_90_CW); + } + + gfx::PointF center_point(width() / 2.f, height() / 2.f); + canvas->DrawImageInt(img, center_point.x() - img.width() / 2, + center_point.y() - img.height() / 2); + + float ring_radius_dp = kArrowButtonSize / 2; + { + gfx::PointF circle_center(center_point); + gfx::ScopedCanvas scoped_canvas(canvas); + const float dsf = canvas->UndoDeviceScaleFactor(); + circle_center.Scale(dsf); + cc::PaintFlags fg_flags; + fg_flags.setAntiAlias(true); + fg_flags.setColor(kShelfControlPermanentHighlightBackground); + + const float radius = std::ceil(ring_radius_dp * dsf); + canvas->DrawCircle(circle_center, radius, fg_flags); + } +} + +const char* OverflowBubbleView::ScrollArrowView::GetClassName() const { + return "ScrollArrowView"; +} + +//////////////////////////////////////////////////////////////////////////////// +// OverflowShelfContainerView impl + +OverflowBubbleView::OverflowShelfContainerView::OverflowShelfContainerView( + ShelfView* shelf_view) + : shelf_view_(shelf_view) {} + +void OverflowBubbleView::OverflowShelfContainerView::Initialize() { + SetPaintToLayer(); + layer()->SetFillsBoundsOpaquely(false); + layer()->SetMasksToBounds(true); + + shelf_view_->SetPaintToLayer(); + shelf_view_->layer()->SetFillsBoundsOpaquely(false); + AddChildView(shelf_view_); +} + +gfx::Size +OverflowBubbleView::OverflowShelfContainerView::CalculatePreferredSize() const { + return shelf_view_->CalculatePreferredSize(); +} + +void OverflowBubbleView::OverflowShelfContainerView::ChildPreferredSizeChanged( + views::View* child) { + PreferredSizeChanged(); +} + +void OverflowBubbleView::OverflowShelfContainerView::Layout() { + shelf_view_->SetBoundsRect( + gfx::Rect(gfx::Point(), shelf_view_->GetPreferredSize())); +} + +const char* OverflowBubbleView::OverflowShelfContainerView::GetClassName() + const { + return "OverflowShelfContainerView"; +} + +void OverflowBubbleView::OverflowShelfContainerView::TranslateShelfView( + const gfx::Vector2d& offset) { + gfx::Transform transform_matrix; + transform_matrix.Translate(-offset); + shelf_view_->SetTransform(transform_matrix); +} + +//////////////////////////////////////////////////////////////////////////////// +// OverflowBubbleView + OverflowBubbleView::OverflowBubbleView(ShelfView* shelf_view, views::View* anchor, SkColor background_color) : ShelfBubble(anchor, shelf_view->shelf()->alignment(), background_color), - shelf_(shelf_view->shelf()), - shelf_view_(shelf_view) { + shelf_(shelf_view->shelf()) { DCHECK(shelf_); set_border_radius(ShelfConstants::shelf_size() / 2); @@ -47,20 +151,29 @@ set_shadow(views::BubbleBorder::NO_ASSETS); set_close_on_deactivate(false); set_accept_events(true); - - if (shelf_->IsHorizontalAlignment()) - set_margins(gfx::Insets(0, kEndPadding)); - else - set_margins(gfx::Insets(kEndPadding, 0)); + set_margins(gfx::Insets(0, 0)); // Makes bubble view has a layer and clip its children layers. SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); layer()->SetMasksToBounds(true); - CreateBubble(); + // Initialize the left arrow button. + left_arrow_ = new ScrollArrowView(ScrollArrowView::LEFT, + shelf_->IsHorizontalAlignment()); + AddChildView(left_arrow_); - AddChildView(shelf_view_); + // Initialize the right arrow button. + right_arrow_ = new ScrollArrowView(ScrollArrowView::RIGHT, + shelf_->IsHorizontalAlignment()); + AddChildView(right_arrow_); + + // Initialize the shelf container view. + shelf_container_view_ = new OverflowShelfContainerView(shelf_view); + shelf_container_view_->Initialize(); + AddChildView(shelf_container_view_); + + CreateBubble(); } OverflowBubbleView::~OverflowBubbleView() = default; @@ -83,55 +196,184 @@ } int OverflowBubbleView::ScrollByXOffset(int x_offset) { - const gfx::Rect visible_bounds(GetContentsBounds()); - const gfx::Size contents_size(shelf_view_->GetPreferredSize()); - - DCHECK_GE(contents_size.width(), visible_bounds.width()); const int old_x = scroll_offset_.x(); - const int x = std::min(contents_size.width() - visible_bounds.width(), - std::max(0, old_x + x_offset)); + const int x = CalculateLayoutStrategyAfterScroll(x_offset); scroll_offset_.set_x(x); Layout(); return x - old_x; } int OverflowBubbleView::ScrollByYOffset(int y_offset) { - const gfx::Rect visible_bounds(GetContentsBounds()); - const gfx::Size contents_size(shelf_view_->GetPreferredSize()); - - DCHECK_GE(contents_size.height(), visible_bounds.height()); const int old_y = scroll_offset_.y(); - const int y = std::min(contents_size.height() - visible_bounds.height(), - std::max(0, old_y + y_offset)); + const int y = CalculateLayoutStrategyAfterScroll(y_offset); scroll_offset_.set_y(y); Layout(); return y - old_y; } -gfx::Size OverflowBubbleView::CalculatePreferredSize() const { - gfx::Size preferred_size = shelf_view_->GetPreferredSize(); +int OverflowBubbleView::CalculateScrollUpperBound() const { + const bool is_horizontal = shelf_->IsHorizontalAlignment(); - const gfx::Rect monitor_rect = + // Calculate the length of the available space. + const gfx::Rect content_size = GetContentsBounds(); + const int available_length = + (is_horizontal ? content_size.width() : content_size.height()) - + 2 * kEndPadding; + + // Calculate the length of the preferred size. + const gfx::Size shelf_preferred_size( + shelf_container_view_->GetPreferredSize()); + const int preferred_length = (is_horizontal ? shelf_preferred_size.width() + : shelf_preferred_size.height()); + + DCHECK_GE(preferred_length, available_length); + return preferred_length - available_length; +} + +int OverflowBubbleView::CalculateLayoutStrategyAfterScroll(int scroll) { + const int old_scroll = + shelf_->IsHorizontalAlignment() ? scroll_offset_.x() : scroll_offset_.y(); + + const int scroll_upper_bound = CalculateScrollUpperBound(); + scroll = std::min(scroll_upper_bound, std::max(0, old_scroll + scroll)); + if (layout_strategy_ != NOT_SHOW_ARROW_BUTTON) { + if (scroll <= 0) + layout_strategy_ = SHOW_RIGHT_ARROW_BUTTON; + else if (scroll >= scroll_upper_bound) + layout_strategy_ = SHOW_LEFT_ARROW_BUTTON; + else + layout_strategy_ = SHOW_BUTTONS; + } + return scroll; +} + +void OverflowBubbleView::AdjustToEnsureIconsFullyVisible( + gfx::Rect* bubble_bounds) const { + if (layout_strategy_ == NOT_SHOW_ARROW_BUTTON) + return; + + int width = shelf_->IsHorizontalAlignment() ? bubble_bounds->width() + : bubble_bounds->height(); + const int rd = width % kUnit; + width -= rd; + + // Offset to ensure that the bubble view is shown at the center of the screen. + if (shelf_->IsHorizontalAlignment()) { + bubble_bounds->set_width(width); + bubble_bounds->Offset(rd / 2, 0); + } else { + bubble_bounds->set_height(width); + bubble_bounds->Offset(0, rd / 2); + } +} + +gfx::Size OverflowBubbleView::CalculatePreferredSize() const { + gfx::Rect monitor_rect = display::Screen::GetScreen() ->GetDisplayNearestPoint(GetAnchorRect().CenterPoint()) .work_area(); - if (!monitor_rect.IsEmpty()) { - if (shelf_->IsHorizontalAlignment()) { - preferred_size.set_width(std::min( - preferred_size.width(), monitor_rect.width() - 2 * kEndPadding)); - } else { - preferred_size.set_height(std::min( - preferred_size.height(), monitor_rect.height() - 2 * kEndPadding)); - } + monitor_rect.Inset(gfx::Insets(kMinimumMargin)); + int available_length = shelf_->IsHorizontalAlignment() + ? monitor_rect.width() + : monitor_rect.height(); + + gfx::Size preferred_size = shelf_container_view_->GetPreferredSize(); + int preferred_length = shelf_->IsHorizontalAlignment() + ? preferred_size.width() + : preferred_size.height(); + preferred_length += 2 * kEndPadding; + int scroll_length = + shelf_->IsHorizontalAlignment() ? scroll_offset_.x() : scroll_offset_.y(); + + if (preferred_length <= available_length) { + // Enough space to accommodate all of shelf buttons. So hide arrow buttons. + layout_strategy_ = NOT_SHOW_ARROW_BUTTON; + } else if (scroll_length == 0) { + // No invisible shelf buttons at the left side. So hide the left button. + layout_strategy_ = SHOW_RIGHT_ARROW_BUTTON; + } else if (scroll_length == CalculateScrollUpperBound()) { + // If there is no invisible shelf button at the right side, hide the right + // button. + layout_strategy_ = SHOW_LEFT_ARROW_BUTTON; + } else { + // There are invisible shelf buttons at both sides. So show two buttons. + layout_strategy_ = SHOW_BUTTONS; } + if (shelf_->IsHorizontalAlignment()) { + preferred_size.set_width(std::min(preferred_length, monitor_rect.width())); + } else { + preferred_size.set_height( + std::min(preferred_length, monitor_rect.height())); + } return preferred_size; } void OverflowBubbleView::Layout() { - shelf_view_->SetBoundsRect( - gfx::Rect(gfx::PointAtOffsetFromOrigin(-scroll_offset_), - shelf_view_->GetPreferredSize())); + constexpr gfx::Size shelf_button_size(kShelfButtonSize, kShelfButtonSize); + constexpr gfx::Size arrow_button_size(kArrowButtonSize, kArrowButtonSize); + + bool is_horizontal = shelf_->IsHorizontalAlignment(); + gfx::Rect shelf_container_bounds = bounds(); + + // Transpose and layout as if it is horizontal. + if (!is_horizontal) + shelf_container_bounds.Transpose(); + + // The bounds of |left_arrow_| and |right_arrow_| in the parent coordinates. + gfx::Rect left_arrow_bounds, right_arrow_bounds; + + // Calculates the bounds of the left arrow button. If the left arrow button + // should not show, |left_arrow_bounds| should be empty. + if (layout_strategy_ == SHOW_LEFT_ARROW_BUTTON || + layout_strategy_ == SHOW_BUTTONS) { + left_arrow_bounds = gfx::Rect(shelf_button_size); + left_arrow_bounds.ClampToCenteredSize(arrow_button_size); + shelf_container_bounds.Inset(kShelfButtonSize + kDistanceToArrowButton, 0, + 0, 0); + } + + if (layout_strategy_ == SHOW_RIGHT_ARROW_BUTTON || + layout_strategy_ == SHOW_BUTTONS) { + shelf_container_bounds.Inset(0, 0, kShelfButtonSize, 0); + right_arrow_bounds = + gfx::Rect(shelf_container_bounds.top_right(), shelf_button_size); + right_arrow_bounds.ClampToCenteredSize(arrow_button_size); + shelf_container_bounds.Inset(0, 0, kDistanceToArrowButton, 0); + } + + shelf_container_bounds.Inset(kEndPadding, 0, kEndPadding, 0); + + // Adjust the bounds when not showing in the horizontal alignment. + if (!shelf_->IsHorizontalAlignment()) { + left_arrow_bounds.Transpose(); + right_arrow_bounds.Transpose(); + shelf_container_bounds.Transpose(); + } + + // Draw |left_arrow| if it should show. + left_arrow_->SetVisible(!left_arrow_bounds.IsEmpty()); + if (left_arrow_->GetVisible()) + left_arrow_->SetBoundsRect(left_arrow_bounds); + + // Draw |right_arrow| if it should show. + right_arrow_->SetVisible(!right_arrow_bounds.IsEmpty()); + if (right_arrow_->GetVisible()) + right_arrow_->SetBoundsRect(right_arrow_bounds); + + // Draw |shelf_container_view_|. + shelf_container_view_->SetBoundsRect(shelf_container_bounds); + + // When the left button shows, the origin of |shelf_container_view_| changes. + // So translate |shelf_container_view| to show the shelf view correctly. + gfx::Vector2d translate_vector; + if (!left_arrow_bounds.IsEmpty()) { + translate_vector = shelf_->IsHorizontalAlignment() + ? gfx::Vector2d(shelf_container_bounds.x(), 0) + : gfx::Vector2d(0, shelf_container_bounds.y()); + } + + shelf_container_view_->TranslateShelfView(scroll_offset_ + translate_vector); } void OverflowBubbleView::ChildPreferredSizeChanged(views::View* child) { @@ -175,7 +417,8 @@ const gfx::Size content_size = GetPreferredSize(); const gfx::Rect anchor_rect = GetAnchorRect(); const int distance_to_overflow_button = - kDistanceToMainShelf + (kShelfSize - kShelfControlSize) / 2; + kDistanceToMainShelf + + (ShelfConstants::shelf_size() - ShelfConstants::control_size()) / 2; gfx::Rect monitor_rect = display::Screen::GetScreen() ->GetDisplayNearestPoint(anchor_rect.CenterPoint()) @@ -183,31 +426,32 @@ // Make sure no part of the bubble touches a screen edge. monitor_rect.Inset(gfx::Insets(kMinimumMargin)); + gfx::Rect bounds; if (shelf_->IsHorizontalAlignment()) { - gfx::Rect bounds( - base::i18n::IsRTL() - ? anchor_rect.x() - kEndPadding - : anchor_rect.right() - content_size.width() - kEndPadding, + bounds = gfx::Rect( + base::i18n::IsRTL() ? anchor_rect.x() + : anchor_rect.right() - content_size.width(), anchor_rect.y() - distance_to_overflow_button - content_size.height(), - content_size.width() + 2 * kEndPadding, content_size.height()); + content_size.width(), content_size.height()); if (bounds.x() < monitor_rect.x()) bounds.Offset(monitor_rect.x() - bounds.x(), 0); if (bounds.right() > monitor_rect.right()) bounds.set_width(monitor_rect.right() - bounds.x()); - return bounds; + } else { + bounds = gfx::Rect(0, anchor_rect.bottom() - content_size.height(), + content_size.width(), content_size.height()); + if (shelf_->alignment() == SHELF_ALIGNMENT_LEFT) + bounds.set_x(anchor_rect.right() + distance_to_overflow_button); + else + bounds.set_x(anchor_rect.x() - distance_to_overflow_button - + content_size.width()); + if (bounds.y() < monitor_rect.y()) + bounds.Offset(0, monitor_rect.y() - bounds.y()); + if (bounds.bottom() > monitor_rect.bottom()) + bounds.set_height(monitor_rect.bottom() - bounds.y()); } - gfx::Rect bounds( - 0, anchor_rect.bottom() - content_size.height() - kEndPadding, - content_size.width(), content_size.height() + 2 * kEndPadding); - if (shelf_->alignment() == SHELF_ALIGNMENT_LEFT) - bounds.set_x(anchor_rect.right() + distance_to_overflow_button); - else - bounds.set_x(anchor_rect.x() - distance_to_overflow_button - - content_size.width()); - if (bounds.y() < monitor_rect.y()) - bounds.Offset(0, monitor_rect.y() - bounds.y()); - if (bounds.bottom() > monitor_rect.bottom()) - bounds.set_height(monitor_rect.bottom() - bounds.y()); + + AdjustToEnsureIconsFullyVisible(&bounds); return bounds; }
diff --git a/ash/shelf/overflow_bubble_view.h b/ash/shelf/overflow_bubble_view.h index 3525ac6b..4ac89f1a 100644 --- a/ash/shelf/overflow_bubble_view.h +++ b/ash/shelf/overflow_bubble_view.h
@@ -17,6 +17,21 @@ // Exports to access this class from OverflowBubbleViewTestAPI. class ASH_EXPORT OverflowBubbleView : public ShelfBubble { public: + enum LayoutStrategy { + // The arrow buttons are not shown. It means that there is enough space to + // accommodate all of shelf icons. + NOT_SHOW_ARROW_BUTTON, + + // Only the left arrow button is shown. + SHOW_LEFT_ARROW_BUTTON, + + // Only the right arrow button is shown. + SHOW_RIGHT_ARROW_BUTTON, + + // Both buttons are shown. + SHOW_BUTTONS + }; + // |anchor| is the overflow button on the main shelf. |shelf_view| is the // ShelfView containing the overflow items. OverflowBubbleView(ShelfView* shelf_view, @@ -36,7 +51,10 @@ gfx::Rect GetBubbleBounds() override; bool CanActivate() const override; - ShelfView* shelf_view() { return shelf_view_; } + ShelfView* shelf_view() { return shelf_container_view_->shelf_view(); } + View* left_arrow() { return left_arrow_; } + View* right_arrow() { return right_arrow_; } + LayoutStrategy layout_strategy() { return layout_strategy_; } // ShelfBubble: bool ShouldCloseOnPressDown() override; @@ -45,6 +63,56 @@ private: friend class OverflowBubbleViewTestAPI; + class ScrollArrowView : public views::View { + public: + enum ArrowType { LEFT, RIGHT }; + ScrollArrowView(ArrowType arrow_type, bool is_horizontal_alignment); + ~ScrollArrowView() override = default; + + // Overridden from views::View: + void OnPaint(gfx::Canvas* canvas) override; + const char* GetClassName() const override; + + private: + ArrowType arrow_type_; + bool is_horizontal_alignment_; + }; + + class OverflowShelfContainerView : public views::View { + public: + explicit OverflowShelfContainerView(ShelfView* shelf_view); + ~OverflowShelfContainerView() override = default; + + void Initialize(); + + // Translate |shelf_view_| by |offset|. + void TranslateShelfView(const gfx::Vector2d& offset); + + // views::View: + gfx::Size CalculatePreferredSize() const override; + void ChildPreferredSizeChanged(views::View* child) override; + void Layout() override; + const char* GetClassName() const override; + + ShelfView* shelf_view() { return shelf_view_; } + + private: + ShelfView* shelf_view_; + }; + + // Returns the maximum scroll distance. + int CalculateScrollUpperBound() const; + + // Updates the overflow bubble view's layout strategy after scrolling by the + // distance of |scroll|. Returns the adapted scroll offset. + int CalculateLayoutStrategyAfterScroll(int scroll); + + // Ensures that the width of |bubble_bounds| (if it is not horizontally + // aligned, adjust |bubble_bounds|'s height) is the multiple of the sum + // between kShelfButtonSize and kShelfButtonSpacing. It helps that all of + // shelf icons are fully visible. + void AdjustToEnsureIconsFullyVisible(gfx::Rect* bubble_bounds) const; + // views::View: gfx::Size CalculatePreferredSize() const override; void Layout() override; @@ -55,8 +123,14 @@ // ui::EventHandler: void OnScrollEvent(ui::ScrollEvent* event) override; + mutable LayoutStrategy layout_strategy_; + + // Child views Owned by views hierarchy. + ScrollArrowView* left_arrow_ = nullptr; + ScrollArrowView* right_arrow_ = nullptr; + OverflowShelfContainerView* shelf_container_view_ = nullptr; + Shelf* shelf_; - ShelfView* shelf_view_; // Owned by views hierarchy. gfx::Vector2d scroll_offset_; DISALLOW_COPY_AND_ASSIGN(OverflowBubbleView);
diff --git a/ash/shelf/overflow_bubble_view_test_api.cc b/ash/shelf/overflow_bubble_view_test_api.cc index 11697253..26bf902 100644 --- a/ash/shelf/overflow_bubble_view_test_api.cc +++ b/ash/shelf/overflow_bubble_view_test_api.cc
@@ -16,7 +16,7 @@ OverflowBubbleViewTestAPI::~OverflowBubbleViewTestAPI() = default; gfx::Size OverflowBubbleViewTestAPI::GetContentsSize() { - return bubble_view_->shelf_view_->GetPreferredSize(); + return bubble_view_->shelf_view()->GetPreferredSize(); } void OverflowBubbleViewTestAPI::ScrollByXOffset(int x_offset) {
diff --git a/ash/shelf/shelf_constants.h b/ash/shelf/shelf_constants.h index 64d1d278..ac3847cf 100644 --- a/ash/shelf/shelf_constants.h +++ b/ash/shelf/shelf_constants.h
@@ -116,6 +116,9 @@ // Size of the icons within shelf buttons. static int button_icon_size() { return kShelfButtonIconSize; } + // Size for controls like the home button, back button, etc. + static int control_size() { return kShelfControlSize; } + // The radius of shelf control buttons. static int control_border_radius() { return kShelfControlSize / 2; }
diff --git a/ash/shelf/shelf_control_button.cc b/ash/shelf/shelf_control_button.cc index 6ab27257..efa5e8f 100644 --- a/ash/shelf/shelf_control_button.cc +++ b/ash/shelf/shelf_control_button.cc
@@ -72,9 +72,10 @@ // maximize the click target, but we still want their "visual" size to be // the same, so we find the center point and draw a square around that. const gfx::Point center = GetCenterPoint(); - const int half_size = kShelfControlSize / 2; + const int half_size = ShelfConstants::control_size() / 2; const gfx::Rect visual_size(center.x() - half_size, center.y() - half_size, - kShelfControlSize, kShelfControlSize); + ShelfConstants::control_size(), + ShelfConstants::control_size()); auto path = std::make_unique<SkPath>(); path->addRoundRect(gfx::RectToSkRect(visual_size), border_radius, border_radius);
diff --git a/ash/shelf/shelf_controller.h b/ash/shelf/shelf_controller.h index edf638d..c94971e0f 100644 --- a/ash/shelf/shelf_controller.h +++ b/ash/shelf/shelf_controller.h
@@ -11,8 +11,8 @@ #include "ash/ash_export.h" #include "ash/display/window_tree_host_manager.h" #include "ash/public/cpp/shelf_model.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/session/session_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/scoped_observer.h" #include "ui/message_center/message_center_observer.h"
diff --git a/ash/shelf/shelf_layout_manager_unittest.cc b/ash/shelf/shelf_layout_manager_unittest.cc index f76ee42..6a2fbc4 100644 --- a/ash/shelf/shelf_layout_manager_unittest.cc +++ b/ash/shelf/shelf_layout_manager_unittest.cc
@@ -2674,7 +2674,7 @@ // Ensure that Shelf is higher than the default height, required by the bug // reproduction procedures. - delta_y = -kShelfSize - 1; + delta_y = -ShelfConstants::shelf_size() - 1; timestamp += base::TimeDelta::FromMilliseconds(200); ui::GestureEvent update_event = ui::GestureEvent( @@ -2757,7 +2757,7 @@ // Verify that the shelf has expected bounds. EXPECT_EQ(GetScreenAvailableBounds().bottom_left() + - gfx::Point(0, -kShelfSize).OffsetFromOrigin(), + gfx::Point(0, -ShelfConstants::shelf_size()).OffsetFromOrigin(), GetPrimaryShelf() ->GetShelfViewForTesting() ->GetBoundsInScreen()
diff --git a/ash/shelf/shelf_view.cc b/ash/shelf/shelf_view.cc index 8cca305..49c05df 100644 --- a/ash/shelf/shelf_view.cc +++ b/ash/shelf/shelf_view.cc
@@ -1176,7 +1176,8 @@ int x = 0; int y = 0; if (last_visible_index_ != -1) { - const int offset = (kShelfButtonSize - kShelfControlSize) / 2; + const int offset = + (ShelfConstants::button_size() - ShelfConstants::control_size()) / 2; x = shelf_->PrimaryAxisValue( offset + view_model_->ideal_bounds(last_visible_index_).right(), offset + view_model_->ideal_bounds(last_visible_index_).x()); @@ -1194,8 +1195,8 @@ y = shelf_->PrimaryAxisValue(y, y + extra_space_before_overflow); } - overflow_button_->SetBoundsRect( - gfx::Rect(x, y, kShelfControlSize, kShelfControlSize)); + overflow_button_->SetBoundsRect(gfx::Rect( + x, y, ShelfConstants::control_size(), ShelfConstants::control_size())); } void ShelfView::AnimateToIdealBounds() {
diff --git a/ash/shelf/shelf_view.h b/ash/shelf/shelf_view.h index e371ba5..b4169e0 100644 --- a/ash/shelf/shelf_view.h +++ b/ash/shelf/shelf_view.h
@@ -15,6 +15,7 @@ #include "ash/public/cpp/app_list/app_list_types.h" #include "ash/public/cpp/shelf_item_delegate.h" #include "ash/public/cpp/shelf_model_observer.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/shelf/overflow_bubble.h" #include "ash/shelf/overflow_bubble_view.h" #include "ash/shelf/shelf_button_delegate.h" @@ -22,7 +23,6 @@ #include "ash/shelf/shelf_tooltip_manager.h" #include "ash/shell_observer.h" #include "ash/system/model/virtual_keyboard_model.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/timer/timer.h"
diff --git a/ash/shelf/shelf_view_unittest.cc b/ash/shelf/shelf_view_unittest.cc index b6b9c83..6bf23e5 100644 --- a/ash/shelf/shelf_view_unittest.cc +++ b/ash/shelf/shelf_view_unittest.cc
@@ -1654,12 +1654,13 @@ ASSERT_TRUE(shelf_view_->IsShowingOverflowBubble()); - ShelfViewTestAPI test_for_overflow_view( - test_api_->overflow_bubble()->bubble_view()->shelf_view()); + ShelfViewTestAPI test_for_overflow_view(bubble_view->shelf_view()); const ShelfView* overflow_shelf_view = shelf_view_->overflow_shelf(); int first_index = overflow_shelf_view->first_visible_index(); int last_index = overflow_shelf_view->last_visible_index(); + views::View* left_arrow_button = bubble_view->left_arrow(); + views::View* right_arrow_button = bubble_view->right_arrow(); ShelfAppButton* first_button = test_for_overflow_view.GetButton(first_index); ShelfAppButton* last_button = test_for_overflow_view.GetButton(last_index); gfx::Point first_point = first_button->GetBoundsInScreen().CenterPoint(); @@ -1669,6 +1670,20 @@ EXPECT_TRUE(drag_reinsert_bounds.Contains(first_point)); EXPECT_FALSE(drag_reinsert_bounds.Contains(last_point)); + // Verfies that at the beginning, the left button is invisible while the right + // button shows. + EXPECT_EQ(OverflowBubbleView::SHOW_RIGHT_ARROW_BUTTON, + bubble_view->layout_strategy()); + EXPECT_FALSE(left_arrow_button->GetVisible()); + EXPECT_TRUE(right_arrow_button->GetVisible()); + + // Scroll the overflow shelf view a little bit. Then verifies that both arrow + // buttons show. + bubble_view_api.ScrollByXOffset(item_width); + EXPECT_EQ(OverflowBubbleView::SHOW_BUTTONS, bubble_view->layout_strategy()); + EXPECT_TRUE(left_arrow_button->GetVisible()); + EXPECT_TRUE(right_arrow_button->GetVisible()); + // Scroll sufficiently to completely show last item. bubble_view_api.ScrollByXOffset(bubble_view_api.GetContentsSize().width() - bubble_view->GetContentsBounds().width()); @@ -1678,6 +1693,13 @@ last_point = last_button->GetBoundsInScreen().CenterPoint(); EXPECT_FALSE(drag_reinsert_bounds.Contains(first_point)); EXPECT_TRUE(drag_reinsert_bounds.Contains(last_point)); + + // Verifies that when the last item shows, the right arrow button is invisible + // while the left one shows. + EXPECT_EQ(OverflowBubbleView::SHOW_LEFT_ARROW_BUTTON, + bubble_view->layout_strategy()); + EXPECT_TRUE(left_arrow_button->GetVisible()); + EXPECT_FALSE(right_arrow_button->GetVisible()); } // Check the drag insertion bounds of shelf view in multi monitor environment.
diff --git a/ash/shell.cc b/ash/shell.cc index dc24de3..23d357d7 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -663,6 +663,7 @@ // Destroy tablet mode controller early on since it has some observers which // need to be removed. + tablet_mode_controller_->Shutdown(); tablet_mode_controller_.reset(); toast_manager_.reset();
diff --git a/ash/shell/content/client/shell_browser_main_parts.cc b/ash/shell/content/client/shell_browser_main_parts.cc index 331007d..3c19ae2 100644 --- a/ash/shell/content/client/shell_browser_main_parts.cc +++ b/ash/shell/content/client/shell_browser_main_parts.cc
@@ -24,6 +24,7 @@ #include "base/command_line.h" #include "base/run_loop.h" #include "chromeos/dbus/biod/biod_client.h" +#include "chromeos/services/network_config/public/cpp/cros_network_config_test_helper.h" #include "components/exo/file_helper.h" #include "content/public/browser/context_factory.h" #include "content/public/browser/system_connector.h" @@ -60,6 +61,9 @@ browser_context_.reset(new content::ShellBrowserContext(false)); ash_test_helper_ = std::make_unique<AshTestHelper>(); + network_config_helper_ = + std::make_unique<chromeos::network_config::CrosNetworkConfigTestHelper>( + content::GetSystemConnector()); AshTestHelper::InitParams init_params; init_params.start_session = true;
diff --git a/ash/shell/content/client/shell_browser_main_parts.h b/ash/shell/content/client/shell_browser_main_parts.h index 067890a..9e0c67d 100644 --- a/ash/shell/content/client/shell_browser_main_parts.h +++ b/ash/shell/content/client/shell_browser_main_parts.h
@@ -11,10 +11,16 @@ #include "content/public/browser/browser_main_parts.h" #include "content/public/common/main_function_params.h" +namespace chromeos { +namespace network_config { +class CrosNetworkConfigTestHelper; +} // namespace network_config +} // namespace chromeos + namespace content { class BrowserContext; struct MainFunctionParams; -} +} // namespace content namespace views { class ViewsDelegate; @@ -51,6 +57,8 @@ example_session_controller_client_; std::unique_ptr<ExampleAppListClient> example_app_list_client_; std::unique_ptr<ash::AshTestHelper> ash_test_helper_; + std::unique_ptr<chromeos::network_config::CrosNetworkConfigTestHelper> + network_config_helper_; content::MainFunctionParams parameters_; DISALLOW_COPY_AND_ASSIGN(ShellBrowserMainParts);
diff --git a/ash/shell/content/client/shell_content_browser_client.cc b/ash/shell/content/client/shell_content_browser_client.cc index 1a4696b..92fc266 100644 --- a/ash/shell/content/client/shell_content_browser_client.cc +++ b/ash/shell/content/client/shell_content_browser_client.cc
@@ -17,6 +17,9 @@ #include "base/no_destructor.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" +#include "chromeos/services/network_config/public/cpp/manifest.h" +#include "chromeos/services/network_config/public/mojom/constants.mojom.h" // nogncheck +#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" // nogncheck #include "content/public/browser/browser_context.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/service_manager_connection.h" @@ -37,6 +40,9 @@ static base::NoDestructor<service_manager::Manifest> manifest{ service_manager::ManifestBuilder() .RequireCapability(device::mojom::kServiceName, "device:fingerprint") + .RequireCapability( + chromeos::network_config::mojom::kServiceName, + chromeos::network_config::mojom::kNetworkConfigCapability) .Build()}; return *manifest; } @@ -71,5 +77,12 @@ return base::nullopt; } +std::vector<service_manager::Manifest> +ShellContentBrowserClient::GetExtraServiceManifests() { + return std::vector<service_manager::Manifest>({ + chromeos::network_config::GetManifest(), + }); +} + } // namespace shell } // namespace ash
diff --git a/ash/shell/content/client/shell_content_browser_client.h b/ash/shell/content/client/shell_content_browser_client.h index 86ecef5..74bbfb8 100644 --- a/ash/shell/content/client/shell_content_browser_client.h +++ b/ash/shell/content/client/shell_content_browser_client.h
@@ -29,6 +29,7 @@ storage::OptionalQuotaSettingsCallback callback) override; base::Optional<service_manager::Manifest> GetServiceManifestOverlay( base::StringPiece name) override; + std::vector<service_manager::Manifest> GetExtraServiceManifests() override; private: DISALLOW_COPY_AND_ASSIGN(ShellContentBrowserClient);
diff --git a/ash/shell_test_api.cc b/ash/shell_test_api.cc index 7506e5c..e1e7924e 100644 --- a/ash/shell_test_api.cc +++ b/ash/shell_test_api.cc
@@ -14,6 +14,7 @@ #include "ash/app_list/views/app_list_view.h" #include "ash/keyboard/keyboard_controller_impl.h" #include "ash/public/cpp/app_list/app_list_types.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/root_window_controller.h" #include "ash/shell.h" #include "ash/system/power/backlights_forced_off_setter.h" @@ -186,8 +187,11 @@ return Shell::IsSystemModalWindowOpen(); } -void ShellTestApi::SetTabletModeEnabledForTest(bool enable) { +void ShellTestApi::SetTabletModeEnabledForTest(bool enable, + bool wait_for_completion) { + TabletMode::Waiter waiter(enable); shell_->tablet_mode_controller()->SetEnabledForTest(enable); + waiter.Wait(); } void ShellTestApi::EnableVirtualKeyboard() {
diff --git a/ash/system/accessibility/autoclick_scroll_bubble_controller.cc b/ash/system/accessibility/autoclick_scroll_bubble_controller.cc index 0c16237..468ae77 100644 --- a/ash/system/accessibility/autoclick_scroll_bubble_controller.cc +++ b/ash/system/accessibility/autoclick_scroll_bubble_controller.cc
@@ -52,8 +52,7 @@ menu_bubble_alignment_ = alignment; if (set_scroll_rect_) return; - bubble_view_->SetArrow(alignment); - bubble_view_->UpdateAnchorRect(rect); + bubble_view_->UpdateAnchorRect(rect, alignment); } void AutoclickScrollBubbleController::SetScrollPosition( @@ -78,8 +77,8 @@ // Buffer around the point so that the scroll bubble does not overlap it. // ScrollBubbleController will automatically layout to avoid edges. anchor.Inset(-kScrollPointBufferDips, -kScrollPointBufferDips); - bubble_view_->SetArrow(views::BubbleBorder::Arrow::LEFT_CENTER); - bubble_view_->UpdateAnchorRect(anchor); + bubble_view_->UpdateAnchorRect(anchor, + views::BubbleBorder::Arrow::LEFT_CENTER); return; } @@ -152,17 +151,18 @@ std::stable_sort(positions.begin(), positions.end(), comparePositions); // Position on the optimal side depending on the shortest distance. - bubble_view_->SetArrow(positions.front().arrow); if (positions.front().is_horizontal) { // Center it vertically on the scroll point. - bubble_view_->UpdateAnchorRect(gfx::Rect(scroll_bounds_in_dips.x(), - scroll_point_in_dips.y(), - scroll_bounds_in_dips.width(), 0)); + bubble_view_->UpdateAnchorRect( + gfx::Rect(scroll_bounds_in_dips.x(), scroll_point_in_dips.y(), + scroll_bounds_in_dips.width(), 0), + positions.at(0).arrow); } else { // Center horizontally on scroll point. - bubble_view_->UpdateAnchorRect(gfx::Rect(scroll_point_in_dips.x(), - scroll_bounds_in_dips.y(), 0, - scroll_bounds_in_dips.height())); + bubble_view_->UpdateAnchorRect( + gfx::Rect(scroll_point_in_dips.x(), scroll_bounds_in_dips.y(), 0, + scroll_bounds_in_dips.height()), + positions.at(0).arrow); } }
diff --git a/ash/system/accessibility/autoclick_scroll_view.cc b/ash/system/accessibility/autoclick_scroll_view.cc index 106a095..e573d371e 100644 --- a/ash/system/accessibility/autoclick_scroll_view.cc +++ b/ash/system/accessibility/autoclick_scroll_view.cc
@@ -327,11 +327,16 @@ AutoclickScrollBubbleView::~AutoclickScrollBubbleView() {} -void AutoclickScrollBubbleView::UpdateAnchorRect(const gfx::Rect& rect) { +void AutoclickScrollBubbleView::UpdateAnchorRect( + const gfx::Rect& rect, + views::BubbleBorder::Arrow arrow) { ui::ScopedLayerAnimationSettings settings( GetWidget()->GetLayer()->GetAnimator()); settings.SetPreemptionStrategy( ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); + // SetAnchorRect will resize, so set the arrow without reizing to avoid a + // double animation. + SetArrowWithoutResizing(arrow); SetAnchorRect(rect); }
diff --git a/ash/system/accessibility/autoclick_scroll_view.h b/ash/system/accessibility/autoclick_scroll_view.h index f4355f2..9450052 100644 --- a/ash/system/accessibility/autoclick_scroll_view.h +++ b/ash/system/accessibility/autoclick_scroll_view.h
@@ -21,7 +21,8 @@ explicit AutoclickScrollBubbleView(TrayBubbleView::InitParams init_params); ~AutoclickScrollBubbleView() override; - void UpdateAnchorRect(const gfx::Rect& rect); + void UpdateAnchorRect(const gfx::Rect& rect, + views::BubbleBorder::Arrow arrow); // TrayBubbleView: bool IsAnchoredToStatusArea() const override;
diff --git a/ash/system/locale/locale_update_controller_impl.cc b/ash/system/locale/locale_update_controller_impl.cc index 5e2e5f18..8ef1d87 100644 --- a/ash/system/locale/locale_update_controller_impl.cc +++ b/ash/system/locale/locale_update_controller_impl.cc
@@ -8,13 +8,13 @@ #include <utility> #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/tray/system_tray_notifier.h" #include "base/strings/string16.h" #include "components/session_manager/session_manager_types.h" +#include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" #include "ui/message_center/message_center.h" #include "ui/message_center/public/cpp/notification.h" @@ -75,6 +75,9 @@ std::move(callback_).Run(button_index ? LocaleNotificationResult::kRevert : LocaleNotificationResult::kAccept); + + message_center::MessageCenter::Get()->RemoveNotification( + kLocaleChangeNotificationId, true /* by_user */); } } // namespace @@ -117,7 +120,7 @@ message_center::NotifierId(message_center::NotifierType::SYSTEM_COMPONENT, kNotifierLocale), optional, new LocaleNotificationDelegate(std::move(callback)), - kNotificationSettingsIcon, + vector_icons::kSettingsIcon, message_center::SystemNotificationWarningLevel::NORMAL); message_center::MessageCenter::Get()->AddNotification( std::move(notification));
diff --git a/ash/system/overview/overview_button_tray.h b/ash/system/overview/overview_button_tray.h index 7669961..dde6b9ea 100644 --- a/ash/system/overview/overview_button_tray.h +++ b/ash/system/overview/overview_button_tray.h
@@ -6,10 +6,10 @@ #define ASH_SYSTEM_OVERVIEW_OVERVIEW_BUTTON_TRAY_H_ #include "ash/ash_export.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/session/session_observer.h" #include "ash/system/tray/tray_background_view.h" #include "ash/wm/overview/overview_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" #include "ui/events/event_constants.h"
diff --git a/ash/system/overview/overview_button_tray_unittest.cc b/ash/system/overview/overview_button_tray_unittest.cc index 09e75a6..c57292167 100644 --- a/ash/system/overview/overview_button_tray_unittest.cc +++ b/ash/system/overview/overview_button_tray_unittest.cc
@@ -7,6 +7,7 @@ #include "ash/display/window_tree_host_manager.h" #include "ash/login_status.h" #include "ash/public/cpp/shelf_types.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/root_window_controller.h" #include "ash/rotator/screen_rotation_animator.h" #include "ash/session/session_controller_impl.h" @@ -20,7 +21,6 @@ #include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller_test_api.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "ash/wm/window_state.h" #include "ash/wm/window_util.h" #include "base/command_line.h"
diff --git a/ash/system/power/power_button_controller.h b/ash/system/power/power_button_controller.h index 67d90b9e..07a79b8 100644 --- a/ash/system/power/power_button_controller.h +++ b/ash/system/power/power_button_controller.h
@@ -9,9 +9,9 @@ #include "ash/accelerometer/accelerometer_reader.h" #include "ash/ash_export.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/system/power/backlights_forced_off_setter.h" #include "ash/wm/lock_state_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/timer/timer.h"
diff --git a/ash/system/rotation/rotation_lock_feature_pod_controller.h b/ash/system/rotation/rotation_lock_feature_pod_controller.h index 24bb10e..f744939 100644 --- a/ash/system/rotation/rotation_lock_feature_pod_controller.h +++ b/ash/system/rotation/rotation_lock_feature_pod_controller.h
@@ -7,8 +7,8 @@ #include "ash/ash_export.h" #include "ash/display/screen_orientation_controller.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/system/unified/feature_pod_controller_base.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" namespace ash {
diff --git a/ash/system/unified/ime_mode_view.h b/ash/system/unified/ime_mode_view.h index abe5bf9..6ee00f2e3f 100644 --- a/ash/system/unified/ime_mode_view.h +++ b/ash/system/unified/ime_mode_view.h
@@ -5,11 +5,11 @@ #ifndef ASH_SYSTEM_UNIFIED_IME_MODE_VIEW_H_ #define ASH_SYSTEM_UNIFIED_IME_MODE_VIEW_H_ +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/session/session_observer.h" #include "ash/system/ime/ime_observer.h" #include "ash/system/model/locale_model.h" #include "ash/system/tray/tray_item_view.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" namespace ash {
diff --git a/ash/system/unified/top_shortcuts_view.cc b/ash/system/unified/top_shortcuts_view.cc index 86ff1ee..7ef376b 100644 --- a/ash/system/unified/top_shortcuts_view.cc +++ b/ash/system/unified/top_shortcuts_view.cc
@@ -7,7 +7,6 @@ #include <numeric> #include "ash/accessibility/accessibility_controller_impl.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" #include "ash/public/cpp/ash_view_ids.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller_impl.h" @@ -171,7 +170,6 @@ bool is_on_login_screen = shell->session_controller()->login_status() == LoginStatus::NOT_LOGGED_IN; - bool is_kiosk_next = shell->kiosk_next_shell_controller()->IsEnabled(); bool can_show_settings = TrayPopupUtils::CanOpenWebUISettings(); bool can_lock_screen = shell->session_controller()->CanLockScreen(); @@ -185,16 +183,14 @@ container_->AddSignOutButton(sign_out_button_); } - if (!is_kiosk_next) { - bool reboot = shell->shutdown_controller()->reboot_on_shutdown(); - power_button_ = new TopShortcutButton( - this, kUnifiedMenuPowerIcon, - reboot ? IDS_ASH_STATUS_TRAY_REBOOT : IDS_ASH_STATUS_TRAY_SHUTDOWN); - power_button_->SetID(VIEW_ID_POWER_BUTTON); - container_->AddChildView(power_button_); - } + bool reboot = shell->shutdown_controller()->reboot_on_shutdown(); + power_button_ = new TopShortcutButton( + this, kUnifiedMenuPowerIcon, + reboot ? IDS_ASH_STATUS_TRAY_REBOOT : IDS_ASH_STATUS_TRAY_SHUTDOWN); + power_button_->SetID(VIEW_ID_POWER_BUTTON); + container_->AddChildView(power_button_); - if (can_show_settings && can_lock_screen && !is_kiosk_next) { + if (can_show_settings && can_lock_screen) { lock_button_ = new TopShortcutButton(this, kUnifiedMenuLockIcon, IDS_ASH_STATUS_TRAY_LOCK); container_->AddChildView(lock_button_);
diff --git a/ash/system/unified/top_shortcuts_view_unittest.cc b/ash/system/unified/top_shortcuts_view_unittest.cc index 8f72a2af..b8b4065 100644 --- a/ash/system/unified/top_shortcuts_view_unittest.cc +++ b/ash/system/unified/top_shortcuts_view_unittest.cc
@@ -4,9 +4,6 @@ #include "ash/system/unified/top_shortcuts_view.h" -#include "ash/kiosk_next/kiosk_next_shell_test_util.h" -#include "ash/kiosk_next/mock_kiosk_next_shell_client.h" -#include "ash/public/cpp/ash_features.h" #include "ash/session/test_session_controller_client.h" #include "ash/system/unified/collapse_button.h" #include "ash/system/unified/sign_out_button.h" @@ -15,7 +12,6 @@ #include "ash/system/unified/unified_system_tray_model.h" #include "ash/test/ash_test_base.h" #include "base/macros.h" -#include "base/test/scoped_feature_list.h" namespace ash { @@ -26,8 +22,6 @@ ~TopShortcutsViewTest() override = default; void SetUp() override { - scoped_feature_list_.InitAndEnableFeature(features::kKioskNextShell); - NoSessionAshTestBase::SetUp(); model_ = std::make_unique<UnifiedSystemTrayModel>(); @@ -35,7 +29,6 @@ } void TearDown() override { - kiosk_next_shell_client_.reset(); controller_.reset(); top_shortcuts_view_.reset(); model_.reset(); @@ -47,11 +40,6 @@ top_shortcuts_view_ = std::make_unique<TopShortcutsView>(controller_.get()); } - void CreateKioskNextSession() { - kiosk_next_shell_client_ = std::make_unique<MockKioskNextShellClient>(); - LogInKioskNextUser(GetSessionControllerClient()); - } - views::View* GetUserAvatar() { return top_shortcuts_view_->user_avatar_button_; } @@ -75,9 +63,6 @@ void Layout() { top_shortcuts_view_->Layout(); } private: - base::test::ScopedFeatureList scoped_feature_list_; - std::unique_ptr<MockKioskNextShellClient> kiosk_next_shell_client_; - std::unique_ptr<UnifiedSystemTrayModel> model_; std::unique_ptr<UnifiedSystemTrayController> controller_; std::unique_ptr<TopShortcutsView> top_shortcuts_view_; @@ -187,29 +172,4 @@ Layout(); } -// Some buttons are hidden in Kiosk Next sessions. -TEST_F(TopShortcutsViewTest, ButtonStatesKioskNextLoggedIn) { - CreateKioskNextSession(); - SetUpView(); - EXPECT_TRUE(GetUserAvatar()->GetVisible()); - EXPECT_TRUE(GetSignOutButton()->GetVisible()); - EXPECT_EQ(nullptr, GetLockButton()); - EXPECT_TRUE(GetSettingsButton()->GetVisible()); - EXPECT_EQ(nullptr, GetPowerButton()); - EXPECT_TRUE(GetCollapseButton()->GetVisible()); -} - -// Settings button is also hidden at the lock screen in Kiosk Next sessions. -TEST_F(TopShortcutsViewTest, ButtonStatesKioskNextLockScreen) { - CreateKioskNextSession(); - GetSessionControllerClient()->LockScreen(); - SetUpView(); - EXPECT_TRUE(GetUserAvatar()->GetVisible()); - EXPECT_TRUE(GetSignOutButton()->GetVisible()); - EXPECT_EQ(nullptr, GetLockButton()); - EXPECT_EQ(nullptr, GetSettingsButton()); - EXPECT_EQ(nullptr, GetPowerButton()); - EXPECT_TRUE(GetCollapseButton()->GetVisible()); -} - } // namespace ash
diff --git a/ash/system/unified/unified_system_tray_bubble.h b/ash/system/unified/unified_system_tray_bubble.h index fdcc966..a3fae0f 100644 --- a/ash/system/unified/unified_system_tray_bubble.h +++ b/ash/system/unified/unified_system_tray_bubble.h
@@ -7,11 +7,11 @@ #include <memory> +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/shelf/shelf_observer.h" #include "ash/system/screen_layout_observer.h" #include "ash/system/tray/time_to_click_recorder.h" #include "ash/system/tray/tray_bubble_base.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" #include "base/optional.h" #include "base/time/time.h"
diff --git a/ash/system/unified/unified_system_tray_controller.cc b/ash/system/unified/unified_system_tray_controller.cc index 0a25cf3..6d4d917 100644 --- a/ash/system/unified/unified_system_tray_controller.cc +++ b/ash/system/unified/unified_system_tray_controller.cc
@@ -4,7 +4,6 @@ #include "ash/system/unified/unified_system_tray_controller.h" -#include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" #include "ash/metrics/user_metrics_action.h" #include "ash/metrics/user_metrics_recorder.h" #include "ash/public/cpp/pagination/pagination_controller.h" @@ -332,10 +331,6 @@ } void UnifiedSystemTrayController::InitFeaturePods() { - // No feature pods in Kisok Next. - if (Shell::Get()->kiosk_next_shell_controller()->IsEnabled()) - return; - AddFeaturePodItem(std::make_unique<NetworkFeaturePodController>(this)); AddFeaturePodItem(std::make_unique<BluetoothFeaturePodController>(this)); AddFeaturePodItem(std::make_unique<QuietModeFeaturePodController>(this));
diff --git a/ash/system/unified/unified_system_tray_model.cc b/ash/system/unified/unified_system_tray_model.cc index 2f3122e9..4331d42 100644 --- a/ash/system/unified/unified_system_tray_model.cc +++ b/ash/system/unified/unified_system_tray_model.cc
@@ -74,7 +74,7 @@ UnifiedSystemTrayModel::UnifiedSystemTrayModel() : dbus_observer_(std::make_unique<DBusObserver>(this)), - pagination_model_(std::make_unique<PaginationModel>()) {} + pagination_model_(std::make_unique<PaginationModel>(nullptr)) {} UnifiedSystemTrayModel::~UnifiedSystemTrayModel() = default;
diff --git a/ash/wallpaper/wallpaper_controller_impl.h b/ash/wallpaper/wallpaper_controller_impl.h index 1c361b9..b5e0cdcf 100644 --- a/ash/wallpaper/wallpaper_controller_impl.h +++ b/ash/wallpaper/wallpaper_controller_impl.h
@@ -13,6 +13,7 @@ #include "ash/ash_export.h" #include "ash/display/window_tree_host_manager.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/public/cpp/wallpaper_controller.h" #include "ash/public/cpp/wallpaper_info.h" #include "ash/public/cpp/wallpaper_types.h" @@ -20,7 +21,6 @@ #include "ash/shell_observer.h" #include "ash/wallpaper/wallpaper_utils/wallpaper_color_calculator_observer.h" #include "ash/wallpaper/wallpaper_utils/wallpaper_resizer_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "base/observer_list.h"
diff --git a/ash/wm/client_controlled_state_unittest.cc b/ash/wm/client_controlled_state_unittest.cc index b006a72..75f27af 100644 --- a/ash/wm/client_controlled_state_unittest.cc +++ b/ash/wm/client_controlled_state_unittest.cc
@@ -385,7 +385,7 @@ window_state()->OnWMEvent(&snap_left_event); EXPECT_EQ(second_display_id, delegate()->display_id()); - EXPECT_EQ(gfx::Rect(0, 0, 300, 500 - kShelfSize), + EXPECT_EQ(gfx::Rect(0, 0, 300, 500 - ShelfConstants::shelf_size()), delegate()->requested_bounds()); state()->EnterNextState(window_state(), delegate()->new_state()); @@ -396,7 +396,7 @@ window()->SetBoundsInScreen(delegate()->requested_bounds(), first_display); state()->set_bounds_locally(false); EXPECT_EQ(first_display.id(), delegate()->display_id()); - EXPECT_EQ(gfx::Rect(0, 0, 400, 600 - kShelfSize), + EXPECT_EQ(gfx::Rect(0, 0, 400, 600 - ShelfConstants::shelf_size()), delegate()->requested_bounds()); }
diff --git a/ash/wm/desks/desk_mini_view.cc b/ash/wm/desks/desk_mini_view.cc index e71a7cf..a6472c4 100644 --- a/ash/wm/desks/desk_mini_view.cc +++ b/ash/wm/desks/desk_mini_view.cc
@@ -13,6 +13,7 @@ #include "ash/wm/desks/desks_controller.h" #include "ui/aura/window.h" #include "ui/views/widget/widget.h" +#include "ui/wm/core/coordinate_conversion.h" namespace ash { @@ -85,6 +86,7 @@ SetInkDropMode(InkDropMode::OFF); UpdateBorderColor(); + SetAccessibleName(title); } DeskMiniView::~DeskMiniView() { @@ -96,6 +98,7 @@ void DeskMiniView::SetTitle(const base::string16& title) { label_->SetText(title); + SetAccessibleName(title); } aura::Window* DeskMiniView::GetDeskContainer() const { @@ -215,6 +218,18 @@ // No need to remove `this` as an observer; it's done automatically. } +views::View* DeskMiniView::GetView() { + return this; +} + +gfx::Rect DeskMiniView::GetHighlightBounds() { + // Use the target bounds instead of |GetBoundsInScreen()| because |this| may + // be animating. + gfx::Rect target_bounds = layer()->GetTargetBounds(); + ::wm::ConvertRectFromScreen(root_window_, &target_bounds); + return target_bounds; +} + bool DeskMiniView::IsPointOnMiniView(const gfx::Point& screen_location) const { gfx::Point point_in_view = screen_location; ConvertPointFromScreen(this, &point_in_view);
diff --git a/ash/wm/desks/desk_mini_view.h b/ash/wm/desks/desk_mini_view.h index 832b0eb0..4352d3f0 100644 --- a/ash/wm/desks/desk_mini_view.h +++ b/ash/wm/desks/desk_mini_view.h
@@ -9,6 +9,7 @@ #include "ash/ash_export.h" #include "ash/wm/desks/desk.h" +#include "ash/wm/overview/overview_highlight_controller.h" #include "base/macros.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/label.h" @@ -23,9 +24,11 @@ // virtual desk in the desk bar view when overview mode is active. This view // shows a preview of the contents of the associated desk, its title, and // supports desk activation and removal. -class ASH_EXPORT DeskMiniView : public views::Button, - public views::ButtonListener, - public Desk::Observer { +class ASH_EXPORT DeskMiniView + : public views::Button, + public views::ButtonListener, + public Desk::Observer, + public OverviewHighlightController::OverviewHighlightableView { public: DeskMiniView(DesksBarView* owner_bar, aura::Window* root_window, @@ -73,6 +76,10 @@ void OnContentChanged() override; void OnDeskDestroyed(const Desk* desk) override; + // OverviewHighlightController::OverviewHighlightableView: + views::View* GetView() override; + gfx::Rect GetHighlightBounds() override; + bool IsPointOnMiniView(const gfx::Point& screen_location) const; private:
diff --git a/ash/wm/desks/desk_mini_view_animations.cc b/ash/wm/desks/desk_mini_view_animations.cc index 462af939..ac4f558 100644 --- a/ash/wm/desks/desk_mini_view_animations.cc +++ b/ash/wm/desks/desk_mini_view_animations.cc
@@ -90,7 +90,7 @@ int shift_x, bool first_time_mini_views) { if (first_time_mini_views) { - ui::Layer* layer = bar_view->backgroud_view()->layer(); + ui::Layer* layer = bar_view->background_view()->layer(); ui::ScopedLayerAnimationSettings settings{layer->GetAnimator()}; InitScopedAnimationSettings(&settings, kBarBackgroundDuration); layer->SetOpacity(1);
diff --git a/ash/wm/desks/desks_bar_view.cc b/ash/wm/desks/desks_bar_view.cc index 5ab8c1b..4dfa6b3 100644 --- a/ash/wm/desks/desks_bar_view.cc +++ b/ash/wm/desks/desks_bar_view.cc
@@ -15,6 +15,8 @@ #include "ash/wm/desks/desk_mini_view_animations.h" #include "ash/wm/desks/new_desk_button.h" #include "ash/wm/overview/overview_controller.h" +#include "ash/wm/overview/overview_highlight_controller.h" +#include "ash/wm/overview/overview_session.h" #include "base/stl_util.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/aura/window.h" @@ -108,16 +110,16 @@ // DesksBarView: DesksBarView::DesksBarView() - : backgroud_view_(new views::View), + : background_view_(new views::View), new_desk_button_(new NewDeskButton(this)) { SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); - backgroud_view_->SetPaintToLayer(ui::LAYER_SOLID_COLOR); - backgroud_view_->layer()->SetFillsBoundsOpaquely(false); - backgroud_view_->layer()->SetColor(SkColorSetARGB(60, 0, 0, 0)); + background_view_->SetPaintToLayer(ui::LAYER_SOLID_COLOR); + background_view_->layer()->SetFillsBoundsOpaquely(false); + background_view_->layer()->SetColor(SkColorSetARGB(60, 0, 0, 0)); - AddChildView(backgroud_view_); + AddChildView(background_view_); AddChildView(new_desk_button_); UpdateNewDeskButtonState(); DesksController::Get()->AddObserver(this); @@ -193,7 +195,7 @@ } void DesksBarView::Layout() { - backgroud_view_->SetBoundsRect(bounds()); + background_view_->SetBoundsRect(bounds()); constexpr int kButtonRightMargin = 36; constexpr int kIconAndTextHorizontalPadding = 16; @@ -268,6 +270,12 @@ Layout(); UpdateMiniViewsLabels(); UpdateNewDeskButtonState(); + DCHECK(Shell::Get()->overview_controller()->InOverviewSession()); + auto* highlight_controller = Shell::Get() + ->overview_controller() + ->overview_session() + ->highlight_controller(); + highlight_controller->OnViewDestroying(removed_mini_view.get()); std::vector<DeskMiniView*> mini_views_before; std::vector<DeskMiniView*> mini_views_after; @@ -281,9 +289,15 @@ std::transform(partition_iter, mini_views_.end(), std::back_inserter(mini_views_after), transform_lambda); + aura::Window* root_window = removed_mini_view->root_window(); PerformRemoveDeskMiniViewAnimation(std::move(removed_mini_view), mini_views_before, mini_views_after, begin_x - GetFirstMiniViewXOffset()); + + // Once the remaining mini views have their bounds updated, notify the + // overview highlight controller so that it can update the focus highlight, if + // needed. + highlight_controller->OnWindowsRepositioned(root_window); } void DesksBarView::OnDeskActivationChanged(const Desk* activated, @@ -310,8 +324,8 @@ // The bar background is initially translated off the screen. gfx::Transform translate; translate.Translate(0, -kBarHeight); - backgroud_view_->layer()->SetTransform(translate); - backgroud_view_->layer()->SetOpacity(0); + background_view_->layer()->SetTransform(translate); + background_view_->layer()->SetOpacity(0); return; }
diff --git a/ash/wm/desks/desks_bar_view.h b/ash/wm/desks/desks_bar_view.h index 2ee6bbc9..0017cc4 100644 --- a/ash/wm/desks/desks_bar_view.h +++ b/ash/wm/desks/desks_bar_view.h
@@ -38,7 +38,7 @@ aura::Window* root, const gfx::Rect& bounds); - views::View* backgroud_view() const { return backgroud_view_; } + views::View* background_view() const { return background_view_; } NewDeskButton* new_desk_button() const { return new_desk_button_; } @@ -109,7 +109,7 @@ // A view that shows a dark gary transparent background that can be animated // when the very first mini_views are created. - views::View* backgroud_view_; + views::View* background_view_; NewDeskButton* new_desk_button_;
diff --git a/ash/wm/desks/desks_unittests.cc b/ash/wm/desks/desks_unittests.cc index ac34dc77..6cf56b3 100644 --- a/ash/wm/desks/desks_unittests.cc +++ b/ash/wm/desks/desks_unittests.cc
@@ -285,7 +285,7 @@ // once animations are added. EXPECT_FALSE(overview_grid->IsDesksBarViewActive()); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); // Since we have a single default desk, there should be no mini_views, and the // new desk button is enabled. @@ -343,7 +343,7 @@ overview_controller->overview_session()->GetGridWithRootWindow( Shell::GetPrimaryRootWindow()); EXPECT_TRUE(overview_grid->IsDesksBarViewActive()); - desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + desks_bar_view = overview_grid->desks_bar_view(); DCHECK(desks_bar_view); EXPECT_EQ(controller->desks().size(), desks_bar_view->mini_views().size()); @@ -699,7 +699,7 @@ EXPECT_TRUE(overview_controller->InOverviewSession()); const auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow()); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); ASSERT_EQ(4u, desks_bar_view->mini_views().size()); EXPECT_EQ(2u, overview_grid->window_list().size()); @@ -769,7 +769,7 @@ ASSERT_EQ(2u, roots.size()); // Use secondary display grid. const auto* overview_grid = GetOverviewGridForRoot(roots[1]); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); ASSERT_EQ(4u, desks_bar_view->mini_views().size()); @@ -819,7 +819,7 @@ // Remove desk_1 using the close button on its mini view. desk_1 is currently // inactive. Its windows should be moved to desk_4 and added to the overview // grid in the MRU order (win0, and win1). - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); ASSERT_EQ(4u, desks_bar_view->mini_views().size()); Desk* desk_1 = controller->desks()[0].get(); @@ -896,7 +896,7 @@ const auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow()); EXPECT_EQ(1u, overview_grid->window_list().size()); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); ASSERT_EQ(2u, desks_bar_view->mini_views().size()); auto* mini_view = desks_bar_view->mini_views().back().get(); @@ -961,7 +961,7 @@ EXPECT_TRUE(overview_controller->InOverviewSession()); const auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow()); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); const Desk* desk_1 = controller->desks()[0].get(); const auto* mini_view = desks_bar_view->mini_views().front().get(); ClickOnMiniView(mini_view, GetEventGenerator()); @@ -1037,7 +1037,7 @@ ASSERT_TRUE(overview_item); const gfx::RectF target_bounds_before_drag = overview_item->target_bounds(); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); ASSERT_EQ(2u, desks_bar_view->mini_views().size()); auto* desk_1_mini_view = desks_bar_view->mini_views()[0].get(); @@ -1096,7 +1096,7 @@ auto* overview_item = overview_session->GetOverviewItemForWindow(window.get()); ASSERT_TRUE(overview_item); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); ASSERT_EQ(2u, desks_bar_view->mini_views().size()); @@ -1147,7 +1147,7 @@ ASSERT_TRUE(overview_item); const gfx::RectF target_bounds_before_drag = overview_item->target_bounds(); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); // Drag it and drop it on the new desk button. Nothing happens, it should be @@ -1289,7 +1289,7 @@ auto* overview_item = overview_session->GetOverviewItemForWindow(window.get()); ASSERT_TRUE(overview_item); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); // Now drag it to desk_2's mini_view, so that it moves to desk_2. Expect that @@ -1346,7 +1346,7 @@ EXPECT_TRUE(overview_controller->InOverviewSession()); const auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow()); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_FALSE(desks_bar_view); // It's possible to drag the window without any crashes. @@ -1364,7 +1364,7 @@ overview_controller->StartOverview(); EXPECT_TRUE(overview_controller->InOverviewSession()); overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow()); - desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); ASSERT_EQ(2u, desks_bar_view->mini_views().size()); } @@ -1426,7 +1426,7 @@ EXPECT_TRUE(overview_controller->InOverviewSession()); const auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow()); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); ASSERT_EQ(3u, desks_bar_view->mini_views().size()); auto* desk_1_mini_view = desks_bar_view->mini_views()[0].get(); @@ -1505,7 +1505,7 @@ auto* overview_item = overview_session->GetOverviewItemForWindow(window.get()); ASSERT_TRUE(overview_item); - const auto* desks_bar_view = overview_grid->GetDesksBarViewForTesting(); + const auto* desks_bar_view = overview_grid->desks_bar_view(); ASSERT_TRUE(desks_bar_view); ASSERT_EQ(2u, desks_bar_view->mini_views().size()); @@ -1650,6 +1650,8 @@ EXPECT_FALSE(win3->IsVisible()); } +} // namespace + // Simulates the same behavior of event rewriting that key presses go through. class DesksAcceleratorsTest : public DesksTest, public ui::EventRewriterChromeOS::Delegate { @@ -1686,10 +1688,17 @@ generator->ReleaseKey(key_code, flags); } + // Moves the overview highlight to the next item. + void MoveOverviewHighlighter(OverviewSession* session) { + session->Move(/*reverse=*/false); + } + private: DISALLOW_COPY_AND_ASSIGN(DesksAcceleratorsTest); }; +namespace { + TEST_F(DesksAcceleratorsTest, NewDesk) { auto* controller = DesksController::Get(); // It's possible to add up to `kMaxNumberOfDesks` desks using the shortcut. @@ -1847,24 +1856,29 @@ ASSERT_EQ(num_windows_before, desk_1->windows().size()); EXPECT_TRUE(desk_2->windows().empty()); - // It's possible to move the highlighted window. - auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow()); - overview_grid->Move(/*reverse=*/false, /*animate=*/false); - EXPECT_EQ(win0.get(), overview_grid->SelectedWindow()->GetWindow()); + auto* overview_session = overview_controller->overview_session(); + ASSERT_TRUE(overview_session); + // It's possible to move the highlighted window. |Move()| will cycle through + // the desk items first, so call it until we are highlighting an OverviewItem. + while (!overview_session->GetHighlightedWindow()) + MoveOverviewHighlighter(overview_session); + EXPECT_EQ(win0.get(), overview_session->GetHighlightedWindow()); SendAccelerator(ui::VKEY_OEM_6, flags); EXPECT_FALSE(DoesActiveDeskContainWindow(win0.get())); EXPECT_TRUE(base::Contains(desk_2->windows(), win0.get())); EXPECT_TRUE(overview_controller->InOverviewSession()); - // The highlight widget should move to the next window. - EXPECT_EQ(win1.get(), overview_grid->SelectedWindow()->GetWindow()); + // The highlight widget should move to the next window if we call + // |MoveOverviewHighlighter()| again. + MoveOverviewHighlighter(overview_session); + EXPECT_EQ(win1.get(), overview_session->GetHighlightedWindow()); SendAccelerator(ui::VKEY_OEM_6, flags); EXPECT_FALSE(DoesActiveDeskContainWindow(win1.get())); EXPECT_TRUE(base::Contains(desk_2->windows(), win1.get())); EXPECT_TRUE(overview_controller->InOverviewSession()); // No more highlighted windows. - EXPECT_FALSE(overview_grid->SelectedWindow()); + EXPECT_FALSE(overview_session->GetHighlightedWindow()); } // TODO(afakhry): Add more tests:
diff --git a/ash/wm/desks/new_desk_button.cc b/ash/wm/desks/new_desk_button.cc index 5876a92..72c006a 100644 --- a/ash/wm/desks/new_desk_button.cc +++ b/ash/wm/desks/new_desk_button.cc
@@ -92,4 +92,12 @@ return border; } +views::View* NewDeskButton::GetView() { + return this; +} + +gfx::Rect NewDeskButton::GetHighlightBounds() { + return GetBoundsInScreen(); +} + } // namespace ash
diff --git a/ash/wm/desks/new_desk_button.h b/ash/wm/desks/new_desk_button.h index 4696e09..964c2fc 100644 --- a/ash/wm/desks/new_desk_button.h +++ b/ash/wm/desks/new_desk_button.h
@@ -8,6 +8,7 @@ #include <memory> #include "ash/ash_export.h" +#include "ash/wm/overview/overview_highlight_controller.h" #include "base/macros.h" #include "ui/views/controls/button/label_button.h" @@ -15,7 +16,9 @@ // A button view that shows up in the top-right corner of the screen when // overview mode is on, which is used to create a new virtual desk. -class ASH_EXPORT NewDeskButton : public views::LabelButton { +class ASH_EXPORT NewDeskButton + : public views::LabelButton, + public OverviewHighlightController::OverviewHighlightableView { public: NewDeskButton(views::ButtonListener* listener); ~NewDeskButton() override = default; @@ -30,6 +33,10 @@ std::unique_ptr<views::LabelButtonBorder> CreateDefaultBorder() const override; + // OverviewHighlightController::OverviewHighlightableView: + views::View* GetView() override; + gfx::Rect GetHighlightBounds() override; + private: DISALLOW_COPY_AND_ASSIGN(NewDeskButton); };
diff --git a/ash/wm/overview/caption_container_view.cc b/ash/wm/overview/caption_container_view.cc index 27931db7..e89d503a 100644 --- a/ash/wm/overview/caption_container_view.cc +++ b/ash/wm/overview/caption_container_view.cc
@@ -18,6 +18,8 @@ #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" +#include "ui/views/widget/widget.h" +#include "ui/wm/core/coordinate_conversion.h" namespace ash { namespace { @@ -250,6 +252,20 @@ Layout(); } +views::View* CaptionContainerView::GetView() { + return this; +} + +gfx::Rect CaptionContainerView::GetHighlightBounds() { + // Use the target bounds instead of |GetBoundsInScreen()| because |this| may + // be animating. + auto* window = GetWidget()->GetNativeWindow(); + gfx::Rect target_bounds = window->GetTargetBounds(); + target_bounds.set_origin(GetBoundsInScreen().origin()); + ::wm::ConvertRectFromScreen(window->GetRootWindow(), &target_bounds); + return target_bounds; +} + void CaptionContainerView::Layout() { gfx::Rect bounds(GetLocalBounds()); bounds.Inset(kMarginDp, kMarginDp);
diff --git a/ash/wm/overview/caption_container_view.h b/ash/wm/overview/caption_container_view.h index 455d501..6e8c446d 100644 --- a/ash/wm/overview/caption_container_view.h +++ b/ash/wm/overview/caption_container_view.h
@@ -6,6 +6,7 @@ #define ASH_WM_OVERVIEW_CAPTION_CONTAINER_VIEW_H_ #include "ash/ash_export.h" +#include "ash/wm/overview/overview_highlight_controller.h" #include "base/macros.h" #include "ui/views/controls/button/button.h" @@ -31,7 +32,9 @@ // also draws a header for overview mode which contains a icon, title and close // button. // TODO(sammiequon): Rename this to something which describes it better. -class ASH_EXPORT CaptionContainerView : public views::Button { +class ASH_EXPORT CaptionContainerView + : public views::Button, + public OverviewHighlightController::OverviewHighlightableView { public: // The visibility of the header. It may be fully visible or invisible, or // everything but the close button is visible. @@ -98,6 +101,10 @@ // dragging. void UpdatePreviewView(); + // OverviewHighlightController::OverviewHighlightableView: + views::View* GetView() override; + gfx::Rect GetHighlightBounds() override; + // TODO(sammiequon): Move these to a test api. views::View* header_view() { return header_view_; } views::Label* title_label() { return title_label_; }
diff --git a/ash/wm/overview/overview_animation_type.h b/ash/wm/overview/overview_animation_type.h index fe66f52f..0a19055 100644 --- a/ash/wm/overview/overview_animation_type.h +++ b/ash/wm/overview/overview_animation_type.h
@@ -42,9 +42,8 @@ // Used to fade in the label which tells users they are in overview mode with // no window in and out. OVERVIEW_ANIMATION_NO_RECENTS_FADE, - // Used to animate the selection window which is activated by using tab or the - // arrow keys. - OVERVIEW_ANIMATION_SELECTION_WINDOW_SHADOW, + // Used to animate the overview highlight which is activated by using tab or + // the arrow keys. OVERVIEW_ANIMATION_SELECTION_WINDOW, };
diff --git a/ash/wm/overview/overview_controller.cc b/ash/wm/overview/overview_controller.cc index 837b240..b33aade 100644 --- a/ash/wm/overview/overview_controller.cc +++ b/ash/wm/overview/overview_controller.cc
@@ -516,7 +516,7 @@ OverviewController::GetWindowsListInOverviewGridsForTest() { std::vector<aura::Window*> windows; for (const std::unique_ptr<OverviewGrid>& grid : - overview_session_->grid_list_for_testing()) { + overview_session_->grid_list()) { for (const auto& overview_item : grid->window_list()) windows.push_back(overview_item->GetWindow()); } @@ -527,7 +527,7 @@ OverviewController::GetItemWindowListInOverviewGridsForTest() { std::vector<aura::Window*> windows; for (const std::unique_ptr<OverviewGrid>& grid : - overview_session_->grid_list_for_testing()) { + overview_session_->grid_list()) { for (const auto& overview_item : grid->window_list()) windows.push_back(overview_item->item_widget()->GetNativeWindow()); }
diff --git a/ash/wm/overview/overview_grid.cc b/ash/wm/overview/overview_grid.cc index bcc9bc7..cfbdf1f 100644 --- a/ash/wm/overview/overview_grid.cc +++ b/ash/wm/overview/overview_grid.cc
@@ -13,7 +13,6 @@ #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/fps_counter.h" #include "ash/public/cpp/shelf_types.h" -#include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_properties.h" #include "ash/public/cpp/window_state_type.h" #include "ash/root_window_controller.h" @@ -30,10 +29,10 @@ #include "ash/wm/overview/overview_constants.h" #include "ash/wm/overview/overview_controller.h" #include "ash/wm/overview/overview_delegate.h" +#include "ash/wm/overview/overview_highlight_controller.h" #include "ash/wm/overview/overview_item.h" #include "ash/wm/overview/overview_session.h" #include "ash/wm/overview/overview_utils.h" -#include "ash/wm/overview/rounded_rect_view.h" #include "ash/wm/overview/scoped_overview_animation_settings.h" #include "ash/wm/resize_shadow_controller.h" #include "ash/wm/splitview/split_view_controller.h" @@ -46,17 +45,12 @@ #include "ash/wm/workspace/workspace_layout_manager.h" #include "ash/wm/workspace_controller.h" #include "base/containers/unique_ptr_adapters.h" -#include "base/i18n/string_search.h" #include "base/numerics/ranges.h" -#include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" -#include "third_party/skia/include/core/SkColor.h" #include "ui/aura/client/aura_constants.h" #include "ui/compositor/layer_animation_observer.h" -#include "ui/compositor_extra/shadow.h" #include "ui/gfx/geometry/safe_integer_conversions.h" -#include "ui/gfx/geometry/vector2d.h" -#include "ui/views/background.h" +#include "ui/gfx/geometry/vector2d_f.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/wm/core/coordinate_conversion.h" @@ -65,13 +59,6 @@ namespace ash { namespace { -// The color and opacity of the overview selector. -constexpr SkColor kWindowSelectionColor = SkColorSetARGB(36, 255, 255, 255); - -// Corner radius and shadow applied to the overview selector border. -constexpr int kWindowSelectionRadius = 9; -constexpr int kWindowSelectionShadowElevation = 24; - // Windows are not allowed to get taller than this. constexpr int kMaxHeight = 512; @@ -101,11 +88,6 @@ constexpr char kOverviewExitSplitViewHistogram[] = "Ash.Overview.AnimationSmoothness.Exit.SplitView"; -// Returns the vector for the fade in animation. -gfx::Vector2d GetSlideVectorForFadeIn(bool reverse, const gfx::Rect& bounds) { - return gfx::Vector2d(bounds.width() * (reverse ? -1 : 1), 0); -} - template <const char* clamshell_single_name, const char* clamshell_multi_name, const char* tablet_name, @@ -488,66 +470,8 @@ window_item->SetBounds(rects[i], animation_types[i]); } - // If the selection widget is active, reposition it without any animation. - if (selection_widget_) - MoveSelectionWidgetToTarget(animate); -} - -bool OverviewGrid::Move(bool reverse, bool animate) { - if (empty()) - return true; - - bool recreate_selection_widget = false; - bool out_of_bounds = false; - bool changed_selection_index = false; - gfx::RectF old_bounds; - if (SelectedWindow()) - old_bounds = SelectedWindow()->target_bounds(); - - // TODO(dantonvu|sammiequon): Refactor this so OverviewSession controls and - // owns |selection_widget_|. Also rename selection related names to - // highlighted as selection can also mean something else in overview. - if (!selection_widget_) { - selected_index_ = reverse ? window_list_.size() - 1 : 0; - changed_selection_index = true; - } - - // Checks number of windows present during a session. If there's only one - // window being used across all displays, allow the user to highlight the - // window but unable to move it. - // TODO(sammiequon): Investigate if we can remove this call. - if (overview_session()->NumWindowsTotal() == 1u) { - MoveSelectionWidget(reverse, recreate_selection_widget, out_of_bounds, - animate); - return true; - } - - while (!changed_selection_index) { - if (reverse) { - if (selected_index_ == 0) - out_of_bounds = true; - --selected_index_; - } else { - if (selected_index_ >= window_list_.size() - 1) - out_of_bounds = true; - ++selected_index_; - } - if (!out_of_bounds && SelectedWindow()) { - if (SelectedWindow()->target_bounds().y() != old_bounds.y()) - recreate_selection_widget = true; - } - changed_selection_index = true; - } - MoveSelectionWidget(reverse, recreate_selection_widget, out_of_bounds, - animate); - return out_of_bounds; -} - -OverviewItem* OverviewGrid::SelectedWindow() const { - if (!selection_widget_) - return nullptr; - CHECK_LT(selected_index_, window_list_.size()); - return window_list_[selected_index_].get(); + overview_session_->highlight_controller()->OnWindowsRepositioned( + root_window_); } OverviewItem* OverviewGrid::GetOverviewItemContaining( @@ -596,24 +520,18 @@ return item->GetWindow() == window; }); DCHECK(iter != window_list_.rend()); - const size_t removed_index = GetOverviewItemIndex(overview_item); window_observer_.Remove(window); window_state_observer_.Remove(wm::GetWindowState(window)); + + if (overview_session_) { + overview_session_->highlight_controller()->OnViewDestroying( + (*iter)->caption_container_view()); + } + // Erase from the list first because deleting OverviewItem can lead to // iterating through the |window_list_|. std::unique_ptr<OverviewItem> tmp = std::move(*iter); window_list_.erase(std::next(iter).base()); - - if (empty()) { - selected_index_ = 0; - selection_widget_.reset(); - } else if (selection_widget_ && !overview_session_->is_shutting_down()) { - const bool send_focus_alert = selected_index_ == removed_index; - if (selected_index_ >= removed_index && selected_index_ != 0) - --selected_index_; - if (send_focus_alert) - SelectedWindow()->SendAccessibleSelectionEvent(); - } } void OverviewGrid::AddDropTargetForDraggingFromOverview( @@ -626,8 +544,7 @@ overview_session_->AddItem(drop_target_widget_->GetNativeWindow(), /*reposition=*/true, /*animate=*/false, /*ignored_items=*/{dragged_item}, position); - if (selection_widget_ && selected_index_ >= position) - ++selected_index_; + // This part is necessary because |OverviewItem::OnSelectorItemDragStarted| is // called on all overview items before the drop target exists among them. That // is because |AddDropTargetForDraggingFromOverview| is only called for drag @@ -695,16 +612,6 @@ target_window && IsDropTargetWindow(target_window)); } -void OverviewGrid::SetSelectionWidgetVisibility(bool visible) { - if (!selection_widget_) - return; - - if (visible) - selection_widget_->Show(); - else - selection_widget_->Hide(); -} - void OverviewGrid::UpdateCannotSnapWarningVisibility() { for (auto& overview_mode_item : window_list_) overview_mode_item->UpdateCannotSnapWarningVisibility(); @@ -727,8 +634,6 @@ drop_target_widget_ = CreateDropTargetWidget(dragged_window, animate); overview_session_->AddItem(drop_target_widget_->GetNativeWindow(), /*reposition=*/true, animate); - if (selection_widget_) - ++selected_index_; // Stack the |dragged_window| at top during drag. dragged_window->parent()->StackChildAtTop(dragged_window); @@ -751,9 +656,8 @@ if (indicator_state == IndicatorState::kPreviewAreaLeft || indicator_state == IndicatorState::kPreviewAreaRight) { // If the dragged window is currently dragged into preview window area, - // clear the selection widget. - if (SelectedWindow()) - selection_widget_.reset(); + // hide the highlight. + overview_session_->highlight_controller()->ClearTabDragHighlight(); // Also clear ash::kIsDeferredTabDraggingTargetWindowKey key on the target // overview item so that it can't merge into this overview item if the @@ -764,29 +668,21 @@ return; } - // Show the selection widget if |location_in_screen| is contained by the + // Show the tab drag highlight if |location_in_screen| is contained by the // browser windows' overview item in overview. if (target_window && target_window->GetProperty(ash::kIsDeferredTabDraggingTargetWindowKey)) { - size_t previous_selected_index = selected_index_; - selected_index_ = GetOverviewItemIterContainingWindow(target_window) - - window_list_.begin(); - if (previous_selected_index == selected_index_ && selection_widget_) + auto* item = GetOverviewItemContaining(target_window); + if (!item) return; - if (previous_selected_index != selected_index_) - selection_widget_.reset(); - - MoveSelectionWidget( - /*reverse=*/(selected_index_ - previous_selected_index) <= 0, - /*recreate_selection_widget=*/true, - /*out_of_bounds=*/false, - /*animate=*/false); + overview_session_->highlight_controller()->UpdateTabDragHighlight( + target_window->GetRootWindow(), + item->caption_container_view()->bounds()); return; } - if (SelectedWindow()) - selection_widget_.reset(); + overview_session_->highlight_controller()->ClearTabDragHighlight(); } void OverviewGrid::OnWindowDragEnded(aura::Window* dragged_window, @@ -801,11 +697,10 @@ // window into drop target if SelectedWindow is false since drop target will // not be selected and tab dragging might drag a tab window to merge it into a // browser window in overview. - if (SelectedWindow()) { - selection_widget_.reset(); - } else if (should_drop_window_into_overview) { + if (overview_session_->highlight_controller()->IsTabDragHighlightVisible()) + overview_session_->highlight_controller()->ClearTabDragHighlight(); + else if (should_drop_window_into_overview) AddDraggedWindowIntoOverviewOnDragEnd(dragged_window); - } RemoveDropTarget(); @@ -851,12 +746,15 @@ window_state_observer_.Remove(wm::GetWindowState(window)); auto iter = GetOverviewItemIterContainingWindow(window); DCHECK(iter != window_list_.end()); + if (overview_session_) { + overview_session_->highlight_controller()->OnViewDestroying( + (*iter)->caption_container_view()); + } // Windows that are animating to a close state already call PositionWindows, // no need to call it twice. const bool needs_repositioning = !((*iter)->animating_to_close()); - size_t removed_index = iter - window_list_.begin(); // Erase from the list first because deleting OverviewItem can lead to // iterating through the |window_list_|. std::unique_ptr<OverviewItem> tmp = std::move(*iter); @@ -864,7 +762,6 @@ tmp.reset(); if (empty()) { - selection_widget_.reset(); // If the grid is now empty, notify |overview_session_| so that it erases us // from its grid list. if (overview_session_) @@ -872,15 +769,6 @@ return; } - // If selecting, update the selection index. - if (selection_widget_) { - bool send_focus_alert = selected_index_ == removed_index; - if (selected_index_ >= removed_index && selected_index_ != 0) - selected_index_--; - if (send_focus_alert) - SelectedWindow()->SendAccessibleSelectionEvent(); - } - if (needs_repositioning) PositionWindows(true); } @@ -1365,124 +1253,6 @@ desks_widget_->Show(); } -void OverviewGrid::InitSelectionWidget(bool reverse) { - selection_widget_ = std::make_unique<views::Widget>(); - views::Widget::InitParams params; - params.type = views::Widget::InitParams::TYPE_POPUP; - params.keep_on_top = false; - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; - params.layer_type = ui::LAYER_SOLID_COLOR; - params.accept_events = false; - selection_widget_->set_focus_on_creation(false); - params.parent = root_window_->GetChildById(kShellWindowId_WallpaperContainer); - selection_widget_->Init(params); - aura::Window* widget_window = selection_widget_->GetNativeWindow(); - widget_window->SetProperty(kHideInDeskMiniViewKey, true); - // Disable the "bounce in" animation when showing the window. - ::wm::SetWindowVisibilityAnimationTransition(widget_window, - ::wm::ANIMATE_NONE); - widget_window->layer()->SetColor(kWindowSelectionColor); - widget_window->layer()->SetRoundedCornerRadius( - {kWindowSelectionRadius, kWindowSelectionRadius, kWindowSelectionRadius, - kWindowSelectionRadius}); - // Set the opacity to 0 initial so we can fade it in. - widget_window->layer()->SetOpacity(0.f); - selection_widget_->Show(); - - gfx::Rect target_bounds = - gfx::ToEnclosedRect(SelectedWindow()->target_bounds()); - ::wm::ConvertRectFromScreen(root_window_, &target_bounds); - gfx::Vector2d fade_out_direction = - GetSlideVectorForFadeIn(reverse, target_bounds); - widget_window->SetBounds(target_bounds - fade_out_direction); - widget_window->SetName("OverviewModeSelector"); - - selector_shadow_ = std::make_unique<ui::Shadow>(); - selector_shadow_->Init(kWindowSelectionShadowElevation); - selector_shadow_->layer()->SetVisible(true); - selection_widget_->GetLayer()->SetMasksToBounds(false); - selection_widget_->GetLayer()->Add(selector_shadow_->layer()); - selector_shadow_->SetContentBounds(gfx::Rect(target_bounds.size())); -} - -void OverviewGrid::MoveSelectionWidget(bool reverse, - bool recreate_selection_widget, - bool out_of_bounds, - bool animate) { - // If the selection widget is already active, fade it out in the selection - // direction. - if (selection_widget_ && (recreate_selection_widget || out_of_bounds)) { - if (overview_session_->enter_exit_overview_type() == - OverviewSession::EnterExitOverviewType::kImmediateExit) { - ImmediatelyCloseWidgetOnExit(std::move(selection_widget_)); - } else { - // Animate the old selection widget and then destroy it. - views::Widget* old_selection = selection_widget_.get(); - aura::Window* old_selection_window = old_selection->GetNativeWindow(); - gfx::Vector2d fade_out_direction = - GetSlideVectorForFadeIn(reverse, old_selection_window->bounds()); - - ScopedOverviewAnimationSettings settings( - OVERVIEW_ANIMATION_SELECTION_WINDOW, old_selection_window); - // CleanupAnimationObserver will delete itself (and the widget) when the - // motion animation is complete. Ownership over the observer is passed to - // the overview_session_->delegate() which has longer lifetime so that - // animations can continue even after the overview session is shut down. - std::unique_ptr<CleanupAnimationObserver> observer( - new CleanupAnimationObserver(std::move(selection_widget_))); - settings.AddObserver(observer.get()); - overview_session_->delegate()->AddExitAnimationObserver( - std::move(observer)); - old_selection->SetOpacity(0.f); - old_selection_window->SetBounds(old_selection_window->bounds() + - fade_out_direction); - old_selection->Hide(); - } - } - if (out_of_bounds) - return; - - if (!selection_widget_) - InitSelectionWidget(reverse); - - // Send an a11y alert so that if ChromeVox is enabled, the item label is - // read. - SelectedWindow()->SendAccessibleSelectionEvent(); - // The selection widget is moved to the newly selected item in the same - // grid. - MoveSelectionWidgetToTarget(animate); -} - -void OverviewGrid::MoveSelectionWidgetToTarget(bool animate) { - gfx::Rect bounds = gfx::ToEnclosingRect(SelectedWindow()->target_bounds()); - ::wm::ConvertRectFromScreen(root_window_, &bounds); - if (animate) { - ScopedOverviewAnimationSettings settings( - OVERVIEW_ANIMATION_SELECTION_WINDOW, - selection_widget_->GetNativeWindow()); - selection_widget_->SetBounds(bounds); - selection_widget_->SetOpacity(1.f); - - if (selector_shadow_) { - ScopedOverviewAnimationSettings settings( - OVERVIEW_ANIMATION_SELECTION_WINDOW_SHADOW, - selector_shadow_->shadow_layer()->GetAnimator()); - bounds.Inset(1, 1); - selector_shadow_->SetContentBounds( - gfx::Rect(gfx::Point(1, 1), bounds.size())); - } - return; - } - selection_widget_->SetBounds(bounds); - selection_widget_->SetOpacity(1.f); - if (selector_shadow_) { - bounds.Inset(1, 1); - selector_shadow_->SetContentBounds( - gfx::Rect(gfx::Point(1, 1), bounds.size())); - } -} - std::vector<gfx::RectF> OverviewGrid::GetWindowRects( const base::flat_set<OverviewItem*>& ignored_items) { gfx::Rect total_bounds = GetGridEffectiveBounds();
diff --git a/ash/wm/overview/overview_grid.h b/ash/wm/overview/overview_grid.h index cf9963f7..e01ce6a 100644 --- a/ash/wm/overview/overview_grid.h +++ b/ash/wm/overview/overview_grid.h
@@ -21,10 +21,6 @@ #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" -namespace ui { -class Shadow; -} - namespace views { class Widget; } @@ -80,18 +76,6 @@ OverviewSession::OverviewTransition transition = OverviewSession::OverviewTransition::kInOverview); - // Updates |selected_index_| according to the specified direction and calls - // MoveSelectionWidget(). The default is to move forward (left to right) - // unless |reverse| is true. If we call this and we are the last item in the - // row (or first if |reverse|), we slide out the current highlight, as a new - // one slides into the next row. Returns |true| if the new selection index is - // out of this window grid bounds. Note: the default is always left to right - // even in RTL languages. - bool Move(bool reverse, bool animate); - - // Returns the target selected window, or NULL if there is none selected. - OverviewItem* SelectedWindow() const; - // Returns the OverviewItem if a window is contained in any of the // OverviewItems this grid owns. Returns nullptr if no such a OverviewItem // exist. @@ -150,10 +134,6 @@ OverviewItem* dragged_item, const gfx::PointF& location_in_screen); - // Shows or hides the selection widget. To be called by an overview item when - // it is dragged. - void SetSelectionWidgetVisibility(bool visible); - void UpdateCannotSnapWarningVisibility(); // Called when any OverviewItem on any OverviewGrid has started/ended being @@ -289,17 +269,16 @@ // Returns how many overview items are in the grid. size_t size() const { return window_list_.size(); } - // Returns true if the selection widget is active. - bool is_selecting() const { return selection_widget_ != nullptr; } - // Returns the root window in which the grid displays the windows. const aura::Window* root_window() const { return root_window_; } + OverviewSession* overview_session() { return overview_session_; } + const std::vector<std::unique_ptr<OverviewItem>>& window_list() const { return window_list_; } - OverviewSession* overview_session() { return overview_session_; } + const DesksBarView* desks_bar_view() const { return desks_bar_view_; } const gfx::Rect bounds() const { return bounds_; } @@ -311,10 +290,6 @@ views::Widget* drop_target_widget() { return drop_target_widget_.get(); } - const DesksBarView* GetDesksBarViewForTesting() const { - return desks_bar_view_; - } - private: class TargetWindowObserver; friend class OverviewSessionTest; @@ -330,18 +305,6 @@ // contains the DeskBarView contents. void MaybeInitDesksWidget(); - // Internal function to initialize the selection widget. - void InitSelectionWidget(bool reverse); - - // Moves the selection widget to the specified direction. - void MoveSelectionWidget(bool reverse, - bool recreate_selection_widget, - bool out_of_bounds, - bool animate); - - // Moves the selection widget to the targeted window. - void MoveSelectionWidgetToTarget(bool animate); - // Gets the layout of the overview items. Layout is done in 2 stages // maintaining fixed MRU ordering. // 1. Optimal height is determined. In this stage |height| is bisected to find @@ -403,12 +366,6 @@ // The contents view of the above |desks_widget_| if created. DesksBarView* desks_bar_view_ = nullptr; - // Widget that indicates to the user which is the selected window. - std::unique_ptr<views::Widget> selection_widget_; - - // Shadow around the selector. - std::unique_ptr<ui::Shadow> selector_shadow_; - // The drop target widget. The drop target is created when a window or // overview item is being dragged, and is destroyed when the drag ends or // overview mode is ended. The drop target is hidden when a snap preview area @@ -424,12 +381,6 @@ // minimized widget's content view so that it reflects the merge. std::unique_ptr<TargetWindowObserver> target_window_observer_; - // Current selected window position. - size_t selected_index_ = 0; - - // Number of columns in the grid. - size_t num_columns_ = 0; - // True only after all windows have been prepared for overview. bool prepared_for_overview_ = false;
diff --git a/ash/wm/overview/overview_highlight_controller.cc b/ash/wm/overview/overview_highlight_controller.cc new file mode 100644 index 0000000..074c73a7 --- /dev/null +++ b/ash/wm/overview/overview_highlight_controller.cc
@@ -0,0 +1,352 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/wm/overview/overview_highlight_controller.h" + +#include "ash/public/cpp/shell_window_ids.h" +#include "ash/public/cpp/window_properties.h" +#include "ash/shell.h" +#include "ash/wm/desks/desk_mini_view.h" +#include "ash/wm/desks/desks_bar_view.h" +#include "ash/wm/desks/desks_util.h" +#include "ash/wm/desks/new_desk_button.h" +#include "ash/wm/overview/cleanup_animation_observer.h" +#include "ash/wm/overview/overview_delegate.h" +#include "ash/wm/overview/overview_grid.h" +#include "ash/wm/overview/overview_item.h" +#include "ash/wm/overview/overview_session.h" +#include "ash/wm/overview/overview_utils.h" +#include "ash/wm/overview/scoped_overview_animation_settings.h" +#include "ui/compositor_extra/shadow.h" +#include "ui/views/view.h" +#include "ui/views/widget/widget.h" +#include "ui/wm/core/window_animations.h" +#include "ui/wm/core/window_properties.h" + +namespace ash { + +namespace { + +// The color and opacity of the overview highlight. +constexpr SkColor kHighlightColor = SkColorSetARGB(36, 255, 255, 255); + +// Corner radius and shadow applied to the overview highlight. +constexpr gfx::RoundedCornersF kHighlightCornerRadii{9}; +constexpr int kHighlightShadowElevation = 24; + +aura::Window* GetWindowForView(views::View* view) { + DCHECK(view->GetWidget()); + return view->GetWidget()->GetNativeWindow(); +} + +bool HasSameRootWindow(views::View* view1, views::View* view2) { + return GetWindowForView(view1)->GetRootWindow() == + GetWindowForView(view2)->GetRootWindow(); +} + +bool ShouldCreateHighlight( + OverviewHighlightController::OverviewHighlightableView* previous_view, + OverviewHighlightController::OverviewHighlightableView* + view_to_be_highlighted, + bool reverse) { + if (!previous_view) + return true; + + DCHECK(view_to_be_highlighted); + // Recreate it if the new highlight is on a different root. + if (!HasSameRootWindow(previous_view->GetView(), + view_to_be_highlighted->GetView())) { + return true; + } + + // Recreate it if the new highlight is on a different row. + if (previous_view->GetView()->GetBoundsInScreen().y() != + view_to_be_highlighted->GetView()->GetBoundsInScreen().y()) { + return true; + } + + // Recreate it if we are going from the first item in the same row to the last + // item, or from the last item to the first item. + const int previous_x = previous_view->GetView()->GetBoundsInScreen().x(); + const int current_x = + view_to_be_highlighted->GetView()->GetBoundsInScreen().x(); + return reverse != (current_x < previous_x); +} + +} // namespace + +// Widget which contains two children, a solid rounded corner layer which +// represents the highlight, and a shadow. Done this way instead of a single +// layer, because the rounded corner will clip out the shadow, and we want to +// avoid animating two separate layers. +class OverviewHighlightController::HighlightWidget : public views::Widget { + public: + HighlightWidget(aura::Window* root_window, const gfx::Rect& bounds) { + DCHECK(root_window->IsRootWindow()); + + views::Widget::InitParams params; + params.type = views::Widget::InitParams::TYPE_POPUP; + params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; + params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; + params.layer_type = ui::LAYER_NOT_DRAWN; + params.accept_events = false; + params.parent = + root_window->GetChildById(kShellWindowId_WallpaperContainer); + set_focus_on_creation(false); + Init(params); + + aura::Window* widget_window = GetNativeWindow(); + widget_window->SetProperty(kHideInDeskMiniViewKey, true); + // Disable the "bounce in" animation when showing the window. + ::wm::SetWindowVisibilityAnimationTransition(widget_window, + ::wm::ANIMATE_NONE); + // Set the opacity to 0 initial so we can fade it in. + SetOpacity(0.f); + Show(); + + widget_window->SetBounds(bounds); + widget_window->SetName("OverviewModeHighlight"); + + // Add the shadow. + shadow_layer_ = new ui::Shadow(); + shadow_layer_->Init(kHighlightShadowElevation); + shadow_layer_->SetContentBounds(gfx::Rect(bounds.size())); + shadow_layer_->layer()->SetVisible(true); + widget_window->layer()->SetMasksToBounds(false); + widget_window->layer()->Add(shadow_layer_->layer()); + + // Add rounded corner solid color layer. + color_layer_ = new ui::Layer(ui::LAYER_SOLID_COLOR); + color_layer_->SetColor(kHighlightColor); + color_layer_->SetRoundedCornerRadius(kHighlightCornerRadii); + color_layer_->SetVisible(true); + color_layer_->SetBounds(gfx::Rect(bounds.size())); + widget_window->layer()->Add(color_layer_); + } + + ~HighlightWidget() override = default; + + // Set the bounds of |this|, and also manually sets the bounds of the + // children, because there is no masks to bounds. + void SetWidgetBounds(const gfx::Rect& bounds) { + SetBounds(bounds); + const gfx::Rect child_bounds(bounds.size()); + shadow_layer_->SetContentBounds(child_bounds); + color_layer_->SetBounds(child_bounds); + } + + private: + ui::Shadow* shadow_layer_ = nullptr; + ui::Layer* color_layer_ = nullptr; + + DISALLOW_COPY_AND_ASSIGN(HighlightWidget); +}; + +// ----------------------------------------------------------------------------- +// OverviewHighlightController + +OverviewHighlightController::OverviewHighlightController( + OverviewSession* overview_session) + : overview_session_(overview_session) {} + +OverviewHighlightController::~OverviewHighlightController() = default; + +void OverviewHighlightController::MoveHighlight(bool reverse) { + const std::vector<OverviewHighlightableView*> traversable_views = + GetTraversableViews(); + const int count = int{traversable_views.size()}; + + // |count| can be zero when there are no overview items and no desk views (eg. + // "No recent items" or PIP windows are shown but they aren't traversable). + if (count == 0) + return; + + int index = 0; + if (!highlighted_view_) { + // Pick up where we left off if |deleted_index_| has a value. + if (deleted_index_) { + index = *deleted_index_ >= count ? count - 1 : *deleted_index_; + deleted_index_.reset(); + } else if (reverse) { + index = count - 1; + } + } else { + auto it = std::find(traversable_views.begin(), traversable_views.end(), + highlighted_view_); + DCHECK(it != traversable_views.end()); + const int current_index = std::distance(traversable_views.begin(), it); + DCHECK_GE(current_index, 0); + index = (((reverse ? -1 : 1) + current_index) + count) % count; + } + + UpdateFocusWidget(traversable_views[index], reverse); +} + +void OverviewHighlightController::OnViewDestroying( + OverviewHighlightableView* view) { + DCHECK(view); + if (view != highlighted_view_) + return; + + const std::vector<OverviewHighlightableView*> traversable_views = + GetTraversableViews(); + const auto it = std::find(traversable_views.begin(), traversable_views.end(), + highlighted_view_); + DCHECK(it != traversable_views.end()); + const int current_index = std::distance(traversable_views.begin(), it); + DCHECK_GE(current_index, 0); + deleted_index_ = base::make_optional(current_index); + highlight_widget_.reset(); + highlighted_view_ = nullptr; +} + +void OverviewHighlightController::SetFocusHighlightVisibility(bool visible) { + if (!highlight_widget_) + return; + + if (visible) + highlight_widget_->Show(); + else + highlight_widget_->Hide(); +} + +bool OverviewHighlightController::IsFocusHighlightVisible() const { + return highlight_widget_ && highlight_widget_->IsVisible(); +} + +OverviewItem* OverviewHighlightController::GetHighlightedItem() const { + if (!highlighted_view_) + return nullptr; + + for (auto& grid : overview_session_->grid_list()) { + for (auto& item : grid->window_list()) { + if (highlighted_view_->GetView() == item->caption_container_view()) + return item.get(); + } + } + + return nullptr; +} + +void OverviewHighlightController::ClearTabDragHighlight() { + tab_drag_widget_.reset(); +} + +void OverviewHighlightController::UpdateTabDragHighlight( + aura::Window* root_window, + const gfx::Rect& bounds) { + DCHECK(root_window); + DCHECK(!bounds.IsEmpty()); + if (tab_drag_widget_) { + tab_drag_widget_->SetWidgetBounds(bounds); + return; + } + tab_drag_widget_ = std::make_unique<HighlightWidget>(root_window, bounds); + tab_drag_widget_->SetOpacity(1.f); +} + +bool OverviewHighlightController::IsTabDragHighlightVisible() const { + return !!tab_drag_widget_; +} + +void OverviewHighlightController::OnWindowsRepositioned( + aura::Window* root_window) { + if (!highlight_widget_) + return; + + aura::Window* highlight_window = highlight_widget_->GetNativeWindow(); + if (root_window != highlight_window->GetRootWindow()) + return; + + DCHECK(highlighted_view_); + highlight_widget_->SetWidgetBounds(highlighted_view_->GetHighlightBounds()); +} + +std::vector<OverviewHighlightController::OverviewHighlightableView*> +OverviewHighlightController::GetTraversableViews() const { + std::vector<OverviewHighlightableView*> traversable_views; + traversable_views.reserve(overview_session_->num_items() + + (desks_util::kMaxNumberOfDesks + 1) * + Shell::Get()->GetAllRootWindows().size()); + for (auto& grid : overview_session_->grid_list()) { + auto* bar_view = grid->desks_bar_view(); + if (bar_view) { + // The desk items are always traversable from left to right, even in RTL + // languages. + for (const auto& mini_view : bar_view->mini_views()) + traversable_views.push_back(mini_view.get()); + traversable_views.push_back(bar_view->new_desk_button()); + } + + for (auto& item : grid->window_list()) + traversable_views.push_back(item->caption_container_view()); + } + return traversable_views; +} + +void OverviewHighlightController::UpdateFocusWidget( + OverviewHighlightableView* view_to_be_highlighted, + bool reverse) { + if (highlighted_view_ == view_to_be_highlighted) + return; + + OverviewHighlightableView* previous_view = highlighted_view_; + highlighted_view_ = view_to_be_highlighted; + highlighted_view_->GetView()->NotifyAccessibilityEvent( + ax::mojom::Event::kSelection, true); + + const bool create_highlight = + ShouldCreateHighlight(previous_view, highlighted_view_, reverse); + // If the highlight exists and we need to recreate it, slide the old one out. + if (highlight_widget_ && create_highlight) { + aura::Window* old_highlight_window = highlight_widget_->GetNativeWindow(); + int highlight_width = old_highlight_window->bounds().width(); + gfx::Vector2dF translation(highlight_width * (reverse ? -1.f : 1.f), 0.f); + gfx::Transform transform = old_highlight_window->transform(); + transform.Translate(translation); + + ScopedOverviewAnimationSettings settings( + OVERVIEW_ANIMATION_SELECTION_WINDOW, old_highlight_window); + // CleanupAnimationObserver will delete itself and the widget when the + // motion animation is complete. Ownership over the observer is passed to + // the overview_session_->delegate() which has longer lifetime so that + // animations can continue even after the overview session is shut down. + auto observer = std::make_unique<CleanupAnimationObserver>( + std::move(highlight_widget_)); + settings.AddObserver(observer.get()); + overview_session_->delegate()->AddExitAnimationObserver( + std::move(observer)); + old_highlight_window->layer()->SetOpacity(0.f); + old_highlight_window->SetTransform(transform); + } + + gfx::Rect target_bounds = highlighted_view_->GetHighlightBounds(); + if (!highlight_widget_) { + // Offset the bounds slightly to create a slide in animation. + gfx::Rect initial_bounds = target_bounds; + initial_bounds.Offset(target_bounds.width() * (reverse ? 1 : -1), 0); + highlight_widget_ = std::make_unique<HighlightWidget>( + GetWindowForView(highlighted_view_->GetView())->GetRootWindow(), + initial_bounds); + } + + // Move the highlight to the target. + aura::Window* highlight_window = highlight_widget_->GetNativeWindow(); + gfx::RectF previous_bounds = + gfx::RectF(highlight_window->GetBoundsInRootWindow()); + highlight_widget_->SetWidgetBounds(target_bounds); + gfx::RectF current_bounds = gfx::RectF(target_bounds); + gfx::Transform transform(previous_bounds.width() / current_bounds.width(), + 0.f, 0.f, + previous_bounds.height() / current_bounds.height(), + previous_bounds.x() - current_bounds.x(), + previous_bounds.y() - current_bounds.y()); + highlight_window->SetTransform(transform); + ScopedOverviewAnimationSettings settings(OVERVIEW_ANIMATION_SELECTION_WINDOW, + highlight_window); + highlight_window->SetTransform(gfx::Transform()); + highlight_widget_->SetOpacity(1.f); +} + +} // namespace ash
diff --git a/ash/wm/overview/overview_highlight_controller.h b/ash/wm/overview/overview_highlight_controller.h new file mode 100644 index 0000000..f1187bf --- /dev/null +++ b/ash/wm/overview/overview_highlight_controller.h
@@ -0,0 +1,111 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_WM_OVERVIEW_OVERVIEW_HIGHLIGHT_CONTROLLER_H_ +#define ASH_WM_OVERVIEW_OVERVIEW_HIGHLIGHT_CONTROLLER_H_ + +#include <memory> + +#include "ash/ash_export.h" +#include "base/macros.h" +#include "base/optional.h" +#include "ui/gfx/geometry/rect.h" + +namespace aura { +class Window; +} + +namespace views { +class View; +} + +namespace ash { +class OverviewItem; +class OverviewSession; + +// Manages highlighting items while in overview. Creates a semi transparent +// highlight when users try to traverse through overview items using arrow keys +// or tab keys, or when users are tab dragging. +// TODO(sammiequon): Add a new test class which tests highlighting desk items, +// and move the existing OverviewSession highlight related tests to the new +// class. +class ASH_EXPORT OverviewHighlightController { + public: + // An interface that must be implemented by classes that want to be + // highlighted in overview. + class OverviewHighlightableView { + public: + // Get the view class associated with |this|. + virtual views::View* GetView() = 0; + // Get the bounds of where the highlight should be for |this|, in screen + // coordinates. + virtual gfx::Rect GetHighlightBounds() = 0; + + protected: + virtual ~OverviewHighlightableView() {} + }; + + explicit OverviewHighlightController(OverviewSession* overview_session); + ~OverviewHighlightController(); + + // Moves the |highlight_widget_| to the next traversable view. + void MoveHighlight(bool reverse); + + // Called when a |view| that might be in the focus traversal rotation is about + // to be deleted. + void OnViewDestroying(OverviewHighlightableView* view); + + // Sets and gets the visibility of |highlight_widget_|. + void SetFocusHighlightVisibility(bool visible); + bool IsFocusHighlightVisible() const; + + // Tries to get the item that is currently highlighted. Returns null if there + // is no highlight, or if the highlight is on a desk view. + OverviewItem* GetHighlightedItem() const; + + // Clears, creates or repositions the tab dragging highlight. + void ClearTabDragHighlight(); + void UpdateTabDragHighlight(aura::Window* root_window, + const gfx::Rect& bounds); + bool IsTabDragHighlightVisible() const; + + // Called when an overview grid repositions its windows. Moves the focus + // highlight widget without animation. + void OnWindowsRepositioned(aura::Window* root_window); + + private: + class HighlightWidget; + + // Returns a vector of views that can be traversed via overview tabbing. + // Includes desk mini views, the new desk button and overview items. + std::vector<OverviewHighlightableView*> GetTraversableViews() const; + + void UpdateFocusWidget(OverviewHighlightableView* view_to_be_highlighted, + bool reverse); + + // The overview session which owns this object. Guaranteed to be non-null for + // the lifetime of |this|. + OverviewSession* const overview_session_; + + // If an item that is selected is deleted, store its index, so the next + // traversal can pick up where it left off. + base::Optional<int> deleted_index_ = base::nullopt; + // The current view that |highlight_widget_| is highlighting. This will be + // non-null if |highlight_widget_| is. + OverviewHighlightableView* highlighted_view_ = nullptr; + // A background highlight that shows up when using keyboard traversal with tab + // or arrow keys. + std::unique_ptr<HighlightWidget> highlight_widget_; + + // A background highlight that shows up when dragging a tab towards a chrome + // window overview item, signaling that we can drop the tab into that browser + // window. + std::unique_ptr<HighlightWidget> tab_drag_widget_; + + DISALLOW_COPY_AND_ASSIGN(OverviewHighlightController); +}; + +} // namespace ash + +#endif // ASH_WM_OVERVIEW_OVERVIEW_HIGHLIGHT_CONTROLLER_H_
diff --git a/ash/wm/overview/overview_item.cc b/ash/wm/overview/overview_item.cc index d165b309..147624f 100644 --- a/ash/wm/overview/overview_item.cc +++ b/ash/wm/overview/overview_item.cc
@@ -21,6 +21,7 @@ #include "ash/wm/overview/overview_constants.h" #include "ash/wm/overview/overview_controller.h" #include "ash/wm/overview/overview_grid.h" +#include "ash/wm/overview/overview_highlight_controller.h" #include "ash/wm/overview/overview_utils.h" #include "ash/wm/overview/overview_window_drag_controller.h" #include "ash/wm/overview/rounded_label_widget.h" @@ -736,7 +737,7 @@ } void OverviewItem::OnStartingAnimationComplete() { - DCHECK(item_widget_.get()); + DCHECK(item_widget_); if (transform_window_.IsMinimized()) { // Fade the title in if minimized. The rest of |item_widget_| should already // be shown. @@ -809,7 +810,6 @@ if (!IsDragItem()) return; - overview_grid_->SetSelectionWidgetVisibility(true); overview_session_->CompleteDrag(this, location_in_screen); } @@ -1046,8 +1046,6 @@ } void OverviewItem::StartDrag() { - overview_grid_->SetSelectionWidgetVisibility(false); - // |transform_window_| handles hiding shadow and rounded edges mask while // animating, and applies them after animation is complete. Prevent the // shadow and rounded edges mask from showing up after dragging in the case
diff --git a/ash/wm/overview/overview_item.h b/ash/wm/overview/overview_item.h index 6d0e88f..07da4d4d 100644 --- a/ash/wm/overview/overview_item.h +++ b/ash/wm/overview/overview_item.h
@@ -221,6 +221,10 @@ views::Widget* item_widget() { return item_widget_.get(); } + CaptionContainerView* caption_container_view() { + return caption_container_view_; + } + OverviewGrid* overview_grid() { return overview_grid_; } void set_should_animate_when_entering(bool should_animate) {
diff --git a/ash/wm/overview/overview_session.cc b/ash/wm/overview/overview_session.cc index 57bd1294..fc7f5c2 100644 --- a/ash/wm/overview/overview_session.cc +++ b/ash/wm/overview/overview_session.cc
@@ -26,6 +26,7 @@ #include "ash/wm/overview/overview_controller.h" #include "ash/wm/overview/overview_delegate.h" #include "ash/wm/overview/overview_grid.h" +#include "ash/wm/overview/overview_highlight_controller.h" #include "ash/wm/overview/overview_item.h" #include "ash/wm/overview/overview_utils.h" #include "ash/wm/overview/overview_window_drag_controller.h" @@ -80,7 +81,7 @@ // shown, but we want to place the thumbnails as if the shelf was shown, so // manually update the work area. if (Shelf::ForWindow(root_window)->GetVisibilityState() == SHELF_AUTO_HIDE) { - const int inset = kShelfSize; + const int inset = ShelfConstants::shelf_size(); switch (Shelf::ForWindow(root_window)->alignment()) { case SHELF_ALIGNMENT_BOTTOM: case SHELF_ALIGNMENT_BOTTOM_LOCKED: @@ -155,7 +156,9 @@ OverviewSession::OverviewSession(OverviewDelegate* delegate) : delegate_(delegate), restore_focus_window_(wm::GetFocusedWindow()), - overview_start_time_(base::Time::Now()) { + overview_start_time_(base::Time::Now()), + highlight_controller_( + std::make_unique<OverviewHighlightController>(this)) { DCHECK(delegate_); Shell::Get()->AddPreTargetHandler(this); } @@ -368,16 +371,7 @@ } } } - if (index > 0 && selected_grid_index_ >= index) { - // If the grid closed is not the one with the selected item, we do not need - // to move the selected item. - if (selected_grid_index_ == index) - --selected_grid_index_; - // If the grid which became empty was the one with the selected window, we - // need to select a window on the newly selected grid. - if (selected_grid_index_ == index - 1) - Move(/*reverse=*/false); - } + if (grid_list_.empty()) EndOverview(); else @@ -389,9 +383,9 @@ } bool OverviewSession::AcceptSelection() { - if (!grid_list_[selected_grid_index_]->is_selecting()) + if (!highlight_controller_->GetHighlightedItem()) return false; - SelectWindow(grid_list_[selected_grid_index_]->SelectedWindow()); + SelectWindow(highlight_controller_->GetHighlightedItem()); return true; } @@ -496,6 +490,7 @@ void OverviewSession::InitiateDrag(OverviewItem* item, const gfx::PointF& location_in_screen, bool allow_drag_to_close) { + highlight_controller_->SetFocusHighlightVisibility(false); window_drag_controller_ = std::make_unique<OverviewWindowDragController>( this, item, allow_drag_to_close); window_drag_controller_->InitiateDrag(location_in_screen); @@ -520,6 +515,8 @@ OverviewWindowDragController::DragResult::kSuccessfulDragToSnap; for (std::unique_ptr<OverviewGrid>& grid : grid_list_) grid->OnSelectorItemDragEnded(snap); + + highlight_controller_->SetFocusHighlightVisibility(true); } void OverviewSession::StartNormalDragMode( @@ -738,12 +735,10 @@ } aura::Window* OverviewSession::GetHighlightedWindow() { - DCHECK_LT(selected_grid_index_, grid_list_.size()); - auto* grid = grid_list_[selected_grid_index_].get(); - if (!grid->is_selecting()) + OverviewItem* item = highlight_controller_->GetHighlightedItem(); + if (!item) return nullptr; - - return grid->SelectedWindow()->GetWindow(); + return item->GetWindow(); } void OverviewSession::SuspendReposition() { @@ -764,13 +759,6 @@ return true; } -size_t OverviewSession::NumWindowsTotal() const { - size_t sum = 0; - for (const std::unique_ptr<OverviewGrid>& overview_grid : grid_list_) - sum += overview_grid->size(); - return sum; -} - void OverviewSession::OnDisplayRemoved(const display::Display& display) { // TODO(flackr): Keep window selection active on remaining displays. EndOverview(); @@ -879,19 +867,33 @@ ++num_key_presses_; Move(/*reverse=*/true); break; - case ui::VKEY_W: + case ui::VKEY_W: { + // TODO(afakhry|sammiequon): Make ctrl W and enter shortcut work for desk + // items. ctrl W should activate the mini desk close button and do nothing + // for the new desk button. Enter should activate the desk mini view or + // new desk button. if (!(event->flags() & ui::EF_CONTROL_DOWN) || - !grid_list_[selected_grid_index_]->is_selecting()) { + !highlight_controller_->IsFocusHighlightVisible()) { return; } + + OverviewItem* item = highlight_controller_->GetHighlightedItem(); + if (!item) + return; base::RecordAction( base::UserMetricsAction("WindowSelector_OverviewCloseKey")); - grid_list_[selected_grid_index_]->SelectedWindow()->CloseWindow(); + item->CloseWindow(); break; - case ui::VKEY_RETURN: + } + case ui::VKEY_RETURN: { // Ignore if no item is selected. - if (!grid_list_[selected_grid_index_]->is_selecting()) + if (!highlight_controller_->IsFocusHighlightVisible()) return; + + OverviewItem* item = highlight_controller_->GetHighlightedItem(); + if (!item) + return; + UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.ArrowKeyPresses", num_key_presses_); UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.WindowSelector.KeyPressesOverItemsRatio", @@ -899,8 +901,9 @@ 30); base::RecordAction( base::UserMetricsAction("WindowSelector_OverviewEnterKey")); - SelectWindow(grid_list_[selected_grid_index_]->SelectedWindow()); + SelectWindow(item); break; + } default: return; } @@ -989,24 +992,11 @@ } void OverviewSession::Move(bool reverse) { - // If this is the first move and it's going backwards, start on the last - // display. - if (reverse && !grid_list_.empty() && - !grid_list_[selected_grid_index_]->is_selecting()) { - selected_grid_index_ = grid_list_.size() - 1; - } + // Do not allow moving the highlight while in the middle of a drag. + if (window_drag_controller_ && window_drag_controller_->item()) + return; - // Keep calling |Move()| on the grids until one of them reports no overflow or - // we made a full cycle on all the grids. - const int grid_index_change = reverse ? -1 : 1; - for (size_t i = 0; - i <= grid_list_.size() && - grid_list_[selected_grid_index_]->Move(reverse, /*animate=*/true); - ++i) { - selected_grid_index_ = - (selected_grid_index_ + grid_index_change + grid_list_.size()) % - grid_list_.size(); - } + highlight_controller_->MoveHighlight(reverse); } void OverviewSession::RemoveAllObservers() {
diff --git a/ash/wm/overview/overview_session.h b/ash/wm/overview/overview_session.h index 8d0c428..2c356ae 100644 --- a/ash/wm/overview/overview_session.h +++ b/ash/wm/overview/overview_session.h
@@ -40,6 +40,7 @@ namespace ash { class OverviewDelegate; class OverviewGrid; +class OverviewHighlightController; class OverviewItem; class OverviewWindowDragController; class RoundedLabelWidget; @@ -234,9 +235,6 @@ // Returns true if all its window grids don't have any window item. bool IsEmpty() const; - // Returns the sum of the number of windows in all window grids. - size_t NumWindowsTotal() const; - // display::DisplayObserver: void OnDisplayRemoved(const display::Display& display) override; void OnDisplayMetricsChanged(const display::Display& display, @@ -268,6 +266,12 @@ return split_view_drag_indicators_.get(); } + const std::vector<std::unique_ptr<OverviewGrid>>& grid_list() const { + return grid_list_; + } + + size_t num_items() const { return num_items_; } + EnterExitOverviewType enter_exit_overview_type() const { return enter_exit_overview_type_; } @@ -279,18 +283,16 @@ return window_drag_controller_.get(); } - const std::vector<std::unique_ptr<OverviewGrid>>& grid_list_for_testing() - const { - return grid_list_; + OverviewHighlightController* highlight_controller() { + return highlight_controller_.get(); } - size_t num_items_for_testing() const { return num_items_; } - RoundedLabelWidget* no_windows_widget_for_testing() { return no_windows_widget_.get(); } private: + friend class DesksAcceleratorsTest; friend class OverviewSessionTest; // |focus|, restores focus to the stored window. @@ -351,9 +353,6 @@ // overview mode. This will be nullptr if split view is not enabled. std::unique_ptr<SplitViewDragIndicators> split_view_drag_indicators_; - // Tracks the index of the root window the selection widget is in. - size_t selected_grid_index_ = 0; - // The following variables are used for metric collection purposes. All of // them refer to this particular overview session and are not cumulative: // The time when overview was started. @@ -379,6 +378,8 @@ std::unique_ptr<ScopedOverviewHideWindows> hide_overview_windows_; + std::unique_ptr<OverviewHighlightController> highlight_controller_; + DISALLOW_COPY_AND_ASSIGN(OverviewSession); };
diff --git a/ash/wm/overview/overview_session_unittest.cc b/ash/wm/overview/overview_session_unittest.cc index e3b7fde..6caf4d5 100644 --- a/ash/wm/overview/overview_session_unittest.cc +++ b/ash/wm/overview/overview_session_unittest.cc
@@ -33,6 +33,7 @@ #include "ash/wm/overview/overview_constants.h" #include "ash/wm/overview/overview_controller.h" #include "ash/wm/overview/overview_grid.h" +#include "ash/wm/overview/overview_highlight_controller.h" #include "ash/wm/overview/overview_item.h" #include "ash/wm/overview/overview_utils.h" #include "ash/wm/overview/overview_window_drag_controller.h" @@ -266,36 +267,30 @@ return overview_session()->grid_list_[grid_index]->GetDropTarget(); } - // Selects |window| in the active overview session by cycling through all + // Highlights |window| in the active overview session by cycling through all // windows in overview until it is found. Returns true if |window| was found, // false otherwise. - bool SelectWindow(const aura::Window* window) { - if (GetSelectedWindow() == nullptr) + bool HighlightWindow(const aura::Window* window) { + if (GetHighlightedWindow() == nullptr) SendKey(ui::VKEY_TAB); - const aura::Window* start_window = GetSelectedWindow(); + const aura::Window* start_window = GetHighlightedWindow(); if (start_window == window) return true; do { SendKey(ui::VKEY_TAB); - } while (GetSelectedWindow() != window && - GetSelectedWindow() != start_window); - return GetSelectedWindow() == window; + } while (GetHighlightedWindow() != window && + GetHighlightedWindow() != start_window); + return GetHighlightedWindow() == window; } - const aura::Window* GetSelectedWindow() { - OverviewSession* os = overview_session(); + const aura::Window* GetHighlightedWindow() { OverviewItem* item = - os->grid_list_[os->selected_grid_index_]->SelectedWindow(); + overview_session()->highlight_controller()->GetHighlightedItem(); if (!item) return nullptr; return item->GetWindow(); } - bool selection_widget_active() { - OverviewSession* os = overview_session(); - return os->grid_list_[os->selected_grid_index_]->is_selecting(); - } - views::ImageButton* GetCloseButton(OverviewItem* item) { return item->GetCloseButtonForTesting(); } @@ -553,11 +548,11 @@ EXPECT_EQ( 2, user_action_tester.GetActionCount(kActiveWindowChangedFromOverview)); - // Select |window2| using the arrow keys. Activate it (and exit overview) by - // pressing the return key. + // Highlight |window2| using the arrow keys. Activate it (and exit overview) + // by pressing the return key. ::wm::ActivateWindow(window1.get()); ToggleOverview(); - ASSERT_TRUE(SelectWindow(window2.get())); + ASSERT_TRUE(HighlightWindow(window2.get())); SendKey(ui::VKEY_RETURN); EXPECT_EQ( 3, user_action_tester.GetActionCount(kActiveWindowChangedFromOverview)); @@ -590,7 +585,7 @@ // |window1| remains active. Select using the keyboard. ASSERT_EQ(window1.get(), wm::GetFocusedWindow()); ToggleOverview(); - ASSERT_TRUE(SelectWindow(window1.get())); + ASSERT_TRUE(HighlightWindow(window1.get())); SendKey(ui::VKEY_RETURN); EXPECT_EQ( 0, user_action_tester.GetActionCount(kActiveWindowChangedFromOverview)); @@ -1422,54 +1417,6 @@ EXPECT_FALSE(GetDropTarget(1)); } -// Test that |OverviewGrid::selected_index_| is updated with the drop target for -// dragging from overview. -TEST_F(OverviewSessionTest, - SelectionUpdatedWithDropTargetForDraggingFromOverview) { - EnterTabletMode(); - std::unique_ptr<aura::Window> window4(CreateTestWindow()); - std::unique_ptr<aura::Window> window3(CreateTestWindow()); - std::unique_ptr<aura::Window> window2(CreateTestWindow()); - std::unique_ptr<aura::Window> window1(CreateTestWindow()); - ToggleOverview(); - OverviewItem* item2 = GetWindowItemForWindow(0, window2.get()); - const gfx::PointF drag_start_point = item2->target_bounds().CenterPoint(); - const gfx::PointF drag_end_point = - drag_start_point + gfx::Vector2dF(5.f, 0.f); - const auto drag_item_and_check_selection = - [this, &drag_start_point, &drag_end_point](aura::Window* selected_window, - OverviewItem* dragged_item) { - EXPECT_TRUE(SelectWindow(selected_window)); - overview_session()->InitiateDrag(dragged_item, drag_start_point, - /*allow_drag_to_close=*/false); - overview_session()->Drag(dragged_item, drag_end_point); - EXPECT_EQ(selected_window, GetSelectedWindow()); - overview_session()->CompleteDrag(dragged_item, drag_end_point); - EXPECT_EQ(selected_window, GetSelectedWindow()); - }; - // Test the case where |OverviewGrid::selected_index_| is strictly less than - // the index of the dragged item. - drag_item_and_check_selection(window1.get(), item2); - // Test the case where |OverviewGrid::selected_index_| is equal to the index - // of the dragged item. - drag_item_and_check_selection(window2.get(), item2); - // Test the case where |OverviewGrid::selected_index_| is equal to the index - // where the drop target is to be inserted. - drag_item_and_check_selection(window3.get(), item2); - // Test the case where |OverviewGrid::selected_index_| is strictly greater - // than the index where the drop target is to be inserted. - drag_item_and_check_selection(window4.get(), item2); - - // Test the case where the drop target becomes selected during the drag. - EXPECT_TRUE(SelectWindow(window4.get())); - overview_session()->InitiateDrag(item2, drag_start_point, - /*allow_drag_to_close=*/false); - overview_session()->Drag(item2, drag_end_point); - EXPECT_TRUE(SelectWindow(GetDropTarget(0)->GetWindow())); - overview_session()->CompleteDrag(item2, drag_end_point); - EXPECT_EQ(window2.get(), GetSelectedWindow()); -} - namespace { // A simple window delegate that returns the specified hit-test code when @@ -1591,11 +1538,11 @@ const std::vector<std::unique_ptr<OverviewItem>>& overview_windows = GetWindowItemsForRoot(0); SendKey(ui::VKEY_TAB); - EXPECT_EQ(GetSelectedWindow(), overview_windows[0]->GetWindow()); + EXPECT_EQ(GetHighlightedWindow(), overview_windows[0]->GetWindow()); SendKey(ui::VKEY_TAB); - EXPECT_EQ(GetSelectedWindow(), overview_windows[1]->GetWindow()); + EXPECT_EQ(GetHighlightedWindow(), overview_windows[1]->GetWindow()); SendKey(ui::VKEY_TAB); - EXPECT_EQ(GetSelectedWindow(), overview_windows[0]->GetWindow()); + EXPECT_EQ(GetHighlightedWindow(), overview_windows[0]->GetWindow()); } TEST_F(OverviewSessionTest, AcceleratorInOverviewSession) { @@ -1620,7 +1567,7 @@ ToggleOverview(); SendKey(ui::VKEY_RIGHT); - EXPECT_EQ(widget->GetNativeWindow(), GetSelectedWindow()); + EXPECT_EQ(widget->GetNativeWindow(), GetHighlightedWindow()); SendKey(ui::VKEY_W, ui::EF_CONTROL_DOWN); EXPECT_TRUE(widget->IsClosed()); } @@ -1631,7 +1578,7 @@ const size_t test_windows = 9; UpdateDisplay("800x600"); std::vector<std::unique_ptr<aura::Window>> windows; - for (size_t i = test_windows; i > 0; i--) { + for (size_t i = test_windows; i > 0; --i) { windows.push_back( std::unique_ptr<aura::Window>(CreateTestWindowInShellWithId(i))); } @@ -1647,7 +1594,7 @@ {9, 8, 7, 6, 5, 4, 3, 2, 1, 9} // Up (same as Left) }; - for (size_t key_index = 0; key_index < base::size(arrow_keys); key_index++) { + for (size_t key_index = 0; key_index < base::size(arrow_keys); ++key_index) { ToggleOverview(); const std::vector<std::unique_ptr<OverviewItem>>& overview_windows = GetWindowItemsForRoot(0); @@ -1656,7 +1603,7 @@ // TODO(flackr): Add a more readable error message by constructing a // string from the window IDs. const int index = index_path_for_direction[key_index][i]; - EXPECT_EQ(GetSelectedWindow()->id(), + EXPECT_EQ(GetHighlightedWindow()->id(), overview_windows[index - 1]->GetWindow()->id()); } ToggleOverview(); @@ -1724,13 +1671,13 @@ const std::vector<std::unique_ptr<OverviewItem>>& overview_root2 = GetWindowItemsForRoot(1); SendKey(ui::VKEY_RIGHT); - EXPECT_EQ(GetSelectedWindow(), overview_root1[0]->GetWindow()); + EXPECT_EQ(GetHighlightedWindow(), overview_root1[0]->GetWindow()); SendKey(ui::VKEY_RIGHT); - EXPECT_EQ(GetSelectedWindow(), overview_root1[1]->GetWindow()); + EXPECT_EQ(GetHighlightedWindow(), overview_root1[1]->GetWindow()); SendKey(ui::VKEY_RIGHT); - EXPECT_EQ(GetSelectedWindow(), overview_root2[0]->GetWindow()); + EXPECT_EQ(GetHighlightedWindow(), overview_root2[0]->GetWindow()); SendKey(ui::VKEY_RIGHT); - EXPECT_EQ(GetSelectedWindow(), overview_root2[1]->GetWindow()); + EXPECT_EQ(GetHighlightedWindow(), overview_root2[1]->GetWindow()); } // Tests first monitor when display order doesn't match left to right screen @@ -1752,7 +1699,7 @@ // Coming from the left to right, we should select window1 first being on the // display to the left. SendKey(ui::VKEY_RIGHT); - EXPECT_EQ(GetSelectedWindow(), window1.get()); + EXPECT_EQ(GetHighlightedWindow(), window1.get()); // Exit and reenter overview. ToggleOverview(); @@ -1761,7 +1708,7 @@ // Coming from right to left, we should select window2 first being on the // display on the right. SendKey(ui::VKEY_LEFT); - EXPECT_EQ(GetSelectedWindow(), window2.get()); + EXPECT_EQ(GetHighlightedWindow(), window2.get()); } // Tests three monitors where the grid becomes empty on one of the monitors. @@ -1782,12 +1729,11 @@ SendKey(ui::VKEY_RIGHT); SendKey(ui::VKEY_RIGHT); SendKey(ui::VKEY_RIGHT); - EXPECT_EQ(GetSelectedWindow(), window3.get()); + EXPECT_EQ(window3.get(), GetHighlightedWindow()); - // If the last window on a display closes it should select the previous - // display's window. + // If the selected window is closed, then nothing should be selected. window3.reset(); - EXPECT_EQ(GetSelectedWindow(), window2.get()); + EXPECT_EQ(nullptr, GetHighlightedWindow()); ToggleOverview(); window3 = CreateTestWindow(gfx::Rect(800, 0, 100, 100)); @@ -1798,13 +1744,13 @@ // If the window on the second display is removed, the selected window should // remain window3. - EXPECT_EQ(GetSelectedWindow(), window3.get()); + EXPECT_EQ(window3.get(), GetHighlightedWindow()); window2.reset(); - EXPECT_EQ(GetSelectedWindow(), window3.get()); + EXPECT_EQ(window3.get(), GetHighlightedWindow()); } // Tests selecting a window in overview mode with the return key. -TEST_F(OverviewSessionTest, SelectWindowWithReturnKey) { +TEST_F(OverviewSessionTest, HighlightWindowWithReturnKey) { std::unique_ptr<aura::Window> window2(CreateTestWindow()); std::unique_ptr<aura::Window> window1(CreateTestWindow()); ToggleOverview(); @@ -1814,14 +1760,14 @@ EXPECT_TRUE(InOverviewSession()); // Select the first window. - ASSERT_TRUE(SelectWindow(window1.get())); + ASSERT_TRUE(HighlightWindow(window1.get())); SendKey(ui::VKEY_RETURN); ASSERT_FALSE(InOverviewSession()); EXPECT_TRUE(wm::IsActiveWindow(window1.get())); // Select the second window. ToggleOverview(); - ASSERT_TRUE(SelectWindow(window2.get())); + ASSERT_TRUE(HighlightWindow(window2.get())); SendKey(ui::VKEY_RETURN); EXPECT_FALSE(InOverviewSession()); EXPECT_TRUE(wm::IsActiveWindow(window2.get())); @@ -2007,7 +1953,7 @@ // Enter overview mode. Verify that the no windows indicator is not visible on // any display. ToggleOverview(); - auto& grids = overview_session()->grid_list_for_testing(); + auto& grids = overview_session()->grid_list(); ASSERT_TRUE(overview_session()); ASSERT_EQ(3u, grids.size()); EXPECT_FALSE(overview_session()->no_windows_widget_for_testing()); @@ -2823,7 +2769,7 @@ views::Widget* tall_widget = item_widget(tall_item); views::Widget* normal_widget = item_widget(normal_item); - OverviewGrid* grid = overview_session()->grid_list_for_testing()[0].get(); + OverviewGrid* grid = overview_session()->grid_list()[0].get(); // Verify all the shadows are within the bounds of their respective item // widgets when the overview windows are positioned without animations. @@ -2952,7 +2898,7 @@ // PIP window should be visible but not in the overview. EXPECT_TRUE(pip_window->IsVisible()); - EXPECT_FALSE(SelectWindow(pip_window.get())); + EXPECT_FALSE(HighlightWindow(pip_window.get())); } // Tests the PositionWindows function works as expected. @@ -3346,7 +3292,7 @@ ToggleOverview(); ASSERT_TRUE(overview_controller()->InOverviewSession()); - EXPECT_EQ(1u, overview_session()->grid_list_for_testing()[0]->size()); + EXPECT_EQ(1u, overview_session()->grid_list()[0]->size()); OverviewItem* item = GetWindowItemForWindow(0, widget->GetNativeWindow()); const gfx::PointF start = item->target_bounds().CenterPoint(); @@ -4188,7 +4134,7 @@ // edge of the screen. Shell::Get()->split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT); - OverviewGrid* grid = overview_session()->grid_list_for_testing()[0].get(); + OverviewGrid* grid = overview_session()->grid_list()[0].get(); ASSERT_TRUE(grid); // Drag the divider to the right edge. @@ -4213,7 +4159,7 @@ // edge of the screen. Shell::Get()->split_view_controller()->SnapWindow(window1.get(), SplitViewController::RIGHT); - grid = overview_session()->grid_list_for_testing()[0].get(); + grid = overview_session()->grid_list()[0].get(); ASSERT_TRUE(grid); // Drag the divider to the left edge. @@ -4429,40 +4375,6 @@ EXPECT_TRUE(InOverviewSession()); } -// Test that |OverviewGrid::selected_index_| is updated with the drop target for -// dragging a snapped window from the top. -TEST_F(SplitViewOverviewSessionTest, - SelectionUpdatedWithDropTargetForDraggingSnappedWindowFromTop) { - std::unique_ptr<aura::Window> window2(CreateTestWindow()); - window2->SetProperty(aura::client::kAppType, - static_cast<int>(AppType::BROWSER)); - ASSERT_TRUE(CanSnapInSplitview(window2.get())); - std::unique_ptr<aura::Window> window1(CreateTestWindow()); - ToggleOverview(); - split_view_controller()->SnapWindow(window2.get(), SplitViewController::LEFT); - EXPECT_TRUE(SelectWindow(window1.get())); - std::unique_ptr<WindowResizer> resizer = - CreateWindowResizer(window2.get(), gfx::Point(300, 0), HTCAPTION, - ::wm::WINDOW_MOVE_SOURCE_TOUCH); - ASSERT_TRUE(resizer); - TabletModeWindowDragDelegate* drag_delegate = - static_cast<TabletModeWindowDragController*>( - static_cast<DragWindowResizer*>(resizer.get()) - ->next_window_resizer_for_testing()) - ->drag_delegate_for_testing(); - drag_delegate->set_drag_start_deadline_for_testing(base::Time::Now()); - SplitViewDragIndicators* drag_indicators = - drag_delegate->split_view_drag_indicators_for_testing(); - EXPECT_EQ(IndicatorState::kNone, drag_indicators->current_indicator_state()); - EXPECT_EQ(window1.get(), GetSelectedWindow()); - resizer->Drag(gfx::Point(300, 400), ui::EF_NONE); - EXPECT_EQ(IndicatorState::kDragArea, - drag_indicators->current_indicator_state()); - EXPECT_TRUE(InOverviewSession()); - EXPECT_EQ(nullptr, GetSelectedWindow()); - resizer->CompleteDrag(); -} - // Test the split view and overview functionalities in clamshell mode. Split // view is only active when overview is active in clamshell mode. class SplitViewOverviewSessionInClamshellTest @@ -4777,9 +4689,7 @@ ToggleOverview(); // Drag |window1| selector item to snap to left. - const int grid_index = 0; - OverviewItem* overview_item1 = - GetWindowItemForWindow(grid_index, window1.get()); + OverviewItem* overview_item1 = GetWindowItemForWindow(0, window1.get()); DragWindowTo(overview_item1, gfx::PointF(0, 0)); EXPECT_TRUE(overview_controller()->InOverviewSession()); EXPECT_TRUE(split_view_controller()->InSplitViewMode()); @@ -4790,4 +4700,40 @@ EXPECT_FALSE(split_view_controller()->InSplitViewMode()); } +// Tests that the location of the overview highlight is as expected while +// dragging an overview item. +TEST_F(OverviewSessionTest, HighlightLocationWhileDragging) { + std::unique_ptr<aura::Window> window1(CreateTestWindow(gfx::Rect(200, 200))); + std::unique_ptr<aura::Window> window2(CreateTestWindow(gfx::Rect(200, 200))); + std::unique_ptr<aura::Window> window3(CreateTestWindow(gfx::Rect(200, 200))); + + ToggleOverview(); + + // Tab once to show the highlight. + SendKey(ui::VKEY_TAB); + EXPECT_EQ(window3.get(), GetHighlightedWindow()); + OverviewItem* item = GetWindowItemForWindow(0, window3.get()); + + // Tests that while dragging an item, tabbing does not change which item the + // highlight is hovered over. Drag the item in a way which does not enter + // splitview, or close overview. + const gfx::PointF start_point = item->target_bounds().CenterPoint(); + const gfx::PointF end_point(20.f, 20.f); + overview_session()->InitiateDrag(item, start_point, + /*allow_drag_to_close=*/true); + overview_session()->Drag(item, end_point); + SendKey(ui::VKEY_TAB); + EXPECT_EQ(window3.get(), GetHighlightedWindow()); + + // Tests that on releasing the item, the highlighted window remains the same. + overview_session()->Drag(item, start_point); + overview_session()->CompleteDrag(item, start_point); + EXPECT_EQ(window3.get(), GetHighlightedWindow()); + + // Tests that on tabbing after releasing, the highlighted window is the next + // one. + SendKey(ui::VKEY_TAB); + EXPECT_EQ(window2.get(), GetHighlightedWindow()); +} + } // namespace ash
diff --git a/ash/wm/overview/scoped_overview_animation_settings.cc b/ash/wm/overview/scoped_overview_animation_settings.cc index 15737d32..10ab3fe 100644 --- a/ash/wm/overview/scoped_overview_animation_settings.cc +++ b/ash/wm/overview/scoped_overview_animation_settings.cc
@@ -38,10 +38,9 @@ constexpr base::TimeDelta kHomeLauncherTransition = base::TimeDelta::FromMilliseconds(250); -// Time it takes for the selector widget to move to the next target. The same -// time is used for fading out shield widget when the overview mode is opened -// or closed. -constexpr base::TimeDelta kOverviewSelectorTransition = +// Time it takes for the overview highlight to move to the next target. The same +// time is used for fading the no recent items label. +constexpr base::TimeDelta kOverviewHighlightTransition = base::TimeDelta::FromMilliseconds(250); // Time duration of the show animation of the drop target. @@ -72,9 +71,8 @@ case OVERVIEW_ANIMATION_DROP_TARGET_FADE_IN: return kDropTargetFadeIn; case OVERVIEW_ANIMATION_NO_RECENTS_FADE: - case OVERVIEW_ANIMATION_SELECTION_WINDOW_SHADOW: case OVERVIEW_ANIMATION_SELECTION_WINDOW: - return kOverviewSelectorTransition; + return kOverviewHighlightTransition; } NOTREACHED(); return base::TimeDelta(); @@ -167,7 +165,6 @@ ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); break; case OVERVIEW_ANIMATION_NO_RECENTS_FADE: - case OVERVIEW_ANIMATION_SELECTION_WINDOW_SHADOW: animation_settings_->SetTweenType(gfx::Tween::EASE_IN_OUT); animation_settings_->SetPreemptionStrategy( ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
diff --git a/ash/wm/splitview/split_view_controller.cc b/ash/wm/splitview/split_view_controller.cc index 8410907..03595dd2 100644 --- a/ash/wm/splitview/split_view_controller.cc +++ b/ash/wm/splitview/split_view_controller.cc
@@ -955,6 +955,17 @@ return; } + // If the divider is animating, then |gained_active| cannot be snapped (and is + // not already snapped either, because then we would have bailed out by now). + // Then if |gained_active| is user-positionable, we should end split view + // mode, but the cannot snap toast would be inappropriate because the user + // still might be able to snap |gained_active|. + if (IsDividerAnimating()) { + if (wm::GetWindowState(gained_active)->IsUserPositionable()) + EndSplitView(EndReason::kUnsnappableWindowActivated); + return; + } + // If it's a user positionable window but can't be snapped, end split view // mode and show the cannot snap toast. if (!CanSnapInSplitview(gained_active)) {
diff --git a/ash/wm/splitview/split_view_controller.h b/ash/wm/splitview/split_view_controller.h index 4da02a07..67bb129 100644 --- a/ash/wm/splitview/split_view_controller.h +++ b/ash/wm/splitview/split_view_controller.h
@@ -11,10 +11,10 @@ #include "ash/ash_export.h" #include "ash/display/screen_orientation_controller.h" #include "ash/public/cpp/split_view.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/shell_observer.h" #include "ash/wm/overview/overview_observer.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "ash/wm/window_state_observer.h" #include "base/containers/flat_map.h" #include "base/macros.h"
diff --git a/ash/wm/splitview/split_view_controller_unittest.cc b/ash/wm/splitview/split_view_controller_unittest.cc index e97ff42..2923cb0 100644 --- a/ash/wm/splitview/split_view_controller_unittest.cc +++ b/ash/wm/splitview/split_view_controller_unittest.cc
@@ -2343,7 +2343,7 @@ Shell::Get()->overview_controller()->RemoveObserver(this); } void OnOverviewModeEnding(OverviewSession* overview_session) override { - items_on_last_overview_end_ = overview_session->num_items_for_testing(); + items_on_last_overview_end_ = overview_session->num_items(); } int items_on_last_overview_end() const { return items_on_last_overview_end_; } @@ -2359,16 +2359,12 @@ std::unique_ptr<aura::Window> window2(CreateWindow(bounds)); ToggleOverview(); - ASSERT_EQ(2u, Shell::Get() - ->overview_controller() - ->overview_session() - ->num_items_for_testing()); + ASSERT_EQ( + 2u, Shell::Get()->overview_controller()->overview_session()->num_items()); split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT); ASSERT_TRUE(Shell::Get()->overview_controller()->InOverviewSession()); - EXPECT_EQ(1u, Shell::Get() - ->overview_controller() - ->overview_session() - ->num_items_for_testing()); + EXPECT_EQ( + 1u, Shell::Get()->overview_controller()->overview_session()->num_items()); // Create |observer| after splitview is entered so that it gets notified after // splitview does, and so will notice the changes splitview made to overview
diff --git a/ash/wm/splitview/split_view_drag_indicators_unittest.cc b/ash/wm/splitview/split_view_drag_indicators_unittest.cc index c920e7e..8cd87db 100644 --- a/ash/wm/splitview/split_view_drag_indicators_unittest.cc +++ b/ash/wm/splitview/split_view_drag_indicators_unittest.cc
@@ -79,8 +79,7 @@ OverviewItem* GetOverviewItemForWindow(aura::Window* window, int grid_index = 0) { - auto& windows = - overview_session_->grid_list_for_testing()[grid_index]->window_list(); + auto& windows = overview_session_->grid_list()[grid_index]->window_list(); auto iter = std::find_if(windows.cbegin(), windows.cend(), [window](const std::unique_ptr<OverviewItem>& item) {
diff --git a/ash/wm/splitview/split_view_highlight_view_test_api.h b/ash/wm/splitview/split_view_highlight_view_test_api.h index 2c3e09c..29699a07 100644 --- a/ash/wm/splitview/split_view_highlight_view_test_api.h +++ b/ash/wm/splitview/split_view_highlight_view_test_api.h
@@ -33,4 +33,4 @@ } // namespace ash -#endif // ASH_WM_SPLITVIEW_SPLIT_VIEW_HIGHLIGHT_VIEW_TEST_API_H_ \ No newline at end of file +#endif // ASH_WM_SPLITVIEW_SPLIT_VIEW_HIGHLIGHT_VIEW_TEST_API_H_
diff --git a/ash/wm/tablet_mode/tablet_mode_controller.cc b/ash/wm/tablet_mode/tablet_mode_controller.cc index f5e33be..dea8fe5 100644 --- a/ash/wm/tablet_mode/tablet_mode_controller.cc +++ b/ash/wm/tablet_mode/tablet_mode_controller.cc
@@ -13,13 +13,12 @@ #include "ash/public/cpp/fps_counter.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/tablet_mode.h" -#include "ash/public/cpp/tablet_mode_toggle_observer.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/root_window_controller.h" #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/wm/overview/overview_controller.h" #include "ash/wm/tablet_mode/internal_input_devices_event_blocker.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "ash/wm/tablet_mode/tablet_mode_window_manager.h" #include "ash/wm/window_state.h" #include "base/bind.h" @@ -278,6 +277,11 @@ //////////////////////////////////////////////////////////////////////////////// // TabletModeContrller, public: +// static +void TabletModeController::SetUseScreenshotForTest(bool use_screenshot) { + use_screenshot_for_test = use_screenshot; +} + TabletModeController::TabletModeController() : event_blocker_(std::make_unique<InternalInputDevicesEventBlocker>()), tablet_mode_usage_interval_start_time_(base::Time::Now()), @@ -309,8 +313,13 @@ } TabletModeController::~TabletModeController() { + DCHECK(!tablet_mode_window_manager_); +} + +void TabletModeController::Shutdown() { if (tablet_mode_window_manager_) tablet_mode_window_manager_->Shutdown(); + tablet_mode_window_manager_.reset(); UMA_HISTOGRAM_COUNTS_1000("Tablet.AppWindowDrag.CountOfPerUserSession", app_window_drag_count_); @@ -336,24 +345,11 @@ observer.OnTabletControllerDestroyed(); } -// static -void TabletModeController::SetUseScreenshotForTest(bool use_screenshot) { - use_screenshot_for_test = use_screenshot; -} - void TabletModeController::AddWindow(aura::Window* window) { if (InTabletMode()) tablet_mode_window_manager_->AddWindow(window); } -void TabletModeController::AddObserver(TabletModeObserver* observer) { - tablet_mode_observers_.AddObserver(observer); -} - -void TabletModeController::RemoveObserver(TabletModeObserver* observer) { - tablet_mode_observers_.RemoveObserver(observer); -} - bool TabletModeController::ShouldAutoHideTitlebars(views::Widget* widget) { DCHECK(widget); const bool tablet_mode = InTabletMode(); @@ -415,11 +411,12 @@ DeleteScreenshot(); } -void TabletModeController::SetTabletModeToggleObserver( - TabletModeToggleObserver* observer) { - DCHECK(observer); - DCHECK(!toggle_observer_); - toggle_observer_ = observer; +void TabletModeController::AddObserver(TabletModeObserver* observer) { + tablet_mode_observers_.AddObserver(observer); +} + +void TabletModeController::RemoveObserver(TabletModeObserver* observer) { + tablet_mode_observers_.RemoveObserver(observer); } bool TabletModeController::InTabletMode() const { @@ -721,12 +718,9 @@ tablet_mode_window_manager_.reset(); base::RecordAction(base::UserMetricsAction("Touchview_Disabled")); RecordTabletModeUsageInterval(TABLET_MODE_INTERVAL_ACTIVE); + state_ = State::kInClamshellMode; for (auto& observer : tablet_mode_observers_) observer.OnTabletModeEnded(); - - state_ = State::kInClamshellMode; - if (toggle_observer_) // Null at startup and in tests. - toggle_observer_->OnTabletModeToggled(false); VLOG(1) << "Exit tablet mode."; UpdateInternalInputDevicesEventBlocker(); @@ -1010,6 +1004,8 @@ base::RecordAction(base::UserMetricsAction("Touchview_Enabled")); RecordTabletModeUsageInterval(TABLET_MODE_INTERVAL_INACTIVE); + state_ = State::kInTabletMode; + for (auto& observer : tablet_mode_observers_) observer.OnTabletModeStarted(); @@ -1024,10 +1020,6 @@ Shell::Get()->overview_controller()->StartOverview(); } - state_ = State::kInTabletMode; - if (toggle_observer_) // Null at startup and in tests. - toggle_observer_->OnTabletModeToggled(true); - UpdateInternalInputDevicesEventBlocker(); VLOG(1) << "Enter tablet mode.";
diff --git a/ash/wm/tablet_mode/tablet_mode_controller.h b/ash/wm/tablet_mode/tablet_mode_controller.h index 56cd9d3..4c25a3c1 100644 --- a/ash/wm/tablet_mode/tablet_mode_controller.h +++ b/ash/wm/tablet_mode/tablet_mode_controller.h
@@ -74,6 +74,10 @@ public KioskNextShellObserver, public ui::LayerAnimationObserver { public: + // Enable or disable using a screenshot for testing as it makes the + // initialization flow async, which makes most tests harder to write. + static void SetUseScreenshotForTest(bool use_screenshot); + // Used for keeping track if the user wants the machine to behave as a // clamshell/tablet regardless of hardware orientation. // TODO(oshima): Move this to common place. @@ -89,9 +93,7 @@ TabletModeController(); ~TabletModeController() override; - // Enable or disable using a screenshot for testing as it makes the - // initialization flow async, which makes most tests harder to write. - static void SetUseScreenshotForTest(bool use_screenshot); + void Shutdown(); // Add a special window to the TabletModeWindowManager for tracking. This is // only required for special windows which are handled by other window @@ -99,9 +101,6 @@ // If the tablet mode is not enabled no action will be performed. void AddWindow(aura::Window* window); - void AddObserver(TabletModeObserver* observer); - void RemoveObserver(TabletModeObserver* observer); - // Checks if we should auto hide title bars for the |widget| in tablet mode. bool ShouldAutoHideTitlebars(views::Widget* widget); @@ -120,7 +119,8 @@ void StopObservingAnimation(bool record_stats, bool delete_screenshot); // TabletMode: - void SetTabletModeToggleObserver(TabletModeToggleObserver* observer) override; + void AddObserver(TabletModeObserver* observer) override; + void RemoveObserver(TabletModeObserver* observer) override; bool InTabletMode() const override; void SetEnabledForTest(bool enabled) override; @@ -369,10 +369,6 @@ gfx::Vector3dF base_smoothed_; gfx::Vector3dF lid_smoothed_; - // A simplified observer that only gets notified of entering or exiting tablet - // mode. - TabletModeToggleObserver* toggle_observer_ = nullptr; - State state_ = State::kInClamshellMode; // Calls RecordLidAngle() periodically.
diff --git a/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc b/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc index 8933772f..a2845048 100644 --- a/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc +++ b/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc
@@ -2017,7 +2017,8 @@ // First test 1 window case. const wm::WMEvent left_snap_event(wm::WM_EVENT_SNAP_LEFT); wm::GetWindowState(window.get())->OnWMEvent(&left_snap_event); - const gfx::Rect left_snapped_bounds = gfx::Rect(1200 / 2, 800 - kShelfSize); + const gfx::Rect left_snapped_bounds = + gfx::Rect(1200 / 2, 800 - ShelfConstants::shelf_size()); EXPECT_EQ(window->bounds().width(), left_snapped_bounds.width()); // Change its bounds horizontally a bit and then enter tablet mode. window->SetBounds(gfx::Rect(400, left_snapped_bounds.height()));
diff --git a/ash/wm/window_util.cc b/ash/wm/window_util.cc index df16373..bb613e1 100644 --- a/ash/wm/window_util.cc +++ b/ash/wm/window_util.cc
@@ -9,6 +9,7 @@ #include "ash/public/cpp/app_types.h" #include "ash/public/cpp/ash_constants.h" #include "ash/public/cpp/shell_window_ids.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/public/cpp/window_properties.h" #include "ash/root_window_controller.h" #include "ash/scoped_animation_disabler.h" @@ -18,7 +19,6 @@ #include "ash/shell.h" #include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "ash/wm/window_positioning_utils.h" #include "ash/wm/window_state.h" #include "ash/wm/wm_event.h"
diff --git a/ash/wm/workspace/backdrop_controller.h b/ash/wm/workspace/backdrop_controller.h index 14155f18..55934106f 100644 --- a/ash/wm/workspace/backdrop_controller.h +++ b/ash/wm/workspace/backdrop_controller.h
@@ -10,10 +10,10 @@ #include "ash/accessibility/accessibility_observer.h" #include "ash/ash_export.h" #include "ash/public/cpp/split_view.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/public/cpp/wallpaper_controller_observer.h" #include "ash/shell_observer.h" #include "ash/wm/overview/overview_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "base/macros.h" #include "ui/gfx/geometry/rect.h"
diff --git a/base/BUILD.gn b/base/BUILD.gn index 044c081..063a042 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -622,6 +622,7 @@ "profiler/native_unwinder_mac.h", "profiler/native_unwinder_win.cc", "profiler/native_unwinder_win.h", + "profiler/profile_builder.cc", "profiler/profile_builder.h", "profiler/register_context.h", "profiler/sample_metadata.cc",
diff --git a/base/android/java/src/org/chromium/base/library_loader/LegacyLinker.java b/base/android/java/src/org/chromium/base/library_loader/LegacyLinker.java index 34e68634..642cac2 100644 --- a/base/android/java/src/org/chromium/base/library_loader/LegacyLinker.java +++ b/base/android/java/src/org/chromium/base/library_loader/LegacyLinker.java
@@ -11,7 +11,6 @@ import org.chromium.base.ContextUtils; import org.chromium.base.Log; -import org.chromium.base.SysUtils; import org.chromium.base.annotations.JniIgnoreNatives; import java.util.HashMap; @@ -48,10 +47,6 @@ // finishLibraryLoad(). private boolean mWaitForSharedRelros; - // Becomes true when initialization determines that the browser process can use the - // shared RELRO. - private boolean mBrowserUsesSharedRelro; - // The map of all RELRO sections either created or used in this process. private Bundle mSharedRelros; @@ -79,50 +74,10 @@ // constructor because instantiation occurs on the UI thread. loadLinkerJniLibrary(); - if (mMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT) { - if (SysUtils.isLowEndDevice()) { - mMemoryDeviceConfig = MEMORY_DEVICE_CONFIG_LOW; - } else { - mMemoryDeviceConfig = MEMORY_DEVICE_CONFIG_NORMAL; - } - } - - // Cannot run in the constructor because SysUtils.isLowEndDevice() relies - // on CommandLine, which may not be available at instantiation. - switch (BROWSER_SHARED_RELRO_CONFIG) { - case BROWSER_SHARED_RELRO_CONFIG_NEVER: - break; - case BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY: - if (mMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW) { - mBrowserUsesSharedRelro = true; - Log.w(TAG, "Low-memory device: shared RELROs used in all processes"); - } - break; - case BROWSER_SHARED_RELRO_CONFIG_ALWAYS: - Log.w(TAG, "Beware: shared RELROs used in all processes!"); - mBrowserUsesSharedRelro = true; - break; - default: - Log.wtf(TAG, "FATAL: illegal shared RELRO config"); - throw new AssertionError(); - } - mInitialized = true; } /** - * Call this method to determine if the linker will try to use shared RELROs - * for the browser process. - */ - @Override - public boolean isUsingBrowserSharedRelros() { - synchronized (sLock) { - ensureInitializedLocked(); - return mInBrowserProcess && mBrowserUsesSharedRelro; - } - } - - /** * Call this method just before loading any native shared libraries in this process. */ @Override @@ -154,9 +109,9 @@ synchronized (sLock) { ensureInitializedLocked(); if (DEBUG) { - String message = String.format(Locale.US, - "mInBrowserProcess=%b mBrowserUsesSharedRelro=%b mWaitForSharedRelros=%b", - mInBrowserProcess, mBrowserUsesSharedRelro, mWaitForSharedRelros); + String message = + String.format(Locale.US, "mInBrowserProcess=%b mWaitForSharedRelros=%b", + mInBrowserProcess, mWaitForSharedRelros); Log.i(TAG, message); } @@ -172,9 +127,7 @@ dumpBundle(mSharedRelros); } - if (mBrowserUsesSharedRelro) { - useSharedRelrosLocked(mSharedRelros); - } + useSharedRelrosLocked(mSharedRelros); } if (mWaitForSharedRelros) { @@ -198,7 +151,7 @@ // If testing, run tests now that all libraries are loaded and initialized. if (NativeLibraries.sEnableLinkerTests) { - runTestRunnerClassForTesting(mMemoryDeviceConfig, mInBrowserProcess); + runTestRunnerClassForTesting(mInBrowserProcess); } } if (DEBUG) Log.i(TAG, "finishLibraryLoad() exiting"); @@ -271,7 +224,6 @@ ensureInitializedLocked(); mInBrowserProcess = false; mWaitForSharedRelros = false; - mBrowserUsesSharedRelro = false; } } @@ -291,7 +243,6 @@ synchronized (sLock) { ensureInitializedLocked(); mInBrowserProcess = false; - mBrowserUsesSharedRelro = false; mWaitForSharedRelros = true; mBaseLoadAddress = baseLoadAddress; mCurrentLoadAddress = baseLoadAddress; @@ -335,7 +286,6 @@ // If the random address is 0 there are issues with finding enough // free address space, so disable RELRO shared / fixed load addresses. Log.w(TAG, "Disabling shared RELROs due address space pressure"); - mBrowserUsesSharedRelro = false; mWaitForSharedRelros = false; } } @@ -447,7 +397,7 @@ LibInfo libInfo = new LibInfo(); long loadAddress = 0; if (isFixedAddressPermitted) { - if ((mInBrowserProcess && mBrowserUsesSharedRelro) || mWaitForSharedRelros) { + if (mInBrowserProcess || mWaitForSharedRelros) { // Load the library at a fixed address. loadAddress = mCurrentLoadAddress;
diff --git a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java index 9e5f0b8..11b1a194 100644 --- a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java +++ b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java
@@ -13,7 +13,6 @@ import android.os.Build.VERSION_CODES; import android.os.SystemClock; import android.support.annotation.NonNull; -import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.system.Os; @@ -113,15 +112,6 @@ // native. private boolean mCommandLineSwitched; - // One-way switches recording attempts to use Relro sharing in the browser. - // The flags are used to report UMA stats later. - private boolean mIsUsingBrowserSharedRelros; - private boolean mLoadAtFixedAddressFailed; - - // One-way switch becomes true if the Chromium library was loaded from the - // APK file directly. - private boolean mLibraryWasLoadedFromApk; - // The type of process the shared library is loaded in. private @LibraryProcessType int mLibraryProcessType; @@ -140,6 +130,20 @@ * libraries instead. */ public static boolean useCrazyLinker() { + // A non-monochrome APK (such as ChromePublic.apk) can be installed on N+ in these + // circumstances: + // * installing APK manually + // * after OTA from M to N + // * side-installing Chrome (possibly from another release channel) + // * Play Store bugs leading to incorrect APK flavor being installed + // * installing other Chromium-based browsers + // + // For Chrome builds regularly shipped to users on N+, the system linker (or the Android + // Framework) provides the necessary functionality to load without crazylinker. The + // crazylinker is risky to auto-enable on newer Android releases, as it may interfere with + // regular library loading. See http://crbug.com/980304 as example. + if (Build.VERSION.SDK_INT >= VERSION_CODES.N) return false; + // The auto-generated NativeLibraries.sUseLinker variable will be true if the // build has not explicitly disabled Linker features. return NativeLibraries.sUseLinker; @@ -318,28 +322,14 @@ // Helper for loadAlreadyLocked(). Load a native shared library with the Chromium linker. // Sets UMA flags depending on the results of loading. - private void loadLibraryWithCustomLinkerAlreadyLocked( - Linker linker, @Nullable String zipFilePath, String libFilePath) { + private void loadLibraryWithCustomLinkerAlreadyLocked(Linker linker, String libFilePath) { assert Thread.holdsLock(mLock); - if (linker.isUsingBrowserSharedRelros()) { - // If the browser is set to attempt shared RELROs then we try first with shared - // RELROs enabled, and if that fails then retry without. - mIsUsingBrowserSharedRelros = true; - try { - linker.loadLibrary(libFilePath); - } catch (UnsatisfiedLinkError e) { - Log.w(TAG, "Failed to load native library with shared RELRO, retrying without"); - mLoadAtFixedAddressFailed = true; - linker.loadLibraryNoFixedAddress(libFilePath); - } - } else { - // No attempt to use shared RELROs in the browser, so load as normal. + // Attempt shared RELROs, and if that fails then retry without. + try { linker.loadLibrary(libFilePath); - } - - // Loaded successfully, so record if we loaded directly from an APK. - if (zipFilePath != null) { - mLibraryWasLoadedFromApk = true; + } catch (UnsatisfiedLinkError e) { + Log.w(TAG, "Failed to load native library with shared RELRO, retrying without"); + linker.loadLibraryNoFixedAddress(libFilePath); } } @@ -400,14 +390,13 @@ try { // Load the library using this Linker. May throw UnsatisfiedLinkError. - loadLibraryWithCustomLinkerAlreadyLocked( - linker, apkFilePath, libFilePath); + loadLibraryWithCustomLinkerAlreadyLocked(linker, libFilePath); incrementRelinkerCountNotHitHistogram(); } catch (UnsatisfiedLinkError e) { if (!isInZipFile() && PLATFORM_REQUIRES_NATIVE_FALLBACK_EXTRACTION) { loadLibraryWithCustomLinkerAlreadyLocked( - linker, null, getExtractedLibraryPath(appInfo, library)); + linker, getExtractedLibraryPath(appInfo, library)); incrementRelinkerCountHitHistogram(); } else { Log.e(TAG, "Unable to load library: " + library);
diff --git a/base/android/java/src/org/chromium/base/library_loader/Linker.java b/base/android/java/src/org/chromium/base/library_loader/Linker.java index bef217f..af2b5600 100644 --- a/base/android/java/src/org/chromium/base/library_loader/Linker.java +++ b/base/android/java/src/org/chromium/base/library_loader/Linker.java
@@ -152,36 +152,6 @@ // Name of the library that contains our JNI code. protected static final String LINKER_JNI_LIBRARY = "chromium_android_linker"; - // Constants used to control the behaviour of the browser process with - // regards to the shared RELRO section. - // NEVER -> The browser never uses it itself. - // LOW_RAM_ONLY -> It is only used on devices with low RAM. - // ALWAYS -> It is always used. - // NOTE: These names are known and expected by the Linker test scripts. - public static final int BROWSER_SHARED_RELRO_CONFIG_NEVER = 0; - public static final int BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY = 1; - public static final int BROWSER_SHARED_RELRO_CONFIG_ALWAYS = 2; - - // Configuration variable used to control how the browser process uses the - // shared RELRO. Only change this while debugging linker-related issues. - // NOTE: This variable's name is known and expected by the Linker test scripts. - public static final int BROWSER_SHARED_RELRO_CONFIG = - BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY; - - // Constants used to control the memory device config. Can be set explicitly - // by setMemoryDeviceConfigForTesting(). - // INIT -> Value is undetermined (will check at runtime). - // LOW -> This is a low-memory device. - // NORMAL -> This is not a low-memory device. - public static final int MEMORY_DEVICE_CONFIG_INIT = 0; - public static final int MEMORY_DEVICE_CONFIG_LOW = 1; - public static final int MEMORY_DEVICE_CONFIG_NORMAL = 2; - - // Indicates if this is a low-memory device or not. The default is to - // determine this by probing the system at runtime, but this can be forced - // for testing by calling setMemoryDeviceConfigForTesting(). - protected int mMemoryDeviceConfig = MEMORY_DEVICE_CONFIG_INIT; - // Set to true to enable debug logs. protected static final boolean DEBUG = false; @@ -261,11 +231,10 @@ /** * Run runtime checks and return true if they all pass. * - * @param memoryDeviceConfig The current memory device configuration. * @param inBrowserProcess true iff this is the browser process. * @return true if all checks pass. */ - public boolean runChecks(int memoryDeviceConfig, boolean inBrowserProcess); + public boolean runChecks(boolean inBrowserProcess); } /** @@ -309,11 +278,9 @@ * must be instantiated _after_ all libraries are loaded to ensure that its * native methods are properly registered. * - * @param memoryDeviceConfig LegacyLinker memory config, or 0 if unused * @param inBrowserProcess true if in the browser process */ - protected final void runTestRunnerClassForTesting( - int memoryDeviceConfig, boolean inBrowserProcess) { + protected final void runTestRunnerClassForTesting(boolean inBrowserProcess) { if (DEBUG) { Log.i(TAG, "runTestRunnerClassForTesting called"); } @@ -338,7 +305,7 @@ assert false; } - if (!testRunner.runChecks(memoryDeviceConfig, inBrowserProcess)) { + if (!testRunner.runChecks(inBrowserProcess)) { Log.wtf(TAG, "Linker runtime tests failed in this process"); assert false; } @@ -348,35 +315,6 @@ } /** - * Call this method before any other Linker method to force a specific - * memory device configuration. Should only be used for testing. - * - * @param memoryDeviceConfig MEMORY_DEVICE_CONFIG_LOW or MEMORY_DEVICE_CONFIG_NORMAL. - */ - public final void setMemoryDeviceConfigForTesting(int memoryDeviceConfig) { - if (DEBUG) { - Log.i(TAG, "setMemoryDeviceConfigForTesting(" + memoryDeviceConfig + ") called"); - } - // Sanity check. This method may only be called during tests. - assertLinkerTestsAreEnabled(); - assert memoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW - || memoryDeviceConfig == MEMORY_DEVICE_CONFIG_NORMAL; - - synchronized (sLock) { - assert mMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT; - - mMemoryDeviceConfig = memoryDeviceConfig; - if (DEBUG) { - if (mMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW) { - Log.i(TAG, "Simulating a low-memory device"); - } else { - Log.i(TAG, "Simulating a regular-memory device"); - } - } - } - } - - /** * Determine whether a library is the linker library. * * @param library the name of the library. @@ -446,15 +384,9 @@ } /** - * Call this method to determine if the linker will try to use shared RELROs - * for the browser process. - */ - public abstract boolean isUsingBrowserSharedRelros(); - - /** * Call this method just before loading any native shared libraries in this process. * - * @param zipFilePath Optional current APK file path. If provided, the linker + * @param apkFilePath Optional current APK file path. If provided, the linker * will try to load libraries directly from it. */ abstract void prepareLibraryLoad(@Nullable String apkFilePath);
diff --git a/base/profiler/metadata_recorder.cc b/base/profiler/metadata_recorder.cc index baca29a..b0f5ea0 100644 --- a/base/profiler/metadata_recorder.cc +++ b/base/profiler/metadata_recorder.cc
@@ -21,20 +21,33 @@ void MetadataRecorder::Set(uint64_t name_hash, int64_t value) { base::AutoLock lock(write_lock_); - // Acquiring the |write_lock_| guarantees that two simultaneous writes don't - // attempt to create items in the same slot. Use of memory_order_release - // guarantees that all writes performed by other threads to the metadata items - // will be seen by the time we reach this point. + // Acquiring the |write_lock_| ensures that: + // + // - We don't try to write into the same new slot at the same time as + // another thread + // - We see all writes by other threads (acquiring a mutex implies acquire + // semantics) size_t item_slots_used = item_slots_used_.load(std::memory_order_relaxed); for (size_t i = 0; i < item_slots_used; ++i) { auto& item = items_[i]; if (item.name_hash == name_hash) { item.value.store(value, std::memory_order_relaxed); - item.is_active.store(true, std::memory_order_release); + + const bool was_active = + item.is_active.exchange(true, std::memory_order_release); + if (!was_active) + inactive_item_count_--; + return; } } + item_slots_used = TryReclaimInactiveSlots(item_slots_used); + + // TODO(charliea): Add an UMA histogram to track the number of occupied + // metadata slots. + // See: https://crbug.com/980308 + // There should always be room in this data structure because there are more // reserved slots than there are unique metadata names in Chromium. DCHECK_NE(item_slots_used, items_.size()) @@ -44,7 +57,7 @@ // Wait until the item is fully created before setting |is_active| to true and // incrementing |item_slots_used_|, which will signal to readers that the item // is ready. - auto& item = items_[item_slots_used_]; + auto& item = items_[item_slots_used]; item.name_hash = name_hash; item.value.store(value, std::memory_order_relaxed); item.is_active.store(true, std::memory_order_release); @@ -58,16 +71,42 @@ for (size_t i = 0; i < item_slots_used; ++i) { auto& item = items_[i]; if (item.name_hash == name_hash) { - // A removed item will occupy its slot indefinitely. - item.is_active.store(false, std::memory_order_release); + // A removed item will occupy its slot until that slot is reclaimed. + const bool was_active = + item.is_active.exchange(false, std::memory_order_relaxed); + if (was_active) + inactive_item_count_++; + + return; } } } -size_t MetadataRecorder::GetItems(ItemArray* const items) const { - // TODO(charliea): Defragment the item array if we can successfully acquire - // the write lock here. This will require either making this function - // non-const or |items_| mutable. +MetadataRecorder::ScopedGetItems::ScopedGetItems( + MetadataRecorder* metadata_recorder) + : metadata_recorder_(metadata_recorder), + auto_lock_(&metadata_recorder->read_lock_) {} + +MetadataRecorder::ScopedGetItems::~ScopedGetItems() {} + +// This function is marked as NO_THREAD_SAFETY_ANALYSIS because the analyzer +// doesn't understand that the lock is acquired in the constructor initializer +// list and can therefore be safely released here. +size_t MetadataRecorder::ScopedGetItems::GetItems( + ProfileBuilder::MetadataItemArray* const items) NO_THREAD_SAFETY_ANALYSIS { + size_t item_count = metadata_recorder_->GetItems(items); + auto_lock_.Release(); + return item_count; +} + +std::unique_ptr<ProfileBuilder::MetadataProvider> +MetadataRecorder::CreateMetadataProvider() { + return std::make_unique<MetadataRecorder::ScopedGetItems>(this); +} + +size_t MetadataRecorder::GetItems( + ProfileBuilder::MetadataItemArray* const items) const { + read_lock_.AssertAcquired(); // If a writer adds a new item after this load, it will be ignored. We do // this instead of calling item_slots_used_.load() explicitly in the for loop @@ -87,12 +126,75 @@ // Because we wait until |is_active| is set to consider an item active and // that field is always set last, we ignore half-created items. if (item.is_active.load(std::memory_order_acquire)) { - (*items)[write_index++] = - Item{item.name_hash, item.value.load(std::memory_order_relaxed)}; + (*items)[write_index++] = ProfileBuilder::MetadataItem{ + item.name_hash, item.value.load(std::memory_order_relaxed)}; } } return write_index; } +size_t MetadataRecorder::TryReclaimInactiveSlots(size_t item_slots_used) { + const size_t remaining_slots = + ProfileBuilder::MAX_METADATA_COUNT - item_slots_used; + + if (inactive_item_count_ == 0 || inactive_item_count_ < remaining_slots) { + // This reclaiming threshold has a few nice properties: + // + // - It avoids reclaiming when no items have been removed + // - It makes doing so more likely as free slots become more scarce + // - It makes doing so less likely when the benefits are lower + return item_slots_used; + } + + if (read_lock_.Try()) { + // The lock isn't already held by a reader or another thread reclaiming + // slots. + item_slots_used = ReclaimInactiveSlots(item_slots_used); + read_lock_.Release(); + } + + return item_slots_used; +} + +size_t MetadataRecorder::ReclaimInactiveSlots(size_t item_slots_used) { + // From here until the end of the reclamation, we can safely use + // memory_order_relaxed for all reads and writes. We don't need + // memory_order_acquire because acquiring the write mutex gives acquire + // semantics and no other threads can write after we hold that mutex. We don't + // need memory_order_release because no readers can read until we release the + // read mutex, which itself has release semantics. + size_t first_inactive_item_idx = 0; + size_t last_active_item_idx = item_slots_used - 1; + while (first_inactive_item_idx < last_active_item_idx) { + ItemInternal& inactive_item = items_[first_inactive_item_idx]; + ItemInternal& active_item = items_[last_active_item_idx]; + + if (inactive_item.is_active.load(std::memory_order_relaxed)) { + // Keep seeking forward to an inactive item. + ++first_inactive_item_idx; + continue; + } + + if (!active_item.is_active.load(std::memory_order_relaxed)) { + // Keep seeking backward to an active item. Skipping over this item + // indicates that we're freeing the slot at this index. + --last_active_item_idx; + item_slots_used--; + continue; + } + + inactive_item.name_hash = active_item.name_hash; + inactive_item.value.store(active_item.value.load(std::memory_order_relaxed), + std::memory_order_relaxed); + inactive_item.is_active.store(true, std::memory_order_relaxed); + + ++first_inactive_item_idx; + --last_active_item_idx; + item_slots_used--; + } + + item_slots_used_.store(item_slots_used, std::memory_order_relaxed); + return item_slots_used; +} } // namespace base
diff --git a/base/profiler/metadata_recorder.h b/base/profiler/metadata_recorder.h index 346a5a1..faec7c27 100644 --- a/base/profiler/metadata_recorder.h +++ b/base/profiler/metadata_recorder.h
@@ -9,7 +9,9 @@ #include <atomic> #include <utility> +#include "base/profiler/profile_builder.h" #include "base/synchronization/lock.h" +#include "base/thread_annotations.h" namespace base { @@ -19,6 +21,105 @@ // with the sample. // // Methods on this class are safe to call unsynchronized from arbitrary threads. +// +// This class was designed to read metadata from a single sampling thread and +// write metadata from many Chrome threads within the same process. These other +// threads might be suspended by the sampling thread at any time in order to +// collect a sample. +// +// This class has a few notable constraints: +// +// A) If a lock that's required to read the metadata might be held while writing +// the metadata, that lock must be acquirable *before* the thread is +// suspended. Otherwise, the sampling thread might suspend the target thread +// while it is holding the required lock, causing deadlock. +// +// Ramifications: +// +// - When retrieving items, lock acquisition (through +// CreateMetadataProvider()) and actual item retrieval (through +// MetadataProvider::GetItems()) are separate. +// +// B) We can't allocate data on the heap while reading the metadata items. This +// is because, on many operating systems, there's a process-wide heap lock +// that is held while allocating on the heap. If a thread is suspended while +// holding this lock and the sampling thread then tries to allocate on the +// heap to read the metadata, it will deadlock trying to acquire the heap +// lock. +// +// Ramifications: +// +// - We hold and retrieve the metadata using a fixed-size array, which +// allows readers to preallocate the data structure that we pass back +// the metadata in. +// +// C) We shouldn't guard writes with a lock that also guards reads. It can take +// ~30us from the time that the sampling thread requests that a thread be +// suspended and the time that it actually happens. If all metadata writes +// block their thread during that time, we're very likely to block all Chrome +// threads for an additional 30us per sample. +// +// Ramifications: +// +// - We use two locks to guard the metadata: a read lock and a write +// lock. Only the write lock is required to write into the metadata, and +// only the read lock is required to read the metadata. +// +// - Because we can't guard reads and writes with the same lock, we have to +// face the possibility of writes occurring during a read. This is +// especially problematic because there's no way to read both the key and +// value for an item atomically without using mutexes, which violates +// constraint A). If the sampling thread were to see the following +// interleaving of reads and writes: +// +// * Reader thread reads key for slot 0 +// * Writer thread removes item at slot 0 +// * Writer thread creates new item with different key in slot 0 +// * Reader thread reads value for slot 0 +// +// then the reader would see an invalid value for the given key. Because +// of this possibility, we keep slots reserved for a specific key even +// after that item has been removed. We reclaim these slots on a +// best-effort basis during writes when the metadata recorder has become +// sufficiently full and we can acquire the read lock. +// +// - We use state stored in atomic data types to ensure that readers and +// writers are synchronized about where data should be written to and +// read from. We must use atomic data types to guarantee that there's no +// instruction during a write after which the recorder is in an +// inconsistent state that might yield garbage data for a reader. +// +// Here are a few of the many states the recorder can be in: +// +// - No thread is using the recorder. +// +// - A single writer is writing into the recorder without a simultaneous +// read. The write will succeed. +// +// - A reader is reading from the recorder without a simultaneous write. The +// read will succeed. +// +// - Multiple writers attempt to write into the recorder simultaneously. All +// writers but one will block because only one can hold the write lock. +// +// - A writer is writing into the recorder, which hasn't reached the threshold +// at which it will try to reclaim inactive slots. The writer won't try to +// acquire the read lock to reclaim inactive slots. The reader will therefore +// be able to immediately acquire the read lock, suspend the target thread, +// and read the metadata. +// +// - A writer is writing into the recorder, the recorder has reached the +// threshold at which it needs to reclaim inactive slots, and the writer +// thread is now in the middle of reclaiming those slots when a reader +// arrives. The reader will try to acquire the read lock before suspending the +// thread but will block until the writer thread finishes reclamation and +// releases the read lock. The reader will then be able to acquire the read +// lock and suspend the target thread. +// +// - A reader is reading the recorder when a writer attempts to write. The write +// will be successful. However, if the writer deems it necessary to reclaim +// inactive slots, it will skip doing so because it won't be able to acquire +// the read lock. class BASE_EXPORT MetadataRecorder { public: MetadataRecorder(); @@ -35,22 +136,62 @@ // If such an item does not exist, this has no effect. void Remove(uint64_t name_hash); - struct Item { - // The hash of the metadata name, as produced by base::HashMetricName(). - uint64_t name_hash; - // The value of the metadata item. - int64_t value; - }; - - static const size_t MAX_METADATA_COUNT = 50; - typedef std::array<Item, MAX_METADATA_COUNT> ItemArray; - // Retrieves the first |available_slots| items in the metadata recorder and - // copies them into |items|, returning the number of metadata items that were - // copied. To ensure that all items can be copied, |available slots| should be - // greater than or equal to |MAX_METADATA_COUNT|. - size_t GetItems(ItemArray* const items) const; + // Creates a MetadataProvider object for the recorder, which acquires the + // necessary exclusive read lock and provides access to the recorder's items + // via its GetItems() function. Reclaiming of inactive slots in the recorder + // can't occur while this object lives, so it should be created as soon before + // it's needed as possible. Calling GetItems() releases the lock held by the + // object and can therefore only be called once during the object's lifetime. + // + // This object should be created *before* suspending the target + // thread. Otherwise, that thread might be suspended while reclaiming inactive + // slots and holding the read lock, which would cause the sampling thread to + // deadlock. + // + // Example usage: + // + // MetadataRecorder r; + // base::ProfileBuilder::MetadataItemArray arr; + // size_t item_count; + // ... + // { + // auto get_items = r.CreateMetadataProvider(); + // item_count = get_items.GetItems(arr); + // } + std::unique_ptr<ProfileBuilder::MetadataProvider> CreateMetadataProvider(); private: + // An object that provides access to a MetadataRecorder's items and holds the + // necessary exclusive read lock until either GetItems() is called or the + // object is destroyed. + // + // For usage and more details, see CreateMetadataProvider(). + class SCOPED_LOCKABLE ScopedGetItems + : public ProfileBuilder::MetadataProvider { + public: + // Acquires an exclusive read lock on the metadata recorder which is held + // until either GetItems() is called or the object is destroyed. + ScopedGetItems(MetadataRecorder* metadata_recorder) + EXCLUSIVE_LOCK_FUNCTION(metadata_recorder->read_lock_); + ~ScopedGetItems() override UNLOCK_FUNCTION(metadata_recorder_->read_lock_); + ScopedGetItems(const ScopedGetItems&) = delete; + ScopedGetItems& operator=(const ScopedGetItems&) = delete; + + // Retrieves the first |available_slots| items in the metadata recorder and + // copies them into |items|, returning the number of metadata items that + // were copied. To ensure that all items can be copied, |available slots| + // should be greater than or equal to |MAX_METADATA_COUNT|. + // + // This function releases the lock held by the object and can therefore only + // be called once during the object's lifetime. + size_t GetItems(ProfileBuilder::MetadataItemArray* const items) override + EXCLUSIVE_LOCKS_REQUIRED(metadata_recorder_->read_lock_); + + private: + const MetadataRecorder* const metadata_recorder_; + base::ReleasableAutoLock auto_lock_; + }; + // TODO(charliea): Support large quantities of metadata efficiently. struct ItemInternal { ItemInternal(); @@ -77,6 +218,24 @@ std::atomic<int64_t> value; }; + // Attempts to free slots in the metadata map that are currently allocated to + // inactive items. May fail silently if the read lock is already held, in + // which case no slots will be freed. Returns the number of item slots used + // after the reclamation. + size_t TryReclaimInactiveSlots(size_t item_slots_used) + EXCLUSIVE_LOCKS_REQUIRED(write_lock_) LOCKS_EXCLUDED(read_lock_); + // Also protected by read_lock_, but current thread annotation limitations + // prevent us from using thread annotations with locks acquired through + // Lock::Try(). Updates item_slots_used_ to reflect the new item count and + // returns the number of item slots used after the reclamation. + size_t ReclaimInactiveSlots(size_t item_slots_used) + EXCLUSIVE_LOCKS_REQUIRED(write_lock_); + + // Protected by read_lock_, but current thread annotation limitations + // prevent us from using thread annotations with locks acquired through + // Lock::Try(). + size_t GetItems(ProfileBuilder::MetadataItemArray* const items) const; + // Metadata items that the recorder has seen. Rather than implementing the // metadata recorder as a dense array, we implement it as a sparse array where // removed metadata items keep their slot with their |is_active| bit set to @@ -85,7 +244,7 @@ // // For the rationale behind this design (along with others considered), see // https://docs.google.com/document/d/18shLhVwuFbLl_jKZxCmOfRB98FmNHdKl0yZZZ3aEO4U/edit#. - std::array<ItemInternal, MAX_METADATA_COUNT> items_; + std::array<ItemInternal, ProfileBuilder::MAX_METADATA_COUNT> items_; // The number of item slots used in the metadata map. // @@ -95,9 +254,21 @@ // of its existence. std::atomic<size_t> item_slots_used_{0}; - // A lock that guards against multiple threads trying to modify the same item - // at once. + // The number of item slots occupied by inactive items. + size_t inactive_item_count_ GUARDED_BY(write_lock_) = 0; + + // A lock that guards against multiple threads trying to manipulate items_, + // item_slots_used_, or inactive_item_count_ at the same time. base::Lock write_lock_; + + // A lock that guards against a reader trying to read items_ while inactive + // slots are being reclaimed. + // + // Note that we can't enforce that this lock is properly acquired through + // thread annotations because thread annotations doesn't understand that + // ScopedGetItems::GetItems() can only be called between ScopedGetItems's + // constructor and destructor. + base::Lock read_lock_; }; } // namespace base
diff --git a/base/profiler/metadata_recorder_unittest.cc b/base/profiler/metadata_recorder_unittest.cc index 8155687..7228ec9 100644 --- a/base/profiler/metadata_recorder_unittest.cc +++ b/base/profiler/metadata_recorder_unittest.cc
@@ -10,15 +10,21 @@ namespace base { -bool operator==(const MetadataRecorder::Item& lhs, - const MetadataRecorder::Item& rhs) { +bool operator==(const base::ProfileBuilder::MetadataItem& lhs, + const base::ProfileBuilder::MetadataItem& rhs) { return lhs.name_hash == rhs.name_hash && lhs.value == rhs.value; } +bool operator<(const base::ProfileBuilder::MetadataItem& lhs, + const base::ProfileBuilder::MetadataItem& rhs) { + return lhs.name_hash < rhs.name_hash; +} + TEST(MetadataRecorderTest, GetItems_Empty) { MetadataRecorder recorder; - MetadataRecorder::ItemArray items; - size_t item_count = recorder.GetItems(&items); + base::ProfileBuilder::MetadataItemArray items; + + size_t item_count = recorder.CreateMetadataProvider()->GetItems(&items); ASSERT_EQ(0u, item_count); } @@ -28,18 +34,23 @@ recorder.Set(10, 20); - MetadataRecorder::ItemArray items; - size_t item_count = recorder.GetItems(&items); - ASSERT_EQ(1u, item_count); - ASSERT_EQ(10u, items[0].name_hash); - ASSERT_EQ(20, items[0].value); + base::ProfileBuilder::MetadataItemArray items; + size_t item_count; + { + item_count = recorder.CreateMetadataProvider()->GetItems(&items); + ASSERT_EQ(1u, item_count); + ASSERT_EQ(10u, items[0].name_hash); + ASSERT_EQ(20, items[0].value); + } recorder.Set(20, 30); - item_count = recorder.GetItems(&items); - ASSERT_EQ(2u, item_count); - ASSERT_EQ(20u, items[1].name_hash); - ASSERT_EQ(30, items[1].value); + { + item_count = recorder.CreateMetadataProvider()->GetItems(&items); + ASSERT_EQ(2u, item_count); + ASSERT_EQ(20u, items[1].name_hash); + ASSERT_EQ(30, items[1].value); + } } TEST(MetadataRecorderTest, Set_ExistingNameNash) { @@ -47,8 +58,8 @@ recorder.Set(10, 20); recorder.Set(10, 30); - MetadataRecorder::ItemArray items; - size_t item_count = recorder.GetItems(&items); + base::ProfileBuilder::MetadataItemArray items; + size_t item_count = recorder.CreateMetadataProvider()->GetItems(&items); ASSERT_EQ(1u, item_count); ASSERT_EQ(10u, items[0].name_hash); ASSERT_EQ(30, items[0].value); @@ -56,10 +67,10 @@ TEST(MetadataRecorderTest, Set_ReAddRemovedNameNash) { MetadataRecorder recorder; - MetadataRecorder::ItemArray items; - std::vector<MetadataRecorder::Item> expected; + base::ProfileBuilder::MetadataItemArray items; + std::vector<base::ProfileBuilder::MetadataItem> expected; for (size_t i = 0; i < items.size(); ++i) { - expected.push_back(MetadataRecorder::Item{i, 0}); + expected.push_back(base::ProfileBuilder::MetadataItem{i, 0}); recorder.Set(i, 0); } @@ -70,14 +81,14 @@ recorder.Remove(3); recorder.Set(3, 0); - size_t item_count = recorder.GetItems(&items); + size_t item_count = recorder.CreateMetadataProvider()->GetItems(&items); EXPECT_EQ(items.size(), item_count); - ASSERT_THAT(expected, ::testing::ElementsAreArray(items)); + ASSERT_THAT(expected, ::testing::UnorderedElementsAreArray(items)); } TEST(MetadataRecorderTest, Set_AddPastMaxCount) { MetadataRecorder recorder; - MetadataRecorder::ItemArray items; + base::ProfileBuilder::MetadataItemArray items; for (size_t i = 0; i < items.size(); ++i) { recorder.Set(i, 0); } @@ -92,8 +103,8 @@ recorder.Set(50, 60); recorder.Remove(30); - MetadataRecorder::ItemArray items; - size_t item_count = recorder.GetItems(&items); + base::ProfileBuilder::MetadataItemArray items; + size_t item_count = recorder.CreateMetadataProvider()->GetItems(&items); ASSERT_EQ(2u, item_count); ASSERT_EQ(10u, items[0].name_hash); ASSERT_EQ(20, items[0].value); @@ -106,11 +117,45 @@ recorder.Set(10, 20); recorder.Remove(20); - MetadataRecorder::ItemArray items; - size_t item_count = recorder.GetItems(&items); + base::ProfileBuilder::MetadataItemArray items; + size_t item_count = recorder.CreateMetadataProvider()->GetItems(&items); ASSERT_EQ(1u, item_count); ASSERT_EQ(10u, items[0].name_hash); ASSERT_EQ(20, items[0].value); } +TEST(MetadataRecorderTest, ReclaimInactiveSlots) { + MetadataRecorder recorder; + + std::set<base::ProfileBuilder::MetadataItem> items_set; + // Fill up the metadata map. + for (size_t i = 0; i < base::ProfileBuilder::MAX_METADATA_COUNT; ++i) { + recorder.Set(i, i); + items_set.insert(base::ProfileBuilder::MetadataItem{i, i}); + } + + // Remove every fourth entry to fragment the data. + size_t entries_removed = 0; + for (size_t i = 3; i < base::ProfileBuilder::MAX_METADATA_COUNT; i += 4) { + recorder.Remove(i); + ++entries_removed; + items_set.erase(base::ProfileBuilder::MetadataItem{i, i}); + } + + // Ensure that the inactive slots are reclaimed to make room for more entries. + for (size_t i = 1; i <= entries_removed; ++i) { + recorder.Set(i * 100, i * 100); + items_set.insert(base::ProfileBuilder::MetadataItem{i * 100, i * 100}); + } + + base::ProfileBuilder::MetadataItemArray items_arr; + std::copy(items_set.begin(), items_set.end(), items_arr.begin()); + + base::ProfileBuilder::MetadataItemArray recorder_items; + size_t recorder_item_count = + recorder.CreateMetadataProvider()->GetItems(&recorder_items); + ASSERT_EQ(recorder_item_count, base::ProfileBuilder::MAX_METADATA_COUNT); + ASSERT_THAT(recorder_items, ::testing::UnorderedElementsAreArray(items_arr)); +} + } // namespace base
diff --git a/base/profiler/profile_builder.cc b/base/profiler/profile_builder.cc new file mode 100644 index 0000000..ca3db2a --- /dev/null +++ b/base/profiler/profile_builder.cc
@@ -0,0 +1,7 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/profiler/profile_builder.h" + +const size_t base::ProfileBuilder::MAX_METADATA_COUNT;
diff --git a/base/profiler/profile_builder.h b/base/profiler/profile_builder.h index 0202c21..49355ef 100644 --- a/base/profiler/profile_builder.h +++ b/base/profiler/profile_builder.h
@@ -26,13 +26,31 @@ // up modules from addresses. virtual ModuleCache* GetModuleCache() = 0; + struct MetadataItem { + // The hash of the metadata name, as produced by base::HashMetricName(). + uint64_t name_hash; + // The value of the metadata item. + int64_t value; + }; + + static constexpr size_t MAX_METADATA_COUNT = 50; + typedef std::array<MetadataItem, MAX_METADATA_COUNT> MetadataItemArray; + + class MetadataProvider { + public: + MetadataProvider() = default; + virtual ~MetadataProvider() = default; + + virtual size_t GetItems(ProfileBuilder::MetadataItemArray* const items) = 0; + }; + // Records metadata to be associated with the current sample. To avoid // deadlock on locks taken by the suspended profiled thread, implementations // of this method must not execute any code that could take a lock, including // heap allocation or use of CHECK/DCHECK/LOG statements. Generally // implementations should simply atomically copy metadata state to be // associated with the sample. - virtual void RecordMetadata() {} + virtual void RecordMetadata(MetadataProvider* metadata_provider) {} // Records a new set of frames. Invoked when sampling a sample completes. virtual void OnSampleCompleted(std::vector<Frame> frames) = 0;
diff --git a/base/profiler/sample_metadata_unittest.cc b/base/profiler/sample_metadata_unittest.cc index 27e177b..e38052f 100644 --- a/base/profiler/sample_metadata_unittest.cc +++ b/base/profiler/sample_metadata_unittest.cc
@@ -10,19 +10,29 @@ namespace base { TEST(SampleMetadataTest, ScopedSampleMetadata) { - MetadataRecorder::ItemArray items; - - ASSERT_EQ(0u, GetSampleMetadataRecorder()->GetItems(&items)); + base::ProfileBuilder::MetadataItemArray items; + { + auto get_items = GetSampleMetadataRecorder()->CreateMetadataProvider(); + ASSERT_EQ(0u, get_items->GetItems(&items)); + } { ScopedSampleMetadata m("myname", 100); - ASSERT_EQ(1u, GetSampleMetadataRecorder()->GetItems(&items)); - EXPECT_EQ(base::HashMetricName("myname"), items[0].name_hash); - EXPECT_EQ(100, items[0].value); + { + ASSERT_EQ(1u, + GetSampleMetadataRecorder()->CreateMetadataProvider()->GetItems( + &items)); + EXPECT_EQ(base::HashMetricName("myname"), items[0].name_hash); + EXPECT_EQ(100, items[0].value); + } } - ASSERT_EQ(0u, GetSampleMetadataRecorder()->GetItems(&items)); + { + ASSERT_EQ(0u, + GetSampleMetadataRecorder()->CreateMetadataProvider()->GetItems( + &items)); + } } } // namespace base
diff --git a/base/profiler/stack_sampler_impl.cc b/base/profiler/stack_sampler_impl.cc index 2c70cc8..6993664 100644 --- a/base/profiler/stack_sampler_impl.cc +++ b/base/profiler/stack_sampler_impl.cc
@@ -8,6 +8,7 @@ #include "base/logging.h" #include "base/profiler/profile_builder.h" +#include "base/profiler/sample_metadata.h" #include "base/profiler/thread_delegate.h" #include "base/profiler/unwinder.h" @@ -79,6 +80,12 @@ uintptr_t bottom = 0; const uint8_t* stack_copy_bottom = nullptr; { + // The MetadataProvider must be created before the ScopedSuspendThread + // because it acquires a lock in its constructor that might otherwise be + // held by the target thread, resulting in deadlock. + std::unique_ptr<base::ProfileBuilder::MetadataProvider> get_metadata_items = + base::GetSampleMetadataRecorder()->CreateMetadataProvider(); + // Allocation of the ScopedSuspendThread object itself is OK since it // necessarily occurs before the thread is suspended by the object. std::unique_ptr<ThreadDelegate::ScopedSuspendThread> suspend_thread = @@ -102,7 +109,7 @@ if (!thread_delegate_->CanCopyStack(bottom)) return false; - profile_builder->RecordMetadata(); + profile_builder->RecordMetadata(get_metadata_items.get()); stack_copy_bottom = CopyStackContentsAndRewritePointers( reinterpret_cast<uint8_t*>(bottom), reinterpret_cast<uintptr_t*>(top),
diff --git a/base/profiler/stack_sampler_impl_unittest.cc b/base/profiler/stack_sampler_impl_unittest.cc index 9884e59c..f86d433 100644 --- a/base/profiler/stack_sampler_impl_unittest.cc +++ b/base/profiler/stack_sampler_impl_unittest.cc
@@ -33,7 +33,8 @@ // ProfileBuilder ModuleCache* GetModuleCache() override { return module_cache_; } - void RecordMetadata() override {} + void RecordMetadata( + base::ProfileBuilder::MetadataProvider* metadata_provider) override {} void OnSampleCompleted(std::vector<Frame> frames) override {} void OnProfileCompleted(TimeDelta profile_duration, TimeDelta sampling_period) override {} @@ -60,8 +61,7 @@ // The register context will be initialized to // *|thread_context| if non-null. RegisterContext* thread_context = nullptr) - : fake_stack_(fake_stack), - thread_context_(thread_context) {} + : fake_stack_(fake_stack), thread_context_(thread_context) {} TestThreadDelegate(const TestThreadDelegate&) = delete; TestThreadDelegate& operator=(const TestThreadDelegate&) = delete;
diff --git a/base/profiler/stack_sampling_profiler_test_util.cc b/base/profiler/stack_sampling_profiler_test_util.cc index e560e0c..b96bbeb 100644 --- a/base/profiler/stack_sampling_profiler_test_util.cc +++ b/base/profiler/stack_sampling_profiler_test_util.cc
@@ -35,7 +35,7 @@ // ProfileBuilder: ModuleCache* GetModuleCache() override { return module_cache_; } - void RecordMetadata() override {} + void RecordMetadata(MetadataProvider* metadata_provider) override {} void OnSampleCompleted(std::vector<Frame> sample) override { EXPECT_TRUE(sample_.empty());
diff --git a/base/profiler/stack_sampling_profiler_unittest.cc b/base/profiler/stack_sampling_profiler_unittest.cc index c52fcc2d..d3035b93 100644 --- a/base/profiler/stack_sampling_profiler_unittest.cc +++ b/base/profiler/stack_sampling_profiler_unittest.cc
@@ -172,7 +172,8 @@ // ProfileBuilder: ModuleCache* GetModuleCache() override; - void RecordMetadata() override; + void RecordMetadata( + base::ProfileBuilder::MetadataProvider* metadata_provider) override; void OnSampleCompleted(std::vector<Frame> sample) override; void OnProfileCompleted(TimeDelta profile_duration, TimeDelta sampling_period) override; @@ -202,7 +203,8 @@ return module_cache_; } -void TestProfileBuilder::RecordMetadata() { +void TestProfileBuilder::RecordMetadata( + base::ProfileBuilder::MetadataProvider* metadata_provider) { ++metadata_count_; }
diff --git a/base/task/sequence_manager/time_domain.h b/base/task/sequence_manager/time_domain.h index 152ebed..cf4ca66 100644 --- a/base/task/sequence_manager/time_domain.h +++ b/base/task/sequence_manager/time_domain.h
@@ -47,10 +47,10 @@ // TODO(alexclarke): Make this main thread only. virtual TimeTicks Now() const = 0; - // Computes the delay until the time when TimeDomain needs to wake up - // some TaskQueue. Specific time domains (e.g. virtual or throttled) may - // return TimeDelata() if TaskQueues have any delayed tasks they deem - // eligible to run. It's also allowed to advance time domains's internal + // Computes the delay until the time when TimeDomain needs to wake up some + // TaskQueue on the main thread. Specific time domains (e.g. virtual or + // throttled) may return TimeDelta() if TaskQueues have any delayed tasks they + // deem eligible to run. It's also allowed to advance time domains's internal // clock when this method is called. // Can be called from main thread only. // NOTE: |lazy_now| and the return value are in the SequenceManager's time.
diff --git a/base/task/thread_pool/delayed_task_manager.cc b/base/task/thread_pool/delayed_task_manager.cc index 58d7f9f3..a2e92a2 100644 --- a/base/task/thread_pool/delayed_task_manager.cc +++ b/base/task/thread_pool/delayed_task_manager.cc
@@ -117,6 +117,13 @@ } } +Optional<TimeTicks> DelayedTaskManager::NextScheduledRunTime() const { + CheckedAutoLock auto_lock(queue_lock_); + if (delayed_task_queue_.empty()) + return nullopt; + return delayed_task_queue_.Min().task.delayed_run_time; +} + TimeTicks DelayedTaskManager::GetTimeToScheduleProcessRipeTasksLockRequired() { queue_lock_.AssertAcquired(); if (delayed_task_queue_.empty())
diff --git a/base/task/thread_pool/delayed_task_manager.h b/base/task/thread_pool/delayed_task_manager.h index 37b32554..f829068 100644 --- a/base/task/thread_pool/delayed_task_manager.h +++ b/base/task/thread_pool/delayed_task_manager.h
@@ -13,6 +13,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" +#include "base/optional.h" #include "base/synchronization/atomic_flag.h" #include "base/task/common/checked_lock.h" #include "base/task/common/intrusive_heap.h" @@ -49,6 +50,12 @@ PostTaskNowCallback post_task_now_callback, scoped_refptr<TaskRunner> task_runner); + // Pop and post all the ripe tasks in the delayed task queue. + void ProcessRipeTasks(); + + // Returns the |delayed_run_time| of the next scheduled task, if any. + Optional<TimeTicks> NextScheduledRunTime() const; + private: struct DelayedTask { DelayedTask(); @@ -86,9 +93,6 @@ DISALLOW_COPY_AND_ASSIGN(DelayedTask); }; - // Pop and post all the ripe tasks in the delayed task queue. - void ProcessRipeTasks(); - // Get the time at which to schedule the next |ProcessRipeTasks()| execution, // or TimeTicks::Max() if none needs to be scheduled (i.e. no task, or next // task already scheduled). @@ -108,7 +112,7 @@ // it is never modified. It is therefore safe to access // |service_thread_task_runner_| without synchronization once it is observed // that it is non-null. - CheckedLock queue_lock_; + mutable CheckedLock queue_lock_; scoped_refptr<TaskRunner> service_thread_task_runner_;
diff --git a/base/task/thread_pool/task_tracker.h b/base/task/thread_pool/task_tracker.h index 2b393dc..1ab341e 100644 --- a/base/task/thread_pool/task_tracker.h +++ b/base/task/thread_pool/task_tracker.h
@@ -160,6 +160,11 @@ return tracked_ref_factory_.GetTrackedRef(); } + // Returns true if there are task sources that haven't completed their + // execution (still queued or in progress). If it returns false: the side- + // effects of all completed tasks are guaranteed to be visible to the caller. + bool HasIncompleteTaskSourcesForTesting() const; + protected: // Runs and deletes |task| if |can_run_task| is true. Otherwise, just deletes // |task|. |task| is always deleted in the environment where it runs or would @@ -172,11 +177,6 @@ const TaskTraits& traits, bool can_run_task); - // Returns true if there are task sources that haven't completed their - // execution (still queued or in progress). If it returns false: the side- - // effects of all completed tasks are guaranteed to be visible to the caller. - bool HasIncompleteTaskSourcesForTesting() const; - private: friend class RegisteredTaskSource; class State;
diff --git a/base/task/thread_pool/thread_pool_impl.cc b/base/task/thread_pool/thread_pool_impl.cc index 0101854..189c86d 100644 --- a/base/task/thread_pool/thread_pool_impl.cc +++ b/base/task/thread_pool/thread_pool_impl.cc
@@ -64,11 +64,13 @@ ThreadPoolImpl::ThreadPoolImpl(StringPiece histogram_label) : ThreadPoolImpl(histogram_label, - std::make_unique<TaskTrackerImpl>(histogram_label)) {} + std::make_unique<TaskTrackerImpl>(histogram_label), + DefaultTickClock::GetInstance()) {} ThreadPoolImpl::ThreadPoolImpl(StringPiece histogram_label, - std::unique_ptr<TaskTrackerImpl> task_tracker) - : thread_pool_clock_(DefaultTickClock::GetInstance()), + std::unique_ptr<TaskTrackerImpl> task_tracker, + const TickClock* tick_clock) + : thread_pool_clock_(tick_clock), task_tracker_(std::move(task_tracker)), service_thread_(std::make_unique<ServiceThread>( task_tracker_.get(), @@ -265,6 +267,16 @@ return MakeRefCounted<PooledSequencedTaskRunner>(new_traits, this); } +Optional<TimeTicks> ThreadPoolImpl::NextScheduledRunTimeForTesting() const { + if (task_tracker_->HasIncompleteTaskSourcesForTesting()) + return ThreadPoolClock::Now(); + return delayed_task_manager_.NextScheduledRunTime(); +} + +void ThreadPoolImpl::ProcessRipeDelayedTasksForTesting() { + delayed_task_manager_.ProcessRipeTasks(); +} + int ThreadPoolImpl::GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( const TaskTraits& traits) const { // This method does not support getting the maximum number of BEST_EFFORT
diff --git a/base/task/thread_pool/thread_pool_impl.h b/base/task/thread_pool/thread_pool_impl.h index b623775..09a7a45c 100644 --- a/base/task/thread_pool/thread_pool_impl.h +++ b/base/task/thread_pool/thread_pool_impl.h
@@ -14,6 +14,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" +#include "base/optional.h" #include "base/sequence_checker.h" #include "base/strings/string_piece.h" #include "base/synchronization/atomic_flag.h" @@ -64,9 +65,11 @@ //|histogram_label| is used to label histograms, it must not be empty. explicit ThreadPoolImpl(StringPiece histogram_label); - // For testing only. Creates a ThreadPoolImpl with a custom TaskTracker. + // For testing only. Creates a ThreadPoolImpl with a custom TaskTracker and + // TickClock. ThreadPoolImpl(StringPiece histogram_label, - std::unique_ptr<TaskTrackerImpl> task_tracker); + std::unique_ptr<TaskTrackerImpl> task_tracker, + const TickClock* tick_clock); ~ThreadPoolImpl() override; @@ -101,6 +104,16 @@ scoped_refptr<UpdateableSequencedTaskRunner> CreateUpdateableSequencedTaskRunner(const TaskTraits& traits); + // Returns the TimeTicks of the next task scheduled on ThreadPool (Now() if + // immediate, nullopt if none). This is thread-safe, i.e., it's safe if tasks + // are being posted in parallel with this call but such a situation obviously + // results in a race as to whether this call will see the new tasks in time. + Optional<TimeTicks> NextScheduledRunTimeForTesting() const; + + // Forces ripe delayed tasks to be posted (e.g. when time is mocked and + // advances faster than the real-time delay on ServiceThread). + void ProcessRipeDelayedTasksForTesting(); + private: // Invoked after |has_fence_| or |has_best_effort_fence_| is updated. Sets the // CanRunPolicy in TaskTracker and wakes up workers as appropriate.
diff --git a/base/test/scoped_task_environment.cc b/base/test/scoped_task_environment.cc index b15eafc..fba6ca89 100644 --- a/base/test/scoped_task_environment.cc +++ b/base/test/scoped_task_environment.cc
@@ -19,6 +19,7 @@ #include "base/task/sequence_manager/sequence_manager_impl.h" #include "base/task/sequence_manager/time_domain.h" #include "base/task/thread_pool/thread_pool.h" +#include "base/task/thread_pool/thread_pool_clock.h" #include "base/task/thread_pool/thread_pool_impl.h" #include "base/test/bind_test_util.h" #include "base/test/test_mock_time_task_runner.h" @@ -29,6 +30,7 @@ #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/clock.h" +#include "base/time/default_tick_clock.h" #include "base/time/tick_clock.h" #include "base/time/time.h" #include "base/time/time_override.h" @@ -112,6 +114,9 @@ // thread, waiting for it to complete results in a deadlock...). bool DisallowRunTasks(); + // Returns true if tasks are currently allowed to run. + bool TasksAllowedToRun() const; + private: friend class ScopedTaskEnvironment; @@ -122,7 +127,7 @@ bool can_run_task) override; // Synchronizes accesses to members below. - Lock lock_; + mutable Lock lock_; // True if running tasks is allowed. bool can_run_tasks_ GUARDED_BY(lock_) = true; @@ -143,15 +148,10 @@ : public sequence_manager::TimeDomain, public TickClock { public: - MockTimeDomain(ScopedTaskEnvironment::NowSource now_source, - sequence_manager::SequenceManager* sequence_manager) + explicit MockTimeDomain(sequence_manager::SequenceManager* sequence_manager) : sequence_manager_(sequence_manager) { DCHECK_EQ(nullptr, current_mock_time_domain_); current_mock_time_domain_ = this; - if (now_source == ScopedTaskEnvironment::NowSource::MAIN_THREAD_MOCK_TIME) { - time_overrides_ = std::make_unique<subtle::ScopedTimeClockOverrides>( - &MockTimeDomain::GetTime, &MockTimeDomain::GetTimeTicks, nullptr); - } } ~MockTimeDomain() override { @@ -177,19 +177,20 @@ } static std::unique_ptr<ScopedTaskEnvironment::MockTimeDomain> - CreateAndRegister(ScopedTaskEnvironment::MainThreadType main_thread_type, - ScopedTaskEnvironment::NowSource now_source, - sequence_manager::SequenceManager* sequence_manager) { - if (main_thread_type == MainThreadType::MOCK_TIME || - main_thread_type == MainThreadType::UI_MOCK_TIME || - main_thread_type == MainThreadType::IO_MOCK_TIME) { - auto mock_time_donain = - std::make_unique<ScopedTaskEnvironment::MockTimeDomain>( - now_source, sequence_manager); - sequence_manager->RegisterTimeDomain(mock_time_donain.get()); - return mock_time_donain; - } - return nullptr; + CreateAndRegister(sequence_manager::SequenceManager* sequence_manager) { + auto mock_time_domain = + std::make_unique<ScopedTaskEnvironment::MockTimeDomain>( + sequence_manager); + sequence_manager->RegisterTimeDomain(mock_time_domain.get()); + return mock_time_domain; + } + + void SetThreadPool(internal::ThreadPoolImpl* thread_pool, + const TestTaskTracker* thread_pool_task_tracker) { + DCHECK(!thread_pool_); + DCHECK(!thread_pool_task_tracker_); + thread_pool_ = thread_pool; + thread_pool_task_tracker_ = thread_pool_task_tracker; } // sequence_manager::TimeDomain: @@ -239,7 +240,8 @@ if (!auto_advance_on_idle_) return false; - return FastForwardToNextTaskOrCap(TimeTicks::Max()); + return FastForwardToNextTaskOrCap(TimeTicks::Max()) == + NextTaskSource::kMainThread; } const char* GetName() const override { return "MockTimeDomain"; } @@ -247,20 +249,73 @@ // TickClock implementation: TimeTicks NowTicks() const override { return Now(); } - // Advances time to the next task or to |fast_forward_cap| (if it's not - // Max()). Returns true if there's additional immediate work as a result - // of this call. - bool FastForwardToNextTaskOrCap(TimeTicks fast_forward_cap) { + // Used by FastForwardToNextTaskOrCap() to return which task source time was + // advanced to. + enum class NextTaskSource { + // Out of tasks under |fast_forward_cap|. + kNone, + // There's now >=1 immediate task on the main thread. + kMainThread, + // There's now >=1 immediate task in the thread pool. + kThreadPool, + }; + + // Advances time to the first of : next main thread task, next thread pool + // task, or |fast_forward_cap| (if it's not Max()). + NextTaskSource FastForwardToNextTaskOrCap(TimeTicks fast_forward_cap) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // We don't need to call ReclaimMemory here because // DelayTillNextTask will have dealt with cancelled delayed tasks for us. - Optional<TimeTicks> next_task_time = NextScheduledRunTime(); + Optional<TimeTicks> next_main_thread_task_time = NextScheduledRunTime(); + + // Consider the next thread pool tasks iff they're running. + Optional<TimeTicks> next_thread_pool_task_time; + if (thread_pool_ && thread_pool_task_tracker_->TasksAllowedToRun()) { + next_thread_pool_task_time = + thread_pool_->NextScheduledRunTimeForTesting(); + } + + // Custom comparison logic to consider nullopt the largest rather than + // smallest value. Could consider using TimeTicks::Max() instead of nullopt + // to represent out-of-tasks? + Optional<TimeTicks> next_task_time; + if (!next_main_thread_task_time) { + next_task_time = next_thread_pool_task_time; + } else if (!next_thread_pool_task_time) { + next_task_time = next_main_thread_task_time; + } else { + next_task_time = + std::min(*next_main_thread_task_time, *next_thread_pool_task_time); + } if (next_task_time && *next_task_time <= fast_forward_cap) { - AutoLock lock(now_ticks_lock_); - now_ticks_ = *next_task_time; - return true; + { + AutoLock lock(now_ticks_lock_); + // It's possible for |next_task_time| to be in the past in the following + // scenario: + // Start with Now() == 100ms + // Thread A : Post 200ms delayed task T (construct and enqueue) + // Thread B : Construct 20ms delayed task U + // => |delayed_run_time| == 120ms. + // Thread A : FastForwardToNextTaskOrCap() => fast-forwards to T @ + // 300ms (task U is not yet in queue). + // Thread B : Complete enqueue of task U. + // Thread A : FastForwardToNextTaskOrCap() => must stay at 300ms and run + // U, not go back to 120ms. + // Hence we need std::max() to protect again this because construction + // and enqueuing isn't atomic in time (LazyNow support in + // base/task/thread_pool could help). + now_ticks_ = std::max(now_ticks_, *next_task_time); + } + + if (next_task_time == next_thread_pool_task_time) { + // Let the thread pool know that it should post its now ripe delayed + // tasks. + thread_pool_->ProcessRipeDelayedTasksForTesting(); + return NextTaskSource::kThreadPool; + } + return NextTaskSource::kMainThread; } if (!fast_forward_cap.is_max()) { @@ -270,11 +325,15 @@ now_ticks_ = std::max(now_ticks_, fast_forward_cap); } - return false; + return NextTaskSource::kNone; } - void set_auto_advance_on_idle(bool auto_advance_on_idle) { + // Sets |auto_advance_on_idle_| to |auto_advance_on_idle| and returns its + // previous value. + bool SetAutoAdvanceOnIdle(bool auto_advance_on_idle) { + const auto previous = auto_advance_on_idle_; auto_advance_on_idle_ = auto_advance_on_idle; + return previous; } private: @@ -287,7 +346,8 @@ sequence_manager::SequenceManager* const sequence_manager_; - std::unique_ptr<subtle::ScopedTimeClockOverrides> time_overrides_; + internal::ThreadPoolImpl* thread_pool_ = nullptr; + const TestTaskTracker* thread_pool_task_tracker_ = nullptr; // Protects |now_ticks_| mutable Lock now_ticks_lock_; @@ -302,9 +362,9 @@ ScopedTaskEnvironment::MockTimeDomain::current_mock_time_domain_ = nullptr; ScopedTaskEnvironment::ScopedTaskEnvironment( + TimeSource time_source, MainThreadType main_thread_type, ThreadPoolExecutionMode thread_pool_execution_mode, - NowSource now_source, ThreadingMode threading_mode, bool subclass_creates_default_taskrunner, trait_helpers::NotATraitTag) @@ -315,9 +375,15 @@ sequence_manager_( CreateSequenceManagerForMainThreadType(main_thread_type)), mock_time_domain_( - MockTimeDomain::CreateAndRegister(main_thread_type, - now_source, - sequence_manager_.get())), + time_source != TimeSource::SYSTEM_TIME + ? MockTimeDomain::CreateAndRegister(sequence_manager_.get()) + : nullptr), + time_overrides_(time_source == TimeSource::MOCK_TIME_AND_NOW + ? std::make_unique<subtle::ScopedTimeClockOverrides>( + &MockTimeDomain::GetTime, + &MockTimeDomain::GetTimeTicks, + nullptr) + : nullptr), mock_clock_(mock_time_domain_ ? std::make_unique<TickClockBasedClock>( mock_time_domain_.get()) : nullptr), @@ -333,9 +399,6 @@ TestTimeouts::action_max_timeout(), MakeExpectedNotRunClosure(FROM_HERE, "RunLoop::Run() timed out."))) { - CHECK(now_source == NowSource::REAL_TIME || mock_time_domain_) - << "NowSource must be REAL_TIME unless we're using mock time"; - CHECK(!base::ThreadTaskRunnerHandle::IsSet()); // If |subclass_creates_default_taskrunner| is true then initialization is // deferred until DeferredInitFromSubclass(). @@ -391,8 +454,14 @@ auto task_tracker = std::make_unique<TestTaskTracker>(); task_tracker_ = task_tracker.get(); - ThreadPoolInstance::Set(std::make_unique<internal::ThreadPoolImpl>( - "ScopedTaskEnvironment", std::move(task_tracker))); + const TickClock* tick_clock = + mock_time_domain_ ? static_cast<TickClock*>(mock_time_domain_.get()) + : DefaultTickClock::GetInstance(); + auto thread_pool = std::make_unique<internal::ThreadPoolImpl>( + "ScopedTaskEnvironment", std::move(task_tracker), tick_clock); + if (mock_time_domain_) + mock_time_domain_->SetThreadPool(thread_pool.get(), task_tracker_); + ThreadPoolInstance::Set(std::move(thread_pool)); ThreadPoolInstance::Get()->Start(init_params); } @@ -571,14 +640,21 @@ void ScopedTaskEnvironment::FastForwardBy(TimeDelta delta) { DCHECK(mock_time_domain_); - mock_time_domain_->set_auto_advance_on_idle(false); + DCHECK_GE(delta, TimeDelta()); + + const bool was_auto_advancing = mock_time_domain_->SetAutoAdvanceOnIdle(false); + const bool could_run_tasks = task_tracker_->AllowRunTasks(); const TimeTicks fast_forward_until = mock_time_domain_->NowTicks() + delta; do { RunUntilIdle(); - } while (mock_time_domain_->FastForwardToNextTaskOrCap(fast_forward_until)); + } while (mock_time_domain_->FastForwardToNextTaskOrCap(fast_forward_until) != + MockTimeDomain::NextTaskSource::kNone); - mock_time_domain_->set_auto_advance_on_idle(true); + if (was_auto_advancing) + mock_time_domain_->SetAutoAdvanceOnIdle(true); + if (!could_run_tasks) + task_tracker_->DisallowRunTasks(); } void ScopedTaskEnvironment::FastForwardUntilNoTasksRemain() { @@ -640,6 +716,11 @@ return could_run_tasks; } +bool ScopedTaskEnvironment::TestTaskTracker::TasksAllowedToRun() const { + AutoLock auto_lock(lock_); + return can_run_tasks_; +} + bool ScopedTaskEnvironment::TestTaskTracker::DisallowRunTasks() { AutoLock auto_lock(lock_);
diff --git a/base/test/scoped_task_environment.h b/base/test/scoped_task_environment.h index cc205a90..ef0cb38 100644 --- a/base/test/scoped_task_environment.h +++ b/base/test/scoped_task_environment.h
@@ -24,6 +24,10 @@ class FileDescriptorWatcher; class TickClock; +namespace subtle { +class ScopedTimeClockOverrides; +} + namespace test { // ScopedTaskEnvironment allows usage of these APIs within its scope: @@ -73,28 +77,51 @@ struct SubclassCreatesDefaultTaskRunner {}; public: + enum class TimeSource { + // Delayed tasks and Time/TimeTicks::Now() use the real-time system clock. + SYSTEM_TIME, + + // Delayed tasks use a mock clock which only advances (in increments to the + // soonest delay) when reaching idle during a FastForward*() call to this + // ScopedTaskEnvironment. Or when RunLoop::Run() goes idle on the main + // thread with no tasks remaining in the thread pool. + // Note: this does not affect threads outside this ScopedTaskEnvironment's + // purview (notably: independent base::Thread's). + MOCK_TIME, + + // Mock Time/TimeTicks::Now() with the same mock clock used for delayed + // tasks. This is useful when a delayed task under test needs to check the + // amount of time that has passed since a previous sample of Now() (e.g. + // cache expiry). + // + // Warning some platform APIs are still real-time, and don't interact with + // MOCK_TIME as expected, e.g.: + // PlatformThread::Sleep + // WaitableEvent::TimedWait + // WaitableEvent::TimedWaitUntil + // ConditionVariable::TimedWait + // + // TODO(crbug.com/905412): Make MOCK_TIME always mock Time/TimeTicks::Now(). + MOCK_TIME_AND_NOW, + + // TODO(gab): Consider making MOCK_TIME the default mode. + DEFAULT = SYSTEM_TIME + }; + enum class MainThreadType { // The main thread doesn't pump system messages. DEFAULT, - // The main thread doesn't pump system messages and uses a mock clock for - // delayed tasks (controllable via FastForward*() methods). - // TODO(gab): Make this the default |main_thread_type|. - // TODO(gab): Also mock the ThreadPoolInstance's clock simultaneously (this - // currently only mocks the main thread's clock). - MOCK_TIME, // The main thread pumps UI messages. UI, - // The main thread pumps UI messages and uses a mock clock for delayed tasks - // (controllable via FastForward*() methods). - // TODO(gab@): Enable mock time on all threads and make MOCK_TIME - // configurable independent of MainThreadType. - UI_MOCK_TIME, // The main thread pumps asynchronous IO messages and supports the // FileDescriptorWatcher API on POSIX. IO, - // The main thread pumps IO messages and uses a mock clock for delayed tasks - // (controllable via FastForward*() methods). In addition it supports the - // FileDescriptorWatcher API on POSIX. + + // TODO(gab): Migrate users of these APIs. + // Deprecated: Use TimeSource::MOCK_TIME instead. + MOCK_TIME, + // Deprecated:: Use MainThreadType::UI/IO + TimeSource::MOCK_TIME instead. + UI_MOCK_TIME, IO_MOCK_TIME, }; @@ -112,6 +139,8 @@ DEFAULT = ASYNC }; + // Deprecated: Use TimeSource::MOCK_TIME_AND_NOW instead. + // TODO(gab): Migrate users. enum class NowSource { // base::Time::Now() and base::TimeTicks::Now() are real time. REAL_TIME, @@ -141,6 +170,7 @@ // List of traits that are valid inputs for the constructor below. struct ValidTrait { + ValidTrait(TimeSource); ValidTrait(MainThreadType); ValidTrait(ThreadPoolExecutionMode); ValidTrait(NowSource); @@ -155,11 +185,11 @@ trait_helpers::AreValidTraits<ValidTrait, ArgTypes...>::value>> NOINLINE ScopedTaskEnvironment(ArgTypes... args) : ScopedTaskEnvironment( + TimeSourceForTraits(args...), trait_helpers::GetEnum<MainThreadType, MainThreadType::DEFAULT>( args...), trait_helpers::GetEnum<ThreadPoolExecutionMode, ThreadPoolExecutionMode::DEFAULT>(args...), - trait_helpers::GetEnum<NowSource, NowSource::REAL_TIME>(args...), trait_helpers::GetEnum<ThreadingMode, ThreadingMode::DEFAULT>( args...), trait_helpers::HasTrait<SubclassCreatesDefaultTaskRunner>(args...), @@ -195,9 +225,9 @@ void RunUntilIdle(); // Only valid for instances with a MOCK_TIME MainThreadType. Fast-forwards - // virtual time by |delta|, causing all tasks on the main thread with a - // remaining delay less than or equal to |delta| to be executed in their - // natural order before this returns. |delta| must be non-negative. Upon + // virtual time by |delta|, causing all tasks on the main thread and thread + // pool with a remaining delay less than or equal to |delta| to be executed in + // their natural order before this returns. |delta| must be non-negative. Upon // returning from this method, NowTicks() will be >= the initial |NowTicks() + // delta|. It is guaranteed to be == iff tasks executed in this // FastForwardBy() didn't result in nested calls to time-advancing-methods. @@ -229,13 +259,13 @@ // FastForwardBy(2ms) // ================================ // Result: NowTicks() is 5ms further in the future. - // - // TODO(gab): Make this apply to ThreadPool delayed tasks as well - // (currently only main thread time is mocked). void FastForwardBy(TimeDelta delta); // Only valid for instances with a MOCK_TIME MainThreadType. // Short for FastForwardBy(TimeDelta::Max()). + // + // WARNING: This has the same caveat as RunUntilIdle() and is even more likely + // to spin forever (any RepeatingTimer will cause this). void FastForwardUntilNoTasksRemain(); // Only valid for instances with a MOCK_TIME MainThreadType. Returns a @@ -310,21 +340,64 @@ // The template constructor has to be in the header but it delegates to this // constructor to initialize all other members out-of-line. - ScopedTaskEnvironment(MainThreadType main_thread_type, + ScopedTaskEnvironment(TimeSource time_source, + MainThreadType main_thread_type, ThreadPoolExecutionMode thread_pool_execution_mode, - NowSource now_source, ThreadingMode threading_mode, bool subclass_creates_default_taskrunner, trait_helpers::NotATraitTag tag); + // Helper to extract TimeSource from a set of traits provided to + // ScopedTaskEnvironment's constructor. Helper for the migration (while + // TimeSource is optionally defined by MainThreadType or NowSource). + template <class... ArgTypes> + constexpr TimeSource TimeSourceForTraits(ArgTypes... args) { + const auto explicit_time_source = + trait_helpers::GetOptionalEnum<TimeSource>(args...); + const auto explicit_main_thread_type = + trait_helpers::GetOptionalEnum<MainThreadType>(args...); + const auto explicit_now_source = + trait_helpers::GetOptionalEnum<NowSource>(args...); + const bool requested_mock_time_via_main_thread_type = + explicit_main_thread_type && + (*explicit_main_thread_type == MainThreadType::MOCK_TIME || + *explicit_main_thread_type == MainThreadType::UI_MOCK_TIME || + *explicit_main_thread_type == MainThreadType::IO_MOCK_TIME); + + if (explicit_time_source) { + DCHECK(!explicit_now_source) << "NowSource is deprecated, use TimeSource"; + DCHECK(!requested_mock_time_via_main_thread_type) + << "Don't specify MOCK_TIME via MainThreadType, TimeSource is " + "sufficient"; + return *explicit_time_source; + } else if (explicit_now_source && + *explicit_now_source == NowSource::MAIN_THREAD_MOCK_TIME) { + // NowSource::MAIN_THREAD_MOCK_TIME was previously combined with + // MainThread::.*MOCK_TIME. + DCHECK(requested_mock_time_via_main_thread_type); + return TimeSource::MOCK_TIME_AND_NOW; + } else if (requested_mock_time_via_main_thread_type) { + return TimeSource::MOCK_TIME; + } + + return TimeSource::DEFAULT; + } + const MainThreadType main_thread_type_; const ThreadPoolExecutionMode thread_pool_execution_mode_; const ThreadingMode threading_mode_; const bool subclass_creates_default_taskrunner_; std::unique_ptr<sequence_manager::SequenceManager> sequence_manager_; + + // Manages the clock under TimeSource::MOCK_TIME modes. Null in + // TimeSource::SYSTEM_TIME mode. std::unique_ptr<MockTimeDomain> mock_time_domain_; + // Overrides Time/TimeTicks::Now() under TimeSource::MOCK_TIME_AND_NOW mode. + // Null in other modes. + std::unique_ptr<subtle::ScopedTimeClockOverrides> time_overrides_; + scoped_refptr<sequence_manager::TaskQueue> task_queue_; scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
diff --git a/base/test/scoped_task_environment_unittest.cc b/base/test/scoped_task_environment_unittest.cc index 145ab886..649d33e 100644 --- a/base/test/scoped_task_environment_unittest.cc +++ b/base/test/scoped_task_environment_unittest.cc
@@ -24,6 +24,7 @@ #include "base/test/test_timeouts.h" #include "base/threading/platform_thread.h" #include "base/threading/sequence_local_storage_slot.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/clock.h" @@ -182,8 +183,6 @@ }, Unretained(&counter)), kShortTaskDelay); - // TODO(gab): This currently doesn't run because the ThreadPool's clock - // isn't mocked but it should be. PostDelayedTask(FROM_HERE, BindOnce( [](subtle::Atomic32* counter) { @@ -211,6 +210,28 @@ }, Unretained(&counter)), kLongTaskDelay); + PostDelayedTask(FROM_HERE, + BindOnce( + [](subtle::Atomic32* counter) { + subtle::NoBarrier_AtomicIncrement(counter, 256); + }, + Unretained(&counter)), + kLongTaskDelay * 2); + ThreadTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, + BindOnce( + [](subtle::Atomic32* counter) { + subtle::NoBarrier_AtomicIncrement(counter, 512); + }, + Unretained(&counter)), + kLongTaskDelay * 3); + PostDelayedTask(FROM_HERE, + BindOnce( + [](subtle::Atomic32* counter) { + subtle::NoBarrier_AtomicIncrement(counter, 1024); + }, + Unretained(&counter)), + kLongTaskDelay * 4); ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, BindOnce( @@ -236,6 +257,8 @@ EXPECT_EQ(expected_value, counter); if (GetParam() == ScopedTaskEnvironment::MainThreadType::MOCK_TIME) { + const TimeTicks start_time = scoped_task_environment.NowTicks(); + // Delay inferior to the delay of the first posted task. constexpr base::TimeDelta kInferiorTaskDelay = TimeDelta::FromSeconds(1); static_assert(kInferiorTaskDelay < kShortTaskDelay, @@ -246,12 +269,19 @@ scoped_task_environment.FastForwardBy(kShortTaskDelay - kInferiorTaskDelay); expected_value += 4; + expected_value += 128; EXPECT_EQ(expected_value, counter); scoped_task_environment.FastForwardUntilNoTasksRemain(); expected_value += 8; expected_value += 16; + expected_value += 256; + expected_value += 512; + expected_value += 1024; EXPECT_EQ(expected_value, counter); + + EXPECT_EQ(scoped_task_environment.NowTicks() - start_time, + kLongTaskDelay * 4); } } @@ -456,7 +486,8 @@ EXPECT_EQ(scoped_task_environment.NowTicks(), start_time + kDelayPerTask * 5); } -TEST_F(ScopedTaskEnvironmentTest, CrossThreadTaskPostingDoesntAffectMockTime) { +TEST_F(ScopedTaskEnvironmentTest, + CrossThreadImmediateTaskPostingDoesntAffectMockTime) { ScopedTaskEnvironment scoped_task_environment( ScopedTaskEnvironment::MainThreadType::MOCK_TIME, ScopedTaskEnvironment::NowSource::MAIN_THREAD_MOCK_TIME); @@ -499,6 +530,158 @@ scoped_task_environment.RunUntilIdle(); } +TEST_F(ScopedTaskEnvironmentTest, MultiThreadedMockTime) { + ScopedTaskEnvironment scoped_task_environment( + ScopedTaskEnvironment::MainThreadType::MOCK_TIME); + + constexpr TimeDelta kOneMs = TimeDelta::FromMilliseconds(1); + const TimeTicks start_time = scoped_task_environment.NowTicks(); + const TimeTicks end_time = start_time + TimeDelta::FromMilliseconds(1'000); + + // Last TimeTicks::Now() seen from either contexts. + TimeTicks last_main_thread_ticks = start_time; + TimeTicks last_thread_pool_ticks = start_time; + + RepeatingClosure post_main_thread_delayed_task; + post_main_thread_delayed_task = BindLambdaForTesting([&]() { + // Expect that time only moves forward. + EXPECT_GE(scoped_task_environment.NowTicks(), last_main_thread_ticks); + + // Post four tasks to exercise the system some more but only if this is the + // first task at its runtime (otherwise we end up with 4^10'000 tasks by + // the end!). + if (last_main_thread_ticks < scoped_task_environment.NowTicks() && + scoped_task_environment.NowTicks() < end_time) { + SequencedTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, post_main_thread_delayed_task, kOneMs); + SequencedTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, post_main_thread_delayed_task, kOneMs); + SequencedTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, post_main_thread_delayed_task, kOneMs); + SequencedTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, post_main_thread_delayed_task, kOneMs); + } + + last_main_thread_ticks = scoped_task_environment.NowTicks(); + }); + + RepeatingClosure post_thread_pool_delayed_task; + post_thread_pool_delayed_task = BindLambdaForTesting([&]() { + // Expect that time only moves forward. + EXPECT_GE(scoped_task_environment.NowTicks(), last_thread_pool_ticks); + + // Post four tasks to exercise the system some more but only if this is the + // first task at its runtime (otherwise we end up with 4^10'000 tasks by + // the end!). + if (last_thread_pool_ticks < scoped_task_environment.NowTicks() && + scoped_task_environment.NowTicks() < end_time) { + SequencedTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, post_thread_pool_delayed_task, kOneMs); + SequencedTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, post_thread_pool_delayed_task, kOneMs); + SequencedTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, post_thread_pool_delayed_task, kOneMs); + SequencedTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, post_thread_pool_delayed_task, kOneMs); + + EXPECT_LT(scoped_task_environment.NowTicks(), end_time); + } + + last_thread_pool_ticks = scoped_task_environment.NowTicks(); + }); + + ThreadTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, post_main_thread_delayed_task, kOneMs); + CreateSequencedTaskRunnerWithTraits({ThreadPool()}) + ->PostDelayedTask(FROM_HERE, post_thread_pool_delayed_task, kOneMs); + + scoped_task_environment.FastForwardUntilNoTasksRemain(); + + EXPECT_EQ(last_main_thread_ticks, end_time); + EXPECT_EQ(last_thread_pool_ticks, end_time); + EXPECT_EQ(scoped_task_environment.NowTicks(), end_time); +} + +// Verify that ThreadPoolExecutionMode::QUEUED doesn't prevent running tasks and +// advancing time on the main thread. +TEST_F(ScopedTaskEnvironmentTest, + MultiThreadedMockTimeAndThreadPoolQueuedMode) { + ScopedTaskEnvironment scoped_task_environment( + ScopedTaskEnvironment::MainThreadType::MOCK_TIME, + ScopedTaskEnvironment::ThreadPoolExecutionMode::QUEUED); + + int count = 0; + const TimeTicks start_time = scoped_task_environment.NowTicks(); + + RunLoop run_loop; + + // Neither of these should run automatically per + // ThreadPoolExecutionMode::QUEUED. + PostTask(FROM_HERE, {ThreadPool()}, + BindLambdaForTesting([&]() { count += 128; })); + PostDelayedTask(FROM_HERE, {ThreadPool()}, + BindLambdaForTesting([&]() { count += 256; }), + TimeDelta::FromSeconds(5)); + + // Time should auto-advance to +500s in RunLoop::Run() without having to run + // the above forcefully QUEUED tasks. + ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, BindLambdaForTesting([&]() { count += 1; })); + ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, + BindLambdaForTesting([&]() { + count += 2; + run_loop.Quit(); + }), + TimeDelta::FromSeconds(500)); + + int expected_value = 0; + EXPECT_EQ(expected_value, count); + run_loop.Run(); + expected_value += 1; + expected_value += 2; + EXPECT_EQ(expected_value, count); + EXPECT_EQ(scoped_task_environment.NowTicks() - start_time, + TimeDelta::FromSeconds(500)); + + // Fast-forward through all remaining tasks, this should unblock QUEUED tasks + // in the thread pool but shouldn't need to advance time to process them. + scoped_task_environment.FastForwardUntilNoTasksRemain(); + expected_value += 128; + expected_value += 256; + EXPECT_EQ(expected_value, count); + EXPECT_EQ(scoped_task_environment.NowTicks() - start_time, + TimeDelta::FromSeconds(500)); + + // Test advancing time to a QUEUED task in the future. + PostDelayedTask(FROM_HERE, {ThreadPool()}, + BindLambdaForTesting([&]() { count += 512; }), + TimeDelta::FromSeconds(5)); + scoped_task_environment.FastForwardBy(TimeDelta::FromSeconds(7)); + expected_value += 512; + EXPECT_EQ(expected_value, count); + EXPECT_EQ(scoped_task_environment.NowTicks() - start_time, + TimeDelta::FromSeconds(507)); + + // Confirm that QUEUED mode is still active after the above fast forwarding + // (only the main thread task should run from RunLoop). + PostTask(FROM_HERE, {ThreadPool()}, + BindLambdaForTesting([&]() { count += 1024; })); + ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, BindLambdaForTesting([&]() { count += 2048; })); + PlatformThread::Sleep(TimeDelta::FromMilliseconds(1)); + RunLoop().RunUntilIdle(); + expected_value += 2048; + EXPECT_EQ(expected_value, count); + EXPECT_EQ(scoped_task_environment.NowTicks() - start_time, + TimeDelta::FromSeconds(507)); + + // Run the remaining task to avoid use-after-free on |count| from + // ~ScopedTaskEnvironment(). + scoped_task_environment.RunUntilIdle(); + expected_value += 1024; + EXPECT_EQ(expected_value, count); +} + #if defined(OS_WIN) // Regression test to ensure that ScopedTaskEnvironment enables the MTA in the // thread pool (so that the test environment matches that of the browser process @@ -862,5 +1045,30 @@ ScopedTaskEnvironmentMockedTime, ::testing::Values(ScopedTaskEnvironment::MainThreadType::IO_MOCK_TIME)); +TEST_F(ScopedTaskEnvironmentTest, TimeSourceMockTime) { + ScopedTaskEnvironment scoped_task_environment( + ScopedTaskEnvironment::TimeSource::MOCK_TIME); + + const TimeTicks start_time = scoped_task_environment.NowTicks(); + + constexpr TimeDelta kDelay = TimeDelta::FromSeconds(10); + ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, DoNothing(), + kDelay); + scoped_task_environment.FastForwardUntilNoTasksRemain(); + EXPECT_EQ(scoped_task_environment.NowTicks(), start_time + kDelay); +} + +TEST_F(ScopedTaskEnvironmentTest, TimeSourceMockTimeAndNow) { + ScopedTaskEnvironment scoped_task_environment( + ScopedTaskEnvironment::TimeSource::MOCK_TIME_AND_NOW); + + const TimeTicks start_time = scoped_task_environment.NowTicks(); + EXPECT_EQ(TimeTicks::Now(), start_time); + + constexpr TimeDelta kDelay = TimeDelta::FromSeconds(10); + scoped_task_environment.FastForwardBy(kDelay); + EXPECT_EQ(TimeTicks::Now(), start_time + kDelay); +} + } // namespace test } // namespace base
diff --git a/base/trace_event/trace_log.cc b/base/trace_event/trace_log.cc index f17dea2..dd59a6b 100644 --- a/base/trace_event/trace_log.cc +++ b/base/trace_event/trace_log.cc
@@ -1562,7 +1562,8 @@ } // TODO(ssid): Stop emitting and tracking thread names when perfetto is - // enabled. The JSON exporter will emit thread names. + // enabled and after crbug/978093 if fixed. The JSON exporter will emit thread + // names from thread descriptors. AutoLock thread_info_lock(thread_info_lock_); for (const auto& it : thread_names_) { if (it.second.empty())
diff --git a/build/android/generate_jacoco_report.py b/build/android/generate_jacoco_report.py index 3f0a8751..c1cad1f2 100755 --- a/build/android/generate_jacoco_report.py +++ b/build/android/generate_jacoco_report.py
@@ -191,7 +191,8 @@ print('Processing file %s' % path) file_coverage = {} - file_coverage['path'] = path + # Source path needs to start with '//', https://bit.ly/2XC80ZL + file_coverage['path'] = '//' + path file_coverage['lines'] = [] file_coverage['branches'] = []
diff --git a/build/android/pylib/linker/linker_test_instance.py b/build/android/pylib/linker/linker_test_instance.py index 5f19db9..53978cb 100644 --- a/build/android/pylib/linker/linker_test_instance.py +++ b/build/android/pylib/linker/linker_test_instance.py
@@ -27,10 +27,7 @@ return self._test_filter def GetTests(self): - tests = [ - test_case.LinkerSharedRelroTest(is_low_memory=False), - test_case.LinkerSharedRelroTest(is_low_memory=True) - ] + tests = [test_case.LinkerSharedRelroTest()] if self._test_filter: filtered_names = unittest_util.FilterTestNames(
diff --git a/build/android/pylib/linker/test_case.py b/build/android/pylib/linker/test_case.py index 2afba5c..f94f1a8 100644 --- a/build/android/pylib/linker/test_case.py +++ b/build/android/pylib/linker/test_case.py
@@ -49,7 +49,6 @@ _PACKAGE_NAME = 'org.chromium.chromium_linker_test_apk' _ACTIVITY_NAME = '.ChromiumLinkerTestActivity' -_COMMAND_LINE_FILE = '/data/local/tmp/chromium-linker-test-command-line' # Logcat filters used during each test. Only the 'chromium' one is really # needed, but the logs are added to the TestResult in case of error, and @@ -126,23 +125,15 @@ class LinkerTestCaseBase(object): """Base class for linker test cases.""" - def __init__(self, is_low_memory=False): - """Create a test case. - Args: - is_low_memory: True to simulate a low-memory device, False otherwise. - """ + def __init__(self): + """Creates a test case.""" test_suffix = 'ForLegacyLinker' - self.is_low_memory = is_low_memory - if is_low_memory: - test_suffix += 'LowMemoryDevice' - else: - test_suffix += 'RegularDevice' class_name = self.__class__.__name__ self.qualified_name = '%s.%s' % (class_name, test_suffix) self.tagged_name = self.qualified_name def _RunTest(self, _device): - """Run the test, must be overriden. + """Runs the test, must be overridden. Args: _device: A DeviceUtils interface. Returns: @@ -153,7 +144,7 @@ return ResultType.FAIL, 'Unimplemented _RunTest() method!' def Run(self, device): - """Run the test on a given device. + """Runs the test on a given device. Args: device: Name of target device where to run the test. Returns: @@ -163,11 +154,6 @@ print('[ %-*s ] %s' % (margin, 'RUN', self.tagged_name)) logging.info('Running linker test: %s', self.tagged_name) - command_line_flags = '' - if self.is_low_memory: - command_line_flags += ' --low-memory-device' - device.WriteFile(_COMMAND_LINE_FILE, command_line_flags) - # Run the test. status, logs = self._RunTest(device)
diff --git a/build/config/android/config.gni b/build/config/android/config.gni index 7483620..be9c296 100644 --- a/build/config/android/config.gni +++ b/build/config/android/config.gni
@@ -214,10 +214,9 @@ android_sdk_tools_bundle_aapt2_dir = "//third_party/android_build_tools/aapt2" - # Use R8 for Java optimization rather than ProGuard for all targets. R8 is - # already used as the default for public targets. This will evenutally be - # the default. https://crbug.com/908988 - use_r8 = false + # Use R8 for Java optimization rather than any progaurd_jar_path provided + # for all targets. Proguard support may be dropped in the near future. + use_r8 = true # Checks that proguard flags have not changed (!is_java_debug only). check_android_configuration = false
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index d4e801b9..28ca2a5 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -8908319511199702128 \ No newline at end of file +8908254478258311552 \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 7078c0a..097742f5 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -8908322498030374672 \ No newline at end of file +8908254542434342448 \ No newline at end of file
diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn index 5e76453..109bcf5 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn
@@ -1765,7 +1765,7 @@ java_cpp_enum("signin_metrics_enum_javagen") { sources = [ - "../components/signin/core/browser/signin_metrics.h", + "../components/signin/public/base/signin_metrics.h", ] }
diff --git a/chrome/VERSION b/chrome/VERSION index 451f84b..d25798f 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=77 MINOR=0 -BUILD=3850 +BUILD=3851 PATCH=0
diff --git a/chrome/android/chrome_java_sources.gni b/chrome/android/chrome_java_sources.gni index e65c96a..251b6cd 100644 --- a/chrome/android/chrome_java_sources.gni +++ b/chrome/android/chrome_java_sources.gni
@@ -672,7 +672,6 @@ "java/src/org/chromium/chrome/browser/findinpage/FindInPageBridge.java", "java/src/org/chromium/chrome/browser/findinpage/FindMatchRectsDetails.java", "java/src/org/chromium/chrome/browser/findinpage/FindNotificationDetails.java", - "java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java", "java/src/org/chromium/chrome/browser/firstrun/DataReductionProxyFirstRunFragment.java", "java/src/org/chromium/chrome/browser/firstrun/DefaultSearchEngineFirstRunFragment.java", "java/src/org/chromium/chrome/browser/firstrun/FirstRunActivity.java", @@ -695,7 +694,6 @@ "java/src/org/chromium/chrome/browser/firstrun/TabbedModeFirstRunActivity.java", "java/src/org/chromium/chrome/browser/firstrun/ToSAckedReceiver.java", "java/src/org/chromium/chrome/browser/firstrun/ToSAndUMAFirstRunFragment.java", - "java/src/org/chromium/chrome/browser/fullscreen/BrowserControlsOffsetHelper.java", "java/src/org/chromium/chrome/browser/fullscreen/BrowserStateBrowserControlsVisibilityDelegate.java", "java/src/org/chromium/chrome/browser/fullscreen/ChromeFullscreenManager.java", "java/src/org/chromium/chrome/browser/fullscreen/ComposedBrowserControlsVisibilityDelegate.java", @@ -1413,10 +1411,6 @@ "java/src/org/chromium/chrome/browser/sharing/SharingJNIBridge.java", "java/src/org/chromium/chrome/browser/signin/AccountAdder.java", "java/src/org/chromium/chrome/browser/signin/AccountPickerDialogFragment.java", - "java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java", - "java/src/org/chromium/chrome/browser/signin/AccountSigninChooseView.java", - "java/src/org/chromium/chrome/browser/signin/AccountSigninConfirmationView.java", - "java/src/org/chromium/chrome/browser/signin/AccountSigninView.java", "java/src/org/chromium/chrome/browser/signin/IdentityServicesProvider.java", "java/src/org/chromium/chrome/browser/signin/ConfirmImportSyncDataDialog.java", "java/src/org/chromium/chrome/browser/signin/ConfirmManagedSyncDataDialog.java",
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java index 2968e032..34c5b65 100644 --- a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java
@@ -17,11 +17,11 @@ /* package */ class AutofillAssistantMetrics { private static final EnumeratedHistogramSample ENUMERATED_DROP_OUT_REASON = new EnumeratedHistogramSample( - "Android.AutofillAssistant.DropOutReason", DropOutReason.NUM_ENTRIES); + "Android.AutofillAssistant.DropOutReason", DropOutReason.MAX_VALUE); private static final EnumeratedHistogramSample ENUMERATED_ON_BOARDING = new EnumeratedHistogramSample( - "Android.AutofillAssistant.OnBoarding", OnBoarding.OB_NUM_ENTRIES); + "Android.AutofillAssistant.OnBoarding", OnBoarding.MAX_VALUE); /** * Records the reason for a drop out.
diff --git a/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_password_info.xml b/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_password_info.xml index 96662ed..31d1ab36 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_password_info.xml +++ b/chrome/android/features/keyboard_accessory/internal/java/res/layout/keyboard_accessory_sheet_tab_password_info.xml
@@ -15,6 +15,15 @@ android:layout_marginBottom="@dimen/keyboard_accessory_sheet_bottom_margin" android:orientation="vertical"> + <TextView + android:id="@+id/password_info_title" + android:paddingTop="@dimen/keyboard_accessory_sheet_bottom_margin" + android:paddingBottom="@dimen/keyboard_accessory_sheet_bottom_margin" + android:gravity="center_vertical|start" + android:textAppearance="@style/TextAppearance.BlackHint1" + android:minHeight="@dimen/keyboard_accessory_height" + android:layout_height="wrap_content" + android:layout_width="match_parent"/> <LinearLayout android:gravity="center_vertical|start"
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessoryInfoView.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessoryInfoView.java index 346f968..d13fb28 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessoryInfoView.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessoryInfoView.java
@@ -16,6 +16,7 @@ import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; +import android.widget.TextView; import org.chromium.chrome.browser.keyboard_accessory.R; import org.chromium.ui.widget.ChipView; @@ -24,6 +25,7 @@ * This view represents a section of user credentials in the password tab of the keyboard accessory. */ class PasswordAccessoryInfoView extends LinearLayout { + private TextView mTitle; private ImageView mIcon; private ChipView mUsername; private ChipView mPassword; @@ -59,6 +61,7 @@ protected void onFinishInflate() { super.onFinishInflate(); + mTitle = findViewById(R.id.password_info_title); mIcon = findViewById(R.id.favicon); mUsername = findViewById(R.id.suggestion_text); mPassword = findViewById(R.id.password_text); @@ -77,6 +80,10 @@ mIcon.setImageDrawable(icon); } + TextView getTitle() { + return mTitle; + } + ChipView getUsername() { return mUsername; }
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetModernViewBinder.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetModernViewBinder.java index c706c1b..603a35d 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetModernViewBinder.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetModernViewBinder.java
@@ -6,6 +6,7 @@ import android.support.v7.widget.RecyclerView; import android.text.method.PasswordTransformationMethod; +import android.view.View; import android.view.ViewGroup; import org.chromium.chrome.browser.keyboard_accessory.R; @@ -49,6 +50,9 @@ bindChipView(view.getUsername(), info.getFields().get(0)); bindChipView(view.getPassword(), info.getFields().get(1)); + view.getTitle().setVisibility(info.getTitle().isEmpty() ? View.GONE : View.VISIBLE); + view.getTitle().setText(info.getTitle()); + view.setIconForBitmap(null); // Set the default icon, then try to get a better one. if (info.getFaviconProvider() != null) { info.getFaviconProvider().fetchFavicon(
diff --git a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetModernViewTest.java b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetModernViewTest.java index f52134f..ab6dc92 100644 --- a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetModernViewTest.java +++ b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_tabs/PasswordAccessorySheetModernViewTest.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.keyboard_accessory.sheet_tabs; +import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; @@ -15,7 +16,6 @@ import android.text.method.PasswordTransformationMethod; import android.view.View; import android.view.ViewGroup; -import android.widget.LinearLayout; import android.widget.TextView; import org.junit.After; @@ -137,19 +137,49 @@ assertThat(clicked.get(), is(true)); } + @Test + @MediumTest + public void testAddingUserInfoTitlesAreRenderedIfNotEmpty() { + assertThat(mView.get().getChildCount(), is(0)); + final UserInfoField kUnusedInfoField = + new UserInfoField("Unused Name", "Unused Password", "", false, cb -> {}); + + TestThreadUtils.runOnUiThreadBlocking(() -> { + UserInfo sameOriginInfo = new UserInfo("", null); + sameOriginInfo.addField(kUnusedInfoField); + sameOriginInfo.addField(kUnusedInfoField); + mModel.add(new AccessorySheetDataPiece( + sameOriginInfo, AccessorySheetDataPiece.Type.PASSWORD_INFO)); + + UserInfo pslOriginInfo = new UserInfo("other.origin.eg", null); + pslOriginInfo.addField(kUnusedInfoField); + pslOriginInfo.addField(kUnusedInfoField); + mModel.add(new AccessorySheetDataPiece( + pslOriginInfo, AccessorySheetDataPiece.Type.PASSWORD_INFO)); + }); + + CriteriaHelper.pollUiThread(Criteria.equals(2, () -> mView.get().getChildCount())); + + assertThat(getUserInfoAt(0).getTitle().isShown(), is(false)); + assertThat(getUserInfoAt(1).getTitle().isShown(), is(true)); + assertThat(getUserInfoAt(1).getTitle().getText(), is("other.origin.eg")); + } + + private PasswordAccessoryInfoView getUserInfoAt(int index) { + assertThat(mView.get().getChildCount(), is(greaterThan(index))); + assertThat(mView.get().getChildAt(index), instanceOf(PasswordAccessoryInfoView.class)); + return (PasswordAccessoryInfoView) mView.get().getChildAt(index); + } + private ChipView getNameSuggestion() { - assertThat(mView.get().getChildAt(0), instanceOf(LinearLayout.class)); - LinearLayout layout = (LinearLayout) mView.get().getChildAt(0); - View view = layout.findViewById(R.id.suggestion_text); + View view = getUserInfoAt(0).findViewById(R.id.suggestion_text); assertThat(view, is(not(nullValue()))); assertThat(view, instanceOf(ChipView.class)); return (ChipView) view; } private ChipView getPasswordSuggestion() { - assertThat(mView.get().getChildAt(0), instanceOf(LinearLayout.class)); - LinearLayout layout = (LinearLayout) mView.get().getChildAt(0); - View view = layout.findViewById(R.id.password_text); + View view = getUserInfoAt(0).findViewById(R.id.password_text); assertThat(view, is(not(nullValue()))); assertThat(view, instanceOf(ChipView.class)); return (ChipView) view;
diff --git a/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingControllerTest.java b/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingControllerTest.java index 1e1851f..f3f9fa4 100644 --- a/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingControllerTest.java +++ b/chrome/android/features/keyboard_accessory/junit/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingControllerTest.java
@@ -284,8 +284,18 @@ when(mMockKeyboard.calculateKeyboardHeight(any())).thenReturn(0); when(mMockActivity.getTabModelSelector()).thenReturn(mMockTabModelSelector); when(mMockActivity.getActivityTabProvider()).thenReturn(mActivityTabProvider); - ChromeFullscreenManager fullscreenManager = - new ChromeFullscreenManager(mMockActivity, null, 0); + ChromeFullscreenManager fullscreenManager = new ChromeFullscreenManager(mMockActivity, 0) { + @Override + protected boolean isInVr() { + return false; + } + @Override + protected boolean bootsToVr() { + return false; + } + @Override + protected void rawTopContentOffsetChangedForVr(int topContentOffset) {} + }; when(mMockActivity.getFullscreenManager()).thenReturn(fullscreenManager); when(mMockActivity.getCompositorViewHolder()).thenReturn(mMockCompositorViewHolder); when(mMockActivity.getResources()).thenReturn(mMockResources);
diff --git a/chrome/android/java/AndroidManifest.xml b/chrome/android/java/AndroidManifest.xml index b727990..d06ab4e 100644 --- a/chrome/android/java/AndroidManifest.xml +++ b/chrome/android/java/AndroidManifest.xml
@@ -620,10 +620,6 @@ {{ self.supports_vr() }} </activity> {% endif %} - <activity android:name="org.chromium.chrome.browser.signin.AccountSigninActivity" - android:theme="@style/Theme.Chromium.DialogWhenLarge" - android:configChanges="orientation|keyboardHidden|keyboard|screenSize|mcc|mnc|screenLayout|smallestScreenSize"> - </activity> <activity android:name="org.chromium.chrome.browser.signin.SigninActivity" android:theme="@style/Theme.Chromium.DialogWhenLarge" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|mcc|mnc|screenLayout|smallestScreenSize"
diff --git a/chrome/android/java/monochrome_public_bundle.proguard_flags.expected b/chrome/android/java/monochrome_public_bundle.proguard_flags.expected index 59b584f..730cf54 100644 --- a/chrome/android/java/monochrome_public_bundle.proguard_flags.expected +++ b/chrome/android/java/monochrome_public_bundle.proguard_flags.expected
@@ -412,26 +412,6 @@ -dontwarn com.google.protobuf.nano.NanoEnumValue ################################################################################ -# gen/third_party/android_deps/android_arch_lifecycle_runtime_java/proguard.txt -################################################################################ --keepattributes *Annotation* - --keepclassmembers enum android.arch.lifecycle.Lifecycle$Event { - <fields>; -} - --keep class * implements android.arch.lifecycle.LifecycleObserver { -} - --keep class * implements android.arch.lifecycle.GeneratedAdapter { - <init>(...); -} - --keepclassmembers class ** { - @android.arch.lifecycle.OnLifecycleEvent *; -} - -################################################################################ # gen/third_party/android_deps/com_android_support_animated_vector_drawable_java/proguard.txt ################################################################################ # Copyright (C) 2016 The Android Open Source Project
diff --git a/chrome/android/java/monochrome_public_bundle__base_bundle_module.AndroidManifest.expected b/chrome/android/java/monochrome_public_bundle__base_bundle_module.AndroidManifest.expected index 6fe743f..755a2e3 100644 --- a/chrome/android/java/monochrome_public_bundle__base_bundle_module.AndroidManifest.expected +++ b/chrome/android/java/monochrome_public_bundle__base_bundle_module.AndroidManifest.expected
@@ -264,10 +264,6 @@ </intent-filter> </activity> <activity - android:configChanges="orientation|keyboardHidden|keyboard|screenSize|mcc|mnc|screenLayout|smallestScreenSize" - android:name="org.chromium.chrome.browser.signin.AccountSigninActivity" - android:theme="@style/Theme.Chromium.DialogWhenLarge"/> - <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|mcc|mnc|screenLayout|smallestScreenSize|uiMode" android:enableVrMode="@string/gvr_vr_mode_component" android:excludeFromRecents="true"
diff --git a/chrome/android/java/res/layout/account_signin_account_view.xml b/chrome/android/java/res/layout/account_signin_account_view.xml deleted file mode 100644 index caab8e52..0000000 --- a/chrome/android/java/res/layout/account_signin_account_view.xml +++ /dev/null
@@ -1,46 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- Copyright 2016 The Chromium Authors. All rights reserved. - - Use of this source code is governed by a BSD-style license that can be - found in the LICENSE file. --> - -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" - xmlns:tools="http://schemas.android.com/tools" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:background="?attr/selectableItemBackground" - android:gravity="center_vertical" - android:orientation="horizontal" - android:paddingEnd="16dp" - android:paddingStart="16dp"> - - <ImageView - android:id="@+id/account_image" - android:layout_width="40dp" - android:layout_height="40dp" - android:layout_marginEnd="16dp" - tools:ignore="ContentDescription" /> - - <!-- 2dp bottom padding is necessary to move text 1dp up according to the Material spec. - See https://crbug.com/701221#c37. --> - <TextView - android:id="@+id/account_name" - android:layout_width="0dp" - android:layout_height="wrap_content" - android:layout_weight="1" - android:gravity="center_vertical" - android:minHeight="56dp" - android:paddingBottom="2dp" - android:textAppearance="@style/TextAppearance.BlackBodyDefault" /> - - <ImageView - android:id="@+id/account_selection_mark" - android:layout_width="24dp" - android:layout_height="24dp" - android:layout_marginStart="16dp" - tools:ignore="ContentDescription" - android:src="@drawable/ic_check_googblue_24dp" - android:visibility="gone" - app:tint="@color/default_icon_color_blue" /> -</LinearLayout>
diff --git a/chrome/android/java/res/layout/account_signin_view.xml b/chrome/android/java/res/layout/account_signin_view.xml deleted file mode 100644 index 0eae8c6a..0000000 --- a/chrome/android/java/res/layout/account_signin_view.xml +++ /dev/null
@@ -1,226 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- Copyright 2015 The Chromium Authors. All rights reserved. - - Use of this source code is governed by a BSD-style license that can be - found in the LICENSE file. ---> -<org.chromium.chrome.browser.signin.AccountSigninView - xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:tools="http://schemas.android.com/tools" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:background="@color/signin_body_background"> - - <FrameLayout - android:layout_width="match_parent" - android:layout_height="match_parent" - android:layout_marginBottom="68dp"> - - <!-- The view that allows the user to choose the sign in account --> - <org.chromium.chrome.browser.signin.AccountSigninChooseView - android:id="@+id/account_signin_choose_view" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:scrollbars="none" - android:requiresFadingEdge="vertical" - android:fadingEdgeLength="48dp"> - - <LinearLayout - android:id="@+id/account_signin_choose_view_root_child_view" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:orientation="vertical"> - - <!-- The layout_width/layout_height is set to 16/9 dynamically in Java --> - <TextView - android:id="@+id/chooser_title" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:gravity="bottom" - android:paddingStart="@dimen/signin_chooser_padding" - android:paddingEnd="@dimen/signin_chooser_padding" - android:paddingBottom="@dimen/signin_chooser_padding" - android:background="@color/signin_head_background" - android:textAppearance="@style/TextAppearance.BlackHeadline" - android:text="@string/sign_in_to_chrome"/> - - <View style="@style/HorizontalDivider"/> - - <TextView - android:id="@+id/signin_choice_description" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:padding="@dimen/signin_chooser_padding" - android:lineSpacingMultiplier="1.4" - android:text="@string/signin_account_choice_description" - android:textAppearance="@style/TextAppearance.BlackBodyDefault"/> - </LinearLayout> - </org.chromium.chrome.browser.signin.AccountSigninChooseView> - - <!-- The view that allows the user to confirm signed in account, sync and service personalization --> - <org.chromium.chrome.browser.signin.AccountSigninConfirmationView - android:id="@+id/signin_confirmation_view" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:scrollbars="none" - android:requiresFadingEdge="vertical" - android:fadingEdgeLength="48dp" - android:visibility="gone"> - - <LinearLayout - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:orientation="vertical"> - - <!-- The layout_width/layout_height is set to 16/9 dynamically in Java --> - <LinearLayout - android:id="@+id/signin_confirmation_head" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:gravity="bottom" - android:paddingStart="16dp" - android:paddingEnd="16dp" - android:background="@color/signin_head_background" - android:orientation="vertical"> - - <ImageView - android:id="@+id/signin_account_image" - android:layout_width="@dimen/signin_account_image_size" - android:layout_height="@dimen/signin_account_image_size" - android:layout_marginBottom="24dp" - android:scaleType="fitCenter" - tools:ignore="ContentDescription"/> - - <TextView - android:id="@+id/signin_account_name" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginBottom="8dp" - android:textAppearance="@style/TextAppearance.BlackHeadline" - android:ellipsize="end" - android:maxLines="1"/> - - <TextView - android:id="@+id/signin_account_email" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginBottom="16dp" - android:textAppearance="@style/TextAppearance.BlackBody" - android:ellipsize="end" - android:maxLines="1"/> - </LinearLayout> - - <View style="@style/HorizontalDivider"/> - - <TextView - android:id="@+id/signin_sync_title" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginTop="16dp" - android:layout_marginBottom="8dp" - android:paddingStart="16dp" - android:paddingEnd="16dp" - android:textAppearance="@style/TextAppearance.BlackTitle2" - android:drawableStart="@drawable/chrome_sync_logo" - android:drawablePadding="16dp"/> - - <TextView - android:id="@+id/signin_sync_description" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginBottom="16dp" - android:paddingStart="56dp" - android:paddingEnd="16dp" - android:lineSpacingMultiplier="1.4" - android:textAppearance="@style/TextAppearance.BlackBody" /> - - <View - style="@style/HorizontalDivider" - android:layout_marginStart="56dp" - android:layout_marginEnd="16dp"/> - - <TextView - android:id="@+id/signin_personalize_service_title" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginTop="16dp" - android:layout_marginBottom="8dp" - android:paddingStart="16dp" - android:paddingEnd="16dp" - android:textAppearance="@style/TextAppearance.BlackTitle2" - android:drawableStart="@drawable/ic_logo_googleg_24dp" - android:drawablePadding="16dp"/> - - <TextView - android:id="@+id/signin_personalize_service_description" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginBottom="32dp" - android:paddingStart="56dp" - android:paddingEnd="16dp" - android:lineSpacingMultiplier="1.4" - android:textAppearance="@style/TextAppearance.BlackBody" /> - - <org.chromium.ui.widget.TextViewWithClickableSpans - android:id="@+id/signin_settings_control" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:paddingStart="16dp" - android:paddingEnd="16dp" - android:paddingBottom="36dp" - android:lineSpacingMultiplier="1.4" - android:textAppearance="@style/TextAppearance.BlackBody" /> - </LinearLayout> - </org.chromium.chrome.browser.signin.AccountSigninConfirmationView> - </FrameLayout> - - <LinearLayout - android:id="@+id/button_bar" - android:layout_width="match_parent" - android:layout_height="68dp" - android:layout_gravity="bottom" - android:padding="16dp" - android:orientation="horizontal" > - - <!--suppress ButtonStyle --> - <org.chromium.ui.widget.ButtonCompat - android:id="@+id/negative_button" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:paddingStart="@dimen/fre_button_padding" - android:paddingEnd="@dimen/fre_button_padding" - style="@style/TextButton" /> - - <View - android:layout_width="0dp" - android:layout_height="0dp" - android:layout_weight="1" - android:visibility="invisible"/> - - <!--suppress ButtonStyle --> - <org.chromium.ui.widget.ButtonCompat - android:id="@+id/positive_button" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:paddingStart="@dimen/fre_button_padding" - android:paddingEnd="@dimen/fre_button_padding" - style="@style/FilledButton.Flat" /> - - <org.chromium.ui.widget.ButtonCompat - android:id="@+id/more_button" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:drawableEnd="@drawable/down_arrow" - android:drawablePadding="8dp" - android:visibility="gone" - style="@style/TextButton" /> - - <View - android:id="@+id/positive_button_end_padding" - android:layout_width="0dp" - android:layout_height="0dp" - android:layout_weight="1" - android:visibility="gone"/> - </LinearLayout> - -</org.chromium.chrome.browser.signin.AccountSigninView>
diff --git a/chrome/android/java/res/values/dimens.xml b/chrome/android/java/res/values/dimens.xml index 9e53018b..dded95b 100644 --- a/chrome/android/java/res/values/dimens.xml +++ b/chrome/android/java/res/values/dimens.xml
@@ -178,7 +178,6 @@ <!-- Account Signin dimensions --> <!-- The Account Signin page appears in the First Run Experience (amongst other places), so uses a lot of the fre_* dimensions for consistency. --> - <dimen name="signin_account_image_size">64dp</dimen> <dimen name="signin_image_carousel_width">240dp</dimen> <dimen name="signin_chooser_padding">16dp</dimen> <dimen name="signin_screen_top_padding">50dp</dimen>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java index a753e6324..0c1beda 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java
@@ -90,7 +90,6 @@ import org.chromium.chrome.browser.download.items.OfflineContentAggregatorNotificationBridgeUiFactory; import org.chromium.chrome.browser.feature_engagement.TrackerFactory; import org.chromium.chrome.browser.firstrun.ForcedSigninProcessor; -import org.chromium.chrome.browser.fullscreen.BrowserControlsOffsetHelper; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; import org.chromium.chrome.browser.gsa.ContextReporter; import org.chromium.chrome.browser.gsa.GSAAccountChangeListener; @@ -322,9 +321,6 @@ /** A means of providing the foreground tab of the activity to different features. */ private ActivityTabProvider mActivityTabProvider = new ActivityTabProvider(); - /** Helper class managing top/bottom browser control offsets. */ - protected BrowserControlsOffsetHelper mBrowserControlsOffsetHelper; - /** A means of providing the theme color to different features. */ private TabThemeColorProvider mTabThemeColorProvider; @@ -566,7 +562,7 @@ // On certain android devices this setup sequence results in disk writes outside // of our control, so we have to disable StrictMode to work. See // https://crbug.com/639352. - try (StrictModeContext smc = StrictModeContext.allowDiskWrites()) { + try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) { TraceEvent.begin("setContentView(R.layout.main)"); setContentView(R.layout.main); TraceEvent.end("setContentView(R.layout.main)"); @@ -835,8 +831,6 @@ mReaderModeManager = new ReaderModeManager(getTabModelSelector(), this); } - mBrowserControlsOffsetHelper = new BrowserControlsOffsetHelper( - getLifecycleDispatcher(), mActivityTabProvider, () -> getFullscreenManager()); TraceEvent.end("ChromeActivity:CompositorInitialization"); } @@ -1847,8 +1841,7 @@ */ @NonNull protected ChromeFullscreenManager createFullscreenManager() { - return new ChromeFullscreenManager(this, - () -> mBrowserControlsOffsetHelper, ChromeFullscreenManager.ControlsPosition.TOP); + return new ChromeFullscreenManager(this, ChromeFullscreenManager.ControlsPosition.TOP); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java index 2de2b71..81433226 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java
@@ -320,7 +320,6 @@ public static final String TAB_GROUPS_UI_IMPROVEMENTS_ANDROID = "TabGroupsUiImprovementsAndroid"; public static final String TAB_GRID_LAYOUT_ANDROID = "TabGridLayoutAndroid"; - public static final String TAB_PERSISTENT_STORE_TASK_RUNNER = "TabPersistentStoreTaskRunner"; public static final String TAB_REPARENTING = "TabReparenting"; public static final String TAB_SWITCHER_ON_RETURN = "TabSwitcherOnReturn"; public static final String TAB_TO_GTS_ANIMATION = "TabToGTSAnimation";
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java index d80eb6d..1f38d44c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java
@@ -2240,8 +2240,7 @@ @Override protected ModalDialogManager createModalDialogManager() { ModalDialogManager manager = super.createModalDialogManager(); - mTabModalHandler = - new TabModalLifetimeHandler(this, manager, () -> mBrowserControlsOffsetHelper); + mTabModalHandler = new TabModalLifetimeHandler(this, manager); return manager; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java deleted file mode 100644 index 8c725a6..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java +++ /dev/null
@@ -1,112 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.firstrun; - -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import org.chromium.base.metrics.RecordUserAction; -import org.chromium.chrome.R; -import org.chromium.chrome.browser.ntp.cards.SignInPromo; -import org.chromium.chrome.browser.signin.AccountSigninView; -import org.chromium.chrome.browser.signin.SigninAccessPoint; -import org.chromium.chrome.browser.signin.SigninManager; -import org.chromium.components.signin.ChildAccountStatus; - -/** - * A {@link Fragment} meant to handle sync setup for the first run experience. - */ -public class AccountFirstRunFragment - extends Fragment implements FirstRunFragment, AccountSigninView.Delegate { - // Per-page parameters: - public static final String FORCE_SIGNIN_ACCOUNT_TO = "ForceSigninAccountTo"; - public static final String CHILD_ACCOUNT_STATUS = "ChildAccountStatus"; - - private AccountSigninView mView; - - @Override - public View onCreateView( - LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - mView = (AccountSigninView) inflater.inflate( - R.layout.account_signin_view, container, false); - return mView; - } - - @Override - public void onViewCreated(View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - - Bundle freProperties = getPageDelegate().getProperties(); - @ChildAccountStatus.Status - int childAccountStatus = - freProperties.getInt(CHILD_ACCOUNT_STATUS, ChildAccountStatus.NOT_CHILD); - String forceAccountTo = freProperties.getString(FORCE_SIGNIN_ACCOUNT_TO); - - AccountSigninView.Listener listener = new AccountSigninView.Listener() { - @Override - public void onAccountSelectionCanceled() { - SignInPromo.temporarilySuppressPromos(); - getPageDelegate().refuseSignIn(); - getPageDelegate().advanceToNextPage(); - } - - @Override - public void onNewAccount() { - FirstRunUtils.openAccountAdder(AccountFirstRunFragment.this); - } - - @Override - public void onAccountSelected( - String accountName, boolean isDefaultAccount, boolean settingsClicked) { - getPageDelegate().acceptSignIn(accountName, isDefaultAccount, settingsClicked); - getPageDelegate().advanceToNextPage(); - } - - @Override - public void onFailedToSetForcedAccount(String forcedAccountName) { - // Somehow the forced account disappeared while we were in the FRE. - // The user would have to go through the FRE again. - getPageDelegate().abortFirstRunExperience(); - } - }; - - final Bundle arguments; - if (forceAccountTo == null) { - arguments = AccountSigninView.createArgumentsForDefaultFlow( - SigninAccessPoint.START_PAGE, childAccountStatus); - } else { - arguments = AccountSigninView.createArgumentsForConfirmationFlow( - SigninAccessPoint.START_PAGE, childAccountStatus, forceAccountTo, false, - AccountSigninView.UndoBehavior.INVISIBLE); - } - mView.init(arguments, this, listener); - - RecordUserAction.record("MobileFre.SignInShown"); - RecordUserAction.record("Signin_Signin_FromStartPage"); - SigninManager.logSigninStartAccessPoint(SigninAccessPoint.START_PAGE); - } - - // FirstRunFragment: - @Override - public boolean interceptBackPressed() { - Bundle freProperties = getPageDelegate().getProperties(); - boolean forceSignin = freProperties.getString(FORCE_SIGNIN_ACCOUNT_TO) != null; - if (!mView.isInConfirmationScreen() || forceSignin) { - return false; - } - - mView.cancelConfirmationScreen(); - return true; - } - - @Override - public FragmentManager getSupportFragmentManager() { - return getFragmentManager(); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/FirstRunActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/FirstRunActivity.java index b3e03f7..344604b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/FirstRunActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/FirstRunActivity.java
@@ -209,7 +209,7 @@ mShowWelcomePage = mFreProperties.getBoolean(SHOW_WELCOME_PAGE); if (TextUtils.isEmpty(mResultSignInAccountName)) { mResultSignInAccountName = mFreProperties.getString( - AccountFirstRunFragment.FORCE_SIGNIN_ACCOUNT_TO); + SigninFirstRunFragment.FORCE_SIGNIN_ACCOUNT_TO); } createPageSequence();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/FirstRunFlowSequencer.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/FirstRunFlowSequencer.java index 03592f83..628a954 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/FirstRunFlowSequencer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/FirstRunFlowSequencer.java
@@ -172,7 +172,7 @@ // In the full FRE we always show the Welcome page, except on EDU devices. boolean showWelcomePage = !mForceEduSignIn; freProperties.putBoolean(FirstRunActivity.SHOW_WELCOME_PAGE, showWelcomePage); - freProperties.putInt(AccountFirstRunFragment.CHILD_ACCOUNT_STATUS, mChildAccountStatus); + freProperties.putInt(SigninFirstRunFragment.CHILD_ACCOUNT_STATUS, mChildAccountStatus); // Initialize usage and crash reporting according to the default value. // The user can explicitly enable or disable the reporting on the Welcome page. @@ -202,7 +202,7 @@ // If the device is an Android EDU device or has a child account, there should be // exactly account on the device. Force sign-in in to that account. freProperties.putString( - AccountFirstRunFragment.FORCE_SIGNIN_ACCOUNT_TO, mGoogleAccounts.get(0).name); + SigninFirstRunFragment.FORCE_SIGNIN_ACCOUNT_TO, mGoogleAccounts.get(0).name); } freProperties.putBoolean(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/LightweightFirstRunActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/LightweightFirstRunActivity.java index 3583d107..f4be682e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/LightweightFirstRunActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/LightweightFirstRunActivity.java
@@ -47,7 +47,7 @@ @ChildAccountStatus.Status int childAccountStatus = freProperties.getInt( - AccountFirstRunFragment.CHILD_ACCOUNT_STATUS, ChildAccountStatus.NOT_CHILD); + SigninFirstRunFragment.CHILD_ACCOUNT_STATUS, ChildAccountStatus.NOT_CHILD); onChildAccountKnown(ChildAccountStatus.isChild(childAccountStatus)); } };
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/SigninFirstRunFragment.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/SigninFirstRunFragment.java index 23407f4c..3c5261bc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/SigninFirstRunFragment.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/SigninFirstRunFragment.java
@@ -18,6 +18,10 @@ /** A {@link Fragment} to handle sign-in within the first run experience. */ public class SigninFirstRunFragment extends SigninFragmentBase implements FirstRunFragment { + // Per-page parameters: + public static final String FORCE_SIGNIN_ACCOUNT_TO = "ForceSigninAccountTo"; + public static final String CHILD_ACCOUNT_STATUS = "ChildAccountStatus"; + private Bundle mArguments; // Every fragment must have a public default constructor. @@ -28,13 +32,12 @@ super.onAttach(context); Bundle freProperties = getPageDelegate().getProperties(); - String forceAccountTo = - freProperties.getString(AccountFirstRunFragment.FORCE_SIGNIN_ACCOUNT_TO); + String forceAccountTo = freProperties.getString(FORCE_SIGNIN_ACCOUNT_TO); if (forceAccountTo == null) { mArguments = createArguments(null); } else { - @ChildAccountStatus.Status int childAccountStatus = - freProperties.getInt(AccountFirstRunFragment.CHILD_ACCOUNT_STATUS); + @ChildAccountStatus.Status + int childAccountStatus = freProperties.getInt(CHILD_ACCOUNT_STATUS); mArguments = createArgumentsForForcedSigninFlow(forceAccountTo, childAccountStatus); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ToSAndUMAFirstRunFragment.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ToSAndUMAFirstRunFragment.java index 563c5d9..929c5910 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ToSAndUMAFirstRunFragment.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ToSAndUMAFirstRunFragment.java
@@ -114,7 +114,7 @@ Bundle freProperties = getPageDelegate().getProperties(); @ChildAccountStatus.Status int childAccountStatus = freProperties.getInt( - AccountFirstRunFragment.CHILD_ACCOUNT_STATUS, ChildAccountStatus.NOT_CHILD); + SigninFirstRunFragment.CHILD_ACCOUNT_STATUS, ChildAccountStatus.NOT_CHILD); if (childAccountStatus == ChildAccountStatus.REGULAR_CHILD) { tosAndPrivacyText = SpanApplier.applySpans(getString(R.string.fre_tos_and_privacy_child_account),
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/BrowserControlsOffsetHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/BrowserControlsOffsetHelper.java deleted file mode 100644 index 628c563..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/BrowserControlsOffsetHelper.java +++ /dev/null
@@ -1,248 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.fullscreen; - -import android.animation.Animator; -import android.animation.AnimatorListenerAdapter; -import android.animation.ValueAnimator; - -import org.chromium.base.Supplier; -import org.chromium.chrome.browser.ActivityTabProvider; -import org.chromium.chrome.browser.ActivityTabProvider.ActivityTabTabObserver; -import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; -import org.chromium.chrome.browser.lifecycle.Destroyable; -import org.chromium.chrome.browser.tab.SadTab; -import org.chromium.chrome.browser.tab.Tab; -import org.chromium.chrome.browser.tab.TabBrowserControlsState; -import org.chromium.chrome.browser.tabmodel.TabModelImpl; -import org.chromium.chrome.browser.vr.VrModeObserver; -import org.chromium.chrome.browser.vr.VrModuleProvider; - -/** - * Handles browser controls offset. - */ -public class BrowserControlsOffsetHelper implements VrModeObserver, Destroyable { - /** - * Maximum duration for the control container slide-in animation. Note that this value matches - * the one in browser_controls_offset_manager.cc. - */ - private static final int MAX_CONTROLS_ANIMATION_DURATION_MS = 200; - - /** Observes active tab. */ - private final ActivityTabTabObserver mTabObserver; - - /* Provides {@link FullscreenManager} lazily when actually used. */ - private final Supplier<FullscreenManager> mFullscreenManager; - - /** Active tab in the foreground. */ - private Tab mTab; - - /** The animator for slide-in animation on the Android controls. */ - private ValueAnimator mControlsAnimator; - - /** Whether the browser is currently in VR mode. */ - private boolean mIsInVr; - - /** - * Indicates if control offset is in the overridden state by animation. Stays {@code true} - * from animation start till the next offset update from compositor arrives. - */ - private boolean mOffsetOverridden; - - public BrowserControlsOffsetHelper(ActivityLifecycleDispatcher lifecycleDispatcher, - ActivityTabProvider activityTabProvider, - Supplier<FullscreenManager> fullscreenManager) { - mFullscreenManager = fullscreenManager; - mTab = activityTabProvider.get(); - mTabObserver = new ActivityTabTabObserver(activityTabProvider) { - @Override - protected void onObservingDifferentTab(Tab tab) { - // Got into a state where there's no active tab (e.g. tab switcher). Wait till the - // next non-null active tab is set for any update. - if (tab == null) return; - mTab = tab; - restorePositions(); - } - - @Override - public void onCrash(Tab tab) { - if (SadTab.isShowing(tab)) showAndroidControls(false); - } - - @Override - public void onRendererResponsiveStateChanged(Tab tab, boolean isResponsive) { - if (!isResponsive) showAndroidControls(false); - } - - @Override - public void onBrowserControlsOffsetChanged( - int topControlsOffset, int bottomControlsOffset, int contentOffset) { - onOffsetsChanged(topControlsOffset, bottomControlsOffset, contentOffset); - } - }; - - VrModuleProvider.registerVrModeObserver(this); - if (VrModuleProvider.getDelegate().isInVr()) onEnterVr(); - lifecycleDispatcher.register(this); - } - - /** - * Called when offset values related with fullscreen functionality has been changed by the - * compositor. - * @param topControlsOffsetY The Y offset of the top controls in physical pixels. - * @param bottomControlsOffsetY The Y offset of the bottom controls in physical pixels. - * @param contentOffsetY The Y offset of the content in physical pixels. - */ - private void onOffsetsChanged( - int topControlsOffsetY, int bottomControlsOffsetY, int contentOffsetY) { - // Cancel any animation on the Android controls and let compositor drive the offset updates. - resetControlsOffsetOverridden(); - - if (SadTab.isShowing(mTab) || mTab.isNativePage()) { - showAndroidControls(false); - } else { - updateFullscreenManagerOffsets( - false, topControlsOffsetY, bottomControlsOffsetY, contentOffsetY); - } - TabModelImpl.setActualTabSwitchLatencyMetricRequired(); - } - - /** - * Shows the Android browser controls view. - * @param animate Whether a slide-in animation should be run. - */ - public void showAndroidControls(boolean animate) { - if (animate) { - runBrowserDrivenShowAnimation(); - } else { - updateFullscreenManagerOffsets(true, 0, 0, mFullscreenManager.get().getContentOffset()); - } - } - - /** - * Restores the controls positions to the cached positions of the active Tab. - */ - private void restorePositions() { - resetControlsOffsetOverridden(); - - // Make sure the dominant control offsets have been set. - TabBrowserControlsState controlState = TabBrowserControlsState.get(mTab); - if (controlState.offsetInitialized()) { - updateFullscreenManagerOffsets(false, controlState.topControlsOffset(), - controlState.bottomControlsOffset(), controlState.contentOffset()); - } else { - showAndroidControls(false); - } - TabBrowserControlsState.updateEnabledState(mTab); - } - - /** - * Helper method to update offsets in {@link FullscreenManager} and notify offset changes to - * observers if necessary. - */ - private void updateFullscreenManagerOffsets(boolean toNonFullscreen, int topControlsOffset, - int bottomControlsOffset, int topContentOffset) { - FullscreenManager manager = mFullscreenManager.get(); - if (mIsInVr) { - VrModuleProvider.getDelegate().rawTopContentOffsetChanged(topContentOffset); - // The dip scale of java UI and WebContents are different while in VR, leading to a - // mismatch in size in pixels when converting from dips. Since we hide the controls in - // VR anyways, just set the offsets to what they're supposed to be with the controls - // hidden. - // TODO(mthiesse): Should we instead just set the top controls height to be 0 while in - // VR? - topControlsOffset = -manager.getTopControlsHeight(); - bottomControlsOffset = manager.getBottomControlsHeight(); - topContentOffset = 0; - manager.setPositionsForTab(topControlsOffset, bottomControlsOffset, topContentOffset); - } else if (toNonFullscreen) { - manager.setPositionsForTabToNonFullscreen(); - } else { - manager.setPositionsForTab(topControlsOffset, bottomControlsOffset, topContentOffset); - } - } - - /** @return {@code true} if browser control offset is overridden by animation. */ - public boolean offsetOverridden() { - return mOffsetOverridden; - } - - /** - * Sets the flat indicating if browser control offset is overridden by animation. - * @param flag Boolean flag of the new offset overridden state. - */ - private void setOffsetOverridden(boolean flag) { - mOffsetOverridden = flag; - } - - /** - * Helper method to cancel overridden offset on Android browser controls. - */ - private void resetControlsOffsetOverridden() { - if (!offsetOverridden()) return; - if (mControlsAnimator != null) mControlsAnimator.cancel(); - setOffsetOverridden(false); - } - - /** - * Helper method to run slide-in animations on the Android browser controls views. - */ - private void runBrowserDrivenShowAnimation() { - if (mControlsAnimator != null) return; - - TabBrowserControlsState controlState = TabBrowserControlsState.get(mTab); - setOffsetOverridden(true); - - final FullscreenManager manager = mFullscreenManager.get(); - final float hiddenRatio = manager.getBrowserControlHiddenRatio(); - final int topControlHeight = manager.getTopControlsHeight(); - final int topControlOffset = manager.getTopControlOffset(); - - // Set animation start value to current renderer controls offset. - mControlsAnimator = ValueAnimator.ofInt(topControlOffset, 0); - mControlsAnimator.setDuration( - (long) Math.abs(hiddenRatio * MAX_CONTROLS_ANIMATION_DURATION_MS)); - mControlsAnimator.addListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - mControlsAnimator = null; - } - - @Override - public void onAnimationCancel(Animator animation) { - updateFullscreenManagerOffsets(false, topControlHeight, 0, topControlHeight); - } - }); - mControlsAnimator.addUpdateListener((animator) -> { - updateFullscreenManagerOffsets( - false, (int) animator.getAnimatedValue(), 0, topControlHeight); - }); - mControlsAnimator.start(); - } - - @Override - public void onEnterVr() { - mIsInVr = true; - restorePositions(); - } - - @Override - public void onExitVr() { - mIsInVr = false; - - // Clear the VR-specific overrides for controls height. - restorePositions(); - - // Show the Controls explicitly because under some situations, like when we're showing a - // Native Page, the renderer won't send any new offsets. - showAndroidControls(false); - } - - @Override - public void destroy() { - VrModuleProvider.unregisterVrModeObserver(this); - mTabObserver.destroy(); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/ChromeFullscreenManager.java b/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/ChromeFullscreenManager.java index c0ff078..6fb0d3cf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/ChromeFullscreenManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/ChromeFullscreenManager.java
@@ -4,6 +4,9 @@ package org.chromium.chrome.browser.fullscreen; +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ValueAnimator; import android.app.Activity; import android.support.annotation.IntDef; import android.support.annotation.Nullable; @@ -18,23 +21,25 @@ import org.chromium.base.ApplicationStatus; import org.chromium.base.ApplicationStatus.ActivityStateListener; import org.chromium.base.ApplicationStatus.WindowFocusChangedListener; -import org.chromium.base.Supplier; import org.chromium.base.TraceEvent; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.fullscreen.FullscreenHtmlApiHandler.FullscreenHtmlApiDelegate; import org.chromium.chrome.browser.tab.BrowserControlsVisibilityDelegate; +import org.chromium.chrome.browser.tab.SadTab; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.Tab.TabHidingType; import org.chromium.chrome.browser.tab.TabAttributeKeys; import org.chromium.chrome.browser.tab.TabAttributes; import org.chromium.chrome.browser.tab.TabBrowserControlsState; +import org.chromium.chrome.browser.tabmodel.TabModelImpl; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.TabModelSelectorTabModelObserver; import org.chromium.chrome.browser.tabmodel.TabModelSelectorTabObserver; import org.chromium.chrome.browser.tabmodel.TabSelectionType; import org.chromium.chrome.browser.util.FeatureUtilities; +import org.chromium.chrome.browser.vr.VrModeObserver; import org.chromium.chrome.browser.vr.VrModuleProvider; import org.chromium.chrome.browser.widget.ControlContainer; import org.chromium.components.embedder_support.view.ContentView; @@ -53,18 +58,24 @@ */ public class ChromeFullscreenManager extends FullscreenManager implements ActivityStateListener, WindowFocusChangedListener, - ViewGroup.OnHierarchyChangeListener, View.OnSystemUiVisibilityChangeListener { + ViewGroup.OnHierarchyChangeListener, View.OnSystemUiVisibilityChangeListener, + VrModeObserver { // The amount of time to delay the control show request after returning to a once visible // activity. This delay is meant to allow Android to run its Activity focusing animation and // have the controls scroll back in smoothly once that has finished. private static final long ACTIVITY_RETURN_SHOW_REQUEST_DELAY_MS = 100; + /** + * Maximum duration for the control container slide-in animation. Note that this value matches + * the one in browser_controls_offset_manager.cc. + */ + private static final int MAX_CONTROLS_ANIMATION_DURATION_MS = 200; + private final Activity mActivity; private final BrowserStateBrowserControlsVisibilityDelegate mBrowserVisibilityDelegate; @ControlsPosition private final int mControlsPosition; private final boolean mExitFullscreenOnStop; private final TokenHolder mHidingTokenHolder = new TokenHolder(this::scheduleVisibilityUpdate); - private final Supplier<BrowserControlsOffsetHelper> mControlsOffsetHelper; private TabModelSelectorTabObserver mTabFullscreenObserver; @Nullable private ControlContainer mControlContainer; @@ -91,6 +102,15 @@ private final ArrayList<FullscreenListener> mListeners = new ArrayList<>(); + /** The animator for slide-in animation on the Android controls. */ + private ValueAnimator mControlsAnimator; + + /** + * Indicates if control offset is in the overridden state by animation. Stays {@code true} + * from animation start till the next offset update from compositor arrives. + */ + private boolean mOffsetOverridden; + @IntDef({ControlsPosition.TOP, ControlsPosition.NONE}) @Retention(RetentionPolicy.SOURCE) public @interface ControlsPosition { @@ -161,31 +181,25 @@ /** * Creates an instance of the fullscreen mode manager. * @param activity The activity that supports fullscreen. - * @param controlsOffsetHelper Supplies {@link BrowserControlsOffsetHelper}. * @param controlsPosition Where the browser controls are. */ - public ChromeFullscreenManager(Activity activity, - Supplier<BrowserControlsOffsetHelper> controlsOffsetHelper, - @ControlsPosition int controlsPosition) { - this(activity, controlsOffsetHelper, controlsPosition, true); + public ChromeFullscreenManager(Activity activity, @ControlsPosition int controlsPosition) { + this(activity, controlsPosition, true); } /** * Creates an instance of the fullscreen mode manager. * @param activity The activity that supports fullscreen. - * @param controlsOffsetHelper Supplies {@link BrowserControlsOffsetHelper}. * @param controlsPosition Where the browser controls are. * @param exitFullscreenOnStop Whether fullscreen mode should exit on stop - should be * true for Activities that are not always fullscreen. */ public ChromeFullscreenManager(Activity activity, - Supplier<BrowserControlsOffsetHelper> controlsOffsetHelper, @ControlsPosition int controlsPosition, boolean exitFullscreenOnStop) { super(activity.getWindow()); mActivity = activity; mControlsPosition = controlsPosition; - mControlsOffsetHelper = controlsOffsetHelper; mExitFullscreenOnStop = exitFullscreenOnStop; mBrowserVisibilityDelegate = new BrowserStateBrowserControlsVisibilityDelegate(new Runnable() { @@ -198,6 +212,8 @@ } } }, this::getPersistentFullscreenMode); + VrModuleProvider.registerVrModeObserver(this); + if (isInVr()) onEnterVr(); } /** @@ -212,6 +228,7 @@ ApplicationStatus.registerStateListenerForActivity(this, mActivity); ApplicationStatus.registerWindowFocusChangedListener(this); + // TODO(crbug.com/978941): Consider switching to ActivityTabTabProvider. mTabModelObserver = new TabModelSelectorTabModelObserver(modelSelector) { @Override public void tabClosureCommitted(Tab tab) { @@ -308,6 +325,24 @@ SelectionPopupController.fromWebContents(webContents).destroySelectActionMode(); } } + + @Override + public void onCrash(Tab tab) { + if (tab == getTab() && SadTab.isShowing(tab)) showAndroidControls(false); + } + + @Override + public void onRendererResponsiveStateChanged(Tab tab, boolean isResponsive) { + if (tab == getTab() && !isResponsive) showAndroidControls(false); + } + + @Override + public void onBrowserControlsOffsetChanged( + Tab tab, int topControlsOffset, int bottomControlsOffset, int contentOffset) { + if (tab == getTab()) { + onOffsetsChanged(topControlsOffset, bottomControlsOffset, contentOffset); + } + } }; assert controlContainer != null || mControlsPosition == ControlsPosition.NONE; mControlContainer = controlContainer; @@ -350,6 +385,7 @@ mBrowserVisibilityDelegate.showControlsTransient(); updateMultiTouchZoomSupport(!getPersistentFullscreenMode()); TabGestureStateListener.from(tab).setFullscreenManager(this); + restoreControlsPositions(); } } @@ -435,8 +471,7 @@ // The toast tells user how to leave fullscreen by touching the screen. Since, // there is no touchscreen when browsing in VR, the toast doesn't have any useful // information. - return !isOverlayVideoMode() && !VrModuleProvider.getDelegate().isInVr() - && !VrModuleProvider.getDelegate().bootsToVr() + return !isOverlayVideoMode() && !isInVr() && !bootsToVr() && !FeatureUtilities.isNoTouchModeEnabled(); } }; @@ -709,7 +744,7 @@ Tab tab = getTab(); if (tab != null) { if (tab.isInitialized()) { - if (mControlsOffsetHelper.get().offsetOverridden()) return true; + if (offsetOverridden()) return true; } else { assert false : "Accessing a destroyed tab, setTab should have been called"; } @@ -832,6 +867,169 @@ if (!scrolling) updateVisuals(); } + /** + * Called when offset values related with fullscreen functionality has been changed by the + * compositor. + * @param topControlsOffsetY The Y offset of the top controls in physical pixels. + * @param bottomControlsOffsetY The Y offset of the bottom controls in physical pixels. + * @param contentOffsetY The Y offset of the content in physical pixels. + */ + private void onOffsetsChanged( + int topControlsOffsetY, int bottomControlsOffsetY, int contentOffsetY) { + // Cancel any animation on the Android controls and let compositor drive the offset updates. + resetControlsOffsetOverridden(); + + Tab tab = getTab(); + if (SadTab.isShowing(tab) || tab.isNativePage()) { + showAndroidControls(false); + } else { + updateFullscreenManagerOffsets( + false, topControlsOffsetY, bottomControlsOffsetY, contentOffsetY); + } + TabModelImpl.setActualTabSwitchLatencyMetricRequired(); + } + + /** + * Shows the Android browser controls view. + * @param animate Whether a slide-in animation should be run. + */ + public void showAndroidControls(boolean animate) { + if (animate) { + runBrowserDrivenShowAnimation(); + } else { + updateFullscreenManagerOffsets(true, 0, 0, getContentOffset()); + } + } + + /** + * Restores the controls positions to the cached positions of the active Tab. + */ + private void restoreControlsPositions() { + resetControlsOffsetOverridden(); + + // Make sure the dominant control offsets have been set. + Tab tab = getTab(); + TabBrowserControlsState controlState = TabBrowserControlsState.get(tab); + if (controlState.offsetInitialized()) { + updateFullscreenManagerOffsets(false, controlState.topControlsOffset(), + controlState.bottomControlsOffset(), controlState.contentOffset()); + } else { + showAndroidControls(false); + } + TabBrowserControlsState.updateEnabledState(tab); + } + + /** + * Helper method to update offsets in {@link FullscreenManager} and notify offset changes to + * observers if necessary. + */ + private void updateFullscreenManagerOffsets(boolean toNonFullscreen, int topControlsOffset, + int bottomControlsOffset, int topContentOffset) { + if (isInVr()) { + rawTopContentOffsetChangedForVr(topContentOffset); + // The dip scale of java UI and WebContents are different while in VR, leading to a + // mismatch in size in pixels when converting from dips. Since we hide the controls in + // VR anyways, just set the offsets to what they're supposed to be with the controls + // hidden. + // TODO(mthiesse): Should we instead just set the top controls height to be 0 while in + // VR? + topControlsOffset = -getTopControlsHeight(); + bottomControlsOffset = getBottomControlsHeight(); + topContentOffset = 0; + setPositionsForTab(topControlsOffset, bottomControlsOffset, topContentOffset); + } else if (toNonFullscreen) { + setPositionsForTabToNonFullscreen(); + } else { + setPositionsForTab(topControlsOffset, bottomControlsOffset, topContentOffset); + } + } + + /** @return {@code true} if browser control offset is overridden by animation. */ + public boolean offsetOverridden() { + return mOffsetOverridden; + } + + /** + * Sets the flat indicating if browser control offset is overridden by animation. + * @param flag Boolean flag of the new offset overridden state. + */ + private void setOffsetOverridden(boolean flag) { + mOffsetOverridden = flag; + } + + /** + * Helper method to cancel overridden offset on Android browser controls. + */ + private void resetControlsOffsetOverridden() { + if (!offsetOverridden()) return; + if (mControlsAnimator != null) mControlsAnimator.cancel(); + setOffsetOverridden(false); + } + + /** + * Helper method to run slide-in animations on the Android browser controls views. + */ + private void runBrowserDrivenShowAnimation() { + if (mControlsAnimator != null) return; + + TabBrowserControlsState controlState = TabBrowserControlsState.get(getTab()); + setOffsetOverridden(true); + + final float hiddenRatio = getBrowserControlHiddenRatio(); + final int topControlHeight = getTopControlsHeight(); + final int topControlOffset = getTopControlOffset(); + + // Set animation start value to current renderer controls offset. + mControlsAnimator = ValueAnimator.ofInt(topControlOffset, 0); + mControlsAnimator.setDuration( + (long) Math.abs(hiddenRatio * MAX_CONTROLS_ANIMATION_DURATION_MS)); + mControlsAnimator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + mControlsAnimator = null; + } + + @Override + public void onAnimationCancel(Animator animation) { + updateFullscreenManagerOffsets(false, topControlHeight, 0, topControlHeight); + } + }); + mControlsAnimator.addUpdateListener((animator) -> { + updateFullscreenManagerOffsets( + false, (int) animator.getAnimatedValue(), 0, topControlHeight); + }); + mControlsAnimator.start(); + } + + // VR-related methods to make this class test-friendly. These are overridden in unit tests. + + protected boolean isInVr() { + return VrModuleProvider.getDelegate().isInVr(); + } + + protected boolean bootsToVr() { + return VrModuleProvider.getDelegate().bootsToVr(); + } + + protected void rawTopContentOffsetChangedForVr(int topContentOffset) { + VrModuleProvider.getDelegate().rawTopContentOffsetChanged(topContentOffset); + } + + @Override + public void onEnterVr() { + restoreControlsPositions(); + } + + @Override + public void onExitVr() { + // Clear the VR-specific overrides for controls height. + restoreControlsPositions(); + + // Show the Controls explicitly because under some situations, like when we're showing a + // Native Page, the renderer won't send any new offsets. + showAndroidControls(false); + } + @Override public void destroy() { super.destroy(); @@ -841,5 +1039,6 @@ mContentView.removeOnHierarchyChangeListener(this); mContentView.removeOnSystemUiVisibilityChangeListener(this); } + VrModuleProvider.unregisterVrModeObserver(this); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/SideSlideLayout.java b/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/SideSlideLayout.java index a1f71f5..a89200c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/SideSlideLayout.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/SideSlideLayout.java
@@ -20,6 +20,7 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.R; +import org.chromium.chrome.browser.ChromeFeatureList; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -34,6 +35,8 @@ * and modified accordingly to support horizontal gesture. */ public class SideSlideLayout extends ViewGroup { + private static final String NAVIGATION_SHEET_ENABLED_KEY = + "overscroll_history_navigation_bottom_sheet"; // Used to record the UMA histogram Overscroll.* This definition should be // in sync with that in content/browser/web_contents/aura/types.h // TODO(jinsukkim): Generate java enum from the native header. @@ -171,6 +174,12 @@ mTotalDragDistance = TARGET_THRESHOLD_DP * density; } + private static boolean isBottomSheetEnabled() { + return ChromeFeatureList.getFieldTrialParamByFeatureAsBoolean( + ChromeFeatureList.OVERSCROLL_HISTORY_NAVIGATION, NAVIGATION_SHEET_ENABLED_KEY, + false); + } + /** * Set the listener to be notified when the navigation is triggered. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/modaldialog/TabModalLifetimeHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/modaldialog/TabModalLifetimeHandler.java index c4ad17d..d84eb0b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/modaldialog/TabModalLifetimeHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/modaldialog/TabModalLifetimeHandler.java
@@ -4,9 +4,7 @@ package org.chromium.chrome.browser.modaldialog; -import org.chromium.base.Supplier; import org.chromium.chrome.browser.ChromeActivity; -import org.chromium.chrome.browser.fullscreen.BrowserControlsOffsetHelper; import org.chromium.chrome.browser.lifecycle.Destroyable; import org.chromium.chrome.browser.lifecycle.NativeInitObserver; import org.chromium.chrome.browser.tab.EmptyTabObserver; @@ -43,7 +41,6 @@ private final ChromeActivity mActivity; private final ModalDialogManager mManager; - private final Supplier<BrowserControlsOffsetHelper> mControlsOffsetHelper; private TabModalPresenter mPresenter; private TabModelSelectorTabModelObserver mTabModelObserver; private boolean mHasBottomControls; @@ -52,13 +49,10 @@ /** * @param activity The {@link ChromeActivity} that this handler is attached to. * @param manager The {@link ModalDialogManager} that this handler handles. - * @param controlsOffsetHelper Supplies {@link BrowserControlsOffsetHelper}. */ - public TabModalLifetimeHandler(ChromeActivity activity, ModalDialogManager manager, - Supplier<BrowserControlsOffsetHelper> controlsOffsetHelper) { + public TabModalLifetimeHandler(ChromeActivity activity, ModalDialogManager manager) { mActivity = activity; mManager = manager; - mControlsOffsetHelper = controlsOffsetHelper; activity.getLifecycleDispatcher().register(this); } @@ -86,7 +80,7 @@ @Override public void onFinishNativeInitialization() { - mPresenter = new TabModalPresenter(mActivity, mControlsOffsetHelper); + mPresenter = new TabModalPresenter(mActivity); mManager.registerPresenter(mPresenter, ModalDialogType.TAB); mHasBottomControls = mActivity.getBottomSheet() != null;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/modaldialog/TabModalPresenter.java b/chrome/android/java/src/org/chromium/chrome/browser/modaldialog/TabModalPresenter.java index 1f114829..41578266 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/modaldialog/TabModalPresenter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/modaldialog/TabModalPresenter.java
@@ -16,13 +16,11 @@ import android.view.ViewStub; import android.widget.FrameLayout; -import org.chromium.base.Supplier; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel; import org.chromium.chrome.browser.contextualsearch.ContextualSearchManager; -import org.chromium.chrome.browser.fullscreen.BrowserControlsOffsetHelper; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabAttributeKeys; @@ -50,8 +48,6 @@ /** The activity displaying the dialogs. */ private final ChromeActivity mChromeActivity; - private final Supplier<BrowserControlsOffsetHelper> mControlsOffsetHelper; - /** The active tab of which the dialog will be shown on top. */ private Tab mActiveTab; @@ -114,12 +110,9 @@ /** * Constructor for initializing dialog container. * @param chromeActivity The activity displaying the dialogs. - * @param controlsOffsetHelper Supplies {@link BrowserControlsOffsetHelper}. */ - public TabModalPresenter(ChromeActivity chromeActivity, - Supplier<BrowserControlsOffsetHelper> controlsOffsetHelper) { + public TabModalPresenter(ChromeActivity chromeActivity) { mChromeActivity = chromeActivity; - mControlsOffsetHelper = controlsOffsetHelper; mEnterExitAnimationDurationMs = ENTER_EXIT_ANIMATION_DURATION_MS; mChromeFullscreenManager = mChromeActivity.getFullscreenManager(); mChromeFullscreenManager.addListener(this); @@ -351,10 +344,10 @@ // Also need to update browser control state after dismissal to refresh the constraints. if (isShowing && mActiveTab.areRendererInputEventsIgnored()) { - mControlsOffsetHelper.get().showAndroidControls(true); + mChromeFullscreenManager.showAndroidControls(true); } else { TabBrowserControlsState.update(mActiveTab, BrowserControlsState.SHOWN, - !mControlsOffsetHelper.get().offsetOverridden()); + !mChromeFullscreenManager.offsetOverridden()); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceManager.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceManager.java index a05c6dc3..e269ba6c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceManager.java
@@ -180,9 +180,9 @@ private static final String NTP_BUTTON_VARIANT_KEY = "ntp_button_variant"; /** - * Whether or not TabPersistentStore is using a TaskRunner instead of SERIAL_EXECUTOR. - * Default value is false. + * Deprecated in M77. This value may still exist in shared preferences file. Do not reuse. */ + @Deprecated public static final String TAB_PERSISTENT_STORE_TASK_RUNNER_ENABLED_KEY = "tab_persistent_store_task_runner_enabled";
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SignInPreference.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SignInPreference.java index af06866..2822bcf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SignInPreference.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/sync/SignInPreference.java
@@ -18,12 +18,12 @@ import org.chromium.chrome.browser.firstrun.FirstRunSignInProcessor; import org.chromium.chrome.browser.preferences.ChromePreferenceManager; import org.chromium.chrome.browser.preferences.ManagedPreferencesUtils; -import org.chromium.chrome.browser.signin.AccountSigninActivity; import org.chromium.chrome.browser.signin.DisplayableProfileData; import org.chromium.chrome.browser.signin.IdentityServicesProvider; import org.chromium.chrome.browser.signin.PersonalizedSigninPromoView; import org.chromium.chrome.browser.signin.ProfileDataCache; import org.chromium.chrome.browser.signin.SigninAccessPoint; +import org.chromium.chrome.browser.signin.SigninActivity; import org.chromium.chrome.browser.signin.SigninManager.SignInAllowedObserver; import org.chromium.chrome.browser.signin.SigninPromoController; import org.chromium.chrome.browser.signin.SigninPromoUtil; @@ -76,7 +76,7 @@ mProfileDataCache = new ProfileDataCache(context, imageSize); setOnPreferenceClickListener(preference - -> AccountSigninActivity.startIfAllowed(getContext(), SigninAccessPoint.SETTINGS)); + -> SigninActivity.startIfAllowed(getContext(), SigninAccessPoint.SETTINGS)); // State will be updated in registerForUpdates. mState = State.SIGNED_IN;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java deleted file mode 100644 index 5a1f30e..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java +++ /dev/null
@@ -1,283 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.signin; - -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.support.annotation.IntDef; - -import org.chromium.base.metrics.RecordHistogram; -import org.chromium.base.metrics.RecordUserAction; -import org.chromium.chrome.R; -import org.chromium.chrome.browser.SynchronousInitializationActivity; -import org.chromium.chrome.browser.preferences.ManagedPreferencesUtils; -import org.chromium.chrome.browser.preferences.PrefServiceBridge; -import org.chromium.chrome.browser.preferences.PreferencesLauncher; -import org.chromium.chrome.browser.preferences.sync.AccountManagementFragment; -import org.chromium.chrome.browser.signin.SigninManager.SignInCallback; -import org.chromium.components.signin.ChildAccountStatus; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * An Activity displayed from the MainPreferences to allow the user to pick an account to - * sign in to. The AccountSigninView.Delegate interface is fulfilled by the AppCompatActivity. - */ -public class AccountSigninActivity extends SynchronousInitializationActivity - implements AccountSigninView.Listener, AccountSigninView.Delegate { - private static final String TAG = "AccountSigninActivity"; - private static final String INTENT_IS_FROM_PERSONALIZED_PROMO = - "AccountSigninActivity.IsFromPersonalizedPromo"; - - @IntDef({SigninAccessPoint.SETTINGS, SigninAccessPoint.BOOKMARK_MANAGER, - SigninAccessPoint.RECENT_TABS, SigninAccessPoint.SIGNIN_PROMO, - SigninAccessPoint.NTP_CONTENT_SUGGESTIONS, SigninAccessPoint.AUTOFILL_DROPDOWN}) - @Retention(RetentionPolicy.SOURCE) - public @interface AccessPoint {} - - @IntDef({SwitchAccountSource.SIGNOUT_SIGNIN, SwitchAccountSource.SYNC_ACCOUNT_SWITCHER}) - @Retention(RetentionPolicy.SOURCE) - public @interface SwitchAccountSource { - int SIGNOUT_SIGNIN = 0; - int SYNC_ACCOUNT_SWITCHER = 1; - int NUM_ENTRIES = 2; - } - - private @AccessPoint int mAccessPoint; - private @AccountSigninView.SigninFlowType int mSigninFlowType; - private boolean mIsFromPersonalizedPromo; - - /** - * A convenience method to create a AccountSigninActivity passing the access point as an - * intent. Checks if the sign in flow can be started before showing the activity. - * @param accessPoint {@link AccessPoint} for starting signin flow. Used in metrics. - * @return {@code true} if sign in has been allowed. - */ - public static boolean startIfAllowed(Context context, @AccessPoint int accessPoint) { - SigninManager signinManager = IdentityServicesProvider.getSigninManager(); - if (!signinManager.isSignInAllowed()) { - if (signinManager.isSigninDisabledByPolicy()) { - ManagedPreferencesUtils.showManagedByAdministratorToast(context); - } - return false; - } - - context.startActivity(SigninActivity.createIntent(context, accessPoint)); - return true; - } - - /** - * Creates an {@link Intent} which can be used to start the default signin flow. - * @param accessPoint {@link AccessPoint} for starting signin flow. Used in metrics. - * @param isFromPersonalizedPromo Whether the signin activity is started from a personalized - * promo. - */ - public static Intent createIntentForDefaultSigninFlow( - Context context, @AccessPoint int accessPoint, boolean isFromPersonalizedPromo) { - Intent intent = new Intent(context, AccountSigninActivity.class); - Bundle viewArguments = AccountSigninView.createArgumentsForDefaultFlow( - accessPoint, ChildAccountStatus.NOT_CHILD); - intent.putExtras(viewArguments); - intent.putExtra(INTENT_IS_FROM_PERSONALIZED_PROMO, isFromPersonalizedPromo); - return intent; - } - - /** - * Creates an {@link Intent} which can be used to start the signin flow from the confirmation - * screen. - * @param accessPoint {@link AccessPoint} for starting signin flow. Used in metrics. - * @param selectAccount Account for which signin confirmation page should be shown. - * @param isDefaultAccount Whether {@param selectedAccount} is the default account on - * the device. Used in metrics. - * @param isFromPersonalizedPromo Whether the signin activity is started from a personalized - * promo. - */ - public static Intent createIntentForConfirmationOnlySigninFlow(Context context, - @AccessPoint int accessPoint, String selectAccount, boolean isDefaultAccount, - boolean isFromPersonalizedPromo) { - Intent intent = new Intent(context, AccountSigninActivity.class); - Bundle viewArguments = AccountSigninView.createArgumentsForConfirmationFlow(accessPoint, - ChildAccountStatus.NOT_CHILD, selectAccount, isDefaultAccount, - AccountSigninView.UndoBehavior.ABORT); - intent.putExtras(viewArguments); - intent.putExtra(INTENT_IS_FROM_PERSONALIZED_PROMO, isFromPersonalizedPromo); - return intent; - } - - /** - * Creates an {@link Intent} which can be used to start the signin flow from the "Add Account" - * page. - * @param accessPoint {@link AccessPoint} for starting signin flow. Used in metrics. - * @param isFromPersonalizedPromo Whether the signin activity is started from a personalized - * promo. - */ - public static Intent createIntentForAddAccountSigninFlow( - Context context, @AccessPoint int accessPoint, boolean isFromPersonalizedPromo) { - Intent intent = new Intent(context, AccountSigninActivity.class); - Bundle viewArguments = AccountSigninView.createArgumentsForAddAccountFlow(accessPoint); - intent.putExtras(viewArguments); - intent.putExtra(INTENT_IS_FROM_PERSONALIZED_PROMO, isFromPersonalizedPromo); - return intent; - } - - /** - * Records the flow that was used to switch sync accounts. - * @param source {@link SwitchAccountSource} that was used for switching accounts. - */ - public static void recordSwitchAccountSourceHistogram(@SwitchAccountSource int source) { - RecordHistogram.recordEnumeratedHistogram( - "Signin.SwitchSyncAccount.Source", source, SwitchAccountSource.NUM_ENTRIES); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - // We don't trust android to restore the saved state correctly, so pass null. - super.onCreate(null); - - AccountSigninView view = - (AccountSigninView) getLayoutInflater().inflate(R.layout.account_signin_view, null); - - view.init(getIntent().getExtras(), this, this); - - mAccessPoint = view.getSigninAccessPoint(); - assert mAccessPoint == SigninAccessPoint.BOOKMARK_MANAGER - || mAccessPoint == SigninAccessPoint.RECENT_TABS - || mAccessPoint == SigninAccessPoint.SETTINGS - || mAccessPoint == SigninAccessPoint.SIGNIN_PROMO - || mAccessPoint == SigninAccessPoint.NTP_CONTENT_SUGGESTIONS - || mAccessPoint == SigninAccessPoint.AUTOFILL_DROPDOWN - : "invalid access point: " + mAccessPoint; - - mSigninFlowType = view.getSigninFlowType(); - mIsFromPersonalizedPromo = - getIntent().getBooleanExtra(INTENT_IS_FROM_PERSONALIZED_PROMO, false); - - setContentView(view); - - SigninManager.logSigninStartAccessPoint(mAccessPoint); - recordSigninStartedHistogramAccountInfo(); - recordSigninStartedUserAction(); - } - - @Override - public void onAccountSelectionCanceled() { - finish(); - } - - @Override - public void onNewAccount() { - AccountAdder.getInstance().addAccount(this, AccountAdder.ADD_ACCOUNT_RESULT); - } - - @Override - public void onAccountSelected( - final String accountName, boolean isDefaultAccount, final boolean settingsClicked) { - if (PrefServiceBridge.getInstance().getSyncLastAccountName() != null) { - recordSwitchAccountSourceHistogram(SwitchAccountSource.SIGNOUT_SIGNIN); - } - - final Context context = this; - IdentityServicesProvider.getSigninManager().signIn(accountName, this, new SignInCallback() { - @Override - public void onSignInComplete() { - if (settingsClicked) { - PreferencesLauncher.launchSettingsPage( - context, AccountManagementFragment.class); - } - - recordSigninCompletedHistogramAccountInfo(); - finish(); - } - - @Override - public void onSignInAborted() {} - }); - } - - @Override - public void onFailedToSetForcedAccount(String forcedAccountName) {} - - private void recordSigninCompletedHistogramAccountInfo() { - if (!mIsFromPersonalizedPromo) { - return; - } - - final String histogram; - switch (mSigninFlowType) { - case AccountSigninView.SigninFlowType.ADD_NEW_ACCOUNT: - histogram = "Signin.SigninCompletedAccessPoint.NewAccountNoExistingAccount"; - break; - case AccountSigninView.SigninFlowType.CONFIRMATION_ONLY: - histogram = "Signin.SigninCompletedAccessPoint.WithDefault"; - break; - case AccountSigninView.SigninFlowType.DEFAULT: - histogram = "Signin.SigninCompletedAccessPoint.NotDefault"; - break; - default: - assert false : "Unexpected signin flow type!"; - return; - } - - RecordHistogram.recordEnumeratedHistogram(histogram, mAccessPoint, SigninAccessPoint.MAX); - } - - private void recordSigninStartedHistogramAccountInfo() { - if (!mIsFromPersonalizedPromo) { - return; - } - - final String histogram; - switch (mSigninFlowType) { - case AccountSigninView.SigninFlowType.ADD_NEW_ACCOUNT: - histogram = "Signin.SigninStartedAccessPoint.NewAccountNoExistingAccount"; - break; - case AccountSigninView.SigninFlowType.CONFIRMATION_ONLY: - histogram = "Signin.SigninStartedAccessPoint.WithDefault"; - break; - case AccountSigninView.SigninFlowType.DEFAULT: - histogram = "Signin.SigninStartedAccessPoint.NotDefault"; - break; - default: - assert false : "Unexpected signin flow type!"; - return; - } - - RecordHistogram.recordEnumeratedHistogram(histogram, mAccessPoint, SigninAccessPoint.MAX); - } - - private void recordSigninStartedUserAction() { - switch (mAccessPoint) { - case SigninAccessPoint.AUTOFILL_DROPDOWN: - RecordUserAction.record("Signin_Signin_FromAutofillDropdown"); - break; - case SigninAccessPoint.BOOKMARK_MANAGER: - RecordUserAction.record("Signin_Signin_FromBookmarkManager"); - break; - case SigninAccessPoint.RECENT_TABS: - RecordUserAction.record("Signin_Signin_FromRecentTabs"); - break; - case SigninAccessPoint.SETTINGS: - RecordUserAction.record("Signin_Signin_FromSettings"); - break; - case SigninAccessPoint.SIGNIN_PROMO: - RecordUserAction.record("Signin_Signin_FromSigninPromo"); - break; - case SigninAccessPoint.NTP_CONTENT_SUGGESTIONS: - RecordUserAction.record("Signin_Signin_FromNTPContentSuggestions"); - break; - default: - assert false : "Invalid access point."; - } - } - - // AccountSigninView.Delegate implementation. - @Override - public Activity getActivity() { - return this; - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninChooseView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninChooseView.java deleted file mode 100644 index be64dd1..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninChooseView.java +++ /dev/null
@@ -1,140 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.signin; - -import android.content.Context; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import org.chromium.chrome.R; -import org.chromium.chrome.browser.firstrun.FirstRunChooserView; - -import java.util.List; - -/** -* The view that allows the user to choose the sign in account. -*/ -public class AccountSigninChooseView extends FirstRunChooserView { - private final LayoutInflater mInflater; - private LinearLayout mRootChildView; - private int mAccountViewStartIndex; - private int mSelectedAccountPosition; - private Observer mObserver; - - /** - * Add new account observer. - */ - public interface Observer { - /** - * On add new account clicked. - */ - void onAddNewAccount(); - } - - public AccountSigninChooseView(Context context, AttributeSet attrs) { - super(context, attrs); - mInflater = LayoutInflater.from(context); - } - - @Override - protected void onFinishInflate() { - super.onFinishInflate(); - mRootChildView = findViewById(R.id.account_signin_choose_view_root_child_view); - mAccountViewStartIndex = mRootChildView.getChildCount(); - } - - /** - * Updates candidate accounts to sign in. - * - * @param accounts The candidate accounts. - * @param accountToSelect The index of the default selected account to sign in. - * @param profileDataCache The ProfileDataCache contains accounts' info. - */ - public void updateAccounts( - List<String> accounts, int accountToSelect, ProfileDataCache profileDataCache) { - mRootChildView.removeViews( - mAccountViewStartIndex, mRootChildView.getChildCount() - mAccountViewStartIndex); - if (accounts.isEmpty()) return; - - // Add accounts view. - for (int i = 0; i < accounts.size(); i++) { - View view = - mInflater.inflate(R.layout.account_signin_account_view, mRootChildView, false); - - // Sets account profile image and name. - String accountName = accounts.get(i); - ((ImageView) view.findViewById(R.id.account_image)) - .setImageDrawable( - profileDataCache.getProfileDataOrDefault(accountName).getImage()); - ((TextView) view.findViewById(R.id.account_name)).setText(accountName); - - view.setOnClickListener((View v) -> { - int indexOfClickedAccount = mRootChildView.indexOfChild(v) - mAccountViewStartIndex; - if (indexOfClickedAccount == mSelectedAccountPosition) return; - mRootChildView.getChildAt(mSelectedAccountPosition + mAccountViewStartIndex) - .findViewById(R.id.account_selection_mark) - .setVisibility(View.GONE); - v.findViewById(R.id.account_selection_mark).setVisibility(View.VISIBLE); - mSelectedAccountPosition = indexOfClickedAccount; - }); - - mRootChildView.addView(view); - } - - // The view at the last position is the "Add account" view. - View view = mInflater.inflate(R.layout.account_signin_account_view, mRootChildView, false); - ((ImageView) view.findViewById(R.id.account_image)) - .setImageResource(R.drawable.ic_add_circle_40dp); - ((TextView) view.findViewById(R.id.account_name)) - .setText(getResources().getString(R.string.signin_add_account)); - view.setOnClickListener((View v) -> { - if (mObserver != null) mObserver.onAddNewAccount(); - }); - mRootChildView.addView(view); - - // Sets the default selected account selection status. - mRootChildView.getChildAt(accountToSelect + mAccountViewStartIndex) - .findViewById(R.id.account_selection_mark) - .setVisibility(View.VISIBLE); - mSelectedAccountPosition = accountToSelect; - } - - /** - * Updates candidate accounts' profile image. - * - * @param profileDataCache The ProfileDataCache contains accounts' profile image. - */ - public void updateAccountProfileImages(ProfileDataCache profileDataCache) { - // Do not update the last "Add account" view. - for (int i = mAccountViewStartIndex; i < mRootChildView.getChildCount() - 1; i++) { - View view = mRootChildView.getChildAt(i); - String accountEmail = - ((TextView) view.findViewById(R.id.account_name)).getText().toString(); - ((ImageView) view.findViewById(R.id.account_image)) - .setImageDrawable( - profileDataCache.getProfileDataOrDefault(accountEmail).getImage()); - } - } - - /** - * Sets add new account observer. See {@link Observer} - * - * @param observer The observer. - */ - public void setAddNewAccountObserver(Observer observer) { - mObserver = observer; - } - - /** - * Gets selected account position. - */ - public int getSelectedAccountPosition() { - return mSelectedAccountPosition; - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninConfirmationView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninConfirmationView.java deleted file mode 100644 index 45b3468..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninConfirmationView.java +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.signin; - -import android.content.Context; -import android.support.annotation.Nullable; -import android.util.AttributeSet; -import android.view.View; -import android.view.ViewTreeObserver; -import android.widget.LinearLayout; -import android.widget.ScrollView; - -import org.chromium.chrome.R; - -/** -* This view allows the user to confirm signed in account, sync, and service personalization. -*/ -public class AccountSigninConfirmationView extends ScrollView { - /** - * Scrolled to bottom observer. - */ - public interface Observer { - /** - * On scrolled to bottom. This won't be called more than once per one - * {@link AccountSigninConfirmationView#setObserver(Observer)} call. - */ - void onScrolledToBottom(); - } - - private Observer mObserver; - private ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener; - private ViewTreeObserver.OnScrollChangedListener mOnScrollChangedListener; - - public AccountSigninConfirmationView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - @Override - protected void onDetachedFromWindow() { - removeObservers(); - super.onDetachedFromWindow(); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - // This assumes that view's layout_width and layout_height are set to match_parent. - assert MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY; - assert MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; - - int width = MeasureSpec.getSize(widthMeasureSpec); - int height = MeasureSpec.getSize(heightMeasureSpec); - - View head = findViewById(R.id.signin_confirmation_head); - LinearLayout.LayoutParams headLayoutParams = - (LinearLayout.LayoutParams) head.getLayoutParams(); - View accountImage = findViewById(R.id.signin_account_image); - LinearLayout.LayoutParams accountImageLayoutParams = - (LinearLayout.LayoutParams) accountImage.getLayoutParams(); - if (height > width) { - // Sets aspect ratio of the head to 16:9. - headLayoutParams.height = width * 9 / 16; - accountImageLayoutParams.topMargin = 0; - } else { - headLayoutParams.height = LayoutParams.WRAP_CONTENT; - - // Adds top margin. - accountImageLayoutParams.topMargin = - getResources().getDimensionPixelOffset(R.dimen.signin_screen_top_padding); - } - head.setLayoutParams(headLayoutParams); - accountImage.setLayoutParams(accountImageLayoutParams); - - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - } - - @Override - protected float getTopFadingEdgeStrength() { - // Disable fading out effect at the top of this ScrollView. - return 0; - } - - private void checkScrolledToBottom() { - int distance = (getChildAt(getChildCount() - 1).getBottom() - (getHeight() + getScrollY())); - if (distance > findViewById(R.id.signin_settings_control).getPaddingBottom()) return; - - mObserver.onScrolledToBottom(); - removeObservers(); - } - - /** - * Sets observer. See {@link Observer}. Regardless of the passed value, notifications for - * the previous observer will be canceled. - * - * @param observer Instance that will receive notifications, or null to clear the observer. - */ - public void setObserver(@Nullable Observer observer) { - removeObservers(); - if (observer == null) return; - - mObserver = observer; - mOnGlobalLayoutListener = this::checkScrolledToBottom; - getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener); - mOnScrollChangedListener = this::checkScrolledToBottom; - getViewTreeObserver().addOnScrollChangedListener(mOnScrollChangedListener); - } - - private void removeObservers() { - if (mObserver == null) return; - mObserver = null; - getViewTreeObserver().removeOnGlobalLayoutListener(mOnGlobalLayoutListener); - mOnGlobalLayoutListener = null; - getViewTreeObserver().removeOnScrollChangedListener(mOnScrollChangedListener); - mOnScrollChangedListener = null; - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java deleted file mode 100644 index bc9daeed..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java +++ /dev/null
@@ -1,828 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.signin; - -import android.app.Activity; -import android.content.Context; -import android.os.Bundle; -import android.os.SystemClock; -import android.support.annotation.IntDef; -import android.support.annotation.StringRes; -import android.support.v4.app.FragmentManager; -import android.support.v4.view.ViewCompat; -import android.support.v7.app.AlertDialog; -import android.text.method.LinkMovementMethod; -import android.util.AttributeSet; -import android.view.View; -import android.widget.Button; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.TextView; - -import org.chromium.base.Log; -import org.chromium.base.metrics.RecordHistogram; -import org.chromium.base.metrics.RecordUserAction; -import org.chromium.base.task.AsyncTask; -import org.chromium.chrome.R; -import org.chromium.chrome.browser.consent_auditor.ConsentAuditorFeature; -import org.chromium.chrome.browser.externalauth.UserRecoverableErrorHandler; -import org.chromium.chrome.browser.preferences.PrefServiceBridge; -import org.chromium.chrome.browser.signin.ConfirmImportSyncDataDialog.ImportSyncType; -import org.chromium.chrome.browser.sync.SyncUserDataWiper; -import org.chromium.components.signin.AccountIdProvider; -import org.chromium.components.signin.AccountManagerDelegateException; -import org.chromium.components.signin.AccountManagerFacade; -import org.chromium.components.signin.AccountManagerResult; -import org.chromium.components.signin.AccountTrackerService; -import org.chromium.components.signin.AccountTrackerService.OnSystemAccountsSeededListener; -import org.chromium.components.signin.AccountsChangeObserver; -import org.chromium.components.signin.ChildAccountStatus; -import org.chromium.components.signin.GmsAvailabilityException; -import org.chromium.components.signin.GmsJustUpdatedException; -import org.chromium.ui.text.NoUnderlineClickableSpan; -import org.chromium.ui.text.SpanApplier; -import org.chromium.ui.text.SpanApplier.SpanInfo; -import org.chromium.ui.widget.ButtonCompat; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.util.Collections; -import java.util.List; - -/** - * This view allows the user to select an account to log in to, add an account, cancel account - * selection, etc. Users of this class should call {@link #init} after the view has been inflated. - */ -public class AccountSigninView extends FrameLayout { - /** - * Callbacks for various account selection events. - */ - public interface Listener { - /** - * The user canceled account selection. - */ - void onAccountSelectionCanceled(); - - /** - * The user wants to make a new account. - */ - void onNewAccount(); - - /** - * The user completed the View and selected an account. - * @param accountName The name of the account - * @param isDefaultAccount Whether selected account is a default one (first of all accounts) - * @param settingsClicked If true, user requested to see their sync settings, if false - * they just clicked Done. - */ - void onAccountSelected( - String accountName, boolean isDefaultAccount, boolean settingsClicked); - - /** - * Failed to set the forced account because it wasn't found. - * @param forcedAccountName The name of the forced-sign-in account - */ - void onFailedToSetForcedAccount(String forcedAccountName); - } - - /** - * Provides UI objects for new UI component creation. - */ - public interface Delegate { - /** - * Provides an Activity for the View to check GMSCore version. - */ - Activity getActivity(); - - /** - * Provides a FragmentManager for the View to create dialogs. This is done through a - * different mechanism than getActivity().getSupportFragmentManager() as a potential fix to - * https://crbug.com/646978 on the theory that getActivity() and getSupportFragmentManager() - * return null at different times. - */ - FragmentManager getSupportFragmentManager(); - } - - private static final String TAG = "AccountSigninView"; - - private static final String SETTINGS_LINK_OPEN = "<LINK1>"; - private static final String SETTINGS_LINK_CLOSE = "</LINK1>"; - - private static final String ARGUMENT_ACCESS_POINT = "AccountSigninView.AccessPoint"; - private static final String ARGUMENT_SIGNIN_FLOW_TYPE = "AccountSigninView.FlowType"; - private static final String ARGUMENT_ACCOUNT_NAME = "AccountSigninView.AccountName"; - private static final String ARGUMENT_IS_DEFAULT_ACCOUNT = "AccountSigninView.IsDefaultAccount"; - private static final String ARGUMENT_CHILD_ACCOUNT_STATUS = - "AccountSigninView.ChildAccountStatus"; - private static final String ARGUMENT_UNDO_BEHAVIOR = "AccountSigninView.UndoBehavior"; - - @IntDef({SigninFlowType.DEFAULT, SigninFlowType.CONFIRMATION_ONLY, - SigninFlowType.ADD_NEW_ACCOUNT}) - @Retention(RetentionPolicy.SOURCE) - public @interface SigninFlowType { - int DEFAULT = 0; - int CONFIRMATION_ONLY = 1; - int ADD_NEW_ACCOUNT = 2; - } - - /** Specifies different behaviors for "Undo" button on signin confirmation page. */ - @IntDef({UndoBehavior.INVISIBLE, UndoBehavior.BACK_TO_SELECTION, UndoBehavior.ABORT}) - @Retention(RetentionPolicy.SOURCE) - public @interface UndoBehavior { - /** "Undo" button is invisible. */ - int INVISIBLE = 0; - /** "Undo" button opens account selection page. */ - int BACK_TO_SELECTION = 1; - /** "Undo" button calls {@link Listener#onAccountSelectionCanceled()}. */ - int ABORT = 2; - } - - private final AccountsChangeObserver mAccountsChangedObserver; - private final ProfileDataCache.Observer mProfileDataCacheObserver; - private final ProfileDataCache mProfileDataCache; - private List<String> mAccountNames; - private AccountSigninChooseView mSigninChooseView; - private ButtonCompat mPositiveButton; - private Button mNegativeButton; - private Button mMoreButton; - private Listener mListener; - private Delegate mDelegate; - private @SigninAccessPoint int mSigninAccessPoint; - private @SigninFlowType int mSigninFlowType; - private @UndoBehavior int mUndoBehavior; - private String mSelectedAccountName; - private boolean mIsDefaultAccountSelected; - private @StringRes int mCancelButtonTextId = R.string.cancel; - private @ChildAccountStatus.Status int mChildAccountStatus; - private UserRecoverableErrorHandler.ModalDialog mGooglePlayServicesUpdateErrorHandler; - private AlertDialog mGmsIsUpdatingDialog; - private long mGmsIsUpdatingDialogShowTime; - private boolean mShouldShowConfirmationPageWhenAttachedToWindow; - - private AccountSigninConfirmationView mSigninConfirmationView; - private ImageView mSigninAccountImage; - private TextView mSigninAccountName; - private TextView mSigninAccountEmail; - private TextView mSigninSyncTitle; - private TextView mSigninSyncDescription; - private TextView mSigninPersonalizeServiceTitle; - private TextView mSigninPersonalizeServiceDescription; - private TextView mSigninSettingsControl; - private ConfirmSyncDataStateMachine mConfirmSyncDataStateMachine; - private ConsentTextTracker mConsentTextTracker; - - public AccountSigninView(Context context, AttributeSet attrs) { - super(context, attrs); - mAccountsChangedObserver = this::triggerUpdateAccounts; - mProfileDataCacheObserver = (String accountId) -> updateProfileData(); - mProfileDataCache = new ProfileDataCache(context, - context.getResources().getDimensionPixelSize(R.dimen.signin_account_image_size)); - mConsentTextTracker = new ConsentTextTracker(context.getResources()); - } - - /** - * Creates an argument bundle to start AccountSigninView from the account selection page. - * - * @param accessPoint The access point for starting signin flow. - * @param childAccountStatus Whether this view is for a child account and of what type. - */ - public static Bundle createArgumentsForDefaultFlow( - @SigninAccessPoint int accessPoint, @ChildAccountStatus.Status int childAccountStatus) { - Bundle result = new Bundle(); - result.putInt(ARGUMENT_SIGNIN_FLOW_TYPE, SigninFlowType.DEFAULT); - result.putInt(ARGUMENT_ACCESS_POINT, accessPoint); - result.putInt(ARGUMENT_CHILD_ACCOUNT_STATUS, childAccountStatus); - result.putInt(ARGUMENT_UNDO_BEHAVIOR, UndoBehavior.BACK_TO_SELECTION); - return result; - } - - /** - * Creates an argument bundle to start AccountSigninView from the new account creation screen. - * - * @param accessPoint The access point for starting signin flow. - */ - public static Bundle createArgumentsForAddAccountFlow(@SigninAccessPoint int accessPoint) { - Bundle result = new Bundle(); - result.putInt(ARGUMENT_SIGNIN_FLOW_TYPE, SigninFlowType.ADD_NEW_ACCOUNT); - result.putInt(ARGUMENT_ACCESS_POINT, accessPoint); - result.putInt(ARGUMENT_CHILD_ACCOUNT_STATUS, - ChildAccountStatus.NOT_CHILD); // Children profiles can't add accounts - result.putInt(ARGUMENT_UNDO_BEHAVIOR, UndoBehavior.ABORT); - return result; - } - - /** - * Creates an argument bundle to start AccountSigninView from the signin confirmation page. - * - * @param accessPoint The access point for starting signin flow. - * @param childAccountStatus Whether this view is for a child account and of what type. - * @param accountName An account that should be used for confirmation page and signin. - * @param isDefaultAccount Whether {@param accountName} is a default account, used for metrics. - * @param undoBehavior "Undo" button behavior (see {@link UndoBehavior}). - */ - public static Bundle createArgumentsForConfirmationFlow(@SigninAccessPoint int accessPoint, - @ChildAccountStatus.Status int childAccountStatus, String accountName, - boolean isDefaultAccount, @UndoBehavior int undoBehavior) { - Bundle result = new Bundle(); - result.putInt(ARGUMENT_SIGNIN_FLOW_TYPE, SigninFlowType.CONFIRMATION_ONLY); - result.putInt(ARGUMENT_ACCESS_POINT, accessPoint); - result.putInt(ARGUMENT_CHILD_ACCOUNT_STATUS, childAccountStatus); - result.putString(ARGUMENT_ACCOUNT_NAME, accountName); - result.putBoolean(ARGUMENT_IS_DEFAULT_ACCOUNT, isDefaultAccount); - result.putInt(ARGUMENT_UNDO_BEHAVIOR, undoBehavior); - return result; - } - - /** - * Initializes the view. - * - * @param arguments The argument bundle created by {@link #createArgumentsForDefaultFlow}, - * {@link #createArgumentsForAddAccountFlow} or - * {@link #createArgumentsForConfirmationFlow}. - * @param delegate The UI object creation delegate. - * @param listener The account selection event listener. - */ - public void init(Bundle arguments, Delegate delegate, Listener listener) { - @SigninAccessPoint int accessPoint = arguments.getInt(ARGUMENT_ACCESS_POINT, -1); - assert accessPoint != -1; - - initAccessPoint(accessPoint); - mChildAccountStatus = - arguments.getInt(ARGUMENT_CHILD_ACCOUNT_STATUS, ChildAccountStatus.NOT_CHILD); - mUndoBehavior = arguments.getInt(ARGUMENT_UNDO_BEHAVIOR, -1); - mSigninFlowType = arguments.getInt(ARGUMENT_SIGNIN_FLOW_TYPE, -1); - mDelegate = delegate; - mListener = listener; - - updateConsentText(); - - switch (mSigninFlowType) { - case SigninFlowType.DEFAULT: - showSigninPage(); - break; - case SigninFlowType.CONFIRMATION_ONLY: { - String accountName = arguments.getString(ARGUMENT_ACCOUNT_NAME); - assert accountName != null; - boolean isDefaultAccount = arguments.getBoolean(ARGUMENT_IS_DEFAULT_ACCOUNT, false); - showConfirmationPageForAccount(accountName, isDefaultAccount); - triggerUpdateAccounts(); - break; - } - case SigninFlowType.ADD_NEW_ACCOUNT: - showSigninPage(); - RecordUserAction.record("Signin_AddAccountToDevice"); - mListener.onNewAccount(); - break; - default: - assert false : "Unknown or missing signin flow type: " + mSigninFlowType; - return; - } - } - - public @SigninFlowType int getSigninFlowType() { - return mSigninFlowType; - } - - public @SigninAccessPoint int getSigninAccessPoint() { - return mSigninAccessPoint; - } - - private void initAccessPoint(@SigninAccessPoint int accessPoint) { - mSigninAccessPoint = accessPoint; - if (accessPoint == SigninAccessPoint.START_PAGE - || accessPoint == SigninAccessPoint.SIGNIN_PROMO) { - mCancelButtonTextId = R.string.no_thanks; - } - } - - @Override - protected void onFinishInflate() { - super.onFinishInflate(); - - mSigninChooseView = findViewById(R.id.account_signin_choose_view); - mSigninChooseView.setAddNewAccountObserver(() -> { - mListener.onNewAccount(); - RecordUserAction.record("Signin_AddAccountToDevice"); - }); - - mPositiveButton = findViewById(R.id.positive_button); - mNegativeButton = findViewById(R.id.negative_button); - mMoreButton = findViewById(R.id.more_button); - mSigninConfirmationView = findViewById(R.id.signin_confirmation_view); - mSigninAccountImage = findViewById(R.id.signin_account_image); - mSigninAccountName = findViewById(R.id.signin_account_name); - mSigninAccountEmail = findViewById(R.id.signin_account_email); - mSigninSyncTitle = findViewById(R.id.signin_sync_title); - mSigninSyncDescription = findViewById(R.id.signin_sync_description); - mSigninPersonalizeServiceTitle = findViewById(R.id.signin_personalize_service_title); - mSigninPersonalizeServiceDescription = - findViewById(R.id.signin_personalize_service_description); - mSigninSettingsControl = findViewById(R.id.signin_settings_control); - // For the spans to be clickable. - mSigninSettingsControl.setMovementMethod(LinkMovementMethod.getInstance()); - } - - private void updateConsentText() { - // Static strings. - mConsentTextTracker.setText(mSigninSyncTitle, R.string.sync_confirmation_chrome_sync_title); - mConsentTextTracker.setText( - mSigninSyncDescription, R.string.sync_confirmation_chrome_sync_message); - mConsentTextTracker.setText(mSigninPersonalizeServiceTitle, - R.string.sync_confirmation_personalize_services_title); - mConsentTextTracker.setText(mSigninPersonalizeServiceDescription, - mChildAccountStatus == ChildAccountStatus.REGULAR_CHILD - ? R.string.sync_confirmation_personalize_services_body_child_account - : R.string.sync_confirmation_personalize_services_body); - mConsentTextTracker.setText( - mSigninSettingsControl, R.string.signin_signed_in_settings_description); - mConsentTextTracker.setText(mNegativeButton, mCancelButtonTextId); - mConsentTextTracker.setText(mPositiveButton, R.string.choose_account_sign_in); - mConsentTextTracker.setText(mMoreButton, R.string.more); - - // The clickable "Settings" link. - NoUnderlineClickableSpan settingsSpan = - new NoUnderlineClickableSpan(getResources(), (widget) -> { - if (mSelectedAccountName == null) return; - mListener.onAccountSelected( - mSelectedAccountName, mIsDefaultAccountSelected, true); - RecordUserAction.record("Signin_Signin_WithAdvancedSyncSettings"); - - // Record the fact that the user consented to the consent text by clicking - // on |mSigninSettingsControl|. - recordConsent((TextView) widget, mSelectedAccountName); - }); - mConsentTextTracker.setText(mSigninSettingsControl, - getSettingsControlDescription(mChildAccountStatus), input -> { - return SpanApplier.applySpans(input.toString(), - new SpanInfo(SETTINGS_LINK_OPEN, SETTINGS_LINK_CLOSE, settingsSpan)); - }); - } - - @Override - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - triggerUpdateAccounts(); - AccountManagerFacade.get().addObserver(mAccountsChangedObserver); - mProfileDataCache.addObserver(mProfileDataCacheObserver); - if (mShouldShowConfirmationPageWhenAttachedToWindow) { - // Can happen if init is invoked before attaching to window (https://crbug.com/800665). - seedAccountsAndShowConfirmationPage(); - } - } - - @Override - protected void onDetachedFromWindow() { - if (mConfirmSyncDataStateMachine != null) { - mConfirmSyncDataStateMachine.cancel(/* isBeingDestroyed = */ true); - mConfirmSyncDataStateMachine = null; - } - mProfileDataCache.removeObserver(mProfileDataCacheObserver); - AccountManagerFacade.get().removeObserver(mAccountsChangedObserver); - super.onDetachedFromWindow(); - } - - @Override - public void onWindowVisibilityChanged(int visibility) { - super.onWindowVisibilityChanged(visibility); - if (visibility == View.VISIBLE) { - triggerUpdateAccounts(); - return; - } - if (visibility == View.INVISIBLE && mGooglePlayServicesUpdateErrorHandler != null) { - mGooglePlayServicesUpdateErrorHandler.cancelDialog(); - mGooglePlayServicesUpdateErrorHandler = null; - } - } - - /** - * @return Whether the view is in signed in mode. - */ - public boolean isInConfirmationScreen() { - return mSelectedAccountName != null; - } - - /** - * Cancels signin confirmation and shows account selection page. - */ - public void cancelConfirmationScreen() { - assert isInConfirmationScreen(); - mUndoBehavior = UndoBehavior.BACK_TO_SELECTION; - showSigninPage(); - } - - private void setButtonsEnabled(boolean enabled) { - mPositiveButton.setEnabled(enabled); - mNegativeButton.setEnabled(enabled); - } - - /** - * Refresh the list of available system accounts asynchronously. - */ - private void triggerUpdateAccounts() { - AccountManagerFacade.get().getGoogleAccountNames(this::updateAccounts); - } - - private void updateAccounts(AccountManagerResult<List<String>> result) { - if (!ViewCompat.isAttachedToWindow(AccountSigninView.this)) { - // This callback is invoked after AccountSigninView is detached from window - // (e.g., Chrome is minimized). Updating view now is redundant and dangerous - // (getSupportFragmentManager() can return null, etc.). See https://crbug.com/733117. - return; - } - - final List<String> accountNames; - try { - accountNames = result.get(); - } catch (GmsAvailabilityException e) { - dismissGmsUpdatingDialog(); - if (e.isUserResolvableError()) { - showGmsErrorDialog(e.getGmsAvailabilityReturnCode()); - } else { - Log.e(TAG, "Unresolvable GmsAvailabilityException.", e); - } - return; - } catch (GmsJustUpdatedException e) { - dismissGmsErrorDialog(); - showGmsUpdatingDialog(); - return; - } catch (AccountManagerDelegateException e) { - Log.e(TAG, "Unknown exception from AccountManagerFacade.", e); - dismissGmsErrorDialog(); - dismissGmsUpdatingDialog(); - return; - } - dismissGmsErrorDialog(); - dismissGmsUpdatingDialog(); - - if (mSelectedAccountName != null) { - if (accountNames.contains(mSelectedAccountName)) return; - - if (mUndoBehavior == UndoBehavior.BACK_TO_SELECTION) { - RecordUserAction.record("Signin_Undo_Signin"); - showSigninPage(); - } else { - mListener.onFailedToSetForcedAccount(mSelectedAccountName); - } - return; - } - - List<String> oldAccountNames = mAccountNames; - mAccountNames = accountNames; - - int oldSelectedAccount = mSigninChooseView.getSelectedAccountPosition(); - AccountSelectionResult selection = selectAccountAfterAccountsUpdate( - oldAccountNames, mAccountNames, oldSelectedAccount); - int accountToSelect = selection.getSelectedAccountIndex(); - boolean shouldJumpToConfirmationScreen = selection.shouldJumpToConfirmationScreen(); - - mSigninChooseView.updateAccounts(mAccountNames, accountToSelect, mProfileDataCache); - setUpSigninButton(!mAccountNames.isEmpty()); - mProfileDataCache.update(mAccountNames); - - boolean selectedAccountChanged = oldAccountNames != null && !oldAccountNames.isEmpty() - && (mAccountNames.isEmpty() - || !mAccountNames.get(accountToSelect) - .equals(oldAccountNames.get(oldSelectedAccount))); - if (selectedAccountChanged && mConfirmSyncDataStateMachine != null) { - // Any dialogs that may have been showing are now invalid (they were created - // for the previously selected account). - mConfirmSyncDataStateMachine.cancel(/* isBeingDestroyed = */ false); - mConfirmSyncDataStateMachine = null; - } - - if (shouldJumpToConfirmationScreen) { - showConfirmationPageForSelectedAccount(); - } - } - - private boolean hasGmsError() { - return mGooglePlayServicesUpdateErrorHandler != null || mGmsIsUpdatingDialog != null; - } - - private void showGmsErrorDialog(int gmsErrorCode) { - if (mGooglePlayServicesUpdateErrorHandler != null - && mGooglePlayServicesUpdateErrorHandler.isShowing()) { - return; - } - boolean cancelable = !IdentityServicesProvider.getSigninManager().isForceSigninEnabled(); - mGooglePlayServicesUpdateErrorHandler = - new UserRecoverableErrorHandler.ModalDialog(mDelegate.getActivity(), cancelable); - mGooglePlayServicesUpdateErrorHandler.handleError(getContext(), gmsErrorCode); - } - - private void showGmsUpdatingDialog() { - if (mGmsIsUpdatingDialog != null) { - return; - } - mGmsIsUpdatingDialog = new AlertDialog.Builder(getContext()) - .setCancelable(false) - .setView(R.layout.updating_gms_progress_view) - .create(); - mGmsIsUpdatingDialog.show(); - mGmsIsUpdatingDialogShowTime = SystemClock.elapsedRealtime(); - } - - private void dismissGmsErrorDialog() { - if (mGooglePlayServicesUpdateErrorHandler == null) { - return; - } - mGooglePlayServicesUpdateErrorHandler.cancelDialog(); - mGooglePlayServicesUpdateErrorHandler = null; - } - - private void dismissGmsUpdatingDialog() { - if (mGmsIsUpdatingDialog == null) { - return; - } - mGmsIsUpdatingDialog.dismiss(); - mGmsIsUpdatingDialog = null; - RecordHistogram.recordTimesHistogram("Signin.AndroidGmsUpdatingDialogShownTime", - SystemClock.elapsedRealtime() - mGmsIsUpdatingDialogShowTime); - } - - private static class AccountSelectionResult { - private final int mSelectedAccountIndex; - private final boolean mShouldJumpToConfirmationScreen; - - AccountSelectionResult(int selectedAccountIndex, boolean shouldJumpToConfirmationScreen) { - mSelectedAccountIndex = selectedAccountIndex; - mShouldJumpToConfirmationScreen = shouldJumpToConfirmationScreen; - } - - int getSelectedAccountIndex() { - return mSelectedAccountIndex; - } - - boolean shouldJumpToConfirmationScreen() { - return mShouldJumpToConfirmationScreen; - } - } - - /** - * Determine what account should be selected after account list update. This function also - * decides whether AccountSigninView should jump to confirmation screen. - * - * @param oldList Old list of user accounts. - * @param newList New list of user accounts. - * @param oldIndex Index of the selected account in the old list. - * @return {@link AccountSelectionResult} that encapsulates new index and jump/no jump flag. - */ - private static AccountSelectionResult selectAccountAfterAccountsUpdate( - List<String> oldList, List<String> newList, int oldIndex) { - if (oldList == null || newList == null) return new AccountSelectionResult(0, false); - // Return the old index if nothing changed - if (oldList.size() == newList.size() && oldList.containsAll(newList)) { - return new AccountSelectionResult(oldIndex, false); - } - if (newList.containsAll(oldList)) { - // A new account(s) has been added and no accounts have been deleted. Select new account - // and jump to the confirmation screen if only one account was added. - boolean shouldJumpToConfirmationScreen = newList.size() == oldList.size() + 1; - for (int i = 0; i < newList.size(); i++) { - if (!oldList.contains(newList.get(i))) { - return new AccountSelectionResult(i, shouldJumpToConfirmationScreen); - } - } - } - return new AccountSelectionResult(0, false); - } - - private void updateProfileData() { - mSigninChooseView.updateAccountProfileImages(mProfileDataCache); - - if (mSelectedAccountName != null) updateSignedInAccountInfo(); - } - - private void updateSignedInAccountInfo() { - DisplayableProfileData profileData = - mProfileDataCache.getProfileDataOrDefault(mSelectedAccountName); - mSigninAccountImage.setImageDrawable(profileData.getImage()); - String name = null; - if (mChildAccountStatus == ChildAccountStatus.REGULAR_CHILD) { - name = profileData.getGivenName(); - } - if (name == null) name = profileData.getFullNameOrEmail(); - mConsentTextTracker.setTextNonRecordable( - mSigninAccountName, getResources().getString(R.string.signin_hi_name, name)); - mConsentTextTracker.setTextNonRecordable(mSigninAccountEmail, mSelectedAccountName); - } - - private void showSigninPage() { - mSelectedAccountName = null; - - mSigninConfirmationView.setVisibility(View.GONE); - mSigninChooseView.setVisibility(View.VISIBLE); - - setUpCancelButton(); - triggerUpdateAccounts(); - } - - private void showConfirmationPage() { - updateSignedInAccountInfo(); - mProfileDataCache.update(Collections.singletonList(mSelectedAccountName)); - - mSigninChooseView.setVisibility(View.GONE); - mSigninConfirmationView.setVisibility(View.VISIBLE); - - setButtonsEnabled(true); - setUpConfirmButton(); - setUpUndoButton(); - } - - private void showConfirmationPageForSelectedAccount() { - int index = mSigninChooseView.getSelectedAccountPosition(); - showConfirmationPageForAccount(mAccountNames.get(index), index == 0); - } - - private void showConfirmationPageForAccount(String accountName, boolean isDefaultAccount) { - assert accountName != null; - - // Disable the buttons to prevent them being clicked again while waiting for the callbacks. - setButtonsEnabled(false); - - mSelectedAccountName = accountName; - mIsDefaultAccountSelected = isDefaultAccount; - seedAccountsAndShowConfirmationPage(); - } - - private void seedAccountsAndShowConfirmationPage() { - // Ensure that the AccountTrackerService has a fully up to date GAIA id <-> email mapping, - // as this is needed for the previous account check. - final long seedingStartTime = SystemClock.elapsedRealtime(); - final AccountTrackerService accountTrackerService = - IdentityServicesProvider.getAccountTrackerService(); - if (accountTrackerService.checkAndSeedSystemAccounts()) { - recordAccountTrackerServiceSeedingTime(seedingStartTime); - runStateMachineAndShowConfirmationPage(); - } else { - accountTrackerService.addSystemAccountsSeededListener( - new OnSystemAccountsSeededListener() { - @Override - public void onSystemAccountsSeedingComplete() { - accountTrackerService.removeSystemAccountsSeededListener(this); - recordAccountTrackerServiceSeedingTime(seedingStartTime); - // Don't show dialogs and confirmation page if activity was destroyed. - if (ViewCompat.isAttachedToWindow(AccountSigninView.this)) { - runStateMachineAndShowConfirmationPage(); - } else { - mShouldShowConfirmationPageWhenAttachedToWindow = true; - } - } - }); - } - } - - private void runStateMachineAndShowConfirmationPage() { - mConfirmSyncDataStateMachine = new ConfirmSyncDataStateMachine(getContext(), - mDelegate.getSupportFragmentManager(), ImportSyncType.PREVIOUS_DATA_FOUND, - PrefServiceBridge.getInstance().getSyncLastAccountName(), mSelectedAccountName, - new ConfirmImportSyncDataDialog.Listener() { - @Override - public void onConfirm(boolean wipeData) { - mConfirmSyncDataStateMachine = null; - SyncUserDataWiper.wipeSyncUserDataIfRequired(wipeData).then( - (Void v) -> showConfirmationPage()); - } - - @Override - public void onCancel() { - mConfirmSyncDataStateMachine = null; - setButtonsEnabled(true); - onSigninConfirmationCancel(); - } - }); - } - - private static void recordAccountTrackerServiceSeedingTime(long seedingStartTime) { - RecordHistogram.recordTimesHistogram("Signin.AndroidAccountSigninViewSeedingTime", - SystemClock.elapsedRealtime() - seedingStartTime); - } - - private void setUpCancelButton() { - setNegativeButtonVisible(true); - - mConsentTextTracker.setText(mNegativeButton, mCancelButtonTextId); - mNegativeButton.setOnClickListener(view -> { - setButtonsEnabled(false); - mListener.onAccountSelectionCanceled(); - }); - } - - private void setUpSigninButton(boolean hasAccounts) { - if (hasAccounts) { - mConsentTextTracker.setText(mPositiveButton, R.string.continue_sign_in); - mPositiveButton.setOnClickListener(view -> showConfirmationPageForSelectedAccount()); - } else { - mConsentTextTracker.setText(mPositiveButton, R.string.choose_account_sign_in); - mPositiveButton.setOnClickListener(view -> { - if (hasGmsError()) return; - - RecordUserAction.record("Signin_AddAccountToDevice"); - mListener.onNewAccount(); - }); - } - setUpMoreButtonVisible(false); - } - - private void setUpUndoButton() { - if (mUndoBehavior == UndoBehavior.INVISIBLE) { - setNegativeButtonVisible(false); - return; - } - setNegativeButtonVisible(true); - mConsentTextTracker.setText(mNegativeButton, R.string.undo); - mNegativeButton.setOnClickListener(view -> { - RecordUserAction.record("Signin_Undo_Signin"); - onSigninConfirmationCancel(); - }); - } - - private void onSigninConfirmationCancel() { - if (mUndoBehavior == UndoBehavior.BACK_TO_SELECTION) { - showSigninPage(); - } else { - assert mUndoBehavior == UndoBehavior.ABORT; - mListener.onAccountSelectionCanceled(); - } - } - - private void setUpConfirmButton() { - mConsentTextTracker.setText(mPositiveButton, R.string.signin_accept); - mPositiveButton.setOnClickListener(view -> { - if (mSelectedAccountName == null) return; - - mListener.onAccountSelected(mSelectedAccountName, mIsDefaultAccountSelected, false); - RecordUserAction.record("Signin_Signin_WithDefaultSyncSettings"); - - // Record the fact that the user consented to the consent text by clicking - // on |mPositiveButton|. - recordConsent((TextView) view, mSelectedAccountName); - }); - setUpMoreButtonVisible(true); - } - - /* - * mMoreButton is used to scroll mSigninConfirmationView down. It displays at the same position - * as mPositiveButton. - */ - private void setUpMoreButtonVisible(boolean enabled) { - if (enabled) { - mPositiveButton.setVisibility(View.GONE); - mMoreButton.setVisibility(View.VISIBLE); - mMoreButton.setOnClickListener(view -> { - mSigninConfirmationView.smoothScrollBy(0, mSigninConfirmationView.getHeight()); - RecordUserAction.record("Signin_MoreButton_Shown"); - }); - mSigninConfirmationView.setObserver(() -> setUpMoreButtonVisible(false)); - } else { - mPositiveButton.setVisibility(View.VISIBLE); - mMoreButton.setVisibility(View.GONE); - mSigninConfirmationView.setObserver(null); - } - } - - private void setNegativeButtonVisible(boolean enabled) { - if (enabled) { - mNegativeButton.setVisibility(View.VISIBLE); - findViewById(R.id.positive_button_end_padding).setVisibility(View.GONE); - } else { - mNegativeButton.setVisibility(View.GONE); - findViewById(R.id.positive_button_end_padding).setVisibility(View.INVISIBLE); - } - } - - private @StringRes int getSettingsControlDescription( - @ChildAccountStatus.Status int childAccountStatus) { - if (childAccountStatus == ChildAccountStatus.REGULAR_CHILD) { - return R.string.signin_signed_in_settings_description_child_account; - } else { - return R.string.signin_signed_in_settings_description; - } - } - - /** - * Records the Sync consent. - * @param confirmationView The view that the user clicked when consenting. - */ - private void recordConsent(TextView confirmationView, String selectedAccountName) { - // TODO(crbug.com/831257): Provide the account id synchronously from AccountManagerFacade. - assert selectedAccountName != null; - final AccountIdProvider accountIdProvider = AccountIdProvider.getInstance(); - new AsyncTask<String>() { - @Override - public String doInBackground() { - return accountIdProvider.getAccountId(selectedAccountName); - } - - @Override - public void onPostExecute(String accountId) { - mConsentTextTracker.recordConsent(accountId, ConsentAuditorFeature.CHROME_SYNC, - confirmationView, findViewById(R.id.signin_confirmation_view), - findViewById(R.id.button_bar)); - } - } - .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/ChromeSigninManagerDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/ChromeSigninManagerDelegate.java index 59bfb44..4c4ba074 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/ChromeSigninManagerDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/ChromeSigninManagerDelegate.java
@@ -10,6 +10,7 @@ import org.chromium.base.Callback; import org.chromium.base.VisibleForTesting; +import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JCaller; import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.externalauth.ExternalAuthUtils; @@ -24,23 +25,24 @@ private final AndroidSyncSettings mAndroidSyncSettings; private long mNativeChromeSigninManagerDelegate; - public ChromeSigninManagerDelegate() { - this(AndroidSyncSettings.get()); + @CalledByNative + private static ChromeSigninManagerDelegate create(long nativeChromeSigninManagerDelegate) { + assert nativeChromeSigninManagerDelegate != 0; + return new ChromeSigninManagerDelegate( + nativeChromeSigninManagerDelegate, AndroidSyncSettings.get()); + } + + @CalledByNative + public void destroy() { + mNativeChromeSigninManagerDelegate = 0; } @VisibleForTesting - ChromeSigninManagerDelegate(AndroidSyncSettings androidSyncSettings) { + ChromeSigninManagerDelegate( + long nativeChromeSigninManagerDelegate, AndroidSyncSettings androidSyncSettings) { assert androidSyncSettings != null; mAndroidSyncSettings = androidSyncSettings; - mNativeChromeSigninManagerDelegate = ChromeSigninManagerDelegateJni.get().init(); - } - - @Override - public void destroy() { - if (mNativeChromeSigninManagerDelegate != 0) { - ChromeSigninManagerDelegateJni.get().destroy(this, mNativeChromeSigninManagerDelegate); - mNativeChromeSigninManagerDelegate = 0; - } + mNativeChromeSigninManagerDelegate = nativeChromeSigninManagerDelegate; } @Override @@ -104,11 +106,6 @@ // Native methods. @NativeMethods interface Natives { - long init(); - - void destroy( - @JCaller ChromeSigninManagerDelegate self, long nativeChromeSigninManagerDelegate); - void fetchAndApplyCloudPolicy(@JCaller ChromeSigninManagerDelegate self, long nativeChromeSigninManagerDelegate, String username, Runnable callback);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/DisplayableProfileData.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/DisplayableProfileData.java index afaa009..5e14408 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/DisplayableProfileData.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/DisplayableProfileData.java
@@ -63,4 +63,14 @@ } return mFullName; } + + /** + * Returns the given name of the user if it is available or the full name or email otherwise. + */ + public String getGivenNameOrFullNameOrEmail() { + if (mGivenName != null) { + return mGivenName; + } + return getFullNameOrEmail(); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninActivity.java index 00ae5d2b..e42e5d3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninActivity.java
@@ -7,11 +7,16 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; +import android.support.annotation.IntDef; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import org.chromium.chrome.R; import org.chromium.chrome.browser.SynchronousInitializationActivity; +import org.chromium.chrome.browser.preferences.ManagedPreferencesUtils; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; /** * Allows user to pick an account and sign in. Started from Settings and various sign-in promos. @@ -21,12 +26,17 @@ private static final String TAG = "SigninActivity"; private static final String ARGUMENT_FRAGMENT_ARGS = "SigninActivity.FragmentArgs"; + @IntDef({SigninAccessPoint.SETTINGS, SigninAccessPoint.BOOKMARK_MANAGER, + SigninAccessPoint.RECENT_TABS, SigninAccessPoint.SIGNIN_PROMO, + SigninAccessPoint.NTP_CONTENT_SUGGESTIONS, SigninAccessPoint.AUTOFILL_DROPDOWN}) + @Retention(RetentionPolicy.SOURCE) + public @interface AccessPoint {} + /** * Creates an {@link Intent} which can be used to start sign-in flow. * @param accessPoint {@link AccessPoint} for starting sign-in flow. Used in metrics. */ - public static Intent createIntent( - Context context, @AccountSigninActivity.AccessPoint int accessPoint) { + public static Intent createIntent(Context context, @AccessPoint int accessPoint) { return createIntentInternal(context, SigninFragment.createArguments(accessPoint)); } @@ -70,6 +80,25 @@ return intent; } + /** + * A convenience method to create a SigninActivity passing the access point in the + * intent. Checks if the sign in flow can be started before showing the activity. + * @param accessPoint {@link AccessPoint} for starting signin flow. Used in metrics. + * @return {@code true} if sign in has been allowed. + */ + public static boolean startIfAllowed(Context context, @AccessPoint int accessPoint) { + SigninManager signinManager = IdentityServicesProvider.getSigninManager(); + if (!signinManager.isSignInAllowed()) { + if (signinManager.isSigninDisabledByPolicy()) { + ManagedPreferencesUtils.showManagedByAdministratorToast(context); + } + return false; + } + + context.startActivity(createIntent(context, accessPoint)); + return true; + } + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragment.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragment.java index e507fa26..93450e4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragment.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragment.java
@@ -11,7 +11,6 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; -import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.preferences.PreferencesLauncher; import org.chromium.chrome.browser.preferences.sync.SyncAndServicesPreferences; @@ -126,11 +125,6 @@ @Override protected void onSigninAccepted(String accountName, boolean isDefaultAccount, boolean settingsClicked, Runnable callback) { - if (PrefServiceBridge.getInstance().getSyncLastAccountName() != null) { - AccountSigninActivity.recordSwitchAccountSourceHistogram( - AccountSigninActivity.SwitchAccountSource.SIGNOUT_SIGNIN); - } - IdentityServicesProvider.getSigninManager().signIn( accountName, getActivity(), new SigninManager.SignInCallback() { @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java index c2a67b6f..5b50cb1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java
@@ -178,7 +178,11 @@ private static SigninManager sTestingSigninManager; private static int sSignInAccessPoint = SigninAccessPoint.UNKNOWN; - private final long mNativeSigninManagerAndroid; + /** + * Address of the native Signin Manager android. + * This is not final, as destroy() updates this. + */ + private long mNativeSigninManagerAndroid; private final Context mContext; private final SigninManagerDelegate mDelegate; private final AccountTrackerService mAccountTrackerService; @@ -215,11 +219,13 @@ * @return */ @CalledByNative - private static SigninManager create(long nativeSigninManagerAndroid) { + private static SigninManager create(long nativeSigninManagerAndroid, + SigninManagerDelegate delegate, AccountTrackerService accountTrackerService) { assert nativeSigninManagerAndroid != 0; + assert delegate != null; + assert accountTrackerService != null; return new SigninManager(ContextUtils.getApplicationContext(), nativeSigninManagerAndroid, - new ChromeSigninManagerDelegate(), - IdentityServicesProvider.getAccountTrackerService()); + delegate, accountTrackerService); } @VisibleForTesting @@ -227,8 +233,6 @@ AccountTrackerService accountTrackerService) { ThreadUtils.assertOnUiThread(); assert context != null; - assert delegate != null; - assert accountTrackerService != null; mContext = context; mNativeSigninManagerAndroid = nativeSigninManagerAndroid; mDelegate = delegate; @@ -241,11 +245,13 @@ } /** - * Perform destruction of the object, cascading destruction to delegate. + * Triggered during SigninManagerAndroidWrapper's KeyedService::Shutdown. + * Drop references with external services and native. */ @CalledByNative public void destroy() { - mDelegate.destroy(); + mAccountTrackerService.removeSystemAccountsSeededListener(this); + mNativeSigninManagerAndroid = 0; } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManagerDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManagerDelegate.java index 3ee437d4..63748ad 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManagerDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManagerDelegate.java
@@ -17,11 +17,6 @@ */ public interface SigninManagerDelegate { /** - * Perform destruction of the object, including destructing the associated native object. - */ - void destroy(); - - /** * If there is no Google Play Services available, ask the user to fix by showing either a * notification or a modal dialog * @param activity The activity used to open the dialog, or null to use notifications
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoController.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoController.java index 2effd36..f6da7f7b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoController.java
@@ -20,8 +20,7 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.metrics.ImpressionTracker; import org.chromium.chrome.browser.metrics.OneShotImpressionListener; -import org.chromium.chrome.browser.signin.AccountSigninActivity.AccessPoint; - +import org.chromium.chrome.browser.signin.SigninActivity.AccessPoint; /** * A controller for configuring the sign in promo. It sets up the sign in promo depending on the @@ -284,7 +283,7 @@ view.getDescription().setText(mDescriptionStringId); String signinButtonText = context.getString( - R.string.signin_promo_continue_as, mProfileData.getFullNameOrEmail()); + R.string.signin_promo_continue_as, mProfileData.getGivenNameOrFullNameOrEmail()); view.getSigninButton().setText(signinButtonText); view.getSigninButton().setOnClickListener(v -> signinWithDefaultAccount(context));
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoUtil.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoUtil.java index badad874..1fd147a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoUtil.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoUtil.java
@@ -47,7 +47,7 @@ return false; } - AccountSigninActivity.startIfAllowed(activity, SigninAccessPoint.SIGNIN_PROMO); + SigninActivity.startIfAllowed(activity, SigninAccessPoint.SIGNIN_PROMO); preferenceManager.setSigninPromoLastShownVersion(currentMajorVersion); preferenceManager.setSigninPromoLastAccountNames( new ArraySet<>(AccountManagerFacade.get().tryGetGoogleAccountNames())); @@ -115,16 +115,16 @@ } /** - * A convenience method to create an AccountSigninActivity, passing the access point as an + * A convenience method to create an SigninActivity, passing the access point as an * intent extra. * @param window WindowAndroid from which to get the Activity/Context. * @param accessPoint for metrics purposes. */ @CalledByNative - private static void openAccountSigninActivityForPromo(WindowAndroid window, int accessPoint) { + private static void openSigninActivityForPromo(WindowAndroid window, int accessPoint) { Activity activity = window.getActivity().get(); if (activity != null) { - AccountSigninActivity.startIfAllowed(activity, accessPoint); + SigninActivity.startIfAllowed(activity, accessPoint); } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SyncPromoView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SyncPromoView.java index 262b72cc..c5f314586 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SyncPromoView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SyncPromoView.java
@@ -19,7 +19,7 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.preferences.PreferencesLauncher; import org.chromium.chrome.browser.preferences.sync.SyncAndServicesPreferences; -import org.chromium.chrome.browser.signin.AccountSigninActivity.AccessPoint; +import org.chromium.chrome.browser.signin.SigninActivity.AccessPoint; import org.chromium.chrome.browser.util.IntentUtils; import org.chromium.components.sync.AndroidSyncSettings; import org.chromium.components.sync.AndroidSyncSettings.AndroidSyncSettingsObserver;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sync/SyncAccountSwitcher.java b/chrome/android/java/src/org/chromium/chrome/browser/sync/SyncAccountSwitcher.java index 5ef727a..5e5b1a9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sync/SyncAccountSwitcher.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sync/SyncAccountSwitcher.java
@@ -10,7 +10,6 @@ import android.text.TextUtils; import org.chromium.chrome.browser.preferences.sync.SyncedAccountPreference; -import org.chromium.chrome.browser.signin.AccountSigninActivity; import org.chromium.chrome.browser.signin.ConfirmImportSyncDataDialog; import org.chromium.chrome.browser.signin.ConfirmImportSyncDataDialog.ImportSyncType; import org.chromium.chrome.browser.signin.ConfirmSyncDataStateMachine; @@ -84,9 +83,6 @@ signinManager.signIn( mNewAccountName, mActivity, SyncAccountSwitcher.this); }); - - AccountSigninActivity.recordSwitchAccountSourceHistogram( - AccountSigninActivity.SwitchAccountSource.SYNC_ACCOUNT_SWITCHER); } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java index ddf29cb..9058cd8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java
@@ -166,5 +166,5 @@ @Override public void onBrowserControlsOffsetChanged( - int topControlsOffsetY, int bottomControlsOffsetY, int contentOffsetY) {} + Tab tab, int topControlsOffsetY, int bottomControlsOffsetY, int contentOffsetY) {} }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabBrowserControlsState.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabBrowserControlsState.java index ba674a5..43c0232 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabBrowserControlsState.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabBrowserControlsState.java
@@ -155,7 +155,7 @@ RewindableIterator<TabObserver> observers = mTab.getTabObservers(); while (observers.hasNext()) { observers.next().onBrowserControlsOffsetChanged( - mTopControlsOffset, mBottomControlsOffset, mContentOffset); + mTab, mTopControlsOffset, mBottomControlsOffset, mContentOffset); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java index 84cd4cf..9a96455 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java
@@ -371,5 +371,5 @@ * @param contentOffsetY The Y offset of the content in physical pixels. */ void onBrowserControlsOffsetChanged( - int topControlsOffsetY, int bottomControlsOffsetY, int contentOffsetY); + Tab tab, int topControlsOffsetY, int bottomControlsOffsetY, int contentOffsetY); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java index 81f365e5..cf97bcd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java
@@ -36,7 +36,6 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabIdManager; import org.chromium.chrome.browser.tab.TabState; -import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.chrome.browser.util.UrlConstants; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.content_public.browser.UiThreadTaskTraits; @@ -223,40 +222,7 @@ mObservers.addObserver(observer); mPreferences = ContextUtils.getAppSharedPreferences(); TaskTraits taskTraits = TaskTraits.USER_BLOCKING_MAY_BLOCK; - if (FeatureUtilities.isTabPersistentStoreTaskRunnerEnabled()) { - mSequencedTaskRunner = PostTask.createSequencedTaskRunner(taskTraits); - } else { - mSequencedTaskRunner = new SequencedTaskRunner() { - @Override - public void postTask(Runnable task) { - AsyncTask.SERIAL_EXECUTOR.execute(task); - } - - @Override - public void destroy() { - assert false : "Should not call destroy() on SERIAL_EXECUTOR TaskRunner"; - } - - @Override - public void disableLifetimeCheck() { - assert false - : "Should not call disableLifetimeCheck() on SERIAL_EXECUTOR TaskRunner"; - } - - @Override - public void postDelayedTask(Runnable task, long delay) { - assert false - : "Should not call postDelayedTask(...) on SERIAL_EXECUTOR TaskRunner"; - } - - @Override - public void initNativeTaskRunner() { - assert false - : "Should not call initNativeTaskRunner() on SERIAL_EXECUTOR TaskRunner"; - } - }; - } - + mSequencedTaskRunner = PostTask.createSequencedTaskRunner(taskTraits); mPrefetchTabListToMergeTasks = new ArrayList<>(); mMergedFileNames = new HashSet<>();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java b/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java index afdd3a3..30b7376 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java
@@ -88,7 +88,6 @@ private static Boolean sIsNetworkServiceEnabled; private static Boolean sIsNetworkServiceWarmUpEnabled; private static Boolean sIsImmersiveUiModeEnabled; - private static Boolean sIsTabPersistentStoreTaskRunnerEnabled; private static Boolean sServiceManagerForDownloadResumption; private static Boolean sDownloadAutoResumptionEnabledInNative; @@ -192,7 +191,6 @@ cacheNetworkServiceWarmUpEnabled(); cacheImmersiveUiModeEnabled(); cacheSwapPixelFormatToFixConvertFromTranslucentEnabled(); - cacheTabPersistentStoreTaskRunnerVariant(); cacheReachedCodeProfilerTrialGroup(); if (isHighEndPhone()) cacheGridTabSwitcherEnabled(); @@ -371,29 +369,6 @@ } /** - * Cache the whether or not TabPersistentStore is using TaskRunners, so on next startup, the - * value can be made available immediately. - */ - private static void cacheTabPersistentStoreTaskRunnerVariant() { - ChromePreferenceManager.getInstance().writeBoolean( - ChromePreferenceManager.TAB_PERSISTENT_STORE_TASK_RUNNER_ENABLED_KEY, - ChromeFeatureList.isEnabled(ChromeFeatureList.TAB_PERSISTENT_STORE_TASK_RUNNER)); - } - - /** - * @return Whether or not we are using the TaskRunner API in TabPersistentStore. - */ - public static boolean isTabPersistentStoreTaskRunnerEnabled() { - if (sIsTabPersistentStoreTaskRunnerEnabled == null) { - ChromePreferenceManager prefManager = ChromePreferenceManager.getInstance(); - - sIsTabPersistentStoreTaskRunnerEnabled = prefManager.readBoolean( - ChromePreferenceManager.TAB_PERSISTENT_STORE_TASK_RUNNER_ENABLED_KEY, false); - } - return sIsTabPersistentStoreTaskRunnerEnabled; - } - - /** * Cache whether or not the new tab page button is enabled so that on next startup, it can be * made available immediately. */
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index 300edd4..cadb698 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -2666,18 +2666,6 @@ </message> <!-- Account Signin Strings --> - <message name="IDS_CHOOSE_ACCOUNT_SIGN_IN" desc="Sign in button for choose google account dialog [CHAR-LIMIT=20]"> - Sign in - </message> - <message name="IDS_CONTINUE_SIGN_IN" desc="Sign in button for proceed sign in with selected account [CHAR-LIMIT=20]"> - Continue - </message> - <message name="IDS_SIGNIN_ACCOUNT_CHOICE_DESCRIPTION" desc="Text for account chooser page"> - Sign in with your Google Account to get your bookmarks, history, passwords, and other settings on all your devices. - </message> - <message name="IDS_SIGNIN_ACCEPT" desc="Text for button to accept being signed in"> - OK, got it - </message> <message name="IDS_SIGNIN_ADD_ACCOUNT" desc="Text for adding another Google Account"> Add account </message> @@ -2687,15 +2675,6 @@ <message name="IDS_SIGNIN_OPEN_SETTINGS_ACCOUNTS" desc="Text for button to open Accounts page in device's Settings app"> Open settings </message> - <message name="IDS_SIGNIN_HI_NAME" desc="Title welcoming the user by their name after they have signed in."> - Hi, <ph name="FULL_NAME">%1$s<ex>John Smith</ex></ph> - </message> - <message name="IDS_SIGNIN_SIGNED_IN_SETTINGS_DESCRIPTION_CHILD_ACCOUNT" desc="Label of the section containing the link to go to the settings page, when signing in to a child account."> - You and your parents can manage Chrome Sync and personalization in <ph name="BEGIN_LINK1"><LINK1></ph>Settings<ph name="END_LINK1"></LINK1></ph> - </message> - <message name="IDS_SIGNIN_SIGNED_IN_SETTINGS_DESCRIPTION" desc="Label of the section containing the link to go to the settings page."> - Manage Chrome Sync and personalization in <ph name="BEGIN_LINK1"><LINK1></ph>Settings<ph name="END_LINK1"></LINK1></ph> - </message> <message name="IDS_SIGNIN_GMS_UPDATING" desc="Message notifying user that Google Play Services is still updating."> Waiting for Google Play Services to finish updating </message> @@ -2759,25 +2738,6 @@ Choose another account </message> - <!-- Sync confirmation dialog --> - <!-- TODO(https://crbug.com/846376): These strings are only used by pre-Unified Consent sync confirmation dialog. Remove them once Unified Consent is enabled by default. --> - <!-- "Chrome sync" is the Google Cloud Based service used for sync. Thus this string resource is set to "Chrome sync" even for Chromium builds. --> - <message name="IDS_SYNC_CONFIRMATION_CHROME_SYNC_TITLE" desc="Title of the chrome sync section of the sync confirmation dialog in the tab modal signin flow"> - Chrome Sync - </message> - <message name="IDS_SYNC_CONFIRMATION_CHROME_SYNC_MESSAGE" desc="Body of the chrome sync section of the sync confirmation dialog in the tab modal signin flow"> - Your bookmarks, history, passwords, and other settings will be synced to your Google Account so you can use them on all your devices - </message> - <message name="IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_TITLE" desc="Title of the personalize services section of the sync confirmation dialog in the tab modal signin flow"> - Personalize Google services - </message> - <message name="IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_BODY" desc="Body of the personalize services section of the sync confirmation dialog in the tab modal signin flow"> - Google may use your browsing history to personalize Search, ads, and other Google services - </message> - <message name="IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_BODY_CHILD_ACCOUNT" desc="Body of the personalize services section of the sync confirmation dialog in the tab modal signin flow for child accounts"> - Google may use your browsing history to personalize Search and other Google services - </message> - <!-- Messages for remote media playback (casting) --> <message name="IDS_ACCESSIBILITY_PLAY" desc="The play button that starts playing the media."> Play
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPersonalizedSigninPromoTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPersonalizedSigninPromoTest.java index e50b187..17e7dbb 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPersonalizedSigninPromoTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPersonalizedSigninPromoTest.java
@@ -35,8 +35,8 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeSwitches; -import org.chromium.chrome.browser.signin.AccountSigninActivity; import org.chromium.chrome.browser.signin.SigninAccessPoint; +import org.chromium.chrome.browser.signin.SigninActivity; import org.chromium.chrome.browser.signin.SigninPromoController; import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; @@ -115,9 +115,9 @@ assertEquals("Choosing to sign in with the default account should fire an intent!", 1, startedIntents.size()); - Intent expectedIntent = AccountSigninActivity.createIntentForConfirmationOnlySigninFlow( - mActivityTestRule.getActivity(), SigninAccessPoint.BOOKMARK_MANAGER, - TEST_ACCOUNT_NAME, true, true); + Intent expectedIntent = + SigninActivity.createIntentForPromoDefaultFlow(mActivityTestRule.getActivity(), + SigninAccessPoint.BOOKMARK_MANAGER, TEST_ACCOUNT_NAME); assertTrue(expectedIntent.filterEquals(startedIntents.get(0))); } @@ -137,8 +137,8 @@ assertEquals("Choosing to sign in with another account should fire an intent!", 1, startedIntents.size()); - Intent expectedIntent = AccountSigninActivity.createIntentForDefaultSigninFlow( - mActivityTestRule.getActivity(), SigninAccessPoint.BOOKMARK_MANAGER, true); + Intent expectedIntent = SigninActivity.createIntent( + mActivityTestRule.getActivity(), SigninAccessPoint.BOOKMARK_MANAGER); assertTrue(expectedIntent.filterEquals(startedIntents.get(0))); } @@ -157,9 +157,9 @@ assertFalse( "Adding a new account should fire at least one intent!", startedIntents.isEmpty()); - Intent expectedIntent = AccountSigninActivity.createIntentForAddAccountSigninFlow( - mActivityTestRule.getActivity(), SigninAccessPoint.BOOKMARK_MANAGER, true); - // Comparing only the first intent as AccountSigninActivity will fire an intent after + Intent expectedIntent = SigninActivity.createIntentForPromoAddAccountFlow( + mActivityTestRule.getActivity(), SigninAccessPoint.BOOKMARK_MANAGER); + // Comparing only the first intent as SigninActivity will fire an intent after // starting the flow to add an account. assertTrue(expectedIntent.filterEquals(startedIntents.get(0))); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/MainIntentBehaviorMetricsIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/MainIntentBehaviorMetricsIntegrationTest.java index bd15707b..9482fd7 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/MainIntentBehaviorMetricsIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/MainIntentBehaviorMetricsIntegrationTest.java
@@ -108,6 +108,7 @@ @MediumTest @Test + @DisabledTest(message = "crbug.com/982081") public void testBackgrounded() { startActivity(true); assertMainIntentBehavior(null);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninTest.java index 00e7e70..6059887 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninTest.java
@@ -319,16 +319,16 @@ final Preferences prefActivity = mActivityTestRule.startPreferences(null); InstrumentationRegistry.getInstrumentation().waitForIdleSync(); - // Create a monitor to catch the AccountSigninActivity when it is created. + // Create a monitor to catch the SigninActivity when it is created. ActivityMonitor monitor = InstrumentationRegistry.getInstrumentation().addMonitor( - AccountSigninActivity.class.getName(), null, false); + SigninActivity.class.getName(), null, false); // Click sign in. TestThreadUtils.runOnUiThreadBlocking(() -> clickSigninPreference(prefActivity)); // Pick the mock account. - AccountSigninActivity signinActivity = - (AccountSigninActivity) InstrumentationRegistry.getInstrumentation().waitForMonitor( + SigninActivity signinActivity = + (SigninActivity) InstrumentationRegistry.getInstrumentation().waitForMonitor( monitor); Button positiveButton = (Button) signinActivity.findViewById(R.id.positive_button); // Press 'sign in'.
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/firstrun/FirstRunFlowSequencerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/firstrun/FirstRunFlowSequencerTest.java index 36bc8fc..a4aa96c3 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/firstrun/FirstRunFlowSequencerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/firstrun/FirstRunFlowSequencerTest.java
@@ -184,7 +184,7 @@ assertFalse(bundle.getBoolean(FirstRunActivityBase.SHOW_DATA_REDUCTION_PAGE)); assertFalse(bundle.getBoolean(FirstRunActivityBase.SHOW_SEARCH_ENGINE_PAGE)); assertEquals(ChildAccountStatus.NOT_CHILD, - bundle.getInt(AccountFirstRunFragment.CHILD_ACCOUNT_STATUS)); + bundle.getInt(SigninFirstRunFragment.CHILD_ACCOUNT_STATUS)); assertEquals(5, bundle.size()); } @@ -213,9 +213,9 @@ assertFalse(bundle.getBoolean(FirstRunActivityBase.SHOW_DATA_REDUCTION_PAGE)); assertFalse(bundle.getBoolean(FirstRunActivityBase.SHOW_SEARCH_ENGINE_PAGE)); assertEquals(ChildAccountStatus.REGULAR_CHILD, - bundle.getInt(AccountFirstRunFragment.CHILD_ACCOUNT_STATUS)); + bundle.getInt(SigninFirstRunFragment.CHILD_ACCOUNT_STATUS)); assertEquals( - DEFAULT_ACCOUNT, bundle.getString(AccountFirstRunFragment.FORCE_SIGNIN_ACCOUNT_TO)); + DEFAULT_ACCOUNT, bundle.getString(SigninFirstRunFragment.FORCE_SIGNIN_ACCOUNT_TO)); assertEquals(6, bundle.size()); } @@ -244,7 +244,7 @@ assertTrue(bundle.getBoolean(FirstRunActivityBase.SHOW_DATA_REDUCTION_PAGE)); assertFalse(bundle.getBoolean(FirstRunActivityBase.SHOW_SEARCH_ENGINE_PAGE)); assertEquals(ChildAccountStatus.NOT_CHILD, - bundle.getInt(AccountFirstRunFragment.CHILD_ACCOUNT_STATUS)); + bundle.getInt(SigninFirstRunFragment.CHILD_ACCOUNT_STATUS)); assertEquals(5, bundle.size()); } @@ -273,7 +273,7 @@ assertTrue(bundle.getBoolean(FirstRunActivityBase.SHOW_DATA_REDUCTION_PAGE)); assertTrue(bundle.getBoolean(FirstRunActivityBase.SHOW_SEARCH_ENGINE_PAGE)); assertEquals(ChildAccountStatus.NOT_CHILD, - bundle.getInt(AccountFirstRunFragment.CHILD_ACCOUNT_STATUS)); + bundle.getInt(SigninFirstRunFragment.CHILD_ACCOUNT_STATUS)); assertEquals(5, bundle.size()); } }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/signin/ChromeSigninManagerDelegateTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/signin/ChromeSigninManagerDelegateTest.java index c3085e5..1a6a13ce 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/signin/ChromeSigninManagerDelegateTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/signin/ChromeSigninManagerDelegateTest.java
@@ -46,7 +46,7 @@ // of this test. Using MockSyncContentResolver reduces burden of test setup. AndroidSyncSettings.overrideForTests(new MockSyncContentResolverDelegate(), null); - mDelegate = new ChromeSigninManagerDelegate(AndroidSyncSettings.get()); + mDelegate = new ChromeSigninManagerDelegate(0, AndroidSyncSettings.get()); } @Test public void signOutWithManagedDomain() {
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/DinoActivity.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/DinoActivity.java index 7b2ba47..5c6bf17 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/DinoActivity.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/DinoActivity.java
@@ -94,8 +94,7 @@ @Override protected ChromeFullscreenManager createFullscreenManager() { - return new ChromeFullscreenManager(this, - () -> mBrowserControlsOffsetHelper, ChromeFullscreenManager.ControlsPosition.NONE); + return new ChromeFullscreenManager(this, ChromeFullscreenManager.ControlsPosition.NONE); } @Override
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchActivity.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchActivity.java index 7f5648f..ef04459 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchActivity.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchActivity.java
@@ -222,8 +222,7 @@ @Override protected ChromeFullscreenManager createFullscreenManager() { - return new ChromeFullscreenManager(this, - () -> mBrowserControlsOffsetHelper, ChromeFullscreenManager.ControlsPosition.NONE); + return new ChromeFullscreenManager(this, ChromeFullscreenManager.ControlsPosition.NONE); } @Override
diff --git a/chrome/app/chromium_strings.grd b/chrome/app/chromium_strings.grd index 1f4d2db..b91ddbf 100644 --- a/chrome/app/chromium_strings.grd +++ b/chrome/app/chromium_strings.grd
@@ -1270,6 +1270,12 @@ <message name="IDS_DESKTOP_MEDIA_PICKER_TITLE_WEB_CONTENTS_ONLY" desc="Title for the window picker dialog shown when desktop capture of a tab is requested by an app."> Share a Chromium tab </message> + <!-- User happiness tracking survey UI --> + <if expr="not is_android"> + <message name="IDS_HATS_BUBBLE_TITLE" translateable="false" desc="The title of Happiness Tracking Survey's invitation banner, it invites users to take a survey"> + Help us improve Chromium + </message> + </if> </messages> </release> </grit>
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index acc07aaa..aeb27b76 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -8941,10 +8941,10 @@ </ph> - VR presenting to headset </message> <message name="IDS_TAB_AX_LABEL_NATIVE_FILE_SYSTEM_WRITABLE_FORMAT" desc="Accessibility label text, when the tab has write access to the native file system. Example: 'Google Docs - is allowed to save to original files'"> - <ph name="WINDOW_TITLE">$1<ex>Google Docs</ex></ph> - is allowed to save to original files + <ph name="WINDOW_TITLE">$1<ex>Google Docs</ex></ph> - Allowed to save to original files </message> <message name="IDS_TAB_AX_LABEL_NATIVE_FILE_SYSTEM_DIRECTORY_FORMAT" desc="Accessibility label text, when the tab has read access to directories on the native file system. Example: 'Google Docs - is allowed to read a folder on your device'"> - <ph name="WINDOW_TITLE">$1<ex>Google Docs</ex></ph> - is allowed to read a folder on your device + <ph name="WINDOW_TITLE">$1<ex>Google Docs</ex></ph> - Allowed to read a folder on your device </message> <!-- ProcessSingleton --> @@ -9543,6 +9543,25 @@ } </message> + <!-- Native File System restricted directory dialog. --> + <message name="IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TITLE" desc="Title of dialog explaining that the user selected a directory that chrome doesn't want to expose to the web"> + Can't save to this folder + </message> + <message name="IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TEXT" desc="Text of dialog explaining that the user selected a directory that chrome doesn't want to expose to the web"> + <ph name="ORIGIN">$1<ex>example.com</ex></ph> can't save your changes to this folder because it contains system files. + </message> + <message name="IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_BUTTON" desc="Text of the button in dialog explaining that the user selected a directory that chrome doesn't want to expose to the web"> + Choose a different folder + </message> + + <!-- Native File System directory access confirmation dialog. --> + <message name="IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TITLE" desc="Title of dialog asking user if they intended to share a particular directory"> + Let site read this folder? + </message> + <message name="IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TEXT" desc="Text of dialog asking user if they intended to share a particular directory"> + <ph name="ORIGIN">$1<ex>example.com</ex></ph> will be able to read all files in the following folder. This site can see any changes to the folder only while this tab is open. + </message> + <!-- Relaunch notification bubble and dialog. --> <if expr="not is_android"> <if expr="not chromeos"> @@ -9840,9 +9859,6 @@ <message name="IDS_HATS_BUBBLE_OK_LABEL" translateable="false" desc="Button label on Happiness Tracking Survey's invitation banner, clicking the button gives the user's consent on taking the survey."> Take Survey </message> - <message name="IDS_HATS_BUBBLE_TITLE" translateable="false" desc="The title of Happiness Tracking Survey's invitation banner, it invites users to take a survey"> - Take a quick survey - </message> <message name="IDS_HATS_BUBBLE_TEXT" translateable="false" desc="The text in Happiness Tracking Survey's invitation banner, it explains why users should take our survey."> Your feedback is important to us. </message>
diff --git a/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TEXT.png.sha1 b/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TEXT.png.sha1 new file mode 100644 index 0000000..0c495fbe --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TEXT.png.sha1
@@ -0,0 +1 @@ +a4d4621b4680a1742fd3ca8366e8e1e886dfef27 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TITLE.png.sha1 b/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TITLE.png.sha1 new file mode 100644 index 0000000..0c495fbe --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TITLE.png.sha1
@@ -0,0 +1 @@ +a4d4621b4680a1742fd3ca8366e8e1e886dfef27 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_BUTTON.png.sha1 b/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_BUTTON.png.sha1 new file mode 100644 index 0000000..192aac9 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_BUTTON.png.sha1
@@ -0,0 +1 @@ +8f6df1b3e036b7d1ff3f02ffb177ce99865ad7cb \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TEXT.png.sha1 b/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TEXT.png.sha1 new file mode 100644 index 0000000..192aac9 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TEXT.png.sha1
@@ -0,0 +1 @@ +8f6df1b3e036b7d1ff3f02ffb177ce99865ad7cb \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TITLE.png.sha1 b/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TITLE.png.sha1 new file mode 100644 index 0000000..192aac9 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TITLE.png.sha1
@@ -0,0 +1 @@ +8f6df1b3e036b7d1ff3f02ffb177ce99865ad7cb \ No newline at end of file
diff --git a/chrome/app/google_chrome_strings.grd b/chrome/app/google_chrome_strings.grd index 3bc04907..678db861 100644 --- a/chrome/app/google_chrome_strings.grd +++ b/chrome/app/google_chrome_strings.grd
@@ -1290,6 +1290,13 @@ <message name="IDS_DESKTOP_MEDIA_PICKER_TITLE_WEB_CONTENTS_ONLY" desc="Title for the window picker dialog shown when desktop capture of a tab is requested by an app."> Share a Chrome tab </message> + + <!-- User happiness tracking survey UI --> + <if expr="not is_android"> + <message name="IDS_HATS_BUBBLE_TITLE" translateable="false" desc="The title of Happiness Tracking Survey's invitation banner, it invites users to take a survey"> + Help us improve Chrome + </message> + </if> </messages> </release> </grit>
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 25df07e85..e02ae67 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -624,7 +624,7 @@ Confirm Restore </message> <message name="IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_MESSAGE" desc="Message of the confirmation dialog displayed before container import begins."> - Restoring will override your existing linux installation. Are you sure you wish to continue? + Restoring from a backup will delete existing Linux applications and data in your Linux files folder. </message> <message name="IDS_SETTINGS_CROSTINI_SHARED_USB_DEVICES_LABEL" desc="Label for managing shared USB devices."> USB preferences @@ -3035,15 +3035,6 @@ <message name="IDS_SETTINGS_GOOGLE_ASSISTANT" desc="Name of the settings page for Google Assistant."> Google Assistant </message> - <message name="IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_CONTEXT" desc="Title for a toggle that lets the assistant use whats on the screen."> - Related info - </message> - <message name="IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_CONTEXT_DESCRIPTION" desc="Sub label for context-enable toggle."> - Let the Assistant show you info related to what's on your screen - </message> - <message name="IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD" desc="Title for a toggle that lets the assistant detect hotword."> - "Ok Google" - </message> <message name="IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD_DESCRIPTION" desc="Sub label for hotword-enable toggle."> Access your Assistant any time you say "Ok Google" </message> @@ -3062,9 +3053,6 @@ <message name="IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS" desc="Title for the Assistant voice settings."> Voice match </message> - <message name="IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS_DESCRIPTION" desc="Sub label for the Assistant voice settings."> - Teach your Assistant to recognize your voice - </message> <message name="IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS_RETRAIN" desc="Button label for retrain voice model."> Retrain </message>
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_MESSAGE.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_MESSAGE.png.sha1 index c394d5f..0d85e25 100644 --- a/chrome/app/settings_strings_grdp/IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_MESSAGE.png.sha1 +++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_MESSAGE.png.sha1
@@ -1 +1 @@ -3f3a4b2a98a73d4de6e438e6c91bea5b7c3cb277 \ No newline at end of file +e62bb8cd606796f5bd999b23d6853549443092ab \ No newline at end of file
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_TITLE.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_TITLE.png.sha1 index c394d5f..0d85e25 100644 --- a/chrome/app/settings_strings_grdp/IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_TITLE.png.sha1 +++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_TITLE.png.sha1
@@ -1 +1 @@ -3f3a4b2a98a73d4de6e438e6c91bea5b7c3cb277 \ No newline at end of file +e62bb8cd606796f5bd999b23d6853549443092ab \ No newline at end of file
diff --git a/chrome/app/vector_icons/BUILD.gn b/chrome/app/vector_icons/BUILD.gn index c6bcef6..dc302f7 100644 --- a/chrome/app/vector_icons/BUILD.gn +++ b/chrome/app/vector_icons/BUILD.gn
@@ -85,7 +85,6 @@ "security.icon", "send_tab_to_self.icon", "sensors.icon", - "settings.icon", "signin_button_drop_down_arrow.icon", "sign_out.icon", "smartphone.icon", @@ -164,7 +163,29 @@ } if (is_chromeos) { - icons += [ "warning_badge_circle.icon" ] + icons += [ + "notification_captive_portal.icon", + "notification_battery.icon", + "notification_cellular_alert.icon", + "notification_download.icon", + "notification_end_of_support.icon", + "notification_family_link.icon", + "notification_google.icon", + "notification_image.icon", + "notification_installed.icon", + "notification_linux.icon", + "notification_messages.icon", + "notification_mobile_data.icon", + "notification_mobile_data_off.icon", + "notification_plugin_vm.icon", + "notification_printing.icon", + "notification_printing_done.icon", + "notification_printing_warning.icon", + "notification_storage_full.icon", + "notification_vpn.icon", + "notification_wifi_off.icon", + "warning_badge_circle.icon", + ] } if (enable_vr && !is_android) {
diff --git a/ash/public/cpp/vector_icons/notification_battery.icon b/chrome/app/vector_icons/notification_battery.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_battery.icon rename to chrome/app/vector_icons/notification_battery.icon
diff --git a/ash/public/cpp/vector_icons/notification_captive_portal.icon b/chrome/app/vector_icons/notification_captive_portal.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_captive_portal.icon rename to chrome/app/vector_icons/notification_captive_portal.icon
diff --git a/ash/public/cpp/vector_icons/notification_cellular_alert.icon b/chrome/app/vector_icons/notification_cellular_alert.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_cellular_alert.icon rename to chrome/app/vector_icons/notification_cellular_alert.icon
diff --git a/ash/public/cpp/vector_icons/notification_download.icon b/chrome/app/vector_icons/notification_download.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_download.icon rename to chrome/app/vector_icons/notification_download.icon
diff --git a/ash/public/cpp/vector_icons/notification_end_of_support.icon b/chrome/app/vector_icons/notification_end_of_support.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_end_of_support.icon rename to chrome/app/vector_icons/notification_end_of_support.icon
diff --git a/ash/public/cpp/vector_icons/notification_family_link.icon b/chrome/app/vector_icons/notification_family_link.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_family_link.icon rename to chrome/app/vector_icons/notification_family_link.icon
diff --git a/ash/public/cpp/vector_icons/notification_google.icon b/chrome/app/vector_icons/notification_google.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_google.icon rename to chrome/app/vector_icons/notification_google.icon
diff --git a/ash/public/cpp/vector_icons/notification_image.icon b/chrome/app/vector_icons/notification_image.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_image.icon rename to chrome/app/vector_icons/notification_image.icon
diff --git a/ash/public/cpp/vector_icons/notification_installed.icon b/chrome/app/vector_icons/notification_installed.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_installed.icon rename to chrome/app/vector_icons/notification_installed.icon
diff --git a/ash/public/cpp/vector_icons/notification_linux.icon b/chrome/app/vector_icons/notification_linux.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_linux.icon rename to chrome/app/vector_icons/notification_linux.icon
diff --git a/ash/public/cpp/vector_icons/notification_messages.icon b/chrome/app/vector_icons/notification_messages.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_messages.icon rename to chrome/app/vector_icons/notification_messages.icon
diff --git a/ash/public/cpp/vector_icons/notification_mobile_data.icon b/chrome/app/vector_icons/notification_mobile_data.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_mobile_data.icon rename to chrome/app/vector_icons/notification_mobile_data.icon
diff --git a/ash/public/cpp/vector_icons/notification_mobile_data_off.icon b/chrome/app/vector_icons/notification_mobile_data_off.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_mobile_data_off.icon rename to chrome/app/vector_icons/notification_mobile_data_off.icon
diff --git a/ash/public/cpp/vector_icons/notification_plugin_vm.icon b/chrome/app/vector_icons/notification_plugin_vm.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_plugin_vm.icon rename to chrome/app/vector_icons/notification_plugin_vm.icon
diff --git a/ash/public/cpp/vector_icons/notification_printing.icon b/chrome/app/vector_icons/notification_printing.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_printing.icon rename to chrome/app/vector_icons/notification_printing.icon
diff --git a/ash/public/cpp/vector_icons/notification_printing_done.icon b/chrome/app/vector_icons/notification_printing_done.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_printing_done.icon rename to chrome/app/vector_icons/notification_printing_done.icon
diff --git a/ash/public/cpp/vector_icons/notification_printing_warning.icon b/chrome/app/vector_icons/notification_printing_warning.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_printing_warning.icon rename to chrome/app/vector_icons/notification_printing_warning.icon
diff --git a/ash/public/cpp/vector_icons/notification_storage_full.icon b/chrome/app/vector_icons/notification_storage_full.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_storage_full.icon rename to chrome/app/vector_icons/notification_storage_full.icon
diff --git a/ash/public/cpp/vector_icons/notification_vpn.icon b/chrome/app/vector_icons/notification_vpn.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_vpn.icon rename to chrome/app/vector_icons/notification_vpn.icon
diff --git a/ash/public/cpp/vector_icons/notification_wifi_off.icon b/chrome/app/vector_icons/notification_wifi_off.icon similarity index 100% rename from ash/public/cpp/vector_icons/notification_wifi_off.icon rename to chrome/app/vector_icons/notification_wifi_off.icon
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index f4236da..3a7ca7f 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -337,6 +337,10 @@ "component_updater/sw_reporter_installer_win.h", "consent_auditor/consent_auditor_factory.cc", "consent_auditor/consent_auditor_factory.h", + "content_index/content_index_provider_factory.cc", + "content_index/content_index_provider_factory.h", + "content_index/content_index_provider_impl.cc", + "content_index/content_index_provider_impl.h", "content_settings/chrome_content_settings_utils.cc", "content_settings/chrome_content_settings_utils.h", "content_settings/cookie_settings_factory.cc", @@ -2008,9 +2012,9 @@ "//components/services/unzip/public/interfaces", "//components/sessions", "//components/signin/core/browser", - "//components/signin/core/browser:signin_buildflags", "//components/signin/core/browser/webdata", "//components/signin/internal/identity_manager", # TODO(974198): remove once closed + "//components/signin/public/base:signin_buildflags", "//components/signin/public/identity_manager", "//components/spellcheck:buildflags", "//components/ssl_errors", @@ -2574,6 +2578,7 @@ "android/signin/signin_investigator_android.h", "android/signin/signin_manager_android.cc", "android/signin/signin_manager_android.h", + "android/signin/signin_manager_delegate.h", "android/signin/signin_promo_util_android.cc", "android/signin/signin_promo_util_android.h", "android/signin/signin_utils.cc", @@ -3793,7 +3798,7 @@ ] if (use_dbus) { - deps += [ "//components/dbus:dbus_thread_linux" ] + deps += [ "//components/dbus/thread_linux" ] } if (enable_native_notifications) {
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 16e05c2..3c73a70 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -92,8 +92,8 @@ #include "components/send_tab_to_self/features.h" #include "components/services/heap_profiling/public/cpp/switches.h" #include "components/signin/core/browser/account_reconcilor.h" -#include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_switches.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "components/signin/public/base/signin_switches.h" #include "components/spellcheck/common/spellcheck_features.h" #include "components/spellcheck/spellcheck_buildflags.h" #include "components/sync/driver/sync_driver_switches.h" @@ -876,6 +876,12 @@ base::size(kTranslateForceTriggerOnEnglishGeo), nullptr}, {"(Zero threshold)", kTranslateForceTriggerOnEnglishBackoff, base::size(kTranslateForceTriggerOnEnglishBackoff), nullptr}}; + +const FeatureEntry::FeatureParam kOverscrollHistoryNavigationBottomSheet[] = { + {"overscroll_history_navigation_bottom_sheet", "true"}}; +const FeatureEntry::FeatureVariation kOverscrollHistoryNavigationVariations[] = + {{"Navigation sheet", kOverscrollHistoryNavigationBottomSheet, + base::size(kOverscrollHistoryNavigationBottomSheet), nullptr}}; #endif // defined(OS_ANDROID) #if !defined(OS_ANDROID) @@ -1559,12 +1565,16 @@ flag_descriptions::kOverscrollHistoryNavigationName, flag_descriptions::kOverscrollHistoryNavigationDescription, kOsAura | kOsAndroid, +#if defined(OS_ANDROID) + FEATURE_WITH_PARAMS_VALUE_TYPE(features::kOverscrollHistoryNavigation, + kOverscrollHistoryNavigationVariations, + "OverscrollNavigation")}, +#else FEATURE_VALUE_TYPE(features::kOverscrollHistoryNavigation)}, -#if !defined(OS_ANDROID) {"pull-to-refresh", flag_descriptions::kPullToRefreshName, flag_descriptions::kPullToRefreshDescription, kOsAura, MULTI_VALUE_TYPE(kPullToRefreshChoices)}, -#endif // !OS_ANDROID +#endif // OS_ANDROID #endif // USE_AURA || OS_ANDROID {"enable-touch-drag-drop", flag_descriptions::kTouchDragDropName, flag_descriptions::kTouchDragDropDescription, kOsWin | kOsCrOS, @@ -2442,6 +2452,9 @@ ENABLE_DISABLE_VALUE_TYPE( chromeos::switches::kShowAndroidFilesInFilesApp, chromeos::switches::kHideAndroidFilesInFilesApp)}, + {"camera-system-web-app", flag_descriptions::kCameraSystemWebAppName, + flag_descriptions::kCameraSystemWebAppDescription, kOsCrOS, + FEATURE_VALUE_TYPE(chromeos::features::kCameraSystemWebApp)}, {"crostini-gpu-support", flag_descriptions::kCrostiniGpuSupportName, flag_descriptions::kCrostiniGpuSupportDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kCrostiniGpuSupport)}, @@ -4075,6 +4088,11 @@ FEATURE_VALUE_TYPE(chromeos::features::kCrostiniWebUIInstaller)}, #endif // OS_CHROMEOS + {"enable-autofill-save-card-show-no-thanks", + flag_descriptions::kEnableAutofillSaveCardShowNoThanksName, + flag_descriptions::kEnableAutofillSaveCardShowNoThanksDescription, kOsAll, + FEATURE_VALUE_TYPE(autofill::features::kAutofillSaveCardShowNoThanks)}, + // NOTE: Adding a new flag requires adding a corresponding entry to enum // "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag // Histograms" in tools/metrics/histograms/README.md (run the
diff --git a/chrome/browser/android/autofill_assistant/client_android.cc b/chrome/browser/android/autofill_assistant/client_android.cc index bbbe7a2..8a1b0cc 100644 --- a/chrome/browser/android/autofill_assistant/client_android.cc +++ b/chrome/browser/android/autofill_assistant/client_android.cc
@@ -28,7 +28,7 @@ #include "components/autofill_assistant/browser/access_token_fetcher.h" #include "components/autofill_assistant/browser/controller.h" #include "components/autofill_assistant/browser/features.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/version_info/channel.h" #include "content/public/browser/browser_task_traits.h" @@ -97,7 +97,7 @@ // In the case of an unexpected closing of the activity or tab, controller_ // will not yet have been cleaned up (since that happens when a web // contents object gets destroyed). - Metrics::RecordDropOut(Metrics::CONTENT_DESTROYED); + Metrics::RecordDropOut(Metrics::DropOutReason::CONTENT_DESTROYED); } Java_AutofillAssistantClient_clearNativePtr(AttachCurrentThread(), java_object_);
diff --git a/chrome/browser/android/autofill_assistant/ui_controller_android.cc b/chrome/browser/android/autofill_assistant/ui_controller_android.cc index b7902c7..1603160 100644 --- a/chrome/browser/android/autofill_assistant/ui_controller_android.cc +++ b/chrome/browser/android/autofill_assistant/ui_controller_android.cc
@@ -40,7 +40,7 @@ #include "components/autofill_assistant/browser/features.h" #include "components/autofill_assistant/browser/metrics.h" #include "components/autofill_assistant/browser/rectf.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/strings/grit/components_strings.h" #include "components/version_info/channel.h" @@ -523,7 +523,7 @@ void UiControllerAndroid::OnCancel(int action_index) { if (action_index == -1 || !ui_delegate_) { - Shutdown(Metrics::SHEET_CLOSED); + Shutdown(Metrics::DropOutReason::SHEET_CLOSED); return; } ui_delegate_->PerformUserAction(action_index); @@ -586,10 +586,10 @@ } void UiControllerAndroid::OnUnexpectedTaps() { - ShowSnackbar( - l10n_util::GetStringUTF8(IDS_AUTOFILL_ASSISTANT_MAYBE_GIVE_UP), - base::BindOnce(&UiControllerAndroid::Shutdown, - weak_ptr_factory_.GetWeakPtr(), Metrics::SHEET_CLOSED)); + ShowSnackbar(l10n_util::GetStringUTF8(IDS_AUTOFILL_ASSISTANT_MAYBE_GIVE_UP), + base::BindOnce(&UiControllerAndroid::Shutdown, + weak_ptr_factory_.GetWeakPtr(), + Metrics::DropOutReason::SHEET_CLOSED)); } void UiControllerAndroid::UpdateTouchableArea() { @@ -605,7 +605,7 @@ // Other methods. void UiControllerAndroid::WillShutdown(Metrics::DropOutReason reason) { - if (reason == Metrics::CUSTOM_TAB_CLOSED) { + if (reason == Metrics::DropOutReason::CUSTOM_TAB_CLOSED) { Java_AutofillAssistantUiController_scheduleCloseCustomTab( AttachCurrentThread(), java_object_); }
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index 6490f70..993cb504 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -29,7 +29,7 @@ #include "components/payments/core/features.h" #include "components/previews/core/previews_features.h" #include "components/safe_browsing/features.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/translate/core/browser/translate_prefs.h" @@ -174,7 +174,6 @@ &kTabGroupsAndroid, &kTabGroupsUiImprovementsAndroid, &kTabGridLayoutAndroid, - &kTabPersistentStoreTaskRunner, &kTabReparenting, &kTabSwitcherOnReturn, &kTabToGTSAnimation, @@ -541,9 +540,6 @@ const base::Feature kTabGridLayoutAndroid{"TabGridLayoutAndroid", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kTabPersistentStoreTaskRunner{ - "TabPersistentStoreTaskRunner", base::FEATURE_DISABLED_BY_DEFAULT}; - const base::Feature kTabReparenting{"TabReparenting", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/chrome/browser/android/chrome_feature_list.h b/chrome/browser/android/chrome_feature_list.h index 69091a31..6702b857 100644 --- a/chrome/browser/android/chrome_feature_list.h +++ b/chrome/browser/android/chrome_feature_list.h
@@ -112,7 +112,6 @@ extern const base::Feature kTabGroupsAndroid; extern const base::Feature kTabGroupsUiImprovementsAndroid; extern const base::Feature kTabGridLayoutAndroid; -extern const base::Feature kTabPersistentStoreTaskRunner; extern const base::Feature kTabReparenting; extern const base::Feature kTabSwitcherOnReturn; extern const base::Feature kTabToGTSAnimation;
diff --git a/chrome/browser/android/contextualsearch/contextual_search_delegate.cc b/chrome/browser/android/contextualsearch/contextual_search_delegate.cc index 278f59f..ce93eda 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_delegate.cc +++ b/chrome/browser/android/contextualsearch/contextual_search_delegate.cc
@@ -30,7 +30,7 @@ #include "components/language/core/browser/pref_names.h" #include "components/prefs/pref_service.h" #include "components/search_engines/template_url_service.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/sync/driver/sync_service.h" #include "components/unified_consent/url_keyed_data_collection_consent_helper.h" #include "components/variations/net/variations_http_headers.h"
diff --git a/chrome/browser/android/preferences/pref_service_bridge.cc b/chrome/browser/android/preferences/pref_service_bridge.cc index e1c789e..6f079ade 100644 --- a/chrome/browser/android/preferences/pref_service_bridge.cc +++ b/chrome/browser/android/preferences/pref_service_bridge.cc
@@ -48,7 +48,7 @@ #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/strings/grit/components_locale_settings.h" #include "components/translate/core/browser/translate_pref_names.h" #include "components/translate/core/browser/translate_prefs.h"
diff --git a/chrome/browser/android/signin/chrome_signin_manager_delegate.cc b/chrome/browser/android/signin/chrome_signin_manager_delegate.cc index 48c7567..89e8ff7 100644 --- a/chrome/browser/android/signin/chrome_signin_manager_delegate.cc +++ b/chrome/browser/android/signin/chrome_signin_manager_delegate.cc
@@ -16,7 +16,7 @@ #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/cloud/user_cloud_policy_manager.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browsing_data_filter_builder.h" #include "content/public/browser/browsing_data_remover.h" @@ -101,7 +101,7 @@ } // namespace -ChromeSigninManagerDelegate::ChromeSigninManagerDelegate(JNIEnv* env) +ChromeSigninManagerDelegate::ChromeSigninManagerDelegate() : profile_(ProfileManager::GetActiveUserProfile()), identity_manager_(IdentityManagerFactory::GetForProfile(profile_)), user_cloud_policy_manager_(profile_->GetUserCloudPolicyManager()), @@ -112,14 +112,20 @@ DCHECK(identity_manager_); DCHECK(user_cloud_policy_manager_); DCHECK(user_policy_signin_service_); + + java_signin_manager_delegate_ = Java_ChromeSigninManagerDelegate_create( + base::android::AttachCurrentThread(), reinterpret_cast<intptr_t>(this)); } -ChromeSigninManagerDelegate::~ChromeSigninManagerDelegate() {} +ChromeSigninManagerDelegate::~ChromeSigninManagerDelegate() { + Java_ChromeSigninManagerDelegate_destroy(base::android::AttachCurrentThread(), + java_signin_manager_delegate_); +} -void ChromeSigninManagerDelegate::Destroy( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj) { - delete this; +base::android::ScopedJavaLocalRef<jobject> +ChromeSigninManagerDelegate::GetJavaObject() { + return base::android::ScopedJavaLocalRef<jobject>( + java_signin_manager_delegate_); } void ChromeSigninManagerDelegate::StopApplyingCloudPolicy( @@ -273,10 +279,3 @@ // The ProfileDataRemover deletes itself once done. new ProfileDataRemover(profile, all_data, std::move(callback)); } - -// instantiates ChromeSigninManagerDelegate -static jlong JNI_ChromeSigninManagerDelegate_Init(JNIEnv* env) { - ChromeSigninManagerDelegate* chrome_signin_manager_delegate = - new ChromeSigninManagerDelegate(env); - return reinterpret_cast<intptr_t>(chrome_signin_manager_delegate); -}
diff --git a/chrome/browser/android/signin/chrome_signin_manager_delegate.h b/chrome/browser/android/signin/chrome_signin_manager_delegate.h index dd9e940..c3110d1 100644 --- a/chrome/browser/android/signin/chrome_signin_manager_delegate.h +++ b/chrome/browser/android/signin/chrome_signin_manager_delegate.h
@@ -8,7 +8,8 @@ #include "base/android/scoped_java_ref.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "components/signin/core/browser/account_info.h" +#include "chrome/browser/android/signin/signin_manager_delegate.h" +#include "components/signin/public/identity_manager/account_info.h" namespace identity { class IdentityManager; @@ -23,11 +24,13 @@ // This class provide ChromeSigninManagerDelegate.java access to the native // dependencies. -class ChromeSigninManagerDelegate { +class ChromeSigninManagerDelegate : public SigninManagerDelegate { public: - explicit ChromeSigninManagerDelegate(JNIEnv* env); + ChromeSigninManagerDelegate(); - void Destroy(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); + ~ChromeSigninManagerDelegate() override; + + base::android::ScopedJavaLocalRef<jobject> GetJavaObject() override; // Registers a CloudPolicyClient for fetching policy for a user and fetches // the policy if necessary. @@ -76,8 +79,6 @@ using RegisterPolicyWithAccountCallback = base::OnceCallback<void( const base::Optional<ManagementCredentials>& credentials)>; - ~ChromeSigninManagerDelegate(); - ChromeSigninManagerDelegate(const ChromeSigninManagerDelegate&) = delete; ChromeSigninManagerDelegate& operator=(const ChromeSigninManagerDelegate&) = @@ -107,6 +108,9 @@ policy::UserCloudPolicyManager* const user_cloud_policy_manager_ = nullptr; policy::UserPolicySigninService* const user_policy_signin_service_ = nullptr; + // Java-side ChromeSigninManagerDelegate object. + base::android::ScopedJavaGlobalRef<jobject> java_signin_manager_delegate_; + base::WeakPtrFactory<ChromeSigninManagerDelegate> weak_factory_; };
diff --git a/chrome/browser/android/signin/signin_investigator_android.cc b/chrome/browser/android/signin/signin_investigator_android.cc index 165d3a7..158ba293 100644 --- a/chrome/browser/android/signin/signin_investigator_android.cc +++ b/chrome/browser/android/signin/signin_investigator_android.cc
@@ -11,7 +11,7 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/investigator_dependency_provider.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" using base::android::ConvertJavaStringToUTF8;
diff --git a/chrome/browser/android/signin/signin_manager_android.cc b/chrome/browser/android/signin/signin_manager_android.cc index 2cd4076..54a9427 100644 --- a/chrome/browser/android/signin/signin_manager_android.cc +++ b/chrome/browser/android/signin/signin_manager_android.cc
@@ -15,9 +15,9 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/primary_account_manager.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" #include "google_apis/gaia/gaia_auth_util.h" @@ -33,10 +33,14 @@ SigninManagerAndroid::SigninManagerAndroid( Profile* profile, - identity::IdentityManager* identity_manager) - : profile_(profile), identity_manager_(identity_manager) { + identity::IdentityManager* identity_manager, + std::unique_ptr<SigninManagerDelegate> signin_manager_delegate) + : profile_(profile), + identity_manager_(identity_manager), + signin_manager_delegate_(std::move(signin_manager_delegate)) { DCHECK(profile_); DCHECK(identity_manager_); + DCHECK(signin_manager_delegate_); identity_manager_->AddObserver(this); pref_change_registrar_.Init(profile_->GetPrefs()); pref_change_registrar_.Add( @@ -44,7 +48,9 @@ base::Bind(&SigninManagerAndroid::OnSigninAllowedPrefChanged, base::Unretained(this))); java_signin_manager_ = Java_SigninManager_create( - base::android::AttachCurrentThread(), reinterpret_cast<intptr_t>(this)); + base::android::AttachCurrentThread(), reinterpret_cast<intptr_t>(this), + signin_manager_delegate_->GetJavaObject(), + identity_manager_->LegacyGetAccountTrackerServiceJavaObject()); } base::android::ScopedJavaLocalRef<jobject> @@ -52,13 +58,13 @@ return base::android::ScopedJavaLocalRef<jobject>(java_signin_manager_); } -SigninManagerAndroid::~SigninManagerAndroid() { - Java_SigninManager_destroy(base::android::AttachCurrentThread(), - java_signin_manager_); -} +SigninManagerAndroid::~SigninManagerAndroid() {} void SigninManagerAndroid::Shutdown() { identity_manager_->RemoveObserver(this); + Java_SigninManager_destroy(base::android::AttachCurrentThread(), + java_signin_manager_); + signin_manager_delegate_.reset(); } void SigninManagerAndroid::OnSignInCompleted(
diff --git a/chrome/browser/android/signin/signin_manager_android.h b/chrome/browser/android/signin/signin_manager_android.h index 7c30fc6..47de7dc 100644 --- a/chrome/browser/android/signin/signin_manager_android.h +++ b/chrome/browser/android/signin/signin_manager_android.h
@@ -11,6 +11,7 @@ #include "base/android/scoped_java_ref.h" #include "base/macros.h" #include "base/threading/thread_checker.h" +#include "chrome/browser/android/signin/signin_manager_delegate.h" #include "components/prefs/pref_change_registrar.h" #include "components/signin/public/identity_manager/identity_manager.h" @@ -26,8 +27,10 @@ // is available before sign-in completes. class SigninManagerAndroid : public identity::IdentityManager::Observer { public: - SigninManagerAndroid(Profile* profile, - identity::IdentityManager* identity_manager); + SigninManagerAndroid( + Profile* profile, + identity::IdentityManager* identity_manager, + std::unique_ptr<SigninManagerDelegate> signin_manager_delegate); ~SigninManagerAndroid() override; @@ -73,6 +76,8 @@ identity::IdentityManager* identity_manager_; + std::unique_ptr<SigninManagerDelegate> signin_manager_delegate_; + // Java-side SigninManager object. base::android::ScopedJavaGlobalRef<jobject> java_signin_manager_;
diff --git a/chrome/browser/android/signin/signin_manager_delegate.h b/chrome/browser/android/signin/signin_manager_delegate.h new file mode 100644 index 0000000..4b080045 --- /dev/null +++ b/chrome/browser/android/signin/signin_manager_delegate.h
@@ -0,0 +1,27 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_ANDROID_SIGNIN_SIGNIN_MANAGER_DELEGATE_H_ +#define CHROME_BROWSER_ANDROID_SIGNIN_SIGNIN_MANAGER_DELEGATE_H_ + +#include "base/android/scoped_java_ref.h" + +// This class provides SigninManager.java access to dependencies on +// chrome/browser through its derivated class ChromeSigninManagerDelegate and +// the java counterparts SigninManagerDelegate.java and +// ChromeSigninManagerDelegate.java. +class SigninManagerDelegate { + public: + virtual base::android::ScopedJavaLocalRef<jobject> GetJavaObject() = 0; + + SigninManagerDelegate() = default; + + virtual ~SigninManagerDelegate() = default; + + SigninManagerDelegate(const SigninManagerDelegate&) = delete; + + SigninManagerDelegate& operator=(const SigninManagerDelegate&) = delete; +}; + +#endif // CHROME_BROWSER_ANDROID_SIGNIN_SIGNIN_MANAGER_DELEGATE_H_
diff --git a/chrome/browser/android/signin/signin_promo_util_android.cc b/chrome/browser/android/signin/signin_promo_util_android.cc index 6d22830..a6725a5 100644 --- a/chrome/browser/android/signin/signin_promo_util_android.cc +++ b/chrome/browser/android/signin/signin_promo_util_android.cc
@@ -12,11 +12,11 @@ namespace android { // static -void SigninPromoUtilAndroid::StartAccountSigninActivityForPromo( +void SigninPromoUtilAndroid::StartSigninActivityForPromo( ui::WindowAndroid* window, signin_metrics::AccessPoint access_point) { if (window) { - Java_SigninPromoUtil_openAccountSigninActivityForPromo( + Java_SigninPromoUtil_openSigninActivityForPromo( base::android::AttachCurrentThread(), window->GetJavaObject(), jint(access_point)); }
diff --git a/chrome/browser/android/signin/signin_promo_util_android.h b/chrome/browser/android/signin/signin_promo_util_android.h index 4f11d1af..217372be 100644 --- a/chrome/browser/android/signin/signin_promo_util_android.h +++ b/chrome/browser/android/signin/signin_promo_util_android.h
@@ -6,7 +6,7 @@ #define CHROME_BROWSER_ANDROID_SIGNIN_SIGNIN_PROMO_UTIL_ANDROID_H_ #include "base/android/jni_android.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" namespace ui { class WindowAndroid; @@ -18,7 +18,7 @@ class SigninPromoUtilAndroid { public: // Opens a signin flow with the specified |access_point| for metrics. - static void StartAccountSigninActivityForPromo( + static void StartSigninActivityForPromo( ui::WindowAndroid* window, signin_metrics::AccessPoint access_point); };
diff --git a/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc b/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc index a9c42fd..a19e0848 100644 --- a/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc +++ b/chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_browsertest.cc
@@ -17,7 +17,7 @@ #include "chrome/browser/sync_file_system/sync_file_system_service.h" #include "chrome/browser/sync_file_system/sync_file_system_service_factory.h" #include "components/drive/service/fake_drive_service.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "extensions/test/extension_test_message_listener.h"
diff --git a/chrome/browser/apps/platform_apps/app_window_interactive_uitest_base.cc b/chrome/browser/apps/platform_apps/app_window_interactive_uitest_base.cc index d9469c7..46c86d00 100644 --- a/chrome/browser/apps/platform_apps/app_window_interactive_uitest_base.cc +++ b/chrome/browser/apps/platform_apps/app_window_interactive_uitest_base.cc
@@ -8,10 +8,10 @@ #include "chrome/test/base/interactive_test_utils.h" #include "components/keep_alive_registry/keep_alive_registry.h" #include "components/keep_alive_registry/keep_alive_types.h" +#include "content/public/test/test_utils.h" #include "extensions/browser/app_window/native_app_window.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" -#include "ui/base/ui_base_features.h" FullscreenChangeWaiter::FullscreenChangeWaiter( extensions::NativeAppWindow* window)
diff --git a/chrome/browser/autofill/autofill_internals_logging_impl.cc b/chrome/browser/autofill/autofill_internals_logging_impl.cc index 028239f78..3f98663 100644 --- a/chrome/browser/autofill/autofill_internals_logging_impl.cc +++ b/chrome/browser/autofill/autofill_internals_logging_impl.cc
@@ -18,6 +18,12 @@ web_ui_->CallJavascriptFunctionUnsafe("addLog", message); } +void AutofillInternalsLoggingImpl::LogRawHelper(const base::Value& message) { + // TODO(crbug.com/928595) Moving this to CallJavascriptFunction requires + // some bigger refactoring that will happen in a separate CL. + web_ui_->CallJavascriptFunctionUnsafe("addRawLog", message); +} + void AutofillInternalsLoggingImpl::set_web_ui(content::WebUI* web_ui) { web_ui_ = web_ui; }
diff --git a/chrome/browser/autofill/autofill_internals_logging_impl.h b/chrome/browser/autofill/autofill_internals_logging_impl.h index 6c3eabee..ca0c512d 100644 --- a/chrome/browser/autofill/autofill_internals_logging_impl.h +++ b/chrome/browser/autofill/autofill_internals_logging_impl.h
@@ -24,6 +24,7 @@ static content::WebUI* web_ui_; void LogHelper(const base::Value& message) override; + void LogRawHelper(const base::Value& message) override; DISALLOW_COPY_AND_ASSIGN(AutofillInternalsLoggingImpl); };
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index b829f54..8b47ca1 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -108,7 +108,7 @@ #include "components/rappor/rappor_service_impl.h" #include "components/safe_browsing/safe_browsing_service_interface.h" #include "components/sessions/core/session_id_generator.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/subresource_filter/content/browser/ruleset_service.h" #include "components/subresource_filter/core/browser/subresource_filter_constants.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h"
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index c9ec510..34ceee5 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -277,6 +277,8 @@ <include name="IDR_APP_MANAGEMENT_PERMISSION_TOGGLE_JS" file="resources\app_management\permission_toggle.js" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_HTML" file="resources\app_management\permission_view_header.html" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_JS" file="resources\app_management\permission_view_header.js" type="BINDATA"/> + <include name="IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_HTML" file="resources\app_management\pin_to_shelf_item.html" type="BINDATA"/> + <include name="IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_JS" file="resources\app_management\pin_to_shelf_item.js" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_HTML" file="resources\app_management\pwa_permission_view.html" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_JS" file="resources\app_management\pwa_permission_view.js" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_REDUCERS_HTML" file="resources\app_management\reducers.html" type="BINDATA" /> @@ -291,6 +293,8 @@ <include name="IDR_APP_MANAGEMENT_STORE_CLIENT_JS" file="resources\app_management\store_client.js" type="BINDATA" /> <include name="IDR_APP_MANAGEMENT_STORE_HTML" file="resources\app_management\store.html" type="BINDATA" /> <include name="IDR_APP_MANAGEMENT_STORE_JS" file="resources\app_management\store.js" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_TOGGLE_ROW_HTML" file="resources\app_management\toggle_row.html" type="BINDATA"/> + <include name="IDR_APP_MANAGEMENT_TOGGLE_ROW_JS" file="resources\app_management\toggle_row.js" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_TYPES_JS" file="resources\app_management\types.js" type="BINDATA" /> <include name="IDR_APP_MANAGEMENT_UTIL_HTML" file="resources\app_management\util.html" type="BINDATA" /> <include name="IDR_APP_MANAGEMENT_UTIL_JS" file="resources\app_management\util.js" type="BINDATA" />
diff --git a/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc b/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc index 0aa08ac..047af7f 100644 --- a/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc +++ b/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc
@@ -47,7 +47,7 @@ #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_reconcilor.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "content/public/browser/browser_context.h"
diff --git a/chrome/browser/browsing_data/counters/browsing_data_counter_utils_browsertest.cc b/chrome/browser/browsing_data/counters/browsing_data_counter_utils_browsertest.cc index 95f74785..df320b5 100644 --- a/chrome/browser/browsing_data/counters/browsing_data_counter_utils_browsertest.cc +++ b/chrome/browser/browsing_data/counters/browsing_data_counter_utils_browsertest.cc
@@ -11,7 +11,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/unified_consent/unified_consent_service_factory.h" #include "chrome/test/base/in_process_browser_test.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" #include "components/sync/driver/profile_sync_service.h" #include "components/sync/test/fake_server/fake_server_network_resources.h" #include "components/unified_consent/feature.h"
diff --git a/chrome/browser/browsing_data/counters/site_settings_counter_unittest.cc b/chrome/browser/browsing_data/counters/site_settings_counter_unittest.cc index 410e4a89..dbed6a1 100644 --- a/chrome/browser/browsing_data/counters/site_settings_counter_unittest.cc +++ b/chrome/browser/browsing_data/counters/site_settings_counter_unittest.cc
@@ -20,6 +20,8 @@ #if !defined(OS_ANDROID) #include "content/public/browser/host_zoom_map.h" +#else +#include "base/android/build_info.h" #endif namespace { @@ -109,6 +111,14 @@ // Test that the counter counts correctly when using a time period. TEST_F(SiteSettingsCounterTest, CountWithTimePeriod) { +#if defined(OS_ANDROID) + // TODO(crbug.com/981972) + if (base::android::BuildInfo::GetInstance()->sdk_int() >= + base::android::SDK_VERSION_OREO) { + return; + } +#endif + base::SimpleTestClock test_clock; map()->SetClockForTesting(&test_clock);
diff --git a/chrome/browser/captive_portal/captive_portal_browsertest.cc b/chrome/browser/captive_portal/captive_portal_browsertest.cc index d4ecc244..eb77b42 100644 --- a/chrome/browser/captive_portal/captive_portal_browsertest.cc +++ b/chrome/browser/captive_portal/captive_portal_browsertest.cc
@@ -762,26 +762,37 @@ // Waits for exactly |num_jobs| kMockHttps* requests. void WaitForJobs(int num_jobs) { - if (!BrowserThread::CurrentlyOn(GetInterceptorThreadID())) { + if (BrowserThread::CurrentlyOn(GetInterceptorThreadID())) { + SetNumJobsToWaitForOnInterceptorThread(num_jobs); + } else { base::PostTaskWithTraits( FROM_HERE, {GetInterceptorThreadID()}, - base::BindOnce(&CaptivePortalBrowserTest::WaitForJobs, - base::Unretained(this), num_jobs)); - run_loop_ = std::make_unique<base::RunLoop>(); - run_loop_->Run(); - return; + base::BindOnce( + &CaptivePortalBrowserTest::SetNumJobsToWaitForOnInterceptorThread, + base::Unretained(this), num_jobs)); } + run_loop_ = std::make_unique<base::RunLoop>(); + // Will be exited via QuitRunLoop() when the interceptor has received + // |num_jobs|. + run_loop_->Run(); + } + + void SetNumJobsToWaitForOnInterceptorThread(int num_jobs) { + DCHECK_CURRENTLY_ON(GetInterceptorThreadID()); DCHECK(!num_jobs_to_wait_for_); - EXPECT_LE(static_cast<int>(ongoing_mock_requests_.size()), num_jobs); - if (num_jobs == static_cast<int>(ongoing_mock_requests_.size())) { + + int num_ongoing_jobs = static_cast<int>(ongoing_mock_requests_.size()); + if (num_ongoing_jobs == num_jobs) { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&CaptivePortalBrowserTest::QuitRunLoop, base::Unretained(this))); - } else { - num_jobs_to_wait_for_ = num_jobs; + return; } + + EXPECT_LT(num_ongoing_jobs, num_jobs); + num_jobs_to_wait_for_ = num_jobs; } // Fails all active kMockHttps* requests with connection timeouts. @@ -887,7 +898,7 @@ protected: std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor_; std::unique_ptr<base::RunLoop> run_loop_; - // Only accessed on the IO thread. + // Only accessed on the |GetInterceptorThreadID()| thread. int num_jobs_to_wait_for_ = 0; std::vector<content::URLLoaderInterceptor::RequestParams> ongoing_mock_requests_;
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index d7c3ddb..f759770 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -148,7 +148,7 @@ #include "components/prefs/pref_value_store.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/rappor/rappor_service_impl.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/startup_metric_utils/browser/startup_metric_utils.h" #include "components/tracing/common/tracing_switches.h" #include "components/translate/core/browser/translate_download_manager.h"
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 23fd28a..a8017edc 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -259,8 +259,8 @@ #include "components/services/quarantine/public/mojom/quarantine.mojom.h" #include "components/services/quarantine/quarantine_service.h" #include "components/services/unzip/public/interfaces/constants.mojom.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/spellcheck/spellcheck_buildflags.h" #include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h" #include "components/translate/core/common/translate_switches.h" @@ -431,6 +431,7 @@ #include "chromeos/services/network_config/public/mojom/constants.mojom.h" #include "chromeos/services/secure_channel/public/mojom/constants.mojom.h" #include "chromeos/services/secure_channel/secure_channel_service.h" +#include "components/crash/content/app/breakpad_linux.h" #include "components/user_manager/user_manager.h" #include "services/service_manager/public/mojom/interface_provider_spec.mojom.h" #elif defined(OS_LINUX) @@ -2301,6 +2302,16 @@ command_line->AppendSwitch(switches::kDisableBreakpad); } +#if defined(OS_CHROMEOS) + if (breakpad::ShouldPassCrashLoopBefore(process_type)) { + static const char* const kSwitchNames[] = { + switches::kCrashLoopBefore, + }; + command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, + base::size(kSwitchNames)); + } +#endif + StackSamplingConfiguration::Get()->AppendCommandLineSwitchForChildProcess( process_type, command_line);
diff --git a/chrome/browser/chrome_service_worker_browsertest.cc b/chrome/browser/chrome_service_worker_browsertest.cc index 0b1527d..b2c8ebd 100644 --- a/chrome/browser/chrome_service_worker_browsertest.cc +++ b/chrome/browser/chrome_service_worker_browsertest.cc
@@ -49,6 +49,7 @@ #include "net/test/embedded_test_server/http_response.h" #include "ppapi/shared_impl/ppapi_switches.h" #include "third_party/blink/public/common/messaging/string_message_codec.h" +#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h" namespace chrome_service_worker_browser_test {
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index 5e0b1a3..1ccbe0a7 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -56,6 +56,7 @@ "//ash/public/cpp", "//ash/system/message_center/arc", "//chrome/app:command_ids", + "//chrome/app/vector_icons", "//chrome/browser/apps/platform_apps", "//chrome/browser/apps/platform_apps/api", "//chrome/browser/chromeos/power/ml/smart_dim", @@ -1921,8 +1922,6 @@ "settings/device_identity_provider.h", "settings/device_oauth2_token_service.cc", "settings/device_oauth2_token_service.h", - "settings/device_oauth2_token_service_delegate.cc", - "settings/device_oauth2_token_service_delegate.h", "settings/device_oauth2_token_service_factory.cc", "settings/device_oauth2_token_service_factory.h", "settings/device_settings_cache.cc",
diff --git a/chrome/browser/chromeos/README.md b/chrome/browser/chromeos/README.md index a16b56e..0947ee6 100644 --- a/chrome/browser/chromeos/README.md +++ b/chrome/browser/chromeos/README.md
@@ -16,6 +16,5 @@ * The notification controller for network portal detection lives in: `chrome/browser/ui/ash/network/network_portal_notification_controller.cc` - (which depends on *chrome/browser/ui*, - *ash/public/cpp/vector_icons/vector_icons.h*, and + (which depends on *chrome/browser/ui*, and *chrome/browser/chromeos/net/network_portal_detector_impl.h*.
diff --git a/chrome/browser/chromeos/accessibility/switch_access_browsertest.cc b/chrome/browser/chromeos/accessibility/switch_access_browsertest.cc index 64eb058..824b9ff9 100644 --- a/chrome/browser/chromeos/accessibility/switch_access_browsertest.cc +++ b/chrome/browser/chromeos/accessibility/switch_access_browsertest.cc
@@ -8,6 +8,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "chromeos/constants/chromeos_switches.h" #include "content/public/test/browser_test_utils.h" #include "ui/accessibility/accessibility_switches.h"
diff --git a/chrome/browser/chromeos/android_sms/pairing_lost_notifier.cc b/chrome/browser/chromeos/android_sms/pairing_lost_notifier.cc index 07b6f196..a5d91c7 100644 --- a/chrome/browser/chromeos/android_sms/pairing_lost_notifier.cc +++ b/chrome/browser/chromeos/android_sms/pairing_lost_notifier.cc
@@ -5,8 +5,8 @@ #include "chrome/browser/chromeos/android_sms/pairing_lost_notifier.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/ui/ash/multi_user/multi_user_util.h" #include "chrome/grit/generated_resources.h" @@ -124,7 +124,7 @@ base::BindRepeating( &PairingLostNotifier::OnPairingLostNotificationClick, weak_ptr_factory_.GetWeakPtr())), - ash::kNotificationMessagesIcon, + kNotificationMessagesIcon, message_center::SystemNotificationWarningLevel::NORMAL), /*metadata=*/nullptr); }
diff --git a/chrome/browser/chromeos/arc/arc_migration_guide_notification.cc b/chrome/browser/chromeos/arc/arc_migration_guide_notification.cc index fabde3b..acf339e 100644 --- a/chrome/browser/chromeos/arc/arc_migration_guide_notification.cc +++ b/chrome/browser/chromeos/arc/arc_migration_guide_notification.cc
@@ -7,7 +7,6 @@ #include <memory> #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/macros.h" #include "base/optional.h" @@ -21,6 +20,7 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/dbus/power_manager/power_supply_properties.pb.h" +#include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" #include "ui/chromeos/devicetype_utils.h" #include "ui/gfx/color_palette.h" @@ -67,7 +67,7 @@ IDS_ARC_MIGRATE_ENCRYPTION_NOTIFICATION_TITLE), message, base::string16(), GURL(), notifier_id, message_center::RichNotificationData(), std::move(delegate), - ash::kNotificationSettingsIcon, + vector_icons::kSettingsIcon, message_center::SystemNotificationWarningLevel::CRITICAL_WARNING); notification->set_renotify(true);
diff --git a/chrome/browser/chromeos/arc/auth/arc_auth_context.cc b/chrome/browser/chromeos/arc/auth/arc_auth_context.cc index e2d09d64..553fa4d 100644 --- a/chrome/browser/chromeos/arc/auth/arc_auth_context.cc +++ b/chrome/browser/chromeos/arc/auth/arc_auth_context.cc
@@ -14,8 +14,8 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" -#include "components/signin/core/browser/ubertoken_fetcher.h" #include "components/signin/public/identity_manager/access_token_fetcher.h" +#include "components/signin/public/identity_manager/ubertoken_fetcher.h" #include "content/public/common/url_constants.h" #include "google_apis/gaia/gaia_auth_fetcher.h" #include "services/network/public/cpp/shared_url_loader_factory.h"
diff --git a/chrome/browser/chromeos/arc/notification/arc_boot_error_notification.cc b/chrome/browser/chromeos/arc/notification/arc_boot_error_notification.cc index 4792828..f259175 100644 --- a/chrome/browser/chromeos/arc/notification/arc_boot_error_notification.cc +++ b/chrome/browser/chromeos/arc/notification/arc_boot_error_notification.cc
@@ -8,11 +8,11 @@ #include <utility> #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/notifications/notification_display_service.h" @@ -80,7 +80,7 @@ } }, profile)), - ash::kNotificationStorageFullIcon, + kNotificationStorageFullIcon, message_center::SystemNotificationWarningLevel::CRITICAL_WARNING); NotificationDisplayService::GetForProfile(profile)->Display( NotificationHandler::Type::TRANSIENT, *notification,
diff --git a/chrome/browser/chromeos/arc/notification/arc_supervision_transition_notification.cc b/chrome/browser/chromeos/arc/notification/arc_supervision_transition_notification.cc index 6cf1487..ee7286f2 100644 --- a/chrome/browser/chromeos/arc/notification/arc_supervision_transition_notification.cc +++ b/chrome/browser/chromeos/arc/notification/arc_supervision_transition_notification.cc
@@ -5,9 +5,9 @@ #include "chrome/browser/chromeos/arc/notification/arc_supervision_transition_notification.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/macros.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/notifications/notification_display_service.h" @@ -105,7 +105,7 @@ l10n_util::GetStringUTF16(IDS_ARC_CHILD_TRANSITION_MESSAGE), l10n_util::GetStringUTF16(IDS_ARC_NOTIFICATION_DISPLAY_SOURCE), GURL(), notifier_id, message_center::RichNotificationData(), - new NotificationDelegate(profile), ash::kNotificationFamilyLinkIcon, + new NotificationDelegate(profile), kNotificationFamilyLinkIcon, message_center::SystemNotificationWarningLevel::NORMAL); NotificationDisplayService::GetForProfile(profile)->Display( NotificationHandler::Type::TRANSIENT, *notification,
diff --git a/chrome/browser/chromeos/assistant/assistant_util.cc b/chrome/browser/chromeos/assistant/assistant_util.cc index f6f079be..b8e481d 100644 --- a/chrome/browser/chromeos/assistant/assistant_util.cc +++ b/chrome/browser/chromeos/assistant/assistant_util.cc
@@ -15,7 +15,7 @@ #include "chromeos/constants/chromeos_switches.h" #include "components/language/core/browser/pref_names.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/user_manager/user_manager.h" #include "third_party/icu/source/common/unicode/locid.h" #include "ui/chromeos/events/keyboard_layout_util.h"
diff --git a/chrome/browser/chromeos/crostini/crostini_export_import_notification.cc b/chrome/browser/chromeos/crostini/crostini_export_import_notification.cc index d39ae8c4..08a1cc32 100644 --- a/chrome/browser/chromeos/crostini/crostini_export_import_notification.cc +++ b/chrome/browser/chromeos/crostini/crostini_export_import_notification.cc
@@ -5,8 +5,8 @@ #include "chrome/browser/chromeos/crostini/crostini_export_import_notification.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/chromeos/crostini/crostini_export_import.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/platform_util.h" @@ -68,7 +68,7 @@ } message_center::RichNotificationData rich_notification_data; - rich_notification_data.vector_small_image = &ash::kNotificationLinuxIcon; + rich_notification_data.vector_small_image = &kNotificationLinuxIcon; rich_notification_data.accent_color = ash::kSystemNotificationColorNormal; notification_ = std::make_unique<message_center::Notification>(
diff --git a/chrome/browser/chromeos/crostini/crostini_manager.cc b/chrome/browser/chromeos/crostini/crostini_manager.cc index f6325a3..03c75fe 100644 --- a/chrome/browser/chromeos/crostini/crostini_manager.cc +++ b/chrome/browser/chromeos/crostini/crostini_manager.cc
@@ -262,11 +262,34 @@ FinishRestart(CrostiniResult::VM_START_FAILED); return; } + // Cache kernel version for enterprise reporting, if it is enabled + // by policy, and we are in the default Termina/penguin case. + if (profile_->GetPrefs()->GetBoolean( + crostini::prefs::kReportCrostiniUsageEnabled) && + vm_name_ == kCrostiniDefaultVmName && + container_name_ == kCrostiniDefaultContainerName) { + crostini_manager_->GetTerminaVmKernelVersion(base::BindOnce( + &CrostiniRestarter::GetTerminaVmKernelVersionFinished, this)); + } crostini_manager_->CreateLxdContainer( vm_name_, container_name_, base::BindOnce(&CrostiniRestarter::CreateLxdContainerFinished, this)); } + void GetTerminaVmKernelVersionFinished( + const base::Optional<std::string>& maybe_kernel_version) { + // In the error case, Crostini should still start, so we do not propagate + // errors any further here. Also, any error would already have been logged + // by CrostiniManager, so here we just (re)set the kernel version pref to + // the empty string in case the response is empty. + std::string kernel_version; + if (maybe_kernel_version.has_value()) { + kernel_version = maybe_kernel_version.value(); + } + WriteTerminaVmKernelVersionToPrefsForReporting(profile_->GetPrefs(), + kernel_version); + } + void CreateLxdContainerFinished(CrostiniResult result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); for (auto& observer : observer_list_) { @@ -888,6 +911,17 @@ std::move(name), std::move(callback))); } +void CrostiniManager::GetTerminaVmKernelVersion( + GetTerminaVmKernelVersionCallback callback) { + vm_tools::concierge::GetVmEnterpriseReportingInfoRequest request; + request.set_vm_name(kCrostiniDefaultVmName); + request.set_owner_id(owner_id_); + GetConciergeClient()->GetVmEnterpriseReportingInfo( + std::move(request), + base::BindOnce(&CrostiniManager::OnGetTerminaVmKernelVersion, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); +} + void CrostiniManager::CreateLxdContainer(std::string vm_name, std::string container_name, CrostiniResultCallback callback) { @@ -1756,6 +1790,26 @@ std::move(callback).Run(CrostiniResult::SUCCESS); } +void CrostiniManager::OnGetTerminaVmKernelVersion( + GetTerminaVmKernelVersionCallback callback, + base::Optional<vm_tools::concierge::GetVmEnterpriseReportingInfoResponse> + response) { + if (!response) { + LOG(ERROR) << "No reply to GetVmEnterpriseReportingInfo"; + std::move(callback).Run(base::nullopt); + return; + } + + if (!response->success()) { + LOG(ERROR) << "Error response for GetVmEnterpriseReportingInfo: " + << response->failure_reason(); + std::move(callback).Run(base::nullopt); + return; + } + + std::move(callback).Run(response->vm_kernel_version()); +} + void CrostiniManager::OnContainerStarted( const vm_tools::cicerone::ContainerStartedSignal& signal) { if (signal.owner_id() != owner_id_)
diff --git a/chrome/browser/chromeos/crostini/crostini_manager.h b/chrome/browser/chromeos/crostini/crostini_manager.h index ffc20ffa..81f1716c 100644 --- a/chrome/browser/chromeos/crostini/crostini_manager.h +++ b/chrome/browser/chromeos/crostini/crostini_manager.h
@@ -344,6 +344,12 @@ // or after the method call finishes. void StopVm(std::string name, CrostiniResultCallback callback); + // Asynchronously retrieve the Termina VM kernel version using + // concierge's GetVmEnterpriseReportingInfo method. + using GetTerminaVmKernelVersionCallback = base::OnceCallback<void( + const base::Optional<std::string>& maybe_kernel_version)>; + void GetTerminaVmKernelVersion(GetTerminaVmKernelVersionCallback callback); + // Checks the arguments for creating an Lxd container via // CiceroneClient::CreateLxdContainer. |callback| is called immediately if the // arguments are bad, or once the container has been created. @@ -649,6 +655,14 @@ CrostiniResultCallback callback, base::Optional<vm_tools::concierge::StopVmResponse> response); + // Callback for ConciergeClient::GetVmEnterpriseReportingInfo. + // Currently used to report the Termina kernel version for enterprise + // reporting. + void OnGetTerminaVmKernelVersion( + GetTerminaVmKernelVersionCallback callback, + base::Optional<vm_tools::concierge::GetVmEnterpriseReportingInfoResponse> + response); + // Callback for CrostiniManager::InstallCrostiniComponent. Must be called on // the UI thread. void OnInstallTerminaComponent(
diff --git a/chrome/browser/chromeos/crostini/crostini_manager_unittest.cc b/chrome/browser/chromeos/crostini/crostini_manager_unittest.cc index 50329b89..f156c3f 100644 --- a/chrome/browser/chromeos/crostini/crostini_manager_unittest.cc +++ b/chrome/browser/chromeos/crostini/crostini_manager_unittest.cc
@@ -35,6 +35,8 @@ const char kPackageID[] = "package;1;;"; constexpr int64_t kDiskSizeBytes = 4ll * 1024 * 1024 * 1024; // 4 GiB const uint8_t kUsbPort = 0x01; +const char kTerminaKernelVersion[] = + "4.19.56-05556-gca219a5b1086 #3 SMP PREEMPT Mon Jul 1 14:36:38 CEST 2019"; void ExpectFailure(base::OnceClosure closure, bool success) { EXPECT_FALSE(success); @@ -1008,6 +1010,85 @@ EXPECT_EQ(1, remove_crostini_callback_count_); } +class CrostiniManagerEnterpriseReportingTest + : public CrostiniManagerRestartTest { + public: + void SetUp() override { + CrostiniManagerRestartTest::SetUp(); + + // Ensure that Crostini restart is successful: + disk_mount_manager_mock_ = new chromeos::disks::MockDiskMountManager; + chromeos::disks::DiskMountManager::InitializeForTesting( + disk_mount_manager_mock_); + EXPECT_CALL(*disk_mount_manager_mock_, MountPath) + .WillOnce( + Invoke(this, &CrostiniManagerEnterpriseReportingTest::SshfsMount)); + + // Enable Crostini reporting: + profile()->GetPrefs()->SetBoolean(prefs::kReportCrostiniUsageEnabled, true); + } + + void TearDown() override { + chromeos::disks::DiskMountManager::Shutdown(); + CrostiniManagerRestartTest::TearDown(); + } +}; + +TEST_F(CrostiniManagerEnterpriseReportingTest, + LogKernelVersionForEnterpriseReportingSuccess) { + // Set success response for retrieving enterprise reporting info: + vm_tools::concierge::GetVmEnterpriseReportingInfoResponse response; + response.set_success(true); + response.set_vm_kernel_version(kTerminaKernelVersion); + fake_concierge_client_->set_get_vm_enterprise_reporting_info_response( + response); + + restart_id_ = crostini_manager()->RestartCrostini( + kCrostiniDefaultVmName, kCrostiniDefaultContainerName, + base::BindOnce(&CrostiniManagerRestartTest::RestartCrostiniCallback, + base::Unretained(this), run_loop()->QuitClosure()), + this); + run_loop()->Run(); + + EXPECT_TRUE(fake_concierge_client_->create_disk_image_called()); + EXPECT_TRUE(fake_concierge_client_->start_termina_vm_called()); + EXPECT_TRUE( + fake_concierge_client_->get_vm_enterprise_reporting_info_called()); + EXPECT_EQ(1, restart_crostini_callback_count_); + EXPECT_EQ(kTerminaKernelVersion, + profile()->GetPrefs()->GetString( + crostini::prefs::kCrostiniLastLaunchTerminaKernelVersion)); +} + +TEST_F(CrostiniManagerEnterpriseReportingTest, + LogKernelVersionForEnterpriseReportingFailure) { + // Set error response for retrieving enterprise reporting info: + vm_tools::concierge::GetVmEnterpriseReportingInfoResponse response; + response.set_success(false); + response.set_failure_reason("Don't feel like it"); + fake_concierge_client_->set_get_vm_enterprise_reporting_info_response( + response); + + restart_id_ = crostini_manager()->RestartCrostini( + kCrostiniDefaultVmName, kCrostiniDefaultContainerName, + base::BindOnce(&CrostiniManagerRestartTest::RestartCrostiniCallback, + base::Unretained(this), run_loop()->QuitClosure()), + this); + run_loop()->Run(); + + EXPECT_TRUE(fake_concierge_client_->create_disk_image_called()); + EXPECT_TRUE(fake_concierge_client_->start_termina_vm_called()); + EXPECT_TRUE( + fake_concierge_client_->get_vm_enterprise_reporting_info_called()); + EXPECT_EQ(1, restart_crostini_callback_count_); + // In case of an error, the pref should be (re)set to the empty string: + EXPECT_TRUE( + profile() + ->GetPrefs() + ->GetString(crostini::prefs::kCrostiniLastLaunchTerminaKernelVersion) + .empty()); +} + TEST_F(CrostiniManagerTest, ExportContainerSuccess) { crostini_manager()->ExportLxdContainer( kVmName, kContainerName, base::FilePath("export_path"),
diff --git a/chrome/browser/chromeos/crostini/crostini_package_notification.cc b/chrome/browser/chromeos/crostini/crostini_package_notification.cc index 19b2f229..dde9b440 100644 --- a/chrome/browser/chromeos/crostini/crostini_package_notification.cc +++ b/chrome/browser/chromeos/crostini/crostini_package_notification.cc
@@ -5,7 +5,7 @@ #include "chrome/browser/chromeos/crostini/crostini_package_notification.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/chromeos/crostini/crostini_package_service.h" #include "chrome/browser/chromeos/crostini/crostini_registry_service_factory.h" #include "chrome/browser/notifications/notification_display_service.h" @@ -59,7 +59,7 @@ CrostiniRegistryServiceFactory::GetForProfile(profile_)->AddObserver(this); } message_center::RichNotificationData rich_notification_data; - rich_notification_data.vector_small_image = &ash::kNotificationLinuxIcon; + rich_notification_data.vector_small_image = &kNotificationLinuxIcon; rich_notification_data.never_timeout = true; rich_notification_data.accent_color = ash::kSystemNotificationColorNormal;
diff --git a/chrome/browser/chromeos/crostini/crostini_pref_names.cc b/chrome/browser/chromeos/crostini/crostini_pref_names.cc index 938e2c72..6d64197 100644 --- a/chrome/browser/chromeos/crostini/crostini_pref_names.cc +++ b/chrome/browser/chromeos/crostini/crostini_pref_names.cc
@@ -37,7 +37,12 @@ // A boolean preference controlling Crostini usage reporting. const char kReportCrostiniUsageEnabled[] = "crostini.usage_reporting_enabled"; // Preferences used to store last launch information for reporting: -const char kCrostiniLastLaunchVersion[] = "crostini.last_launch.version"; +// Last launch Termina component version. +const char kCrostiniLastLaunchTerminaComponentVersion[] = + "crostini.last_launch.version"; +// Last launch Termina kernel version. +const char kCrostiniLastLaunchTerminaKernelVersion[] = + "crostini.last_launch.vm_kernel_version"; // The start of a three day window of the last app launch // stored as Java time (ms since epoch). const char kCrostiniLastLaunchTimeWindowStart[] = @@ -67,7 +72,10 @@ registry->RegisterBooleanPref(crostini::prefs::kReportCrostiniUsageEnabled, false); - registry->RegisterStringPref(kCrostiniLastLaunchVersion, std::string()); + registry->RegisterStringPref(kCrostiniLastLaunchTerminaComponentVersion, + std::string()); + registry->RegisterStringPref(kCrostiniLastLaunchTerminaKernelVersion, + std::string()); registry->RegisterInt64Pref(kCrostiniLastLaunchTimeWindowStart, 0u); registry->RegisterInt64Pref(kCrostiniLastDiskSize, 0u); registry->RegisterBooleanPref(kUserCrostiniAllowedByPolicy, true);
diff --git a/chrome/browser/chromeos/crostini/crostini_pref_names.h b/chrome/browser/chromeos/crostini/crostini_pref_names.h index 8b3f6e4e0..caae53e 100644 --- a/chrome/browser/chromeos/crostini/crostini_pref_names.h +++ b/chrome/browser/chromeos/crostini/crostini_pref_names.h
@@ -22,7 +22,8 @@ extern const char kUserCrostiniExportImportUIAllowedByPolicy[]; extern const char kReportCrostiniUsageEnabled[]; -extern const char kCrostiniLastLaunchVersion[]; +extern const char kCrostiniLastLaunchTerminaComponentVersion[]; +extern const char kCrostiniLastLaunchTerminaKernelVersion[]; extern const char kCrostiniLastLaunchTimeWindowStart[]; extern const char kCrostiniLastDiskSize[];
diff --git a/chrome/browser/chromeos/crostini/crostini_reporting_util.cc b/chrome/browser/chromeos/crostini/crostini_reporting_util.cc index 0d9b8bb6..8718b832 100644 --- a/chrome/browser/chromeos/crostini/crostini_reporting_util.cc +++ b/chrome/browser/chromeos/crostini/crostini_reporting_util.cc
@@ -31,8 +31,9 @@ profile_prefs->SetInt64(crostini::prefs::kCrostiniLastLaunchTimeWindowStart, last_launch_time_window_start.ToJavaTime()); - profile_prefs->SetString(crostini::prefs::kCrostiniLastLaunchVersion, - crostini_version); + profile_prefs->SetString( + crostini::prefs::kCrostiniLastLaunchTerminaComponentVersion, + crostini_version); } } // namespace @@ -45,6 +46,13 @@ } } +void WriteTerminaVmKernelVersionToPrefsForReporting( + PrefService* profile_prefs, + const std::string& kernel_version) { + profile_prefs->SetString( + crostini::prefs::kCrostiniLastLaunchTerminaKernelVersion, kernel_version); +} + base::Time GetThreeDayWindowStart(const base::Time& actual_time) { const base::Time actual_time_midnight = actual_time.UTCMidnight(); const base::TimeDelta delta = base::TimeDelta::FromDays(
diff --git a/chrome/browser/chromeos/crostini/crostini_reporting_util.h b/chrome/browser/chromeos/crostini/crostini_reporting_util.h index 80b0498..3d1d989b 100644 --- a/chrome/browser/chromeos/crostini/crostini_reporting_util.h +++ b/chrome/browser/chromeos/crostini/crostini_reporting_util.h
@@ -27,6 +27,13 @@ const component_updater::ComponentUpdateService* update_service, const base::Clock* clock); +// Cache the Termina VM kernel in profile prefs from where they +// are copied to the device status proto during status collection +// in case advanced Crostini reporting is enabled. +void WriteTerminaVmKernelVersionToPrefsForReporting( + PrefService* profile_prefs, + const std::string& kernel_version); + // "Coarsens" the given time to the start of a three-day time window. // Used for privacy reasons. base::Time GetThreeDayWindowStart(const base::Time& actual_time);
diff --git a/chrome/browser/chromeos/crostini/crostini_reporting_util_unittest.cc b/chrome/browser/chromeos/crostini/crostini_reporting_util_unittest.cc index ac232136..9578f50 100644 --- a/chrome/browser/chromeos/crostini/crostini_reporting_util_unittest.cc +++ b/chrome/browser/chromeos/crostini/crostini_reporting_util_unittest.cc
@@ -66,10 +66,11 @@ int64_t timestamp = preferences->GetInt64(prefs::kCrostiniLastLaunchTimeWindowStart); std::string termina_version = - preferences->GetString(prefs::kCrostiniLastLaunchVersion); + preferences->GetString(prefs::kCrostiniLastLaunchTerminaComponentVersion); EXPECT_FALSE( preferences->HasPrefPath(prefs::kCrostiniLastLaunchTimeWindowStart)); - EXPECT_FALSE(preferences->HasPrefPath(prefs::kCrostiniLastLaunchVersion)); + EXPECT_FALSE(preferences->HasPrefPath( + prefs::kCrostiniLastLaunchTerminaComponentVersion)); EXPECT_EQ(0, timestamp); EXPECT_TRUE(termina_version.empty()); @@ -80,7 +81,8 @@ &test_clock_); timestamp = preferences->GetInt64(prefs::kCrostiniLastLaunchTimeWindowStart); - termina_version = preferences->GetString(prefs::kCrostiniLastLaunchVersion); + termina_version = + preferences->GetString(prefs::kCrostiniLastLaunchTerminaComponentVersion); EXPECT_EQ(1535760000000, timestamp); // 1 Sep 2018 00:00:00 GMT EXPECT_EQ("1.33.7", termina_version); } @@ -104,7 +106,7 @@ const int64_t timestamp = preferences->GetInt64(prefs::kCrostiniLastLaunchTimeWindowStart); const std::string termina_version = - preferences->GetString(prefs::kCrostiniLastLaunchVersion); + preferences->GetString(prefs::kCrostiniLastLaunchTerminaComponentVersion); EXPECT_EQ(1535760000000, timestamp); // 1 Sep 2018 00:00:00 GMT EXPECT_TRUE(termina_version.empty()); }
diff --git a/chrome/browser/chromeos/eol_notification.cc b/chrome/browser/chromeos/eol_notification.cc index 711958f..63955b4 100644 --- a/chrome/browser/chromeos/eol_notification.cc +++ b/chrome/browser/chromeos/eol_notification.cc
@@ -5,8 +5,8 @@ #include "chrome/browser/chromeos/eol_notification.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/notifications/notification_display_service.h" @@ -156,7 +156,7 @@ message_center::NotifierType::SYSTEM_COMPONENT, kEolNotificationId), data, new EolNotificationDelegate(profile_), - ash::kNotificationEndOfSupportIcon, + kNotificationEndOfSupportIcon, message_center::SystemNotificationWarningLevel::NORMAL); NotificationDisplayServiceFactory::GetForProfile(profile_)->Display(
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc index 0dff8c8..b3681ca 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc
@@ -1607,7 +1607,9 @@ std::unique_ptr<api::autotest_private::SetTabletModeEnabled::Params> params( api::autotest_private::SetTabletModeEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); + ash::TabletMode::Waiter waiter(params->enabled); ash::TabletMode::Get()->SetEnabledForTest(params->enabled); + waiter.Wait(); return RespondNow(OneArgument( std::make_unique<base::Value>(ash::TabletMode::Get()->InTabletMode()))); }
diff --git a/chrome/browser/chromeos/extensions/input_method_api.cc b/chrome/browser/chromeos/extensions/input_method_api.cc index 866c2598..13b1706 100644 --- a/chrome/browser/chromeos/extensions/input_method_api.cc +++ b/chrome/browser/chromeos/extensions/input_method_api.cc
@@ -410,6 +410,14 @@ case input_method_private::UNDERLINE_STYLE_UNDERLINE: segment_info.style = InputMethodEngineBase::SEGMENT_STYLE_UNDERLINE; break; + case input_method_private::UNDERLINE_STYLE_DOUBLEUNDERLINE: + segment_info.style = + InputMethodEngineBase::SEGMENT_STYLE_DOUBLE_UNDERLINE; + break; + case input_method_private::UNDERLINE_STYLE_NOUNDERLINE: + segment_info.style = + InputMethodEngineBase::SEGMENT_STYLE_NO_UNDERLINE; + break; case input_method_private::UNDERLINE_STYLE_NONE: EXTENSION_FUNCTION_VALIDATE(false); break;
diff --git a/chrome/browser/chromeos/first_run/first_run.cc b/chrome/browser/chromeos/first_run/first_run.cc index 9b1648f..d433fa7 100644 --- a/chrome/browser/chromeos/first_run/first_run.cc +++ b/chrome/browser/chromeos/first_run/first_run.cc
@@ -30,7 +30,7 @@ #include "components/arc/arc_service_manager.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/sync_preferences/pref_service_syncable.h" #include "components/user_manager/user_manager.h"
diff --git a/chrome/browser/chromeos/hats/hats_notification_controller.cc b/chrome/browser/chromeos/hats/hats_notification_controller.cc index 53d4ea1..acb3e7a 100644 --- a/chrome/browser/chromeos/hats/hats_notification_controller.cc +++ b/chrome/browser/chromeos/hats/hats_notification_controller.cc
@@ -5,11 +5,11 @@ #include "chrome/browser/chromeos/hats/hats_notification_controller.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/task/post_task.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/hats/hats_dialog.h" #include "chrome/browser/chromeos/hats/hats_finch_helper.h" @@ -215,8 +215,7 @@ GURL(kNotificationOriginUrl), message_center::NotifierId( message_center::NotifierType::SYSTEM_COMPONENT, kNotifierHats), - message_center::RichNotificationData(), this, - ash::kNotificationGoogleIcon, + message_center::RichNotificationData(), this, kNotificationGoogleIcon, message_center::SystemNotificationWarningLevel::NORMAL); }
diff --git a/chrome/browser/chromeos/input_method/input_method_engine.cc b/chrome/browser/chromeos/input_method/input_method_engine.cc index 27a4edd..9d3b895 100644 --- a/chrome/browser/chromeos/input_method/input_method_engine.cc +++ b/chrome/browser/chromeos/input_method/input_method_engine.cc
@@ -330,6 +330,15 @@ return false; } +void InputMethodEngine::ConfirmCompositionText() { + ui::IMEInputContextHandlerInterface* input_context = + ui::IMEBridge::Get()->GetInputContextHandler(); + if (input_context) { + input_context->ConfirmCompositionText(); + composition_text_.reset(new ui::CompositionText()); + } +} + void InputMethodEngine::EnableInputView() { input_method::InputMethodManager::Get() ->GetActiveIMEState()
diff --git a/chrome/browser/chromeos/input_method/input_method_engine.h b/chrome/browser/chromeos/input_method/input_method_engine.h index 6ff8bce..8465090 100644 --- a/chrome/browser/chromeos/input_method/input_method_engine.h +++ b/chrome/browser/chromeos/input_method/input_method_engine.h
@@ -142,6 +142,7 @@ void DeleteSurroundingTextToInputContext(int offset, size_t number_of_chars) override; bool SendKeyEvent(ui::KeyEvent* event, const std::string& code) override; + void ConfirmCompositionText() override; // Enables overriding input view page to Virtual Keyboard window. void EnableInputView();
diff --git a/chrome/browser/chromeos/input_method/input_method_engine_unittest.cc b/chrome/browser/chromeos/input_method/input_method_engine_unittest.cc index 9e2f197..4adf824b 100644 --- a/chrome/browser/chromeos/input_method/input_method_engine_unittest.cc +++ b/chrome/browser/chromeos/input_method/input_method_engine_unittest.cc
@@ -333,5 +333,32 @@ EXPECT_EQ(ONCOMPOSITIONBOUNDSCHANGED, observer_->GetCallsBitmapAndReset()); } +// See https://crbug.com/980437. +TEST_F(InputMethodEngineTest, TestDisableAfterSetCompositionRange) { + CreateEngine(true); + FocusIn(ui::TEXT_INPUT_TYPE_TEXT); + engine_->Enable(kTestImeComponentId); + + const int context = engine_->GetContextIdForTesting(); + + std::string error; + engine_->CommitText(context, "text", &error); + EXPECT_EQ("", error); + EXPECT_EQ(1, mock_ime_input_context_handler_->commit_text_call_count()); + EXPECT_EQ("text", mock_ime_input_context_handler_->last_commit_text()); + + // Change composition range to include "text". + engine_->::input_method::InputMethodEngineBase::SetCompositionRange( + context, 0, 4, {}, &error); + EXPECT_EQ("", error); + + // Disable to commit + engine_->Disable(); + + EXPECT_EQ("", error); + EXPECT_EQ(2, mock_ime_input_context_handler_->commit_text_call_count()); + EXPECT_EQ("text", mock_ime_input_context_handler_->last_commit_text()); +} + } // namespace input_method } // namespace chromeos
diff --git a/chrome/browser/chromeos/input_method/textinput_browsertest.cc b/chrome/browser/chromeos/input_method/textinput_browsertest.cc index c85c37bd..3a910d93 100644 --- a/chrome/browser/chromeos/input_method/textinput_browsertest.cc +++ b/chrome/browser/chromeos/input_method/textinput_browsertest.cc
@@ -10,7 +10,7 @@ #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h"
diff --git a/chrome/browser/chromeos/input_method/textinput_surroundingtext_browsertest.cc b/chrome/browser/chromeos/input_method/textinput_surroundingtext_browsertest.cc index 4cfcbab..962a127 100644 --- a/chrome/browser/chromeos/input_method/textinput_surroundingtext_browsertest.cc +++ b/chrome/browser/chromeos/input_method/textinput_surroundingtext_browsertest.cc
@@ -7,6 +7,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/chromeos/input_method/textinput_test_helper.cc b/chrome/browser/chromeos/input_method/textinput_test_helper.cc index b69c4df..084e59af 100644 --- a/chrome/browser/chromeos/input_method/textinput_test_helper.cc +++ b/chrome/browser/chromeos/input_method/textinput_test_helper.cc
@@ -17,6 +17,7 @@ #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" +#include "content/public/test/test_utils.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_tree_host.h" #include "ui/base/ime/init/input_method_factory.h"
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_unittest_chromeos.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_unittest_chromeos.cc index 62b5910f..1a14a03 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_unittest_chromeos.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_unittest_chromeos.cc
@@ -31,7 +31,7 @@ #include "chromeos/services/device_sync/public/cpp/fake_device_sync_client.h" #include "chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup_client.h" #include "components/account_id/account_id.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/user_manager/scoped_user_manager.h" #include "content/public/test/test_browser_thread_bundle.h"
diff --git a/chrome/browser/chromeos/login/existing_user_controller.cc b/chrome/browser/chromeos/login/existing_user_controller.cc index b5f914f2..c1e128dfc 100644 --- a/chrome/browser/chromeos/login/existing_user_controller.cc +++ b/chrome/browser/chromeos/login/existing_user_controller.cc
@@ -9,7 +9,6 @@ #include <vector> #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/barrier_closure.h" #include "base/bind.h" #include "base/bind_helpers.h" @@ -25,6 +24,7 @@ #include "base/task/post_task.h" #include "base/values.h" #include "base/version.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chrome_notification_types.h"
diff --git a/chrome/browser/chromeos/login/login_browsertest.cc b/chrome/browser/chromeos/login/login_browsertest.cc index fed8f91..a9a9930c 100644 --- a/chrome/browser/chromeos/login/login_browsertest.cc +++ b/chrome/browser/chromeos/login/login_browsertest.cc
@@ -22,6 +22,7 @@ #include "chrome/test/base/interactive_test_utils.h" #include "chromeos/constants/chromeos_switches.h" #include "components/user_manager/user_names.h" +#include "content/public/test/test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "ui/gfx/geometry/test/rect_test_util.h"
diff --git a/chrome/browser/chromeos/login/signin/device_id_browsertest.cc b/chrome/browser/chromeos/login/signin/device_id_browsertest.cc index d8eb8e6c..e38fbf1e 100644 --- a/chrome/browser/chromeos/login/signin/device_id_browsertest.cc +++ b/chrome/browser/chromeos/login/signin/device_id_browsertest.cc
@@ -22,7 +22,7 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chromeos/constants/chromeos_switches.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/user_manager/known_user.h" #include "components/user_manager/remove_user_delegate.h" #include "components/user_manager/user_manager.h"
diff --git a/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc b/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc index e3f24aa9..0395ab16 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc +++ b/chrome/browser/chromeos/login/signin/oauth2_login_manager.cc
@@ -18,7 +18,7 @@ #include "chromeos/components/account_manager/account_manager_factory.h" #include "chromeos/constants/chromeos_switches.h" #include "components/account_id/account_id.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/user_manager/user_manager.h"
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc index 2ead40d..dc71f085 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc +++ b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc
@@ -60,7 +60,7 @@ #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user.h"
diff --git a/chrome/browser/chromeos/plugin_vm/plugin_vm_manager.cc b/chrome/browser/chromeos/plugin_vm/plugin_vm_manager.cc index 997e682..fe5f8f2e 100644 --- a/chrome/browser/chromeos/plugin_vm/plugin_vm_manager.cc +++ b/chrome/browser/chromeos/plugin_vm/plugin_vm_manager.cc
@@ -5,8 +5,8 @@ #include "chrome/browser/chromeos/plugin_vm/plugin_vm_manager.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind_helpers.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/chromeos/guest_os/guest_os_share_path.h" #include "chrome/browser/chromeos/plugin_vm/plugin_vm_files.h" #include "chrome/browser/chromeos/plugin_vm/plugin_vm_pref_names.h" @@ -85,7 +85,7 @@ message_center::NotifierType::SYSTEM_COMPONENT, kInvalidLicenseNotifierId), {}, new message_center::NotificationDelegate(), - ash::kNotificationPluginVmIcon, + kNotificationPluginVmIcon, message_center::SystemNotificationWarningLevel::CRITICAL_WARNING); notification->SetSystemPriority(); NotificationDisplayServiceFactory::GetForProfile(profile)->Display(
diff --git a/chrome/browser/chromeos/policy/secondary_google_account_signin_policy_handler.cc b/chrome/browser/chromeos/policy/secondary_google_account_signin_policy_handler.cc index d68d01c..6eccffa 100644 --- a/chrome/browser/chromeos/policy/secondary_google_account_signin_policy_handler.cc +++ b/chrome/browser/chromeos/policy/secondary_google_account_signin_policy_handler.cc
@@ -7,7 +7,7 @@ #include "components/policy/core/common/policy_map.h" #include "components/policy/policy_constants.h" #include "components/prefs/pref_value_map.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" namespace policy {
diff --git a/chrome/browser/chromeos/policy/secondary_google_account_signin_policy_handler_unittest.cc b/chrome/browser/chromeos/policy/secondary_google_account_signin_policy_handler_unittest.cc index de09538..46a69aa 100644 --- a/chrome/browser/chromeos/policy/secondary_google_account_signin_policy_handler_unittest.cc +++ b/chrome/browser/chromeos/policy/secondary_google_account_signin_policy_handler_unittest.cc
@@ -13,7 +13,7 @@ #include "components/policy/core/common/policy_pref_names.h" #include "components/policy/policy_constants.h" #include "components/prefs/pref_value_map.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "testing/gtest/include/gtest/gtest.h" namespace policy {
diff --git a/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc b/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc index d69c464..0e0b48d 100644 --- a/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc +++ b/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc
@@ -1936,7 +1936,7 @@ const int64_t last_launch_time_window_start = profile->GetPrefs()->GetInt64( crostini::prefs::kCrostiniLastLaunchTimeWindowStart); const std::string& termina_version = profile->GetPrefs()->GetString( - crostini::prefs::kCrostiniLastLaunchVersion); + crostini::prefs::kCrostiniLastLaunchTerminaComponentVersion); crostini_status->set_last_launch_time_window_start_timestamp( last_launch_time_window_start); crostini_status->set_last_launch_vm_image_version(termina_version); @@ -1944,6 +1944,10 @@ if (profile->GetPrefs()->GetBoolean(crostini::prefs::kCrostiniEnabled) && base::FeatureList::IsEnabled( features::kCrostiniAdditionalEnterpriseReporting)) { + const std::string& vm_kernel_version = profile->GetPrefs()->GetString( + crostini::prefs::kCrostiniLastLaunchTerminaKernelVersion); + crostini_status->set_last_launch_vm_kernel_version(vm_kernel_version); + AddCrostiniAppListForProfile(profile, crostini_status); }
diff --git a/chrome/browser/chromeos/policy/status_collector/device_status_collector_browsertest.cc b/chrome/browser/chromeos/policy/status_collector/device_status_collector_browsertest.cc index d5a1b51..40d52cf 100644 --- a/chrome/browser/chromeos/policy/status_collector/device_status_collector_browsertest.cc +++ b/chrome/browser/chromeos/policy/status_collector/device_status_collector_browsertest.cc
@@ -126,7 +126,9 @@ // Constants for Crostini reporting test cases: const char kCrostiniUserEmail[] = "user0@managed.com"; -const char kTerminaVmVersion[] = "1.33.7"; +const char kTerminaVmComponentVersion[] = "1.33.7"; +const char kTerminaVmKernelVersion[] = + "4.19.56-05556-gca219a5b1086 #3 SMP PREEMPT Mon Jul 1 14:36:38 CEST 2019"; const char kActualLastLaunchTimeFormatted[] = "Sat, 1 Sep 2018 11:50:50 GMT"; const char kLastLaunchTimeWindowStartFormatted[] = "Sat, 1 Sep 2018 00:00:00 GMT"; @@ -1551,7 +1553,8 @@ testing_profile_->GetPrefs()->SetBoolean( crostini::prefs::kReportCrostiniUsageEnabled, true); testing_profile_->GetPrefs()->SetString( - crostini::prefs::kCrostiniLastLaunchVersion, kTerminaVmVersion); + crostini::prefs::kCrostiniLastLaunchTerminaComponentVersion, + kTerminaVmComponentVersion); testing_profile_->GetPrefs()->SetInt64( crostini::prefs::kCrostiniLastLaunchTimeWindowStart, kLastLaunchTimeWindowStartInJavaTime); @@ -1561,7 +1564,7 @@ EXPECT_EQ(kLastLaunchTimeWindowStartInJavaTime, session_status_.crostini_status() .last_launch_time_window_start_timestamp()); - EXPECT_EQ(kTerminaVmVersion, + EXPECT_EQ(kTerminaVmComponentVersion, session_status_.crostini_status().last_launch_vm_image_version()); // In tests, GetUserDMToken returns the e-mail for easy verification. EXPECT_EQ(account_id.GetUserEmail(), session_status_.user_dm_token()); @@ -1589,6 +1592,49 @@ EXPECT_FALSE(got_session_status_); } +TEST_F(DeviceStatusCollectorTest, CrostiniTerminaVmKernelVersionReporting) { + RestartStatusCollector( + base::BindRepeating(&GetEmptyVolumeInfo), + base::BindRepeating(&GetEmptyCPUStatistics), + base::BindRepeating(&GetEmptyCPUTempInfo), + base::BindRepeating(&GetFakeAndroidStatus, kArcStatus, kDroidGuardInfo), + base::BindRepeating(&GetEmptyTpmStatus), + base::BindRepeating(&GetEmptyEMMCLifetimeEstimation)); + + // Prerequisites for any Crostini reporting to take place: + const AccountId account_id(AccountId::FromUserEmail(kCrostiniUserEmail)); + MockRegularUserWithAffiliation(account_id, true); + testing_profile_->GetPrefs()->SetBoolean( + crostini::prefs::kReportCrostiniUsageEnabled, true); + testing_profile_->GetPrefs()->SetInt64( + crostini::prefs::kCrostiniLastLaunchTimeWindowStart, + kLastLaunchTimeWindowStartInJavaTime); + testing_profile_->GetPrefs()->SetBoolean(crostini::prefs::kCrostiniEnabled, + true); + + // Set the kernel version to be reported in our cache: + testing_profile_->GetPrefs()->SetString( + crostini::prefs::kCrostiniLastLaunchTerminaKernelVersion, + kTerminaVmKernelVersion); + + // Check that nothing is reported when the feature flag is not enabled: + GetStatus(); + EXPECT_TRUE(got_session_status_); + EXPECT_TRUE(session_status_.crostini_status() + .last_launch_vm_kernel_version() + .empty()); + + scoped_feature_list_.InitAndEnableFeature( + features::kCrostiniAdditionalEnterpriseReporting); + + // Check that the kernel version is reported now that the feature flag is + // enabled: + GetStatus(); + EXPECT_TRUE(got_session_status_); + EXPECT_EQ(kTerminaVmKernelVersion, + session_status_.crostini_status().last_launch_vm_kernel_version()); +} + TEST_F(DeviceStatusCollectorTest, CrostiniAppUsageReporting) { RestartStatusCollector( base::BindRepeating(&GetEmptyVolumeInfo), @@ -1603,7 +1649,8 @@ testing_profile_->GetPrefs()->SetBoolean( crostini::prefs::kReportCrostiniUsageEnabled, true); testing_profile_->GetPrefs()->SetString( - crostini::prefs::kCrostiniLastLaunchVersion, kTerminaVmVersion); + crostini::prefs::kCrostiniLastLaunchTerminaComponentVersion, + kTerminaVmComponentVersion); testing_profile_->GetPrefs()->SetInt64( crostini::prefs::kCrostiniLastLaunchTimeWindowStart, kLastLaunchTimeWindowStartInJavaTime); @@ -1690,7 +1737,8 @@ testing_profile_->GetPrefs()->SetBoolean( crostini::prefs::kReportCrostiniUsageEnabled, true); testing_profile_->GetPrefs()->SetString( - crostini::prefs::kCrostiniLastLaunchVersion, kTerminaVmVersion); + crostini::prefs::kCrostiniLastLaunchTerminaComponentVersion, + kTerminaVmComponentVersion); testing_profile_->GetPrefs()->SetInt64( crostini::prefs::kCrostiniLastLaunchTimeWindowStart, kLastLaunchTimeWindowStartInJavaTime);
diff --git a/chrome/browser/chromeos/printing/cups_print_job_notification.cc b/chrome/browser/chromeos/printing/cups_print_job_notification.cc index d132c75..218a961 100644 --- a/chrome/browser/chromeos/printing/cups_print_job_notification.cc +++ b/chrome/browser/chromeos/printing/cups_print_job_notification.cc
@@ -5,10 +5,10 @@ #include "chrome/browser/chromeos/printing/cups_print_job_notification.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/chromeos/printing/cups_print_job.h" #include "chrome/browser/chromeos/printing/cups_print_job_manager.h" #include "chrome/browser/chromeos/printing/cups_print_job_manager_factory.h" @@ -208,17 +208,16 @@ case CupsPrintJob::State::STATE_SUSPENDED: case CupsPrintJob::State::STATE_RESUMED: notification_->set_accent_color(ash::kSystemNotificationColorNormal); - notification_->set_vector_small_image(ash::kNotificationPrintingIcon); + notification_->set_vector_small_image(kNotificationPrintingIcon); break; case CupsPrintJob::State::STATE_DOCUMENT_DONE: notification_->set_accent_color(ash::kSystemNotificationColorNormal); - notification_->set_vector_small_image(ash::kNotificationPrintingDoneIcon); + notification_->set_vector_small_image(kNotificationPrintingDoneIcon); break; case CupsPrintJob::State::STATE_CANCELLED: case CupsPrintJob::State::STATE_ERROR: notification_->set_accent_color(ash::kSystemNotificationColorWarning); - notification_->set_vector_small_image( - ash::kNotificationPrintingWarningIcon); + notification_->set_vector_small_image(kNotificationPrintingWarningIcon); break; case CupsPrintJob::State::STATE_NONE: break;
diff --git a/chrome/browser/chromeos/printing/usb_printer_notification.cc b/chrome/browser/chromeos/printing/usb_printer_notification.cc index 9a9c3672..000e60b 100644 --- a/chrome/browser/chromeos/printing/usb_printer_notification.cc +++ b/chrome/browser/chromeos/printing/usb_printer_notification.cc
@@ -5,9 +5,9 @@ #include "chrome/browser/chromeos/printing/usb_printer_notification.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/notifications/notification_handler.h" #include "chrome/browser/profiles/profile.h" @@ -40,7 +40,7 @@ profile_(profile), weak_factory_(this) { message_center::RichNotificationData rich_notification_data; - rich_notification_data.vector_small_image = &ash::kNotificationPrintingIcon; + rich_notification_data.vector_small_image = &kNotificationPrintingIcon; rich_notification_data.accent_color = ash::kSystemNotificationColorNormal; notification_ = std::make_unique<message_center::Notification>(
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service.cc b/chrome/browser/chromeos/settings/device_oauth2_token_service.cc index 715e9ad..af54fae 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service.cc +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service.cc
@@ -14,10 +14,19 @@ #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" +#include "chrome/browser/chromeos/settings/token_encryptor.h" #include "chrome/common/pref_names.h" +#include "chromeos/cryptohome/system_salt_getter.h" +#include "chromeos/settings/cros_settings_names.h" +#include "components/policy/proto/device_management_backend.pb.h" #include "components/prefs/pref_registry_simple.h" +#include "components/prefs/pref_service.h" +#include "google_apis/gaia/gaia_constants.h" +#include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/google_service_auth_error.h" +#include "google_apis/gaia/oauth2_access_token_consumer.h" #include "google_apis/gaia/oauth2_access_token_fetcher.h" +#include "google_apis/gaia/oauth2_access_token_fetcher_impl.h" #include "services/network/public/cpp/shared_url_loader_factory.h" namespace chromeos { @@ -39,26 +48,31 @@ const OAuth2AccessTokenManager::ScopeSet scopes; }; -void DeviceOAuth2TokenService::OnValidationCompleted( - GoogleServiceAuthError::State error) { - if (error == GoogleServiceAuthError::NONE) - FlushPendingRequests(true, GoogleServiceAuthError::NONE); - else - FlushPendingRequests(false, error); -} - DeviceOAuth2TokenService::DeviceOAuth2TokenService( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - PrefService* local_state) { - delegate_ = std::make_unique<DeviceOAuth2TokenServiceDelegate>( - url_loader_factory, local_state, this); + PrefService* local_state) + : url_loader_factory_(url_loader_factory), + local_state_(local_state), + state_(STATE_LOADING), + max_refresh_token_validation_retries_(3), + validation_requested_(false), + service_account_identity_subscription_( + CrosSettings::Get()->AddSettingsObserver( + kServiceAccountIdentity, + base::Bind( + &DeviceOAuth2TokenService::OnServiceAccountIdentityChanged, + base::Unretained(this)))), + weak_ptr_factory_(this) { token_manager_ = std::make_unique<OAuth2AccessTokenManager>( this /* OAuth2AccessTokenManager::Delegate* */); - delegate_->InitializeWithValidationStatusDelegate(this); + // Pull in the system salt. + SystemSaltGetter::Get()->GetSystemSalt( + base::Bind(&DeviceOAuth2TokenService::DidGetSystemSalt, + weak_ptr_factory_.GetWeakPtr())); } DeviceOAuth2TokenService::~DeviceOAuth2TokenService() { - delegate_->ClearValidationStatusDelegate(); + FlushTokenSaveCallbacks(false); FlushPendingRequests(false, GoogleServiceAuthError::REQUEST_CANCELED); } @@ -71,16 +85,40 @@ void DeviceOAuth2TokenService::SetAndSaveRefreshToken( const std::string& refresh_token, const StatusCallback& result_callback) { - delegate_->SetAndSaveRefreshToken(refresh_token, result_callback); + ReportServiceError(GoogleServiceAuthError::REQUEST_CANCELED); + + bool waiting_for_salt = state_ == STATE_LOADING; + refresh_token_ = refresh_token; + state_ = STATE_VALIDATION_PENDING; + + // If the robot account ID is not available yet, do not announce the token. It + // will be done from OnServiceAccountIdentityChanged() once the robot account + // ID becomes available as well. + if (!GetRobotAccountId().empty()) + FireRefreshTokenAvailable(GetRobotAccountId()); + + token_save_callbacks_.push_back(result_callback); + if (!waiting_for_salt) { + if (system_salt_.empty()) + FlushTokenSaveCallbacks(false); + else + EncryptAndSaveToken(); + } } -std::string DeviceOAuth2TokenService::GetRobotAccountId() const { - return delegate_->GetRobotAccountId(); +CoreAccountId DeviceOAuth2TokenService::GetRobotAccountId() const { + if (!robot_account_id_for_testing_.empty()) { + return robot_account_id_for_testing_; + } + + std::string account_id; + CrosSettings::Get()->GetString(kServiceAccountIdentity, &account_id); + return CoreAccountId(account_id); } void DeviceOAuth2TokenService::set_robot_account_id_for_testing( const CoreAccountId& account_id) { - delegate_->set_robot_account_id_for_testing(account_id); + robot_account_id_for_testing_ = account_id; } void DeviceOAuth2TokenService::SetRefreshTokenAvailableCallback( @@ -110,20 +148,56 @@ bool DeviceOAuth2TokenService::RefreshTokenIsAvailable( const CoreAccountId& account_id) const { - return delegate_->RefreshTokenIsAvailable(account_id); + auto accounts = GetAccounts(); + return std::find(accounts.begin(), accounts.end(), account_id) != + accounts.end(); } OAuth2AccessTokenManager* DeviceOAuth2TokenService::GetAccessTokenManager() { return token_manager_.get(); } +void DeviceOAuth2TokenService::OnRefreshTokenResponse( + const std::string& access_token, + int expires_in_seconds) { + gaia_oauth_client_->GetTokenInfo(access_token, + max_refresh_token_validation_retries_, this); +} + +void DeviceOAuth2TokenService::OnGetTokenInfoResponse( + std::unique_ptr<base::DictionaryValue> token_info) { + std::string gaia_robot_id; + // For robot accounts email id is the account id. + token_info->GetString("email", &gaia_robot_id); + gaia_oauth_client_.reset(); + + CheckRobotAccountId(CoreAccountId(gaia_robot_id)); +} + +void DeviceOAuth2TokenService::OnOAuthError() { + gaia_oauth_client_.reset(); + state_ = STATE_TOKEN_INVALID; + ReportServiceError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); +} + +void DeviceOAuth2TokenService::OnNetworkError(int response_code) { + gaia_oauth_client_.reset(); + + // Go back to pending validation state. That'll allow a retry on subsequent + // token minting requests. + state_ = STATE_VALIDATION_PENDING; + ReportServiceError(GoogleServiceAuthError::CONNECTION_FAILED); +} + std::unique_ptr<OAuth2AccessTokenFetcher> DeviceOAuth2TokenService::CreateAccessTokenFetcher( const CoreAccountId& account_id, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, OAuth2AccessTokenConsumer* consumer) { - return delegate_->CreateAccessTokenFetcher(account_id, url_loader_factory, - consumer); + std::string refresh_token = GetRefreshToken(); + DCHECK(!refresh_token.empty()); + return std::make_unique<OAuth2AccessTokenFetcherImpl>( + consumer, url_loader_factory, refresh_token); } bool DeviceOAuth2TokenService::HasRefreshToken( @@ -133,7 +207,7 @@ scoped_refptr<network::SharedURLLoaderFactory> DeviceOAuth2TokenService::GetURLLoaderFactory() const { - return delegate_->GetURLLoaderFactory(); + return url_loader_factory_; } void DeviceOAuth2TokenService::FireRefreshTokenAvailable( @@ -155,30 +229,30 @@ const std::string& client_id, const std::string& client_secret, const OAuth2AccessTokenManager::ScopeSet& scopes) { - switch (delegate_->state_) { - case DeviceOAuth2TokenServiceDelegate::STATE_VALIDATION_PENDING: + switch (state_) { + case STATE_VALIDATION_PENDING: // If this is the first request for a token, start validation. - delegate_->StartValidation(); + StartValidation(); FALLTHROUGH; - case DeviceOAuth2TokenServiceDelegate::STATE_LOADING: - case DeviceOAuth2TokenServiceDelegate::STATE_VALIDATION_STARTED: + case STATE_LOADING: + case STATE_VALIDATION_STARTED: // Add a pending request that will be satisfied once validation completes. pending_requests_.push_back(new PendingRequest( request->AsWeakPtr(), client_id, client_secret, scopes)); - delegate_->RequestValidation(); + RequestValidation(); return true; - case DeviceOAuth2TokenServiceDelegate::STATE_NO_TOKEN: + case STATE_NO_TOKEN: FailRequest(request, GoogleServiceAuthError::USER_NOT_SIGNED_UP); return true; - case DeviceOAuth2TokenServiceDelegate::STATE_TOKEN_INVALID: + case STATE_TOKEN_INVALID: FailRequest(request, GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); return true; - case DeviceOAuth2TokenServiceDelegate::STATE_TOKEN_VALID: + case STATE_TOKEN_VALID: // Let OAuth2AccessTokenManager handle the request. return false; } - NOTREACHED() << "Unexpected state " << delegate_->state_; + NOTREACHED() << "Unexpected state " << state_; return false; } @@ -197,9 +271,9 @@ if (token_is_valid) { token_manager_->FetchOAuth2Token( scoped_request->request.get(), - scoped_request->request->GetAccountId(), - delegate_->GetURLLoaderFactory(), scoped_request->client_id, - scoped_request->client_secret, scoped_request->scopes); + scoped_request->request->GetAccountId(), GetURLLoaderFactory(), + scoped_request->client_id, scoped_request->client_secret, + scoped_request->scopes); } else { FailRequest(scoped_request->request.get(), error); } @@ -221,4 +295,191 @@ request->AsWeakPtr(), auth_error, OAuth2AccessTokenConsumer::TokenResponse())); } + +std::vector<CoreAccountId> DeviceOAuth2TokenService::GetAccounts() const { + std::vector<CoreAccountId> accounts; + switch (state_) { + case STATE_NO_TOKEN: + case STATE_TOKEN_INVALID: + return accounts; + case STATE_LOADING: + case STATE_VALIDATION_PENDING: + case STATE_VALIDATION_STARTED: + case STATE_TOKEN_VALID: + if (!GetRobotAccountId().empty()) + accounts.push_back(GetRobotAccountId()); + return accounts; + } + + NOTREACHED() << "Unhandled state " << state_; + return accounts; +} + +void DeviceOAuth2TokenService::OnServiceAccountIdentityChanged() { + if (!GetRobotAccountId().empty() && !refresh_token_.empty()) + FireRefreshTokenAvailable(GetRobotAccountId()); +} + +void DeviceOAuth2TokenService::CheckRobotAccountId( + const CoreAccountId& gaia_robot_id) { + // Make sure the value returned by GetRobotAccountId has been validated + // against current device settings. + switch (CrosSettings::Get()->PrepareTrustedValues( + base::Bind(&DeviceOAuth2TokenService::CheckRobotAccountId, + weak_ptr_factory_.GetWeakPtr(), gaia_robot_id))) { + case CrosSettingsProvider::TRUSTED: + // All good, compare account ids below. + break; + case CrosSettingsProvider::TEMPORARILY_UNTRUSTED: + // The callback passed to PrepareTrustedValues above will trigger a + // re-check eventually. + return; + case CrosSettingsProvider::PERMANENTLY_UNTRUSTED: + // There's no trusted account id, which is equivalent to no token present. + LOG(WARNING) << "Device settings permanently untrusted."; + state_ = STATE_NO_TOKEN; + ReportServiceError(GoogleServiceAuthError::USER_NOT_SIGNED_UP); + return; + } + + CoreAccountId policy_robot_id = GetRobotAccountId(); + if (policy_robot_id == gaia_robot_id) { + state_ = STATE_TOKEN_VALID; + ReportServiceError(GoogleServiceAuthError::NONE); + } else { + if (gaia_robot_id.empty()) { + LOG(WARNING) << "Device service account owner in policy is empty."; + } else { + LOG(WARNING) << "Device service account owner in policy does not match " + << "refresh token owner \"" << gaia_robot_id << "\"."; + } + state_ = STATE_TOKEN_INVALID; + ReportServiceError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); + } +} + +std::string DeviceOAuth2TokenService::GetRefreshToken() const { + switch (state_) { + case STATE_LOADING: + case STATE_NO_TOKEN: + case STATE_TOKEN_INVALID: + // This shouldn't happen: GetRefreshToken() is only called for actual + // token minting operations. In above states, requests are either queued + // or short-circuited to signal error immediately, so no actual token + // minting via OAuth2TokenService::FetchOAuth2Token should be triggered. + NOTREACHED(); + return std::string(); + case STATE_VALIDATION_PENDING: + case STATE_VALIDATION_STARTED: + case STATE_TOKEN_VALID: + return refresh_token_; + } + + NOTREACHED() << "Unhandled state " << state_; + return std::string(); +} + +void DeviceOAuth2TokenService::DidGetSystemSalt( + const std::string& system_salt) { + system_salt_ = system_salt; + + // Bail out if system salt is not available. + if (system_salt_.empty()) { + LOG(ERROR) << "Failed to get system salt."; + FlushTokenSaveCallbacks(false); + state_ = STATE_NO_TOKEN; + return; + } + + // If the token has been set meanwhile, write it to |local_state_|. + if (!refresh_token_.empty()) { + EncryptAndSaveToken(); + return; + } + + // Otherwise, load the refresh token from |local_state_|. + std::string encrypted_refresh_token = + local_state_->GetString(prefs::kDeviceRobotAnyApiRefreshToken); + if (!encrypted_refresh_token.empty()) { + CryptohomeTokenEncryptor encryptor(system_salt_); + refresh_token_ = encryptor.DecryptWithSystemSalt(encrypted_refresh_token); + if (refresh_token_.empty()) { + LOG(ERROR) << "Failed to decrypt refresh token."; + state_ = STATE_NO_TOKEN; + return; + } + } + + state_ = STATE_VALIDATION_PENDING; + + // If there are pending requests, start a validation. + if (validation_requested_) + StartValidation(); + + // Announce the token. + if (!GetRobotAccountId().empty()) { + FireRefreshTokenAvailable(GetRobotAccountId()); + } +} + +void DeviceOAuth2TokenService::EncryptAndSaveToken() { + DCHECK_NE(state_, STATE_LOADING); + + CryptohomeTokenEncryptor encryptor(system_salt_); + std::string encrypted_refresh_token = + encryptor.EncryptWithSystemSalt(refresh_token_); + bool result = true; + if (encrypted_refresh_token.empty()) { + LOG(ERROR) << "Failed to encrypt refresh token; save aborted."; + result = false; + } else { + local_state_->SetString(prefs::kDeviceRobotAnyApiRefreshToken, + encrypted_refresh_token); + } + + FlushTokenSaveCallbacks(result); +} + +void DeviceOAuth2TokenService::FlushTokenSaveCallbacks(bool result) { + std::vector<StatusCallback> callbacks; + callbacks.swap(token_save_callbacks_); + for (std::vector<StatusCallback>::iterator callback(callbacks.begin()); + callback != callbacks.end(); ++callback) { + if (!callback->is_null()) + callback->Run(result); + } +} + +void DeviceOAuth2TokenService::StartValidation() { + DCHECK_EQ(state_, STATE_VALIDATION_PENDING); + DCHECK(!gaia_oauth_client_); + + state_ = STATE_VALIDATION_STARTED; + + gaia_oauth_client_ = + std::make_unique<gaia::GaiaOAuthClient>(url_loader_factory_); + + GaiaUrls* gaia_urls = GaiaUrls::GetInstance(); + gaia::OAuthClientInfo client_info; + client_info.client_id = gaia_urls->oauth2_chrome_client_id(); + client_info.client_secret = gaia_urls->oauth2_chrome_client_secret(); + + gaia_oauth_client_->RefreshToken( + client_info, refresh_token_, + std::vector<std::string>(1, GaiaConstants::kOAuthWrapBridgeUserInfoScope), + max_refresh_token_validation_retries_, this); +} + +void DeviceOAuth2TokenService::RequestValidation() { + validation_requested_ = true; +} + +void DeviceOAuth2TokenService::ReportServiceError( + GoogleServiceAuthError::State error) { + if (error == GoogleServiceAuthError::NONE) + FlushPendingRequests(true, GoogleServiceAuthError::NONE); + else + FlushPendingRequests(false, error); +} + } // namespace chromeos
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service.h b/chrome/browser/chromeos/settings/device_oauth2_token_service.h index 0c8b3fe..106dbc98 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service.h +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service.h
@@ -10,16 +10,19 @@ #include "base/callback.h" #include "base/macros.h" -#include "chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/chromeos/settings/cros_settings.h" #include "google_apis/gaia/core_account_id.h" +#include "google_apis/gaia/gaia_oauth_client.h" #include "google_apis/gaia/google_service_auth_error.h" -#include "google_apis/gaia/oauth2_access_token_consumer.h" #include "google_apis/gaia/oauth2_access_token_manager.h" namespace network { class SharedURLLoaderFactory; } +class OAuth2AccessTokenFetcher; +class OAuth2AccessTokenConsumer; class PrefRegistrySimple; class PrefService; @@ -32,9 +35,8 @@ // be used in places where API expects |account_id|. // // Note that requests must be made from the UI thread. -class DeviceOAuth2TokenService - : public OAuth2AccessTokenManager::Delegate, - public DeviceOAuth2TokenServiceDelegate::ValidationStatusDelegate { +class DeviceOAuth2TokenService : public OAuth2AccessTokenManager::Delegate, + public gaia::GaiaOAuthClient::Delegate { public: typedef base::RepeatingCallback<void(const CoreAccountId& /* account_id */)> RefreshTokenAvailableCallback; @@ -52,7 +54,7 @@ static void RegisterPrefs(PrefRegistrySimple* registry); // Pull the robot account ID from device policy. - virtual std::string GetRobotAccountId() const; + CoreAccountId GetRobotAccountId() const; // Can be used to override the robot account ID for testing purposes. Most // common use case is to easily inject a non-empty account ID to make the @@ -92,14 +94,35 @@ OAuth2AccessTokenManager* GetAccessTokenManager(); + // gaia::GaiaOAuthClient::Delegate implementation. + void OnRefreshTokenResponse(const std::string& access_token, + int expires_in_seconds) override; + void OnGetTokenInfoResponse( + std::unique_ptr<base::DictionaryValue> token_info) override; + void OnOAuthError() override; + void OnNetworkError(int response_code) override; + private: - // TODO(https://crbug.com/967598): Merge DeviceOAuth2TokenServiceDelegate - // into DeviceOAuth2TokenService. - friend class DeviceOAuth2TokenServiceDelegate; friend class DeviceOAuth2TokenServiceFactory; friend class DeviceOAuth2TokenServiceTest; struct PendingRequest; + // Describes the operational state of this object. + enum State { + // Pending system salt / refresh token load. + STATE_LOADING, + // No token available. + STATE_NO_TOKEN, + // System salt loaded, validation not started yet. + STATE_VALIDATION_PENDING, + // Refresh token validation underway. + STATE_VALIDATION_STARTED, + // Token validation failed. + STATE_TOKEN_INVALID, + // Refresh token is valid. + STATE_TOKEN_VALID, + }; + // OAuth2AccessTokenManager::Delegate: std::unique_ptr<OAuth2AccessTokenFetcher> CreateAccessTokenFetcher( const CoreAccountId& account_id, @@ -119,10 +142,6 @@ void FireRefreshTokenAvailable(const CoreAccountId& account_id); void FireRefreshTokenRevoked(const CoreAccountId& account_id); - // Implementation of - // DeviceOAuth2TokenServiceDelegate::ValidationStatusDelegate. - void OnValidationCompleted(GoogleServiceAuthError::State error) override; - // Use DeviceOAuth2TokenServiceFactory to get an instance of this class. explicit DeviceOAuth2TokenService( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, @@ -137,9 +156,36 @@ void FailRequest(OAuth2AccessTokenManager::RequestImpl* request, GoogleServiceAuthError::State error); - // TODO(https://crbug.com/967598): Merge DeviceOAuth2TokenServiceDelegate - // into DeviceOAuth2TokenService. - std::unique_ptr<DeviceOAuth2TokenServiceDelegate> delegate_; + // Returns a list of accounts based on |state_|. + std::vector<CoreAccountId> GetAccounts() const; + + // Starts the token validation flow, i.e. token info fetch. + void StartValidation(); + + void RequestValidation(); + + // Invoked by CrosSettings when the robot account ID becomes available. + void OnServiceAccountIdentityChanged(); + + // Checks whether |gaia_robot_id| matches the expected account ID indicated in + // device settings. + void CheckRobotAccountId(const CoreAccountId& gaia_robot_id); + + // Returns the refresh token for the robot account id. + std::string GetRefreshToken() const; + + // Handles completion of the system salt input. + void DidGetSystemSalt(const std::string& system_salt); + + // Encrypts and saves the refresh token. Should only be called when the system + // salt is available. + void EncryptAndSaveToken(); + + // Flushes |token_save_callbacks_|, indicating the specified result. + void FlushTokenSaveCallbacks(bool result); + + void ReportServiceError(GoogleServiceAuthError::State error); + std::unique_ptr<OAuth2AccessTokenManager> token_manager_; // Currently open requests that are waiting while loading the system salt or @@ -150,6 +196,36 @@ RefreshTokenAvailableCallback on_refresh_token_available_callback_; RefreshTokenRevokedCallback on_refresh_token_revoked_callback_; + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; + + PrefService* local_state_; + + // Current operational state. + State state_; + + // Token save callbacks waiting to be completed. + std::vector<StatusCallback> token_save_callbacks_; + + // The system salt for encrypting and decrypting the refresh token. + std::string system_salt_; + + int max_refresh_token_validation_retries_; + + // Flag to indicate whether there are pending requests. + bool validation_requested_; + + // Cache the decrypted refresh token, so we only decrypt once. + std::string refresh_token_; + + std::unique_ptr<gaia::GaiaOAuthClient> gaia_oauth_client_; + + std::unique_ptr<CrosSettings::ObserverSubscription> + service_account_identity_subscription_; + + CoreAccountId robot_account_id_for_testing_; + + base::WeakPtrFactory<DeviceOAuth2TokenService> weak_ptr_factory_; + DISALLOW_COPY_AND_ASSIGN(DeviceOAuth2TokenService); };
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.cc b/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.cc deleted file mode 100644 index 3d4329d..0000000 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.cc +++ /dev/null
@@ -1,341 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h" - -#include <string> -#include <vector> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/memory/weak_ptr.h" -#include "base/values.h" -#include "chrome/browser/chromeos/settings/device_oauth2_token_service.h" -#include "chrome/browser/chromeos/settings/token_encryptor.h" -#include "chrome/common/pref_names.h" -#include "chromeos/cryptohome/system_salt_getter.h" -#include "chromeos/settings/cros_settings_names.h" -#include "components/policy/proto/device_management_backend.pb.h" -#include "components/prefs/pref_registry_simple.h" -#include "components/prefs/pref_service.h" -#include "google_apis/gaia/gaia_constants.h" -#include "google_apis/gaia/gaia_urls.h" -#include "google_apis/gaia/oauth2_access_token_fetcher_impl.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" - -namespace chromeos { - -void DeviceOAuth2TokenServiceDelegate::OnServiceAccountIdentityChanged() { - if (!GetRobotAccountId().empty() && !refresh_token_.empty()) - service_->FireRefreshTokenAvailable(GetRobotAccountId()); -} - -DeviceOAuth2TokenServiceDelegate::DeviceOAuth2TokenServiceDelegate( - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - PrefService* local_state, - DeviceOAuth2TokenService* service) - : url_loader_factory_(url_loader_factory), - local_state_(local_state), - state_(STATE_LOADING), - max_refresh_token_validation_retries_(3), - validation_requested_(false), - validation_status_delegate_(nullptr), - service_account_identity_subscription_( - CrosSettings::Get()->AddSettingsObserver( - kServiceAccountIdentity, - base::Bind(&DeviceOAuth2TokenServiceDelegate:: - OnServiceAccountIdentityChanged, - base::Unretained(this)))), - service_(service), - weak_ptr_factory_(this) { - // Pull in the system salt. - SystemSaltGetter::Get()->GetSystemSalt( - base::Bind(&DeviceOAuth2TokenServiceDelegate::DidGetSystemSalt, - weak_ptr_factory_.GetWeakPtr())); -} - -DeviceOAuth2TokenServiceDelegate::~DeviceOAuth2TokenServiceDelegate() { - FlushTokenSaveCallbacks(false); -} - -void DeviceOAuth2TokenServiceDelegate::SetAndSaveRefreshToken( - const std::string& refresh_token, - const StatusCallback& result_callback) { - ReportServiceError(GoogleServiceAuthError::REQUEST_CANCELED); - - bool waiting_for_salt = state_ == STATE_LOADING; - refresh_token_ = refresh_token; - state_ = STATE_VALIDATION_PENDING; - - // If the robot account ID is not available yet, do not announce the token. It - // will be done from OnServiceAccountIdentityChanged() once the robot account - // ID becomes available as well. - if (!GetRobotAccountId().empty()) - service_->FireRefreshTokenAvailable(GetRobotAccountId()); - - token_save_callbacks_.push_back(result_callback); - if (!waiting_for_salt) { - if (system_salt_.empty()) - FlushTokenSaveCallbacks(false); - else - EncryptAndSaveToken(); - } -} - -bool DeviceOAuth2TokenServiceDelegate::RefreshTokenIsAvailable( - const CoreAccountId& account_id) const { - auto accounts = GetAccounts(); - return std::find(accounts.begin(), accounts.end(), account_id) != - accounts.end(); -} - -std::vector<CoreAccountId> DeviceOAuth2TokenServiceDelegate::GetAccounts() - const { - std::vector<CoreAccountId> accounts; - switch (state_) { - case STATE_NO_TOKEN: - case STATE_TOKEN_INVALID: - return accounts; - case STATE_LOADING: - case STATE_VALIDATION_PENDING: - case STATE_VALIDATION_STARTED: - case STATE_TOKEN_VALID: - if (!GetRobotAccountId().empty()) - accounts.push_back(GetRobotAccountId()); - return accounts; - } - - NOTREACHED() << "Unhandled state " << state_; - return accounts; -} - -CoreAccountId DeviceOAuth2TokenServiceDelegate::GetRobotAccountId() const { - if (!robot_account_id_for_testing_.empty()) { - return robot_account_id_for_testing_; - } - - std::string account_id; - CrosSettings::Get()->GetString(kServiceAccountIdentity, &account_id); - return CoreAccountId(account_id); -} - -void DeviceOAuth2TokenServiceDelegate::OnRefreshTokenResponse( - const std::string& access_token, - int expires_in_seconds) { - gaia_oauth_client_->GetTokenInfo(access_token, - max_refresh_token_validation_retries_, this); -} - -void DeviceOAuth2TokenServiceDelegate::OnGetTokenInfoResponse( - std::unique_ptr<base::DictionaryValue> token_info) { - std::string gaia_robot_id; - // For robot accounts email id is the account id. - token_info->GetString("email", &gaia_robot_id); - gaia_oauth_client_.reset(); - - CheckRobotAccountId(CoreAccountId(gaia_robot_id)); -} - -void DeviceOAuth2TokenServiceDelegate::OnOAuthError() { - gaia_oauth_client_.reset(); - state_ = STATE_TOKEN_INVALID; - ReportServiceError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); -} - -void DeviceOAuth2TokenServiceDelegate::OnNetworkError(int response_code) { - gaia_oauth_client_.reset(); - - // Go back to pending validation state. That'll allow a retry on subsequent - // token minting requests. - state_ = STATE_VALIDATION_PENDING; - ReportServiceError(GoogleServiceAuthError::CONNECTION_FAILED); -} - -std::string DeviceOAuth2TokenServiceDelegate::GetRefreshToken() const { - switch (state_) { - case STATE_LOADING: - case STATE_NO_TOKEN: - case STATE_TOKEN_INVALID: - // This shouldn't happen: GetRefreshToken() is only called for actual - // token minting operations. In above states, requests are either queued - // or short-circuited to signal error immediately, so no actual token - // minting via OAuth2TokenService::FetchOAuth2Token should be triggered. - NOTREACHED(); - return std::string(); - case STATE_VALIDATION_PENDING: - case STATE_VALIDATION_STARTED: - case STATE_TOKEN_VALID: - return refresh_token_; - } - - NOTREACHED() << "Unhandled state " << state_; - return std::string(); -} - -scoped_refptr<network::SharedURLLoaderFactory> -DeviceOAuth2TokenServiceDelegate::GetURLLoaderFactory() const { - return url_loader_factory_; -} - -std::unique_ptr<OAuth2AccessTokenFetcher> -DeviceOAuth2TokenServiceDelegate::CreateAccessTokenFetcher( - const CoreAccountId& account_id, - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - OAuth2AccessTokenConsumer* consumer) { - std::string refresh_token = GetRefreshToken(); - DCHECK(!refresh_token.empty()); - return std::make_unique<OAuth2AccessTokenFetcherImpl>( - consumer, url_loader_factory, refresh_token); -} - -void DeviceOAuth2TokenServiceDelegate::DidGetSystemSalt( - const std::string& system_salt) { - system_salt_ = system_salt; - - // Bail out if system salt is not available. - if (system_salt_.empty()) { - LOG(ERROR) << "Failed to get system salt."; - FlushTokenSaveCallbacks(false); - state_ = STATE_NO_TOKEN; - return; - } - - // If the token has been set meanwhile, write it to |local_state_|. - if (!refresh_token_.empty()) { - EncryptAndSaveToken(); - return; - } - - // Otherwise, load the refresh token from |local_state_|. - std::string encrypted_refresh_token = - local_state_->GetString(prefs::kDeviceRobotAnyApiRefreshToken); - if (!encrypted_refresh_token.empty()) { - CryptohomeTokenEncryptor encryptor(system_salt_); - refresh_token_ = encryptor.DecryptWithSystemSalt(encrypted_refresh_token); - if (refresh_token_.empty()) { - LOG(ERROR) << "Failed to decrypt refresh token."; - state_ = STATE_NO_TOKEN; - return; - } - } - - state_ = STATE_VALIDATION_PENDING; - - // If there are pending requests, start a validation. - if (validation_requested_) - StartValidation(); - - // Announce the token. - if (!GetRobotAccountId().empty()) { - service_->FireRefreshTokenAvailable(GetRobotAccountId()); - } -} - -void DeviceOAuth2TokenServiceDelegate::CheckRobotAccountId( - const CoreAccountId& gaia_robot_id) { - // Make sure the value returned by GetRobotAccountId has been validated - // against current device settings. - switch (CrosSettings::Get()->PrepareTrustedValues( - base::Bind(&DeviceOAuth2TokenServiceDelegate::CheckRobotAccountId, - weak_ptr_factory_.GetWeakPtr(), gaia_robot_id))) { - case CrosSettingsProvider::TRUSTED: - // All good, compare account ids below. - break; - case CrosSettingsProvider::TEMPORARILY_UNTRUSTED: - // The callback passed to PrepareTrustedValues above will trigger a - // re-check eventually. - return; - case CrosSettingsProvider::PERMANENTLY_UNTRUSTED: - // There's no trusted account id, which is equivalent to no token present. - LOG(WARNING) << "Device settings permanently untrusted."; - state_ = STATE_NO_TOKEN; - ReportServiceError(GoogleServiceAuthError::USER_NOT_SIGNED_UP); - return; - } - - CoreAccountId policy_robot_id = GetRobotAccountId(); - if (policy_robot_id == gaia_robot_id) { - state_ = STATE_TOKEN_VALID; - ReportServiceError(GoogleServiceAuthError::NONE); - } else { - if (gaia_robot_id.empty()) { - LOG(WARNING) << "Device service account owner in policy is empty."; - } else { - LOG(WARNING) << "Device service account owner in policy does not match " - << "refresh token owner \"" << gaia_robot_id << "\"."; - } - state_ = STATE_TOKEN_INVALID; - ReportServiceError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); - } -} - -void DeviceOAuth2TokenServiceDelegate::EncryptAndSaveToken() { - DCHECK_NE(state_, STATE_LOADING); - - CryptohomeTokenEncryptor encryptor(system_salt_); - std::string encrypted_refresh_token = - encryptor.EncryptWithSystemSalt(refresh_token_); - bool result = true; - if (encrypted_refresh_token.empty()) { - LOG(ERROR) << "Failed to encrypt refresh token; save aborted."; - result = false; - } else { - local_state_->SetString(prefs::kDeviceRobotAnyApiRefreshToken, - encrypted_refresh_token); - } - - FlushTokenSaveCallbacks(result); -} - -void DeviceOAuth2TokenServiceDelegate::StartValidation() { - DCHECK_EQ(state_, STATE_VALIDATION_PENDING); - DCHECK(!gaia_oauth_client_); - - state_ = STATE_VALIDATION_STARTED; - - gaia_oauth_client_ = - std::make_unique<gaia::GaiaOAuthClient>(url_loader_factory_); - - GaiaUrls* gaia_urls = GaiaUrls::GetInstance(); - gaia::OAuthClientInfo client_info; - client_info.client_id = gaia_urls->oauth2_chrome_client_id(); - client_info.client_secret = gaia_urls->oauth2_chrome_client_secret(); - - gaia_oauth_client_->RefreshToken( - client_info, refresh_token_, - std::vector<std::string>(1, GaiaConstants::kOAuthWrapBridgeUserInfoScope), - max_refresh_token_validation_retries_, this); -} - -void DeviceOAuth2TokenServiceDelegate::FlushTokenSaveCallbacks(bool result) { - std::vector<StatusCallback> callbacks; - callbacks.swap(token_save_callbacks_); - for (std::vector<StatusCallback>::iterator callback(callbacks.begin()); - callback != callbacks.end(); ++callback) { - if (!callback->is_null()) - callback->Run(result); - } -} - -void DeviceOAuth2TokenServiceDelegate::RequestValidation() { - validation_requested_ = true; -} - -void DeviceOAuth2TokenServiceDelegate::InitializeWithValidationStatusDelegate( - ValidationStatusDelegate* delegate) { - validation_status_delegate_ = delegate; -} - -void DeviceOAuth2TokenServiceDelegate::ClearValidationStatusDelegate() { - validation_status_delegate_ = nullptr; -} - -void DeviceOAuth2TokenServiceDelegate::ReportServiceError( - GoogleServiceAuthError::State error) { - if (validation_status_delegate_) { - validation_status_delegate_->OnValidationCompleted(error); - } -} - -} // namespace chromeos
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h b/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h deleted file mode 100644 index 58db8af..0000000 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h +++ /dev/null
@@ -1,176 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_CHROMEOS_SETTINGS_DEVICE_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ -#define CHROME_BROWSER_CHROMEOS_SETTINGS_DEVICE_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ - -#include <memory> -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/chromeos/settings/cros_settings.h" -#include "google_apis/gaia/core_account_id.h" -#include "google_apis/gaia/gaia_oauth_client.h" -#include "google_apis/gaia/google_service_auth_error.h" -#include "net/url_request/url_request_context_getter.h" - -namespace gaia { -class GaiaOAuthClient; -} - -namespace network { -class SharedURLLoaderFactory; -} - -class PrefService; -class OAuth2AccessTokenFetcher; -class OAuth2AccessTokenConsumer; - -namespace chromeos { - -class DeviceOAuth2TokenService; - -class DeviceOAuth2TokenServiceDelegate - : public gaia::GaiaOAuthClient::Delegate { - public: - DeviceOAuth2TokenServiceDelegate( - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - PrefService* local_state, - DeviceOAuth2TokenService* service); - ~DeviceOAuth2TokenServiceDelegate() override; - - typedef base::Callback<void(bool)> StatusCallback; - - // Persist the given refresh token on the device. Overwrites any previous - // value. Should only be called during initial device setup. Signals - // completion via the given callback, passing true if the operation succeeded. - void SetAndSaveRefreshToken(const std::string& refresh_token, - const StatusCallback& callback); - - // Pull the robot account ID from device policy. - CoreAccountId GetRobotAccountId() const; - - void set_robot_account_id_for_testing(const CoreAccountId& account_id) { - robot_account_id_for_testing_ = account_id; - } - - bool RefreshTokenIsAvailable(const CoreAccountId& account_id) const; - scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() const; - std::unique_ptr<OAuth2AccessTokenFetcher> CreateAccessTokenFetcher( - const CoreAccountId& account_id, - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - OAuth2AccessTokenConsumer* consumer); - std::vector<CoreAccountId> GetAccounts() const; - - // gaia::GaiaOAuthClient::Delegate implementation. - void OnRefreshTokenResponse(const std::string& access_token, - int expires_in_seconds) override; - void OnGetTokenInfoResponse( - std::unique_ptr<base::DictionaryValue> token_info) override; - void OnOAuthError() override; - void OnNetworkError(int response_code) override; - - class ValidationStatusDelegate { - public: - virtual void OnValidationCompleted(GoogleServiceAuthError::State error) {} - }; - - private: - friend class DeviceOAuth2TokenService; - friend class DeviceOAuth2TokenServiceTest; - - // Describes the operational state of this object. - enum State { - // Pending system salt / refresh token load. - STATE_LOADING, - // No token available. - STATE_NO_TOKEN, - // System salt loaded, validation not started yet. - STATE_VALIDATION_PENDING, - // Refresh token validation underway. - STATE_VALIDATION_STARTED, - // Token validation failed. - STATE_TOKEN_INVALID, - // Refresh token is valid. - STATE_TOKEN_VALID, - }; - - // Invoked by CrosSettings when the robot account ID becomes available. - void OnServiceAccountIdentityChanged(); - - // Returns the refresh token for the robot account id. - std::string GetRefreshToken() const; - - // Handles completion of the system salt input. - void DidGetSystemSalt(const std::string& system_salt); - - // Checks whether |gaia_robot_id| matches the expected account ID indicated in - // device settings. - void CheckRobotAccountId(const CoreAccountId& gaia_robot_id); - - // Encrypts and saves the refresh token. Should only be called when the system - // salt is available. - void EncryptAndSaveToken(); - - // Starts the token validation flow, i.e. token info fetch. - void StartValidation(); - - // Flushes |token_save_callbacks_|, indicating the specified result. - void FlushTokenSaveCallbacks(bool result); - - void RequestValidation(); - - void InitializeWithValidationStatusDelegate( - ValidationStatusDelegate* delegate); - void ClearValidationStatusDelegate(); - - void ReportServiceError(GoogleServiceAuthError::State error); - - // Dependencies. - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - PrefService* local_state_; - - // Current operational state. - State state_; - - // Token save callbacks waiting to be completed. - std::vector<StatusCallback> token_save_callbacks_; - - // The system salt for encrypting and decrypting the refresh token. - std::string system_salt_; - - int max_refresh_token_validation_retries_; - - // Flag to indicate whether there are pending requests. - bool validation_requested_; - - // Validation status delegate - ValidationStatusDelegate* validation_status_delegate_; - - // Cache the decrypted refresh token, so we only decrypt once. - std::string refresh_token_; - - std::unique_ptr<gaia::GaiaOAuthClient> gaia_oauth_client_; - - std::unique_ptr<CrosSettings::ObserverSubscription> - service_account_identity_subscription_; - - CoreAccountId robot_account_id_for_testing_; - - // TODO(https://crbug.com/967598): Completely merge this class into - // DeviceOAuth2TokenService. - DeviceOAuth2TokenService* service_; - - base::WeakPtrFactory<DeviceOAuth2TokenServiceDelegate> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(DeviceOAuth2TokenServiceDelegate); -}; - -} // namespace chromeos - -#endif // CHROME_BROWSER_CHROMEOS_SETTINGS_DEVICE_OAUTH2_TOKEN_SERVICE_DELEGATE_H_
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service_factory.cc b/chrome/browser/chromeos/settings/device_oauth2_token_service_factory.cc index 590fe10..d9e9160c5 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service_factory.cc +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service_factory.cc
@@ -7,7 +7,6 @@ #include <memory> #include "chrome/browser/chromeos/settings/device_oauth2_token_service.h" -#include "chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h" #include "chrome/browser/chromeos/settings/token_encryptor.h" #include "chromeos/cryptohome/system_salt_getter.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc b/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc index c8c627f..74b1e5ff 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc
@@ -15,7 +15,6 @@ #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/chromeos/policy/device_policy_builder.h" #include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chrome/browser/chromeos/settings/scoped_testing_cros_settings.h" #include "chrome/browser/chromeos/settings/token_encryptor.h" @@ -108,7 +107,7 @@ oauth2_service_.reset(new DeviceOAuth2TokenService( test_url_loader_factory_.GetSafeWeakWrapper(), scoped_testing_local_state_.Get())); - oauth2_service_->delegate_->max_refresh_token_validation_retries_ = 0; + oauth2_service_->max_refresh_token_validation_retries_ = 0; oauth2_service_->GetAccessTokenManager() ->set_max_authorization_token_fetch_retries_for_testing(0); } @@ -126,10 +125,6 @@ " \"user_id\": \"1234567890\" }"; } - DeviceOAuth2TokenServiceDelegate* GetDelegate() { - return oauth2_service_->delegate_.get(); - } - bool RefreshTokenIsAvailable() { return oauth2_service_->RefreshTokenIsAvailable( oauth2_service_->GetRobotAccountId()); @@ -139,7 +134,7 @@ if (!RefreshTokenIsAvailable()) return std::string(); - return GetDelegate()->GetRefreshToken(); + return oauth2_service_->GetRefreshToken(); } // A utility method to return fake URL results, for testing the refresh token
diff --git a/chrome/browser/chromeos/ui/low_disk_notification.cc b/chrome/browser/chromeos/ui/low_disk_notification.cc index a77c411..9761963c 100644 --- a/chrome/browser/chromeos/ui/low_disk_notification.cc +++ b/chrome/browser/chromeos/ui/low_disk_notification.cc
@@ -7,10 +7,10 @@ #include <stdint.h> #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/macros.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/notifications/system_notification_helper.h" @@ -114,7 +114,7 @@ message_center::NOTIFICATION_TYPE_SIMPLE, kLowDiskId, title, message, base::string16(), GURL(), notifier_id, optional_fields, new message_center::HandleNotificationClickDelegate(on_click), - ash::kNotificationStorageFullIcon, warning_level); + kNotificationStorageFullIcon, warning_level); return notification; }
diff --git a/chrome/browser/chromeos/wilco_dtc_supportd/wilco_dtc_supportd_notification_controller.cc b/chrome/browser/chromeos/wilco_dtc_supportd/wilco_dtc_supportd_notification_controller.cc index 69712d7..2e16377 100644 --- a/chrome/browser/chromeos/wilco_dtc_supportd/wilco_dtc_supportd_notification_controller.cc +++ b/chrome/browser/chromeos/wilco_dtc_supportd/wilco_dtc_supportd_notification_controller.cc
@@ -9,13 +9,14 @@ #include <utility> #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/strings/string16.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/notifications/notification_handler.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/grit/generated_resources.h" +#include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" #include "ui/message_center/public/cpp/notification_delegate.h" #include "ui/message_center/public/cpp/notification_types.h" @@ -81,8 +82,7 @@ DisplayNotification(kWilcoDtcSupportdNotificationIdBatteryAuth, IDS_WILCO_NOTIFICATION_BATTERY_AUTH_TITLE, IDS_WILCO_NOTIFICATION_BATTERY_AUTH_MESSAGE, - message_center::SYSTEM_PRIORITY, - ash::kNotificationBatteryIcon, + message_center::SYSTEM_PRIORITY, kNotificationBatteryIcon, message_center::SystemNotificationWarningLevel::WARNING, HelpAppLauncher::HelpTopic::HELP_WILCO); return kWilcoDtcSupportdNotificationIdBatteryAuth; @@ -95,7 +95,7 @@ IDS_WILCO_NOTIFICATION_NON_WILCO_CHARGER_TITLE, IDS_WILCO_NOTIFICATION_NON_WILCO_CHARGER_MESSAGE, message_center::DEFAULT_PRIORITY, - ash::kNotificationBatteryIcon, + kNotificationBatteryIcon, message_center::SystemNotificationWarningLevel::WARNING, HelpAppLauncher::HelpTopic::HELP_WILCO); return kWilcoDtcSupportdNotificationIdNonWilcoCharger; @@ -108,7 +108,7 @@ IDS_WILCO_NOTIFICATION_INCOMPATIBLE_DOCK_TITLE, IDS_WILCO_NOTIFICATION_INCOMPATIBLE_DOCK_MESSAGE, message_center::DEFAULT_PRIORITY, - ash::kNotificationSettingsIcon, + vector_icons::kSettingsIcon, message_center::SystemNotificationWarningLevel::NORMAL, HelpAppLauncher::HelpTopic::HELP_WILCO); return kWilcoDtcSupportdNotificationIdIncompatibleDock; @@ -120,7 +120,7 @@ IDS_WILCO_NOTIFICATION_DOCK_ERROR_TITLE, IDS_WILCO_NOTIFICATION_DOCK_ERROR_MESSAGE, message_center::DEFAULT_PRIORITY, - ash::kNotificationSettingsIcon, + vector_icons::kSettingsIcon, message_center::SystemNotificationWarningLevel::NORMAL, HelpAppLauncher::HelpTopic::HELP_WILCO); return kWilcoDtcSupportdNotificationIdDockHardwareError; @@ -132,7 +132,7 @@ IDS_WILCO_NOTIFICATION_DOCK_DISPLAY_TITLE, IDS_WILCO_NOTIFICATION_DOCK_DISPLAY_MESSAGE, message_center::DEFAULT_PRIORITY, - ash::kNotificationSettingsIcon, + vector_icons::kSettingsIcon, message_center::SystemNotificationWarningLevel::NORMAL, HelpAppLauncher::HelpTopic::HELP_WILCO); return kWilcoDtcSupportdNotificationIdDockDisplay; @@ -145,7 +145,7 @@ IDS_WILCO_NOTIFICATION_DOCK_THUNDERBOLT_TITLE, IDS_WILCO_NOTIFICATION_DOCK_THUNDERBOLT_MESSAGE, message_center::DEFAULT_PRIORITY, - ash::kNotificationSettingsIcon, + vector_icons::kSettingsIcon, message_center::SystemNotificationWarningLevel::NORMAL, HelpAppLauncher::HelpTopic::HELP_WILCO); return kWilcoDtcSupportdNotificationIdDockThunderbolt;
diff --git a/chrome/browser/content_index/OWNERS b/chrome/browser/content_index/OWNERS new file mode 100644 index 0000000..5e751de --- /dev/null +++ b/chrome/browser/content_index/OWNERS
@@ -0,0 +1 @@ +file://content/browser/content_index/OWNERS
diff --git a/chrome/browser/content_index/content_index_provider_factory.cc b/chrome/browser/content_index/content_index_provider_factory.cc new file mode 100644 index 0000000..266a2bac --- /dev/null +++ b/chrome/browser/content_index/content_index_provider_factory.cc
@@ -0,0 +1,44 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/content_index/content_index_provider_factory.h" + +#include "chrome/browser/content_index/content_index_provider_impl.h" +#include "chrome/browser/offline_items_collection/offline_content_aggregator_factory.h" +#include "chrome/browser/profiles/incognito_helpers.h" +#include "chrome/browser/profiles/profile.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" + +// static +ContentIndexProviderImpl* ContentIndexProviderFactory::GetForProfile( + Profile* profile) { + return static_cast<ContentIndexProviderImpl*>( + GetInstance()->GetServiceForBrowserContext(profile, true)); +} + +// static +ContentIndexProviderFactory* ContentIndexProviderFactory::GetInstance() { + return base::Singleton<ContentIndexProviderFactory>::get(); +} + +ContentIndexProviderFactory::ContentIndexProviderFactory() + : BrowserContextKeyedServiceFactory( + "ContentIndexProvider", + BrowserContextDependencyManager::GetInstance()) { + DependsOn(OfflineContentAggregatorFactory::GetInstance()); +} + +ContentIndexProviderFactory::~ContentIndexProviderFactory() {} + +KeyedService* ContentIndexProviderFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + auto* aggregator = OfflineContentAggregatorFactory::GetForKey( + Profile::FromBrowserContext(context)->GetProfileKey()); + return new ContentIndexProviderImpl(aggregator); +} + +content::BrowserContext* ContentIndexProviderFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return chrome::GetBrowserContextOwnInstanceInIncognito(context); +}
diff --git a/chrome/browser/content_index/content_index_provider_factory.h b/chrome/browser/content_index/content_index_provider_factory.h new file mode 100644 index 0000000..c9f4d56 --- /dev/null +++ b/chrome/browser/content_index/content_index_provider_factory.h
@@ -0,0 +1,35 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CONTENT_INDEX_CONTENT_INDEX_PROVIDER_FACTORY_H_ +#define CHROME_BROWSER_CONTENT_INDEX_CONTENT_INDEX_PROVIDER_FACTORY_H_ + +#include "base/macros.h" +#include "base/memory/singleton.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" + +class ContentIndexProviderImpl; +class Profile; + +class ContentIndexProviderFactory : public BrowserContextKeyedServiceFactory { + public: + static ContentIndexProviderImpl* GetForProfile(Profile* profile); + static ContentIndexProviderFactory* GetInstance(); + + private: + friend struct base::DefaultSingletonTraits<ContentIndexProviderFactory>; + + ContentIndexProviderFactory(); + ~ContentIndexProviderFactory() override; + + // BrowserContextKeyedServiceFactory overrides. + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const override; + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; + + DISALLOW_COPY_AND_ASSIGN(ContentIndexProviderFactory); +}; + +#endif // CHROME_BROWSER_CONTENT_INDEX_CONTENT_INDEX_PROVIDER_FACTORY_H_
diff --git a/chrome/browser/content_index/content_index_provider_impl.cc b/chrome/browser/content_index/content_index_provider_impl.cc new file mode 100644 index 0000000..4f4b8f31 --- /dev/null +++ b/chrome/browser/content_index/content_index_provider_impl.cc
@@ -0,0 +1,231 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/content_index/content_index_provider_impl.h" + +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_split.h" +#include "base/task/post_task.h" +#include "chrome/browser/offline_items_collection/offline_content_aggregator_factory.h" +#include "components/offline_items_collection/core/offline_content_aggregator.h" +#include "components/offline_items_collection/core/offline_item.h" +#include "components/offline_items_collection/core/update_delta.h" +#include "content/public/browser/browser_thread.h" +#include "ui/gfx/image/image_skia.h" + +using offline_items_collection::ContentId; +using offline_items_collection::LaunchLocation; +using offline_items_collection::OfflineItem; +using offline_items_collection::OfflineItemFilter; + +struct ContentIndexProviderImpl::EntryData { + EntryData() = delete; + ~EntryData() = default; + + OfflineItem offline_item; + base::WeakPtr<content::ContentIndexProvider::Client> client; +}; + +namespace { + +constexpr char kProviderNamespace[] = "content_index"; +constexpr char kSeparator[] = "-"; + +std::string EntryKey(int64_t service_worker_registration_id, + const std::string& description_id) { + return base::NumberToString(service_worker_registration_id) + kSeparator + + description_id; +} + +std::string EntryKey(const content::ContentIndexEntry& entry) { + return EntryKey(entry.service_worker_registration_id, entry.description->id); +} + +std::pair<int64_t, std::string> GetEntryKeyComponents(const std::string& key) { + size_t pos = key.find_first_of(kSeparator); + DCHECK_NE(pos, std::string::npos); + + int64_t service_worker_registration_id = -1; + base::StringToInt64(base::StringPiece(key.data(), pos), + &service_worker_registration_id); + + return {service_worker_registration_id, key.substr(pos + 1)}; +} + +OfflineItemFilter CategoryToFilter(blink::mojom::ContentCategory category) { + switch (category) { + case blink::mojom::ContentCategory::HOME_PAGE: + case blink::mojom::ContentCategory::ARTICLE: + return OfflineItemFilter::FILTER_PAGE; + case blink::mojom::ContentCategory::VIDEO: + return OfflineItemFilter::FILTER_VIDEO; + case blink::mojom::ContentCategory::AUDIO: + return OfflineItemFilter::FILTER_AUDIO; + } +} + +OfflineItem EntryToOfflineItem(const content::ContentIndexEntry& entry) { + OfflineItem item; + item.id = ContentId(kProviderNamespace, EntryKey(entry)); + item.title = entry.description->title; + item.description = entry.description->description; + item.filter = CategoryToFilter(entry.description->category); + item.is_transient = false; + item.is_suggested = true; + item.creation_time = entry.registration_time; + item.is_openable = true; + item.state = offline_items_collection::OfflineItemState::COMPLETE; + item.is_resumable = false; + item.can_rename = false; + + // TODO(crbug.com/973844): Include URL info. + + return item; +} + +} // namespace + +ContentIndexProviderImpl::ContentIndexProviderImpl( + offline_items_collection::OfflineContentAggregator* aggregator) + : aggregator_(aggregator), weak_ptr_factory_(this) { + aggregator_->RegisterProvider(kProviderNamespace, this); +} + +ContentIndexProviderImpl::~ContentIndexProviderImpl() { + if (aggregator_) + aggregator_->UnregisterProvider(kProviderNamespace); +} + +void ContentIndexProviderImpl::Shutdown() { + aggregator_->UnregisterProvider(kProviderNamespace); + aggregator_ = nullptr; +} + +void ContentIndexProviderImpl::OnContentAdded( + content::ContentIndexEntry entry, + base::WeakPtr<content::ContentIndexProvider::Client> client) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + std::string entry_key = EntryKey(entry); + EntryData entry_data = {EntryToOfflineItem(entry), std::move(client)}; + + bool is_update = entries_.erase(entry_key); + + if (is_update) { + offline_items_collection::UpdateDelta delta; + delta.visuals_changed = true; + for (auto& observer : observers_) + observer.OnItemUpdated(entry_data.offline_item, delta); + } else { + OfflineItemList items(1, entry_data.offline_item); + for (auto& observer : observers_) + observer.OnItemsAdded(items); + } + + entries_.emplace(std::move(entry_key), std::move(entry_data)); +} + +void ContentIndexProviderImpl::OnContentDeleted( + int64_t service_worker_registration_id, + const std::string& description_id) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + auto did_erase = + entries_.erase(EntryKey(service_worker_registration_id, description_id)); + + if (did_erase) { + ContentId id(kProviderNamespace, + EntryKey(service_worker_registration_id, description_id)); + for (auto& observer : observers_) + observer.OnItemRemoved(id); + } +} + +void ContentIndexProviderImpl::OpenItem(LaunchLocation location, + const ContentId& id) { + NOTIMPLEMENTED(); +} + +void ContentIndexProviderImpl::RemoveItem(const ContentId& id) { + NOTIMPLEMENTED(); +} + +void ContentIndexProviderImpl::CancelDownload(const ContentId& id) { + NOTREACHED(); +} + +void ContentIndexProviderImpl::PauseDownload(const ContentId& id) { + NOTREACHED(); +} + +void ContentIndexProviderImpl::ResumeDownload(const ContentId& id, + bool has_user_gesture) { + NOTREACHED(); +} + +void ContentIndexProviderImpl::GetItemById(const ContentId& id, + SingleItemCallback callback) { + auto it = entries_.find(id.id); + if (it == entries_.end()) + return; + + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), it->second.offline_item)); +} + +void ContentIndexProviderImpl::GetAllItems(MultipleItemCallback callback) { + OfflineItemList list; + for (const auto& entry : entries_) + list.push_back(entry.second.offline_item); + + // TODO(crbug.com/1687257): Consider fetching these from the DB rather than + // storing them in memory. + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), std::move(list))); +} + +void ContentIndexProviderImpl::GetVisualsForItem(const ContentId& id, + GetVisualsOptions options, + VisualsCallback callback) { + auto it = entries_.find(id.id); + if (it == entries_.end() || !it->second.client) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), id, nullptr)); + return; + } + + auto components = GetEntryKeyComponents(id.id); + it->second.client->GetIcon( + components.first, components.second, + base::BindOnce(&ContentIndexProviderImpl::DidGetIcon, + weak_ptr_factory_.GetWeakPtr(), id, std::move(callback))); +} + +void ContentIndexProviderImpl::DidGetIcon(const ContentId& id, + VisualsCallback callback, + SkBitmap icon) { + auto visuals = + std::make_unique<offline_items_collection::OfflineItemVisuals>(); + visuals->icon = gfx::Image::CreateFrom1xBitmap(icon); + std::move(callback).Run(id, std::move(visuals)); +} + +void ContentIndexProviderImpl::GetShareInfoForItem(const ContentId& id, + ShareCallback callback) { + NOTIMPLEMENTED(); +} + +void ContentIndexProviderImpl::RenameItem(const ContentId& id, + const std::string& name, + RenameCallback callback) { + NOTREACHED(); +} + +void ContentIndexProviderImpl::AddObserver(Observer* observer) { + observers_.AddObserver(observer); +} + +void ContentIndexProviderImpl::RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); +}
diff --git a/chrome/browser/content_index/content_index_provider_impl.h b/chrome/browser/content_index/content_index_provider_impl.h new file mode 100644 index 0000000..810381a --- /dev/null +++ b/chrome/browser/content_index/content_index_provider_impl.h
@@ -0,0 +1,81 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CONTENT_INDEX_CONTENT_INDEX_PROVIDER_IMPL_H_ +#define CHROME_BROWSER_CONTENT_INDEX_CONTENT_INDEX_PROVIDER_IMPL_H_ + +#include <map> +#include <string> + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/observer_list.h" +#include "components/keyed_service/core/keyed_service.h" +#include "components/offline_items_collection/core/offline_content_provider.h" +#include "components/offline_items_collection/core/offline_item.h" +#include "content/public/browser/content_index_provider.h" + +namespace offline_items_collection { +class OfflineContentAggregator; +} // namespace offline_items_collection + +class ContentIndexProviderImpl + : public KeyedService, + public offline_items_collection::OfflineContentProvider, + public content::ContentIndexProvider { + public: + explicit ContentIndexProviderImpl( + offline_items_collection::OfflineContentAggregator* aggregator); + ~ContentIndexProviderImpl() override; + + // KeyedService implementation. + void Shutdown() override; + + // ContentIndexProvider implementation. + void OnContentAdded( + content::ContentIndexEntry entry, + base::WeakPtr<content::ContentIndexProvider::Client> client) override; + void OnContentDeleted(int64_t service_worker_registration_id, + const std::string& description_id) override; + + // OfflineContentProvider implementation. + void OpenItem(offline_items_collection::LaunchLocation location, + const offline_items_collection::ContentId& id) override; + void RemoveItem(const offline_items_collection::ContentId& id) override; + void CancelDownload(const offline_items_collection::ContentId& id) override; + void PauseDownload(const offline_items_collection::ContentId& id) override; + void ResumeDownload(const offline_items_collection::ContentId& id, + bool has_user_gesture) override; + void GetItemById(const offline_items_collection::ContentId& id, + SingleItemCallback callback) override; + void GetAllItems(MultipleItemCallback callback) override; + void GetVisualsForItem(const offline_items_collection::ContentId& id, + GetVisualsOptions options, + VisualsCallback callback) override; + void GetShareInfoForItem(const offline_items_collection::ContentId& id, + ShareCallback callback) override; + void RenameItem(const offline_items_collection::ContentId& id, + const std::string& name, + RenameCallback callback) override; + void AddObserver(Observer* observer) override; + void RemoveObserver(Observer* observer) override; + + private: + // All the information the OfflineContentProvider needs to know about the + // ContentIndexEntry. + struct EntryData; + + void DidGetIcon(const offline_items_collection::ContentId& id, + VisualsCallback callback, + SkBitmap icon); + + offline_items_collection::OfflineContentAggregator* aggregator_; + std::map<std::string, EntryData> entries_; + base::ObserverList<Observer>::Unchecked observers_; + base::WeakPtrFactory<ContentIndexProviderImpl> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(ContentIndexProviderImpl); +}; + +#endif // CHROME_BROWSER_CONTENT_INDEX_CONTENT_INDEX_PROVIDER_IMPL_H_
diff --git a/chrome/browser/content_index/content_index_provider_unittest.cc b/chrome/browser/content_index/content_index_provider_unittest.cc new file mode 100644 index 0000000..88f772a --- /dev/null +++ b/chrome/browser/content_index/content_index_provider_unittest.cc
@@ -0,0 +1,196 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/content_index/content_index_provider_impl.h" + +#include <memory> + +#include "base/memory/weak_ptr.h" +#include "base/run_loop.h" +#include "base/test/bind_test_util.h" +#include "base/time/time.h" +#include "chrome/test/base/testing_profile.h" +#include "components/offline_items_collection/core/offline_content_aggregator.h" +#include "components/offline_items_collection/core/offline_content_provider.h" +#include "content/public/browser/content_index_provider.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/gfx/image/image.h" + +using offline_items_collection::ContentId; +using offline_items_collection::OfflineContentAggregator; +using offline_items_collection::OfflineContentProvider; +using offline_items_collection::OfflineItem; +using offline_items_collection::OfflineItemVisuals; +using offline_items_collection::UpdateDelta; +using testing::_; + +constexpr int64_t kServiceWorkerRegistrationId = 42; + +class ProviderClient : public content::ContentIndexProvider::Client { + public: + ProviderClient() = default; + ~ProviderClient() override = default; + + MOCK_METHOD3(GetIcon, + void(int64_t service_worker_registration_id, + const std::string& description_id, + base::OnceCallback<void(SkBitmap)> icon_callback)); + + base::WeakPtr<ProviderClient> GetWeakPtr() { + return weak_ptr_factory_.GetWeakPtr(); + } + + private: + base::WeakPtrFactory<ProviderClient> weak_ptr_factory_{this}; +}; + +class ContentIndexProviderImplTest : public testing::Test, + public OfflineContentProvider::Observer { + public: + void SetUp() override { + aggregator_ = std::make_unique<OfflineContentAggregator>(); + provider_ = std::make_unique<ContentIndexProviderImpl>(aggregator_.get()); + provider_->AddObserver(this); + } + + void TearDown() override { provider_->RemoveObserver(this); } + + // OfflineContentProvider::Observer implementation. + MOCK_METHOD1(OnItemsAdded, + void(const OfflineContentProvider::OfflineItemList& items)); + MOCK_METHOD1(OnItemRemoved, void(const ContentId& id)); + MOCK_METHOD2(OnItemUpdated, + void(const OfflineItem& item, + const base::Optional<UpdateDelta>& update_delta)); + + content::ContentIndexEntry CreateEntry(const std::string& id) { + auto description = blink::mojom::ContentDescription::New( + id, "title", "description", blink::mojom::ContentCategory::ARTICLE, + "icon_url", "launch_url"); + return content::ContentIndexEntry(kServiceWorkerRegistrationId, + std::move(description), + base::Time::Now()); + } + + SkBitmap GetVisuals(const ContentId& id) { + SkBitmap icon; + + base::RunLoop run_loop; + provider_->GetVisualsForItem( + id, ContentIndexProviderImpl::GetVisualsOptions(), + base::BindLambdaForTesting( + [&](const ContentId& visual_id, + std::unique_ptr<OfflineItemVisuals> visuals) { + ASSERT_EQ(visual_id, id); + ASSERT_TRUE(visuals); + icon = visuals->icon.AsBitmap(); + run_loop.Quit(); + })); + run_loop.Run(); + + return icon; + } + + std::vector<OfflineItem> GetAllItems() { + std::vector<OfflineItem> out_items; + + base::RunLoop run_loop; + provider_->GetAllItems( + base::BindLambdaForTesting([&](const std::vector<OfflineItem>& items) { + out_items = items; + run_loop.Quit(); + })); + run_loop.Run(); + + return out_items; + } + + protected: + content::TestBrowserThreadBundle threads_; + std::unique_ptr<offline_items_collection::OfflineContentAggregator> + aggregator_; + ProviderClient client_; + std::unique_ptr<ContentIndexProviderImpl> provider_; +}; + +TEST_F(ContentIndexProviderImplTest, OfflineItemCreation) { + std::vector<OfflineItem> items; + { + EXPECT_CALL(*this, OnItemsAdded(_)).WillOnce(testing::SaveArg<0>(&items)); + provider_->OnContentAdded(CreateEntry("id"), /* client= */ nullptr); + } + ASSERT_EQ(items.size(), 1u); + const auto& item = items[0]; + + EXPECT_FALSE(item.id.name_space.empty()); + EXPECT_FALSE(item.id.id.empty()); + EXPECT_FALSE(item.title.empty()); + EXPECT_FALSE(item.description.empty()); + EXPECT_FALSE(item.is_transient); + EXPECT_TRUE(item.is_openable); +} + +TEST_F(ContentIndexProviderImplTest, ObserverUpdates) { + { + EXPECT_CALL(*this, OnItemsAdded(_)); + provider_->OnContentAdded(CreateEntry("id"), /* client= */ nullptr); + } + + // Adding an already existing ID should call update. + { + EXPECT_CALL(*this, OnItemsAdded(_)).Times(0); + EXPECT_CALL(*this, OnItemUpdated(_, _)); + provider_->OnContentAdded(CreateEntry("id"), /* client= */ nullptr); + } + + // Removing a fake ID won't notify observers. + { + EXPECT_CALL(*this, OnItemRemoved(_)).Times(0); + provider_->OnContentDeleted(kServiceWorkerRegistrationId, "wrong-id"); + } + + { + EXPECT_CALL(*this, OnItemRemoved(_)); + provider_->OnContentDeleted(kServiceWorkerRegistrationId, "id"); + } +} + +TEST_F(ContentIndexProviderImplTest, VisualUpdates) { + // Add an entry and save it's ID. + std::vector<OfflineItem> items; + { + EXPECT_CALL(*this, OnItemsAdded(_)).WillOnce(testing::SaveArg<0>(&items)); + provider_->OnContentAdded(CreateEntry("id"), client_.GetWeakPtr()); + } + ASSERT_EQ(items.size(), 1u); + ContentId id = items[0].id; + + EXPECT_CALL(client_, GetIcon(kServiceWorkerRegistrationId, "id", _)) + .WillOnce(testing::Invoke( + [](int64_t sw_id, const std::string& id, auto icon_callback) { + SkBitmap icon; + icon.allocN32Pixels(4, 2); + std::move(icon_callback).Run(icon); + })); + + auto icon = GetVisuals(id); + EXPECT_FALSE(icon.isNull()); + EXPECT_EQ(icon.width(), 4); + EXPECT_EQ(icon.height(), 2); +} + +TEST_F(ContentIndexProviderImplTest, GetAllItems) { + // Inititally there are no items. + EXPECT_TRUE(GetAllItems().empty()); + + provider_->OnContentAdded(CreateEntry("id1"), /* client= */ nullptr); + provider_->OnContentAdded(CreateEntry("id2"), /* client= */ nullptr); + + auto items = GetAllItems(); + ASSERT_EQ(items.size(), 2u); + EXPECT_EQ(items[0].id.name_space, items[0].id.name_space); + EXPECT_NE(items[0].id.id, items[1].id.id); +}
diff --git a/chrome/browser/content_settings/host_content_settings_map_unittest.cc b/chrome/browser/content_settings/host_content_settings_map_unittest.cc index 5843fa7..ae20761e 100644 --- a/chrome/browser/content_settings/host_content_settings_map_unittest.cc +++ b/chrome/browser/content_settings/host_content_settings_map_unittest.cc
@@ -2099,7 +2099,7 @@ // Testing case: WebsiteSettingsInfo::REQUESTING_ORIGIN_ONLY_SCOPE. host_content_settings_map->SetContentSettingDefaultScope( primary_url, secondary_url, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), CONTENT_SETTING_ASK); + std::string(), CONTENT_SETTING_ALLOW); host_content_settings_map->GetSettingsForOneType( CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), &settings);
diff --git a/chrome/browser/devtools/devtools_sanity_browsertest.cc b/chrome/browser/devtools/devtools_sanity_browsertest.cc index 21cc0ca6..8b4744b 100644 --- a/chrome/browser/devtools/devtools_sanity_browsertest.cc +++ b/chrome/browser/devtools/devtools_sanity_browsertest.cc
@@ -358,13 +358,10 @@ before_unload_observer.Wait(); } { - content::WindowedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::Source<Browser>(browser())); close_method.Run(); AcceptModalDialog(); if (wait_for_browser_close) - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(browser()); } runner->Run(); } @@ -808,13 +805,10 @@ } // Try to exit application. { - content::WindowedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::Source<Browser>(browser())); chrome::CloseAllBrowsers(); AcceptModalDialog(); AcceptModalDialog(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(browser()); } for (auto& close_observer : close_observers) close_observer->Wait(); @@ -2341,11 +2335,9 @@ "window.addEventListener('beforeunload'," "function(event) { event.returnValue = 'Foo'; });")); content::PrepContentsForBeforeUnloadTest(tab); - content::WindowedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(browser())); BrowserHandler handler(nullptr, std::string()); handler.Close(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(browser()); } // Flaky on Mus. See https://crbug.com/819285.
diff --git a/chrome/browser/download/download_browsertest.cc b/chrome/browser/download/download_browsertest.cc index c7c1264..05c84af 100644 --- a/chrome/browser/download/download_browsertest.cc +++ b/chrome/browser/download/download_browsertest.cc
@@ -1593,22 +1593,11 @@ // We should still have 2 windows. ExpectWindowCountAfterDownload(2); -#if !defined(OS_MACOSX) - // On Mac OS X, the UI window close is delayed until the outermost - // message loop runs. So it isn't possible to get a BROWSER_CLOSED - // notification inside of a test. - content::WindowedNotificationObserver signal( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::Source<Browser>(incognito)); -#endif - // Close the Incognito window and don't crash. chrome::CloseWindow(incognito); -#if !defined(OS_MACOSX) - signal.Wait(); + ui_test_utils::WaitForBrowserToClose(incognito); ExpectWindowCountAfterDownload(1); -#endif base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); CheckDownload(browser(), file, file); @@ -4237,10 +4226,7 @@ GURL url = embedded_test_server()->GetURL("/" + std::string(kDownloadTest1Path)); -#if !defined(OS_MACOSX) - // See below. - Browser* first_browser = browser(); -#endif + const Browser* first_browser = browser(); // Download a file in a new window and wait. DownloadAndWaitWithDisposition(browser(), url, @@ -4264,23 +4250,12 @@ EXPECT_EQ(1, download_browser->tab_strip_model()->count()); EXPECT_TRUE(download_browser->window()->IsDownloadShelfVisible()); -#if !defined(OS_MACOSX) - // On Mac OS X, the UI window close is delayed until the outermost - // message loop runs. So it isn't possible to get a BROWSER_CLOSED - // notification inside of a test. - content::WindowedNotificationObserver signal( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::Source<Browser>(download_browser)); -#endif - // Close the new window. chrome::CloseWindow(download_browser); -#if !defined(OS_MACOSX) - signal.Wait(); + ui_test_utils::WaitForBrowserToClose(download_browser); EXPECT_EQ(first_browser, browser()); ExpectWindowCountAfterDownload(1); -#endif EXPECT_EQ(1, browser()->tab_strip_model()->count()); // Download shelf should close.
diff --git a/chrome/browser/download/notification/download_item_notification.cc b/chrome/browser/download/notification/download_item_notification.cc index a2ed6cbc..e4a77b1 100644 --- a/chrome/browser/download/notification/download_item_notification.cc +++ b/chrome/browser/download/notification/download_item_notification.cc
@@ -8,7 +8,6 @@ #include <stdint.h> #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/files/file_util.h" #include "base/i18n/rtl.h" @@ -16,6 +15,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "build/build_config.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/note_taking_helper.h" #include "chrome/browser/download/download_crx_util.h" @@ -193,7 +193,7 @@ // overridden by UpdateNotificationData() below. message_center::RichNotificationData rich_notification_data; rich_notification_data.should_make_spoken_feedback_for_popup_updates = false; - rich_notification_data.vector_small_image = &ash::kNotificationDownloadIcon; + rich_notification_data.vector_small_image = &kNotificationDownloadIcon; notification_ = std::make_unique<message_center::Notification>( message_center::NOTIFICATION_TYPE_PROGRESS, GetNotificationId(),
diff --git a/chrome/browser/enterprise_reporting/profile_report_generator.cc b/chrome/browser/enterprise_reporting/profile_report_generator.cc index 91065a7..209b61b0 100644 --- a/chrome/browser/enterprise_reporting/profile_report_generator.cc +++ b/chrome/browser/enterprise_reporting/profile_report_generator.cc
@@ -12,7 +12,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/identity_manager_factory.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/plugin_service.h" #include "content/public/common/webplugininfo.h"
diff --git a/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc b/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc index 5c4b7b7..88842c39 100644 --- a/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc +++ b/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc
@@ -19,8 +19,7 @@ #include "chrome/browser/sync/sync_ui_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" -#include "components/signin/core/browser/account_reconcilor.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/sync/driver/sync_service.h"
diff --git a/chrome/browser/extensions/api/identity/gaia_web_auth_flow.cc b/chrome/browser/extensions/api/identity/gaia_web_auth_flow.cc index 3c3708a..63053ca 100644 --- a/chrome/browser/extensions/api/identity/gaia_web_auth_flow.cc +++ b/chrome/browser/extensions/api/identity/gaia_web_auth_flow.cc
@@ -14,8 +14,8 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/chrome_device_id_helper.h" #include "chrome/browser/signin/identity_manager_factory.h" -#include "components/signin/core/browser/ubertoken_fetcher.h" #include "components/signin/public/identity_manager/identity_manager.h" +#include "components/signin/public/identity_manager/ubertoken_fetcher.h" #include "google_apis/gaia/gaia_auth_fetcher.h" #include "google_apis/gaia/gaia_urls.h" #include "net/base/escape.h"
diff --git a/chrome/browser/extensions/api/identity/identity_api.h b/chrome/browser/extensions/api/identity/identity_api.h index 23bc6ed..d766319 100644 --- a/chrome/browser/extensions/api/identity/identity_api.h +++ b/chrome/browser/extensions/api/identity/identity_api.h
@@ -29,7 +29,7 @@ #include "chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h" #include "chrome/browser/extensions/api/identity/web_auth_flow.h" #include "chrome/browser/extensions/chrome_extension_function.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h"
diff --git a/chrome/browser/extensions/api/identity/identity_api_unittest.cc b/chrome/browser/extensions/api/identity/identity_api_unittest.cc index 06ba8e1..a4d5166 100644 --- a/chrome/browser/extensions/api/identity/identity_api_unittest.cc +++ b/chrome/browser/extensions/api/identity/identity_api_unittest.cc
@@ -8,7 +8,7 @@ #include "build/build_config.h" #include "chrome/browser/signin/scoped_account_consistency.h" #include "chrome/test/base/testing_profile.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/extensions/api/identity/identity_apitest.cc b/chrome/browser/extensions/api/identity/identity_apitest.cc index 4c5a733..14ec9eb52 100644 --- a/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chrome/browser/extensions/api/identity/identity_apitest.cc
@@ -47,8 +47,8 @@ #include "components/guest_view/browser/guest_view_base.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_reconcilor.h" -#include "components/signin/core/browser/list_accounts_test_utils.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/list_accounts_test_utils.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h"
diff --git a/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc b/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc index bc522cc..87a72fb 100644 --- a/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc +++ b/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc
@@ -13,7 +13,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/common/extensions/api/identity.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browser_context.h"
diff --git a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc index 9ef98cc..b3bf908 100644 --- a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc +++ b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc
@@ -23,7 +23,7 @@ #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/extensions/api/identity.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/access_token_info.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "content/public/browser/browser_task_traits.h"
diff --git a/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc b/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc index 6b844d55..638ad8b7 100644 --- a/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc +++ b/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc
@@ -8,7 +8,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/common/extensions/api/identity.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browser_context.h" #include "extensions/common/extension.h"
diff --git a/chrome/browser/extensions/extension_commands_global_registry_apitest.cc b/chrome/browser/extensions/extension_commands_global_registry_apitest.cc index 371b4fba..99eeb642 100644 --- a/chrome/browser/extensions/extension_commands_global_registry_apitest.cc +++ b/chrome/browser/extensions/extension_commands_global_registry_apitest.cc
@@ -12,6 +12,7 @@ #include "extensions/test/result_catcher.h" #include "ui/base/base_window.h" #include "ui/base/test/ui_controls.h" +#include "ui/events/event_constants.h" #if defined(USE_X11) #include "ui/aura/window.h"
diff --git a/chrome/browser/external_protocol/external_protocol_handler_browsertest.cc b/chrome/browser/external_protocol/external_protocol_handler_browsertest.cc index 125d7aa6..cc4676f9 100644 --- a/chrome/browser/external_protocol/external_protocol_handler_browsertest.cc +++ b/chrome/browser/external_protocol/external_protocol_handler_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 "build/build_config.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/test/browser_test_utils.h" @@ -16,8 +17,16 @@ " });" "});"; +// http://crbug.com/982234 +#if defined(OS_WIN) +#define MAYBE_AutoCloseTabOnNonWebProtocolNavigation \ + DISABLED_AutoCloseTabOnNonWebProtocolNavigation +#else +#define MAYBE_AutoCloseTabOnNonWebProtocolNavigation \ + AutoCloseTabOnNonWebProtocolNavigation +#endif IN_PROC_BROWSER_TEST_F(ExternalProtocolHandlerBrowserTest, - AutoCloseTabOnNonWebProtocolNavigation) { + MAYBE_AutoCloseTabOnNonWebProtocolNavigation) { content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(true, EvalJs(web_contents, kScript));
diff --git a/chrome/browser/fast_shutdown_browsertest.cc b/chrome/browser/fast_shutdown_browsertest.cc index 72e87c0..e9f86fe 100644 --- a/chrome/browser/fast_shutdown_browsertest.cc +++ b/chrome/browser/fast_shutdown_browsertest.cc
@@ -7,7 +7,6 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "build/build_config.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -18,7 +17,6 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/test/browser_test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" @@ -50,13 +48,10 @@ GURL url = embedded_test_server()->GetURL("/fast_shutdown/on_unloader.html"); EXPECT_EQ("", content::GetCookies(browser()->profile(), url)); - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); ui_test_utils::NavigateToURLWithDisposition( browser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_NONE); - window_observer.Wait(); + ui_test_utils::WaitForBrowserToOpen(); // Close the new window, removing the one and only beforeunload handler. ASSERT_EQ(2u, chrome::GetTotalBrowserCount());
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index ec7f6305..45cba2a7 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -341,6 +341,11 @@ "expiry_milestone": 79 }, { + "name": "enable-autofill-save-card-show-no-thanks", + "owners": ["siashah", "jsaul@google.com"], + "expiry_milestone": 82 + }, + { "name": "automatic-password-generation", "owners": [ "ioanap", "fhorschig" ], "expiry_milestone": 76 @@ -366,6 +371,11 @@ "expiry_milestone": 76 }, { + "name": "camera-system-web-app", + "owners": [ "calamity", "ortuno" ], + "expiry_milestone": 82 + }, + { "name": "cast-media-route-provider", "owners": [ "mfoltz", "takumif" ], "expiry_milestone": 83
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 5e3762c..1a7e2f2 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -516,6 +516,11 @@ "If enabled, adds a [No thanks] button to credit card save bubbles and " "updates their title headers."; +const char kEnableAutofillSaveCardShowNoThanksName[] = + "Show explicit decline option in credit card save prompts"; +const char kEnableAutofillSaveCardShowNoThanksDescription[] = + "If enabled, adds a [No thanks] button to credit card save prompts."; + const char kEnableAutofillSaveCreditCardUsesImprovedMessagingName[] = "Enable new title and button label for credit card upload bubble"; const char kEnableAutofillSaveCreditCardUsesImprovedMessagingDescription[] = @@ -2971,6 +2976,10 @@ const char kBulkPrintersName[] = "Bulk Printers Policy"; const char kBulkPrintersDescription[] = "Enables the new bulk printers policy"; +const char kCameraSystemWebAppName[] = "Camera System Web App"; +const char kCameraSystemWebAppDescription[] = + "Run the Chrome Camera App as a System Web App."; + const char kCrOSContainerName[] = "Chrome OS Container"; const char kCrOSContainerDescription[] = "Enable the use of Chrome OS Container utility.";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 31798884..466865b 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -312,6 +312,9 @@ extern const char kEnableAutofillSaveCardImprovedUserConsentName[]; extern const char kEnableAutofillSaveCardImprovedUserConsentDescription[]; +extern const char kEnableAutofillSaveCardShowNoThanksName[]; +extern const char kEnableAutofillSaveCardShowNoThanksDescription[]; + extern const char kEnableAutofillSaveCreditCardUsesImprovedMessagingName[]; extern const char kEnableAutofillSaveCreditCardUsesImprovedMessagingDescription[]; @@ -1770,6 +1773,9 @@ extern const char kBulkPrintersName[]; extern const char kBulkPrintersDescription[]; +extern const char kCameraSystemWebAppName[]; +extern const char kCameraSystemWebAppDescription[]; + extern const char kCrOSContainerName[]; extern const char kCrOSContainerDescription[];
diff --git a/chrome/browser/lifetime/browser_close_manager_browsertest.cc b/chrome/browser/lifetime/browser_close_manager_browsertest.cc index 3864ba1..8ef59bb 100644 --- a/chrome/browser/lifetime/browser_close_manager_browsertest.cc +++ b/chrome/browser/lifetime/browser_close_manager_browsertest.cc
@@ -303,6 +303,11 @@ PrepareForDialog(browser->tab_strip_model()->GetWebContentsAt(i)); } + void WaitForAllBrowsersToClose() { + for (size_t i = 0U; i < browsers_.size(); ++i) + ui_test_utils::WaitForBrowserToClose(); + } + std::vector<Browser*> browsers_; }; @@ -319,11 +324,9 @@ EXPECT_FALSE(browser_shutdown::IsTryingToQuit()); EXPECT_EQ(1, browser()->tab_strip_model()->count()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); chrome::CloseAllBrowsersAndQuit(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -343,12 +346,10 @@ EXPECT_FALSE(browser_shutdown::IsTryingToQuit()); EXPECT_EQ(1, browser()->tab_strip_model()->count()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); chrome::CloseAllBrowsersAndQuit(); chrome::CloseAllBrowsersAndQuit(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -378,10 +379,8 @@ ASSERT_NO_FATAL_FAILURE(AcceptClose()); navigation_observer.Wait(); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); chrome::CloseAllBrowsersAndQuit(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -441,12 +440,10 @@ EXPECT_EQ(1, browsers_[1]->tab_strip_model()->count()); // Allow shutdown for both beforeunload events. - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 2); chrome::CloseAllBrowsersAndQuit(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -477,11 +474,9 @@ // All tabs should still be open. EXPECT_EQ(3, browsers_[0]->tab_strip_model()->count()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); chrome::CloseAllBrowsersAndQuit(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -514,13 +509,10 @@ EXPECT_EQ(1, browsers_[1]->tab_strip_model()->count()); EXPECT_EQ(1, browsers_[2]->tab_strip_model()->count()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 3); chrome::CloseAllBrowsersAndQuit(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); - EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); - EXPECT_TRUE(BrowserList::GetInstance()->empty()); + + WaitForAllBrowsersToClose(); } // Test that tabs that are slow to respond are not closed prematurely. @@ -563,13 +555,11 @@ // All tabs should still be open. EXPECT_EQ(kTabCount, browsers_[0]->tab_strip_model()->count()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); // Quit, this time accepting close confirmation dialog. chrome::CloseAllBrowsersAndQuit(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -621,11 +611,9 @@ EXPECT_EQ(1, browsers_[i]->tab_strip_model()->count()); // Quit, this time accepting close confirmation dialog. - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, kBrowserCount); chrome::CloseAllBrowsersAndQuit(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -644,12 +632,10 @@ browsers_[0], embedded_test_server()->GetURL("/beforeunload.html"))); PrepareForDialog(browsers_[0]); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 2); chrome::CloseAllBrowsersAndQuit(); browsers_.push_back(CreateBrowser(browser()->profile())); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -677,12 +663,10 @@ EXPECT_EQ(1, browsers_[1]->tab_strip_model()->count()); // Allow shutdown for both beforeunload dialogs. - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 2); chrome::CloseAllBrowsersAndQuit(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -698,14 +682,12 @@ PrepareForDialog(browsers_[0]); PrepareForDialog(browsers_[1]); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 2); chrome::CloseAllBrowsersAndQuit(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); AddBlankTabAndShow(browsers_[0]); AddBlankTabAndShow(browsers_[1]); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -742,15 +724,13 @@ EXPECT_EQ(2, browsers_[0]->tab_strip_model()->count()); EXPECT_EQ(2, browsers_[1]->tab_strip_model()->count()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 2); chrome::CloseAllBrowsersAndQuit(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); ASSERT_NO_FATAL_FAILURE(AcceptClose()); ASSERT_NO_FATAL_FAILURE(AcceptClose()); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -800,9 +780,6 @@ // The test. TabRestoreServiceChangesObserver restore_observer(browser2->profile()); - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); chrome::CloseWindow(browser2); // Just to be sure CloseWindow doesn't have asynchronous tasks // that could have an impact. @@ -829,18 +806,14 @@ EXPECT_EQ(2, browser2->tab_strip_model()->count()); // Accept closing the second tab. ASSERT_NO_FATAL_FAILURE(AcceptClose()); - observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); // Now the second window/browser should be closed. EXPECT_EQ(1u, BrowserList::GetInstance()->size()); EXPECT_EQ(browser(), BrowserList::GetInstance()->get(0)); EXPECT_EQ(1u, restore_observer.changes_count()); // Restore the closed browser. - content::WindowedNotificationObserver open_window_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); chrome::OpenWindowWithRestoredTabs(browser()->profile()); - open_window_observer.Wait(); EXPECT_EQ(2u, BrowserList::GetInstance()->size()); browser2 = BrowserList::GetInstance()->get(0) != browser() ? BrowserList::GetInstance()->get(0) @@ -876,14 +849,12 @@ EXPECT_EQ(1, browsers_[0]->tab_strip_model()->count()); EXPECT_EQ(1, browsers_[1]->tab_strip_model()->count()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 2); chrome::CloseAllBrowsersAndQuit(); browsers_[1]->tab_strip_model()->CloseAllTabs(); ASSERT_NO_FATAL_FAILURE(AcceptClose()); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -910,14 +881,12 @@ EXPECT_EQ(1, browsers_[0]->tab_strip_model()->count()); EXPECT_EQ(1, browsers_[1]->tab_strip_model()->count()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 2); chrome::CloseAllBrowsersAndQuit(); ASSERT_FALSE(browsers_[1]->ShouldCloseWindow()); ASSERT_NO_FATAL_FAILURE(AcceptClose()); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -943,14 +912,12 @@ EXPECT_EQ(1, browsers_[0]->tab_strip_model()->count()); EXPECT_EQ(1, browsers_[1]->tab_strip_model()->count()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 2); chrome::CloseAllBrowsersAndQuit(); ASSERT_FALSE(browsers_[0]->ShouldCloseWindow()); ASSERT_NO_FATAL_FAILURE(AcceptClose()); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -962,12 +929,9 @@ IN_PROC_BROWSER_TEST_F(BrowserCloseManagerBrowserTest, TestWithDownloads) { ASSERT_NO_FATAL_FAILURE(CreateStalledDownload(browser())); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); - TestBrowserCloseManager::AttemptClose( TestBrowserCloseManager::NO_USER_CHOICE); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); EXPECT_EQ(1, DownloadCoreService::NonMaliciousDownloadCountAllProfiles()); @@ -1008,11 +972,9 @@ browser()->profile())->NonMaliciousInProgressCount()); // Close the browser with no user action. - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); TestBrowserCloseManager::AttemptClose( TestBrowserCloseManager::NO_USER_CHOICE); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -1029,12 +991,9 @@ EXPECT_EQ(GURL(chrome::kChromeUIDownloadsURL), browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); - TestBrowserCloseManager::AttemptClose( TestBrowserCloseManager::USER_CHOICE_USER_ALLOWS_CLOSE); - close_observer.Wait(); + WaitForAllBrowsersToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); if (browser_defaults::kBrowserAliveWithNoWindows) @@ -1049,10 +1008,8 @@ Profile* otr_profile = browser()->profile()->GetOffTheRecordProfile(); Browser* otr_browser = CreateBrowser(otr_profile); { - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); browser()->window()->Close(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); } ASSERT_NO_FATAL_FAILURE(CreateStalledDownload(otr_browser)); content::TestNavigationObserver navigation_observer( @@ -1064,12 +1021,9 @@ EXPECT_EQ(GURL(chrome::kChromeUIDownloadsURL), otr_browser->tab_strip_model()->GetActiveWebContents()->GetURL()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); - TestBrowserCloseManager::AttemptClose( TestBrowserCloseManager::USER_CHOICE_USER_ALLOWS_CLOSE); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); EXPECT_EQ(0, DownloadCoreService::NonMaliciousDownloadCountAllProfiles()); @@ -1099,10 +1053,8 @@ ASSERT_EQ(0, num_downloads_blocking); { - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); otr_browser->window()->Close(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); } ASSERT_EQ( @@ -1111,11 +1063,9 @@ ASSERT_EQ(1, num_downloads_blocking); { - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 2); TestBrowserCloseManager::AttemptClose( TestBrowserCloseManager::USER_CHOICE_USER_ALLOWS_CLOSE); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); } EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); @@ -1148,10 +1098,8 @@ ASSERT_NO_FATAL_FAILURE(CreateStalledDownload(browser())); { - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); browser()->window()->Close(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); } // When the shutdown is cancelled, the downloads page should be opened in a @@ -1169,11 +1117,10 @@ other_profile_browser->tab_strip_model()->GetActiveWebContents() ->GetURL()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 2); TestBrowserCloseManager::AttemptClose( TestBrowserCloseManager::USER_CHOICE_USER_ALLOWS_CLOSE); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); if (browser_defaults::kBrowserAliveWithNoWindows) @@ -1200,12 +1147,10 @@ cancel_observer.Wait(); EXPECT_FALSE(browser_shutdown::IsTryingToQuit()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); TestBrowserCloseManager::AttemptClose( TestBrowserCloseManager::USER_CHOICE_USER_ALLOWS_CLOSE); ASSERT_NO_FATAL_FAILURE(AcceptClose()); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); } @@ -1244,12 +1189,10 @@ std::unique_ptr<ScopedKeepAlive> tmp_keep_alive; Profile* profile = browser()->profile(); { - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); tmp_keep_alive.reset(new ScopedKeepAlive(KeepAliveOrigin::PANEL_VIEW, KeepAliveRestartOption::DISABLED)); chrome::CloseAllBrowsers(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); } EXPECT_FALSE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); @@ -1261,12 +1204,10 @@ new_browser_observer.WaitForSingleNewBrowser(); tmp_keep_alive.reset(); EXPECT_FALSE(IsBackgroundModeSuspended()); - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); // Background mode should not be suspended when quitting. chrome::CloseAllBrowsersAndQuit(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); EXPECT_FALSE(IsBackgroundModeSuspended()); @@ -1276,11 +1217,9 @@ // background mode. IN_PROC_BROWSER_TEST_F(BrowserCloseManagerWithBackgroundModeBrowserTest, DISABLED_CloseSingleBrowserWithBackgroundMode) { - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); EXPECT_FALSE(IsBackgroundModeSuspended()); browser()->window()->Close(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_FALSE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); EXPECT_FALSE(IsBackgroundModeSuspended()); @@ -1291,13 +1230,11 @@ IN_PROC_BROWSER_TEST_F( BrowserCloseManagerWithBackgroundModeBrowserTest, DISABLED_CloseAllBrowsersWithNoOpenBrowsersWithBackgroundMode) { - RepeatedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, 1); EXPECT_FALSE(IsBackgroundModeSuspended()); ScopedKeepAlive tmp_keep_alive(KeepAliveOrigin::PANEL_VIEW, KeepAliveRestartOption::DISABLED); browser()->window()->Close(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_FALSE(browser_shutdown::IsTryingToQuit()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); EXPECT_FALSE(IsBackgroundModeSuspended());
diff --git a/chrome/browser/media/android/router/media_router_dialog_controller_android.cc b/chrome/browser/media/android/router/media_router_dialog_controller_android.cc index 27bf2f2..149455f 100644 --- a/chrome/browser/media/android/router/media_router_dialog_controller_android.cc +++ b/chrome/browser/media/android/router/media_router_dialog_controller_android.cc
@@ -35,8 +35,8 @@ namespace media_router { // static -MediaRouterDialogControllerAndroid* -MediaRouterDialogControllerAndroid::GetOrCreateForWebContents( +MediaRouterDialogController* +MediaRouterDialogController::GetOrCreateForWebContents( WebContents* web_contents) { DCHECK(web_contents); // This call does nothing if the controller already exists.
diff --git a/chrome/browser/media/android/router/media_router_dialog_controller_android.h b/chrome/browser/media/android/router/media_router_dialog_controller_android.h index 75ff7c1a..00d28b8 100644 --- a/chrome/browser/media/android/router/media_router_dialog_controller_android.h +++ b/chrome/browser/media/android/router/media_router_dialog_controller_android.h
@@ -21,9 +21,6 @@ public: ~MediaRouterDialogControllerAndroid() override; - static MediaRouterDialogControllerAndroid* GetOrCreateForWebContents( - content::WebContents* web_contents); - // The methods called by the Java counterpart. // Notifies the controller that user has selected a sink with |jsink_id| for
diff --git a/chrome/browser/media/router/media_router_dialog_controller.cc b/chrome/browser/media/router/media_router_dialog_controller.cc index 5b598c7..84fe219 100644 --- a/chrome/browser/media/router/media_router_dialog_controller.cc +++ b/chrome/browser/media/router/media_router_dialog_controller.cc
@@ -14,27 +14,8 @@ #include "content/public/browser/web_contents_delegate.h" #include "third_party/blink/public/mojom/presentation/presentation.mojom.h" -#if defined(OS_ANDROID) -#include "chrome/browser/media/android/router/media_router_dialog_controller_android.h" -#else -#include "chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.h" -#endif - namespace media_router { -// static -MediaRouterDialogController* -MediaRouterDialogController::GetOrCreateForWebContents( - content::WebContents* contents) { -#if defined(OS_ANDROID) - return MediaRouterDialogControllerAndroid::GetOrCreateForWebContents( - contents); -#else - return MediaRouterDialogControllerImplBase::GetOrCreateForWebContents( - contents); -#endif -} - class MediaRouterDialogController::InitiatorWebContentsObserver : public content::WebContentsObserver { public:
diff --git a/chrome/browser/media/router/media_router_dialog_controller.h b/chrome/browser/media/router/media_router_dialog_controller.h index ddf9351..8b0266c 100644 --- a/chrome/browser/media/router/media_router_dialog_controller.h +++ b/chrome/browser/media/router/media_router_dialog_controller.h
@@ -33,7 +33,9 @@ // Gets a reference to the MediaRouterDialogController associated with // |web_contents|, creating one if it does not exist. The returned pointer is - // guaranteed to be non-null. + // guaranteed to be non-null. This method has platform-specific + // implementations in directories such as chrome/browser/ui/views/ and + // chrome/browser/media/android/. static MediaRouterDialogController* GetOrCreateForWebContents( content::WebContents* web_contents);
diff --git a/chrome/browser/navigation_predictor/navigation_predictor.cc b/chrome/browser/navigation_predictor/navigation_predictor.cc index e432978..8e58fdc 100644 --- a/chrome/browser/navigation_predictor/navigation_predictor.cc +++ b/chrome/browser/navigation_predictor/navigation_predictor.cc
@@ -201,6 +201,7 @@ content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); current_visibility_ = web_contents->GetVisibility(); + ukm_source_id_ = web_contents->GetLastCommittedSourceId(); Observe(web_contents); }
diff --git a/chrome/browser/navigation_predictor/navigation_predictor.h b/chrome/browser/navigation_predictor/navigation_predictor.h index 2485012..fa75cb69 100644 --- a/chrome/browser/navigation_predictor/navigation_predictor.h +++ b/chrome/browser/navigation_predictor/navigation_predictor.h
@@ -17,6 +17,7 @@ #include "content/public/browser/visibility.h" #include "content/public/browser/web_contents_observer.h" #include "mojo/public/cpp/bindings/interface_request.h" +#include "services/metrics/public/cpp/ukm_source_id.h" #include "third_party/blink/public/mojom/loader/navigation_predictor.mojom.h" #include "ui/gfx/geometry/size.h" #include "url/origin.h" @@ -286,6 +287,11 @@ // PrerenderHandle returned after completing a prefetch in PrerenderManager. std::unique_ptr<prerender::PrerenderHandle> prerender_handle_; + // UKM ID for navigation + // TODO(sofiyase): implement that function that uses this id to send aggregate + // link information to the UKM. + ukm::SourceId ukm_source_id_; + SEQUENCE_CHECKER(sequence_checker_); DISALLOW_COPY_AND_ASSIGN(NavigationPredictor);
diff --git a/chrome/browser/net/log_net_log_browsertest.cc b/chrome/browser/net/log_net_log_browsertest.cc index 34a67615..db8e070 100644 --- a/chrome/browser/net/log_net_log_browsertest.cc +++ b/chrome/browser/net/log_net_log_browsertest.cc
@@ -67,9 +67,9 @@ // Verify that cookies were stripped when the --net-log-capture-mode flag // was omitted, and not stripped when it was given a value of - // IncludeCookiesAndCredentials - bool include_cookies = GetParam() && base::StringPiece(GetParam()) == - "IncludeCookiesAndCredentials"; + // IncludeSensitive + bool include_cookies = + GetParam() && base::StringPiece(GetParam()) == "IncludeSensitive"; if (include_cookies) { EXPECT_TRUE(file_contents.find("Set-Cookie: name=Good;Max-Age=3600") != @@ -88,8 +88,7 @@ INSTANTIATE_TEST_SUITE_P(, LogNetLogTest, - ::testing::Values(nullptr, - "IncludeCookiesAndCredentials")); + ::testing::Values(nullptr, "IncludeSensitive")); IN_PROC_BROWSER_TEST_P(LogNetLogTest, Basic) { ASSERT_TRUE(embedded_test_server()->Start());
diff --git a/chrome/browser/net/profile_network_context_service.cc b/chrome/browser/net/profile_network_context_service.cc index 3be72281..2688351b 100644 --- a/chrome/browser/net/profile_network_context_service.cc +++ b/chrome/browser/net/profile_network_context_service.cc
@@ -467,9 +467,7 @@ #if defined(OS_CHROMEOS) user_manager::UserManager* user_manager = user_manager::UserManager::Get(); - if (user_manager && - policy::PolicyCertServiceFactory::CreateAndStartObservingForProfile( - profile_)) { + if (user_manager) { const user_manager::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile(profile_); // No need to initialize NSS for users with empty username hash: @@ -479,15 +477,17 @@ if (user && !user->username_hash().empty()) { network_context_params->username_hash = user->username_hash(); network_context_params->nss_path = profile_->GetPath(); - - policy::PolicyCertService* service = - policy::PolicyCertServiceFactory::GetForProfile(profile_); - network_context_params->initial_additional_certificates = - network::mojom::AdditionalCertificates::New(); - network_context_params->initial_additional_certificates - ->all_certificates = service->all_server_and_authority_certs(); - network_context_params->initial_additional_certificates->trust_anchors = - service->trust_anchors(); + if (policy::PolicyCertServiceFactory::CreateAndStartObservingForProfile( + profile_)) { + policy::PolicyCertService* service = + policy::PolicyCertServiceFactory::GetForProfile(profile_); + network_context_params->initial_additional_certificates = + network::mojom::AdditionalCertificates::New(); + network_context_params->initial_additional_certificates + ->all_certificates = service->all_server_and_authority_certs(); + network_context_params->initial_additional_certificates->trust_anchors = + service->trust_anchors(); + } } } #endif
diff --git a/chrome/browser/notifications/notification_interactive_uitest_mac.mm b/chrome/browser/notifications/notification_interactive_uitest_mac.mm index 9a648ae..5d03fed6 100644 --- a/chrome/browser/notifications/notification_interactive_uitest_mac.mm +++ b/chrome/browser/notifications/notification_interactive_uitest_mac.mm
@@ -8,6 +8,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #import "ui/base/test/windowed_nsnotification_observer.h" #include "ui/message_center/message_center.h"
diff --git a/chrome/browser/notifications/notification_platform_bridge_linux.cc b/chrome/browser/notifications/notification_platform_bridge_linux.cc index c34c8ddf..04a4ac46 100644 --- a/chrome/browser/notifications/notification_platform_bridge_linux.cc +++ b/chrome/browser/notifications/notification_platform_bridge_linux.cc
@@ -35,7 +35,7 @@ #include "chrome/grit/chrome_unscaled_resources.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" -#include "components/dbus/dbus_thread_linux.h" +#include "components/dbus/thread_linux/dbus_thread_linux.h" #include "components/url_formatter/elide_url.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/notifications/notification_platform_bridge_linux_unittest.cc b/chrome/browser/notifications/notification_platform_bridge_linux_unittest.cc index 748c759..3dde64419 100644 --- a/chrome/browser/notifications/notification_platform_bridge_linux_unittest.cc +++ b/chrome/browser/notifications/notification_platform_bridge_linux_unittest.cc
@@ -21,7 +21,7 @@ #include "chrome/browser/notifications/notification_display_service_tester.h" #include "chrome/browser/notifications/notification_test_util.h" #include "chrome/test/base/browser_with_test_window_test.h" -#include "components/dbus/dbus_thread_linux.h" +#include "components/dbus/thread_linux/dbus_thread_linux.h" #include "content/public/test/test_utils.h" #include "dbus/mock_bus.h" #include "dbus/mock_object_proxy.h"
diff --git a/chrome/browser/offline_pages/offline_page_utils_unittest.cc b/chrome/browser/offline_pages/offline_page_utils_unittest.cc index 2bd76419..cd4e214 100644 --- a/chrome/browser/offline_pages/offline_page_utils_unittest.cc +++ b/chrome/browser/offline_pages/offline_page_utils_unittest.cc
@@ -350,12 +350,7 @@ EXPECT_EQ(OfflinePageUtils::DuplicateCheckResult::NOT_FOUND, result); } -#if defined(DISABLE_OFFLINE_PAGES_TOUCHLESS) -#define MAYBE_ScheduleDownload DISABLED_ScheduleDownload -#else -#define MAYBE_ScheduleDownload ScheduleDownload -#endif -TEST_F(OfflinePageUtilsTest, MAYBE_ScheduleDownload) { +TEST_F(OfflinePageUtilsTest, ScheduleDownload) { // Pre-check. ASSERT_EQ(0, FindRequestByNamespaceAndURL(kDownloadNamespace, kTestPage1Url)); ASSERT_EQ(1, FindRequestByNamespaceAndURL(kDownloadNamespace, kTestPage3Url)); @@ -394,14 +389,7 @@ } #endif -#if defined(DISABLE_OFFLINE_PAGES_TOUCHLESS) -#define MAYBE_TestGetCachedOfflinePageSizeBetween \ - DISABLED_TestGetCachedOfflinePageSizeBetween -#else -#define MAYBE_TestGetCachedOfflinePageSizeBetween \ - TestGetCachedOfflinePageSizeBetween -#endif -TEST_F(OfflinePageUtilsTest, MAYBE_TestGetCachedOfflinePageSizeBetween) { +TEST_F(OfflinePageUtilsTest, TestGetCachedOfflinePageSizeBetween) { // The clock will be at 03:00:00 after adding pages. CreateCachedOfflinePages();
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc index 6fff588..be72b35f 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" +#include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/subprocess_metrics_provider.h" #include "chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.h" @@ -873,7 +874,7 @@ } // Flaky on Mac. http://crbug.com/972822 -#if defined(OS_MACOSX) +#if defined(OS_MACOSX) || defined(OS_LINUX) #define MAYBE_AdFrameSizeInterventionMediaStatusPlayed DISABLED_AdFrameSizeInterventionMediaStatusPlayed #else #define MAYBE_AdFrameSizeInterventionMediaStatusPlayed AdFrameSizeInterventionMediaStatusPlayed
diff --git a/chrome/browser/page_load_metrics/observers/previews_ukm_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/previews_ukm_observer_unittest.cc index 644f92cf..72a62e0 100644 --- a/chrome/browser/page_load_metrics/observers/previews_ukm_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/previews_ukm_observer_unittest.cc
@@ -10,6 +10,7 @@ #include "base/base64.h" #include "base/macros.h" #include "base/metrics/metrics_hashes.h" +#include "base/metrics/statistics_recorder.h" #include "base/optional.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" @@ -976,62 +977,58 @@ } TEST_F(PreviewsUKMObserverTest, TestPageEndReasonUMA) { - base::HistogramTester tester; + std::unique_ptr<base::StatisticsRecorder> recorder( + base::StatisticsRecorder::CreateTemporaryForTesting()); + base::HistogramTester tester; - // No preview: - RunTest(content::PREVIEWS_OFF /* committed_state */, - content::PREVIEWS_UNSPECIFIED /* allowed_state */, - false /* origin_opt_out */, false /* save_data_enabled */, - CoinFlipHoldbackResult::kNotSet, {} /* eligibility_reasons */, - base::nullopt /* navigation_restart_penalty */, - base::nullopt /* hint_version_string */); - NavigateToUntrackedUrl(); - tester.ExpectUniqueSample( - "Previews.PageEndReason.None", - page_load_metrics::PageEndReason::END_NEW_NAVIGATION, 1); - // The top level metric is not recorded on a non-preview. - tester.ExpectTotalCount("Previews.PageEndReason", 0); + // No preview: + RunTest(content::PREVIEWS_OFF /* committed_state */, + content::PREVIEWS_UNSPECIFIED /* allowed_state */, + false /* origin_opt_out */, false /* save_data_enabled */, + CoinFlipHoldbackResult::kNotSet, {} /* eligibility_reasons */, + base::nullopt /* navigation_restart_penalty */, + base::nullopt /* hint_version_string */); + NavigateToUntrackedUrl(); + tester.ExpectUniqueSample( + "Previews.PageEndReason.None", + page_load_metrics::PageEndReason::END_NEW_NAVIGATION, 1); + // The top level metric is not recorded on a non-preview. + tester.ExpectTotalCount("Previews.PageEndReason", 0); - // Lite Page Redirect: - RunTest(content::LITE_PAGE_REDIRECT_ON /* committed_state */, - content::PREVIEWS_UNSPECIFIED /* allowed_state */, - false /* origin_opt_out */, false /* save_data_enabled */, - CoinFlipHoldbackResult::kNotSet, {} /* eligibility_reasons */, - base::nullopt /* navigation_restart_penalty */, - base::nullopt /* hint_version_string */); - NavigateToUntrackedUrl(); - tester.ExpectUniqueSample( - "Previews.PageEndReason.LitePageRedirect", - page_load_metrics::PageEndReason::END_NEW_NAVIGATION, 1); - tester.ExpectBucketCount( - "Previews.PageEndReason", - page_load_metrics::PageEndReason::END_NEW_NAVIGATION, 1); + // Lite Page Redirect: + RunTest(content::LITE_PAGE_REDIRECT_ON /* committed_state */, + content::PREVIEWS_UNSPECIFIED /* allowed_state */, + false /* origin_opt_out */, false /* save_data_enabled */, + CoinFlipHoldbackResult::kNotSet, {} /* eligibility_reasons */, + base::nullopt /* navigation_restart_penalty */, + base::nullopt /* hint_version_string */); + NavigateToUntrackedUrl(); + tester.ExpectUniqueSample( + "Previews.PageEndReason.LitePageRedirect", + page_load_metrics::PageEndReason::END_NEW_NAVIGATION, 1); + tester.ExpectBucketCount("Previews.PageEndReason", + page_load_metrics::PageEndReason::END_NEW_NAVIGATION, + 1); - // Defer All Script: - RunTest(content::DEFER_ALL_SCRIPT_ON /* committed_state */, - content::PREVIEWS_UNSPECIFIED /* allowed_state */, - false /* origin_opt_out */, false /* save_data_enabled */, - CoinFlipHoldbackResult::kNotSet, {} /* eligibility_reasons */, - base::nullopt /* navigation_restart_penalty */, - base::nullopt /* hint_version_string */); - NavigateToUntrackedUrl(); - tester.ExpectUniqueSample( - "Previews.PageEndReason.DeferAllScript", - page_load_metrics::PageEndReason::END_NEW_NAVIGATION, 1); - tester.ExpectBucketCount( - "Previews.PageEndReason", - page_load_metrics::PageEndReason::END_NEW_NAVIGATION, 2); + // Defer All Script: + RunTest(content::DEFER_ALL_SCRIPT_ON /* committed_state */, + content::PREVIEWS_UNSPECIFIED /* allowed_state */, + false /* origin_opt_out */, false /* save_data_enabled */, + CoinFlipHoldbackResult::kNotSet, {} /* eligibility_reasons */, + base::nullopt /* navigation_restart_penalty */, + base::nullopt /* hint_version_string */); + NavigateToUntrackedUrl(); + tester.ExpectUniqueSample( + "Previews.PageEndReason.DeferAllScript", + page_load_metrics::PageEndReason::END_NEW_NAVIGATION, 1); + tester.ExpectBucketCount("Previews.PageEndReason", + page_load_metrics::PageEndReason::END_NEW_NAVIGATION, + 2); } -// TODO(crbug.com/981058): Re-enable this test on Linux and Windows. -#if defined(OS_LINUX) || defined(OS_WIN) -#define MAYBE_TestPageEndReasonUMACoinFlipHoldback \ - DISABLED_TestPageEndReasonUMACoinFlipHoldback -#else -#define MAYBE_TestPageEndReasonUMACoinFlipHoldback \ - TestPageEndReasonUMACoinFlipHoldback -#endif -TEST_F(PreviewsUKMObserverTest, MAYBE_TestPageEndReasonUMACoinFlipHoldback) { +TEST_F(PreviewsUKMObserverTest, TestPageEndReasonUMACoinFlipHoldback) { + std::unique_ptr<base::StatisticsRecorder> recorder( + base::StatisticsRecorder::CreateTemporaryForTesting()); base::HistogramTester tester; // No preview: @@ -1061,9 +1058,7 @@ tester.ExpectBucketCount("Previews.PageEndReason.None", page_load_metrics::PageEndReason::END_NEW_NAVIGATION, 2); - tester.ExpectBucketCount("Previews.PageEndReason", - page_load_metrics::PageEndReason::END_NEW_NAVIGATION, - 0); + tester.ExpectTotalCount("Previews.PageEndReason", 0); // Defer All Script: RunTest(content::DEFER_ALL_SCRIPT_ON /* committed_state */, @@ -1078,9 +1073,7 @@ tester.ExpectBucketCount("Previews.PageEndReason.None", page_load_metrics::PageEndReason::END_NEW_NAVIGATION, 3); - tester.ExpectBucketCount("Previews.PageEndReason", - page_load_metrics::PageEndReason::END_NEW_NAVIGATION, - 0); + tester.ExpectTotalCount("Previews.PageEndReason", 0); } } // namespace
diff --git a/chrome/browser/password_manager/native_backend_kwallet_x.cc b/chrome/browser/password_manager/native_backend_kwallet_x.cc index 5064159..9a93d09 100644 --- a/chrome/browser/password_manager/native_backend_kwallet_x.cc +++ b/chrome/browser/password_manager/native_backend_kwallet_x.cc
@@ -23,7 +23,7 @@ #include "base/threading/thread_restrictions.h" #include "chrome/grit/chromium_strings.h" #include "components/autofill/core/common/password_form.h" -#include "components/dbus/dbus_thread_linux.h" +#include "components/dbus/thread_linux/dbus_thread_linux.h" #include "components/password_manager/core/browser/password_manager_util.h" #include "dbus/bus.h" #include "dbus/message.h"
diff --git a/chrome/browser/pdf/pdf_extension_test.cc b/chrome/browser/pdf/pdf_extension_test.cc index 5aac57a..e6c11a7 100644 --- a/chrome/browser/pdf/pdf_extension_test.cc +++ b/chrome/browser/pdf/pdf_extension_test.cc
@@ -51,6 +51,7 @@ #include "components/zoom/page_zoom.h" #include "components/zoom/test/zoom_test_utils.h" #include "components/zoom/zoom_controller.h" +#include "content/public/browser/accessibility_tree_formatter.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_plugin_guest_manager.h" #include "content/public/browser/browser_task_traits.h" @@ -71,6 +72,7 @@ #include "content/public/common/mime_handler_view_mode.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" +#include "content/public/test/dump_accessibility_test_helper.h" #include "content/public/test/hit_test_region_observer.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/url_loader_interceptor.h" @@ -1351,13 +1353,10 @@ WebContents* web_contents = GetActiveWebContents(); - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); content::SimulateMouseClickAt( GetWebContentsForInputRouting(), blink::WebInputEvent::kShiftKey, blink::WebMouseEvent::Button::kLeft, GetLinkPosition()); - observer.Wait(); + ui_test_utils::WaitForBrowserToOpen(); ASSERT_EQ(2U, chrome::GetTotalBrowserCount()); @@ -1517,13 +1516,10 @@ WebContents* web_contents = GetActiveWebContents(); - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); content::SimulateMouseClickAt( GetWebContentsForInputRouting(), blink::WebInputEvent::kShiftKey, blink::WebMouseEvent::Button::kLeft, GetLinkPosition()); - observer.Wait(); + ui_test_utils::WaitForBrowserToOpen(); ASSERT_EQ(2U, chrome::GetTotalBrowserCount()); @@ -2242,3 +2238,144 @@ // loading. content::WaitForLoadStop(web_contents); } + +class PDFExtensionAccessibilityTreeDumpTest + : public PDFExtensionTest, + public ::testing::WithParamInterface<size_t> { + public: + PDFExtensionAccessibilityTreeDumpTest() + : test_pass_( + content::AccessibilityTreeFormatter::GetTestPass(GetParam())) {} + ~PDFExtensionAccessibilityTreeDumpTest() override = default; + + void SetUpCommandLine(base::CommandLine* command_line) override { + PDFExtensionTest::SetUpCommandLine(command_line); + + // Each test pass might require custom command-line setup + if (test_pass_.set_up_command_line) + test_pass_.set_up_command_line(command_line); + } + + protected: + void RunPDFTest(const base::FilePath::CharType* pdf_file) { + base::FilePath test_path = ui_test_utils::GetTestFilePath( + base::FilePath(FILE_PATH_LITERAL("pdf")), + base::FilePath(FILE_PATH_LITERAL("accessibility"))); + { + base::ScopedAllowBlockingForTesting allow_blocking; + ASSERT_TRUE(base::PathExists(test_path)) << test_path.LossyDisplayName(); + } + base::FilePath pdf_path = test_path.Append(pdf_file); + + RunTest(pdf_path, "pdf/accessibility"); + } + + private: + using PropertyFilter = content::AccessibilityTreeFormatter::PropertyFilter; + + void RunTest(const base::FilePath& test_file_path, const char* file_dir) { + // Set up the tree formatter. + std::unique_ptr<content::AccessibilityTreeFormatter> formatter = + test_pass_.create_formatter(); + std::vector<PropertyFilter> property_filters; + formatter->AddDefaultFilters(&property_filters); + AddDefaultFilters(&property_filters); + formatter->SetPropertyFilters(property_filters); + + // Exit without running the test if we can't find an expectation file or if + // the expectation file contains a skip marker. + // This is used to skip certain tests on certain platforms. + content::DumpAccessibilityTestHelper test_helper(formatter.get()); + base::Optional<base::FilePath> expected_file_path = + test_helper.GetExpectationFilePath(test_file_path); + if (!expected_file_path) { + LOG(INFO) << "No expectation file present, ignoring test on this " + "platform."; + return; + } + + base::Optional<std::vector<std::string>> expected_lines = + test_helper.LoadExpectationFile(*expected_file_path); + if (!expected_lines) { + LOG(INFO) << "Skipping this test on this platform."; + return; + } + + // Enable accessibility and load the test file. + content::BrowserAccessibilityState::GetInstance()->EnableAccessibility(); + GURL test_pdf_url(embedded_test_server()->GetURL( + "/" + std::string(file_dir) + "/" + + test_file_path.BaseName().MaybeAsASCII())); + WebContents* guest_contents = LoadPdfGetGuestContents(test_pdf_url); + ASSERT_TRUE(guest_contents); + WaitForAccessibilityTreeToContainNodeWithName(guest_contents, "Page 1"); + + // Find the embedded PDF and dump the accessibility tree. + content::FindAccessibilityNodeCriteria find_criteria; + find_criteria.role = ax::mojom::Role::kEmbeddedObject; + content::BrowserAccessibility* pdf_root = + content::FindAccessibilityNode(guest_contents, find_criteria); + CHECK(pdf_root); + + base::string16 actual_contents_utf16; + formatter->FormatAccessibilityTree(pdf_root, &actual_contents_utf16); + std::string actual_contents = base::UTF16ToUTF8(actual_contents_utf16); + + std::vector<std::string> actual_lines = + base::SplitString(actual_contents, "\n", base::KEEP_WHITESPACE, + base::SPLIT_WANT_NONEMPTY); + + // Validate the dump against the expectation file. + EXPECT_TRUE(test_helper.ValidateAgainstExpectation( + test_file_path, *expected_file_path, actual_lines, *expected_lines)); + } + + void AddDefaultFilters(std::vector<PropertyFilter>* property_filters) { + AddPropertyFilter(property_filters, "value='*'"); + // The value attribute on the document object contains the URL of the + // current page which will not be the same every time the test is run. + AddPropertyFilter(property_filters, "value='http*'", PropertyFilter::DENY); + // Object attributes.value + AddPropertyFilter(property_filters, "layout-guess:*", + PropertyFilter::ALLOW); + + AddPropertyFilter(property_filters, "select*"); + AddPropertyFilter(property_filters, "descript*"); + AddPropertyFilter(property_filters, "check*"); + AddPropertyFilter(property_filters, "horizontal"); + AddPropertyFilter(property_filters, "multiselectable"); + + // Deny most empty values + AddPropertyFilter(property_filters, "*=''", PropertyFilter::DENY); + // After denying empty values, because we want to allow name='' + AddPropertyFilter(property_filters, "name=*", PropertyFilter::ALLOW_EMPTY); + } + + void AddPropertyFilter(std::vector<PropertyFilter>* property_filters, + std::string filter, + PropertyFilter::Type type = PropertyFilter::ALLOW) { + property_filters->push_back( + PropertyFilter(base::ASCIIToUTF16(filter), type)); + } + + content::AccessibilityTreeFormatter::TestPass test_pass_; +}; + +// Parameterize the tests so that each test-pass is run independently. +struct DumpAccessibilityTreeTestPassToString { + std::string operator()(const ::testing::TestParamInfo<size_t>& i) const { + return content::AccessibilityTreeFormatter::GetTestPass(i.param).name; + } +}; + +INSTANTIATE_TEST_SUITE_P( + , + PDFExtensionAccessibilityTreeDumpTest, + ::testing::Range( + size_t{0}, + content::AccessibilityTreeFormatter::GetTestPasses().size()), + DumpAccessibilityTreeTestPassToString()); + +IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest, HelloWorld) { + RunPDFTest(FILE_PATH_LITERAL("hello-world.pdf")); +}
diff --git a/chrome/browser/permissions/permission_context_base_unittest.cc b/chrome/browser/permissions/permission_context_base_unittest.cc index 727e2fd..66fd0c29 100644 --- a/chrome/browser/permissions/permission_context_base_unittest.cc +++ b/chrome/browser/permissions/permission_context_base_unittest.cc
@@ -570,8 +570,8 @@ // Don't call this more than once in the same test, as it persists data to // HostContentSettingsMap. void TestParallelRequests(ContentSetting response) { - TestPermissionContext permission_context( - profile(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS); + TestPermissionContext permission_context(profile(), + CONTENT_SETTINGS_TYPE_GEOLOCATION); GURL url("http://www.google.com"); SetUpUrl(url); @@ -611,8 +611,8 @@ const GURL& virtual_url, const ContentSetting want_response, const PermissionStatusSource& want_source) { - TestPermissionContext permission_context( - profile(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS); + TestPermissionContext permission_context(profile(), + CONTENT_SETTINGS_TYPE_GEOLOCATION); NavigateAndCommit(loaded_url); web_contents()->GetController().GetVisibleEntry()->SetVirtualURL(
diff --git a/chrome/browser/policy/browser_signin_policy_handler.cc b/chrome/browser/policy/browser_signin_policy_handler.cc index 286c02e56..05bcb98 100644 --- a/chrome/browser/policy/browser_signin_policy_handler.cc +++ b/chrome/browser/policy/browser_signin_policy_handler.cc
@@ -13,7 +13,7 @@ #include "components/policy/core/common/policy_map.h" #include "components/policy/policy_constants.h" #include "components/prefs/pref_value_map.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" namespace policy { BrowserSigninPolicyHandler::BrowserSigninPolicyHandler(Schema chrome_schema)
diff --git a/chrome/browser/policy/cloud/cloud_policy_invalidator.cc b/chrome/browser/policy/cloud/cloud_policy_invalidator.cc index 7d271d1..e8a17741 100644 --- a/chrome/browser/policy/cloud/cloud_policy_invalidator.cc +++ b/chrome/browser/policy/cloud/cloud_policy_invalidator.cc
@@ -10,7 +10,7 @@ #include "base/feature_list.h" #include "base/hash/hash.h" #include "base/location.h" -#include "base/metrics/histogram_macros.h" +#include "base/metrics/histogram_functions.h" #include "base/rand_util.h" #include "base/sequenced_task_runner.h" #include "base/time/clock.h" @@ -28,6 +28,14 @@ namespace policy { +namespace { + +bool IsFcmEnabled() { + return base::FeatureList::IsEnabled(features::kPolicyFcmInvalidations); +} + +} // namespace + const int CloudPolicyInvalidator::kMissingPayloadDelay = 5; const int CloudPolicyInvalidator::kMaxFetchDelayDefault = 10000; const int CloudPolicyInvalidator::kMaxFetchDelayMin = 1000; @@ -166,14 +174,24 @@ if (is_registered_) { // Update the kMetricDevicePolicyRefresh/kMetricUserPolicyRefresh histogram. + MetricPolicyRefresh metric_policy_refresh = + GetPolicyRefreshMetric(policy_changed); if (type_ == enterprise_management::DeviceRegisterRequest::DEVICE) { - UMA_HISTOGRAM_ENUMERATION(kMetricDevicePolicyRefresh, - GetPolicyRefreshMetric(policy_changed), - METRIC_POLICY_REFRESH_SIZE); + base::UmaHistogramEnumeration(kMetricDevicePolicyRefresh, + metric_policy_refresh, + METRIC_POLICY_REFRESH_SIZE); + base::UmaHistogramEnumeration( + IsFcmEnabled() ? kMetricDevicePolicyRefreshFcm + : kMetricDevicePolicyRefreshTicl, + metric_policy_refresh, METRIC_POLICY_REFRESH_SIZE); } else { - UMA_HISTOGRAM_ENUMERATION(kMetricUserPolicyRefresh, - GetPolicyRefreshMetric(policy_changed), - METRIC_POLICY_REFRESH_SIZE); + base::UmaHistogramEnumeration(kMetricUserPolicyRefresh, + metric_policy_refresh, + METRIC_POLICY_REFRESH_SIZE); + base::UmaHistogramEnumeration( + IsFcmEnabled() ? kMetricUserPolicyRefreshFcm + : kMetricUserPolicyRefreshTicl, + metric_policy_refresh, METRIC_POLICY_REFRESH_SIZE); } const int64_t store_invalidation_version = store->invalidation_version(); @@ -233,16 +251,24 @@ // Ignore the invalidation if it is expired. bool is_expired = IsInvalidationExpired(version); + PolicyInvalidationType policy_invalidation_type = + GetInvalidationMetric(payload.empty(), is_expired); if (type_ == enterprise_management::DeviceRegisterRequest::DEVICE) { - UMA_HISTOGRAM_ENUMERATION( - kMetricDevicePolicyInvalidations, - GetInvalidationMetric(payload.empty(), is_expired), - POLICY_INVALIDATION_TYPE_SIZE); + base::UmaHistogramEnumeration(kMetricDevicePolicyInvalidations, + policy_invalidation_type, + POLICY_INVALIDATION_TYPE_SIZE); + base::UmaHistogramEnumeration( + IsFcmEnabled() ? kMetricDevicePolicyInvalidationsFcm + : kMetricDevicePolicyInvalidationsTicl, + policy_invalidation_type, POLICY_INVALIDATION_TYPE_SIZE); } else { - UMA_HISTOGRAM_ENUMERATION( - kMetricUserPolicyInvalidations, - GetInvalidationMetric(payload.empty(), is_expired), - POLICY_INVALIDATION_TYPE_SIZE); + base::UmaHistogramEnumeration(kMetricUserPolicyInvalidations, + policy_invalidation_type, + POLICY_INVALIDATION_TYPE_SIZE); + base::UmaHistogramEnumeration( + IsFcmEnabled() ? kMetricUserPolicyInvalidationsFcm + : kMetricUserPolicyInvalidationsTicl, + policy_invalidation_type, POLICY_INVALIDATION_TYPE_SIZE); } if (is_expired) { invalidation.Acknowledge(); @@ -320,8 +346,11 @@ LOG(ERROR) << "Failed to register " << syncer::ObjectIdToString(object_id) << " for policy invalidations"; } - UMA_HISTOGRAM_BOOLEAN("Enterprise.PolicyInvalidationsRegistrationResult", - success); + base::UmaHistogramBoolean(kMetricPolicyInvalidationRegistration, success); + base::UmaHistogramBoolean(IsFcmEnabled() + ? kMetricPolicyInvalidationRegistrationFcm + : kMetricPolicyInvalidationRegistrationTicl, + success); } void CloudPolicyInvalidator::Unregister() {
diff --git a/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc b/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc index ceaeb7a..9890e905 100644 --- a/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc
@@ -911,7 +911,13 @@ // Get the current count for the given metric. base::HistogramBase::Count GetCount(MetricPolicyRefresh metric); + base::HistogramBase::Count GetCountFcm(MetricPolicyRefresh metric); + base::HistogramBase::Count GetCountTicl(MetricPolicyRefresh metric); base::HistogramBase::Count GetInvalidationCount(PolicyInvalidationType type); + base::HistogramBase::Count GetInvalidationCountFcm( + PolicyInvalidationType type); + base::HistogramBase::Count GetInvalidationCountTicl( + PolicyInvalidationType type); private: // CloudPolicyInvalidatorTest: @@ -923,9 +929,13 @@ // Stores starting histogram counts for kMetricPolicyRefresh. std::unique_ptr<base::HistogramSamples> refresh_samples_; + std::unique_ptr<base::HistogramSamples> refresh_samples_fcm_; + std::unique_ptr<base::HistogramSamples> refresh_samples_ticl_; // Stores starting histogram counts for kMetricPolicyInvalidations. std::unique_ptr<base::HistogramSamples> invalidations_samples_; + std::unique_ptr<base::HistogramSamples> invalidations_samples_fcm_; + std::unique_ptr<base::HistogramSamples> invalidations_samples_ticl_; DISALLOW_COPY_AND_ASSIGN(CloudPolicyInvalidatorUserTypedTest); }; @@ -940,9 +950,26 @@ refresh_samples_ = GetHistogramSamples( GetPolicyType() == em::DeviceRegisterRequest::DEVICE ? kMetricDevicePolicyRefresh : kMetricUserPolicyRefresh); + refresh_samples_fcm_ = + GetHistogramSamples(GetPolicyType() == em::DeviceRegisterRequest::DEVICE + ? kMetricDevicePolicyRefreshFcm + : kMetricUserPolicyRefreshFcm); + refresh_samples_ticl_ = + GetHistogramSamples(GetPolicyType() == em::DeviceRegisterRequest::DEVICE + ? kMetricDevicePolicyRefreshTicl + : kMetricUserPolicyRefreshTicl); + invalidations_samples_ = GetHistogramSamples( GetPolicyType() == em::DeviceRegisterRequest::DEVICE ? kMetricDevicePolicyInvalidations : kMetricUserPolicyInvalidations); + invalidations_samples_fcm_ = + GetHistogramSamples(GetPolicyType() == em::DeviceRegisterRequest::DEVICE + ? kMetricDevicePolicyInvalidationsFcm + : kMetricUserPolicyInvalidationsFcm); + invalidations_samples_ticl_ = + GetHistogramSamples(GetPolicyType() == em::DeviceRegisterRequest::DEVICE + ? kMetricDevicePolicyInvalidationsTicl + : kMetricUserPolicyInvalidationsTicl); } base::HistogramBase::Count CloudPolicyInvalidatorUserTypedTest::GetCount( @@ -953,6 +980,26 @@ GetCount(metric) - refresh_samples_->GetCount(metric); } +base::HistogramBase::Count CloudPolicyInvalidatorUserTypedTest::GetCountFcm( + MetricPolicyRefresh metric) { + return GetHistogramSamples(GetPolicyType() == + em::DeviceRegisterRequest::DEVICE + ? kMetricDevicePolicyRefreshFcm + : kMetricUserPolicyRefreshFcm) + ->GetCount(metric) - + refresh_samples_fcm_->GetCount(metric); +} + +base::HistogramBase::Count CloudPolicyInvalidatorUserTypedTest::GetCountTicl( + MetricPolicyRefresh metric) { + return GetHistogramSamples(GetPolicyType() == + em::DeviceRegisterRequest::DEVICE + ? kMetricDevicePolicyRefreshTicl + : kMetricUserPolicyRefreshTicl) + ->GetCount(metric) - + refresh_samples_ticl_->GetCount(metric); +} + base::HistogramBase::Count CloudPolicyInvalidatorUserTypedTest::GetInvalidationCount( PolicyInvalidationType type) { @@ -962,6 +1009,28 @@ GetCount(type) - invalidations_samples_->GetCount(type); } +base::HistogramBase::Count +CloudPolicyInvalidatorUserTypedTest::GetInvalidationCountFcm( + PolicyInvalidationType type) { + return GetHistogramSamples(GetPolicyType() == + em::DeviceRegisterRequest::DEVICE + ? kMetricDevicePolicyInvalidationsFcm + : kMetricUserPolicyInvalidationsFcm) + ->GetCount(type) - + invalidations_samples_fcm_->GetCount(type); +} + +base::HistogramBase::Count +CloudPolicyInvalidatorUserTypedTest::GetInvalidationCountTicl( + PolicyInvalidationType type) { + return GetHistogramSamples(GetPolicyType() == + em::DeviceRegisterRequest::DEVICE + ? kMetricDevicePolicyInvalidationsTicl + : kMetricUserPolicyInvalidationsTicl) + ->GetCount(type) - + invalidations_samples_ticl_->GetCount(type); +} + em::DeviceRegisterRequest::Type CloudPolicyInvalidatorUserTypedTest::GetPolicyType() const { return GetParam().policy_type; @@ -987,6 +1056,16 @@ EXPECT_EQ(0, GetCount(METRIC_POLICY_REFRESH_UNCHANGED)); EXPECT_EQ(0, GetCount(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED)); EXPECT_EQ(0, GetCount(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED)); + EXPECT_EQ(0, GetCountFcm(METRIC_POLICY_REFRESH_CHANGED)); + EXPECT_EQ(0, GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(0, GetCountFcm(METRIC_POLICY_REFRESH_UNCHANGED)); + EXPECT_EQ(0, GetCountFcm(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED)); + EXPECT_EQ(0, GetCountFcm(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED)); + EXPECT_EQ(0, GetCountTicl(METRIC_POLICY_REFRESH_CHANGED)); + EXPECT_EQ(0, GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(0, GetCountTicl(METRIC_POLICY_REFRESH_UNCHANGED)); + EXPECT_EQ(0, GetCountTicl(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED)); + EXPECT_EQ(0, GetCountTicl(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED)); EXPECT_EQ(0, GetHighestHandledInvalidationVersion()); } @@ -1001,12 +1080,28 @@ StorePolicy(POLICY_OBJECT_A, 0, false /* policy_changed */); StorePolicy(POLICY_OBJECT_A, 0, true /* policy_changed */); EXPECT_EQ(1, GetCount(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS), + is_fcm_enabled() + ? GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(0, + is_fcm_enabled() + ? GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); // If the clock advances less than the grace period, invalidations are OFF. AdvanceClock(base::TimeDelta::FromSeconds(1)); StorePolicy(POLICY_OBJECT_A, 0, false /* policy_changed */); StorePolicy(POLICY_OBJECT_A, 0, true /* policy_changed */); EXPECT_EQ(2, GetCount(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS), + is_fcm_enabled() + ? GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(0, + is_fcm_enabled() + ? GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); // After the grace period elapses, invalidations are ON. AdvanceClock(base::TimeDelta::FromSeconds( @@ -1014,12 +1109,25 @@ StorePolicy(POLICY_OBJECT_A, 0, false /* policy_changed */); StorePolicy(POLICY_OBJECT_A, 0, true /* policy_changed */); EXPECT_EQ(1, GetCount(METRIC_POLICY_REFRESH_CHANGED)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_CHANGED), + is_fcm_enabled() ? GetCountFcm(METRIC_POLICY_REFRESH_CHANGED) + : GetCountTicl(METRIC_POLICY_REFRESH_CHANGED)); + EXPECT_EQ(0, is_fcm_enabled() ? GetCountTicl(METRIC_POLICY_REFRESH_CHANGED) + : GetCountFcm(METRIC_POLICY_REFRESH_CHANGED)); // After the invalidation service is disabled, invalidations are OFF. DisableInvalidationService(); StorePolicy(POLICY_OBJECT_A, 0, false /* policy_changed */); StorePolicy(POLICY_OBJECT_A, 0, true /* policy_changed */); EXPECT_EQ(3, GetCount(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS), + is_fcm_enabled() + ? GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(0, + is_fcm_enabled() + ? GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); // Enabling the invalidation service results in a new grace period, so // invalidations are OFF. @@ -1027,6 +1135,10 @@ StorePolicy(POLICY_OBJECT_A, 0, false /* policy_changed */); StorePolicy(POLICY_OBJECT_A, 0, true /* policy_changed */); EXPECT_EQ(4, GetCount(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS), + is_fcm_enabled() + ? GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); // After the grace period elapses, invalidations are ON. AdvanceClock(base::TimeDelta::FromSeconds( @@ -1039,6 +1151,44 @@ EXPECT_EQ(6, GetCount(METRIC_POLICY_REFRESH_UNCHANGED)); EXPECT_EQ(0, GetCount(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED)); EXPECT_EQ(0, GetCount(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED)); + + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_CHANGED), + is_fcm_enabled() ? GetCountFcm(METRIC_POLICY_REFRESH_CHANGED) + : GetCountTicl(METRIC_POLICY_REFRESH_CHANGED)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS), + is_fcm_enabled() + ? GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_UNCHANGED), + is_fcm_enabled() ? GetCountFcm(METRIC_POLICY_REFRESH_UNCHANGED) + : GetCountTicl(METRIC_POLICY_REFRESH_UNCHANGED)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED), + is_fcm_enabled() + ? GetCountFcm(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED) + : GetCountTicl(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED), + is_fcm_enabled() + ? GetCountFcm(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED) + : GetCountTicl(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED)); + + EXPECT_EQ(0, is_fcm_enabled() ? GetCountTicl(METRIC_POLICY_REFRESH_CHANGED) + : GetCountFcm(METRIC_POLICY_REFRESH_CHANGED)); + EXPECT_EQ(0, + is_fcm_enabled() + ? GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(0, + is_fcm_enabled() + ? GetCountTicl(METRIC_POLICY_REFRESH_UNCHANGED) + : GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(0, + is_fcm_enabled() + ? GetCountTicl(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED) + : GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(0, is_fcm_enabled() + ? GetCountTicl(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED) + : GetCountFcm(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED)); + EXPECT_EQ(0, GetHighestHandledInvalidationVersion()); } @@ -1071,6 +1221,41 @@ EXPECT_EQ(4, GetCount(METRIC_POLICY_REFRESH_UNCHANGED)); EXPECT_EQ(2, GetCount(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED)); EXPECT_EQ(1, GetCount(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED)); + + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_CHANGED), + is_fcm_enabled() ? GetCountFcm(METRIC_POLICY_REFRESH_CHANGED) + : GetCountTicl(METRIC_POLICY_REFRESH_CHANGED)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS), + is_fcm_enabled() + ? GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_UNCHANGED), + is_fcm_enabled() ? GetCountFcm(METRIC_POLICY_REFRESH_UNCHANGED) + : GetCountTicl(METRIC_POLICY_REFRESH_UNCHANGED)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED), + is_fcm_enabled() + ? GetCountFcm(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED) + : GetCountTicl(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED)); + EXPECT_EQ(GetCount(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED), + is_fcm_enabled() + ? GetCountFcm(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED) + : GetCountTicl(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED)); + + EXPECT_EQ(0, is_fcm_enabled() ? GetCountTicl(METRIC_POLICY_REFRESH_CHANGED) + : GetCountFcm(METRIC_POLICY_REFRESH_CHANGED)); + EXPECT_EQ(0, + is_fcm_enabled() + ? GetCountTicl(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS) + : GetCountFcm(METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS)); + EXPECT_EQ(0, is_fcm_enabled() ? GetCountTicl(METRIC_POLICY_REFRESH_UNCHANGED) + : GetCountFcm(METRIC_POLICY_REFRESH_UNCHANGED)); + EXPECT_EQ(0, is_fcm_enabled() + ? GetCountTicl(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED) + : GetCountFcm(METRIC_POLICY_REFRESH_INVALIDATED_CHANGED)); + EXPECT_EQ(0, is_fcm_enabled() + ? GetCountTicl(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED) + : GetCountFcm(METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED)); + EXPECT_EQ(V(5), GetHighestHandledInvalidationVersion()); } @@ -1133,6 +1318,43 @@ EXPECT_EQ(2, GetInvalidationCount(POLICY_INVALIDATION_TYPE_NO_PAYLOAD_EXPIRED)); EXPECT_EQ(2, GetInvalidationCount(POLICY_INVALIDATION_TYPE_EXPIRED)); + + EXPECT_EQ( + GetInvalidationCount(POLICY_INVALIDATION_TYPE_NO_PAYLOAD), + is_fcm_enabled() + ? GetInvalidationCountFcm(POLICY_INVALIDATION_TYPE_NO_PAYLOAD) + : GetInvalidationCountTicl(POLICY_INVALIDATION_TYPE_NO_PAYLOAD)); + EXPECT_EQ(GetInvalidationCount(POLICY_INVALIDATION_TYPE_NORMAL), + is_fcm_enabled() + ? GetInvalidationCountFcm(POLICY_INVALIDATION_TYPE_NORMAL) + : GetInvalidationCountTicl(POLICY_INVALIDATION_TYPE_NORMAL)); + EXPECT_EQ( + GetInvalidationCount(POLICY_INVALIDATION_TYPE_NO_PAYLOAD_EXPIRED), + is_fcm_enabled() + ? GetInvalidationCountFcm(POLICY_INVALIDATION_TYPE_NO_PAYLOAD_EXPIRED) + : GetInvalidationCountTicl( + POLICY_INVALIDATION_TYPE_NO_PAYLOAD_EXPIRED)); + EXPECT_EQ(GetInvalidationCount(POLICY_INVALIDATION_TYPE_EXPIRED), + is_fcm_enabled() + ? GetInvalidationCountFcm(POLICY_INVALIDATION_TYPE_EXPIRED) + : GetInvalidationCountTicl(POLICY_INVALIDATION_TYPE_EXPIRED)); + + EXPECT_EQ(0, + is_fcm_enabled() + ? GetInvalidationCountTicl(POLICY_INVALIDATION_TYPE_NO_PAYLOAD) + : GetInvalidationCountFcm(POLICY_INVALIDATION_TYPE_NO_PAYLOAD)); + EXPECT_EQ(0, is_fcm_enabled() + ? GetInvalidationCountTicl(POLICY_INVALIDATION_TYPE_NORMAL) + : GetInvalidationCountFcm(POLICY_INVALIDATION_TYPE_NORMAL)); + EXPECT_EQ(0, is_fcm_enabled() + ? GetInvalidationCountTicl( + POLICY_INVALIDATION_TYPE_NO_PAYLOAD_EXPIRED) + : GetInvalidationCountFcm( + POLICY_INVALIDATION_TYPE_NO_PAYLOAD_EXPIRED)); + EXPECT_EQ(0, is_fcm_enabled() + ? GetInvalidationCountTicl(POLICY_INVALIDATION_TYPE_EXPIRED) + : GetInvalidationCountFcm(POLICY_INVALIDATION_TYPE_EXPIRED)); + EXPECT_EQ(0, GetHighestHandledInvalidationVersion()); }
diff --git a/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc index 5295c6d9..e2cd466 100644 --- a/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc
@@ -32,7 +32,7 @@ #include "components/policy/proto/cloud_policy.pb.h" #include "components/policy/proto/device_management_backend.pb.h" #include "components/policy/test_support/local_policy_test_server.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "extensions/common/extension.h" #include "extensions/test/extension_test_message_listener.h" #include "net/url_request/url_request_context_getter.h"
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service.cc b/chrome/browser/policy/cloud/user_policy_signin_service.cc index 15f9822..ed1b957 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service.cc
@@ -18,7 +18,7 @@ #include "components/account_id/account_id.h" #include "components/policy/core/common/cloud/cloud_policy_client_registration_helper.h" #include "components/policy/core/common/cloud/user_cloud_policy_manager.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/storage_partition.h"
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_base.cc b/chrome/browser/policy/cloud/user_policy_signin_service_base.cc index eb7b356..0d02d30 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_base.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_base.cc
@@ -18,7 +18,7 @@ #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/cloud/user_cloud_policy_manager.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/storage_partition.h" #include "services/network/public/cpp/shared_url_loader_factory.h"
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 6da4353..396d791 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -63,7 +63,7 @@ #include "components/policy/policy_constants.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/search_engines/default_search_policy_handler.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/spellcheck/spellcheck_buildflags.h" #include "components/sync/base/pref_names.h" #include "components/sync/driver/sync_policy_handler.h" @@ -533,8 +533,8 @@ #endif // !defined(OS_MACOSX) #if defined(OS_CHROMEOS) - { key::kCertificateManagementAllowed, - prefs::kCertificateManagementAllowed, + { key::kClientCertificateManagementAllowed, + prefs::kClientCertificateManagementAllowed, base::Value::Type::INTEGER }, { key::kChromeOsLockOnIdleSuspend, ash::prefs::kEnableAutoScreenLock, @@ -596,6 +596,9 @@ { key::kLargeCursorEnabled, ash::prefs::kAccessibilityLargeCursorEnabled, base::Value::Type::BOOLEAN }, + { key::kSelectToSpeakEnabled, + ash::prefs::kAccessibilitySelectToSpeakEnabled, + base::Value::Type::BOOLEAN }, { key::kSpokenFeedbackEnabled, ash::prefs::kAccessibilitySpokenFeedbackEnabled, base::Value::Type::BOOLEAN },
diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc index 2e77e2d..5a5dc0c 100644 --- a/chrome/browser/policy/policy_browsertest.cc +++ b/chrome/browser/policy/policy_browsertest.cc
@@ -154,7 +154,7 @@ #include "components/security_interstitials/content/security_interstitial_page.h" #include "components/security_interstitials/content/security_interstitial_tab_helper.h" #include "components/security_interstitials/core/controller_client.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/strings/grit/components_strings.h" #include "components/translate/core/browser/language_state.h" #include "components/translate/core/browser/translate_infobar_delegate.h" @@ -4053,6 +4053,32 @@ EXPECT_FALSE(keyboard_client->is_keyboard_enabled()); } +IN_PROC_BROWSER_TEST_F(PolicyTest, SelectToSpeakEnabled) { + // Verifies that the select to speak accessibility feature can be + // controlled through policy. + chromeos::AccessibilityManager* accessibility_manager = + chromeos::AccessibilityManager::Get(); + + // Verify that the select to speak is initially disabled + EXPECT_FALSE(accessibility_manager->IsSelectToSpeakEnabled()); + + // Manually enable the select to speak. + accessibility_manager->SetSelectToSpeakEnabled(true); + EXPECT_TRUE(accessibility_manager->IsSelectToSpeakEnabled()); + + // Verify that policy overrides the manual setting. + PolicyMap policies; + policies.Set(key::kSelectToSpeakEnabled, POLICY_LEVEL_MANDATORY, + POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, + std::make_unique<base::Value>(false), nullptr); + UpdateProviderPolicy(policies); + EXPECT_FALSE(accessibility_manager->IsSelectToSpeakEnabled()); + + // Verify that the select to speak cannot be enabled manually anymore. + accessibility_manager->SetSelectToSpeakEnabled(true); + EXPECT_FALSE(accessibility_manager->IsSelectToSpeakEnabled()); +} + IN_PROC_BROWSER_TEST_F(PolicyTest, AssistantContextEnabled) { PrefService* prefs = browser()->profile()->GetPrefs(); EXPECT_FALSE(
diff --git a/chrome/browser/prefs/chrome_pref_service_factory.cc b/chrome/browser/prefs/chrome_pref_service_factory.cc index abd18c28..26bb789 100644 --- a/chrome/browser/prefs/chrome_pref_service_factory.cc +++ b/chrome/browser/prefs/chrome_pref_service_factory.cc
@@ -49,7 +49,7 @@ #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/search_engines/default_search_manager.h" #include "components/search_engines/search_engines_pref_names.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/sync/base/model_type.h" #include "components/sync/base/pref_names.h" #include "components/sync_preferences/pref_model_associator.h"
diff --git a/chrome/browser/previews/defer_all_script_priority_browsertest.cc b/chrome/browser/previews/defer_all_script_priority_browsertest.cc new file mode 100644 index 0000000..2839401 --- /dev/null +++ b/chrome/browser/previews/defer_all_script_priority_browsertest.cc
@@ -0,0 +1,314 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <string> + +#include "base/bind.h" +#include "base/command_line.h" +#include "base/logging.h" +#include "base/macros.h" +#include "base/run_loop.h" +#include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_feature_list.h" +#include "build/build_config.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/browser_process_impl.h" +#include "chrome/browser/chrome_content_browser_client.h" +#include "chrome/browser/metrics/subprocess_metrics_provider.h" +#include "chrome/browser/previews/previews_service.h" +#include "chrome/browser/previews/previews_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" +#include "components/data_reduction_proxy/core/common/data_reduction_proxy_features.h" +#include "components/optimization_guide/hints_component_info.h" +#include "components/optimization_guide/optimization_guide_features.h" +#include "components/optimization_guide/optimization_guide_service.h" +#include "components/optimization_guide/proto/hints.pb.h" +#include "components/optimization_guide/test_hints_component_creator.h" +#include "components/previews/content/previews_hints.h" +#include "components/previews/content/previews_optimization_guide.h" +#include "components/previews/content/previews_ui_service.h" +#include "components/previews/core/previews_constants.h" +#include "components/previews/core/previews_features.h" +#include "components/previews/core/previews_switches.h" +#include "content/public/test/browser_test.h" +#include "content/public/test/browser_test_base.h" +#include "content/public/test/browser_test_utils.h" +#include "net/test/embedded_test_server/http_request.h" +#include "net/test/embedded_test_server/http_response.h" + +namespace { + +// Retries fetching |histogram_name| until it contains at least |count| samples. +void RetryForHistogramUntilCountReached(base::HistogramTester* histogram_tester, + const std::string& histogram_name, + size_t count) { + while (true) { + base::ThreadPoolInstance::Get()->FlushForTesting(); + base::RunLoop().RunUntilIdle(); + + content::FetchHistogramsFromChildProcesses(); + SubprocessMetricsProvider::MergeHistogramDeltasForTesting(); + + const std::vector<base::Bucket> buckets = + histogram_tester->GetAllSamples(histogram_name); + size_t total_count = 0; + for (const auto& bucket : buckets) { + total_count += bucket.count; + } + if (total_count >= count) { + break; + } + } +} + +} // namespace + +class DeferAllScriptPriorityBrowserTest + : public ::testing::WithParamInterface<bool>, + public InProcessBrowserTest { + public: + DeferAllScriptPriorityBrowserTest() = default; + ~DeferAllScriptPriorityBrowserTest() override = default; + + void SetUp() override { + if (IsDeferAllScriptFeatureEnabled()) { + scoped_feature_list_.InitWithFeatures( + {previews::features::kPreviews, + previews::features::kDeferAllScriptPreviews, + optimization_guide::features::kOptimizationHints, + data_reduction_proxy::features:: + kDataReductionProxyEnabledWithNetworkService}, + {}); + } else { + scoped_feature_list_.InitWithFeatures( + {previews::features::kPreviews, + optimization_guide::features::kOptimizationHints, + data_reduction_proxy::features:: + kDataReductionProxyEnabledWithNetworkService}, + {}); + } + + InProcessBrowserTest::SetUp(); + } + + bool IsDeferAllScriptFeatureEnabled() const { return GetParam(); } + + // Returns the fetch time for the JavaScript file (in milliseconds). This + // value is obtained using the resource timing API. + double GetFetchTimeForJavaScriptFileInMilliseconds() { + double script_log; + std::string script = "getFetchTimeForJavaScriptFileInMilliseconds()"; + EXPECT_TRUE(ExecuteScriptAndExtractDouble( + browser()->tab_strip_model()->GetActiveWebContents(), script, + &script_log)); + return script_log; + } + + void SetUpOnMainThread() override { + https_server_.reset( + new net::EmbeddedTestServer(net::EmbeddedTestServer::TYPE_HTTPS)); + https_server_->RegisterRequestHandler( + base::BindRepeating(&DeferAllScriptPriorityBrowserTest::RequestHandler, + base::Unretained(this))); + + ASSERT_TRUE(https_server_->Start()); + + https_url_ = https_server_->GetURL("/defer_all_script_priority_test.html"); + ASSERT_TRUE(https_url_.SchemeIs(url::kHttpsScheme)); + + InProcessBrowserTest::SetUpOnMainThread(); + } + + void SetUpCommandLine(base::CommandLine* cmd) override { + cmd->AppendSwitch("enable-spdy-proxy-auth"); + cmd->AppendSwitchASCII("--force-effective-connection-type", "Slow-2G"); + + cmd->AppendSwitch("optimization-guide-disable-installer"); + cmd->AppendSwitch("purge_hint_cache_store"); + + // Due to race conditions, it's possible that blacklist data is not loaded + // at the time of first navigation. That may prevent Preview from + // triggering, and causing the test to flake. + cmd->AppendSwitch(previews::switches::kIgnorePreviewsBlacklist); + } + + // Returns a unique script for each request, to test service worker update. + std::unique_ptr<net::test_server::HttpResponse> RequestHandler( + const net::test_server::HttpRequest& request) { + if (request.GetURL().path().find("/defer_all_script_priority_test.html") != + std::string::npos) { + return GetHtmlResponse(request); + } + + if (request.GetURL().path().find("/hung") != std::string::npos) { + return GetDelayedResponse(request); + } + return std::make_unique<net::test_server::BasicHttpResponse>(); + } + + // Returns an HTML response that fetches CSS files followed by synchronous + // external JavaScript file. The HTML file contains an inline JavaScript + // function getFetchTimeForJavaScriptFileInMilliseconds() that returns + // the fetch time for JavaScript file in milliseconds. + std::unique_ptr<net::test_server::HttpResponse> GetHtmlResponse( + const net::test_server::HttpRequest& request) { + std::unique_ptr<net::test_server::BasicHttpResponse> response = + std::make_unique<net::test_server::BasicHttpResponse>(); + response->set_content( + "<html><body>" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"hung1.css\">" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"hung2.css\">" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"hung3.css\">" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"hung4.css\">" + "<script src=\"defer_all_script_syncscript.js\"></script>" + "<script>function getFetchTimeForJavaScriptFileInMilliseconds() {" + "var p=window.performance.getEntriesByType(\"resource\");" + "for (var i=0; i < p.length; i++) {" + "if(p[i].name.includes(\"defer_all_script_syncscript.js\")) {" + "sendValueToTest(p[i].responseStart-p[i].fetchStart);" + "}" + "}" + "}" + "function sendValueToTest(value) {" + "window.domAutomationController.send(value);" + "}" + "</script></body></html>"); + return std::move(response); + } + + int css_files_hung_time_milliseconds() { return 5000; } + + std::unique_ptr<net::test_server::HttpResponse> GetDelayedResponse( + const net::test_server::HttpRequest& request) { + std::unique_ptr<net::test_server::DelayedHttpResponse> response = + std::make_unique<net::test_server::DelayedHttpResponse>( + base::TimeDelta::FromMilliseconds( + css_files_hung_time_milliseconds())); + response->set_code(net::HttpStatusCode::HTTP_OK); + return std::move(response); + } + + // Creates hint data from the |component_info| and waits for it to be fully + // processed before returning. + void ProcessHintsComponent( + const optimization_guide::HintsComponentInfo& component_info) { + // Register a QuitClosure for when the next hint update is started below. + base::RunLoop run_loop; + PreviewsServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser() + ->tab_strip_model() + ->GetActiveWebContents() + ->GetBrowserContext())) + ->previews_ui_service() + ->previews_decider_impl() + ->previews_opt_guide() + ->ListenForNextUpdateForTesting(run_loop.QuitClosure()); + + g_browser_process->optimization_guide_service()->MaybeUpdateHintsComponent( + component_info); + run_loop.Run(); + } + + // Performs a navigation to |url| and waits for the the url's host's hints to + // load before returning. This ensures that the hints will be available in the + // hint cache for a subsequent navigation to a test url with the same host. + void LoadHintsForUrl(const GURL& url) { + base::HistogramTester histogram_tester; + + // Navigate to the url to prime the OptimizationGuide hints for the + // url's host and ensure that they have been loaded from the store (via + // histogram) prior to the navigation that tests functionality. + ui_test_utils::NavigateToURL(browser(), url); + + RetryForHistogramUntilCountReached( + &histogram_tester, + previews::kPreviewsOptimizationGuideOnLoadedHintResultHistogramString, + 1); + } + + void SetDeferAllScriptHintWithPageWithPattern( + const GURL& hint_setup_url, + const std::string& page_pattern) { + ProcessHintsComponent( + test_hints_component_creator_.CreateHintsComponentInfoWithPageHints( + optimization_guide::proto::DEFER_ALL_SCRIPT, + {hint_setup_url.host()}, page_pattern, {})); + LoadHintsForUrl(hint_setup_url); + } + + virtual const GURL& https_url() const { return https_url_; } + + protected: + base::test::ScopedFeatureList scoped_feature_list_; + + private: + void TearDownOnMainThread() override { + EXPECT_TRUE(https_server_->ShutdownAndWaitUntilComplete()); + + InProcessBrowserTest::TearDownOnMainThread(); + } + + optimization_guide::testing::TestHintsComponentCreator + test_hints_component_creator_; + + std::unique_ptr<net::EmbeddedTestServer> https_server_; + GURL https_url_; + + DISALLOW_COPY_AND_ASSIGN(DeferAllScriptPriorityBrowserTest); +}; + +// Parameter is true if the test should be run with defer feature enabled. +INSTANTIATE_TEST_SUITE_P(, + DeferAllScriptPriorityBrowserTest, + ::testing::Values(false, true)); + +// Avoid flakes and issues on non-applicable platforms. +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS) +#define DISABLE_ON_WIN_MAC_CHROMESOS(x) DISABLED_##x +#else +#define DISABLE_ON_WIN_MAC_CHROMESOS(x) x +#endif + +// Fetches an HTML weboage that fetches CSS files followed by an external +// JavaScript file. Verifies that the fetching of the JavaScript files is +// delayed only when it's not render blocking. +// +// When feature kDeferAllScriptPreviews is enabled, loading priority of +// JavaScript file should be lowered. This should cause resource scheduler +// to mark the JavaScript request as delayable, and delay its fetching to after +// the fetching of CSS files finish. +// +// However, if kDeferAllScriptPreviews is not enabled, then JavaScript is render +// blocking. This should cause resource scheduler to mark the JavaScript request +// as non-delayale, thus fetching it in parallel with the CSS files. +IN_PROC_BROWSER_TEST_P( + DeferAllScriptPriorityBrowserTest, + DISABLE_ON_WIN_MAC_CHROMESOS(DeferAllScriptHttpsWhitelisted)) { + GURL url = https_url(); + + if (IsDeferAllScriptFeatureEnabled()) { + // Whitelist DeferAllScript for any path for the url's host. + SetDeferAllScriptHintWithPageWithPattern(url, "*"); + } + + ui_test_utils::NavigateToURL(browser(), url); + + double delay_milliseconds = GetFetchTimeForJavaScriptFileInMilliseconds(); + + if (IsDeferAllScriptFeatureEnabled()) { + // Fetching of JavaScript must start after fetching of the CSS files are + // finished. + EXPECT_LT(css_files_hung_time_milliseconds(), delay_milliseconds); + } else { + // Fetching of JavaScript should start in parallel with fetching of the + // other files. So, it should finish fast enough. Note that even without any + // queuing delays in resource scheduler, it's possible that this fetching + // takes more css_files_hung_time_milliseconds(). This can potentially make + // this test a bit flaky. + EXPECT_GT(css_files_hung_time_milliseconds(), delay_milliseconds); + } +}
diff --git a/chrome/browser/printing/print_dialog_cloud.cc b/chrome/browser/printing/print_dialog_cloud.cc index e224495..d2da80ee 100644 --- a/chrome/browser/printing/print_dialog_cloud.cc +++ b/chrome/browser/printing/print_dialog_cloud.cc
@@ -14,9 +14,9 @@ #include "chrome/browser/ui/browser_window.h" #include "components/cloud_devices/common/cloud_devices_urls.h" #include "components/google/core/common/google_util.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_metrics.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h"
diff --git a/chrome/browser/profiles/avatar_menu.cc b/chrome/browser/profiles/avatar_menu.cc index 2c73243..fa2b7abd 100644 --- a/chrome/browser/profiles/avatar_menu.cc +++ b/chrome/browser/profiles/avatar_menu.cc
@@ -25,7 +25,7 @@ #include "chrome/common/buildflags.h" #include "chrome/common/chrome_switches.h" #include "chrome/grit/generated_resources.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "ui/base/l10n/l10n_util.h"
diff --git a/chrome/browser/profiles/gaia_info_update_service.cc b/chrome/browser/profiles/gaia_info_update_service.cc index 080d93c2..e5c35a64 100644 --- a/chrome/browser/profiles/gaia_info_update_service.cc +++ b/chrome/browser/profiles/gaia_info_update_service.cc
@@ -19,9 +19,9 @@ #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/identity_manager/account_info.h" #include "content/public/browser/notification_details.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/image/image.h"
diff --git a/chrome/browser/profiles/gaia_info_update_service_unittest.cc b/chrome/browser/profiles/gaia_info_update_service_unittest.cc index 257e99a..eb81891 100644 --- a/chrome/browser/profiles/gaia_info_update_service_unittest.cc +++ b/chrome/browser/profiles/gaia_info_update_service_unittest.cc
@@ -26,8 +26,8 @@ #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/sync_preferences/pref_service_syncable.h" #include "testing/gmock/include/gmock/gmock.h" #include "ui/gfx/image/image.h"
diff --git a/chrome/browser/profiles/host_zoom_map_browsertest.cc b/chrome/browser/profiles/host_zoom_map_browsertest.cc index 74995f4a7..2cb3cd7 100644 --- a/chrome/browser/profiles/host_zoom_map_browsertest.cc +++ b/chrome/browser/profiles/host_zoom_map_browsertest.cc
@@ -33,8 +33,8 @@ #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/ui_test_utils.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_switches.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_switches.h" #include "components/zoom/page_zoom.h" #include "components/zoom/zoom_event_manager.h" #include "content/public/browser/host_zoom_map.h"
diff --git a/chrome/browser/profiles/profile_downloader.cc b/chrome/browser/profiles/profile_downloader.cc index 4100536..7030449 100644 --- a/chrome/browser/profiles/profile_downloader.cc +++ b/chrome/browser/profiles/profile_downloader.cc
@@ -22,10 +22,10 @@ #include "chrome/browser/profiles/profile_downloader_delegate.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/identity_manager_factory.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/avatar_icon_util.h" +#include "components/signin/public/base/avatar_icon_util.h" #include "components/signin/public/identity_manager/access_token_fetcher.h" #include "components/signin/public/identity_manager/access_token_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "google_apis/gaia/gaia_constants.h"
diff --git a/chrome/browser/profiles/profile_downloader.h b/chrome/browser/profiles/profile_downloader.h index 1345cd6..60d22b4 100644 --- a/chrome/browser/profiles/profile_downloader.h +++ b/chrome/browser/profiles/profile_downloader.h
@@ -13,7 +13,7 @@ #include "base/scoped_observer.h" #include "base/strings/string16.h" #include "chrome/browser/image_decoder.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/mojom/url_loader_factory.mojom.h"
diff --git a/chrome/browser/profiles/profile_downloader_unittest.cc b/chrome/browser/profiles/profile_downloader_unittest.cc index 218b4e4..6684cf1 100644 --- a/chrome/browser/profiles/profile_downloader_unittest.cc +++ b/chrome/browser/profiles/profile_downloader_unittest.cc
@@ -11,8 +11,8 @@ #include "chrome/browser/signin/identity_test_environment_profile_adaptor.h" #include "chrome/browser/signin/test_signin_client_builder.h" #include "chrome/test/base/testing_profile.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/test_signin_client.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/test/test_browser_thread_bundle.h" #include "net/url_request/test_url_fetcher_factory.h"
diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc index 395887c..63651d2 100644 --- a/chrome/browser/profiles/profile_impl.cc +++ b/chrome/browser/profiles/profile_impl.cc
@@ -46,6 +46,8 @@ #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_factory.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/client_hints/client_hints_factory.h" +#include "chrome/browser/content_index/content_index_provider_factory.h" +#include "chrome/browser/content_index/content_index_provider_impl.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/dom_distiller/profile_utils.h" @@ -127,7 +129,7 @@ #include "components/policy/core/common/cloud/user_cloud_policy_manager.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/sync_preferences/pref_service_syncable.h" #include "components/url_formatter/url_fixer.h" @@ -1222,6 +1224,10 @@ return BackgroundSyncControllerFactory::GetForProfile(this); } +content::ContentIndexProvider* ProfileImpl::GetContentIndexProvider() { + return ContentIndexProviderFactory::GetForProfile(this); +} + net::URLRequestContextGetter* ProfileImpl::CreateRequestContext( content::ProtocolHandlerMap* protocol_handlers, content::URLRequestInterceptorScopedVector request_interceptors) {
diff --git a/chrome/browser/profiles/profile_impl.h b/chrome/browser/profiles/profile_impl.h index 01f29579..1bcebd6 100644 --- a/chrome/browser/profiles/profile_impl.h +++ b/chrome/browser/profiles/profile_impl.h
@@ -110,6 +110,7 @@ content::SmsService* GetSmsService() override; content::NativeFileSystemPermissionContext* GetNativeFileSystemPermissionContext() override; + content::ContentIndexProvider* GetContentIndexProvider() override; // Profile implementation: scoped_refptr<base::SequencedTaskRunner> GetIOTaskRunner() override;
diff --git a/chrome/browser/profiles/profile_info_cache.cc b/chrome/browser/profiles/profile_info_cache.cc index 7d811e6..c17f39f0 100644 --- a/chrome/browser/profiles/profile_info_cache.cc +++ b/chrome/browser/profiles/profile_info_cache.cc
@@ -29,7 +29,7 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image.h"
diff --git a/chrome/browser/profiles/profile_info_cache_unittest.cc b/chrome/browser/profiles/profile_info_cache_unittest.cc index 47b7ca0..9ed49be 100644 --- a/chrome/browser/profiles/profile_info_cache_unittest.cc +++ b/chrome/browser/profiles/profile_info_cache_unittest.cc
@@ -27,7 +27,7 @@ #include "chrome/test/base/testing_browser_process.h" #include "components/account_id/account_id.h" #include "components/prefs/testing_pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/sync_preferences/pref_service_syncable.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h"
diff --git a/chrome/browser/profiles/profile_io_data.cc b/chrome/browser/profiles/profile_io_data.cc index d7081bdb..02e0b00 100644 --- a/chrome/browser/profiles/profile_io_data.cc +++ b/chrome/browser/profiles/profile_io_data.cc
@@ -55,8 +55,8 @@ #include "components/net_log/chrome_net_log.h" #include "components/policy/core/common/cloud/user_cloud_policy_manager.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/sync/base/pref_names.h" #include "components/url_formatter/url_fixer.h" #include "content/public/browser/browser_task_traits.h"
diff --git a/chrome/browser/profiles/profile_io_data.h b/chrome/browser/profiles/profile_io_data.h index beb8ec5..8672dc1 100644 --- a/chrome/browser/profiles/profile_io_data.h +++ b/chrome/browser/profiles/profile_io_data.h
@@ -25,7 +25,7 @@ #include "chrome/common/buildflags.h" #include "components/content_settings/core/common/content_settings_types.h" #include "components/prefs/pref_member.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/resource_context.h" #include "extensions/buildflags/buildflags.h"
diff --git a/chrome/browser/profiles/profile_list_desktop.cc b/chrome/browser/profiles/profile_list_desktop.cc index 6e7de24..e74462e3 100644 --- a/chrome/browser/profiles/profile_list_desktop.cc +++ b/chrome/browser/profiles/profile_list_desktop.cc
@@ -11,7 +11,7 @@ #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/grit/generated_resources.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "ui/base/l10n/l10n_util.h" ProfileListDesktop::ProfileListDesktop(
diff --git a/chrome/browser/profiles/profile_list_desktop_browsertest.cc b/chrome/browser/profiles/profile_list_desktop_browsertest.cc index dbee673..f692bd47 100644 --- a/chrome/browser/profiles/profile_list_desktop_browsertest.cc +++ b/chrome/browser/profiles/profile_list_desktop_browsertest.cc
@@ -22,6 +22,7 @@ #include "chrome/common/chrome_paths.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_browser_process.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" @@ -84,9 +85,6 @@ BrowserList* browser_list = BrowserList::GetInstance(); EXPECT_EQ(1u, browser_list->size()); - content::WindowedNotificationObserver window_close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::Source<Browser>(browser())); content::WindowedNotificationObserver system_profile_created_observer( chrome::NOTIFICATION_PROFILE_CREATED, @@ -94,7 +92,8 @@ EXPECT_FALSE(entry->IsSigninRequired()); profiles::LockProfile(current_profile); - window_close_observer.Wait(); // rely on test time-out for failure indication + // Rely on test time-out for failure indication. + ui_test_utils::WaitForBrowserToClose(browser()); EXPECT_TRUE(entry->IsSigninRequired()); EXPECT_EQ(0u, browser_list->size());
diff --git a/chrome/browser/profiles/profile_list_desktop_unittest.cc b/chrome/browser/profiles/profile_list_desktop_unittest.cc index 81a4ce2..2de80a40b 100644 --- a/chrome/browser/profiles/profile_list_desktop_unittest.cc +++ b/chrome/browser/profiles/profile_list_desktop_unittest.cc
@@ -23,7 +23,7 @@ #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" #include "components/account_id/account_id.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/sync_preferences/pref_service_syncable.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/profiles/profile_manager.cc b/chrome/browser/profiles/profile_manager.cc index 2a9e9af..a0b96dfe 100644 --- a/chrome/browser/profiles/profile_manager.cc +++ b/chrome/browser/profiles/profile_manager.cc
@@ -78,8 +78,8 @@ #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/search_engines/default_search_manager.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #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"
diff --git a/chrome/browser/profiles/profile_manager_unittest.cc b/chrome/browser/profiles/profile_manager_unittest.cc index 44f2b97..4d1dc025 100644 --- a/chrome/browser/profiles/profile_manager_unittest.cc +++ b/chrome/browser/profiles/profile_manager_unittest.cc
@@ -41,7 +41,7 @@ #include "chrome/test/base/testing_profile.h" #include "components/account_id/account_id.h" #include "components/history/core/browser/history_service.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/browser/notification_service.h" #include "content/public/common/content_switches.h" #include "content/public/test/test_browser_thread_bundle.h"
diff --git a/chrome/browser/profiles/profile_window.cc b/chrome/browser/profiles/profile_window.cc index 570e259..1a5eda6 100644 --- a/chrome/browser/profiles/profile_window.cc +++ b/chrome/browser/profiles/profile_window.cc
@@ -39,9 +39,8 @@ #include "chrome/common/url_constants.h" #include "components/flags_ui/pref_service_flags_storage.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/account_reconcilor.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browser_thread.h" #include "extensions/buildflags/buildflags.h"
diff --git a/chrome/browser/profiles/profile_window_browsertest.cc b/chrome/browser/profiles/profile_window_browsertest.cc index e25f5e0fe..87d5ab9 100644 --- a/chrome/browser/profiles/profile_window_browsertest.cc +++ b/chrome/browser/profiles/profile_window_browsertest.cc
@@ -16,7 +16,6 @@ #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" @@ -35,8 +34,7 @@ #include "components/history/core/browser/history_db_task.h" #include "components/history/core/browser/history_service.h" #include "components/search_engines/template_url_service.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "content/public/browser/notification_service.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" @@ -130,12 +128,9 @@ // Create a guest browser nicely. Using CreateProfile() and CreateBrowser() // does incomplete initialization that would lead to // SystemUrlRequestContextGetter being leaked. - content::WindowedNotificationObserver browser_creation_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); profiles::SwitchToGuestProfile(ProfileManager::CreateCallback()); + ui_test_utils::WaitForBrowserToOpen(); - browser_creation_observer.Wait(); DCHECK_NE(static_cast<Profile*>(nullptr), g_browser_process->profile_manager()->GetProfileByPath( ProfileManager::GetGuestProfilePath()));
diff --git a/chrome/browser/profiles/profiles_state.cc b/chrome/browser/profiles/profiles_state.cc index 3540193..1d5c8209 100644 --- a/chrome/browser/profiles/profiles_state.cc +++ b/chrome/browser/profiles/profiles_state.cc
@@ -21,7 +21,7 @@ #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browsing_data_remover.h" #include "content/public/browser/resource_dispatcher_host.h" @@ -38,7 +38,7 @@ #include "chrome/browser/profiles/gaia_info_update_service.h" #include "chrome/browser/profiles/gaia_info_update_service_factory.h" #include "chrome/browser/signin/signin_error_controller_factory.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #endif namespace profiles {
diff --git a/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc b/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc index 603ca9d9..324856b8 100644 --- a/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc +++ b/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc
@@ -11,7 +11,6 @@ #include "base/run_loop.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/search/search.h" @@ -25,6 +24,7 @@ #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/child_process_launcher_utils.h" #include "content/public/browser/notification_service.h" +#include "content/public/browser/notification_types.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" @@ -575,13 +575,10 @@ class WindowDestroyer : public content::WebContentsObserver { public: WindowDestroyer(content::WebContents* web_contents, TabStripModel* model) - : content::WebContentsObserver(web_contents), - tab_strip_model_(model), - browser_closed_observer_(chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()) {} + : content::WebContentsObserver(web_contents), tab_strip_model_(model) {} // Wait for the browser window to be destroyed. - void Wait() { browser_closed_observer_.Wait(); } + void Wait() { ui_test_utils::WaitForBrowserToClose(); } void RenderProcessGone(base::TerminationStatus status) override { tab_strip_model_->CloseAllTabs(); @@ -589,7 +586,6 @@ private: TabStripModel* tab_strip_model_; - content::WindowedNotificationObserver browser_closed_observer_; DISALLOW_COPY_AND_ASSIGN(WindowDestroyer); };
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_data_store_factory_browsertest.cc b/chrome/browser/resource_coordinator/local_site_characteristics_data_store_factory_browsertest.cc index 0924aae..180f6795 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_data_store_factory_browsertest.cc +++ b/chrome/browser/resource_coordinator/local_site_characteristics_data_store_factory_browsertest.cc
@@ -11,6 +11,7 @@ #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/resource_coordinator/tab_manager_features.h" #include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" @@ -77,11 +78,8 @@ EXPECT_TRUE(DataStoreRespectsOffTheRecordValue(incognito_profile, incognito_data_store)); - content::WindowedNotificationObserver browser_creation_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); profiles::SwitchToGuestProfile(ProfileManager::CreateCallback()); - browser_creation_observer.Wait(); + ui_test_utils::WaitForBrowserToOpen(); ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* guest_profile =
diff --git a/chrome/browser/resource_coordinator/tab_manager_browsertest.cc b/chrome/browser/resource_coordinator/tab_manager_browsertest.cc index 1966e1b..e779271b 100644 --- a/chrome/browser/resource_coordinator/tab_manager_browsertest.cc +++ b/chrome/browser/resource_coordinator/tab_manager_browsertest.cc
@@ -1200,11 +1200,8 @@ // - (optional) Freeze happens in renderer: PENDING_FREEZE->FROZEN // - Renderer is notified of new visibility: PENDING_FREEZE->ACTIVE or // FROZEN->ACTIVE. -// -// DISABLED: consistent timeout crbug.com/978021 -IN_PROC_BROWSER_TEST_F( - TabManagerTestWithTwoTabs, - DISABLED_TabProactiveDiscardAndFocusBeforeFreezeCompletes) { +IN_PROC_BROWSER_TEST_F(TabManagerTestWithTwoTabs, + TabProactiveDiscardAndFocusBeforeFreezeCompletes) { // Proactively discard the background tab. EXPECT_EQ(LifecycleUnitState::ACTIVE, GetLifecycleUnitAt(1)->GetState()); EXPECT_TRUE(
diff --git a/chrome/browser/resources/app_management/BUILD.gn b/chrome/browser/resources/app_management/BUILD.gn index ec62355..d52e422 100644 --- a/chrome/browser/resources/app_management/BUILD.gn +++ b/chrome/browser/resources/app_management/BUILD.gn
@@ -25,12 +25,14 @@ ":permission_item", ":permission_toggle", ":permission_view_header", + ":pin_to_shelf_item", ":pwa_permission_view", ":reducers", ":router", ":search_view", ":store", ":store_client", + ":toggle_row", ":types", ":util", ] @@ -88,6 +90,7 @@ ":metadata_view", ":permission_item", ":permission_view_header", + ":pin_to_shelf_item", ":store_client", ] } @@ -105,6 +108,7 @@ ":fake_page_handler", ":metadata_view", ":permission_view_header", + ":pin_to_shelf_item", ":store_client", ] } @@ -186,6 +190,14 @@ ] } + js_library("pin_to_shelf_item") { + deps = [ + ":browser_proxy", + ":toggle_row", + ":types", + ] + } + js_library("pwa_permission_view") { deps = [ ":constants", @@ -193,6 +205,7 @@ ":metadata_view", ":permission_item", ":permission_view_header", + ":pin_to_shelf_item", ":store_client", ] } @@ -240,6 +253,12 @@ ] } + js_library("toggle_row") { + deps = [ + ":types", + ] + } + js_library("types") { deps = [ "//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile",
diff --git a/chrome/browser/resources/app_management/arc_permission_view.html b/chrome/browser/resources/app_management/arc_permission_view.html index a760a4ea..9b9eaa5 100644 --- a/chrome/browser/resources/app_management/arc_permission_view.html +++ b/chrome/browser/resources/app_management/arc_permission_view.html
@@ -7,6 +7,7 @@ <link rel="import" href="permission_view_header.html"> <link rel="import" href="shared_style.html"> <link rel="import" href="store_client.html"> +<link rel="import" href="pin_to_shelf_item.html"> <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> @@ -19,6 +20,11 @@ </app-management-permission-view-header> <div class="permission-list card-container"> + <app-management-pin-to-shelf-item + id="pin-to-shelf-setting" + class="permission-card-row separated-row header-text" + app_="[[app_]]"> + </app-management-pin-to-shelf-item> <app-management-permission-item id="notifications-card" class="permission-card-row separated-row header-text" permission-label="$i18n{notifications}" permission-type="NOTIFICATIONS"> @@ -61,7 +67,6 @@ </div> </div> </div> - <app-management-metadata-view></app-management-metadata-view> </template> <script src="arc_permission_view.js"></script> </dom-module>
diff --git a/chrome/browser/resources/app_management/chrome_app_permission_view.html b/chrome/browser/resources/app_management/chrome_app_permission_view.html index 322bf4beb..64b890ff 100644 --- a/chrome/browser/resources/app_management/chrome_app_permission_view.html +++ b/chrome/browser/resources/app_management/chrome_app_permission_view.html
@@ -3,6 +3,7 @@ <link rel="import" href="shared_style.html"> <link rel="import" href="store_client.html"> <link rel="import" href="util.html"> +<link rel="import" href="pin_to_shelf_item.html"> <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <dom-module id="app-management-chrome-app-permission-view"> @@ -22,6 +23,11 @@ #no-permissions { padding-inline-start: 24px; } + + #pin-to-shelf-setting { + border-top: var(--card-separator); + } + </style> <app-management-permission-view-header> </app-management-permission-view-header> @@ -29,30 +35,37 @@ <div id="app-description" class="permission-card-row secondary-text"> [[app_.description]] </div> - <div id="permissions-card" class="permission-card-row"> - <div class="subpermission-list"> - <div class="subpermission-row separated-row"> - <div class="header-text">$i18n{thisAppCan}</div> - </div> - <template is="dom-if" if="[[!hasPermissions_(messages_)]]"> - <div id="no-permissions"> - $i18n{appNoPermission} + <div class="permission-list"> + <app-management-pin-to-shelf-item + id="pin-to-shelf-setting" + class="permission-card-row separated-row header-text" + app_="[[app_]]"> + </app-management-pin-to-shelf-item> + + <div id="permissions-card" class="permission-card-row"> + <div class="subpermission-list"> + <div class="subpermission-row separated-row"> + <div class="header-text">$i18n{thisAppCan}</div> </div> - </template> - <ul> - <template is="dom-repeat" - items="[[getPermissionMessages_(messages_)]]" as="message"> - <li>[[message]]</li> - <ul> - <template is="dom-repeat" - items="[[getPermissionSubmessagesByMessage_(index, messages_)]]" - as="submessage"> - <li>[[submessage]]</li> - </template> - </ul> + <template is="dom-if" if="[[!hasPermissions_(messages_)]]"> + <div id="no-permissions"> + $i18n{appNoPermission} + </div> </template> - </ul> - <!-- TODO(crbug.com/906508): For apps which are hosted apps but not + <ul> + <template is="dom-repeat" + items="[[getPermissionMessages_(messages_)]]" as="message"> + <li>[[message]]</li> + <ul> + <template is="dom-repeat" + items="[[getPermissionSubmessagesByMessage_(index, messages_)]]" + as="submessage"> + <li>[[submessage]]</li> + </template> + </ul> + </template> + </ul> + <!-- TODO(crbug.com/906508): For apps which are hosted apps but not bookmark apps, this button will actually open the site settings page corresponding to the app, since hosted apps are not listed in chrome://extensions. @@ -74,7 +87,6 @@ </div> </div> </div> - <app-management-metadata-view></app-management-metadata-view> </template> <script src="chrome_app_permission_view.js"></script> </dom-module>
diff --git a/chrome/browser/resources/app_management/fake_page_handler.js b/chrome/browser/resources/app_management/fake_page_handler.js index bdf351fa..db77640 100644 --- a/chrome/browser/resources/app_management/fake_page_handler.js +++ b/chrome/browser/resources/app_management/fake_page_handler.js
@@ -96,6 +96,7 @@ installSource: apps.mojom.InstallSource.kUser, permissions: {}, hideMoreSettings: false, + hidePinToShelf: false, }; if (optConfig) {
diff --git a/chrome/browser/resources/app_management/permission_item.js b/chrome/browser/resources/app_management/permission_item.js index 760aaf7..cf610ef 100644 --- a/chrome/browser/resources/app_management/permission_item.js +++ b/chrome/browser/resources/app_management/permission_item.js
@@ -71,6 +71,7 @@ }, /** + * @param {MouseEvent} e * @private */ onClick_: function(e) {
diff --git a/chrome/browser/resources/app_management/permission_toggle.html b/chrome/browser/resources/app_management/permission_toggle.html index 15d2a807..7086ec6 100644 --- a/chrome/browser/resources/app_management/permission_toggle.html +++ b/chrome/browser/resources/app_management/permission_toggle.html
@@ -3,6 +3,8 @@ <link rel="import" href="chrome://resources/cr_elements/policy/cr_tooltip_icon.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> +<!-- TODO(jshikaram): use toggle-row here. --> + <dom-module id="app-management-permission-toggle"> <template> <style>
diff --git a/chrome/browser/resources/app_management/pin_to_shelf_item.html b/chrome/browser/resources/app_management/pin_to_shelf_item.html new file mode 100644 index 0000000..fe4821f --- /dev/null +++ b/chrome/browser/resources/app_management/pin_to_shelf_item.html
@@ -0,0 +1,19 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> +<link rel="import" href="toggle_row.html"> + +<dom-module id="app-management-pin-to-shelf-item"> + <template> + <style> + :host(:not([disabled])) { + cursor: pointer; + } + </style> + <app-management-toggle-row + label_="$i18n{pinToShelf}" + managed_$="[[isManaged_(app_)]]" + policy-label_="$i18n{pinControlledByPolicy}" + value_$="[[getValue_(app_)]]"> + </app-management-toggle-row> + </template> + <script src="pin_to_shelf_item.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/app_management/pin_to_shelf_item.js b/chrome/browser/resources/app_management/pin_to_shelf_item.js new file mode 100644 index 0000000..ee5d2ac --- /dev/null +++ b/chrome/browser/resources/app_management/pin_to_shelf_item.js
@@ -0,0 +1,95 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +Polymer({ + is: 'app-management-pin-to-shelf-item', + + properties: { + /** + * @type {App} + * @private + */ + app_: Object, + + /** + * @type {boolean} + * @private + */ + hidden: { + type: Boolean, + computed: 'isAvailable_(app_)', + reflectToAttribute: true, + }, + + /** + * @type {boolean} + * @private + */ + disabled: { + type: Boolean, + computed: 'isManaged_(app_)', + reflectToAttribute: true, + }, + }, + + ready: function() { + // capture the onClick event before it reaches the toggle. + this.addEventListener('click', this.onClick_, true); + }, + + /** + * @param {App} app + * @returns {boolean} true if the app is pinned + * @private + */ + getValue_: function(app) { + if (app === undefined) { + return false; + } + assert(app); + return app.isPinned === OptionalBool.kTrue; + }, + + /** + * @param {App} app + * @returns {boolean} true if pinning is available. + */ + isAvailable_: function(app) { + if (app === undefined) { + return false; + } + assert(app); + return app.hidePinToShelf; + }, + + /** + * @param {App} app + * @returns {boolean} true if the pinning is managed by policy. + * @private + */ + isManaged_: function(app) { + if (app === undefined) { + return false; + } + assert(app); + return app.isPolicyPinned === OptionalBool.kTrue; + }, + + /** + * @param {Event} event + * @private + */ + onClick_: function(event) { + event.stopPropagation(); + + // Disabled + if (this.isManaged_(this.app_)) { + return; + } + + app_management.BrowserProxy.getInstance().handler.setPinned( + this.app_.id, + assert(app_management.util.toggleOptionalBool(this.app_.isPinned)), + ); + }, +});
diff --git a/chrome/browser/resources/app_management/pwa_permission_view.html b/chrome/browser/resources/app_management/pwa_permission_view.html index adbdc55..17952e85 100644 --- a/chrome/browser/resources/app_management/pwa_permission_view.html +++ b/chrome/browser/resources/app_management/pwa_permission_view.html
@@ -6,6 +6,7 @@ <link rel="import" href="permission_view_header.html"> <link rel="import" href="shared_style.html"> <link rel="import" href="store_client.html"> +<link rel="import" href="pin_to_shelf_item.html"> <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> @@ -18,6 +19,11 @@ </app-management-permission-view-header> <div class="permission-list card-container"> + <app-management-pin-to-shelf-item + id="pin-to-shelf-setting" + class="permission-card-row separated-row header-text" + app_="[[app_]]"> + </app-management-pin-to-shelf-item> <app-management-permission-item id="notifications-card" class="permission-card-row separated-row header-text" permission-label="$i18n{notifications}" @@ -54,7 +60,6 @@ </div> </div> </div> - <app-management-metadata-view></app-management-metadata-view> </template> <script src="pwa_permission_view.js"></script> </dom-module>
diff --git a/chrome/browser/resources/app_management/shared_style.html b/chrome/browser/resources/app_management/shared_style.html index 2750489..57215df 100644 --- a/chrome/browser/resources/app_management/shared_style.html +++ b/chrome/browser/resources/app_management/shared_style.html
@@ -23,6 +23,11 @@ justify-content: space-between; } + .card-row { + border-top: var(--card-separator); + padding: 0 24px; + } + .permission-card-row { border-top: var(--card-separator); padding: 0 24px; @@ -82,6 +87,11 @@ width: 36px; } + .horizontal-align { + align-items: center; + display: flex; + } + .expander-list-row { align-items: center; border-top: var(--card-separator);
diff --git a/chrome/browser/resources/app_management/shared_vars.html b/chrome/browser/resources/app_management/shared_vars.html index 667ce2c..d42cace 100644 --- a/chrome/browser/resources/app_management/shared_vars.html +++ b/chrome/browser/resources/app_management/shared_vars.html
@@ -19,6 +19,7 @@ --permission-icon-padding: 12px; --permission-list-item-height: 64px; --primary-text-color: rgba(0, 0, 0, 0.87); + --row-item-icon-padding: 12px; --secondary-font-weight: 400; --secondary-text-color: rgba(0, 0, 0, 0.54); }
diff --git a/chrome/browser/resources/app_management/toggle_row.html b/chrome/browser/resources/app_management/toggle_row.html new file mode 100644 index 0000000..8e2ccf12 --- /dev/null +++ b/chrome/browser/resources/app_management/toggle_row.html
@@ -0,0 +1,55 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="browser_proxy.html"> +<link rel="import" href="shared_style.html"> +<link rel="import" href="store_client.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> + +<dom-module id="app-management-toggle-row"> + <template> + <style include="app-management-shared-css"> + :host { + align-items: center; + display: flex; + flex: 1; + justify-content: space-between; + } + + #icon { + padding-inline-end: var(--row-item-icon-padding); + } + + #policy-indicator { + fill: var(--google-grey-refresh-700); + padding-inline-end: 12px; + } + </style> + + <div id="left-content" class="horizontal-align"> + <template is="dom-if" if="[[icon_]]"> + <iron-icon id="icon" icon="[[icon_]]"></iron-icon> + </template> + <div id="label">[[label_]]</div> + </div> + <div id="right-content" class="horizontal-align"> + <iron-icon id="policy-indicator" + icon="cr:domain" + tabindex="0" + aria-describedby="tooltip" + hidden$="[[!managed_]]"> + </iron-icon> + <paper-tooltip id="tooltip" + for="policy-indicator" + position="top" + fit-to-visible-bounds> + [[policyLabel_]] + </paper-tooltip> + <cr-toggle id="toggle" + checked="[[value_]]" + disabled$="[[managed_]]"> + </cr-toggle> + </div> + </template> + <script src="toggle_row.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/app_management/toggle_row.js b/chrome/browser/resources/app_management/toggle_row.js new file mode 100644 index 0000000..16aff0b --- /dev/null +++ b/chrome/browser/resources/app_management/toggle_row.js
@@ -0,0 +1,34 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +Polymer({ + is: 'app-management-toggle-row', + + properties: { + /** + * @type {string} + * @private + */ + icon_: String, + /** + * @type {string} + * @private + */ + label_: String, + /** + * @type {boolean} + * @private + */ + managed_: {type: Boolean, value: false, reflectToAttribute: true}, + /** + * @type {string} + * @private + */ + policyLabel_: String, + /** + * @type {boolean} + * @private + */ + value_: {type: Boolean, value: false, reflectToAttribute: true}, + }, +});
diff --git a/chrome/browser/resources/app_management/util.js b/chrome/browser/resources/app_management/util.js index 57402cb..b89a765 100644 --- a/chrome/browser/resources/app_management/util.js +++ b/chrome/browser/resources/app_management/util.js
@@ -220,6 +220,23 @@ return a.localeCompare(b); } + /** + * Toggles an OptionalBool + * + * @param {OptionalBool} bool + * @return {OptionalBool} + */ + function toggleOptionalBool(bool) { + switch (bool) { + case OptionalBool.kFalse: + return OptionalBool.kTrue; + case OptionalBool.kTrue: + return OptionalBool.kFalse; + default: + assertNotReached(); + } + } + return { addIfNeeded: addIfNeeded, alphabeticalSort: alphabeticalSort, @@ -234,5 +251,6 @@ notificationsPermissionType: notificationsPermissionType, permissionTypeHandle: permissionTypeHandle, removeIfNeeded: removeIfNeeded, + toggleOptionalBool: toggleOptionalBool, }; });
diff --git a/chrome/browser/resources/chromeos/camera/src/js/mojo/imagecapture.js b/chrome/browser/resources/chromeos/camera/src/js/mojo/imagecapture.js index 03a23395..13da126 100644 --- a/chrome/browser/resources/chromeos/camera/src/js/mojo/imagecapture.js +++ b/chrome/browser/resources/chromeos/camera/src/js/mojo/imagecapture.js
@@ -342,12 +342,21 @@ streamHeight = constraints.video.height; } + let hasSpecifiedFrameRateRange = minFrameRate > 0 && maxFrameRate > 0; + // If the frame rate range is specified in |constraints|, we should try to set + // the frame rate range and should report error if fails since it is + // unexpected. + // + // Otherwise, if the frame rate is incomplete or totally missing in + // |constraints| , we assume the app wants to use default frame rate range. + // We set the frame rate range to an invalid range (e.g. 0 fps) so that it + // will fallback to use the default one. try { return cca.mojo.MojoInterface.getProxy() .setFpsRange( deviceId, streamWidth, streamHeight, minFrameRate, maxFrameRate) .then(({isSuccess}) => { - if (!isSuccess) { + if (!isSuccess && hasSpecifiedFrameRateRange) { console.error('Failed to negotiate the frame rate range.'); } return navigator.mediaDevices.getUserMedia(constraints);
diff --git a/chrome/browser/resources/hats/hats.html b/chrome/browser/resources/hats/hats.html index b2a34217..08793f1 100644 --- a/chrome/browser/resources/hats/hats.html +++ b/chrome/browser/resources/hats/hats.html
@@ -36,8 +36,21 @@ /* Display the done button at the end of the survey. */ document.getElementById('id-done-button').hidden = false; + + /* Auto dismiss after two seconds. */ + setTimeout(function(){ window.close(); }, 2000); }; + /** + * Called after the survey HTML is injected into the page. + */ + function onSurveyShown() { + /* Don't show logo on the survey */ + const elements = document.getElementsByClassName('t402-prompt-logo'); + for (const element of elements) + element.style.display = 'none'; + } + document.addEventListener('DOMContentLoaded', function() { document.getElementById('id-link-done-button').onclick = function() { window.close();
diff --git a/chrome/browser/resources/history/history_toolbar.html b/chrome/browser/resources/history/history_toolbar.html index cd86b39..9357ef7 100644 --- a/chrome/browser/resources/history/history_toolbar.html +++ b/chrome/browser/resources/history/history_toolbar.html
@@ -12,6 +12,7 @@ <style include="shared-style"> :host { display: flex; + overflow: hidden; position: relative; }
diff --git a/chrome/browser/resources/local_ntp/customize.js b/chrome/browser/resources/local_ntp/customize.js index 92ad17b6..831ce83 100644 --- a/chrome/browser/resources/local_ntp/customize.js +++ b/chrome/browser/resources/local_ntp/customize.js
@@ -94,6 +94,7 @@ COLORS_DEFAULT: 'colors-default', COLORS_THEME: 'colors-theme', COLORS_THEME_NAME: 'colors-theme-name', + COLORS_THEME_UNINSTALL: 'colors-theme-uninstall', COLORS_THEME_WEBSTORE_LINK: 'colors-theme-link', COLORS_MENU: 'colors-menu', CUSTOMIZATION_MENU: 'customization-menu', @@ -247,6 +248,7 @@ */ customize.selectedOptions = { background: null, // Contains the background image tile. + backgroundId: '', // The id of the selected background image tile. // Contains the selected shortcut type's DOM element, i.e. either custom links // or most visited. shortcutType: null, @@ -269,7 +271,7 @@ * Whether tiles for Colors menu already loaded. * @type {boolean} */ -customize.colorMenuLoaded = false; +customize.colorsMenuLoaded = false; /** * The original NTP background. Used to restore from image previews. @@ -294,6 +296,20 @@ }; /** + * Called when user changes the theme. + */ +customize.onThemeChange = function() { + // Hide the settings menu or individual options if the related features are + // disabled. + customize.setMenuVisibility(); + + // If theme changed after Colors menu was loaded, then reload theme info. + if (customize.colorsMenuLoaded) { + customize.updateWebstoreThemeInfo(); + } +}; + +/** * Display custom background image attributions on the page. * @param {string} attributionLine1 First line of attribution. * @param {string} attributionLine2 Second line of attribution. @@ -443,9 +459,6 @@ customize.IDS.BACKGROUNDS_MENU; customize.richerPicker_openBackgroundSubmenu.title = ''; backgroundMenu.scrollTop = 0; - - customize.richerPicker_deselectBackgroundTile( - customize.selectedOptions.background); }; /** @@ -606,7 +619,7 @@ if (configData.richerPicker) { return customize.richerPicker_getNextTile(deltaX, deltaY, currentElem); } - const current = currentElem.dataset.tileNum; + const current = currentElem.dataset.tileIndex; let idPrefix = 'coll_tile_'; if ($(customize.IDS.MENU) .classList.contains(customize.CLASSES.IMAGE_DIALOG)) { @@ -699,7 +712,8 @@ } else { customize.resetSelectionDialog(); } - customize.showImageSelectionDialog(tile.dataset.name); + customize.showImageSelectionDialog( + tile.dataset.name, tile.dataset.tileIndex); } else { customize.handleError(collImgErrors); } @@ -747,7 +761,7 @@ const id = coll[i].collectionId; const name = coll[i].collectionName; const imageUrl = coll[i].previewImageUrl; - const dataset = {'id': id, 'name': name, 'tileNum': i}; + const dataset = {'id': id, 'name': name, 'tileIndex': i}; const tile = customize.createTileWithTitle( 'coll_tile_' + i, imageUrl, name, dataset, tileOnClickInteraction, @@ -878,6 +892,7 @@ return; } customize.selectedOptions.background = tile; + customize.selectedOptions.backgroundId = tile.id; customize.richerPicker_applySelectedState(tile); customize.richerPicker_maybeToggleDone(); customize.richerPicker_previewImage(tile); @@ -972,8 +987,10 @@ * chrome-search://local-ntp/ntp-background-images.js?collection_id=<collection_id> * @param {string} dialogTitle The title to be displayed at the top of the * dialog. + * @param {number} collIndex The index of the collection this image menu belongs + * to. */ -customize.showImageSelectionDialog = function(dialogTitle) { +customize.showImageSelectionDialog = function(dialogTitle, collIndex) { const firstNTile = customize.ROWS_TO_PRELOAD * customize.getTilesWide(); const tileContainer = configData.richerPicker ? $(customize.IDS.BACKGROUNDS_IMAGE_MENU) : @@ -1091,10 +1108,15 @@ ''); dataset.attributionActionUrl = collImg[i].attributionActionUrl; dataset.url = collImg[i].imageUrl; - dataset.tileNum = i; + dataset.tileIndex = i; + + let tileId = 'img_tile_' + i; + if (configData.richerPicker) { + tileId = 'coll_' + collIndex + '_' + tileId; + } const tile = customize.createTile( - 'img_tile_' + i, collImg[i].imageUrl, dataset, tileOnClickInteraction, + tileId, collImg[i].imageUrl, dataset, tileOnClickInteraction, tileOnKeyDownInteraction); tile.setAttribute('aria-label', collImg[i].attributions[0]); @@ -1123,6 +1145,13 @@ }); } + // If an image tile was previously selected re-select it now. + const selected = $(customize.selectedOptions.backgroundId); + if (selected) { + customize.richerPicker_selectBackgroundTile(selected); + } + + $(customize.IDS.TILES).focus(); }; @@ -1136,9 +1165,9 @@ */ customize.loadTile = function(tile, imageData, countLoad) { tile.style.backgroundImage = - 'url(' + imageData[tile.dataset.tileNum].thumbnailImageUrl + ')'; + 'url(' + imageData[tile.dataset.tileIndex].thumbnailImageUrl + ')'; customize.fadeInImageTile( - tile, imageData[tile.dataset.tileNum].thumbnailImageUrl, countLoad); + tile, imageData[tile.dataset.tileIndex].thumbnailImageUrl, countLoad); }; /** @@ -1242,7 +1271,7 @@ $(customize.IDS.BACKGROUNDS_BUTTON), $(customize.IDS.BACKGROUNDS_MENU)); customize.loadChromeBackgrounds(); - customize.loadColorTiles(); + customize.loadColorsMenu(); if (!$(customize.IDS.CUSTOMIZATION_MENU).open) { $(customize.IDS.CUSTOMIZATION_MENU).showModal(); } @@ -1256,6 +1285,7 @@ customize.richerPicker_deselectBackgroundTile( customize.selectedOptions.background); customize.selectedOptions.background = null; + customize.selectedOptions.backgroundId = null; // Reset color selection. customize.richerPicker_removeSelectedState(customize.selectedOptions.color); @@ -1740,7 +1770,7 @@ .classList.contains(customize.CLASSES.COLLECTION_DIALOG)) { $('coll_tile_0').focus(); } else { - $('img_tile_0').focus(); + document.querySelector('[id$="img_tile_0"]').focus(); } } }; @@ -1753,7 +1783,7 @@ $(customize.IDS.BACKGROUNDS_IMAGE_MENU).onkeydown = function(event) { if (customize.arrowKeys.includes(event.keyCode)) { - $('img_tile_0').focus(); + document.querySelector('[id$="img_tile_0"]').focus(); } }; @@ -1896,7 +1926,7 @@ * picker and enable the done button. * @param {?Element} tile The selected color tile. */ -customize.updateColorMenuTileSelection = function(tile) { +customize.updateColorsMenuTileSelection = function(tile) { if (!tile) { return; } @@ -1915,7 +1945,7 @@ * @param {Event} event The event attributes for the interaction. */ customize.colorTileInteraction = function(event) { - customize.updateColorMenuTileSelection( + customize.updateColorsMenuTileSelection( /** @type HTMLElement */ (event.target)); ntpApiHandle.applyAutogeneratedTheme(event.target.dataset.color.split(',')); }; @@ -1926,31 +1956,21 @@ * @param {Event} event The event attributes for the interaction. */ customize.defaultThemeTileInteraction = function(event) { - customize.updateColorMenuTileSelection( + customize.updateColorsMenuTileSelection( /** @type HTMLElement */ (event.target)); ntpApiHandle.applyDefaultTheme(); }; /** - * Loads tiles for colors menu. + * Loads Colors menu elements. */ -customize.loadColorTiles = function() { - // Configure webstore theme elements. - // TODO(gayane): Consider reloading when theme changes. - const themeInfo = ntpApiHandle.themeBackgroundInfo; - if (themeInfo.themeId && themeInfo.themeName) { - $(customize.IDS.COLORS_THEME).classList.add(customize.CLASSES.VISIBLE); - $(customize.IDS.COLORS_THEME_NAME).innerHTML = themeInfo.themeName; - $(customize.IDS.COLORS_THEME_WEBSTORE_LINK).href = - 'https://chrome.google.com/webstore/detail/' + themeInfo.themeId; - } else { - $(customize.IDS.COLORS_THEME).classList.remove(customize.CLASSES.VISIBLE); - } - - if (customize.colorMenuLoaded) { +customize.loadColorsMenu = function() { + if (customize.colorsMenuLoaded) { return; } + customize.updateWebstoreThemeInfo(); + const colorsColl = ntpApiHandle.getColorsInfo(); for (let i = 0; i < colorsColl.length; ++i) { const id = 'color_' + i; @@ -1969,7 +1989,24 @@ $(customize.IDS.COLORS_DEFAULT).onclick = customize.defaultThemeTileInteraction; - customize.colorMenuLoaded = true; + customize.colorsMenuLoaded = true; +}; + +/** + * Update webstore theme info for Colors menu. + */ +customize.updateWebstoreThemeInfo = function() { + const themeInfo = ntpApiHandle.themeBackgroundInfo; + if (themeInfo.themeId && themeInfo.themeName) { + $(customize.IDS.COLORS_THEME).classList.add(customize.CLASSES.VISIBLE); + $(customize.IDS.COLORS_THEME_NAME).innerHTML = themeInfo.themeName; + $(customize.IDS.COLORS_THEME_WEBSTORE_LINK).href = + 'https://chrome.google.com/webstore/detail/' + themeInfo.themeId; + $(customize.IDS.COLORS_THEME_UNINSTALL).onclick = + ntpApiHandle.useDefaultTheme; + } else { + $(customize.IDS.COLORS_THEME).classList.remove(customize.CLASSES.VISIBLE); + } }; /**
diff --git a/chrome/browser/resources/local_ntp/externs.js b/chrome/browser/resources/local_ntp/externs.js index 279b9dbc..d06806d 100644 --- a/chrome/browser/resources/local_ntp/externs.js +++ b/chrome/browser/resources/local_ntp/externs.js
@@ -325,6 +325,11 @@ /** * No params. */ +window.chrome.embeddedSearch.newTabPage.useDefaultTheme; + +/** + * No params. + */ window.chrome.embeddedSearch.newTabPage.undoAllMostVisitedDeletions; /**
diff --git a/chrome/browser/resources/local_ntp/local_ntp.js b/chrome/browser/resources/local_ntp/local_ntp.js index a4619d78..8528448 100644 --- a/chrome/browser/resources/local_ntp/local_ntp.js +++ b/chrome/browser/resources/local_ntp/local_ntp.js
@@ -445,9 +445,7 @@ !info.customBackgroundConfigured); if (configData.isGooglePage) { - // Hide the settings menu or individual options if the related features are - // disabled. - customize.setMenuVisibility(); + customize.onThemeChange(); } }
diff --git a/chrome/browser/resources/management/icons.html b/chrome/browser/resources/management/icons.html index dc4ca72a..2311bf2 100644 --- a/chrome/browser/resources/management/icons.html +++ b/chrome/browser/resources/management/icons.html
@@ -12,6 +12,7 @@ <g id="report"><path d="M15.73 3H8.27L3 8.27v7.46L8.27 21h7.46L21 15.73V8.27L15.73 3zM12 17.3c-.72 0-1.3-.58-1.3-1.3 0-.72.58-1.3 1.3-1.3.72 0 1.3.58 1.3 1.3 0 .72-.58 1.3-1.3 1.3zm1-4.3h-2V7h2v6z"></path></g> <g id="supervised-user"><path d="M11.99 2c-5.52 0-10 4.48-10 10s4.48 10 10 10 10-4.48 10-10-4.48-10-10-10zm3.61 6.34c1.07 0 1.93.86 1.93 1.93 0 1.07-.86 1.93-1.93 1.93-1.07 0-1.93-.86-1.93-1.93-.01-1.07.86-1.93 1.93-1.93zm-6-1.58c1.3 0 2.36 1.06 2.36 2.36 0 1.3-1.06 2.36-2.36 2.36s-2.36-1.06-2.36-2.36c0-1.31 1.05-2.36 2.36-2.36zm0 9.13v3.75c-2.4-.75-4.3-2.6-5.14-4.96 1.05-1.12 3.67-1.69 5.14-1.69.53 0 1.2.08 1.9.22-1.64.87-1.9 2.02-1.9 2.68zM11.99 20c-.27 0-.53-.01-.79-.04v-4.07c0-1.42 2.94-2.13 4.4-2.13 1.07 0 2.92.39 3.84 1.15-1.17 2.97-4.06 5.09-7.45 5.09z"></path></g> <g id="timelapse"><path d="M16.24 7.76C15.07 6.59 13.54 6 12 6v6l-4.24 4.24c2.34 2.34 6.14 2.34 8.49 0 2.34-2.34 2.34-6.14-.01-8.48zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"></path></g> + <g id="linux"><path d="M 6.9375 22.042969 C 3.867188 20.457031 1.886719 17.347656 1.824219 13.234375 C 1.527344 13.378906 1.1875 13.402344 0.800781 13.265625 C -0.3125 12.875 -0.0625 11.578125 0.34375 10.421875 C 0.683594 9.460938 1.835938 8.761719 2.402344 8.613281 C 3.71875 3.78125 6.804688 0 12 0 C 17.257812 0 20.367188 3.625 21.644531 8.628906 C 22.222656 8.796875 23.324219 9.484375 23.65625 10.421875 C 24.0625 11.578125 24.3125 12.875 23.199219 13.265625 C 22.8125 13.402344 22.472656 13.378906 22.175781 13.234375 C 22.117188 17.375 20.140625 20.472656 17.070312 22.046875 C 17.257812 22.191406 17.363281 22.375 17.363281 22.613281 C 17.363281 23.378906 17.75 24 14.898438 24 C 12.8125 24 12.457031 23.578125 12.417969 23.117188 C 12.28125 23.035156 12.140625 22.910156 12 22.910156 C 11.859375 22.910156 11.71875 23.042969 11.582031 23.128906 C 11.535156 23.582031 11.171875 24 9.101562 24 C 6.25 24 6.636719 23.378906 6.636719 22.613281 C 6.636719 22.371094 6.746094 22.183594 6.9375 22.042969 Z M 12 21.222656 C 17.929688 21.222656 20.070312 17.1875 20.070312 11.820312 C 20.070312 7.371094 18.125 3.28125 14.898438 2.597656 C 13.863281 2.378906 13.136719 4.761719 12 4.761719 C 10.863281 4.761719 10.035156 2.378906 9.101562 2.597656 C 5.863281 3.359375 3.929688 7.605469 3.929688 11.820312 C 3.929688 16.882812 6.070312 21.222656 12 21.222656 Z M 8.277344 9.324219 C 7.589844 9.324219 7.035156 8.789062 7.035156 8.132812 C 7.035156 7.476562 7.589844 6.941406 8.277344 6.941406 C 8.960938 6.941406 9.515625 7.476562 9.515625 8.132812 C 9.515625 8.789062 8.960938 9.324219 8.277344 9.324219 Z M 15.722656 9.324219 C 15.039062 9.324219 14.484375 8.789062 14.484375 8.132812 C 14.484375 7.476562 15.039062 6.941406 15.722656 6.941406 C 16.410156 6.941406 16.964844 7.476562 16.964844 8.132812 C 16.964844 8.789062 16.410156 9.324219 15.722656 9.324219 Z M 12.226562 9.964844 L 13.929688 10.683594 C 14.222656 10.804688 14.355469 11.132812 14.226562 11.414062 C 14.199219 11.46875 14.164062 11.519531 14.121094 11.5625 L 12.425781 13.308594 C 12.210938 13.535156 11.839844 13.546875 11.601562 13.339844 C 11.589844 13.332031 11.578125 13.320312 11.566406 13.308594 L 9.878906 11.558594 C 9.660156 11.332031 9.675781 10.980469 9.914062 10.773438 C 9.960938 10.734375 10.011719 10.703125 10.070312 10.679688 L 11.75 9.964844 C 11.898438 9.902344 12.074219 9.902344 12.226562 9.964844 Z M 12.226562 9.964844"></path></g> </if> <g id="account-circle"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"></path><path d="M0 0h24v24H0z" fill="none"></path></g> <g id="public"><path d="M0 0h24v24H0z" fill="none"></path><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"></path></g>
diff --git a/chrome/browser/resources/management/management_browser_proxy.js b/chrome/browser/resources/management/management_browser_proxy.js index 3d73753a..20c54008 100644 --- a/chrome/browser/resources/management/management_browser_proxy.js +++ b/chrome/browser/resources/management/management_browser_proxy.js
@@ -51,7 +51,8 @@ STATISTIC: 'device statistics', DEVICE: 'device', LOGS: 'logs', - PRINT: 'print' + PRINT: 'print', + CROSTINI: 'crostini' };
diff --git a/chrome/browser/resources/management/management_ui.js b/chrome/browser/resources/management/management_ui.js index afc2712..3d5011b 100644 --- a/chrome/browser/resources/management/management_ui.js +++ b/chrome/browser/resources/management/management_ui.js
@@ -178,6 +178,8 @@ return 'management:report'; case management.DeviceReportingType.PRINT: return 'cr:print'; + case management.DeviceReportingType.CROSTINI: + return 'management:linux'; default: return 'cr:computer'; }
diff --git a/chrome/browser/resources/settings/a11y_page/a11y_page.html b/chrome/browser/resources/settings/a11y_page/a11y_page.html index a4acf13..0b546ed 100644 --- a/chrome/browser/resources/settings/a11y_page/a11y_page.html +++ b/chrome/browser/resources/settings/a11y_page/a11y_page.html
@@ -43,14 +43,14 @@ </div> </if> <if expr="chromeos"> - <template is="dom-if" if="[[pageVisibility.webstoreLink]]"> - <div route-path="default"> - <template is="dom-if" if="[[showCaptionSettings_]]"> - <cr-link-row class="hr" id="captions" - label="$i18n{captionsTitle}" - on-click="onTapCaptions_"> - </cr-link-row> - </template> + <div route-path="default"> + <template is="dom-if" if="[[showCaptionSettings_]]"> + <cr-link-row class="hr" id="captions" + label="$i18n{captionsTitle}" + on-click="onTapCaptions_"> + </cr-link-row> + </template> + <template is="dom-if" if="[[pageVisibility.webstoreLink]]"> <settings-toggle-button id="a11yImageLabels" hidden$="[[!showAccessibilityLabelsSetting_]]" pref="{{prefs.settings.a11y.enable_accessibility_image_labels}}" @@ -67,38 +67,42 @@ on-click="onManageAccessibilityFeaturesTap_" sub-label="$i18n{moreFeaturesLinkDescription}"> </cr-link-row> - </div> - <template is="dom-if" route-path="/manageAccessibility"> - <settings-subpage associated-control="[[$$('#subpage-trigger')]]" - page-title="$i18n{manageAccessibilityFeatures}"> - <settings-manage-a11y-page prefs="{{prefs}}"> - </settings-manage-a11y-page> - </settings-subpage> - </template> - <template is="dom-if" route-path="/manageAccessibility/tts"> - <settings-subpage - associated-control="[[$$('#subpage-trigger')]]" - page-title="$i18n{manageTtsSettings}"> - <settings-tts-subpage prefs="{{prefs}}"> - </settings-tts-subpage> - </settings-subpage> - </template> - <template is="dom-if" if="[[showExperimentalSwitchAccess_]]"> - <template is="dom-if" - route-path="/manageAccessibility/switchAccess"> - <settings-subpage associated-control="[[$$('#subpage-trigger')]]" - page-title="$i18n{manageSwitchAccessSettings}"> - <settings-switch-access-subpage prefs="{{prefs.settings.a11y}}"> - </settings-switch-access-subpage> + <template is="dom-if" route-path="/manageAccessibility"> + <settings-subpage + associated-control="[[$$('#subpage-trigger')]]" + page-title="$i18n{manageAccessibilityFeatures}"> + <settings-manage-a11y-page prefs="{{prefs}}"> + </settings-manage-a11y-page> </settings-subpage> </template> + <template is="dom-if" route-path="/manageAccessibility/tts"> + <settings-subpage + associated-control="[[$$('#subpage-trigger')]]" + page-title="$i18n{manageTtsSettings}"> + <settings-tts-subpage prefs="{{prefs}}"> + </settings-tts-subpage> + </settings-subpage> + </template> + <template is="dom-if" if="[[showExperimentalSwitchAccess_]]"> + <template is="dom-if" + route-path="/manageAccessibility/switchAccess"> + <settings-subpage + associated-control="[[$$('#subpage-trigger')]]" + page-title="$i18n{manageSwitchAccessSettings}"> + <settings-switch-access-subpage + prefs="{{prefs.settings.a11y}}"> + </settings-switch-access-subpage> + </settings-subpage> + </template> + </template> </template> - </template> - <cr-link-row class="hr" - label="$i18n{moreFeaturesLink}" - on-click="onMoreFeaturesLinkClick_" - sub-label="$i18n{a11yWebStore}" - hidden="[[pageVisibility.webstoreLink]]" external></cr-link-row> + <cr-link-row class="hr" + label="$i18n{moreFeaturesLink}" + on-click="onMoreFeaturesLinkClick_" + sub-label="$i18n{a11yWebStore}" + hidden="[[pageVisibility.webstoreLink]]" external> + </cr-link-row> + </div> </if> <if expr="chromeos or is_linux or is_win">
diff --git a/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_page.html b/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_page.html index 9553ef6..f93de3c 100644 --- a/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_page.html +++ b/chrome/browser/resources/settings/chromeos/os_languages_page/os_languages_page.html
@@ -181,8 +181,7 @@ <div class="explain-selected" hidden="[[!isProspectiveUILanguage_( item.language.code, - languages.prospectiveUILanguage, - pageVisibility.uiDisplayedInThisLanguage)]]"> + languages.prospectiveUILanguage)]]"> $i18n{isDisplayedInThisLanguage} </div> </div>
diff --git a/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.html b/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.html index 8426cfe..4351e857 100644 --- a/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.html +++ b/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.html
@@ -16,7 +16,9 @@ <cr-button id="cancel" class="cancel-button" on-click="onCancelTap_">$i18n{cancel}</cr-button> <cr-button id="continue" class="action-button" - on-click="onContinueTap_">$i18n{confirm}</cr-button> + on-click="onContinueTap_"> + $i18n{crostiniImportConfirmationDialogConfirmationButton} + </cr-button> </div> </cr-dialog> </template>
diff --git a/chrome/browser/resources/settings/languages_page/languages_page.html b/chrome/browser/resources/settings/languages_page/languages_page.html index e622104..2cc7d7d 100644 --- a/chrome/browser/resources/settings/languages_page/languages_page.html +++ b/chrome/browser/resources/settings/languages_page/languages_page.html
@@ -221,17 +221,9 @@ </div> <if expr="chromeos or is_win"> <div class="explain-selected" -<if expr="is_win"> hidden="[[!isProspectiveUILanguage_( item.language.code, languages.prospectiveUILanguage)]]"> -</if> -<if expr="chromeos"> - hidden="[[!shouldShowExplanation_( - item.language.code, - languages.prospectiveUILanguage, - pageVisibility.uiDisplayedInThisLanguage)]]"> -</if> $i18n{isDisplayedInThisLanguage} </div> </if> <!-- chromeos or is_win --> @@ -240,11 +232,7 @@ <template is="dom-if" if="[[isRestartRequired_( item.language.code, languages.prospectiveUILanguage)]]" restamp> - <cr-button id="restartButton" -<if expr="chromeos"> - hidden="[[!pageVisibility.uiDisplayedInThisLanguage]]" -</if> - on-click="onRestartTap_"> + <cr-button id="restartButton" on-click="onRestartTap_"> $i18n{restart} </cr-button> </template> @@ -421,9 +409,6 @@ class$="[[getMenuClass_(prefs.translate.enabled.value)]]"> <if expr="chromeos or is_win"> <cr-checkbox id="uiLanguageItem" -<if expr="chromeos"> - hidden="[[!pageVisibility.uiDisplayedInThisLanguage]]" -</if> class="dropdown-item" checked="[[isProspectiveUILanguage_( detailLanguage_.language.code,
diff --git a/chrome/browser/resources/settings/languages_page/languages_page.js b/chrome/browser/resources/settings/languages_page/languages_page.js index ba4c14f..a69c59b 100644 --- a/chrome/browser/resources/settings/languages_page/languages_page.js +++ b/chrome/browser/resources/settings/languages_page/languages_page.js
@@ -316,21 +316,6 @@ this.languageHelper.openInputMethodOptions(e.model.item.id); }, - // TODO(hsuregan): Remove when SplitSettings is complete. - /** - * Incorporates pageVisibility check along with isProspectiveUILanguage_(). - * @param {string} languageCode The language code identifying a language. - * @param {string} prospectiveUILanguage The prospective UI language. - * @return {boolean} True if the given language matches the prospective UI - * pref (which may be different from the actual UI language). - * @private - */ - shouldShowExplanation_: function(languageCode, prospectiveUILanguage) { - return this.pageVisibility && - this.pageVisibility.uiDisplayedInThisLanguage && - this.isProspectiveUILanguage_(languageCode, prospectiveUILanguage); - }, - /** * @param {string} id The input method ID. * @param {string} currentId The ID of the currently enabled input method.
diff --git a/chrome/browser/resources/settings/page_visibility.js b/chrome/browser/resources/settings/page_visibility.js index 426b4bb..fc8d51f 100644 --- a/chrome/browser/resources/settings/page_visibility.js +++ b/chrome/browser/resources/settings/page_visibility.js
@@ -84,7 +84,6 @@ /** * @typedef {{ - * uiDisplayedInThisLanguage: boolean, * manageInputMethods: boolean, * inputMethodsList: boolean, * }} @@ -152,7 +151,6 @@ extensions: false, printing: true, languages: { - uiDisplayedInThisLanguage: showOSSettings, manageInputMethods: showOSSettings, inputMethodsList: showOSSettings, }, @@ -203,7 +201,6 @@ extensions: true, printing: true, languages: { - uiDisplayedInThisLanguage: showOSSettings, manageInputMethods: showOSSettings, inputMethodsList: showOSSettings, },
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/google_apps/BUILD.gn b/chrome/browser/resources/welcome/onboarding_welcome/google_apps/BUILD.gn index 7a39dd1..6566c5e 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/google_apps/BUILD.gn +++ b/chrome/browser/resources/welcome/onboarding_welcome/google_apps/BUILD.gn
@@ -6,6 +6,8 @@ js_type_check("closure_compile") { deps = [ + ":google_app_proxy", + ":google_apps_metrics_proxy", ":nux_google_apps", ] } @@ -13,9 +15,9 @@ js_library("nux_google_apps") { deps = [ ":google_app_proxy", + ":google_apps_metrics_proxy", "../:navigation_behavior", "../shared:bookmark_proxy", - "../shared:module_metrics_proxy", "../shared:nux_types", "../shared:step_indicator", "//third_party/polymer/v1_0/components-chromium/iron-a11y-announcer:iron-a11y-announcer-extracted", @@ -31,3 +33,9 @@ ] externs_list = [ "$externs_path/chrome_send.js" ] } + +js_library("google_apps_metrics_proxy") { + deps = [ + "../shared:module_metrics_proxy", + ] +}
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_apps_metrics_proxy.html b/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_apps_metrics_proxy.html new file mode 100644 index 0000000..222483c --- /dev/null +++ b/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_apps_metrics_proxy.html
@@ -0,0 +1,3 @@ +<link rel="import" href="chrome://resources/html/cr.html"> +<link rel="import" href="../shared/module_metrics_proxy.html"> +<script src="google_apps_metrics_proxy.js"></script>
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_apps_metrics_proxy.js b/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_apps_metrics_proxy.js new file mode 100644 index 0000000..77886462 --- /dev/null +++ b/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_apps_metrics_proxy.js
@@ -0,0 +1,19 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +cr.define('welcome', function() { + class GoogleAppsMetricsProxyImpl extends welcome.ModuleMetricsProxyImpl { + constructor() { + super( + 'FirstRun.NewUserExperience.GoogleAppsInteraction', + welcome.NuxGoogleAppsInteractions); + } + } + + cr.addSingletonGetter(GoogleAppsMetricsProxyImpl); + + return { + GoogleAppsMetricsProxyImpl: GoogleAppsMetricsProxyImpl, + }; +});
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html b/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html index ff87621..a5d31e1 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html
@@ -13,9 +13,9 @@ <link rel="import" href="../shared/bookmark_proxy.html"> <link rel="import" href="../shared/chooser_shared_css.html"> <link rel="import" href="../shared/i18n_setup.html"> -<link rel="import" href="../shared/module_metrics_proxy.html"> <link rel="import" href="../shared/step_indicator.html"> <link rel="import" href="google_app_proxy.html"> +<link rel="import" href="google_apps_metrics_proxy.html"> <dom-module id="nux-google-apps"> <template>
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/BUILD.gn b/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/BUILD.gn index f15e760..32399f99 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/BUILD.gn +++ b/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/BUILD.gn
@@ -6,15 +6,17 @@ js_type_check("closure_compile") { deps = [ + ":ntp_background_metrics_proxy", + ":ntp_background_proxy", ":nux_ntp_background", ] } js_library("nux_ntp_background") { deps = [ + ":ntp_background_metrics_proxy", ":ntp_background_proxy", "../:navigation_behavior", - "../shared:module_metrics_proxy", "../shared:nux_types", "//ui/webui/resources/js:cr", "//ui/webui/resources/js:i18n_behavior", @@ -28,3 +30,9 @@ ] externs_list = [ "$externs_path/chrome_send.js" ] } + +js_library("ntp_background_metrics_proxy") { + deps = [ + "../shared:module_metrics_proxy", + ] +}
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_metrics_proxy.html b/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_metrics_proxy.html new file mode 100644 index 0000000..a5bbfe09 --- /dev/null +++ b/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_metrics_proxy.html
@@ -0,0 +1,3 @@ +<link rel="import" href="chrome://resources/html/cr.html"> +<link rel="import" href="../shared/module_metrics_proxy.html"> +<script src="ntp_background_metrics_proxy.js"></script>
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_metrics_proxy.js b/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_metrics_proxy.js new file mode 100644 index 0000000..dcdb0ff --- /dev/null +++ b/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_metrics_proxy.js
@@ -0,0 +1,23 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +cr.define('welcome', function() { + class NtpBackgroundMetricsProxyImpl extends welcome.ModuleMetricsProxyImpl { + constructor() { + super( + 'FirstRun.NewUserExperience.NtpBackgroundInteraction', + welcome.NuxNtpBackgroundInteractions); + } + + getInteractions() { + return this.interactions_; + } + } + + cr.addSingletonGetter(NtpBackgroundMetricsProxyImpl); + + return { + NtpBackgroundMetricsProxyImpl: NtpBackgroundMetricsProxyImpl, + }; +});
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html b/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html index 77364b47..c6d03b9a 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html
@@ -11,8 +11,8 @@ <link rel="import" href="../shared/animations_css.html"> <link rel="import" href="../shared/chooser_shared_css.html"> <link rel="import" href="../shared/i18n_setup.html"> -<link rel="import" href="../shared/module_metrics_proxy.html"> <link rel="import" href="../shared/step_indicator.html"> +<link rel="import" href="ntp_background_metrics_proxy.html"> <link rel="import" href="ntp_background_proxy.html"> <dom-module id="nux-ntp-background">
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd b/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd index a857eff..011b9b1 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd +++ b/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd
@@ -223,6 +223,14 @@ file="set_as_default/nux_set_as_default_proxy.js" compress="gzip" type="chrome_html" /> + <structure name="IDR_GOOGLE_APPS_METRICS_PROXY_HTML" + file="google_apps/google_apps_metrics_proxy.html" + compress="gzip" + type="chrome_html" /> + <structure name="IDR_GOOGLE_APPS_METRICS_PROXY_JS" + file="google_apps/google_apps_metrics_proxy.js" + compress="gzip" + type="chrome_html" /> <!-- NUX NTP background--> <structure name="IDR_NUX_NTP_BACKGROUND_HTML" @@ -241,6 +249,14 @@ file="ntp_background/ntp_background_proxy.js" compress="gzip" type="chrome_html" /> + <structure name="IDR_NUX_NTP_BACKGROUND_METRICS_PROXY_HTML" + file="ntp_background/ntp_background_metrics_proxy.html" + compress="gzip" + type="chrome_html" /> + <structure name="IDR_NUX_NTP_BACKGROUND_METRICS_PROXY_JS" + file="ntp_background/ntp_background_metrics_proxy.js" + compress="gzip" + type="chrome_html" /> </structures> </release> </grit>
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/shared/BUILD.gn b/chrome/browser/resources/welcome/onboarding_welcome/shared/BUILD.gn index d2c36998..9a06f41 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/shared/BUILD.gn +++ b/chrome/browser/resources/welcome/onboarding_welcome/shared/BUILD.gn
@@ -7,6 +7,7 @@ js_type_check("closure_compile") { deps = [ ":bookmark_proxy", + ":module_metrics_proxy", ":nux_types", ":step_indicator", ]
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/shared/module_metrics_proxy.js b/chrome/browser/resources/welcome/onboarding_welcome/shared/module_metrics_proxy.js index 384ae2ac..d6a437b 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/shared/module_metrics_proxy.js +++ b/chrome/browser/resources/welcome/onboarding_welcome/shared/module_metrics_proxy.js
@@ -3,6 +3,49 @@ // found in the LICENSE file. cr.define('welcome', function() { + /** + * NuxNtpBackgroundInteractions enum. + * These values are persisted to logs and should not be renumbered or + * re-used. + * See tools/metrics/histograms/enums.xml. + * @enum {number} + */ + const NuxNtpBackgroundInteractions = { + PageShown: 0, + DidNothingAndNavigatedAway: 1, + DidNothingAndChoseSkip: 2, + DidNothingAndChoseNext: 3, + ChoseAnOptionAndNavigatedAway: 4, + ChoseAnOptionAndChoseSkip: 5, + ChoseAnOptionAndChoseNext: 6, + NavigatedAwayThroughBrowserHistory: 7, + BackgroundImageFailedToLoad: 8, + BackgroundImageNeverLoaded: 9, + }; + + /** + * NuxGoogleAppsInteractions enum. + * These values are persisted to logs and should not be renumbered or + * re-used. + * See tools/metrics/histograms/enums.xml. + * @enum {number} + */ + const NuxGoogleAppsInteractions = { + PageShown: 0, + NotUsed_DEPRECATED: 1, + GetStarted_DEPRECATED: 2, + DidNothingAndNavigatedAway: 3, + DidNothingAndChoseSkip: 4, + ChoseAnOptionAndNavigatedAway: 5, + ChoseAnOptionAndChoseSkip: 6, + ChoseAnOptionAndChoseNext: 7, + ClickedDisabledNextButtonAndNavigatedAway: 8, + ClickedDisabledNextButtonAndChoseSkip: 9, + ClickedDisabledNextButtonAndChoseNext: 10, + DidNothingAndChoseNext: 11, + NavigatedAwayThroughBrowserHistory: 12, + }; + /** @interface */ class ModuleMetricsProxy { recordPageShown() {} @@ -190,76 +233,10 @@ } return { - ModuleMetricsProxy: ModuleMetricsProxy, - ModuleMetricsProxyImpl: ModuleMetricsProxyImpl, ModuleMetricsManager: ModuleMetricsManager, + ModuleMetricsProxyImpl: ModuleMetricsProxyImpl, + ModuleMetricsProxy: ModuleMetricsProxy, + NuxGoogleAppsInteractions: NuxGoogleAppsInteractions, + NuxNtpBackgroundInteractions: NuxNtpBackgroundInteractions, }; }); - -welcome.GoogleAppsMetricsProxyImpl = - class extends welcome.ModuleMetricsProxyImpl { - constructor() { - /** - * NuxGoogleAppsInteractions enum. - * These values are persisted to logs and should not be renumbered or - * re-used. - * See tools/metrics/histograms/enums.xml. - * @enum {number} - */ - const NuxGoogleAppsInteractions = { - PageShown: 0, - NotUsed_DEPRECATED: 1, - GetStarted_DEPRECATED: 2, - DidNothingAndNavigatedAway: 3, - DidNothingAndChoseSkip: 4, - ChoseAnOptionAndNavigatedAway: 5, - ChoseAnOptionAndChoseSkip: 6, - ChoseAnOptionAndChoseNext: 7, - ClickedDisabledNextButtonAndNavigatedAway: 8, - ClickedDisabledNextButtonAndChoseSkip: 9, - ClickedDisabledNextButtonAndChoseNext: 10, - DidNothingAndChoseNext: 11, - NavigatedAwayThroughBrowserHistory: 12, - }; - - super( - 'FirstRun.NewUserExperience.GoogleAppsInteraction', - NuxGoogleAppsInteractions); - } -}; - -welcome.NtpBackgroundMetricsProxyImpl = - class extends welcome.ModuleMetricsProxyImpl { - constructor() { - /** - * NuxNtpBackgroundInteractions enum. - * These values are persisted to logs and should not be renumbered or - * re-used. - * See tools/metrics/histograms/enums.xml. - * @enum {number} - */ - const NuxNtpBackgroundInteractions = { - PageShown: 0, - DidNothingAndNavigatedAway: 1, - DidNothingAndChoseSkip: 2, - DidNothingAndChoseNext: 3, - ChoseAnOptionAndNavigatedAway: 4, - ChoseAnOptionAndChoseSkip: 5, - ChoseAnOptionAndChoseNext: 6, - NavigatedAwayThroughBrowserHistory: 7, - BackgroundImageFailedToLoad: 8, - BackgroundImageNeverLoaded: 9, - }; - - super( - 'FirstRun.NewUserExperience.NtpBackgroundInteraction', - NuxNtpBackgroundInteractions); - } - - getInteractions() { - return this.interactions_; - } -}; - -cr.addSingletonGetter(welcome.GoogleAppsMetricsProxyImpl); -cr.addSingletonGetter(welcome.NtpBackgroundMetricsProxyImpl);
diff --git a/chrome/browser/safe_browsing/advanced_protection_status_manager.h b/chrome/browser/safe_browsing/advanced_protection_status_manager.h index fda7e092..a450ec1 100644 --- a/chrome/browser/safe_browsing/advanced_protection_status_manager.h +++ b/chrome/browser/safe_browsing/advanced_protection_status_manager.h
@@ -7,8 +7,8 @@ #include "base/timer/timer.h" #include "components/keyed_service/core/keyed_service.h" -#include "components/signin/core/browser/account_info.h" #include "components/signin/public/identity_manager/access_token_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" namespace identity {
diff --git a/chrome/browser/safe_browsing/chrome_password_protection_service.cc b/chrome/browser/safe_browsing/chrome_password_protection_service.cc index deef656..44885c2 100644 --- a/chrome/browser/safe_browsing/chrome_password_protection_service.cc +++ b/chrome/browser/safe_browsing/chrome_password_protection_service.cc
@@ -50,7 +50,7 @@ #include "components/safe_browsing/triggers/trigger_throttler.h" #include "components/safe_browsing/verdict_cache_manager.h" #include "components/safe_browsing/web_ui/safe_browsing_ui.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/strings/grit/components_strings.h" #include "components/sync/driver/sync_service.h"
diff --git a/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc b/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc index 9cd98cd..f7e0197 100644 --- a/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc +++ b/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc
@@ -26,7 +26,7 @@ #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/safe_browsing/password_protection/password_protection_request.h" #include "components/security_state/core/security_state.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/user_manager/user_names.h" #include "content/public/browser/web_contents.h"
diff --git a/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc b/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc index b1c22f0..489fdef 100644 --- a/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc +++ b/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc
@@ -31,7 +31,7 @@ #include "components/safe_browsing/password_protection/password_protection_navigation_throttle.h" #include "components/safe_browsing/password_protection/password_protection_request.h" #include "components/safe_browsing/verdict_cache_manager.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/strings/grit/components_strings.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/sync_user_events/fake_user_event_service.h"
diff --git a/chrome/browser/search/search_suggest/search_suggest_service_unittest.cc b/chrome/browser/search/search_suggest/search_suggest_service_unittest.cc index 99df26e..071d1bb 100644 --- a/chrome/browser/search/search_suggest/search_suggest_service_unittest.cc +++ b/chrome/browser/search/search_suggest/search_suggest_service_unittest.cc
@@ -18,7 +18,7 @@ #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/search_test_utils.h" #include "components/search_engines/template_url_service.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/sync_preferences/testing_pref_service_syncable.h"
diff --git a/chrome/browser/sessions/tab_restore_browsertest.cc b/chrome/browser/sessions/tab_restore_browsertest.cc index c9df3f1..fced7a7 100644 --- a/chrome/browser/sessions/tab_restore_browsertest.cc +++ b/chrome/browser/sessions/tab_restore_browsertest.cc
@@ -266,11 +266,8 @@ EXPECT_EQ(2u, active_browser_list_->size()); // Close the final tab in the first browser. - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); CloseTab(0); - window_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); ASSERT_NO_FATAL_FAILURE(RestoreTab(1, 0)); @@ -369,11 +366,8 @@ CloseTab(0); // Close the last tab, closing the browser. - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); CloseTab(0); - observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_EQ(1u, active_browser_list_->size()); // Restore the last-closed tab into a new window. @@ -656,14 +650,10 @@ EXPECT_EQ(window_count - 1, active_browser_list_->size()); // Restore the window. - content::WindowedNotificationObserver open_window_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); content::WindowedNotificationObserver load_stop_observer( content::NOTIFICATION_LOAD_STOP, content::NotificationService::AllSources()); chrome::RestoreTab(active_browser_list_->get(0)); - open_window_observer.Wait(); EXPECT_EQ(window_count, active_browser_list_->size()); Browser* browser = GetBrowser(1); @@ -826,11 +816,8 @@ TabLoaderTester::SetConstructionCallbackForTesting(&callback); // Restore recently closed window. - content::WindowedNotificationObserver open_window_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); chrome::OpenWindowWithRestoredTabs(browser()->profile()); - open_window_observer.Wait(); + ASSERT_EQ(2U, active_browser_list_->size()); browser2 = GetBrowser(1); EXPECT_EQ(tabs_count, browser2->tab_strip_model()->count()); @@ -931,11 +918,7 @@ CloseBrowserSynchronously(browser()); ASSERT_EQ(1u, active_browser_list_->size()); - content::WindowedNotificationObserver open_window_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); chrome::RestoreTab(GetBrowser(0)); - open_window_observer.Wait(); ASSERT_EQ(2u, active_browser_list_->size()); Browser* restored_window = GetBrowser(1);
diff --git a/chrome/browser/signin/account_consistency_mode_manager.cc b/chrome/browser/signin/account_consistency_mode_manager.cc index 23ac951..e53c51b 100644 --- a/chrome/browser/signin/account_consistency_mode_manager.cc +++ b/chrome/browser/signin/account_consistency_mode_manager.cc
@@ -16,8 +16,8 @@ #include "chrome/common/pref_names.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "components/signin/public/base/signin_pref_names.h" #include "google_apis/google_api_keys.h" #if defined(OS_CHROMEOS)
diff --git a/chrome/browser/signin/account_consistency_mode_manager.h b/chrome/browser/signin/account_consistency_mode_manager.h index 3a898c7..9fef873 100644 --- a/chrome/browser/signin/account_consistency_mode_manager.h +++ b/chrome/browser/signin/account_consistency_mode_manager.h
@@ -11,8 +11,8 @@ #include "build/buildflag.h" #include "components/keyed_service/core/keyed_service.h" #include "components/prefs/pref_member.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_buildflags.h" namespace user_prefs { class PrefRegistrySyncable;
diff --git a/chrome/browser/signin/account_consistency_mode_manager_unittest.cc b/chrome/browser/signin/account_consistency_mode_manager_unittest.cc index d1f3f65..7cf4ecf 100644 --- a/chrome/browser/signin/account_consistency_mode_manager_unittest.cc +++ b/chrome/browser/signin/account_consistency_mode_manager_unittest.cc
@@ -18,9 +18,9 @@ #include "chrome/test/base/testing_profile.h" #include "components/prefs/pref_notifier_impl.h" #include "components/prefs/testing_pref_store.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/signin/account_reconcilor_factory.cc b/chrome/browser/signin/account_reconcilor_factory.cc index 010c303e..55e9eb3 100644 --- a/chrome/browser/signin/account_reconcilor_factory.cc +++ b/chrome/browser/signin/account_reconcilor_factory.cc
@@ -15,12 +15,12 @@ #include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/account_reconcilor_delegate.h" #include "components/signin/core/browser/consistency_cookie_manager_base.h" #include "components/signin/core/browser/mirror_account_reconcilor_delegate.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_buildflags.h" #if defined(OS_CHROMEOS) #include "base/metrics/histogram_macros.h"
diff --git a/chrome/browser/signin/chrome_device_id_helper.cc b/chrome/browser/signin/chrome_device_id_helper.cc index 7bae327..1f38b72 100644 --- a/chrome/browser/signin/chrome_device_id_helper.cc +++ b/chrome/browser/signin/chrome_device_id_helper.cc
@@ -7,7 +7,7 @@ #include <string> #include "chrome/browser/profiles/profile.h" -#include "components/signin/core/browser/device_id_helper.h" +#include "components/signin/public/base/device_id_helper.h" #if defined(OS_CHROMEOS) #include "base/command_line.h" @@ -15,8 +15,8 @@ #include "base/logging.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/signin_switches.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/signin_switches.h" #include "components/user_manager/known_user.h" #include "components/user_manager/user_manager.h" #endif
diff --git a/chrome/browser/signin/chrome_signin_client.cc b/chrome/browser/signin/chrome_signin_client.cc index 213e116..99df6e8 100644 --- a/chrome/browser/signin/chrome_signin_client.cc +++ b/chrome/browser/signin/chrome_signin_client.cc
@@ -33,11 +33,11 @@ #include "components/content_settings/core/browser/cookie_settings.h" #include "components/metrics/metrics_service.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/cookie_settings_util.h" -#include "components/signin/core/browser/signin_buildflags.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/access_token_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browser_context.h"
diff --git a/chrome/browser/signin/chrome_signin_client.h b/chrome/browser/signin/chrome_signin_client.h index 6689d0f..869d060 100644 --- a/chrome/browser/signin/chrome_signin_client.h +++ b/chrome/browser/signin/chrome_signin_client.h
@@ -14,7 +14,7 @@ #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/signin_client.h" #include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h" #include "google_apis/gaia/gaia_oauth_client.h" #include "services/network/public/cpp/shared_url_loader_factory.h"
diff --git a/chrome/browser/signin/chrome_signin_client_unittest.cc b/chrome/browser/signin/chrome_signin_client_unittest.cc index 201e474..291db11 100644 --- a/chrome/browser/signin/chrome_signin_client_unittest.cc +++ b/chrome/browser/signin/chrome_signin_client_unittest.cc
@@ -18,7 +18,7 @@ #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/browser/network_service_instance.h" #include "content/public/test/test_browser_thread_bundle.h" #include "services/network/test/test_network_connection_tracker.h"
diff --git a/chrome/browser/signin/chrome_signin_helper.cc b/chrome/browser/signin/chrome_signin_helper.cc index 427cf15..e60d49a 100644 --- a/chrome/browser/signin/chrome_signin_helper.cc +++ b/chrome/browser/signin/chrome_signin_helper.cc
@@ -33,11 +33,11 @@ #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/url_constants.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/chrome_connected_header_helper.h" -#include "components/signin/core/browser/signin_buildflags.h" #include "components/signin/core/browser/signin_header_helper.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_buildflags.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/resource_request_info.h"
diff --git a/chrome/browser/signin/chrome_signin_helper_unittest.cc b/chrome/browser/signin/chrome_signin_helper_unittest.cc index 6b5e6a77..af93e8e4 100644 --- a/chrome/browser/signin/chrome_signin_helper_unittest.cc +++ b/chrome/browser/signin/chrome_signin_helper_unittest.cc
@@ -10,9 +10,9 @@ #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "chrome/browser/signin/scoped_account_consistency.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_buildflags.h" #include "components/signin/core/browser/signin_header_helper.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_buildflags.h" #include "content/public/browser/resource_request_info.h" #include "content/public/test/test_browser_thread_bundle.h" #include "net/http/http_response_headers.h"
diff --git a/chrome/browser/signin/chromeos_mirror_account_consistency_browsertest.cc b/chrome/browser/signin/chromeos_mirror_account_consistency_browsertest.cc index f24fd2d..ad723380 100644 --- a/chrome/browser/signin/chromeos_mirror_account_consistency_browsertest.cc +++ b/chrome/browser/signin/chromeos_mirror_account_consistency_browsertest.cc
@@ -21,7 +21,7 @@ #include "components/network_session_configurator/common/network_switches.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "content/public/test/browser_test_utils.h"
diff --git a/chrome/browser/signin/dice_browsertest.cc b/chrome/browser/signin/dice_browsertest.cc index 7e140b7..2c6c811 100644 --- a/chrome/browser/signin/dice_browsertest.cc +++ b/chrome/browser/signin/dice_browsertest.cc
@@ -48,13 +48,13 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/dice_header_helper.h" -#include "components/signin/core/browser/signin_client.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/signin/public/identity_manager/primary_account_mutator.h"
diff --git a/chrome/browser/signin/dice_response_handler.cc b/chrome/browser/signin/dice_response_handler.cc index 634bf1f9..810cd96 100644 --- a/chrome/browser/signin/dice_response_handler.cc +++ b/chrome/browser/signin/dice_response_handler.cc
@@ -24,9 +24,9 @@ #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" #include "components/signin/core/browser/about_signin_internals.h" -#include "components/signin/core/browser/signin_client.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "google_apis/gaia/gaia_auth_fetcher.h"
diff --git a/chrome/browser/signin/dice_response_handler.h b/chrome/browser/signin/dice_response_handler.h index 52f9935..a789d38 100644 --- a/chrome/browser/signin/dice_response_handler.h +++ b/chrome/browser/signin/dice_response_handler.h
@@ -13,9 +13,9 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "components/keyed_service/core/keyed_service.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/signin_header_helper.h" +#include "components/signin/public/base/account_consistency_method.h" #include "google_apis/gaia/gaia_auth_consumer.h" class AboutSigninInternals;
diff --git a/chrome/browser/signin/dice_response_handler_unittest.cc b/chrome/browser/signin/dice_response_handler_unittest.cc index fea8852..d41a153 100644 --- a/chrome/browser/signin/dice_response_handler_unittest.cc +++ b/chrome/browser/signin/dice_response_handler_unittest.cc
@@ -18,12 +18,12 @@ #include "base/time/time.h" #include "chrome/test/base/testing_profile.h" #include "components/signin/core/browser/about_signin_internals.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/dice_account_reconcilor_delegate.h" #include "components/signin/core/browser/signin_error_controller.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/sync_preferences/testing_pref_service_syncable.h"
diff --git a/chrome/browser/signin/dice_tab_helper.cc b/chrome/browser/signin/dice_tab_helper.cc index 0db0b54e..bd5af69 100644 --- a/chrome/browser/signin/dice_tab_helper.cc +++ b/chrome/browser/signin/dice_tab_helper.cc
@@ -9,7 +9,7 @@ #include "chrome/browser/signin/dice_tab_helper.h" #include "chrome/browser/signin/signin_util.h" #include "chrome/browser/ui/browser_finder.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h"
diff --git a/chrome/browser/signin/dice_tab_helper.h b/chrome/browser/signin/dice_tab_helper.h index d81dfa4..3682b16b 100644 --- a/chrome/browser/signin/dice_tab_helper.h +++ b/chrome/browser/signin/dice_tab_helper.h
@@ -6,7 +6,7 @@ #define CHROME_BROWSER_SIGNIN_DICE_TAB_HELPER_H_ #include "base/macros.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h"
diff --git a/chrome/browser/signin/dice_tab_helper_unittest.cc b/chrome/browser/signin/dice_tab_helper_unittest.cc index b7060c9..e848db1 100644 --- a/chrome/browser/signin/dice_tab_helper_unittest.cc +++ b/chrome/browser/signin/dice_tab_helper_unittest.cc
@@ -8,7 +8,7 @@ #include "base/test/metrics/user_action_tester.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "content/public/test/navigation_simulator.h" #include "content/public/test/test_renderer_host.h" #include "google_apis/gaia/gaia_urls.h"
diff --git a/chrome/browser/signin/force_signin_verifier.cc b/chrome/browser/signin/force_signin_verifier.cc index 61b80b6..5c65ce6b 100644 --- a/chrome/browser/signin/force_signin_verifier.cc +++ b/chrome/browser/signin/force_signin_verifier.cc
@@ -10,7 +10,7 @@ #include "base/metrics/histogram_macros.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/access_token_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h"
diff --git a/chrome/browser/signin/identity_manager_factory.cc b/chrome/browser/signin/identity_manager_factory.cc index 75fdaaa..a99c03dc 100644 --- a/chrome/browser/signin/identity_manager_factory.cc +++ b/chrome/browser/signin/identity_manager_factory.cc
@@ -20,12 +20,17 @@ #include "components/pref_registry/pref_registry_syncable.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" +#include "components/signin/core/browser/webdata/token_web_data.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_manager_builder.h" #include "content/public/browser/network_service_instance.h" #if !defined(OS_ANDROID) +#include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/web_data_service_factory.h" +#include "components/content_settings/core/browser/cookie_settings.h" +#include "components/keyed_service/core/service_access_type.h" +#include "components/signin/core/browser/cookie_settings_util.h" #include "components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.h" #endif @@ -35,6 +40,11 @@ #include "chromeos/components/account_manager/account_manager_factory.h" #endif +#if defined(OS_WIN) +#include "base/bind.h" +#include "chrome/browser/signin/signin_util_win.h" +#endif + namespace { std::unique_ptr<AccountTrackerService> BuildAccountTrackerService( @@ -114,6 +124,14 @@ params.pref_service = profile->GetPrefs(); params.signin_client = ChromeSigninClientFactory::GetForProfile(profile); +#if !defined(OS_ANDROID) + params.delete_signin_cookies_on_exit = + signin::SettingsDeleteSigninCookiesOnExit( + CookieSettingsFactory::GetForProfile(profile).get()); + params.token_web_data = WebDataServiceFactory::GetTokenWebDataForProfile( + profile, ServiceAccessType::EXPLICIT_ACCESS); +#endif + #if defined(OS_CHROMEOS) chromeos::AccountManagerFactory* factory = g_browser_process->platform_part()->GetAccountManagerFactory(); @@ -125,12 +143,24 @@ !chromeos::ProfileHelper::IsLockScreenAppProfile(profile); #endif +#if defined(OS_WIN) + params.reauth_callback = + base::BindRepeating(&signin_util::ReauthWithCredentialProviderIfPossible, + base::Unretained(profile)); +#endif + params.token_service = ProfileOAuth2TokenServiceBuilder::BuildInstanceFor( context, params.pref_service, params.account_tracker_service.get(), params.network_connection_tracker, params.account_consistency, #if defined(OS_CHROMEOS) params.account_manager, params.is_regular_profile, #endif +#if !defined(OS_ANDROID) + params.delete_signin_cookies_on_exit, params.token_web_data, +#endif +#if defined(OS_WIN) + params.reauth_callback, +#endif params.signin_client); std::unique_ptr<identity::IdentityManager> identity_manager =
diff --git a/chrome/browser/signin/mirror_browsertest.cc b/chrome/browser/signin/mirror_browsertest.cc index 1ca7b7b..90ecc8d 100644 --- a/chrome/browser/signin/mirror_browsertest.cc +++ b/chrome/browser/signin/mirror_browsertest.cc
@@ -32,7 +32,7 @@ #include "components/prefs/pref_service.h" #include "components/signin/core/browser/dice_header_helper.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "content/public/common/url_loader_throttle.h" #include "google_apis/gaia/gaia_urls.h" #include "net/dns/mock_host_resolver.h"
diff --git a/chrome/browser/signin/process_dice_header_delegate_impl.h b/chrome/browser/signin/process_dice_header_delegate_impl.h index 4c93997..a7e487be 100644 --- a/chrome/browser/signin/process_dice_header_delegate_impl.h +++ b/chrome/browser/signin/process_dice_header_delegate_impl.h
@@ -12,7 +12,7 @@ #include "base/callback_forward.h" #include "base/macros.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/browser/web_contents_observer.h" namespace content {
diff --git a/chrome/browser/signin/process_dice_header_delegate_impl_unittest.cc b/chrome/browser/signin/process_dice_header_delegate_impl_unittest.cc index 1430d87..f3466bb 100644 --- a/chrome/browser/signin/process_dice_header_delegate_impl_unittest.cc +++ b/chrome/browser/signin/process_dice_header_delegate_impl_unittest.cc
@@ -12,7 +12,7 @@ #include "base/bind_helpers.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "content/public/browser/web_contents.h"
diff --git a/chrome/browser/signin/profile_oauth2_token_service_builder.cc b/chrome/browser/signin/profile_oauth2_token_service_builder.cc index a21a90c..b97e422c 100644 --- a/chrome/browser/signin/profile_oauth2_token_service_builder.cc +++ b/chrome/browser/signin/profile_oauth2_token_service_builder.cc
@@ -8,22 +8,17 @@ #include <string> #include <utility> -#include "base/bind.h" -#include "base/callback.h" #include "chrome/browser/profiles/profile.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/device_id_helper.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/device_id_helper.h" +#include "components/signin/public/base/signin_client.h" #if defined(OS_ANDROID) #include "components/signin/core/browser/oauth2_token_service_delegate_android.h" #else -#include "chrome/browser/content_settings/cookie_settings_factory.h" -#include "chrome/browser/web_data_service_factory.h" -#include "components/content_settings/core/browser/cookie_settings.h" -#include "components/signin/core/browser/cookie_settings_util.h" #include "components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.h" +#include "components/signin/core/browser/webdata/token_web_data.h" #endif #if defined(OS_CHROMEOS) @@ -33,10 +28,6 @@ #include "components/user_manager/user_manager.h" #endif // defined(OS_CHROMEOS) -#if defined(OS_WIN) -#include "chrome/browser/signin/signin_util_win.h" -#endif - namespace { #if defined(OS_ANDROID) @@ -82,27 +73,30 @@ Profile* profile, AccountTrackerService* account_tracker_service, signin::AccountConsistencyMethod account_consistency, + bool delete_signin_cookies_on_exit, + scoped_refptr<TokenWebData> token_web_data, SigninClient* signin_client, +#if defined(OS_WIN) + MutableProfileOAuth2TokenServiceDelegate::FixRequestErrorCallback + reauth_callback, +#endif network::NetworkConnectionTracker* network_connection_tracker) { // When signin cookies are cleared on exit and Dice is enabled, all tokens // should also be cleared. bool revoke_all_tokens_on_load = (account_consistency == signin::AccountConsistencyMethod::kDice) && - signin::SettingsDeleteSigninCookiesOnExit( - CookieSettingsFactory::GetForProfile(profile).get()); + delete_signin_cookies_on_exit; return std::make_unique<MutableProfileOAuth2TokenServiceDelegate>( signin_client, account_tracker_service, network_connection_tracker, - WebDataServiceFactory::GetTokenWebDataForProfile( - profile, ServiceAccessType::EXPLICIT_ACCESS), - account_consistency, revoke_all_tokens_on_load, + token_web_data, account_consistency, revoke_all_tokens_on_load, CanRevokeCredentials(profile), #if defined(OS_WIN) - base::BindRepeating(&signin_util::ReauthWithCredentialProviderIfPossible, - base::Unretained(profile))); + reauth_callback #else - MutableProfileOAuth2TokenServiceDelegate::FixRequestErrorCallback()); + MutableProfileOAuth2TokenServiceDelegate::FixRequestErrorCallback() #endif // defined(OS_WIN) + ); } #endif // !defined(OS_ANDROID) @@ -115,6 +109,14 @@ chromeos::AccountManager* account_manager, bool is_regular_profile, #endif +#if !defined(OS_ANDROID) + bool delete_signin_cookies_on_exit, + scoped_refptr<TokenWebData> token_web_data, +#endif +#if defined(OS_WIN) + MutableProfileOAuth2TokenServiceDelegate::FixRequestErrorCallback + reauth_callback, +#endif network::NetworkConnectionTracker* network_connection_tracker) { #if defined(OS_ANDROID) return CreateAndroidOAuthDelegate(account_tracker_service); @@ -131,9 +133,14 @@ // 1. On all platforms other than Android and Chrome OS. // 2. On Chrome OS, if Account Manager has not been switched on yet // (chromeos::switches::IsAccountManagerEnabled). - return CreateMutableProfileOAuthDelegate(profile, account_tracker_service, - account_consistency, signin_client, - network_connection_tracker); + return CreateMutableProfileOAuthDelegate( + profile, account_tracker_service, account_consistency, + delete_signin_cookies_on_exit, token_web_data, signin_client, +#if defined(OS_WIN) + reauth_callback, +#endif + network_connection_tracker); + #endif // !defined(OS_ANDROID) } @@ -151,6 +158,14 @@ chromeos::AccountManager* account_manager, bool is_regular_profile, #endif +#if !defined(OS_ANDROID) + bool delete_signin_cookies_on_exit, + scoped_refptr<TokenWebData> token_web_data, +#endif +#if defined(OS_WIN) + MutableProfileOAuth2TokenServiceDelegate::FixRequestErrorCallback + reauth_callback, +#endif SigninClient* signin_client) { Profile* profile = static_cast<Profile*>(context); @@ -165,10 +180,16 @@ return std::make_unique<ProfileOAuth2TokenService>( pref_service, - CreateOAuth2TokenServiceDelegate(profile, account_tracker_service, - account_consistency, signin_client, + CreateOAuth2TokenServiceDelegate( + profile, account_tracker_service, account_consistency, signin_client, #if defined(OS_CHROMEOS) - account_manager, is_regular_profile, + account_manager, is_regular_profile, #endif - network_connection_tracker)); +#if !defined(OS_ANDROID) + delete_signin_cookies_on_exit, token_web_data, +#endif +#if defined(OS_WIN) + reauth_callback, +#endif + network_connection_tracker)); }
diff --git a/chrome/browser/signin/profile_oauth2_token_service_builder.h b/chrome/browser/signin/profile_oauth2_token_service_builder.h index f6b7584..9e484ffd 100644 --- a/chrome/browser/signin/profile_oauth2_token_service_builder.h +++ b/chrome/browser/signin/profile_oauth2_token_service_builder.h
@@ -7,13 +7,19 @@ #include <memory> +#include "base/memory/scoped_refptr.h" #include "build/build_config.h" +#if defined(OS_WIN) +#include "components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.h" +#endif + class AccountTrackerService; class IdentityManagerFactory; class PrefService; class ProfileOAuth2TokenService; class SigninClient; +class TokenWebData; namespace signin { enum class AccountConsistencyMethod; @@ -46,6 +52,14 @@ chromeos::AccountManager* account_manager, bool is_regular_profile, #endif +#if !defined(OS_ANDROID) + bool delete_signin_cookies_on_exit, + scoped_refptr<TokenWebData> token_web_data, +#endif +#if defined(OS_WIN) + MutableProfileOAuth2TokenServiceDelegate::FixRequestErrorCallback + reauth_callback, +#endif SigninClient* signin_client); friend IdentityManagerFactory;
diff --git a/chrome/browser/signin/scoped_account_consistency.cc b/chrome/browser/signin/scoped_account_consistency.cc index 884e39a..86daa94 100644 --- a/chrome/browser/signin/scoped_account_consistency.cc +++ b/chrome/browser/signin/scoped_account_consistency.cc
@@ -11,7 +11,7 @@ #include "base/feature_list.h" #include "base/logging.h" #include "chrome/browser/signin/account_consistency_mode_manager.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" using signin::AccountConsistencyMethod;
diff --git a/chrome/browser/signin/scoped_account_consistency.h b/chrome/browser/signin/scoped_account_consistency.h index 06d09a6a..f9886d2f 100644 --- a/chrome/browser/signin/scoped_account_consistency.h +++ b/chrome/browser/signin/scoped_account_consistency.h
@@ -9,7 +9,7 @@ #include "base/macros.h" #include "base/test/scoped_feature_list.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" // Changes the account consistency method while it is in scope. Useful for // tests.
diff --git a/chrome/browser/signin/signin_error_controller_factory.cc b/chrome/browser/signin/signin_error_controller_factory.cc index 40c3943..f8d8be0 100644 --- a/chrome/browser/signin/signin_error_controller_factory.cc +++ b/chrome/browser/signin/signin_error_controller_factory.cc
@@ -9,7 +9,7 @@ #include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" SigninErrorControllerFactory::SigninErrorControllerFactory() : BrowserContextKeyedServiceFactory(
diff --git a/chrome/browser/signin/signin_error_notifier_ash.cc b/chrome/browser/signin/signin_error_notifier_ash.cc index bdde43d..529fe62 100644 --- a/chrome/browser/signin/signin_error_notifier_ash.cc +++ b/chrome/browser/signin/signin_error_notifier_ash.cc
@@ -39,6 +39,7 @@ #include "components/account_id/account_id.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/user_manager/user_manager.h" +#include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/message_center/public/cpp/notification.h" @@ -220,7 +221,7 @@ &SigninErrorNotifier:: HandleSecondaryAccountReauthNotificationClick, weak_factory_.GetWeakPtr())), - ash::kNotificationSettingsIcon, + vector_icons::kSettingsIcon, message_center::SystemNotificationWarningLevel::NORMAL); notification->SetSystemPriority();
diff --git a/chrome/browser/signin/signin_global_error.cc b/chrome/browser/signin/signin_global_error.cc index e849ee89..9034999 100644 --- a/chrome/browser/signin/signin_global_error.cc +++ b/chrome/browser/signin/signin_global_error.cc
@@ -21,9 +21,9 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "net/base/url_util.h" #include "ui/base/l10n/l10n_util.h"
diff --git a/chrome/browser/signin/signin_manager_android_wrapper.cc b/chrome/browser/signin/signin_manager_android_wrapper.cc index 8270d61..fc64845a 100644 --- a/chrome/browser/signin/signin_manager_android_wrapper.cc +++ b/chrome/browser/signin/signin_manager_android_wrapper.cc
@@ -6,8 +6,11 @@ SigninManagerAndroidWrapper::SigninManagerAndroidWrapper( Profile* profile, - identity::IdentityManager* identity_manager) - : signin_manager_android_(profile, identity_manager) {} + identity::IdentityManager* identity_manager, + std::unique_ptr<SigninManagerDelegate> signin_manager_delegate) + : signin_manager_android_(profile, + identity_manager, + std::move(signin_manager_delegate)) {} SigninManagerAndroidWrapper::~SigninManagerAndroidWrapper() {}
diff --git a/chrome/browser/signin/signin_manager_android_wrapper.h b/chrome/browser/signin/signin_manager_android_wrapper.h index b5372cff..8589a75 100644 --- a/chrome/browser/signin/signin_manager_android_wrapper.h +++ b/chrome/browser/signin/signin_manager_android_wrapper.h
@@ -15,8 +15,10 @@ class SigninManagerAndroidWrapper : public KeyedService { public: // initializes the member signin_manager_android_ and keeps ownership. - SigninManagerAndroidWrapper(Profile* profile, - identity::IdentityManager* identity_manager); + SigninManagerAndroidWrapper( + Profile* profile, + identity::IdentityManager* identity_manager, + std::unique_ptr<SigninManagerDelegate> signin_manager_delegate); ~SigninManagerAndroidWrapper() override;
diff --git a/chrome/browser/signin/signin_manager_android_wrapper_factory.cc b/chrome/browser/signin/signin_manager_android_wrapper_factory.cc index 40e55f0..895bee2 100644 --- a/chrome/browser/signin/signin_manager_android_wrapper_factory.cc +++ b/chrome/browser/signin/signin_manager_android_wrapper_factory.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/signin/signin_manager_android_wrapper_factory.h" +#include "chrome/browser/android/signin/chrome_signin_manager_delegate.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" @@ -35,6 +36,10 @@ KeyedService* SigninManagerAndroidWrapperFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - return new SigninManagerAndroidWrapper( - profile, IdentityManagerFactory::GetForProfile(profile)); + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); + auto signin_manager_delegate = + std::make_unique<ChromeSigninManagerDelegate>(); + + return new SigninManagerAndroidWrapper(profile, identity_manager, + std::move(signin_manager_delegate)); }
diff --git a/chrome/browser/signin/signin_profile_attributes_updater.cc b/chrome/browser/signin/signin_profile_attributes_updater.cc index 00a7312f..3078514 100644 --- a/chrome/browser/signin/signin_profile_attributes_updater.cc +++ b/chrome/browser/signin/signin_profile_attributes_updater.cc
@@ -10,7 +10,7 @@ #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/signin/signin_util.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" SigninProfileAttributesUpdater::SigninProfileAttributesUpdater( identity::IdentityManager* identity_manager,
diff --git a/chrome/browser/signin/signin_promo.cc b/chrome/browser/signin/signin_promo.cc index 31a1b7aba..d296f04 100644 --- a/chrome/browser/signin/signin_promo.cc +++ b/chrome/browser/signin/signin_promo.cc
@@ -17,7 +17,7 @@ #include "components/google/core/common/google_util.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "google_apis/gaia/gaia_urls.h" #include "net/base/url_util.h" #include "url/gurl.h"
diff --git a/chrome/browser/signin/signin_promo.h b/chrome/browser/signin/signin_promo.h index cfde093..d8e7a46 100644 --- a/chrome/browser/signin/signin_promo.h +++ b/chrome/browser/signin/signin_promo.h
@@ -8,7 +8,7 @@ #include <string> #include "build/build_config.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" class GURL;
diff --git a/chrome/browser/signin/signin_promo_util.cc b/chrome/browser/signin/signin_promo_util.cc index bea38114..612f981 100644 --- a/chrome/browser/signin/signin_promo_util.cc +++ b/chrome/browser/signin/signin_promo_util.cc
@@ -7,7 +7,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" #include "net/base/network_change_notifier.h"
diff --git a/chrome/browser/signin/signin_ui_util.cc b/chrome/browser/signin/signin_ui_util.cc index 423b9f1..77df17d 100644 --- a/chrome/browser/signin/signin_ui_util.cc +++ b/chrome/browser/signin/signin_ui_util.cc
@@ -21,10 +21,10 @@ #include "chrome/browser/ui/chrome_pages.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/identity_utils.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/identity_manager.h" +#include "components/signin/public/identity_manager/identity_utils.h" #include "components/user_manager/user_manager.h" #include "third_party/re2/src/re2/re2.h" #include "ui/gfx/font_list.h"
diff --git a/chrome/browser/signin/signin_ui_util.h b/chrome/browser/signin/signin_ui_util.h index e593654..0ab7f7f8 100644 --- a/chrome/browser/signin/signin_ui_util.h +++ b/chrome/browser/signin/signin_ui_util.h
@@ -12,9 +12,9 @@ #include "base/strings/string16.h" #include "build/buildflag.h" #include "chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/identity_manager/account_info.h" class Profile; class Browser;
diff --git a/chrome/browser/signin/signin_ui_util_unittest.cc b/chrome/browser/signin/signin_ui_util_unittest.cc index 0dc62da..2ef02f7 100644 --- a/chrome/browser/signin/signin_ui_util_unittest.cc +++ b/chrome/browser/signin/signin_ui_util_unittest.cc
@@ -15,9 +15,9 @@ #include "chrome/browser/signin/signin_promo.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "components/google/core/browser/google_url_tracker.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h"
diff --git a/chrome/browser/signin/signin_util.cc b/chrome/browser/signin/signin_util.cc index 50cfb0d..cb67058f5 100644 --- a/chrome/browser/signin/signin_util.cc +++ b/chrome/browser/signin/signin_util.cc
@@ -26,10 +26,10 @@ #include "chrome/grit/generated_resources.h" #include "components/google/core/common/google_util.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/identity_utils.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" +#include "components/signin/public/identity_manager/identity_utils.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" #include "google_apis/gaia/gaia_auth_util.h" #include "ui/base/l10n/l10n_util.h"
diff --git a/chrome/browser/signin/signin_util_win.cc b/chrome/browser/signin/signin_util_win.cc index 7bc241e..13b63e5 100644 --- a/chrome/browser/signin/signin_util_win.cc +++ b/chrome/browser/signin/signin_util_win.cc
@@ -28,8 +28,8 @@ #include "components/os_crypt/os_crypt.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/about_signin_internals.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h"
diff --git a/chrome/browser/signin/signin_util_win_browsertest.cc b/chrome/browser/signin/signin_util_win_browsertest.cc index 8737cba..b9196b1 100644 --- a/chrome/browser/signin/signin_util_win_browsertest.cc +++ b/chrome/browser/signin/signin_util_win_browsertest.cc
@@ -26,7 +26,7 @@ #include "chrome/test/base/testing_browser_process.h" #include "components/os_crypt/os_crypt.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/signin/public/identity_manager/primary_account_mutator.h"
diff --git a/chrome/browser/signin/test_signin_client_builder.cc b/chrome/browser/signin/test_signin_client_builder.cc index 5f84d36..9795a5e 100644 --- a/chrome/browser/signin/test_signin_client_builder.cc +++ b/chrome/browser/signin/test_signin_client_builder.cc
@@ -5,7 +5,7 @@ #include "chrome/browser/signin/test_signin_client_builder.h" #include "chrome/browser/profiles/profile.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/test_signin_client.h" namespace signin {
diff --git a/chrome/browser/site_isolation/site_details.cc b/chrome/browser/site_isolation/site_details.cc index fbe0b38..5759ed8 100644 --- a/chrome/browser/site_isolation/site_details.cc +++ b/chrome/browser/site_isolation/site_details.cc
@@ -17,47 +17,11 @@ #include "extensions/common/extension.h" #endif -using content::BrowserContext; using content::BrowserThread; using content::RenderFrameHost; -using content::RenderProcessHost; -using content::SiteInstance; -using content::WebContents; namespace { -bool ShouldIsolate(BrowserContext* browser_context, - const IsolationScenario& scenario, - const GURL& site) { - switch (scenario.policy) { - case ISOLATE_NOTHING: - return false; - case ISOLATE_ALL_SITES: - return true; - case ISOLATE_HTTPS_SITES: - // Note: For estimation purposes "isolate https sites" is really - // implemented as "isolate non-http sites". This means that, for example, - // the New Tab Page gets counted as two processes under this policy, and - // extensions are isolated as well. - return !site.SchemeIs(url::kHttpScheme); - case ISOLATE_EXTENSIONS: { -#if !BUILDFLAG(ENABLE_EXTENSIONS) - return false; -#else - if (!site.SchemeIs(extensions::kExtensionScheme)) - return false; - extensions::ExtensionRegistry* registry = - extensions::ExtensionRegistry::Get(browser_context); - const extensions::Extension* extension = - registry->enabled_extensions().GetExtensionOrAppByURL(site); - return extension && !extension->is_hosted_app(); -#endif - } - } - NOTREACHED(); - return true; -} - content::SiteInstance* DeterminePrimarySiteInstance( content::SiteInstance* site_instance, SiteData* site_data) { @@ -83,45 +47,21 @@ } // namespace -ScenarioBrowsingInstanceInfo::ScenarioBrowsingInstanceInfo() {} - -ScenarioBrowsingInstanceInfo::ScenarioBrowsingInstanceInfo( - const ScenarioBrowsingInstanceInfo& other) = default; - -ScenarioBrowsingInstanceInfo::~ScenarioBrowsingInstanceInfo() {} - -BrowsingInstanceInfo::BrowsingInstanceInfo() {} - +BrowsingInstanceInfo::BrowsingInstanceInfo() = default; BrowsingInstanceInfo::BrowsingInstanceInfo(const BrowsingInstanceInfo& other) = default; +BrowsingInstanceInfo::~BrowsingInstanceInfo() = default; -BrowsingInstanceInfo::~BrowsingInstanceInfo() {} - -IsolationScenario::IsolationScenario() {} - -IsolationScenario::IsolationScenario(const IsolationScenario& other) = default; - -IsolationScenario::~IsolationScenario() {} - -SiteData::SiteData() { - for (int i = 0; i <= ISOLATION_SCENARIO_LAST; i++) - scenarios[i].policy = static_cast<IsolationScenarioType>(i); -} - +SiteData::SiteData() = default; SiteData::SiteData(const SiteData& other) = default; +SiteData::~SiteData() = default; -SiteData::~SiteData() {} - -SiteDetails::SiteDetails() {} - -SiteDetails::~SiteDetails() {} - -void SiteDetails::CollectSiteInfo(WebContents* contents, SiteData* site_data) { +void SiteDetails::CollectSiteInfo(content::WebContents* contents, + SiteData* site_data) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - BrowserContext* context = contents->GetBrowserContext(); // The primary should be the same for the whole tab. - SiteInstance* primary = + content::SiteInstance* primary = DeterminePrimarySiteInstance(contents->GetSiteInstance(), site_data); BrowsingInstanceInfo* browsing_instance = &site_data->browsing_instances[primary]; @@ -137,76 +77,19 @@ site_data->out_of_process_frames++; } } - - // Now keep track of how many sites we have in this BrowsingInstance (and - // overall), including sites in iframes. - for (IsolationScenario& scenario : site_data->scenarios) { - std::map<RenderFrameHost*, GURL> frame_urls; - for (RenderFrameHost* frame : contents->GetAllFrames()) { - // Determine the site from the frame's origin, with a fallback to the - // frame's URL. In cases like <iframe sandbox>, we can wind up with an - // http URL but a unique origin. The origin of the resource will still - // determine process placement. - url::Origin origin = frame->GetLastCommittedOrigin(); - GURL site = SiteInstance::GetSiteForURL( - context, - origin.opaque() ? frame->GetLastCommittedURL() : origin.GetURL()); - - bool should_isolate = ShouldIsolate(context, scenario, site); - - // Treat a subframe as part of its parent site if neither needs isolation. - if (!should_isolate && frame->GetParent()) { - GURL parent_site = frame_urls[frame->GetParent()]; - if (!ShouldIsolate(context, scenario, parent_site)) - site = parent_site; - } - - bool process_per_site = - site.is_valid() && - RenderProcessHost::ShouldUseProcessPerSite(context, site); - - // If we don't need a dedicated process, and aren't living in a process- - // per-site process, we are nothing special: collapse our URL to a dummy - // site. - if (!process_per_site && !should_isolate) - site = GURL("http://"); - - // We model process-per-site by only inserting those sites into the first - // browsing instance in which they appear. - if (scenario.all_sites.insert(site).second || !process_per_site) - scenario.browsing_instances[primary->GetId()].sites.insert(site); - - // Record our result in |frame_urls| for use by children. - frame_urls[frame] = site; - } - } } void SiteDetails::UpdateHistograms( const BrowserContextSiteDataMap& site_data_map, int all_renderer_process_count, int non_renderer_process_count) { - // Reports a set of site-based process metrics to UMA. - int process_limit = RenderProcessHost::GetMaxRendererProcessCount(); - // Sum the number of sites and SiteInstances in each BrowserContext and // the total number of out-of-process iframes. - int num_sites[ISOLATION_SCENARIO_LAST + 1] = {}; - int num_isolated_site_instances[ISOLATION_SCENARIO_LAST + 1] = {}; int num_browsing_instances = 0; int num_oopifs = 0; int num_proxies = 0; for (auto& site_data_map_entry : site_data_map) { const SiteData& site_data = site_data_map_entry.second; - for (const IsolationScenario& scenario : site_data.scenarios) { - num_sites[scenario.policy] += scenario.all_sites.size(); - for (auto& entry : scenario.browsing_instances) { - const ScenarioBrowsingInstanceInfo& scenario_browsing_instance_info = - entry.second; - num_isolated_site_instances[scenario.policy] += - scenario_browsing_instance_info.sites.size(); - } - } for (const auto& entry : site_data.browsing_instances) { const BrowsingInstanceInfo& browsing_instance_info = entry.second; UMA_HISTOGRAM_COUNTS_100("SiteIsolation.SiteInstancesPerBrowsingInstance", @@ -219,18 +102,6 @@ num_oopifs += site_data.out_of_process_frames; } - // Predict the number of processes needed when isolating all sites, when - // isolating only HTTPS sites, and when isolating extensions. - int process_count_lower_bound[ISOLATION_SCENARIO_LAST + 1]; - int process_count_upper_bound[ISOLATION_SCENARIO_LAST + 1]; - int process_count_estimate[ISOLATION_SCENARIO_LAST + 1]; - for (int policy = 0; policy <= ISOLATION_SCENARIO_LAST; policy++) { - process_count_lower_bound[policy] = num_sites[policy]; - process_count_upper_bound[policy] = num_sites[policy] + process_limit - 1; - process_count_estimate[policy] = std::min( - num_isolated_site_instances[policy], process_count_upper_bound[policy]); - } - // Just renderer process count: UMA_HISTOGRAM_COUNTS_100("SiteIsolation.CurrentRendererProcessCount", all_renderer_process_count); @@ -238,53 +109,4 @@ num_browsing_instances); UMA_HISTOGRAM_COUNTS_10000("SiteIsolation.ProxyCount", num_proxies); UMA_HISTOGRAM_COUNTS_100("SiteIsolation.OutOfProcessIframes", num_oopifs); - - // ISOLATE_NOTHING metrics. - UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateNothingProcessCountNoLimit", - num_isolated_site_instances[ISOLATE_NOTHING]); - UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateNothingProcessCountLowerBound", - process_count_lower_bound[ISOLATE_NOTHING]); - UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateNothingProcessCountEstimate", - process_count_estimate[ISOLATE_NOTHING]); - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateNothingTotalProcessCountEstimate", - process_count_estimate[ISOLATE_NOTHING] + non_renderer_process_count); - - // ISOLATE_ALL_SITES metrics. - UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateAllSitesProcessCountNoLimit", - num_isolated_site_instances[ISOLATE_ALL_SITES]); - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateAllSitesProcessCountLowerBound", - process_count_lower_bound[ISOLATE_ALL_SITES]); - UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateAllSitesProcessCountEstimate", - process_count_estimate[ISOLATE_ALL_SITES]); - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateAllSitesTotalProcessCountEstimate", - process_count_estimate[ISOLATE_ALL_SITES] + non_renderer_process_count); - - // ISOLATE_HTTPS_SITES metrics. - UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateHttpsSitesProcessCountNoLimit", - num_isolated_site_instances[ISOLATE_HTTPS_SITES]); - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound", - process_count_lower_bound[ISOLATE_HTTPS_SITES]); - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateHttpsSitesProcessCountEstimate", - process_count_estimate[ISOLATE_HTTPS_SITES]); - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateHttpsSitesTotalProcessCountEstimate", - process_count_estimate[ISOLATE_HTTPS_SITES] + non_renderer_process_count); - - // ISOLATE_EXTENSIONS metrics. - UMA_HISTOGRAM_COUNTS_100("SiteIsolation.IsolateExtensionsProcessCountNoLimit", - num_isolated_site_instances[ISOLATE_EXTENSIONS]); - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound", - process_count_lower_bound[ISOLATE_EXTENSIONS]); - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateExtensionsProcessCountEstimate", - process_count_estimate[ISOLATE_EXTENSIONS]); - UMA_HISTOGRAM_COUNTS_100( - "SiteIsolation.IsolateExtensionsTotalProcessCountEstimate", - process_count_estimate[ISOLATE_EXTENSIONS] + non_renderer_process_count); }
diff --git a/chrome/browser/site_isolation/site_details.h b/chrome/browser/site_isolation/site_details.h index dd25fe4..5ebf38f 100644 --- a/chrome/browser/site_isolation/site_details.h +++ b/chrome/browser/site_isolation/site_details.h
@@ -8,24 +8,13 @@ #include <stdint.h> #include <map> +#include <set> #include "base/macros.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" -// Collects information for a browsing instance assuming some alternate -// isolation scenario. -struct ScenarioBrowsingInstanceInfo { - ScenarioBrowsingInstanceInfo(); - ScenarioBrowsingInstanceInfo(const ScenarioBrowsingInstanceInfo& other); - ~ScenarioBrowsingInstanceInfo(); - - std::set<GURL> sites; -}; -using ScenarioBrowsingInstanceMap = - std::map<int32_t, ScenarioBrowsingInstanceInfo>; - // Collects metrics about an actual browsing instance in the current session. struct BrowsingInstanceInfo { BrowsingInstanceInfo(); @@ -38,28 +27,6 @@ using BrowsingInstanceMap = std::map<content::SiteInstance*, BrowsingInstanceInfo>; -// This enum represents various alternative process model policies that we want -// to evaluate. We'll estimate the process cost of each scenario. -enum IsolationScenarioType { - ISOLATE_NOTHING, - ISOLATE_ALL_SITES, - ISOLATE_HTTPS_SITES, - ISOLATE_EXTENSIONS, - ISOLATION_SCENARIO_LAST = ISOLATE_EXTENSIONS -}; - -// Contains the state required to estimate the process count under a particular -// process model. We have one of these per IsolationScenarioType. -struct IsolationScenario { - IsolationScenario(); - IsolationScenario(const IsolationScenario& other); - ~IsolationScenario(); - - IsolationScenarioType policy = ISOLATE_NOTHING; - std::set<GURL> all_sites; - ScenarioBrowsingInstanceMap browsing_instances; -}; - // Information about the sites and SiteInstances in each BrowsingInstance, for // use in estimating the number of processes needed for various process models. struct SiteData { @@ -67,9 +34,6 @@ SiteData(const SiteData& other); ~SiteData(); - // One IsolationScenario object per IsolationScenarioType. - IsolationScenario scenarios[ISOLATION_SCENARIO_LAST + 1]; - // This map groups related SiteInstances together into BrowsingInstances. The // first SiteInstance we see in a BrowsingInstance is designated as the // 'primary' SiteInstance, and becomes the key of this map. @@ -96,9 +60,9 @@ int non_renderer_process_count); private: - // Never needs to be constructed. - SiteDetails(); - ~SiteDetails(); + // Only static methods - never needs to be constructed. + SiteDetails() = delete; + ~SiteDetails() = delete; DISALLOW_COPY_AND_ASSIGN(SiteDetails); };
diff --git a/chrome/browser/site_isolation/site_details_browsertest.cc b/chrome/browser/site_isolation/site_details_browsertest.cc index 17e345e1..2b72774 100644 --- a/chrome/browser/site_isolation/site_details_browsertest.cc +++ b/chrome/browser/site_isolation/site_details_browsertest.cc
@@ -18,6 +18,7 @@ #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/test/metrics/histogram_tester.h" +#include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/metrics/metrics_memory_details.h" @@ -96,16 +97,6 @@ DISALLOW_COPY_AND_ASSIGN(TestMemoryDetails); }; -IsolationScenarioType GetCurrentPolicy() { - if (content::AreAllSitesIsolatedForTesting()) - return ISOLATE_ALL_SITES; -#if BUILDFLAG(ENABLE_EXTENSIONS) - return ISOLATE_EXTENSIONS; -#else - return ISOLATE_NOTHING; -#endif -} - // This matcher takes three other matchers as arguments, and applies one of them // depending on the current site isolation mode. The first applies if no site // isolation mode is active; the second applies under --isolate-extensions mode; @@ -114,24 +105,24 @@ isolate_nothing, isolate_extensions, isolate_all_sites, - GetCurrentPolicy() == ISOLATE_NOTHING - ? std::string("(with oopifs disabled) ") + - PrintToString(isolate_nothing) - : GetCurrentPolicy() == ISOLATE_EXTENSIONS - ? std::string("(under --isolate-extensions) ") + - PrintToString(isolate_extensions) - : std::string("(under --site-per-process) ") + - PrintToString(isolate_all_sites)) { - switch (GetCurrentPolicy()) { - case ISOLATE_NOTHING: - return ExplainMatchResult(isolate_nothing, arg, result_listener); - case ISOLATE_EXTENSIONS: - return ExplainMatchResult(isolate_extensions, arg, result_listener); - case ISOLATE_ALL_SITES: - return ExplainMatchResult(isolate_all_sites, arg, result_listener); - default: - return false; - } +#if defined(OS_ANDROID) + std::string("(with oopifs disabled) ") + + PrintToString(isolate_nothing) +#else + content::AreAllSitesIsolatedForTesting() + ? std::string("(under --site-per-process) ") + + PrintToString(isolate_all_sites) + : std::string("(under --isolate-extensions) ") + + PrintToString(isolate_extensions) +#endif +) { +#if defined(OS_ANDROID) + return ExplainMatchResult(isolate_nothing, arg, result_listener); +#else + return content::AreAllSitesIsolatedForTesting() + ? ExplainMatchResult(isolate_all_sites, arg, result_listener) + : ExplainMatchResult(isolate_extensions, arg, result_listener); +#endif } // Matcher for base::Bucket objects that allows bucket_min to be a matcher. @@ -299,36 +290,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountEstimate"), - HasOneSample(9)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), - HasOneSample(9)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), - HasOneSample(9)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountNoLimit"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(1)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 1, 9)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 0, 14)); @@ -354,36 +315,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountEstimate"), - HasOneSample(7)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), - HasOneSample(7)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), - HasOneSample(7)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountNoLimit"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(1)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 1, 7)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 0, 11)); @@ -408,36 +339,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountEstimate"), - HasOneSample(11)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), - HasOneSample(11)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), - HasOneSample(11)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountEstimate"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound"), - HasOneSample(1)); // TODO(nick): This should be 2. - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountNoLimit"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(2)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(2, 2, 11)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 0, 14)); @@ -461,37 +362,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(3)); - // Could be 11 if subframe processes were reused across BrowsingInstances. - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountEstimate"), - HasOneSample(15)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), - HasOneSample(11)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), - HasOneSample(15)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound"), - HasOneSample(1)); // TODO(nick): This should be 3. - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountNoLimit"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(3)); // For --site-per-process, the total process count will be 12 instead of 15, // because the third tab's subframes (b, c, d) will reuse matching subframe @@ -536,37 +406,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(3)); - // Could be 11 if subframe processes were reused across BrowsingInstances. - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountEstimate"), - HasOneSample(16)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), - HasOneSample(12)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), - HasOneSample(16)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound"), - HasOneSample(1)); // TODO(nick): This should be 3. - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateHttpsSitesProcessCountNoLimit"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(3)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(3, 3, 13)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 0, 21)); @@ -588,18 +427,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(1)); EXPECT_THAT(GetRenderProcessCount(), 1); EXPECT_EQ(0, details->GetOutOfProcessIframeCount()); @@ -625,18 +452,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(3)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(3, 3, 7)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 0, 4)); @@ -654,18 +469,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(3)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(3, 3, 6)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 1, 4)); @@ -680,18 +483,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(3)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(3, 3, 5)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 2, 4)); @@ -705,18 +496,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(4)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(4)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(3, 4, 5)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 3, 4)); @@ -730,18 +509,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(4)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(4)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(3, 4, 4)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 4, 4)); @@ -760,18 +527,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(4)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(4)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(4)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(3, 4, 4)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 2, 2)); @@ -786,18 +541,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(5)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(4)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(5)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(3, 5, 5)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 3, 3)); @@ -814,18 +557,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(3)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(2, 3, 3)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 1, 1)); @@ -840,18 +571,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(4)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(3)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(4)); // There should be four total renderer processes: one for each of the two web // iframes, one for extension3, and one for extension 1's background page. @@ -882,18 +601,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(2)); // TODO(nick): https://crbug.com/512560 Make the number below agree with the // estimates above, which assume consolidation of subframe processes. EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 3, 3)); @@ -918,28 +625,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(1)); - EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 1, 2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountEstimate"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), - HasOneSample(2)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 1, 2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 0, 1)); @@ -950,28 +635,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(1)); - EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 1, 2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountEstimate"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), - HasOneSample(2)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 1, 2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 0, 1)); @@ -987,28 +650,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(1)); - EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 1, 2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountEstimate"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), - HasOneSample(2)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 1, 2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 0, 1)); @@ -1019,28 +660,6 @@ EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), HasOneSample(GetRenderProcessCount())); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateNothingProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountEstimate"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), - HasOneSample(1)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), - HasOneSample(1)); - EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 1, 2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountEstimate"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), - HasOneSample(2)); - EXPECT_THAT(details->uma()->GetAllSamples( - "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), - HasOneSample(2)); EXPECT_THAT(GetRenderProcessCount(), DependingOnPolicy(1, 1, 2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), DependingOnPolicy(0, 0, 1));
diff --git a/chrome/browser/ssl/ssl_browsertest.cc b/chrome/browser/ssl/ssl_browsertest.cc index e1b7888..ab29d39e 100644 --- a/chrome/browser/ssl/ssl_browsertest.cc +++ b/chrome/browser/ssl/ssl_browsertest.cc
@@ -48,6 +48,7 @@ #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_io_data.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ssl/bad_clock_blocking_page.h" #include "chrome/browser/ssl/captive_portal_blocking_page.h" #include "chrome/browser/ssl/cert_report_helper.h" @@ -175,11 +176,22 @@ #if defined(USE_NSS_CERTS) #include "chrome/browser/certificate_manager_model.h" +#include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/net/nss_context.h" +#include "components/user_manager/scoped_user_manager.h" +#include "components/user_manager/user_manager.h" +#include "crypto/scoped_test_nss_db.h" #include "net/cert/nss_cert_database.h" #include "net/cert/x509_util_nss.h" #endif // defined(USE_NSS_CERTS) +#if defined(OS_CHROMEOS) +#include "base/path_service.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chromeos/constants/chromeos_switches.h" +#include "components/session_manager/core/session_manager.h" +#endif // defined(OS_CHROMEOS) + using namespace ssl_test_util; using base::ASCIIToUTF16; @@ -5895,6 +5907,148 @@ EXPECT_FALSE(IsShowingInterstitial(tab)); } +// A test class which prepares two profiles and allows importing certificates +// into their NSS databases. +class SSLUITestCustomCACerts : public SSLUITestNoCert { + public: + SSLUITestCustomCACerts() = default; + ~SSLUITestCustomCACerts() override = default; + + void SetUpCommandLine(base::CommandLine* command_line) override { + SSLUITestNoCert::SetUpCommandLine(command_line); + // Don't require policy for our sessions - this is required so the policy + // code knows not to expect cached policy for the secondary profile. + command_line->AppendSwitchASCII(chromeos::switches::kProfileRequiresPolicy, + "false"); + } + + void SetUpOnMainThread() override { + SSLUITestNoCert::SetUpOnMainThread(); + + profile_1_ = browser()->profile(); + + // Create a second profile. + { + static const char kSecondProfileAccount[] = "profile2@test.com"; + static const char kSecondProfileGaiaId[] = "9876543210"; + static const char kSecondProfileHash[] = "testProfile2"; + + base::FilePath user_data_directory; + base::PathService::Get(chrome::DIR_USER_DATA, &user_data_directory); + session_manager::SessionManager::Get()->CreateSession( + AccountId::FromUserEmailGaiaId(kSecondProfileAccount, + kSecondProfileGaiaId), + kSecondProfileHash, false); + // Set up the secondary profile. + base::FilePath profile_dir = user_data_directory.Append( + chromeos::ProfileHelper::GetUserProfileDir(kSecondProfileHash) + .BaseName()); + profile_2_ = + g_browser_process->profile_manager()->GetProfile(profile_dir); + } + + // Get cert databases for both profiles. + { + base::RunLoop loop; + GetNSSCertDatabaseForProfile( + profile_1_, + base::Bind(&SSLUITestCustomCACerts::DidGetCertDatabase, + base::Unretained(this), &loop, &profile_1_cert_db_)); + loop.Run(); + } + + { + base::RunLoop loop; + GetNSSCertDatabaseForProfile( + profile_2_, + base::Bind(&SSLUITestCustomCACerts::DidGetCertDatabase, + base::Unretained(this), &loop, &profile_2_cert_db_)); + loop.Run(); + } + + // Double-check that the profile initialization was correct and the two + // profiles have distinct NSS databases with distinc NSS public slots. + EXPECT_NE(profile_1_cert_db_, profile_2_cert_db_); + EXPECT_NE(profile_1_cert_db_->GetPublicSlot().get(), + profile_2_cert_db_->GetPublicSlot().get()); + } + + protected: + void ImportCACertAsTrusted(const std::string& cert_file_name, + net::NSSCertDatabase* cert_db) { + base::ScopedAllowBlockingForTesting allow_blocking; + + net::ScopedCERTCertificateList ca_cert_list = + net::CreateCERTCertificateListFromFile( + net::GetTestCertsDirectory(), cert_file_name, + net::X509Certificate::FORMAT_AUTO); + ASSERT_FALSE(ca_cert_list.empty()); + net::NSSCertDatabase::ImportCertFailureList failures; + ASSERT_TRUE(cert_db->ImportCACerts( + ca_cert_list, net::NSSCertDatabase::TRUSTED_SSL, &failures)); + ASSERT_TRUE(failures.empty()); + } + + // The first profile. + Profile* profile_1_; + // The second profile. + Profile* profile_2_; + + // The NSSCertDatabase for |profile_1_|. + net::NSSCertDatabase* profile_1_cert_db_; + + // The NSSCertDatabase for |profile_2_|. + net::NSSCertDatabase* profile_2_cert_db_; + + private: + void DidGetCertDatabase(base::RunLoop* loop, + net::NSSCertDatabase** out_cert_db, + net::NSSCertDatabase* cert_db) { + *out_cert_db = cert_db; + loop->Quit(); + } + + DISALLOW_COPY_AND_ASSIGN(SSLUITestCustomCACerts); +}; + +// Imports a trusted CA certiifcate into a profile's NSS database. +// Verifies that the certificate is trusted in the context of the profile it was +// imported for. +// Verifies that the certificate is *not* trusted in the context of a different +// profile. +IN_PROC_BROWSER_TEST_F(SSLUITestCustomCACerts, + TrustedCertOnlyRespectedInProfileThatOwnsIt) { + ASSERT_TRUE(https_server_.Start()); + + ASSERT_NO_FATAL_FAILURE( + ImportCACertAsTrusted("root_ca_cert.pem", profile_2_cert_db_)); + + // Flush the network service instance so persistent NSS Database changes are + // reflected in the network service. + content::FlushNetworkServiceInstanceForTesting(); + + // The certificate that is trusted in |profile_2_| should not be respected in + // browsers that belong to |profile_1_|. + ui_test_utils::NavigateToURL(browser(), + https_server_.GetURL("/ssl/google.html")); + + WebContents* tab_for_profile_1 = + browser()->tab_strip_model()->GetActiveWebContents(); + WaitForInterstitial(tab_for_profile_1); + CheckAuthenticationBrokenState(tab_for_profile_1, + net::CERT_STATUS_AUTHORITY_INVALID, + AuthState::SHOWING_INTERSTITIAL); + + // The certificate that is trusted in |profile_2_| should be respected in + // browsers that belong to |profile_2_|. + Browser* browser_for_profile_2 = CreateBrowser(profile_2_); + ui_test_utils::NavigateToURL(browser_for_profile_2, + https_server_.GetURL("/ssl/google.html")); + WebContents* tab_for_profile_2 = + browser_for_profile_2->tab_strip_model()->GetActiveWebContents(); + CheckAuthenticatedState(tab_for_profile_2, AuthState::NONE); +} + #endif // defined(OS_CHROMEOS) // Regression test for http://crbug.com/635833 (crash when a window with no
diff --git a/chrome/browser/supervised_user/child_accounts/child_account_service_unittest.cc b/chrome/browser/supervised_user/child_accounts/child_account_service_unittest.cc index 16291a4b..ed90452 100644 --- a/chrome/browser/supervised_user/child_accounts/child_account_service_unittest.cc +++ b/chrome/browser/supervised_user/child_accounts/child_account_service_unittest.cc
@@ -9,8 +9,8 @@ #include "chrome/browser/signin/identity_test_environment_profile_adaptor.h" #include "chrome/browser/supervised_user/child_accounts/child_account_service_factory.h" #include "chrome/test/base/testing_profile.h" -#include "components/signin/core/browser/list_accounts_test_utils.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/list_accounts_test_utils.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/accounts_cookie_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_environment.h"
diff --git a/chrome/browser/supervised_user/supervised_user_browsertest.cc b/chrome/browser/supervised_user/supervised_user_browsertest.cc index 0c1f50d..beeaa01 100644 --- a/chrome/browser/supervised_user/supervised_user_browsertest.cc +++ b/chrome/browser/supervised_user/supervised_user_browsertest.cc
@@ -18,15 +18,11 @@ #include "chrome/browser/supervised_user/supervised_user_constants.h" #include "chrome/browser/supervised_user/supervised_user_interstitial.h" #include "chrome/browser/supervised_user/supervised_user_navigation_observer.h" -#include "chrome/browser/supervised_user/supervised_user_service.h" -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chrome/browser/supervised_user/supervised_user_settings_service.h" #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h" -#include "chrome/browser/ui/browser.h" +#include "chrome/browser/supervised_user/supervised_user_test_base.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/infobars/core/confirm_infobar_delegate.h" #include "components/infobars/core/infobar.h" @@ -46,10 +42,6 @@ #include "net/test/embedded_test_server/embedded_test_server.h" #include "services/network/public/cpp/network_switches.h" -#if defined(OS_CHROMEOS) -#include "chromeos/constants/chromeos_switches.h" -#endif - using content::InterstitialPage; using content::NavigationController; using content::NavigationEntry; @@ -78,7 +70,7 @@ }; // Tests filtering for supervised users. -class SupervisedUserTest : public InProcessBrowserTest { +class SupervisedUserTest : public SupervisedUserTestBase { public: // Indicates whether the interstitial should proceed or not. enum InterstitialAction { @@ -86,8 +78,8 @@ INTERSTITIAL_DONTPROCEED, }; - SupervisedUserTest() : supervised_user_service_(nullptr) {} - ~SupervisedUserTest() override {} + SupervisedUserTest() = default; + ~SupervisedUserTest() override = default; bool ShownPageIsInterstitial(Browser* browser) { WebContents* tab = browser->tab_strip_model()->GetActiveWebContents(); @@ -121,34 +113,16 @@ } protected: - void SetUpOnMainThread() override { - // Set up the SupervisedUserNavigationObserver manually since the profile - // was not supervised when the browser was created. - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - SupervisedUserNavigationObserver::CreateForWebContents(web_contents); - - supervised_user_service_ = - SupervisedUserServiceFactory::GetForProfile(browser()->profile()); - } void SetUpCommandLine(base::CommandLine* command_line) override { - // Enable the test server and remap all URLs to it. - ASSERT_TRUE(embedded_test_server()->Start()); + // Remap all URLs to test server. + ASSERT_TRUE(embedded_test_server()->Started()); std::string host_port = embedded_test_server()->host_port_pair().ToString(); command_line->AppendSwitchASCII(network::switches::kHostResolverRules, "MAP *.example.com " + host_port + "," + "MAP *.new-example.com " + host_port + "," + "MAP *.a.com " + host_port); - - command_line->AppendSwitchASCII(switches::kSupervisedUserId, - supervised_users::kChildAccountSUID); -#if defined(OS_CHROMEOS) - command_line->AppendSwitchASCII( - chromeos::switches::kLoginUser, - "supervised_user@locally-managed.localhost"); - command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "hash"); -#endif + SupervisedUserTestBase::SetUpCommandLine(command_line); } // Acts like a synchronous call to history's QueryHistory. Modified from @@ -168,17 +142,13 @@ &history_task_tracker); run_loop.Run(); // Will go until ...Complete calls Quit. } - - SupervisedUserService* supervised_user_service_; }; // Tests the filter mode in which all sites are blocked by default. class SupervisedUserBlockModeTest : public SupervisedUserTest { public: - void SetUpOnMainThread() override { - SupervisedUserTest::SetUpOnMainThread(); - - Profile* profile = browser()->profile(); + void BlockAllSites() { + Profile* profile = GetPrimaryUserProfile(); SupervisedUserSettingsService* supervised_user_settings_service = SupervisedUserSettingsServiceFactory::GetForKey( profile->GetProfileKey()); @@ -239,6 +209,9 @@ // Navigates to a blocked URL. IN_PROC_BROWSER_TEST_F(SupervisedUserBlockModeTest, SendAccessRequestOnBlockedURL) { + LogInUser(true /*child*/); + BlockAllSites(); + GURL test_url("http://www.example.com/simple.html"); ui_test_utils::NavigateToURL(browser(), test_url); @@ -261,6 +234,9 @@ // Navigates to a blocked URL in a new tab. We expect the tab to be closed // automatically on pressing the "back" button on the interstitial. IN_PROC_BROWSER_TEST_F(SupervisedUserBlockModeTest, OpenBlockedURLInNewTab) { + LogInUser(true /*child*/); + BlockAllSites(); + TabStripModel* tab_strip = browser()->tab_strip_model(); WebContents* prev_tab = tab_strip->GetActiveWebContents(); @@ -288,6 +264,8 @@ // navigation is blocked before it commits). The expected behavior is the same // though: the tab should be closed when going back. IN_PROC_BROWSER_TEST_F(SupervisedUserTest, BlockNewTabAfterLoading) { + LogInUser(true /*child*/); + TabStripModel* tab_strip = browser()->tab_strip_model(); WebContents* prev_tab = tab_strip->GetActiveWebContents(); @@ -305,13 +283,13 @@ // Block the current URL. SupervisedUserSettingsService* supervised_user_settings_service = SupervisedUserSettingsServiceFactory::GetForKey( - browser()->profile()->GetProfileKey()); + GetPrimaryUserProfile()->GetProfileKey()); supervised_user_settings_service->SetLocalSetting( supervised_users::kContentPackDefaultFilteringBehavior, std::make_unique<base::Value>(SupervisedUserURLFilter::BLOCK)); const SupervisedUserURLFilter* filter = - supervised_user_service_->GetURLFilter(); + supervised_user_service()->GetURLFilter(); ASSERT_EQ(SupervisedUserURLFilter::BLOCK, filter->GetFilteringBehaviorForURL(test_url)); @@ -335,6 +313,8 @@ // Tests that we don't end up canceling an interstitial (thereby closing the // whole tab) by attempting to show a second one above it. IN_PROC_BROWSER_TEST_F(SupervisedUserTest, DontShowInterstitialTwice) { + LogInUser(true /*child*/); + TabStripModel* tab_strip = browser()->tab_strip_model(); // Open URL in a new tab. @@ -350,13 +330,13 @@ // Block the current URL. SupervisedUserSettingsService* supervised_user_settings_service = SupervisedUserSettingsServiceFactory::GetForKey( - browser()->profile()->GetProfileKey()); + GetPrimaryUserProfile()->GetProfileKey()); supervised_user_settings_service->SetLocalSetting( supervised_users::kContentPackDefaultFilteringBehavior, std::make_unique<base::Value>(SupervisedUserURLFilter::BLOCK)); const SupervisedUserURLFilter* filter = - supervised_user_service_->GetURLFilter(); + supervised_user_service()->GetURLFilter(); ASSERT_EQ(SupervisedUserURLFilter::BLOCK, filter->GetFilteringBehaviorForURL(test_url)); @@ -368,10 +348,7 @@ // Trigger a no-op change to the site lists, which will notify observers of // the URL filter. - Profile* profile = browser()->profile(); - SupervisedUserService* supervised_user_service = - SupervisedUserServiceFactory::GetForProfile(profile); - supervised_user_service->OnSiteListUpdated(); + supervised_user_service()->OnSiteListUpdated(); content::RunAllPendingInMessageLoop(); EXPECT_EQ(tab, tab_strip->GetActiveWebContents()); @@ -381,6 +358,9 @@ // page. IN_PROC_BROWSER_TEST_F(SupervisedUserBlockModeTest, NavigateFromBlockedPageToBlockedPage) { + LogInUser(true /*child*/); + BlockAllSites(); + GURL test_url("http://www.example.com/simple.html"); ui_test_utils::NavigateToURL(browser(), test_url); @@ -397,17 +377,20 @@ // Tests whether a visit attempt adds a special history entry. IN_PROC_BROWSER_TEST_F(SupervisedUserBlockModeTest, HistoryVisitRecorded) { + LogInUser(true /*child*/); + BlockAllSites(); + GURL allowed_url("http://www.example.com/simple.html"); const SupervisedUserURLFilter* filter = - supervised_user_service_->GetURLFilter(); + supervised_user_service()->GetURLFilter(); // Set the host as allowed. std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); dict->SetKey(allowed_url.host(), base::Value(true)); SupervisedUserSettingsService* supervised_user_settings_service = SupervisedUserSettingsServiceFactory::GetForKey( - browser()->profile()->GetProfileKey()); + GetPrimaryUserProfile()->GetProfileKey()); supervised_user_settings_service->SetLocalSetting( supervised_users::kContentPackManualBehaviorHosts, std::move(dict)); EXPECT_EQ(SupervisedUserURLFilter::ALLOW, @@ -437,7 +420,7 @@ // Query the history entry. history::HistoryService* history_service = - HistoryServiceFactory::GetForProfile(browser()->profile(), + HistoryServiceFactory::GetForProfile(GetPrimaryUserProfile(), ServiceAccessType::EXPLICIT_ACCESS); history::QueryOptions options; history::QueryResults results; @@ -452,9 +435,13 @@ } IN_PROC_BROWSER_TEST_F(SupervisedUserTest, GoBackOnDontProceed) { - // We start out at the initial navigation. + LogInUser(true /*child*/); + WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + // Ensure navigation completes. + WaitForLoadStop(web_contents); + // We start out at the initial navigation. ASSERT_EQ(0, web_contents->GetController().GetCurrentEntryIndex()); GURL test_url("http://www.example.com/simple.html"); @@ -467,12 +454,12 @@ dict->SetKey(test_url.host(), base::Value(false)); SupervisedUserSettingsService* supervised_user_settings_service = SupervisedUserSettingsServiceFactory::GetForKey( - browser()->profile()->GetProfileKey()); + GetPrimaryUserProfile()->GetProfileKey()); supervised_user_settings_service->SetLocalSetting( supervised_users::kContentPackManualBehaviorHosts, std::move(dict)); const SupervisedUserURLFilter* filter = - supervised_user_service_->GetURLFilter(); + supervised_user_service()->GetURLFilter(); ASSERT_EQ(SupervisedUserURLFilter::BLOCK, filter->GetFilteringBehaviorForURL(test_url)); @@ -490,8 +477,12 @@ } IN_PROC_BROWSER_TEST_F(SupervisedUserTest, ClosingBlockedTabDoesNotCrash) { + LogInUser(true /*child*/); + WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + // Ensure navigation completes. + WaitForLoadStop(web_contents); ASSERT_EQ(0, web_contents->GetController().GetCurrentEntryIndex()); GURL test_url("http://www.example.com/simple.html"); @@ -504,12 +495,12 @@ dict->SetKey(test_url.host(), base::Value(false)); SupervisedUserSettingsService* supervised_user_settings_service = SupervisedUserSettingsServiceFactory::GetForKey( - browser()->profile()->GetProfileKey()); + GetPrimaryUserProfile()->GetProfileKey()); supervised_user_settings_service->SetLocalSetting( supervised_users::kContentPackManualBehaviorHosts, std::move(dict)); const SupervisedUserURLFilter* filter = - supervised_user_service_->GetURLFilter(); + supervised_user_service()->GetURLFilter(); ASSERT_EQ(SupervisedUserURLFilter::BLOCK, filter->GetFilteringBehaviorForURL(test_url)); @@ -521,6 +512,8 @@ } IN_PROC_BROWSER_TEST_F(SupervisedUserTest, BlockThenUnblock) { + LogInUser(true /*child*/); + GURL test_url("http://www.example.com/simple.html"); ui_test_utils::NavigateToURL(browser(), test_url); @@ -534,12 +527,12 @@ dict->SetKey(test_url.host(), base::Value(false)); SupervisedUserSettingsService* supervised_user_settings_service = SupervisedUserSettingsServiceFactory::GetForKey( - browser()->profile()->GetProfileKey()); + GetPrimaryUserProfile()->GetProfileKey()); supervised_user_settings_service->SetLocalSetting( supervised_users::kContentPackManualBehaviorHosts, std::move(dict)); const SupervisedUserURLFilter* filter = - supervised_user_service_->GetURLFilter(); + supervised_user_service()->GetURLFilter(); ASSERT_EQ(SupervisedUserURLFilter::BLOCK, filter->GetFilteringBehaviorForURL(test_url)); @@ -564,6 +557,9 @@ } IN_PROC_BROWSER_TEST_F(SupervisedUserBlockModeTest, Unblock) { + LogInUser(true /*child*/); + BlockAllSites(); + GURL test_url("http://www.example.com/simple.html"); ui_test_utils::NavigateToURL(browser(), test_url); @@ -581,12 +577,12 @@ dict->SetKey(test_url.host(), base::Value(true)); SupervisedUserSettingsService* supervised_user_settings_service = SupervisedUserSettingsServiceFactory::GetForKey( - browser()->profile()->GetProfileKey()); + GetPrimaryUserProfile()->GetProfileKey()); supervised_user_settings_service->SetLocalSetting( supervised_users::kContentPackManualBehaviorHosts, std::move(dict)); const SupervisedUserURLFilter* filter = - supervised_user_service_->GetURLFilter(); + supervised_user_service()->GetURLFilter(); EXPECT_EQ(SupervisedUserURLFilter::ALLOW, filter->GetFilteringBehaviorForURL(test_url.GetWithEmptyPath()));
diff --git a/chrome/browser/supervised_user/supervised_user_navigation_throttle_browsertest.cc b/chrome/browser/supervised_user/supervised_user_navigation_throttle_browsertest.cc index 67a49a85..51f5ce38 100644 --- a/chrome/browser/supervised_user/supervised_user_navigation_throttle_browsertest.cc +++ b/chrome/browser/supervised_user/supervised_user_navigation_throttle_browsertest.cc
@@ -11,14 +11,10 @@ #include "base/values.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/supervised_user/supervised_user_constants.h" -#include "chrome/browser/supervised_user/supervised_user_service.h" -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chrome/browser/supervised_user/supervised_user_settings_service.h" #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h" -#include "chrome/browser/ui/browser.h" +#include "chrome/browser/supervised_user/supervised_user_test_base.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" @@ -29,10 +25,6 @@ #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" -#if defined(OS_CHROMEOS) -#include "chromeos/constants/chromeos_switches.h" -#endif - using content::NavigationController; using content::WebContents; @@ -45,13 +37,13 @@ } // namespace -class SupervisedUserNavigationThrottleTest : public InProcessBrowserTest { +class SupervisedUserNavigationThrottleTest : public SupervisedUserTestBase { protected: - SupervisedUserNavigationThrottleTest() {} - ~SupervisedUserNavigationThrottleTest() override {} + SupervisedUserNavigationThrottleTest() = default; + ~SupervisedUserNavigationThrottleTest() override = default; void BlockHost(const std::string& host) { - Profile* profile = browser()->profile(); + Profile* profile = GetPrimaryUserProfile(); SupervisedUserSettingsService* settings_service = SupervisedUserSettingsServiceFactory::GetForKey( profile->GetProfileKey()); @@ -65,7 +57,6 @@ private: void SetUpOnMainThread() override; - void SetUpCommandLine(base::CommandLine* command_line) override; }; bool SupervisedUserNavigationThrottleTest::IsInterstitialBeingShown( @@ -79,28 +70,20 @@ } void SupervisedUserNavigationThrottleTest::SetUpOnMainThread() { + SupervisedUserTestBase::SetUpOnMainThread(); + // Resolve everything to localhost. host_resolver()->AddIPLiteralRule("*", "127.0.0.1", "localhost"); - ASSERT_TRUE(embedded_test_server()->Start()); -} - -void SupervisedUserNavigationThrottleTest::SetUpCommandLine( - base::CommandLine* command_line) { - command_line->AppendSwitchASCII(switches::kSupervisedUserId, - supervised_users::kChildAccountSUID); -#if defined(OS_CHROMEOS) - command_line->AppendSwitchASCII(chromeos::switches::kLoginUser, - "supervised_user@locally-managed.localhost"); - command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "hash"); -#endif + ASSERT_TRUE(embedded_test_server()->Started()); } // Tests that navigating to a blocked page simply fails if there is no // SupervisedUserNavigationObserver. IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationThrottleTest, NoNavigationObserverBlock) { - Profile* profile = browser()->profile(); + LogInUser(true /*child*/); + Profile* profile = GetPrimaryUserProfile(); SupervisedUserSettingsService* supervised_user_settings_service = SupervisedUserSettingsServiceFactory::GetForKey(profile->GetProfileKey()); supervised_user_settings_service->SetLocalSetting( @@ -123,6 +106,8 @@ IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationThrottleTest, BlockMainFrameWithInterstitial) { + LogInUser(true /*child*/); + BlockHost(kExampleHost2); GURL allowed_url = embedded_test_server()->GetURL( @@ -138,6 +123,8 @@ IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationThrottleTest, DontBlockSubFrame) { + LogInUser(true /*child*/); + BlockHost(kExampleHost2); BlockHost(kIframeHost2); @@ -162,16 +149,13 @@ class SupervisedUserNavigationThrottleNotSupervisedTest : public SupervisedUserNavigationThrottleTest { protected: - SupervisedUserNavigationThrottleNotSupervisedTest() {} - ~SupervisedUserNavigationThrottleNotSupervisedTest() override {} - - private: - // Overridden to do nothing, so that the supervised user ID will be empty. - void SetUpCommandLine(base::CommandLine* command_line) override {} + SupervisedUserNavigationThrottleNotSupervisedTest() = default; + ~SupervisedUserNavigationThrottleNotSupervisedTest() override = default; }; IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationThrottleNotSupervisedTest, DontBlock) { + LogInUser(false /*child*/); BlockHost(kExampleHost); GURL blocked_url = embedded_test_server()->GetURL(
diff --git a/chrome/browser/supervised_user/supervised_user_pref_store.cc b/chrome/browser/supervised_user/supervised_user_pref_store.cc index ea022f8..40e9ddf 100644 --- a/chrome/browser/supervised_user/supervised_user_pref_store.cc +++ b/chrome/browser/supervised_user/supervised_user_pref_store.cc
@@ -21,7 +21,7 @@ #include "chrome/common/pref_names.h" #include "components/ntp_snippets/pref_names.h" #include "components/prefs/pref_value_map.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" namespace {
diff --git a/chrome/browser/supervised_user/supervised_user_service_browsertest.cc b/chrome/browser/supervised_user/supervised_user_service_browsertest.cc index 59fdcf2..73466ad 100644 --- a/chrome/browser/supervised_user/supervised_user_service_browsertest.cc +++ b/chrome/browser/supervised_user/supervised_user_service_browsertest.cc
@@ -14,46 +14,22 @@ #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/supervised_user/supervised_user_constants.h" -#include "chrome/browser/supervised_user/supervised_user_service.h" -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chrome/browser/supervised_user/supervised_user_settings_service.h" #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/chrome_switches.h" +#include "chrome/browser/supervised_user/supervised_user_test_base.h" #include "chrome/common/net/safe_search_util.h" #include "chrome/common/pref_names.h" -#include "chrome/test/base/in_process_browser_test.h" #include "components/prefs/pref_service.h" #include "content/public/test/test_utils.h" #include "google_apis/gaia/google_service_auth_error.h" -#if defined(OS_CHROMEOS) -#include "chromeos/constants/chromeos_switches.h" -#endif +using SupervisedUserServiceTestSupervised = SupervisedUserTestBase; -namespace { - -class SupervisedUserServiceTestSupervised : public InProcessBrowserTest { - public: - // content::BrowserTestBase: - void SetUpCommandLine(base::CommandLine* command_line) override { - command_line->AppendSwitchASCII(switches::kSupervisedUserId, - supervised_users::kChildAccountSUID); -#if defined(OS_CHROMEOS) - command_line->AppendSwitchASCII( - chromeos::switches::kLoginUser, - "supervised_user@locally-managed.localhost"); - command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "hash"); -#endif - } -}; - -} // namespace - -typedef InProcessBrowserTest SupervisedUserServiceTest; +// unsupervised tests +using SupervisedUserServiceTest = InProcessBrowserTest; IN_PROC_BROWSER_TEST_F(SupervisedUserServiceTest, LocalPolicies) { - Profile* profile = browser()->profile(); + Profile* profile = SupervisedUserTestBase::GetPrimaryUserProfile(); PrefService* prefs = profile->GetPrefs(); EXPECT_FALSE(prefs->GetBoolean(prefs::kForceGoogleSafeSearch)); EXPECT_EQ(prefs->GetInteger(prefs::kForceYouTubeRestrict), @@ -63,7 +39,7 @@ } IN_PROC_BROWSER_TEST_F(SupervisedUserServiceTest, ProfileName) { - Profile* profile = browser()->profile(); + Profile* profile = SupervisedUserTestBase::GetPrimaryUserProfile(); PrefService* prefs = profile->GetPrefs(); EXPECT_TRUE(prefs->IsUserModifiablePreference(prefs::kProfileName)); @@ -76,7 +52,8 @@ } IN_PROC_BROWSER_TEST_F(SupervisedUserServiceTestSupervised, LocalPolicies) { - Profile* profile = browser()->profile(); + LogInUser(true /*child*/); + Profile* profile = GetPrimaryUserProfile(); PrefService* prefs = profile->GetPrefs(); EXPECT_FALSE(prefs->GetBoolean(prefs::kForceGoogleSafeSearch)); EXPECT_EQ(prefs->GetInteger(prefs::kForceYouTubeRestrict), @@ -87,7 +64,9 @@ } IN_PROC_BROWSER_TEST_F(SupervisedUserServiceTestSupervised, ProfileName) { - Profile* profile = browser()->profile(); + LogInUser(true /*child*/); + + Profile* profile = GetPrimaryUserProfile(); PrefService* prefs = profile->GetPrefs(); std::string original_name = prefs->GetString(prefs::kProfileName);
diff --git a/chrome/browser/supervised_user/supervised_user_test_base.cc b/chrome/browser/supervised_user/supervised_user_test_base.cc new file mode 100644 index 0000000..677ef53b --- /dev/null +++ b/chrome/browser/supervised_user/supervised_user_test_base.cc
@@ -0,0 +1,35 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/supervised_user/supervised_user_test_base.h" + +#include "chrome/browser/chromeos/child_accounts/child_account_test_utils.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/supervised_user/supervised_user_service_factory.h" +#include "chrome/browser/ui/browser_list.h" +#include "components/user_manager/user_manager.h" + +void SupervisedUserTestBase::LogInUser(bool child) { + SkipToLoginScreen(); + const char* services_to_use = + child ? chromeos::test::kChildAccountServiceFlags : kEmptyServices; + LogIn(kAccountId, kAccountPassword, services_to_use); +} + +Browser* SupervisedUserTestBase::browser() { + const BrowserList* active_browser_list = BrowserList::GetInstance(); + if (active_browser_list->empty()) + return nullptr; + Browser* browser = active_browser_list->get(0); + return browser; +} + +Profile* SupervisedUserTestBase::GetPrimaryUserProfile() { + return chromeos::ProfileHelper::Get()->GetProfileByUser( + user_manager::UserManager::Get()->GetPrimaryUser()); +} + +SupervisedUserService* SupervisedUserTestBase::supervised_user_service() { + return SupervisedUserServiceFactory::GetForProfile(GetPrimaryUserProfile()); +}
diff --git a/chrome/browser/supervised_user/supervised_user_test_base.h b/chrome/browser/supervised_user/supervised_user_test_base.h new file mode 100644 index 0000000..34af982 --- /dev/null +++ b/chrome/browser/supervised_user/supervised_user_test_base.h
@@ -0,0 +1,33 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_TEST_BASE_H_ +#define CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_TEST_BASE_H_ + +#include "chrome/browser/chromeos/policy/login_policy_test_base.h" +#include "chrome/browser/supervised_user/supervised_user_service.h" +#include "chrome/browser/ui/browser.h" + +// Base class for child user browser tests. +// Inherit from this class if logging in as child user is required for tests. +// This class inherits from LoginPolicyTestBase because signing in a child +// account requires fetching user policies. +class SupervisedUserTestBase : public policy::LoginPolicyTestBase { + public: + static Profile* GetPrimaryUserProfile(); + + protected: + void LogInUser(bool child); + + // Returns the first browser in the active browser list. + // Hides InProcessBrowserTest::browser() because the browser is only created + // after LogInUser() is called and by then it's too late to set + // InProcessBrowserTest::browser_ because it's a private member. + // Will return null if called before LogInUser(). + static Browser* browser(); + + static SupervisedUserService* supervised_user_service(); +}; + +#endif // CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_TEST_BASE_H_
diff --git a/chrome/browser/sync/profile_sync_service_android.cc b/chrome/browser/sync/profile_sync_service_android.cc index a3cd9142..46e0273 100644 --- a/chrome/browser/sync/profile_sync_service_android.cc +++ b/chrome/browser/sync/profile_sync_service_android.cc
@@ -25,7 +25,7 @@ #include "chrome/browser/sync/session_sync_service_factory.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/strings/grit/components_strings.h" #include "components/sync/base/model_type.h" #include "components/sync/base/user_selectable_type.h"
diff --git a/chrome/browser/sync/profile_sync_service_factory_unittest.cc b/chrome/browser/sync/profile_sync_service_factory_unittest.cc index 2cbbd2a..007fd8c6 100644 --- a/chrome/browser/sync/profile_sync_service_factory_unittest.cc +++ b/chrome/browser/sync/profile_sync_service_factory_unittest.cc
@@ -104,7 +104,12 @@ datatypes.push_back(syncer::FAVICON_TRACKING); datatypes.push_back(syncer::FAVICON_IMAGES); datatypes.push_back(syncer::HISTORY_DELETE_DIRECTIVES); - datatypes.push_back(syncer::PASSWORDS); + if (!base::FeatureList::IsEnabled(switches::kSyncUSSPasswords)) { + // Password store factory is null for testing. For directory + // implementation, a controller was added anyway. For USS, no controller + // gets added, and hence the type isn't available. + datatypes.push_back(syncer::PASSWORDS); + } datatypes.push_back(syncer::PREFERENCES); datatypes.push_back(syncer::PRIORITY_PREFERENCES); datatypes.push_back(syncer::SESSIONS);
diff --git a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc index 213968a..4f7fff99 100644 --- a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc
@@ -24,7 +24,7 @@ #include "components/favicon/core/features.h" #include "components/history/core/browser/history_types.h" #include "components/sessions/core/session_types.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/sync/base/time.h" #include "components/sync/protocol/proto_value_conversions.h"
diff --git a/chrome/browser/sync_file_system/drive_backend/sync_engine.h b/chrome/browser/sync_file_system/drive_backend/sync_engine.h index 7063971..0b5d467 100644 --- a/chrome/browser/sync_file_system/drive_backend/sync_engine.h +++ b/chrome/browser/sync_file_system/drive_backend/sync_engine.h
@@ -20,7 +20,7 @@ #include "chrome/browser/sync_file_system/sync_direction.h" #include "components/drive/drive_notification_observer.h" #include "components/drive/service/drive_service_interface.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "services/network/public/cpp/network_connection_tracker.h" #include "services/network/public/cpp/shared_url_loader_factory.h"
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index e708e6a..c7d46ac 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -497,7 +497,7 @@ "//components/send_tab_to_self", "//components/sessions", "//components/signin/core/browser", - "//components/signin/core/browser:signin_buildflags", + "//components/signin/public/base:signin_buildflags", "//components/signin/public/identity_manager", "//components/spellcheck/browser", "//components/ssl_errors", @@ -962,8 +962,6 @@ "media_router/cloud_services_dialog.h", "media_router/media_cast_mode.cc", "media_router/media_cast_mode.h", - "media_router/media_router_dialog_controller_impl_base.cc", - "media_router/media_router_dialog_controller_impl_base.h", "media_router/media_router_file_dialog.cc", "media_router/media_router_file_dialog.h", "media_router/media_router_ui_base.cc", @@ -2407,19 +2405,15 @@ sources += [ "views/status_icons/concat_menu_model.cc", "views/status_icons/concat_menu_model.h", - "views/status_icons/dbus_menu.cc", - "views/status_icons/dbus_menu.h", - "views/status_icons/dbus_properties_interface.cc", - "views/status_icons/dbus_properties_interface.h", - "views/status_icons/dbus_types.cc", - "views/status_icons/dbus_types.h", "views/status_icons/status_icon_linux_dbus.cc", "views/status_icons/status_icon_linux_dbus.h", - "views/status_icons/success_barrier_callback.cc", - "views/status_icons/success_barrier_callback.h", ] defines += [ "USE_DBUS" ] - deps += [ "//components/dbus:dbus_thread_linux" ] + deps += [ + "//components/dbus/menu", + "//components/dbus/menu:success_barrier_callback", + "//components/dbus/thread_linux", + ] } if (use_x11) { @@ -2820,8 +2814,12 @@ "views/media_router/web_contents_display_observer_view.h", "views/native_file_system/native_file_system_access_icon_view.cc", "views/native_file_system/native_file_system_access_icon_view.h", + "views/native_file_system/native_file_system_directory_access_confirmation_view.cc", + "views/native_file_system/native_file_system_directory_access_confirmation_view.h", "views/native_file_system/native_file_system_permission_view.cc", "views/native_file_system/native_file_system_permission_view.h", + "views/native_file_system/native_file_system_restricted_directory_dialog_view.cc", + "views/native_file_system/native_file_system_restricted_directory_dialog_view.h", "views/native_file_system/native_file_system_ui_helpers.cc", "views/native_file_system/native_file_system_ui_helpers.h", "views/native_file_system/native_file_system_usage_bubble_view.cc", @@ -3946,6 +3944,7 @@ deps += [ "//chrome/test:test_support_ui", "//components/signin/core/browser", + "//components/signin/public/identity_manager", "//components/ukm:test_support", "//components/zoom", "//services/metrics/public/mojom",
diff --git a/chrome/browser/ui/ash/assistant/assistant_context_browsertest.cc b/chrome/browser/ui/ash/assistant/assistant_context_browsertest.cc index 75eb2ab..974333c6 100644 --- a/chrome/browser/ui/ash/assistant/assistant_context_browsertest.cc +++ b/chrome/browser/ui/ash/assistant/assistant_context_browsertest.cc
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/ash/assistant/assistant_client.h" - #include <string> #include <vector> @@ -12,11 +10,13 @@ #include "base/macros.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/browser/ui/ash/assistant/assistant_client.h" #include "chrome/browser/ui/ash/assistant/assistant_context_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/test/browser_test.h" #include "content/public/test/test_utils.h" #include "ui/accessibility/ax_assistant_structure.h"
diff --git a/chrome/browser/ui/ash/chrome_launcher_prefs.cc b/chrome/browser/ui/ash/chrome_launcher_prefs.cc index c9fa2fa..10557f7 100644 --- a/chrome/browser/ui/ash/chrome_launcher_prefs.cc +++ b/chrome/browser/ui/ash/chrome_launcher_prefs.cc
@@ -22,9 +22,13 @@ #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller_util.h" #include "chrome/browser/ui/ash/launcher/launcher_controller_helper.h" +#include "chrome/browser/web_applications/components/app_registrar.h" +#include "chrome/browser/web_applications/components/web_app_helpers.h" +#include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/pref_names.h" +#include "components/crx_file/id_util.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" @@ -184,10 +188,11 @@ // Helper that extracts app list from policy preferences. std::vector<std::string> GetAppsPinnedByPolicy( - const LauncherControllerHelper* helper) { + LauncherControllerHelper* helper) { const PrefService* prefs = helper->profile()->GetPrefs(); std::vector<std::string> result; - const auto* policy_apps = prefs->GetList(prefs::kPolicyPinnedLauncherApps); + const base::Value* policy_apps = + prefs->GetList(prefs::kPolicyPinnedLauncherApps); if (!policy_apps) return result; @@ -198,29 +203,47 @@ arc_app_list_pref ? arc_app_list_pref->GetAppIds() : std::vector<std::string>()); - for (const auto& policy_apps_entry : policy_apps->GetList()) { - const base::Value* app_id_value = - policy_apps_entry.is_dict() - ? policy_apps_entry.FindKeyOfType(kPinnedAppsPrefAppIDKey, - base::Value::Type::STRING) + for (const auto& policy_dict_entry : policy_apps->GetList()) { + const std::string* policy_entry = + policy_dict_entry.is_dict() + ? policy_dict_entry.FindStringKey(kPinnedAppsPrefAppIDKey) : nullptr; - if (!app_id_value) { + + if (!policy_entry) { LOG(ERROR) << "Cannot extract policy app info from prefs."; continue; } - const std::string app_id = app_id_value->GetString(); if (chromeos::DemoSession::Get() && - chromeos::DemoSession::Get()->ShouldIgnorePinPolicy(app_id)) { + chromeos::DemoSession::Get()->ShouldIgnorePinPolicy(*policy_entry)) { continue; } - if (IsAppIdArcPackage(app_id)) { + // Handle Chrome App ids + if (crx_file::id_util::IdIsValid(*policy_entry)) { + result.emplace_back(*policy_entry); + continue; + } + + // Handle Web App ids + const GURL web_app_url(*policy_entry); + if (web_app_url.is_valid()) { + base::Optional<web_app::AppId> web_app_id = + web_app::WebAppProvider::Get(helper->profile()) + ->registrar() + .LookupExternalAppId(web_app_url); + if (web_app_id.has_value()) + result.emplace_back(web_app_id.value()); + continue; + } + + // Handle Arc++ App ids + if (IsAppIdArcPackage(*policy_entry)) { if (!arc_app_list_pref) continue; // We are dealing with package name, not with 32 characters ID. - const std::string& arc_package = app_id; + const std::string& arc_package = *policy_entry; const std::vector<std::string> activities = GetActivitiesForPackage( arc_package, all_arc_app_ids, *arc_app_list_pref); for (const auto& activity : activities) { @@ -228,8 +251,8 @@ ArcAppListPrefs::GetAppId(arc_package, activity); result.emplace_back(arc_app_id); } - } else { - result.emplace_back(app_id); + + continue; } } return result;
diff --git a/chrome/browser/ui/ash/chrome_screenshot_grabber.cc b/chrome/browser/ui/ash/chrome_screenshot_grabber.cc index 392c48b..703edcae 100644 --- a/chrome/browser/ui/ash/chrome_screenshot_grabber.cc +++ b/chrome/browser/ui/ash/chrome_screenshot_grabber.cc
@@ -11,7 +11,6 @@ #include <vector> #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "ash/shell.h" #include "base/base64.h" #include "base/bind.h" @@ -27,6 +26,7 @@ #include "base/task/post_task.h" #include "base/threading/scoped_blocking_call.h" #include "build/build_config.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/file_manager/open_util.h" @@ -683,7 +683,7 @@ optional_field, new ScreenshotGrabberNotificationDelegate(success, GetProfile(), screenshot_path), - ash::kNotificationImageIcon, + kNotificationImageIcon, message_center::SystemNotificationWarningLevel::NORMAL); notification->SetSystemPriority();
diff --git a/chrome/browser/ui/ash/fake_tablet_mode_controller.cc b/chrome/browser/ui/ash/fake_tablet_mode_controller.cc index 61a34145..b789e0f3 100644 --- a/chrome/browser/ui/ash/fake_tablet_mode_controller.cc +++ b/chrome/browser/ui/ash/fake_tablet_mode_controller.cc
@@ -5,16 +5,22 @@ #include "chrome/browser/ui/ash/fake_tablet_mode_controller.h" #include <utility> +#include "base/logging.h" FakeTabletModeController::FakeTabletModeController() = default; FakeTabletModeController::~FakeTabletModeController() = default; -void FakeTabletModeController::SetTabletModeToggleObserver( - ash::TabletModeToggleObserver* observer) { +void FakeTabletModeController::AddObserver(ash::TabletModeObserver* observer) { observer_ = observer; } +void FakeTabletModeController::RemoveObserver( + ash::TabletModeObserver* observer) { + DCHECK_EQ(observer_, observer); + observer_ = nullptr; +} + bool FakeTabletModeController::InTabletMode() const { return enabled_; }
diff --git a/chrome/browser/ui/ash/fake_tablet_mode_controller.h b/chrome/browser/ui/ash/fake_tablet_mode_controller.h index 99c4ae9..e5562ad 100644 --- a/chrome/browser/ui/ash/fake_tablet_mode_controller.h +++ b/chrome/browser/ui/ash/fake_tablet_mode_controller.h
@@ -17,15 +17,15 @@ bool has_observer() const { return !!observer_; } - // ash::mojom::TabletModeController: - void SetTabletModeToggleObserver( - ash::TabletModeToggleObserver* observer) override; + // ash::TabletMode: + void AddObserver(ash::TabletModeObserver* observer) override; + void RemoveObserver(ash::TabletModeObserver* observer) override; bool InTabletMode() const override; void SetEnabledForTest(bool enabled) override; private: bool enabled_ = false; - ash::TabletModeToggleObserver* observer_ = nullptr; + ash::TabletModeObserver* observer_ = nullptr; DISALLOW_COPY_AND_ASSIGN(FakeTabletModeController); };
diff --git a/chrome/browser/ui/ash/launcher/browser_shortcut_launcher_item_controller_browsertest.cc b/chrome/browser/ui/ash/launcher/browser_shortcut_launcher_item_controller_browsertest.cc index 7a72d4e..6e2668f 100644 --- a/chrome/browser/ui/ash/launcher/browser_shortcut_launcher_item_controller_browsertest.cc +++ b/chrome/browser/ui/ash/launcher/browser_shortcut_launcher_item_controller_browsertest.cc
@@ -6,7 +6,6 @@ #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" @@ -79,8 +78,6 @@ // Create and close a window, but don't allow asynchronous teardown to occur. browser1 = CreateBrowser(browser()->profile()); EXPECT_EQ(2U, browser_list->size()); - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(browser1)); CloseBrowserAsynchronously(browser1); EXPECT_EQ(2U, browser_list->size()); // The app menu should not list the browser window while it is closing. @@ -88,6 +85,6 @@ EXPECT_EQ(1U, items.size()); // Now, allow the asynchronous teardown to occur. EXPECT_EQ(2U, browser_list->size()); - observer.Wait(); + ui_test_utils::WaitForBrowserToClose(browser1); EXPECT_EQ(1U, browser_list->size()); }
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc index ceba2b3..a65c07f 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc
@@ -1273,4 +1273,3 @@ else if (ItemTypeIsPinned(old_item) && !ItemTypeIsPinned(item)) RemovePinPosition(profile(), old_item.id); } -
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_browsertest.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_browsertest.cc index 91e3293..06acbece 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_browsertest.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_browsertest.cc
@@ -27,7 +27,6 @@ #include "base/test/bind_test_util.h" #include "base/test/metrics/histogram_tester.h" #include "chrome/browser/apps/platform_apps/app_browsertest_util.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/login/demo_mode/demo_session.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_browsertest.h" @@ -59,8 +58,6 @@ #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/test/base/ui_test_utils.h" #include "components/crx_file/id_util.h" -#include "content/public/browser/notification_service.h" -#include "content/public/browser/notification_source.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "extensions/browser/app_window/app_window.h" @@ -119,22 +116,17 @@ // Close |app_browser| and wait until it's closed. void CloseAppBrowserWindow(Browser* app_browser) { - content::WindowedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::Source<Browser>(app_browser)); app_browser->window()->Close(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(app_browser); } // Close browsers from context menu void CloseBrowserWindow(Browser* browser, LauncherContextMenu* menu, int close_command) { - content::WindowedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(browser)); // Note that event_flag is never used inside function ExecuteCommand. menu->ExecuteCommand(close_command, ui::EventFlags::EF_NONE); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(browser); } int64_t GetDisplayIdForBrowserWindow(BrowserWindow* window) {
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc index cc21f765..b386f94c 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc
@@ -80,6 +80,9 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/web_applications/components/externally_installed_web_app_prefs.h" +#include "chrome/browser/web_applications/components/policy/web_app_policy_constants.h" +#include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" @@ -153,6 +156,10 @@ // pin model with default apps that can affect some tests. constexpr char kDummyAppId[] = "dummyappid_dummyappid_dummyappid"; +// Web App id. +constexpr char kWebAppId[] = "lpikggcgamknpihimepdkohalcnpofed"; +constexpr char kWebAppUrl[] = "https://foo.example/"; + constexpr char kCameraAppName[] = "Camera"; constexpr char kCameraAppPackage[] = "com.google.android.GoogleCameraArc"; constexpr char kCameraAppActivity[] = "com.android.camera.CameraLauncher"; @@ -398,6 +405,18 @@ extensionYoutubeApp_ = Extension::Create( base::FilePath(), Manifest::UNPACKED, manifest, Extension::NO_FLAGS, extension_misc::kYoutubeAppId, &error); + + // Fake Web App. + base::DictionaryValue manifest_web_app; + manifest_web_app.SetString(extensions::manifest_keys::kName, + "Test Web App"); + manifest_web_app.SetString(extensions::manifest_keys::kVersion, "1"); + manifest_web_app.SetInteger(extensions::manifest_keys::kManifestVersion, 2); + manifest_web_app.SetString(extensions::manifest_keys::kDescription, + "For testing"); + web_app_ = Extension::Create(base::FilePath(), Manifest::UNPACKED, + manifest_web_app, Extension::NO_FLAGS, + kWebAppId, &error); } ui::BaseWindow* GetLastActiveWindowForItemController( @@ -763,6 +782,8 @@ result += "Play Store"; } else if (app == crostini::kCrostiniTerminalId) { result += "Terminal"; + } else if (app == web_app_->id()) { + result += "WebApp"; } else { bool arc_app_found = false; for (const auto& arc_app : arc_test_.fake_apps()) { @@ -915,6 +936,7 @@ scoped_refptr<Extension> extensionYoutubeApp_; scoped_refptr<Extension> extension_platform_app_; scoped_refptr<Extension> arc_support_host_; + scoped_refptr<Extension> web_app_; ArcAppTest arc_test_; bool auto_start_arc_test_ = false; @@ -2855,6 +2877,42 @@ EXPECT_EQ("Chrome, App1, App2", GetPinnedAppStatus()); } +TEST_F(ChromeLauncherControllerTest, WebAppPolicy) { + // Simulate one Web App being installed. + web_app::ExternallyInstalledWebAppPrefs web_app_prefs(profile()->GetPrefs()); + web_app_prefs.Insert(GURL(kWebAppUrl), kWebAppId, + web_app::InstallSource::kExternalPolicy); + extension_service_->AddExtension(web_app_.get()); + + // Set the policy value. + base::ListValue policy_value; + AppendPrefValue(&policy_value, kWebAppUrl); + profile()->GetTestingPrefService()->SetManagedPref( + prefs::kPolicyPinnedLauncherApps, + base::Value::ToUniquePtrValue(std::move(policy_value))); + + InitLauncherController(); + + EXPECT_EQ("Chrome, WebApp", GetPinnedAppStatus()); + EXPECT_EQ(AppListControllerDelegate::PIN_FIXED, + GetPinnableForAppID(kWebAppId, profile())); +} + +TEST_F(ChromeLauncherControllerTest, WebAppPolicyNonExistentApp) { + // Set the policy value but don't install an app for it. + base::ListValue policy_value; + AppendPrefValue(&policy_value, kWebAppUrl); + profile()->GetTestingPrefService()->SetManagedPref( + prefs::kPolicyPinnedLauncherApps, + base::Value::ToUniquePtrValue(std::move(policy_value))); + + InitLauncherController(); + + EXPECT_EQ("Chrome", GetPinnedAppStatus()); + EXPECT_EQ(AppListControllerDelegate::PIN_EDITABLE, + GetPinnableForAppID(kWebAppId, profile())); +} + TEST_F(ChromeLauncherControllerTest, UnpinWithUninstall) { extension_service_->AddExtension(extensionGmailApp_.get()); extension_service_->AddExtension(extensionDocApp_.get());
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_util.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_util.cc index 6549f851..4bd1d0855 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_util.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_util.cc
@@ -15,12 +15,70 @@ #include "chrome/browser/ui/ash/multi_user/multi_user_util.h" #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager_helper.h" #include "chrome/browser/ui/browser.h" +#include "chrome/browser/web_applications/components/policy/web_app_policy_manager.h" +#include "chrome/browser/web_applications/components/web_app_helpers.h" +#include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" +namespace { + +// The PinnedLauncherApps policy allows specifying three types of identifiers: +// Chrome App Ids, Android App package names, and Web App install URLs. This +// method returns the value that would have been used in the policy to pin an +// app with |app_id|. +// +// Web App Example: +// Admin installs a Web App using "https://foo.example" as the install URL. +// Chrome generates an app id based on the URL e.g. "abc123". Calling +// GetPolicyValueFromAppId() with "abc123" will return "https://foo.example", +// which is the value that would be specified in the PinnedLauncherApps policy +// to pin this Web App. +// +// Arc++ Example: +// Admin installs an Android App with package name "com.example.foo". Chrome +// generates an app id based on the package e.g. "123abc". Calling +// GetPolicyValueFromAppId() with "123abc" will return "com.example.foo", which +// is the value that would be specified in the PinnedLauncherApps policy to +// pin this Android App. +// +// Chrome App Example: +// Admin installs a Chrome App with "aaa111" as its app id. Calling +// GetPolicyValueFromAppId() with "aaa111" will return "aaa111", which is the +// value that would be specified in the PinnedLauncherApps policy to pin this +// Chrome App. +std::string GetPolicyValueFromAppId(const std::string& app_id, + Profile* profile) { + // Handle Web App ids + // + // WebAppProvider is absent in some cases e.g. Arc++ Kiosk Mode. + if (auto* provider = web_app::WebAppProvider::Get(profile)) { + std::map<web_app::AppId, GURL> installed_apps = + provider->registrar().GetExternallyInstalledApps( + web_app::InstallSource::kExternalPolicy); + auto it = installed_apps.find(app_id); + if (it != installed_apps.end()) + return it->second.spec(); + } + + // Handle Arc++ ids + const ArcAppListPrefs* const arc_prefs = ArcAppListPrefs::Get(profile); + if (arc_prefs) { + std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = + arc_prefs->GetApp(app_id); + if (app_info) + return app_info->package_name; + } + + // Handle Chrome App ids + return app_id; +} + +} // namespace + const extensions::Extension* GetExtensionForAppID(const std::string& app_id, Profile* profile) { return extensions::ExtensionRegistry::Get(profile)->GetExtensionById( @@ -42,39 +100,33 @@ if (base::Contains(kNoPinAppIds, app_id)) return AppListControllerDelegate::NO_PIN; - const base::ListValue* pref = - profile->GetPrefs()->GetList(prefs::kPolicyPinnedLauncherApps); - if (!pref) + const std::string policy_value_for_id = + GetPolicyValueFromAppId(app_id, profile); + + if (chromeos::DemoSession::Get() && + chromeos::DemoSession::Get()->ShouldIgnorePinPolicy( + policy_value_for_id)) { return AppListControllerDelegate::PIN_EDITABLE; - // Pinned ARC apps policy defines the package name of the apps, that must - // be pinned. All the launch activities of any package in policy are pinned. - // In turn the input parameter to this function is app_id, which - // is 32 chars hash. In case of ARC app this is a hash of - // (package name + activity). This means that we must identify the package - // from the hash, and check if this package is pinned by policy. - const ArcAppListPrefs* const arc_prefs = ArcAppListPrefs::Get(profile); - std::string arc_app_package_name; - if (arc_prefs) { - std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = - arc_prefs->GetApp(app_id); - if (app_info) - arc_app_package_name = app_info->package_name; } - for (size_t index = 0; index < pref->GetSize(); ++index) { - const base::DictionaryValue* app = nullptr; - std::string app_id_or_package; - if (pref->GetDictionary(index, &app) && - app->GetString(kPinnedAppsPrefAppIDKey, &app_id_or_package) && - (app_id == app_id_or_package || - arc_app_package_name == app_id_or_package)) { - if (chromeos::DemoSession::Get() && - chromeos::DemoSession::Get()->ShouldIgnorePinPolicy( - app_id_or_package)) { - return AppListControllerDelegate::PIN_EDITABLE; - } + + const base::ListValue* policy_apps = + profile->GetPrefs()->GetList(prefs::kPolicyPinnedLauncherApps); + if (!policy_apps) + return AppListControllerDelegate::PIN_EDITABLE; + + for (const base::Value& policy_dict_entry : *policy_apps) { + if (!policy_dict_entry.is_dict()) + return AppListControllerDelegate::PIN_EDITABLE; + + const std::string* policy_entry = + policy_dict_entry.FindStringKey(kPinnedAppsPrefAppIDKey); + if (!policy_entry) + return AppListControllerDelegate::PIN_EDITABLE; + + if (policy_value_for_id == *policy_entry) return AppListControllerDelegate::PIN_FIXED; - } } + return AppListControllerDelegate::PIN_EDITABLE; }
diff --git a/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc b/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc index 0f39dd8..d01ff88 100644 --- a/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc +++ b/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc
@@ -63,9 +63,9 @@ ash::ShellTestApi shell_test_api; gfx::Rect display_bounds = GetDisplayBounds(browser_window); - gfx::Point start_point = - gfx::Point(display_bounds.width() / 4, - display_bounds.bottom() - ash::kShelfSize / 2); + gfx::Point start_point = gfx::Point( + display_bounds.width() / 4, + display_bounds.bottom() - ash::ShelfConstants::shelf_size() / 2); gfx::Point end_point(start_point); end_point.set_y(10); ui_test_utils::DragEventGenerator generator( @@ -94,7 +94,8 @@ gfx::Rect display_bounds = GetDisplayBounds(browser_window); gfx::Point start_point = gfx::Point(display_bounds.width() / 4, 10); gfx::Point end_point(start_point); - end_point.set_y(display_bounds.bottom() - ash::kShelfSize / 2); + end_point.set_y(display_bounds.bottom() - + ash::ShelfConstants::shelf_size() / 2); ui_test_utils::DragEventGenerator generator( std::make_unique<ui_test_utils::InterpolatedProducer>( start_point, end_point, base::TimeDelta::FromMilliseconds(1000)),
diff --git a/chrome/browser/ui/ash/launcher_page_switches_interactive_uitest.cc b/chrome/browser/ui/ash/launcher_page_switches_interactive_uitest.cc index c1f51b4..bf8f784 100644 --- a/chrome/browser/ui/ash/launcher_page_switches_interactive_uitest.cc +++ b/chrome/browser/ui/ash/launcher_page_switches_interactive_uitest.cc
@@ -8,7 +8,6 @@ #include "ash/public/cpp/test/shell_test_api.h" #include "base/run_loop.h" #include "base/task/post_task.h" -#include "build/build_config.h" #include "chrome/browser/ui/app_list/test/chrome_app_list_test_support.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" @@ -92,13 +91,7 @@ DISALLOW_COPY_AND_ASSIGN(LauncherPageSwitchesTest); }; -// Flaky on CrOS. See https://crbug.com/981281 -#if defined(OS_CHROMEOS) -#define MAYBE_SwitchToNextPage DISABLED_SwitchToNextPage -#else -#define MAYBE_SwitchToNextPage SwitchToNextPage -#endif -IN_PROC_BROWSER_TEST_P(LauncherPageSwitchesTest, MAYBE_SwitchToNextPage) { +IN_PROC_BROWSER_TEST_P(LauncherPageSwitchesTest, SwitchToNextPage) { ash::PaginationModel* model = ash::ShellTestApi().GetAppListPaginationModel(); ASSERT_TRUE(model); EXPECT_LT(1, model->total_pages()); @@ -109,13 +102,7 @@ waiter.Wait(); } -// Flaky on CrOS. See https://crbug.com/981281 -#if defined(OS_CHROMEOS) -#define MAYBE_SwitchToFarPage DISABLED_SwitchToFarPage -#else -#define MAYBE_SwitchToFarPage SwitchToFarPage -#endif -IN_PROC_BROWSER_TEST_P(LauncherPageSwitchesTest, MAYBE_SwitchToFarPage) { +IN_PROC_BROWSER_TEST_P(LauncherPageSwitchesTest, SwitchToFarPage) { ash::PaginationModel* model = ash::ShellTestApi().GetAppListPaginationModel(); ASSERT_TRUE(model); EXPECT_LT(2, model->total_pages());
diff --git a/chrome/browser/ui/ash/multi_user/multi_user_util_chromeos_unittest.cc b/chrome/browser/ui/ash/multi_user/multi_user_util_chromeos_unittest.cc index f15a707..87abe02 100644 --- a/chrome/browser/ui/ash/multi_user/multi_user_util_chromeos_unittest.cc +++ b/chrome/browser/ui/ash/multi_user/multi_user_util_chromeos_unittest.cc
@@ -12,7 +12,7 @@ #include "chrome/test/base/chrome_ash_test_base.h" #include "chrome/test/base/testing_profile.h" #include "components/account_id/account_id.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/user_manager/scoped_user_manager.h"
diff --git a/chrome/browser/ui/ash/network/mobile_data_notifications.cc b/chrome/browser/ui/ash/network/mobile_data_notifications.cc index 247d71e5..037a96a 100644 --- a/chrome/browser/ui/ash/network/mobile_data_notifications.cc +++ b/chrome/browser/ui/ash/network/mobile_data_notifications.cc
@@ -7,9 +7,9 @@ #include <string> #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/time/time.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/notifications/system_notification_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" @@ -144,7 +144,7 @@ base::MakeRefCounted<message_center::HandleNotificationClickDelegate>( base::BindRepeating(&MobileDataNotificationClicked, first_active_network->guid())), - ash::kNotificationMobileDataIcon, + kNotificationMobileDataIcon, message_center::SystemNotificationWarningLevel::NORMAL); SystemNotificationHelper::GetInstance()->Display(*notification);
diff --git a/chrome/browser/ui/ash/network/network_portal_notification_controller.cc b/chrome/browser/ui/ash/network/network_portal_notification_controller.cc index 6d4b1893..103c47c 100644 --- a/chrome/browser/ui/ash/network/network_portal_notification_controller.cc +++ b/chrome/browser/ui/ash/network/network_portal_notification_controller.cc
@@ -10,7 +10,6 @@ #include <vector> #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" @@ -20,6 +19,7 @@ #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/chromeos/mobile/mobile_activator.h" #include "chrome/browser/chromeos/net/network_portal_web_dialog.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" @@ -337,7 +337,7 @@ : IDS_PORTAL_DETECTION_NOTIFICATION_MESSAGE_WIRED, base::UTF8ToUTF16(network->name())), base::string16(), GURL(), notifier_id, data, std::move(delegate), - ash::kNotificationCaptivePortalIcon, + kNotificationCaptivePortalIcon, message_center::SystemNotificationWarningLevel::NORMAL); notification->SetSystemPriority(); return notification; @@ -391,7 +391,7 @@ IDS_PORTAL_DETECTION_NOTIFICATION_TITLE_WIFI), notification_text, base::string16() /* display_source */, GURL(), notifier_id, data, std::move(delegate), - ash::kNotificationCaptivePortalIcon, + kNotificationCaptivePortalIcon, message_center::SystemNotificationWarningLevel::NORMAL); notification->SetSystemPriority(); return notification;
diff --git a/chrome/browser/ui/ash/network/network_state_notifier.cc b/chrome/browser/ui/ash/network/network_state_notifier.cc index 0c74dd1..2210a30a 100644 --- a/chrome/browser/ui/ash/network/network_state_notifier.cc +++ b/chrome/browser/ui/ash/network/network_state_notifier.cc
@@ -5,12 +5,12 @@ #include "chrome/browser/ui/ash/network/network_state_notifier.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/location.h" #include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/chromeos/net/shill_error.h" #include "chrome/browser/notifications/system_notification_helper.h" #include "chrome/browser/ui/ash/system_tray_client.h" @@ -64,10 +64,10 @@ const gfx::VectorIcon& GetErrorNotificationVectorIcon( const std::string& network_type) { if (network_type == shill::kTypeVPN) - return ash::kNotificationVpnIcon; + return kNotificationVpnIcon; if (network_type == shill::kTypeCellular) - return ash::kNotificationMobileDataOffIcon; - return ash::kNotificationWifiOffIcon; + return kNotificationMobileDataOffIcon; + return kNotificationWifiOffIcon; } void ShowErrorNotification(const std::string& service_path, @@ -302,7 +302,7 @@ new message_center::HandleNotificationClickDelegate( base::Bind(&NetworkStateNotifier::ShowNetworkSettings, weak_ptr_factory_.GetWeakPtr(), cellular_guid)), - ash::kNotificationMobileDataIcon, + kNotificationMobileDataIcon, message_center::SystemNotificationWarningLevel::CRITICAL_WARNING); notification->set_priority(message_center::SYSTEM_PRIORITY); SystemNotificationHelper::GetInstance()->Display(*notification); @@ -349,7 +349,7 @@ new message_center::HandleNotificationClickDelegate( base::Bind(&NetworkStateNotifier::ShowNetworkSettings, weak_ptr_factory_.GetWeakPtr(), cellular->guid())), - ash::kNotificationMobileDataOffIcon, + kNotificationMobileDataOffIcon, message_center::SystemNotificationWarningLevel::CRITICAL_WARNING); notification->set_priority(message_center::SYSTEM_PRIORITY); SystemNotificationHelper::GetInstance()->Display(*notification);
diff --git a/chrome/browser/ui/ash/network/tether_notification_presenter.cc b/chrome/browser/ui/ash/network/tether_notification_presenter.cc index 045a2909..bf2b128 100644 --- a/chrome/browser/ui/ash/network/tether_notification_presenter.cc +++ b/chrome/browser/ui/ash/network/tether_notification_presenter.cc
@@ -6,12 +6,12 @@ #include "ash/public/cpp/network_icon_image_source.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" #include "chrome/common/url_constants.h" @@ -221,7 +221,7 @@ new message_center::HandleNotificationClickDelegate(base::BindRepeating( &TetherNotificationPresenter::OnNotificationClicked, weak_ptr_factory_.GetWeakPtr(), id)), - ash::kNotificationCellularAlertIcon, + kNotificationCellularAlertIcon, message_center::SystemNotificationWarningLevel::WARNING)); }
diff --git a/chrome/browser/ui/ash/overview_animations_interactive_uitest.cc b/chrome/browser/ui/ash/overview_animations_interactive_uitest.cc index f4d8546..294f1a1 100644 --- a/chrome/browser/ui/ash/overview_animations_interactive_uitest.cc +++ b/chrome/browser/ui/ash/overview_animations_interactive_uitest.cc
@@ -9,8 +9,8 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/views/frame/browser_view.h" -#include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/perf/performance_test.h" +#include "chrome/test/base/ui_test_utils.h" #include "ui/base/test/ui_controls.h" // Test overview enter/exit animations with following conditions
diff --git a/chrome/browser/ui/ash/overview_window_drag_interactive_uitest.cc b/chrome/browser/ui/ash/overview_window_drag_interactive_uitest.cc index 454d7432..f42a792 100644 --- a/chrome/browser/ui/ash/overview_window_drag_interactive_uitest.cc +++ b/chrome/browser/ui/ash/overview_window_drag_interactive_uitest.cc
@@ -12,9 +12,9 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/views/frame/browser_view.h" -#include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/perf/drag_event_generator.h" #include "chrome/test/base/perf/performance_test.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" @@ -156,10 +156,6 @@ ash::ShellTestApi().WaitForOverviewAnimationState( ash::OverviewAnimationState::kEnterAnimationComplete); - content::WindowedNotificationObserver waiter( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::Source<Browser>(chrome::FindLastActive())); - gfx::Point start_point = GetStartLocation(GetDisplaySize(browser_window)); gfx::Point end_point(start_point); end_point.set_y(0); @@ -171,8 +167,7 @@ /*touch=*/true); generator.Wait(); - // Wait for the window to close. - waiter.Wait(); + ui_test_utils::WaitForBrowserToClose(chrome::FindLastActive()); } IN_PROC_BROWSER_TEST_P(OverviewWindowDragTest, DragToSnap) {
diff --git a/chrome/browser/ui/ash/screen_rotation_interactive_uitest.cc b/chrome/browser/ui/ash/screen_rotation_interactive_uitest.cc index ed0ee4e..0f276415 100644 --- a/chrome/browser/ui/ash/screen_rotation_interactive_uitest.cc +++ b/chrome/browser/ui/ash/screen_rotation_interactive_uitest.cc
@@ -13,8 +13,8 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/views/frame/browser_view.h" -#include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/perf/performance_test.h" +#include "chrome/test/base/ui_test_utils.h" #include "ui/aura/window.h" #include "ui/base/test/ui_controls.h" #include "ui/compositor/layer_animation_observer.h"
diff --git a/chrome/browser/ui/ash/split_view_interactive_uitest.cc b/chrome/browser/ui/ash/split_view_interactive_uitest.cc index 72de74e2..7dbeeea 100644 --- a/chrome/browser/ui/ash/split_view_interactive_uitest.cc +++ b/chrome/browser/ui/ash/split_view_interactive_uitest.cc
@@ -14,9 +14,9 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/webui_url_constants.h" -#include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/perf/drag_event_generator.h" #include "chrome/test/base/perf/performance_test.h" +#include "chrome/test/base/ui_test_utils.h" #include "ui/aura/window.h" #include "ui/compositor/compositor.h" #include "ui/display/display.h"
diff --git a/chrome/browser/ui/ash/tablet_mode_client.cc b/chrome/browser/ui/ash/tablet_mode_client.cc index e9fbe73..5dc07946 100644 --- a/chrome/browser/ui/ash/tablet_mode_client.cc +++ b/chrome/browser/ui/ash/tablet_mode_client.cc
@@ -40,7 +40,7 @@ } void TabletModeClient::Init() { - ash::TabletMode::Get()->SetTabletModeToggleObserver(this); + ash::TabletMode::Get()->AddObserver(this); OnTabletModeToggled(ash::TabletMode::Get()->InTabletMode()); } @@ -70,6 +70,18 @@ observer.OnTabletModeToggled(enabled); } +void TabletModeClient::OnTabletModeStarted() { + OnTabletModeToggled(true); +} + +void TabletModeClient::OnTabletModeEnded() { + OnTabletModeToggled(false); +} + +void TabletModeClient::OnTabletControllerDestroyed() { + ash::TabletMode::Get()->RemoveObserver(this); +} + bool TabletModeClient::ShouldTrackBrowser(Browser* browser) { return tablet_mode_enabled_; }
diff --git a/chrome/browser/ui/ash/tablet_mode_client.h b/chrome/browser/ui/ash/tablet_mode_client.h index 309f364a..1cc76d64 100644 --- a/chrome/browser/ui/ash/tablet_mode_client.h +++ b/chrome/browser/ui/ash/tablet_mode_client.h
@@ -7,7 +7,7 @@ #include <memory> -#include "ash/public/cpp/tablet_mode_toggle_observer.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "base/macros.h" #include "base/observer_list.h" #include "chrome/browser/ui/browser_tab_strip_tracker_delegate.h" @@ -19,7 +19,7 @@ // Holds tablet mode state in chrome. Observes ash for changes, then // synchronously fires all its observers. This allows all tablet mode code in // chrome to see a state change at the same time. -class TabletModeClient : public ash::TabletModeToggleObserver, +class TabletModeClient : public ash::TabletModeObserver, public BrowserTabStripTrackerDelegate, public TabStripModelObserver { public: @@ -38,8 +38,13 @@ void RemoveObserver(TabletModeClientObserver* observer); - // ash::TabletModeToggleObserver: - void OnTabletModeToggled(bool enabled) override; + // Notify the tablet mode change. + void OnTabletModeToggled(bool enabled); + + // ash::TabletModeObserver: + void OnTabletModeStarted() override; + void OnTabletModeEnded() override; + void OnTabletControllerDestroyed() override; // BrowserTabStripTrackerDelegate: bool ShouldTrackBrowser(Browser* browser) override;
diff --git a/chrome/browser/ui/ash/tablet_mode_transition_interactive_uitest.cc b/chrome/browser/ui/ash/tablet_mode_transition_interactive_uitest.cc index 168a6668..ad07a59f 100644 --- a/chrome/browser/ui/ash/tablet_mode_transition_interactive_uitest.cc +++ b/chrome/browser/ui/ash/tablet_mode_transition_interactive_uitest.cc
@@ -98,7 +98,9 @@ base::RunLoop run_loop; ui::LayerAnimator* animator = browser_window->layer()->GetAnimator(); TestLayerAnimationObserver waiter(animator, run_loop.QuitClosure()); - ash::ShellTestApi().SetTabletModeEnabledForTest(true); + ash::ShellTestApi().SetTabletModeEnabledForTest( + true, /*wait_for_completion=*/false); + EXPECT_TRUE(animator->is_animating()); run_loop.Run(); } @@ -106,7 +108,9 @@ base::RunLoop run_loop; ui::LayerAnimator* animator = browser_window->layer()->GetAnimator(); TestLayerAnimationObserver waiter(animator, run_loop.QuitClosure()); - ash::ShellTestApi().SetTabletModeEnabledForTest(false); + ash::ShellTestApi().SetTabletModeEnabledForTest( + false, /*wait_for_completion=*/false); + EXPECT_TRUE(animator->is_animating()); run_loop.Run(); } }
diff --git a/chrome/browser/ui/ash/window_resize_interactive_uitest.cc b/chrome/browser/ui/ash/window_resize_interactive_uitest.cc index 9696aff..3e1f89a 100644 --- a/chrome/browser/ui/ash/window_resize_interactive_uitest.cc +++ b/chrome/browser/ui/ash/window_resize_interactive_uitest.cc
@@ -10,9 +10,9 @@ #include "chrome/browser/ui/ash/ash_test_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" -#include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/perf/drag_event_generator.h" #include "chrome/test/base/perf/performance_test.h" +#include "chrome/test/base/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/window.h" #include "ui/base/test/ui_controls.h"
diff --git a/chrome/browser/ui/autofill/chrome_autofill_client.cc b/chrome/browser/ui/autofill/chrome_autofill_client.cc index e91194e5..748d193 100644 --- a/chrome/browser/ui/autofill/chrome_autofill_client.cc +++ b/chrome/browser/ui/autofill/chrome_autofill_client.cc
@@ -49,9 +49,9 @@ #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_requirements_service.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/sync/driver/sync_service.h" #include "components/translate/core/browser/translate_manager.h" @@ -506,10 +506,8 @@ if (id == autofill::POPUP_ITEM_ID_CREDIT_CARD_SIGNIN_PROMO) { auto* window = web_contents()->GetNativeView()->GetWindowAndroid(); if (window) { - chrome::android::SigninPromoUtilAndroid:: - StartAccountSigninActivityForPromo( - window, - signin_metrics::AccessPoint::ACCESS_POINT_AUTOFILL_DROPDOWN); + chrome::android::SigninPromoUtilAndroid::StartSigninActivityForPromo( + window, signin_metrics::AccessPoint::ACCESS_POINT_AUTOFILL_DROPDOWN); } } #endif
diff --git a/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.cc b/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.cc index a4d73c28..acd4c914 100644 --- a/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.cc +++ b/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.cc
@@ -37,7 +37,7 @@ #include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/strings/grit/components_strings.h" #include "components/sync/driver/sync_service.h"
diff --git a/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.h b/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.h index b24341e4a9..4aace50 100644 --- a/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.h +++ b/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.h
@@ -14,7 +14,7 @@ #include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/browser/ui/payments/save_card_bubble_controller.h" #include "components/security_state/core/security_state.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h"
diff --git a/chrome/browser/ui/browser_command_controller.cc b/chrome/browser/ui/browser_command_controller.cc index 55be14f0..6f7fe4a 100644 --- a/chrome/browser/ui/browser_command_controller.cc +++ b/chrome/browser/ui/browser_command_controller.cc
@@ -52,7 +52,7 @@ #include "components/feature_engagement/buildflags.h" #include "components/prefs/pref_service.h" #include "components/sessions/core/tab_restore_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h"
diff --git a/chrome/browser/ui/browser_command_controller_browsertest.cc b/chrome/browser/ui/browser_command_controller_browsertest.cc index 97330e2..b499dda 100644 --- a/chrome/browser/ui/browser_command_controller_browsertest.cc +++ b/chrome/browser/ui/browser_command_controller_browsertest.cc
@@ -11,7 +11,6 @@ #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/search_engines/template_url_service_factory.h" @@ -30,8 +29,7 @@ #include "components/search_engines/template_url_service.h" #include "components/sessions/core/tab_restore_service.h" #include "components/sessions/core/tab_restore_service_observer.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "content/public/browser/notification_service.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/test/test_utils.h" #if defined(OS_CHROMEOS) @@ -96,15 +94,8 @@ // Create a guest browser nicely. Using CreateProfile() and CreateBrowser() // does incomplete initialization that would lead to // SystemUrlRequestContextGetter being leaked. - content::WindowedNotificationObserver browser_creation_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); profiles::SwitchToGuestProfile(ProfileManager::CreateCallback()); - - // RunUntilIdle() (racily) isn't sufficient to ensure browser creation, so - // listen for the notification. - base::RunLoop().RunUntilIdle(); - browser_creation_observer.Wait(); + ui_test_utils::WaitForBrowserToOpen(); EXPECT_EQ(2U, BrowserList::GetInstance()->size()); // Access the browser that was created for the new Guest Profile.
diff --git a/chrome/browser/ui/browser_command_controller_unittest.cc b/chrome/browser/ui/browser_command_controller_unittest.cc index d453b828..d063538 100644 --- a/chrome/browser/ui/browser_command_controller_unittest.cc +++ b/chrome/browser/ui/browser_command_controller_unittest.cc
@@ -25,8 +25,8 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_pref_names.h" #include "content/public/browser/native_web_keyboard_event.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/events/keycodes/keyboard_codes.h"
diff --git a/chrome/browser/ui/browser_dialogs.cc b/chrome/browser/ui/browser_dialogs.cc index 3307df24..445c956 100644 --- a/chrome/browser/ui/browser_dialogs.cc +++ b/chrome/browser/ui/browser_dialogs.cc
@@ -37,4 +37,25 @@ // if the dialog was instantly cancelled. std::move(callback).Run(PermissionAction::DISMISSED); } + +void ShowNativeFileSystemRestrictedDirectoryDialog( + const url::Origin& origin, + const base::FilePath& path, + base::OnceClosure callback, + content::WebContents* web_contents) { + // There's no dialog version of this available outside views, run callback as + // if the dialog was instantly dismissed. + std::move(callback).Run(); +} + +void ShowNativeFileSystemDirectoryAccessConfirmationDialog( + const url::Origin& origin, + const base::FilePath& path, + base::OnceCallback<void(PermissionAction result)> callback, + content::WebContents* web_contents) { + // There's no dialog version of this available outside views, run callback as + // if the dialog was instantly dismissed. + std::move(callback).Run(PermissionAction::DISMISSED); +} + #endif // !defined(TOOLKIT_VIEWS)
diff --git a/chrome/browser/ui/browser_dialogs.h b/chrome/browser/ui/browser_dialogs.h index e8381e5..0c6f99b 100644 --- a/chrome/browser/ui/browser_dialogs.h +++ b/chrome/browser/ui/browser_dialogs.h
@@ -313,4 +313,22 @@ base::OnceCallback<void(PermissionAction result)> callback, content::WebContents* web_contents); +// Displays a dialog to inform the user that the directory |path| they picked +// using the native file system API is blocked by chrome. +// |callback| is called when the user has dismissed the dialog. +void ShowNativeFileSystemRestrictedDirectoryDialog( + const url::Origin& origin, + const base::FilePath& path, + base::OnceClosure callback, + content::WebContents* web_contents); + +// Displays a dialog to confirm that the user intended to give read access to a +// specific directory. Similar to ShowFolderUploadConfirmationDialog above, +// except for use by the Native File System API. +void ShowNativeFileSystemDirectoryAccessConfirmationDialog( + const url::Origin& origin, + const base::FilePath& path, + base::OnceCallback<void(PermissionAction result)> callback, + content::WebContents* web_contents); + #endif // CHROME_BROWSER_UI_BROWSER_DIALOGS_H_
diff --git a/chrome/browser/ui/browser_focus_uitest.cc b/chrome/browser/ui/browser_focus_uitest.cc index 0946acb..cfb3a19 100644 --- a/chrome/browser/ui/browser_focus_uitest.cc +++ b/chrome/browser/ui/browser_focus_uitest.cc
@@ -123,11 +123,17 @@ bool is_editable_node = index == 0; // Press Tab (or Shift+Tab) and check the focused element id. - ASSERT_TRUE(ui_test_utils::SendKeyPressAndWaitWithDetails( - browser(), key, false, reverse, false, false, - content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE, - content::Source<RenderViewHost>(render_view_host), - content::Details<bool>(&is_editable_node))); + auto source = content::Source<RenderViewHost>(render_view_host); + ui_test_utils::WindowedNotificationObserverWithDetails<bool> observer( + content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE, source); + ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), key, false, + reverse, false, false)); + observer.Wait(); + bool observed_editable_node; + ASSERT_TRUE( + observer.GetDetailsFor(source.map_key(), &observed_editable_node)); + EXPECT_EQ(is_editable_node, observed_editable_node); + std::string focused_id; EXPECT_TRUE(content::ExecuteScriptAndExtractString( WebContents::FromRenderViewHost(render_view_host),
diff --git a/chrome/browser/ui/browser_tabrestore_browsertest.cc b/chrome/browser/ui/browser_tabrestore_browsertest.cc index fb8846b8..aa39ae4 100644 --- a/chrome/browser/ui/browser_tabrestore_browsertest.cc +++ b/chrome/browser/ui/browser_tabrestore_browsertest.cc
@@ -12,11 +12,13 @@ #include "chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "components/sessions/core/tab_restore_service.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" +#include "content/public/test/test_utils.h" typedef InProcessBrowserTest BrowserTabRestoreTest;
diff --git a/chrome/browser/ui/chrome_pages.cc b/chrome/browser/ui/chrome_pages.cc index 17af855ba..a5be518 100644 --- a/chrome/browser/ui/chrome_pages.cc +++ b/chrome/browser/ui/chrome_pages.cc
@@ -55,7 +55,7 @@ #if !defined(OS_ANDROID) #include "chrome/browser/signin/identity_manager_factory.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #endif
diff --git a/chrome/browser/ui/cocoa/permission_bubble/permission_bubble_cocoa_interactive_uitest.mm b/chrome/browser/ui/cocoa/permission_bubble/permission_bubble_cocoa_interactive_uitest.mm index 2731ce3..1f34a88 100644 --- a/chrome/browser/ui/cocoa/permission_bubble/permission_bubble_cocoa_interactive_uitest.mm +++ b/chrome/browser/ui/cocoa/permission_bubble/permission_bubble_cocoa_interactive_uitest.mm
@@ -18,6 +18,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "content/public/test/test_utils.h" #include "ui/base/test/ui_controls.h" #import "ui/base/test/windowed_nsnotification_observer.h" #include "ui/base/ui_base_features.h"
diff --git a/chrome/browser/ui/cocoa/profiles/profile_menu_controller.mm b/chrome/browser/ui/cocoa/profiles/profile_menu_controller.mm index d81c792..342e948 100644 --- a/chrome/browser/ui/cocoa/profiles/profile_menu_controller.mm +++ b/chrome/browser/ui/cocoa/profiles/profile_menu_controller.mm
@@ -24,7 +24,7 @@ #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "ui/base/l10n/l10n_util_mac.h" #include "ui/gfx/image/image.h"
diff --git a/chrome/browser/ui/cocoa/test/cocoa_profile_test.mm b/chrome/browser/ui/cocoa/test/cocoa_profile_test.mm index a697a471..f161761 100644 --- a/chrome/browser/ui/cocoa/test/cocoa_profile_test.mm +++ b/chrome/browser/ui/cocoa/test/cocoa_profile_test.mm
@@ -22,7 +22,7 @@ #include "chrome/test/base/testing_profile.h" #include "chrome/test/views/chrome_test_views_delegate.h" #include "components/bookmarks/test/bookmark_test_helpers.h" -#include "components/signin/core/browser/list_accounts_test_utils.h" +#include "components/signin/public/base/list_accounts_test_utils.h" #include "components/sync_preferences/pref_service_syncable.h" #include "content/public/test/test_browser_thread_bundle.h" #include "ui/views/test/widget_test.h"
diff --git a/chrome/browser/ui/exclusive_access/flash_fullscreen_interactive_browsertest.cc b/chrome/browser/ui/exclusive_access/flash_fullscreen_interactive_browsertest.cc index 5261fdbf..cb20d48 100644 --- a/chrome/browser/ui/exclusive_access/flash_fullscreen_interactive_browsertest.cc +++ b/chrome/browser/ui/exclusive_access/flash_fullscreen_interactive_browsertest.cc
@@ -16,6 +16,7 @@ #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "chrome/test/ppapi/ppapi_test.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_widget_host.h"
diff --git a/chrome/browser/ui/extensions/extension_installed_notification.cc b/chrome/browser/ui/extensions/extension_installed_notification.cc index 1546c55..4daa61ad 100644 --- a/chrome/browser/ui/extensions/extension_installed_notification.cc +++ b/chrome/browser/ui/extensions/extension_installed_notification.cc
@@ -5,8 +5,8 @@ #include "chrome/browser/ui/extensions/extension_installed_notification.h" #include "ash/public/cpp/notification_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/notifications/notification_common.h" @@ -50,7 +50,7 @@ GURL(extension_urls::kChromeWebstoreBaseURL) /* origin_url */, message_center::NotifierId( message_center::NotifierType::SYSTEM_COMPONENT, kNotifierId), - {}, this, ash::kNotificationInstalledIcon, + {}, this, kNotificationInstalledIcon, message_center::SystemNotificationWarningLevel::NORMAL); NotificationDisplayService::GetForProfile(profile_)->Display(
diff --git a/chrome/browser/ui/fullscreen_keyboard_browsertest_base.cc b/chrome/browser/ui/fullscreen_keyboard_browsertest_base.cc index 6a1716c..5759118f 100644 --- a/chrome/browser/ui/fullscreen_keyboard_browsertest_base.cc +++ b/chrome/browser/ui/fullscreen_keyboard_browsertest_base.cc
@@ -18,6 +18,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "ui/events/keycodes/dom/keycode_converter.h"
diff --git a/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.cc b/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.cc index 27ab3ec0..e328f4e 100644 --- a/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.cc +++ b/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.cc
@@ -39,11 +39,6 @@ void MediaToolbarButtonController::MediaSessionInfoChanged( media_session::mojom::MediaSessionInfoPtr session_info) { - if (session_info) { - // We only want to show if there's a controllable media session. However, as - // a MediaControllerObserver we should only receive a - // |MediaSessionInfoChanged()| call for a controllable session. - DCHECK(session_info->is_controllable); + if (session_info && session_info->is_controllable) delegate_->Show(); - } }
diff --git a/chrome/browser/ui/input_method/input_method_engine.cc b/chrome/browser/ui/input_method/input_method_engine.cc index 9a9d314..05cec7a 100644 --- a/chrome/browser/ui/input_method/input_method_engine.cc +++ b/chrome/browser/ui/input_method/input_method_engine.cc
@@ -149,6 +149,13 @@ return true; } +void InputMethodEngine::ConfirmCompositionText() { + ui::IMEInputContextHandlerInterface* input_context = + ui::IMEBridge::Get()->GetInputContextHandler(); + if (input_context) + input_context->ConfirmCompositionText(); +} + bool InputMethodEngine::IsActive() const { return true; }
diff --git a/chrome/browser/ui/input_method/input_method_engine.h b/chrome/browser/ui/input_method/input_method_engine.h index 9293e0d..ddd4612 100644 --- a/chrome/browser/ui/input_method/input_method_engine.h +++ b/chrome/browser/ui/input_method/input_method_engine.h
@@ -40,6 +40,7 @@ void DeleteSurroundingTextToInputContext(int offset, size_t number_of_chars) override; bool SendKeyEvent(ui::KeyEvent* ui_event, const std::string& code) override; + void ConfirmCompositionText() override; bool IsActive() const override; std::string GetExtensionId() const;
diff --git a/chrome/browser/ui/input_method/input_method_engine_base.cc b/chrome/browser/ui/input_method/input_method_engine_base.cc index c819c858..40ee0f2 100644 --- a/chrome/browser/ui/input_method/input_method_engine_base.cc +++ b/chrome/browser/ui/input_method/input_method_engine_base.cc
@@ -211,8 +211,7 @@ void InputMethodEngineBase::Disable() { std::string last_component_id{active_component_id_}; active_component_id_.clear(); - CommitTextToInputContext(context_id_, - base::UTF16ToUTF8(composition_text_->text)); + ConfirmCompositionText(); composition_text_.reset(new ui::CompositionText()); observer_->OnDeactivated(last_component_id); }
diff --git a/chrome/browser/ui/input_method/input_method_engine_base.h b/chrome/browser/ui/input_method/input_method_engine_base.h index fb8757de..d29b62c 100644 --- a/chrome/browser/ui/input_method/input_method_engine_base.h +++ b/chrome/browser/ui/input_method/input_method_engine_base.h
@@ -230,6 +230,8 @@ // Sends the key event to the window tree host. virtual bool SendKeyEvent(ui::KeyEvent* ui_event, const std::string& code) = 0; + // Notifies InputContextHandler to commit any composition text. + virtual void ConfirmCompositionText() = 0; ui::TextInputType current_input_type_;
diff --git a/chrome/browser/ui/input_method/input_method_engine_unittest.cc b/chrome/browser/ui/input_method/input_method_engine_unittest.cc index 97463854..262ee05 100644 --- a/chrome/browser/ui/input_method/input_method_engine_unittest.cc +++ b/chrome/browser/ui/input_method/input_method_engine_unittest.cc
@@ -282,4 +282,20 @@ EXPECT_EQ(0, observer_->GetSurroundingInfo().offset); } +TEST_F(InputMethodEngineTest, TestDisableAfterSetComposition) { + // Enables the extension with focus. + engine_->Enable(kTestImeComponentId); + FocusIn(ui::TEXT_INPUT_TYPE_TEXT); + + ui::CompositionText composition_text; + composition_text.text = base::ASCIIToUTF16("hello"); + engine_->UpdateComposition(composition_text, 0, /* is_visible */ true); + + // Disable to commit + engine_->Disable(); + + EXPECT_EQ(1, mock_ime_input_context_handler_->commit_text_call_count()); + EXPECT_EQ("hello", mock_ime_input_context_handler_->last_commit_text()); +} + } // namespace input_method
diff --git a/chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.cc b/chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.cc deleted file mode 100644 index 14859d40..0000000 --- a/chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.cc +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.h" - -#include <utility> - -#include "chrome/browser/media/router/presentation/presentation_service_delegate_impl.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/media_router/media_router_ui_base.h" -#include "chrome/browser/ui/media_router/media_router_ui_service.h" - -using content::WebContents; - -namespace media_router { - -namespace { - -MediaRouterUIService* GetMediaRouterUIService(WebContents* web_contents) { - Profile* profile = - Profile::FromBrowserContext(web_contents->GetBrowserContext()); - // TODO(crbug.com/826091): Move MRUIService to c/b/ui/media_router/. - return MediaRouterUIService::Get(profile); -} - -} // namespace - -MediaRouterDialogControllerImplBase::~MediaRouterDialogControllerImplBase() { - media_router_ui_service_->RemoveObserver(this); -} - -void MediaRouterDialogControllerImplBase::CreateMediaRouterDialog() { - if (!GetActionController()) - return; - GetActionController()->OnDialogShown(); -} - -void MediaRouterDialogControllerImplBase::Reset() { - if (IsShowingMediaRouterDialog() && GetActionController()) - GetActionController()->OnDialogHidden(); - MediaRouterDialogController::Reset(); -} - -MediaRouterDialogControllerImplBase::MediaRouterDialogControllerImplBase( - WebContents* web_contents) - : MediaRouterDialogController(web_contents), - media_router_ui_service_(GetMediaRouterUIService(web_contents)) { - DCHECK(media_router_ui_service_); - media_router_ui_service_->AddObserver(this); -} - -void MediaRouterDialogControllerImplBase::InitializeMediaRouterUI( - MediaRouterUIBase* media_router_ui) { - auto start_presentation_context = std::move(start_presentation_context_); - PresentationServiceDelegateImpl* delegate = - PresentationServiceDelegateImpl::FromWebContents(initiator()); - if (!start_presentation_context) { - media_router_ui->InitWithDefaultMediaSource(initiator(), delegate); - } else { - media_router_ui->InitWithStartPresentationContext( - initiator(), delegate, std::move(start_presentation_context)); - } -} - -void MediaRouterDialogControllerImplBase::OnServiceDisabled() { - CloseMediaRouterDialog(); - Reset(); -} - -MediaRouterActionController* -MediaRouterDialogControllerImplBase::GetActionController() { - return media_router_ui_service_->action_controller(); -} - -} // namespace media_router
diff --git a/chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.h b/chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.h deleted file mode 100644 index 2b4db93..0000000 --- a/chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.h +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_IMPL_BASE_H_ -#define CHROME_BROWSER_UI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_IMPL_BASE_H_ - -#include "base/macros.h" -#include "chrome/browser/media/router/media_router_dialog_controller.h" -#include "chrome/browser/ui/media_router/media_router_ui_service.h" - -namespace media_router { - -class MediaRouterUIBase; - -// The base class for desktop implementations of MediaRouterDialogController. -// This class is not thread safe and must be called on the UI thread. -class MediaRouterDialogControllerImplBase : public MediaRouterDialogController, - MediaRouterUIService::Observer { - public: - ~MediaRouterDialogControllerImplBase() override; - - static MediaRouterDialogControllerImplBase* GetOrCreateForWebContents( - content::WebContents* web_contents); - static MediaRouterDialogControllerImplBase* FromWebContents( - content::WebContents* web_contents); - - // MediaRouterDialogController: - void CreateMediaRouterDialog() override; - void Reset() override; - - protected: - // Use MediaRouterDialogControllerImplBase::CreateForWebContents() to create - // an instance. - explicit MediaRouterDialogControllerImplBase( - content::WebContents* web_contents); - - // Called by subclasses to initialize |media_router_ui| that they use. - void InitializeMediaRouterUI(MediaRouterUIBase* media_router_ui); - - private: - // MediaRouterUIService::Observer: - void OnServiceDisabled() override; - - // MediaRouterActionController is responsible for showing and hiding the - // toolbar action. It's owned by MediaRouterUIService and it may be nullptr. - MediaRouterActionController* GetActionController(); - - // |media_router_ui_service_| Service which provides - // MediaRouterActionController. It outlives |this|. - MediaRouterUIService* const media_router_ui_service_; - - DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogControllerImplBase); -}; - -} // namespace media_router - -#endif // CHROME_BROWSER_UI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_IMPL_BASE_H_
diff --git a/chrome/browser/ui/omnibox/omnibox_view_browsertest.cc b/chrome/browser/ui/omnibox/omnibox_view_browsertest.cc index e6aa603..90f77c7 100644 --- a/chrome/browser/ui/omnibox/omnibox_view_browsertest.cc +++ b/chrome/browser/ui/omnibox/omnibox_view_browsertest.cc
@@ -7,12 +7,14 @@ #include <memory> +#include "base/bind.h" #include "base/run_loop.h" #include "base/scoped_observer.h" #include "base/stl_util.h" #include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" @@ -207,15 +209,23 @@ ASSERT_NO_FATAL_FAILURE(SendKey(*keys, 0)); } - bool ExpectBrowserClosed(const Browser* browser, + void ExpectBrowserClosed(const Browser* browser, ui::KeyboardCode key, - int modifiers) WARN_UNUSED_RESULT { - return ui_test_utils::SendKeyPressAndWait( - browser, key, (modifiers & ui::EF_CONTROL_DOWN) != 0, - (modifiers & ui::EF_SHIFT_DOWN) != 0, - (modifiers & ui::EF_ALT_DOWN) != 0, - (modifiers & ui::EF_COMMAND_DOWN) != 0, - chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(browser)); + int modifiers) { + // Press the accelerator after starting to wait for a browser to close as + // the close may be synchronous. + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce( + [](const Browser* browser, ui::KeyboardCode key, int modifiers) { + EXPECT_TRUE(ui_test_utils::SendKeyPressSync( + browser, key, (modifiers & ui::EF_CONTROL_DOWN) != 0, + (modifiers & ui::EF_SHIFT_DOWN) != 0, + (modifiers & ui::EF_ALT_DOWN) != 0, + (modifiers & ui::EF_COMMAND_DOWN) != 0)); + }, + browser, key, modifiers)); + ui_test_utils::WaitForBrowserToClose(browser); } void NavigateExpectUrl(const GURL& url, int modifiers = 0) { @@ -448,7 +458,7 @@ #if !defined(OS_CHROMEOS) && !defined(OS_MACOSX) // Try alt-f4 to close the browser. - ASSERT_TRUE(ExpectBrowserClosed(browser(), ui::VKEY_F4, ui::EF_ALT_DOWN)); + ExpectBrowserClosed(browser(), ui::VKEY_F4, ui::EF_ALT_DOWN); #endif } @@ -462,19 +472,14 @@ chrome::FocusLocationBar(popup); EXPECT_TRUE(omnibox_view->IsSelectAll()); -#if !defined(OS_MACOSX) - // Try ctrl-w to close the popup. - // This piece of code doesn't work on Mac, because the Browser object won't - // be destroyed before finishing the current message loop iteration, thus - // No BROWSER_CLOSED notification will be sent. - ASSERT_TRUE(ExpectBrowserClosed(popup, ui::VKEY_W, ui::EF_CONTROL_DOWN)); + // Try ctrl/cmd-w to close the popup. + ExpectBrowserClosed(popup, ui::VKEY_W, kCtrlOrCmdMask); // Create another popup. popup = CreateBrowserForPopup(browser()->profile()); ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(popup)); ASSERT_NO_FATAL_FAILURE( GetOmniboxViewForBrowser(popup, &omnibox_view)); -#endif // Set the edit text to "Hello world". omnibox_view->SetUserText(ASCIIToUTF16("Hello world")); @@ -493,7 +498,7 @@ #if !defined(OS_CHROMEOS) && !defined(OS_MACOSX) // Try alt-f4 to close the popup. - ASSERT_TRUE(ExpectBrowserClosed(popup, ui::VKEY_F4, ui::EF_ALT_DOWN)); + ExpectBrowserClosed(popup, ui::VKEY_F4, ui::EF_ALT_DOWN); #endif }
diff --git a/chrome/browser/ui/page_info/page_info.cc b/chrome/browser/ui/page_info/page_info.cc index 0352cd9..bba1d27 100644 --- a/chrome/browser/ui/page_info/page_info.cc +++ b/chrome/browser/ui/page_info/page_info.cc
@@ -60,7 +60,7 @@ #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/rappor/public/rappor_utils.h" #include "components/rappor/rappor_service_impl.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/ssl_errors/error_info.h" #include "components/strings/grit/components_chromium_strings.h" #include "components/strings/grit/components_strings.h"
diff --git a/chrome/browser/ui/page_info/page_info_infobar_delegate.cc b/chrome/browser/ui/page_info/page_info_infobar_delegate.cc index 520dee0..0daafc8 100644 --- a/chrome/browser/ui/page_info/page_info_infobar_delegate.cc +++ b/chrome/browser/ui/page_info/page_info_infobar_delegate.cc
@@ -7,10 +7,10 @@ #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" -#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/infobars/infobar_service.h" #include "components/infobars/core/infobar.h" #include "components/strings/grit/components_strings.h" +#include "components/vector_icons/vector_icons.h" #include "content/public/browser/web_contents.h" #include "ui/base/l10n/l10n_util.h" @@ -30,7 +30,7 @@ } const gfx::VectorIcon& PageInfoInfoBarDelegate::GetVectorIcon() const { - return kSettingsIcon; + return vector_icons::kSettingsIcon; } base::string16 PageInfoInfoBarDelegate::GetMessageText() const {
diff --git a/chrome/browser/ui/page_info/page_info_ui.cc b/chrome/browser/ui/page_info/page_info_ui.cc index 97525ba..8a2d9387 100644 --- a/chrome/browser/ui/page_info/page_info_ui.cc +++ b/chrome/browser/ui/page_info/page_info_ui.cc
@@ -21,6 +21,7 @@ #include "chrome/grit/generated_resources.h" #include "components/strings/grit/components_chromium_strings.h" #include "components/strings/grit/components_strings.h" +#include "components/vector_icons/vector_icons.h" #include "ppapi/buildflags/buildflags.h" #include "services/device/public/cpp/device_features.h" #include "ui/base/l10n/l10n_util.h" @@ -641,7 +642,7 @@ const gfx::ImageSkia PageInfoUI::GetSiteSettingsIcon( const SkColor related_text_color) { return gfx::CreateVectorIcon( - kSettingsIcon, kVectorIconSize, + vector_icons::kSettingsIcon, kVectorIconSize, color_utils::DeriveDefaultIconColor(related_text_color)); }
diff --git a/chrome/browser/ui/passwords/manage_passwords_bubble_model_unittest.cc b/chrome/browser/ui/passwords/manage_passwords_bubble_model_unittest.cc index bb37a80d..e65e7fa 100644 --- a/chrome/browser/ui/passwords/manage_passwords_bubble_model_unittest.cc +++ b/chrome/browser/ui/passwords/manage_passwords_bubble_model_unittest.cc
@@ -28,7 +28,7 @@ #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/password_manager/core/common/password_manager_ui.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/sync/driver/test_sync_service.h" #include "components/ukm/test_ukm_recorder.h" #include "content/public/browser/web_contents.h"
diff --git a/chrome/browser/ui/passwords/manage_passwords_test.cc b/chrome/browser/ui/passwords/manage_passwords_test.cc index b7b59b3..0cedc70 100644 --- a/chrome/browser/ui/passwords/manage_passwords_test.cc +++ b/chrome/browser/ui/passwords/manage_passwords_test.cc
@@ -23,6 +23,7 @@ #include "components/password_manager/core/browser/password_form_manager.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/stub_form_saver.h" +#include "content/public/test/test_utils.h" namespace { constexpr char kTestOrigin[] = "https://www.example.com";
diff --git a/chrome/browser/ui/passwords/password_dialog_controller_impl_unittest.cc b/chrome/browser/ui/passwords/password_dialog_controller_impl_unittest.cc index 557860c..c036de6 100644 --- a/chrome/browser/ui/passwords/password_dialog_controller_impl_unittest.cc +++ b/chrome/browser/ui/passwords/password_dialog_controller_impl_unittest.cc
@@ -18,7 +18,7 @@ #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/ui/passwords/passwords_model_delegate_mock.cc b/chrome/browser/ui/passwords/passwords_model_delegate_mock.cc index cf300af..b36d8ee 100644 --- a/chrome/browser/ui/passwords/passwords_model_delegate_mock.cc +++ b/chrome/browser/ui/passwords/passwords_model_delegate_mock.cc
@@ -5,7 +5,7 @@ #include "chrome/browser/ui/passwords/passwords_model_delegate_mock.h" #include "components/autofill/core/common/password_form.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" PasswordsModelDelegateMock::PasswordsModelDelegateMock() = default;
diff --git a/chrome/browser/ui/signin_view_controller.cc b/chrome/browser/ui/signin_view_controller.cc index 3855dfd..543518ed 100644 --- a/chrome/browser/ui/signin_view_controller.cc +++ b/chrome/browser/ui/signin_view_controller.cc
@@ -21,7 +21,7 @@ #include "chrome/browser/ui/singleton_tabs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/webui_url_constants.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/web_contents.h" #include "google_apis/gaia/gaia_auth_util.h"
diff --git a/chrome/browser/ui/signin_view_controller_interactive_uitest.cc b/chrome/browser/ui/signin_view_controller_interactive_uitest.cc index bbb3d70..452a65c 100644 --- a/chrome/browser/ui/signin_view_controller_interactive_uitest.cc +++ b/chrome/browser/ui/signin_view_controller_interactive_uitest.cc
@@ -10,7 +10,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h"
diff --git a/chrome/browser/ui/startup/credential_provider_signin_dialog_win.cc b/chrome/browser/ui/startup/credential_provider_signin_dialog_win.cc index 732ae8ec..059df2b 100644 --- a/chrome/browser/ui/startup/credential_provider_signin_dialog_win.cc +++ b/chrome/browser/ui/startup/credential_provider_signin_dialog_win.cc
@@ -22,7 +22,7 @@ #include "chrome/credential_provider/common/gcp_strings.h" #include "components/keep_alive_registry/keep_alive_types.h" #include "components/keep_alive_registry/scoped_keep_alive.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_ui_message_handler.h"
diff --git a/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc b/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc index fc1d12b..6d180f6 100644 --- a/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc +++ b/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc
@@ -141,10 +141,8 @@ } Browser* CloseBrowserAndOpenNew(Browser* browser, Profile* profile) { - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(browser)); browser->window()->Close(); - observer.Wait(); + ui_test_utils::WaitForBrowserToClose(browser); return OpenNewBrowser(profile); }
diff --git a/chrome/browser/ui/toolbar/app_menu_model.cc b/chrome/browser/ui/toolbar/app_menu_model.cc index 102ce7a2..c6b17eca 100644 --- a/chrome/browser/ui/toolbar/app_menu_model.cc +++ b/chrome/browser/ui/toolbar/app_menu_model.cc
@@ -54,7 +54,7 @@ #include "components/bookmarks/common/bookmark_pref_names.h" #include "components/dom_distiller/core/dom_distiller_switches.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/strings/grit/components_strings.h" #include "components/vector_icons/vector_icons.h" #include "components/zoom/zoom_controller.h"
diff --git a/chrome/browser/ui/toolbar/browser_actions_bar_browsertest.cc b/chrome/browser/ui/toolbar/browser_actions_bar_browsertest.cc index 3a217e8..955db24 100644 --- a/chrome/browser/ui/toolbar/browser_actions_bar_browsertest.cc +++ b/chrome/browser/ui/toolbar/browser_actions_bar_browsertest.cc
@@ -968,10 +968,7 @@ void WaitForUserDismissal() override { // Since this UI is shown in the browser's toolbar, just consider closing // the browser to be dismissal. - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); - observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); } private:
diff --git a/chrome/browser/ui/user_manager.h b/chrome/browser/ui/user_manager.h index cf0e188..79bd4c01 100644 --- a/chrome/browser/ui/user_manager.h +++ b/chrome/browser/ui/user_manager.h
@@ -9,7 +9,7 @@ #include "base/macros.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile_window.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "content/public/browser/web_contents_delegate.h" namespace base {
diff --git a/chrome/browser/ui/views/autofill/payments/save_card_bubble_views.h b/chrome/browser/ui/views/autofill/payments/save_card_bubble_views.h index 75c149b9..3712279 100644 --- a/chrome/browser/ui/views/autofill/payments/save_card_bubble_views.h +++ b/chrome/browser/ui/views/autofill/payments/save_card_bubble_views.h
@@ -11,7 +11,7 @@ #include "chrome/browser/ui/sync/bubble_sync_promo_delegate.h" #include "chrome/browser/ui/views/location_bar/location_bar_bubble_delegate_view.h" #include "components/autofill/core/browser/ui/payments/save_card_bubble_controller.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" namespace content { class WebContents;
diff --git a/chrome/browser/ui/views/autofill/payments/save_card_bubble_views_browsertest.cc b/chrome/browser/ui/views/autofill/payments/save_card_bubble_views_browsertest.cc index e54b8d8..e4c98a61 100644 --- a/chrome/browser/ui/views/autofill/payments/save_card_bubble_views_browsertest.cc +++ b/chrome/browser/ui/views/autofill/payments/save_card_bubble_views_browsertest.cc
@@ -51,7 +51,7 @@ #include "components/autofill/core/common/autofill_payments_features.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/network_session_configurator/common/network_switches.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/sync/driver/profile_sync_service.h"
diff --git a/chrome/browser/ui/views/autofill/payments/save_card_manage_cards_bubble_views.cc b/chrome/browser/ui/views/autofill/payments/save_card_manage_cards_bubble_views.cc index 513434d..91cdad0 100644 --- a/chrome/browser/ui/views/autofill/payments/save_card_manage_cards_bubble_views.cc +++ b/chrome/browser/ui/views/autofill/payments/save_card_manage_cards_bubble_views.cc
@@ -10,7 +10,7 @@ #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/views/autofill/payments/dialog_view_ids.h" #include "chrome/browser/ui/views/chrome_typography.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/md_text_button.h"
diff --git a/chrome/browser/ui/views/autofill/payments/save_card_sign_in_promo_bubble_views.cc b/chrome/browser/ui/views/autofill/payments/save_card_sign_in_promo_bubble_views.cc index 55179f0d..b302f2b 100644 --- a/chrome/browser/ui/views/autofill/payments/save_card_sign_in_promo_bubble_views.cc +++ b/chrome/browser/ui/views/autofill/payments/save_card_sign_in_promo_bubble_views.cc
@@ -12,7 +12,7 @@ #include "chrome/browser/ui/views/autofill/payments/dialog_view_ids.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/grit/generated_resources.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/layout/box_layout.h"
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bubble_sign_in_delegate_browsertest.cc b/chrome/browser/ui/views/bookmarks/bookmark_bubble_sign_in_delegate_browsertest.cc index 4b5ad5c..447f503 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bubble_sign_in_delegate_browsertest.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bubble_sign_in_delegate_browsertest.cc
@@ -23,8 +23,8 @@ #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/identity_manager/account_info.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" #include "ui/events/event_constants.h"
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc index 67c21059..b7d4b0c7 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc
@@ -21,7 +21,7 @@ #include "chrome/grit/generated_resources.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_utils.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/events/keycodes/keyboard_codes.h"
diff --git a/chrome/browser/ui/views/extensions/extension_installed_bubble_view.cc b/chrome/browser/ui/views/extensions/extension_installed_bubble_view.cc index 510862c1..fdd39d0 100644 --- a/chrome/browser/ui/views/extensions/extension_installed_bubble_view.cc +++ b/chrome/browser/ui/views/extensions/extension_installed_bubble_view.cc
@@ -34,8 +34,8 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/bubble/bubble_controller.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/identity_manager/account_info.h" #include "extensions/common/extension.h" #include "ui/base/buildflags.h" #include "ui/base/l10n/l10n_util.h"
diff --git a/chrome/browser/ui/views/extensions/extensions_menu_view.cc b/chrome/browser/ui/views/extensions/extensions_menu_view.cc index df1b77c..aa44a76 100644 --- a/chrome/browser/ui/views/extensions/extensions_menu_view.cc +++ b/chrome/browser/ui/views/extensions/extensions_menu_view.cc
@@ -5,7 +5,6 @@ #include "chrome/browser/ui/views/extensions/extensions_menu_view.h" #include "base/memory/ptr_util.h" -#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/chrome_pages.h" @@ -14,6 +13,7 @@ #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/views/extensions/extensions_menu_button.h" #include "chrome/grit/generated_resources.h" +#include "components/vector_icons/vector_icons.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/paint_vector_icon.h" @@ -102,7 +102,7 @@ AddChildView(std::make_unique<views::Separator>()); auto icon_view = CreateFixedSizeIconView(); - icon_view->SetImage(CreateVectorIcon(kSettingsIcon)); + icon_view->SetImage(CreateVectorIcon(vector_icons::kSettingsIcon)); auto footer = std::make_unique<HoverButton>( this, std::move(icon_view), l10n_util::GetStringUTF16(IDS_MANAGE_EXTENSION), base::string16());
diff --git a/chrome/browser/ui/views/frame/browser_frame_header_ash.cc b/chrome/browser/ui/views/frame/browser_frame_header_ash.cc index 94c9c7f..73c9ec9 100644 --- a/chrome/browser/ui/views/frame/browser_frame_header_ash.cc +++ b/chrome/browser/ui/views/frame/browser_frame_header_ash.cc
@@ -7,8 +7,8 @@ #include "ash/public/cpp/ash_constants.h" #include "ash/public/cpp/caption_buttons/frame_caption_button_container_view.h" #include "ash/public/cpp/frame_utils.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/logging.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/ui/ash/tablet_mode_client.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColor.h"
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc index 963219b..34681f5 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc
@@ -12,7 +12,6 @@ #include "ash/public/cpp/immersive/immersive_fullscreen_controller_test_api.h" #include "ash/public/cpp/shelf_test_api.h" #include "ash/public/cpp/test/shell_test_api.h" -#include "ash/public/cpp/vector_icons/vector_icons.h" #include "ash/public/cpp/window_pin_type.h" #include "ash/public/cpp/window_properties.h" #include "ash/public/interfaces/constants.mojom.h" @@ -26,6 +25,7 @@ #include "base/test/metrics/histogram_tester.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/command_updater.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h"
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 07d9a7f..254d61c2 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -138,7 +138,7 @@ #include "components/prefs/pref_service.h" #include "components/safe_browsing/password_protection/metrics_util.h" #include "components/sessions/core/tab_restore_service.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/translate/core/browser/language_state.h" #include "components/version_info/channel.h" #include "components/web_modal/web_contents_modal_dialog_manager.h"
diff --git a/chrome/browser/ui/views/frame/test_with_browser_view.cc b/chrome/browser/ui/views/frame/test_with_browser_view.cc index 8279d68..2dad23d4 100644 --- a/chrome/browser/ui/views/frame/test_with_browser_view.cc +++ b/chrome/browser/ui/views/frame/test_with_browser_view.cc
@@ -27,7 +27,7 @@ #include "components/omnibox/browser/test_scheme_classifier.h" #include "components/search_engines/search_terms_data.h" #include "components/search_engines/template_url_service.h" -#include "components/signin/core/browser/list_accounts_test_utils.h" +#include "components/signin/public/base/list_accounts_test_utils.h" #include "content/public/test/test_utils.h" #include "services/network/test/test_url_loader_factory.h"
diff --git a/chrome/browser/ui/views/hats/hats_bubble_view.cc b/chrome/browser/ui/views/hats/hats_bubble_view.cc index 1fa262f7..07f31ca 100644 --- a/chrome/browser/ui/views/hats/hats_bubble_view.cc +++ b/chrome/browser/ui/views/hats/hats_bubble_view.cc
@@ -19,7 +19,6 @@ #include "content/public/browser/web_contents.h" #include "ui/base/buildflags.h" #include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/view.h" @@ -53,6 +52,10 @@ browser_(browser) { chrome::RecordDialogCreation(chrome::DialogIdentifier::HATS_BUBBLE); + set_close_on_deactivate(false); + set_parent_window(parent_view); + set_margins(gfx::Insets()); + auto* layout_manager = SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets(10, 20, 10, 0), 10)); @@ -61,20 +64,11 @@ layout_manager->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::kStart); - // Add Logo icon. - auto icon_view = std::make_unique<views::ImageView>(); - icon_view->SetImage(ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( - IDR_PRODUCT_LOGO_32)); - AddChildView(std::move(icon_view)); - auto message = std::make_unique<views::Label>( l10n_util::GetStringUTF16(IDS_HATS_BUBBLE_TEXT)); message->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); AddChildView(std::move(message)); - set_parent_window(parent_view); - set_margins(gfx::Insets()); - views::BubbleDialogDelegateView::CreateBubble(this); instance_ = this;
diff --git a/chrome/browser/ui/views/location_bar/location_icon_view_interactive_uitest.cc b/chrome/browser/ui/views/location_bar/location_icon_view_interactive_uitest.cc index bc3bc7c..8311604 100644 --- a/chrome/browser/ui/views/location_bar/location_icon_view_interactive_uitest.cc +++ b/chrome/browser/ui/views/location_bar/location_icon_view_interactive_uitest.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "content/public/test/test_utils.h" namespace {
diff --git a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.cc b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.cc index 29ecb23c..4351fcb 100644 --- a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.cc +++ b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.cc
@@ -13,50 +13,45 @@ #include "chrome/browser/ui/views/frame/top_container_view.h" #include "chrome/browser/ui/views/media_router/cast_dialog_view.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" +#include "content/public/browser/web_contents.h" + +using content::WebContents; namespace media_router { -// static -MediaRouterDialogControllerImplBase* -MediaRouterDialogControllerImplBase::GetOrCreateForWebContents( - content::WebContents* web_contents) { - return MediaRouterDialogControllerViews::GetOrCreateForWebContents( - web_contents); +namespace { + +MediaRouterUIService* GetMediaRouterUIService(WebContents* web_contents) { + Profile* profile = + Profile::FromBrowserContext(web_contents->GetBrowserContext()); + return MediaRouterUIService::Get(profile); } +} // namespace + // static -MediaRouterDialogControllerImplBase* -MediaRouterDialogControllerImplBase::FromWebContents( +MediaRouterDialogController* +MediaRouterDialogController::GetOrCreateForWebContents( content::WebContents* web_contents) { + DCHECK(web_contents); + // This call does nothing if the controller already exists. + MediaRouterDialogControllerViews::CreateForWebContents(web_contents); return MediaRouterDialogControllerViews::FromWebContents(web_contents); } MediaRouterDialogControllerViews::~MediaRouterDialogControllerViews() { Reset(); - if (dialog_widget_) { - dialog_widget_->RemoveObserver(this); - dialog_widget_ = nullptr; - } -} - -// static -MediaRouterDialogControllerViews* -MediaRouterDialogControllerViews::GetOrCreateForWebContents( - content::WebContents* web_contents) { - DCHECK(web_contents); - // This call does nothing if the controller already exists. - CreateForWebContents(web_contents); - return FromWebContents(web_contents); + media_router_ui_service_->RemoveObserver(this); } void MediaRouterDialogControllerViews::CreateMediaRouterDialog() { base::Time dialog_creation_time = base::Time::Now(); - MediaRouterDialogControllerImplBase::CreateMediaRouterDialog(); + if (GetActionController()) + GetActionController()->OnDialogShown(); Profile* profile = Profile::FromBrowserContext(initiator()->GetBrowserContext()); - ui_ = std::make_unique<MediaRouterViewsUI>(); - InitializeMediaRouterUI(ui_.get()); + InitializeMediaRouterUI(); Browser* browser = chrome::FindBrowserWithWebContents(initiator()); if (browser) { @@ -76,8 +71,7 @@ CastDialogView::ShowDialogCentered(anchor_bounds, ui_.get(), profile, dialog_creation_time); } - dialog_widget_ = CastDialogView::GetCurrentDialogWidget(); - dialog_widget_->AddObserver(this); + scoped_widget_observer_.Add(CastDialogView::GetCurrentDialogWidget()); if (dialog_creation_callback_) dialog_creation_callback_.Run(); } @@ -93,16 +87,17 @@ void MediaRouterDialogControllerViews::Reset() { // If |ui_| is null, Reset() has already been called. if (ui_) { - MediaRouterDialogControllerImplBase::Reset(); + if (IsShowingMediaRouterDialog() && GetActionController()) + GetActionController()->OnDialogHidden(); ui_.reset(); + MediaRouterDialogController::Reset(); } } void MediaRouterDialogControllerViews::OnWidgetClosing(views::Widget* widget) { - DCHECK_EQ(dialog_widget_, widget); + DCHECK(scoped_widget_observer_.IsObserving(widget)); Reset(); - dialog_widget_->RemoveObserver(this); - dialog_widget_ = nullptr; + scoped_widget_observer_.Remove(widget); } void MediaRouterDialogControllerViews::SetDialogCreationCallbackForTesting( @@ -111,8 +106,35 @@ } MediaRouterDialogControllerViews::MediaRouterDialogControllerViews( - content::WebContents* web_contents) - : MediaRouterDialogControllerImplBase(web_contents) {} + WebContents* web_contents) + : MediaRouterDialogController(web_contents), + scoped_widget_observer_(this), + media_router_ui_service_(GetMediaRouterUIService(web_contents)) { + DCHECK(media_router_ui_service_); + media_router_ui_service_->AddObserver(this); +} + +void MediaRouterDialogControllerViews::OnServiceDisabled() { + CloseMediaRouterDialog(); + Reset(); +} + +void MediaRouterDialogControllerViews::InitializeMediaRouterUI() { + ui_ = std::make_unique<MediaRouterViewsUI>(); + PresentationServiceDelegateImpl* delegate = + PresentationServiceDelegateImpl::FromWebContents(initiator()); + if (!start_presentation_context_) { + ui_->InitWithDefaultMediaSource(initiator(), delegate); + } else { + ui_->InitWithStartPresentationContext( + initiator(), delegate, std::move(start_presentation_context_)); + } +} + +MediaRouterActionController* +MediaRouterDialogControllerViews::GetActionController() { + return media_router_ui_service_->action_controller(); +} WEB_CONTENTS_USER_DATA_KEY_IMPL(MediaRouterDialogControllerViews)
diff --git a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h index 1c40ff9..d6a08f7 100644 --- a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h +++ b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h
@@ -9,7 +9,9 @@ #include "base/macros.h" #include "base/observer_list.h" -#include "chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.h" +#include "base/scoped_observer.h" +#include "chrome/browser/media/router/media_router_dialog_controller.h" +#include "chrome/browser/ui/media_router/media_router_ui_service.h" #include "chrome/browser/ui/views/media_router/media_router_views_ui.h" #include "ui/views/widget/widget_observer.h" @@ -18,16 +20,12 @@ // A Views implementation of MediaRouterDialogController. class MediaRouterDialogControllerViews : public content::WebContentsUserData<MediaRouterDialogControllerViews>, - public MediaRouterDialogControllerImplBase, - public views::WidgetObserver { + public MediaRouterDialogController, + public views::WidgetObserver, + public MediaRouterUIService::Observer { public: ~MediaRouterDialogControllerViews() override; - static MediaRouterDialogControllerViews* GetOrCreateForWebContents( - content::WebContents* web_contents); - using content::WebContentsUserData< - MediaRouterDialogControllerViews>::FromWebContents; - // MediaRouterDialogController: void CreateMediaRouterDialog() override; void CloseMediaRouterDialog() override; @@ -48,6 +46,16 @@ // an instance. explicit MediaRouterDialogControllerViews(content::WebContents* web_contents); + // MediaRouterUIService::Observer: + void OnServiceDisabled() override; + + // Initializes |ui_|. + void InitializeMediaRouterUI(); + + // MediaRouterActionController is responsible for showing and hiding the + // toolbar action. It's owned by MediaRouterUIService and it may be nullptr. + MediaRouterActionController* GetActionController(); + MediaRouterViewsUI* ui() { return ui_.get(); } // Responsible for notifying the dialog view of dialog model updates and @@ -57,9 +65,10 @@ base::RepeatingClosure dialog_creation_callback_; - // This is not null while there is a dialog shown and |this| is observing the - // widget. - views::Widget* dialog_widget_ = nullptr; + ScopedObserver<views::Widget, views::WidgetObserver> scoped_widget_observer_; + + // Service that provides MediaRouterActionController. It outlives |this|. + MediaRouterUIService* const media_router_ui_service_; WEB_CONTENTS_USER_DATA_KEY_DECL();
diff --git a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views_browsertest.cc b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views_browsertest.cc index b98ca2f5..b696abf 100644 --- a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views_browsertest.cc +++ b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views_browsertest.cc
@@ -40,8 +40,8 @@ // Create a reference to initiator contents. initiator_ = browser()->tab_strip_model()->GetActiveWebContents(); - dialog_controller_ = - MediaRouterDialogControllerViews::GetOrCreateForWebContents(initiator_); + dialog_controller_ = static_cast<MediaRouterDialogControllerViews*>( + MediaRouterDialogController::GetOrCreateForWebContents(initiator_)); ASSERT_TRUE(dialog_controller_); // Show the media router dialog for the initiator.
diff --git a/chrome/browser/ui/views/media_router/media_router_ui_browsertest.cc b/chrome/browser/ui/views/media_router/media_router_ui_browsertest.cc index f3145887..53144625 100644 --- a/chrome/browser/ui/views/media_router/media_router_ui_browsertest.cc +++ b/chrome/browser/ui/views/media_router/media_router_ui_browsertest.cc
@@ -8,6 +8,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" +#include "chrome/browser/media/router/media_router_dialog_controller.h" #include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" @@ -15,7 +16,6 @@ #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/extensions/browser_action_test_util.h" -#include "chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.h" #include "chrome/browser/ui/media_router/media_router_ui_service.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/toolbar/media_router_action_controller.h" @@ -57,8 +57,8 @@ } // Returns the dialog controller for the active WebContents. - MediaRouterDialogControllerImplBase* GetDialogController() { - return MediaRouterDialogControllerImplBase::GetOrCreateForWebContents( + MediaRouterDialogController* GetDialogController() { + return MediaRouterDialogController::GetOrCreateForWebContents( browser()->tab_strip_model()->GetActiveWebContents()); }
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view.cc b/chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view.cc new file mode 100644 index 0000000..f5ba6916 --- /dev/null +++ b/chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view.cc
@@ -0,0 +1,152 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view.h" + +#include "base/files/file_path.h" +#include "chrome/app/vector_icons/vector_icons.h" +#include "chrome/browser/ui/views/chrome_layout_provider.h" +#include "chrome/browser/ui/views/chrome_typography.h" +#include "chrome/grit/generated_resources.h" +#include "components/constrained_window/constrained_window_views.h" +#include "components/url_formatter/elide_url.h" +#include "components/vector_icons/vector_icons.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/gfx/paint_vector_icon.h" +#include "ui/strings/grit/ui_strings.h" +#include "ui/views/controls/image_view.h" +#include "ui/views/controls/label.h" +#include "ui/views/controls/styled_label.h" +#include "ui/views/layout/box_layout.h" +#include "ui/views/window/dialog_client_view.h" + +NativeFileSystemDirectoryAccessConfirmationView:: + ~NativeFileSystemDirectoryAccessConfirmationView() { + // Make sure the dialog ends up calling the callback no matter what. + if (!callback_.is_null()) + Close(); +} + +// static +views::Widget* NativeFileSystemDirectoryAccessConfirmationView::ShowDialog( + const url::Origin& origin, + const base::FilePath& path, + base::OnceCallback<void(PermissionAction result)> callback, + content::WebContents* web_contents) { + auto delegate = + base::WrapUnique(new NativeFileSystemDirectoryAccessConfirmationView( + origin, path, std::move(callback))); + return constrained_window::ShowWebModalDialogViews(delegate.release(), + web_contents); +} + +base::string16 NativeFileSystemDirectoryAccessConfirmationView::GetWindowTitle() + const { + return l10n_util::GetStringUTF16( + IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TITLE); +} + +int NativeFileSystemDirectoryAccessConfirmationView::GetDefaultDialogButton() + const { + return ui::DIALOG_BUTTON_NONE; +} + +base::string16 +NativeFileSystemDirectoryAccessConfirmationView::GetDialogButtonLabel( + ui::DialogButton button) const { + if (button == ui::DIALOG_BUTTON_OK) + return l10n_util::GetStringUTF16(IDS_PERMISSION_ALLOW); + return l10n_util::GetStringUTF16(IDS_APP_CANCEL); +} + +bool NativeFileSystemDirectoryAccessConfirmationView::ShouldShowCloseButton() + const { + return false; +} + +bool NativeFileSystemDirectoryAccessConfirmationView::Accept() { + std::move(callback_).Run(PermissionAction::GRANTED); + return true; +} + +bool NativeFileSystemDirectoryAccessConfirmationView::Cancel() { + std::move(callback_).Run(PermissionAction::DISMISSED); + return true; +} + +gfx::Size +NativeFileSystemDirectoryAccessConfirmationView::CalculatePreferredSize() + const { + const int width = ChromeLayoutProvider::Get()->GetDistanceMetric( + DISTANCE_MODAL_DIALOG_PREFERRED_WIDTH) - + margins().width(); + return gfx::Size(width, GetHeightForWidth(width)); +} + +ui::ModalType NativeFileSystemDirectoryAccessConfirmationView::GetModalType() + const { + return ui::MODAL_TYPE_CHILD; +} + +NativeFileSystemDirectoryAccessConfirmationView:: + NativeFileSystemDirectoryAccessConfirmationView( + const url::Origin& origin, + const base::FilePath& path, + base::OnceCallback<void(PermissionAction result)> callback) + : callback_(std::move(callback)) { + const views::LayoutProvider* provider = ChromeLayoutProvider::Get(); + SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical, + provider->GetDialogInsetsForContentType(views::TEXT, views::TEXT), + provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL))); + + base::string16 formatted_origin = + url_formatter::FormatOriginForSecurityDisplay( + origin, url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC); + size_t offset; + auto label = std::make_unique<views::StyledLabel>( + l10n_util::GetStringFUTF16( + IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TEXT, + formatted_origin, &offset), + nullptr); + label->SetTextContext(CONTEXT_BODY_TEXT_SMALL); + label->SetDefaultTextStyle(STYLE_SECONDARY); + label->SetHorizontalAlignment(gfx::ALIGN_LEFT); + + views::StyledLabel::RangeStyleInfo origin_style; + origin_style.text_style = STYLE_EMPHASIZED_SECONDARY; + label->AddStyleRange(gfx::Range(offset, offset + formatted_origin.length()), + origin_style); + + AddChildView(std::move(label)); + + auto file_label_container = std::make_unique<views::View>(); + int indent = + provider->GetDistanceMetric(DISTANCE_SUBSECTION_HORIZONTAL_INDENT); + file_label_container->SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kHorizontal, + gfx::Insets(/*vertical=*/0, indent), + provider->GetDistanceMetric(views::DISTANCE_RELATED_LABEL_HORIZONTAL))); + auto icon = std::make_unique<views::ImageView>(); + const SkColor icon_color = icon->GetNativeTheme()->GetSystemColor( + ui::NativeTheme::kColorId_DefaultIconColor); + icon->SetImage(gfx::CreateVectorIcon(vector_icons::kFolderOpenIcon, + /*dip_size=*/18, icon_color)); + file_label_container->AddChildView(std::move(icon)); + auto file_label = std::make_unique<views::Label>(path.LossyDisplayName(), + CONTEXT_BODY_TEXT_SMALL, + STYLE_EMPHASIZED_SECONDARY); + file_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); + file_label_container->AddChildView(std::move(file_label)); + AddChildView(std::move(file_label_container)); +} + +void ShowNativeFileSystemDirectoryAccessConfirmationDialog( + const url::Origin& origin, + const base::FilePath& path, + base::OnceCallback<void(PermissionAction result)> callback, + content::WebContents* web_contents) { + NativeFileSystemDirectoryAccessConfirmationView::ShowDialog( + origin, path, std::move(callback), web_contents); +}
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view.h b/chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view.h new file mode 100644 index 0000000..6d8cb745 --- /dev/null +++ b/chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view.h
@@ -0,0 +1,66 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_VIEW_H_ +#define CHROME_BROWSER_UI_VIEWS_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_VIEW_H_ + +#include "base/macros.h" +#include "base/strings/string16.h" +#include "chrome/browser/permissions/permission_util.h" +#include "ui/views/window/dialog_delegate.h" + +namespace base { +class FilePath; +} + +namespace content { +class WebContents; +} // namespace content + +namespace url { +class Origin; +} // namespace url + +namespace views { +class Widget; +} // namespace views + +// A dialog similar to FolderUploadConfirmationView that confirms that the user +// intended to give access to the specific folder. +// This is also a security measure against sites that trick a user into pressing +// enter, which would instantly confirm the OS folder picker and share the +// default folder selection without explicit user approval. +class NativeFileSystemDirectoryAccessConfirmationView + : public views::DialogDelegateView { + public: + ~NativeFileSystemDirectoryAccessConfirmationView() override; + + static views::Widget* ShowDialog( + const url::Origin& origin, + const base::FilePath& path, + base::OnceCallback<void(PermissionAction result)> callback, + content::WebContents* web_contents); + + // views::DialogDelegateView: + base::string16 GetWindowTitle() const override; + int GetDefaultDialogButton() const override; + base::string16 GetDialogButtonLabel(ui::DialogButton button) const override; + bool ShouldShowCloseButton() const override; + bool Accept() override; + bool Cancel() override; + gfx::Size CalculatePreferredSize() const override; + ui::ModalType GetModalType() const override; + + private: + NativeFileSystemDirectoryAccessConfirmationView( + const url::Origin& origin, + const base::FilePath& path, + base::OnceCallback<void(PermissionAction result)> callback); + + base::OnceCallback<void(PermissionAction result)> callback_; + + DISALLOW_COPY_AND_ASSIGN(NativeFileSystemDirectoryAccessConfirmationView); +}; + +#endif // CHROME_BROWSER_UI_VIEWS_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_VIEW_H_
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view_browsertest.cc b/chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view_browsertest.cc new file mode 100644 index 0000000..10ccc6e --- /dev/null +++ b/chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view_browsertest.cc
@@ -0,0 +1,51 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view.h" + +#include "base/files/file_path.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/test/test_browser_dialog.h" +#include "chrome/grit/generated_resources.h" +#include "ui/base/resource/resource_bundle.h" + +class NativeFileSystemRestrictedDirectoryDialogViewTest + : public DialogBrowserTest { + public: + void SetUpOnMainThread() override { + // Release builds may strip out unused string resources when + // enable_resource_whitelist_generation is enabled. Manually override the + // strings needed by the dialog to ensure they are available for tests. + // TODO(https://crbug.com/979659): Remove these overrides once the strings + // are referenced from the Chrome binary. + auto& shared_resource_bundle = ui::ResourceBundle::GetSharedInstance(); + shared_resource_bundle.OverrideLocaleStringResource( + IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TITLE, + base::ASCIIToUTF16("Can't save to this folder")); + shared_resource_bundle.OverrideLocaleStringResource( + IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TEXT, + base::ASCIIToUTF16("$1 can't save your changes to this folder because " + "it contains system files.")); + shared_resource_bundle.OverrideLocaleStringResource( + IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_BUTTON, + base::ASCIIToUTF16("Choose a different folder")); + } + + // DialogBrowserTest: + void ShowUi(const std::string& name) override { + NativeFileSystemRestrictedDirectoryDialogView::ShowDialog( + kTestOrigin, base::FilePath(FILE_PATH_LITERAL("/foo/bar")), + base::DoNothing(), + browser()->tab_strip_model()->GetActiveWebContents()); + } + + protected: + const url::Origin kTestOrigin = + url::Origin::Create(GURL("https://example.com")); +}; + +IN_PROC_BROWSER_TEST_F(NativeFileSystemRestrictedDirectoryDialogViewTest, + InvokeUi_default) { + ShowAndVerifyUi(); +}
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view.cc b/chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view.cc new file mode 100644 index 0000000..c60143f --- /dev/null +++ b/chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view.cc
@@ -0,0 +1,108 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view.h" + +#include "chrome/browser/ui/views/chrome_layout_provider.h" +#include "chrome/browser/ui/views/chrome_typography.h" +#include "chrome/grit/generated_resources.h" +#include "components/constrained_window/constrained_window_views.h" +#include "components/url_formatter/elide_url.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/views/controls/label.h" +#include "ui/views/layout/fill_layout.h" +#include "ui/views/window/dialog_client_view.h" + +NativeFileSystemRestrictedDirectoryDialogView:: + ~NativeFileSystemRestrictedDirectoryDialogView() { + // Make sure the dialog ends up calling the callback no matter what. + if (!callback_.is_null()) + Accept(); +} + +// static +views::Widget* NativeFileSystemRestrictedDirectoryDialogView::ShowDialog( + const url::Origin& origin, + const base::FilePath& path, + base::OnceClosure callback, + content::WebContents* web_contents) { + auto delegate = + base::WrapUnique(new NativeFileSystemRestrictedDirectoryDialogView( + origin, path, std::move(callback))); + return constrained_window::ShowWebModalDialogViews(delegate.release(), + web_contents); +} + +base::string16 NativeFileSystemRestrictedDirectoryDialogView::GetWindowTitle() + const { + return l10n_util::GetStringUTF16( + IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TITLE); +} + +int NativeFileSystemRestrictedDirectoryDialogView::GetDialogButtons() const { + return ui::DIALOG_BUTTON_OK; +} + +base::string16 +NativeFileSystemRestrictedDirectoryDialogView::GetDialogButtonLabel( + ui::DialogButton button) const { + return l10n_util::GetStringUTF16( + IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_BUTTON); +} + +bool NativeFileSystemRestrictedDirectoryDialogView::ShouldShowCloseButton() + const { + return false; +} + +bool NativeFileSystemRestrictedDirectoryDialogView::Accept() { + std::move(callback_).Run(); + return true; +} + +bool NativeFileSystemRestrictedDirectoryDialogView::Cancel() { + std::move(callback_).Run(); + return true; +} + +gfx::Size +NativeFileSystemRestrictedDirectoryDialogView::CalculatePreferredSize() const { + const int width = ChromeLayoutProvider::Get()->GetDistanceMetric( + DISTANCE_MODAL_DIALOG_PREFERRED_WIDTH) - + margins().width(); + return gfx::Size(width, GetHeightForWidth(width)); +} + +ui::ModalType NativeFileSystemRestrictedDirectoryDialogView::GetModalType() + const { + return ui::MODAL_TYPE_CHILD; +} + +NativeFileSystemRestrictedDirectoryDialogView:: + NativeFileSystemRestrictedDirectoryDialogView(const url::Origin& origin, + const base::FilePath& path, + base::OnceClosure callback) + : callback_(std::move(callback)) { + SetLayoutManager(std::make_unique<views::FillLayout>()); + auto label = std::make_unique<views::Label>( + l10n_util::GetStringFUTF16( + IDS_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_TEXT, + url_formatter::FormatOriginForSecurityDisplay( + origin, url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC)), + CONTEXT_BODY_TEXT_LARGE, STYLE_SECONDARY); + label->SetMultiLine(true); + label->SetHorizontalAlignment(gfx::ALIGN_LEFT); + AddChildView(label.release()); + set_margins(ChromeLayoutProvider::Get()->GetDialogInsetsForContentType( + views::TEXT, views::TEXT)); +} + +void ShowNativeFileSystemRestrictedDirectoryDialog( + const url::Origin& origin, + const base::FilePath& path, + base::OnceClosure callback, + content::WebContents* web_contents) { + NativeFileSystemRestrictedDirectoryDialogView::ShowDialog( + origin, path, std::move(callback), web_contents); +}
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view.h b/chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view.h new file mode 100644 index 0000000..d704de40 --- /dev/null +++ b/chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view.h
@@ -0,0 +1,62 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_DIALOG_VIEW_H_ +#define CHROME_BROWSER_UI_VIEWS_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_DIALOG_VIEW_H_ + +#include "base/macros.h" +#include "base/strings/string16.h" +#include "ui/views/window/dialog_delegate.h" + +namespace base { +class FilePath; +} + +namespace content { +class WebContents; +} // namespace content + +namespace url { +class Origin; +} // namespace url + +namespace views { +class Widget; +} // namespace views + +// A dialog that informs the user that they can't give a website access to a +// specific folder. +class NativeFileSystemRestrictedDirectoryDialogView + : public views::DialogDelegateView { + public: + ~NativeFileSystemRestrictedDirectoryDialogView() override; + + // Creates and shows the dialog. The |callback| is called when the dialog is + // dismissed. + static views::Widget* ShowDialog(const url::Origin& origin, + const base::FilePath& path, + base::OnceClosure callback, + content::WebContents* web_contents); + + // views::DialogDelegateView: + base::string16 GetWindowTitle() const override; + int GetDialogButtons() const override; + base::string16 GetDialogButtonLabel(ui::DialogButton button) const override; + bool ShouldShowCloseButton() const override; + bool Accept() override; + bool Cancel() override; + gfx::Size CalculatePreferredSize() const override; + ui::ModalType GetModalType() const override; + + private: + NativeFileSystemRestrictedDirectoryDialogView(const url::Origin& origin, + const base::FilePath& path, + base::OnceClosure callback); + + base::OnceClosure callback_; + + DISALLOW_COPY_AND_ASSIGN(NativeFileSystemRestrictedDirectoryDialogView); +}; + +#endif // CHROME_BROWSER_UI_VIEWS_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_RESTRICTED_DIRECTORY_DIALOG_VIEW_H_
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view_browsertest.cc b/chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view_browsertest.cc new file mode 100644 index 0000000..b9f3006 --- /dev/null +++ b/chrome/browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view_browsertest.cc
@@ -0,0 +1,96 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view.h" + +#include "base/files/file_path.h" +#include "base/test/bind_test_util.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/test/test_browser_dialog.h" +#include "chrome/grit/generated_resources.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/views/controls/button/label_button.h" +#include "ui/views/window/dialog_client_view.h" + +class NativeFileSystemDirectoryAccessConfirmationViewTest + : public DialogBrowserTest { + public: + void SetUpOnMainThread() override { + // Release builds may strip out unused string resources when + // enable_resource_whitelist_generation is enabled. Manually override the + // strings needed by the dialog to ensure they are available for tests. + // TODO(https://crbug.com/979659): Remove these overrides once the strings + // are referenced from the Chrome binary. + auto& shared_resource_bundle = ui::ResourceBundle::GetSharedInstance(); + shared_resource_bundle.OverrideLocaleStringResource( + IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TITLE, + base::ASCIIToUTF16("Let site read this folder?")); + shared_resource_bundle.OverrideLocaleStringResource( + IDS_NATIVE_FILE_SYSTEM_DIRECTORY_ACCESS_CONFIRMATION_TEXT, + base::ASCIIToUTF16("$1 will be able to read all files in the following " + "folder. This site can see any changes to the " + "folder only while this tab is open.")); + } + + // DialogBrowserTest: + void ShowUi(const std::string& name) override { + widget_ = NativeFileSystemDirectoryAccessConfirmationView::ShowDialog( + kTestOrigin, base::FilePath(FILE_PATH_LITERAL("/foo/bar")), + base::BindLambdaForTesting([&](PermissionAction result) { + callback_called_ = true; + callback_result_ = result; + }), + browser()->tab_strip_model()->GetActiveWebContents()); + } + + protected: + const url::Origin kTestOrigin = + url::Origin::Create(GURL("https://example.com")); + + views::Widget* widget_ = nullptr; + + bool callback_called_ = false; + PermissionAction callback_result_ = PermissionAction::IGNORED; +}; + +IN_PROC_BROWSER_TEST_F(NativeFileSystemDirectoryAccessConfirmationViewTest, + AcceptIsntDefaultFocused) { + ShowUi(std::string()); + EXPECT_NE(widget_->client_view()->AsDialogClientView()->ok_button(), + widget_->GetFocusManager()->GetFocusedView()); + widget_->Close(); + base::RunLoop().RunUntilIdle(); +} + +IN_PROC_BROWSER_TEST_F(NativeFileSystemDirectoryAccessConfirmationViewTest, + AcceptRunsCallback) { + ShowUi(std::string()); + widget_->client_view()->AsDialogClientView()->AcceptWindow(); + EXPECT_TRUE(callback_called_); + EXPECT_EQ(PermissionAction::GRANTED, callback_result_); + base::RunLoop().RunUntilIdle(); +} + +IN_PROC_BROWSER_TEST_F(NativeFileSystemDirectoryAccessConfirmationViewTest, + CancelRunsCallback) { + ShowUi(std::string()); + widget_->client_view()->AsDialogClientView()->CancelWindow(); + EXPECT_TRUE(callback_called_); + EXPECT_EQ(PermissionAction::DISMISSED, callback_result_); + base::RunLoop().RunUntilIdle(); +} + +IN_PROC_BROWSER_TEST_F(NativeFileSystemDirectoryAccessConfirmationViewTest, + CancelsWhenClosed) { + ShowUi(std::string()); + widget_->Close(); + EXPECT_TRUE(callback_called_); + EXPECT_EQ(PermissionAction::DISMISSED, callback_result_); + base::RunLoop().RunUntilIdle(); +} + +IN_PROC_BROWSER_TEST_F(NativeFileSystemDirectoryAccessConfirmationViewTest, + InvokeUi_default) { + ShowAndVerifyUi(); +}
diff --git a/chrome/browser/ui/views/omnibox/omnibox_view_views_browsertest.cc b/chrome/browser/ui/views/omnibox/omnibox_view_views_browsertest.cc index b528600..6621dcbe 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_view_views_browsertest.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_view_views_browsertest.cc
@@ -23,6 +23,7 @@ #include "chrome/grit/generated_resources.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "components/omnibox/browser/omnibox_popup_model.h" #include "components/omnibox/browser/test_scheme_classifier.h" #include "content/public/browser/web_contents.h"
diff --git a/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc b/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc index 23ec94e..dd14fb8 100644 --- a/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc +++ b/chrome/browser/ui/views/passwords/password_bubble_interactive_uitest.cc
@@ -23,11 +23,11 @@ #include "chrome/browser/ui/views/passwords/password_auto_sign_in_view.h" #include "chrome/browser/ui/views/passwords/password_pending_view.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" -#include "chrome/common/chrome_features.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" -#include "content/public/common/content_features.h" +#include "content/public/test/test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h"
diff --git a/chrome/browser/ui/views/passwords/password_items_view.cc b/chrome/browser/ui/views/passwords/password_items_view.cc index 66ac926..b6bef992 100644 --- a/chrome/browser/ui/views/passwords/password_items_view.cc +++ b/chrome/browser/ui/views/passwords/password_items_view.cc
@@ -116,7 +116,7 @@ const autofill::PasswordForm& form) { std::vector<base::string16> usernames = {form.username_value}; for (const autofill::ValueElementPair& other_possible_username_pair : - form.other_possible_usernames) { + form.all_possible_usernames) { if (other_possible_username_pair.first != form.username_value) usernames.push_back(other_possible_username_pair.first); }
diff --git a/chrome/browser/ui/views/passwords/password_sign_in_promo_view.cc b/chrome/browser/ui/views/passwords/password_sign_in_promo_view.cc index 90946b7..f401e3f 100644 --- a/chrome/browser/ui/views/passwords/password_sign_in_promo_view.cc +++ b/chrome/browser/ui/views/passwords/password_sign_in_promo_view.cc
@@ -13,9 +13,9 @@ #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/grit/generated_resources.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/identity_manager/account_info.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/layout/fill_layout.h"
diff --git a/chrome/browser/ui/views/permission_bubble/permission_bubble_views_interactive_uitest_mac.mm b/chrome/browser/ui/views/permission_bubble/permission_bubble_views_interactive_uitest_mac.mm index 9015e20c..dc5df83 100644 --- a/chrome/browser/ui/views/permission_bubble/permission_bubble_views_interactive_uitest_mac.mm +++ b/chrome/browser/ui/views/permission_bubble/permission_bubble_views_interactive_uitest_mac.mm
@@ -15,6 +15,7 @@ #include "chrome/browser/ui/browser_window.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "content/public/test/test_utils.h" #include "ui/base/test/ui_controls.h" #import "ui/base/test/windowed_nsnotification_observer.h" #include "ui/base/ui_base_features.h"
diff --git a/chrome/browser/ui/views/profiles/dice_accounts_menu.h b/chrome/browser/ui/views/profiles/dice_accounts_menu.h index 85454db..ec34f28 100644 --- a/chrome/browser/ui/views/profiles/dice_accounts_menu.h +++ b/chrome/browser/ui/views/profiles/dice_accounts_menu.h
@@ -9,7 +9,7 @@ #include "base/callback_forward.h" #include "base/optional.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "ui/gfx/image/image.h" #include "ui/views/controls/menu/menu_delegate.h" #include "ui/views/controls/menu/menu_item_view.h"
diff --git a/chrome/browser/ui/views/profiles/profile_chooser_view.cc b/chrome/browser/ui/views/profiles/profile_chooser_view.cc index 46efe149..1f3de0e 100644 --- a/chrome/browser/ui/views/profiles/profile_chooser_view.cc +++ b/chrome/browser/ui/views/profiles/profile_chooser_view.cc
@@ -44,7 +44,7 @@ #include "chrome/grit/generated_resources.h" #include "chrome/grit/theme_resources.h" #include "components/signin/core/browser/signin_error_controller.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" #include "components/sync/driver/sync_service_utils.h" @@ -778,7 +778,7 @@ base::string16 text = l10n_util::GetStringUTF16( is_guest ? IDS_PROFILES_EXIT_GUEST : IDS_PROFILES_MANAGE_USERS_BUTTON); const gfx::VectorIcon& settings_icon = - is_guest ? kCloseAllIcon : kSettingsIcon; + is_guest ? kCloseAllIcon : vector_icons::kSettingsIcon; users_button_ = CreateAndAddButton(CreateVectorIcon(settings_icon), text); if (display_lock) {
diff --git a/chrome/browser/ui/views/profiles/profile_chooser_view_browsertest.cc b/chrome/browser/ui/views/profiles/profile_chooser_view_browsertest.cc index dc8a8f7df..2d82493 100644 --- a/chrome/browser/ui/views/profiles/profile_chooser_view_browsertest.cc +++ b/chrome/browser/ui/views/profiles/profile_chooser_view_browsertest.cc
@@ -2,8 +2,6 @@ // 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_chooser_view.h" - #include <stddef.h> #include "base/command_line.h" @@ -33,14 +31,16 @@ #include "chrome/browser/ui/test/test_browser_dialog.h" #include "chrome/browser/ui/user_manager.h" #include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/profiles/profile_chooser_view.h" #include "chrome/browser/ui/views/profiles/user_manager_view.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" +#include "chrome/test/base/ui_test_utils.h" #include "components/autofill/core/common/autofill_payments_features.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" #include "extensions/browser/extension_registry.h" @@ -142,11 +142,7 @@ CreateTestingProfile(profile_manager->GenerateNextProfileDirectoryPath()); } if (name == kGuest || name == kDiceGuest) { - content::WindowedNotificationObserver browser_creation_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); profiles::SwitchToGuestProfile(ProfileManager::CreateCallback()); - browser_creation_observer.Wait(); Profile* guest = g_browser_process->profile_manager()->GetProfileByPath( ProfileManager::GetGuestProfilePath()); @@ -175,11 +171,6 @@ base::RunLoop().RunUntilIdle(); ASSERT_TRUE(ProfileChooserView::IsShowing()); - - // Create this observer before lock is pressed to avoid a race condition. - window_close_observer_.reset(new content::WindowedNotificationObserver( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::Source<Browser>(browser))); } void OpenProfileChooserViews(Browser* browser) { @@ -217,10 +208,6 @@ return registry; } - content::WindowedNotificationObserver* window_close_observer() { - return window_close_observer_.get(); - } - ProfileChooserView* current_profile_bubble() { return static_cast<ProfileChooserView*>( ProfileChooserView::GetBubbleForTesting()); @@ -235,8 +222,6 @@ } private: - std::unique_ptr<content::WindowedNotificationObserver> window_close_observer_; - DISALLOW_COPY_AND_ASSIGN(ProfileChooserViewExtensionsTest); }; @@ -339,7 +324,8 @@ ClickProfileChooserViewLockButton(); EXPECT_TRUE(menu->GetItemAt(menu->GetActiveProfileIndex()).signin_required); - window_close_observer()->Wait(); + if (!BrowserList::GetInstance()->empty()) + ui_test_utils::WaitForBrowserToClose(browser()); EXPECT_TRUE(BrowserList::GetInstance()->empty()); // Wait until the user manager is shown. @@ -365,7 +351,10 @@ ASSERT_NO_FATAL_FAILURE(OpenProfileChooserView(browser())); ClickProfileChooserViewLockButton(); - window_close_observer()->Wait(); + + if (!BrowserList::GetInstance()->empty()) + ui_test_utils::WaitForBrowserToClose(browser()); + EXPECT_TRUE(BrowserList::GetInstance()->empty()); // Wait until the user manager is shown. runner->Run(); @@ -400,7 +389,9 @@ ASSERT_NO_FATAL_FAILURE(OpenProfileChooserView(browser_to_lock)); ClickProfileChooserViewLockButton(); - window_close_observer()->Wait(); + + if (1U != BrowserList::GetInstance()->size()) + ui_test_utils::WaitForBrowserToClose(browser_to_lock); EXPECT_EQ(1U, BrowserList::GetInstance()->size()); // Wait until the user manager is shown.
diff --git a/chrome/browser/ui/views/profiles/user_manager_view.h b/chrome/browser/ui/views/profiles/user_manager_view.h index 2756550..e96b370 100644 --- a/chrome/browser/ui/views/profiles/user_manager_view.h +++ b/chrome/browser/ui/views/profiles/user_manager_view.h
@@ -13,7 +13,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/ui/user_manager.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/window/dialog_delegate.h"
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 09e85819..90608e1 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
@@ -16,11 +16,11 @@ #include "base/process/process.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/ui/views/status_icons/dbus_menu.h" -#include "chrome/browser/ui/views/status_icons/dbus_properties_interface.h" -#include "chrome/browser/ui/views/status_icons/dbus_types.h" -#include "chrome/browser/ui/views/status_icons/success_barrier_callback.h" -#include "components/dbus/dbus_thread_linux.h" +#include "components/dbus/menu/menu.h" +#include "components/dbus/menu/properties_interface.h" +#include "components/dbus/menu/success_barrier_callback.h" +#include "components/dbus/menu/types.h" +#include "components/dbus/thread_linux/dbus_thread_linux.h" #include "dbus/bus.h" #include "dbus/exported_object.h" #include "dbus/message.h"
diff --git a/chrome/browser/ui/views/sync/bubble_sync_promo_view.cc b/chrome/browser/ui/views/sync/bubble_sync_promo_view.cc index eb9ea74..0f380b6 100644 --- a/chrome/browser/ui/views/sync/bubble_sync_promo_view.cc +++ b/chrome/browser/ui/views/sync/bubble_sync_promo_view.cc
@@ -9,7 +9,7 @@ #include "base/strings/string16.h" #include "chrome/browser/ui/sync/bubble_sync_promo_delegate.h" #include "chrome/browser/ui/views/chrome_typography.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/font.h"
diff --git a/chrome/browser/ui/views/sync/bubble_sync_promo_view.h b/chrome/browser/ui/views/sync/bubble_sync_promo_view.h index e879b24..560aa97 100644 --- a/chrome/browser/ui/views/sync/bubble_sync_promo_view.h +++ b/chrome/browser/ui/views/sync/bubble_sync_promo_view.h
@@ -7,7 +7,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "ui/views/controls/styled_label.h" #include "ui/views/controls/styled_label_listener.h"
diff --git a/chrome/browser/ui/views/sync/bubble_sync_promo_view_unittest.cc b/chrome/browser/ui/views/sync/bubble_sync_promo_view_unittest.cc index d1a4850d..b8d870c 100644 --- a/chrome/browser/ui/views/sync/bubble_sync_promo_view_unittest.cc +++ b/chrome/browser/ui/views/sync/bubble_sync_promo_view_unittest.cc
@@ -13,7 +13,7 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/views/chrome_views_test_base.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/events/event_constants.h" #include "ui/gfx/range/range.h"
diff --git a/chrome/browser/ui/views/sync/bubble_sync_promo_view_util.h b/chrome/browser/ui/views/sync/bubble_sync_promo_view_util.h index c72446d..28ec9a1e 100644 --- a/chrome/browser/ui/views/sync/bubble_sync_promo_view_util.h +++ b/chrome/browser/ui/views/sync/bubble_sync_promo_view_util.h
@@ -8,7 +8,7 @@ #include <memory> #include "build/build_config.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "ui/views/style/typography.h" namespace views {
diff --git a/chrome/browser/ui/views/sync/dice_bubble_sync_promo_view.h b/chrome/browser/ui/views/sync/dice_bubble_sync_promo_view.h index c4c13f8..f79f819 100644 --- a/chrome/browser/ui/views/sync/dice_bubble_sync_promo_view.h +++ b/chrome/browser/ui/views/sync/dice_bubble_sync_promo_view.h
@@ -11,7 +11,7 @@ #include "base/macros.h" #include "chrome/browser/ui/sync/bubble_sync_promo_delegate.h" #include "chrome/browser/ui/views/profiles/dice_accounts_menu.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "ui/views/controls/button/button.h" #include "ui/views/style/typography.h" #include "ui/views/view.h"
diff --git a/chrome/browser/ui/views/sync/dice_signin_button_view.h b/chrome/browser/ui/views/sync/dice_signin_button_view.h index c18cd5d..54660364 100644 --- a/chrome/browser/ui/views/sync/dice_signin_button_view.h +++ b/chrome/browser/ui/views/sync/dice_signin_button_view.h
@@ -8,7 +8,7 @@ #include "base/macros.h" #include "base/optional.h" #include "chrome/browser/ui/views/hover_button.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/view.h"
diff --git a/chrome/browser/ui/views/sync/inline_login_ui_browsertest.cc b/chrome/browser/ui/views/sync/inline_login_ui_browsertest.cc index 46ad66e..a35fb403 100644 --- a/chrome/browser/ui/views/sync/inline_login_ui_browsertest.cc +++ b/chrome/browser/ui/views/sync/inline_login_ui_browsertest.cc
@@ -43,8 +43,8 @@ #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" @@ -552,7 +552,7 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, SigninCreatesSyncStarter1) { InlineLoginHandlerImpl handler; - // See Source enum in components/signin/core/browser/signin_metrics.h for + // See Source enum in components/signin/public/base/signin_metrics.h for // possible values of access_point=, reason=. GURL url("chrome://chrome-signin/?access_point=0&reason=5"); // MockSyncStarterInlineSigninHelper will delete itself when done using @@ -588,7 +588,7 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, SigninCreatesSyncStarter2) { InlineLoginHandlerImpl handler; - // See Source enum in components/signin/core/browser/signin_metrics.h for + // See Source enum in components/signin/public/base/signin_metrics.h for // possible values of access_point=, reason=. const GURL url("chrome://chrome-signin/?access_point=0&reason=5"); // MockSyncStarterInlineSigninHelper will delete itself when done using @@ -611,7 +611,7 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, UntrustedSigninDialogCancel) { InlineLoginHandlerImpl handler; - // See Source enum in components/signin/core/browser/signin_metrics.h for + // See Source enum in components/signin/public/base/signin_metrics.h for // possible values of access_point=, reason=. GURL url("chrome://chrome-signin/?access_point=0&reason=5"); // MockSyncStarterInlineSigninHelper will delete itself when done using @@ -636,7 +636,7 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, UntrustedSigninDialogConfirm) { InlineLoginHandlerImpl handler; - // See Source enum in components/signin/core/browser/signin_metrics.h for + // See Source enum in components/signin/public/base/signin_metrics.h for // possible values of access_point=, reason=. GURL url("chrome://chrome-signin/?access_point=0&reason=5"); // MockSyncStarterInlineSigninHelper will delete itself when done using @@ -664,7 +664,7 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, SigninCreatesSyncStarter4) { InlineLoginHandlerImpl handler; - // See Source enum in components/signin/core/browser/signin_metrics.h for + // See Source enum in components/signin/public/base/signin_metrics.h for // possible values of access_point=, reason=. const GURL url("chrome://chrome-signin/?access_point=3&reason=5"); // MockSyncStarterInlineSigninHelper will delete itself when done using @@ -691,7 +691,7 @@ ASSERT_EQ(0ul, identity_manager()->GetAccountsWithRefreshTokens().size()); InlineLoginHandlerImpl handler; - // See Source enum in components/signin/core/browser/signin_metrics.h for + // See Source enum in components/signin/public/base/signin_metrics.h for // possible values of access_point=, reason=. GURL url("chrome://chrome-signin/?access_point=3&reason=3"); // InlineSigninHelper will delete itself when done using
diff --git a/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.cc b/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.cc index 246e943..3101b38 100644 --- a/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.cc +++ b/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.cc
@@ -21,7 +21,7 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/constrained_window/constrained_window_views.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/strings/grit/components_strings.h" #include "components/vector_icons/vector_icons.h" #include "content/public/browser/web_contents.h"
diff --git a/chrome/browser/ui/views/toolbar/toolbar_action_view_interactive_uitest.cc b/chrome/browser/ui/views/toolbar/toolbar_action_view_interactive_uitest.cc index 569a50e..fb818109 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_action_view_interactive_uitest.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_action_view_interactive_uitest.cc
@@ -24,6 +24,7 @@ #include "chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "chrome/test/base/interactive_test_utils.h" +#include "content/public/test/test_utils.h" #include "extensions/browser/notification_types.h" #include "extensions/common/extension_builder.h" #include "extensions/common/feature_switch.h"
diff --git a/chrome/browser/ui/views/toolbar/toolbar_view_interactive_uitest.cc b/chrome/browser/ui/views/toolbar/toolbar_view_interactive_uitest.cc index c7ea62a..d5ea5e8 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_view_interactive_uitest.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_view_interactive_uitest.cc
@@ -30,6 +30,7 @@ #include "chrome/browser/ui/views/toolbar/toolbar_button.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_utils.h" #include "ui/views/focus/focus_manager.h"
diff --git a/chrome/browser/ui/webui/app_launcher_login_handler.cc b/chrome/browser/ui/webui/app_launcher_login_handler.cc index ae32c50..4b44c8cf 100644 --- a/chrome/browser/ui/webui/app_launcher_login_handler.cc +++ b/chrome/browser/ui/webui/app_launcher_login_handler.cc
@@ -29,8 +29,8 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h"
diff --git a/chrome/browser/ui/webui/app_management/app_management.mojom b/chrome/browser/ui/webui/app_management/app_management.mojom index c2e7c54..8bdeeb8 100644 --- a/chrome/browser/ui/webui/app_management/app_management.mojom +++ b/chrome/browser/ui/webui/app_management/app_management.mojom
@@ -23,6 +23,7 @@ map<uint32, apps.mojom.Permission> permissions; apps.mojom.InstallSource install_source; bool hide_more_settings; + bool hide_pin_to_shelf; }; // Extension-based apps primarily use install-time permissions that cannot be
diff --git a/chrome/browser/ui/webui/app_management/app_management_page_handler.cc b/chrome/browser/ui/webui/app_management/app_management_page_handler.cc index f9c7788..802afb20 100644 --- a/chrome/browser/ui/webui/app_management/app_management_page_handler.cc +++ b/chrome/browser/ui/webui/app_management/app_management_page_handler.cc
@@ -31,6 +31,10 @@ extensions::kWebStoreAppId, }; +constexpr char const* kAppIdsWithHiddenPinToShelf[] = { + extension_misc::kChromeAppId, +}; + app_management::mojom::ExtensionAppPermissionMessagePtr CreateExtensionAppPermissionMessage( const extensions::PermissionMessage& message) { @@ -46,6 +50,11 @@ return base::Contains(kAppIdsWithHiddenMoreSettings, app_id); } +bool ShouldHidePinToShelf(const std::string app_id) { + return base::Contains(kAppIdsWithHiddenPinToShelf, app_id); +} + + } // namespace AppManagementPageHandler::AppManagementPageHandler( @@ -214,6 +223,7 @@ #endif app->hide_more_settings = ShouldHideMoreSettings(app->id); + app->hide_pin_to_shelf = ShouldHidePinToShelf(app->id); return app; }
diff --git a/chrome/browser/ui/webui/app_management/app_management_ui.cc b/chrome/browser/ui/webui/app_management/app_management_ui.cc index 58a21d4..2ebb0d2 100644 --- a/chrome/browser/ui/webui/app_management/app_management_ui.cc +++ b/chrome/browser/ui/webui/app_management/app_management_ui.cc
@@ -21,6 +21,7 @@ #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" +#include "extensions/common/constants.h" #include "ui/base/resource/resource_bundle.h" namespace { @@ -60,6 +61,19 @@ }; AddLocalizedStringsBulk(source, kStrings, base::size(kStrings)); + source->AddString("chromeAppId", extension_misc::kChromeAppId); + + source->AddResourcePath("app_management.mojom-lite.js", + IDR_APP_MANAGEMENT_MOJO_LITE_JS); + source->AddResourcePath("types.mojom-lite.js", + IDR_APP_MANAGEMENT_TYPES_MOJO_LITE_JS); + source->AddResourcePath("bitmap.mojom-lite.js", + IDR_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS); + source->AddResourcePath("image.mojom-lite.js", + IDR_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS); + source->AddResourcePath("image_info.mojom-lite.js", + IDR_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS); + source->AddResourcePath("actions.html", IDR_APP_MANAGEMENT_ACTIONS_HTML); source->AddResourcePath("actions.js", IDR_APP_MANAGEMENT_ACTIONS_JS); source->AddResourcePath("api_listener.html", @@ -68,16 +82,12 @@ IDR_APP_MANAGEMENT_API_LISTENER_JS); source->AddResourcePath("app_item.html", IDR_APP_MANAGEMENT_APP_ITEM_HTML); source->AddResourcePath("app_item.js", IDR_APP_MANAGEMENT_APP_ITEM_JS); - source->AddResourcePath("app_management.mojom-lite.js", - IDR_APP_MANAGEMENT_MOJO_LITE_JS); source->AddResourcePath("app.html", IDR_APP_MANAGEMENT_APP_HTML); source->AddResourcePath("app.js", IDR_APP_MANAGEMENT_APP_JS); source->AddResourcePath("arc_permission_view.html", IDR_APP_MANAGEMENT_ARC_PERMISSION_VIEW_HTML); source->AddResourcePath("arc_permission_view.js", IDR_APP_MANAGEMENT_ARC_PERMISSION_VIEW_JS); - source->AddResourcePath("bitmap.mojom-lite.js", - IDR_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS); source->AddResourcePath("browser_proxy.html", IDR_APP_MANAGEMENT_BROWSER_PROXY_HTML); source->AddResourcePath("browser_proxy.js", @@ -98,10 +108,6 @@ source->AddResourcePath("fake_page_handler.js", IDR_APP_MANAGEMENT_FAKE_PAGE_HANDLER_JS); source->AddResourcePath("icons.html", IDR_APP_MANAGEMENT_ICONS_HTML); - source->AddResourcePath("image_info.mojom-lite.js", - IDR_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS); - source->AddResourcePath("image.mojom-lite.js", - IDR_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS); source->AddResourcePath("main_view.html", IDR_APP_MANAGEMENT_MAIN_VIEW_HTML); source->AddResourcePath("main_view.js", IDR_APP_MANAGEMENT_MAIN_VIEW_JS); source->AddResourcePath("metadata_view.html", @@ -124,6 +130,10 @@ IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_HTML); source->AddResourcePath("permission_view_header.js", IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_JS); + source->AddResourcePath("pin_to_shelf_item.html", + IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_HTML); + source->AddResourcePath("pin_to_shelf_item.js", + IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_JS); source->AddResourcePath("pwa_permission_view.html", IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_HTML); source->AddResourcePath("pwa_permission_view.js", @@ -145,9 +155,10 @@ IDR_APP_MANAGEMENT_STORE_CLIENT_JS); source->AddResourcePath("store.html", IDR_APP_MANAGEMENT_STORE_HTML); source->AddResourcePath("store.js", IDR_APP_MANAGEMENT_STORE_JS); + source->AddResourcePath("toggle_row.html", + IDR_APP_MANAGEMENT_TOGGLE_ROW_HTML); + source->AddResourcePath("toggle_row.js", IDR_APP_MANAGEMENT_TOGGLE_ROW_JS); source->AddResourcePath("types.js", IDR_APP_MANAGEMENT_TYPES_JS); - source->AddResourcePath("types.mojom-lite.js", - IDR_APP_MANAGEMENT_TYPES_MOJO_LITE_JS); source->AddResourcePath("util.html", IDR_APP_MANAGEMENT_UTIL_HTML); source->AddResourcePath("util.js", IDR_APP_MANAGEMENT_UTIL_JS);
diff --git a/chrome/browser/ui/webui/certificates_handler.cc b/chrome/browser/ui/webui/certificates_handler.cc index 799279d..a2a09b2 100644 --- a/chrome/browser/ui/webui/certificates_handler.cc +++ b/chrome/browser/ui/webui/certificates_handler.cc
@@ -80,7 +80,7 @@ #if defined(OS_CHROMEOS) // Enumeration of certificate management permissions which corresponds to -// values of policy CertificateManagementAllowed. +// values of policy ClientCertificateManagementAllowed. enum class CertificateManagementPermission : int { // Allow users to manage all certificates kAll = 0, @@ -577,7 +577,7 @@ CHECK(args->GetBoolean(1, &use_hardware_backed_)); #if defined(OS_CHROMEOS) - CHECK(IsCertificateManagementAllowedPolicy(Slot::kUser)) + CHECK(IsClientCertificateManagementAllowedPolicy(Slot::kUser)) << "Importing certificates not allowed by policy"; #endif @@ -742,7 +742,7 @@ AssignWebUICallbackId(args); #if defined(OS_CHROMEOS) - CHECK(IsCertificateManagementAllowedPolicy(Slot::kUser)) + CHECK(IsClientCertificateManagementAllowedPolicy(Slot::kUser)) << "Importing certificates not allowed by policy"; #endif @@ -813,11 +813,6 @@ CHECK_EQ(1U, args->GetSize()); AssignWebUICallbackId(args); -#if defined(OS_CHROMEOS) - CHECK(IsCertificateManagementAllowedPolicy(Slot::kUser)) - << "Importing certificates not allowed by policy"; -#endif - select_file_dialog_ = ui::SelectFileDialog::Create( this, std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents())); @@ -950,12 +945,14 @@ } void CertificatesHandler::CertificateManagerModelReady() { - bool import_allowed = true; + bool client_import_allowed = true; #if defined(OS_CHROMEOS) - import_allowed = IsCertificateManagementAllowedPolicy(Slot::kUser); + client_import_allowed = + IsClientCertificateManagementAllowedPolicy(Slot::kUser); #endif if (IsJavascriptAllowed()) { - FireWebUIListener("certificates-model-ready", base::Value(import_allowed)); + FireWebUIListener("certificates-model-ready", + base::Value(client_import_allowed)); } certificate_manager_model_->Refresh(); } @@ -1136,12 +1133,12 @@ } #if defined(OS_CHROMEOS) -bool CertificatesHandler::IsCertificateManagementAllowedPolicy( +bool CertificatesHandler::IsClientCertificateManagementAllowedPolicy( Slot slot) const { Profile* profile = Profile::FromWebUI(web_ui()); PrefService* prefs = profile->GetPrefs(); auto policy_value = static_cast<CertificateManagementPermission>( - prefs->GetInteger(prefs::kCertificateManagementAllowed)); + prefs->GetInteger(prefs::kClientCertificateManagementAllowed)); if (slot == Slot::kUser) { return policy_value != CertificateManagementPermission::kNone; @@ -1157,8 +1154,9 @@ } #if defined(OS_CHROMEOS) - return !IsCertificateManagementAllowedPolicy( - cert_info->device_wide() ? Slot::kSystem : Slot::kUser); + return cert_info->type() == net::CertType::USER_CERT && + !IsClientCertificateManagementAllowedPolicy( + cert_info->device_wide() ? Slot::kSystem : Slot::kUser); #else return false; #endif @@ -1170,7 +1168,7 @@ // Allow users to manage all certificates by default. This can be overridden // by enterprise policy. registry->RegisterIntegerPref( - prefs::kCertificateManagementAllowed, + prefs::kClientCertificateManagementAllowed, static_cast<int>(CertificateManagementPermission::kAll)); } #endif // defined(OS_CHROMEOS)
diff --git a/chrome/browser/ui/webui/certificates_handler.h b/chrome/browser/ui/webui/certificates_handler.h index 50df107..1ae3da8a 100644 --- a/chrome/browser/ui/webui/certificates_handler.h +++ b/chrome/browser/ui/webui/certificates_handler.h
@@ -178,13 +178,14 @@ #if defined(OS_CHROMEOS) // Returns true if the user may manage certificates on |slot| according - // CertificateManagementAllowed to policy. - bool IsCertificateManagementAllowedPolicy(Slot slot) const; + // ClientCertificateManagementAllowed to policy. + bool IsClientCertificateManagementAllowedPolicy(Slot slot) const; #endif // Returns true if the certificate represented by |cert_info| is read-only // (i.e. can not be deleted). Evaluates the certificate attributes and, on - // Chrome OS devices, the enterprise policy CertificateManagementAllowed. + // Chrome OS devices, the enterprise policy + // ClientCertificateManagementAllowed. bool IsCertificateReadOnly( const CertificateManagerModel::CertInfo* cert_info);
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index f652fa1..6ab11f4 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -85,7 +85,7 @@ #include "components/safe_browsing/web_ui/safe_browsing_ui.h" #include "components/security_interstitials/content/connection_help_ui.h" #include "components/security_interstitials/content/urls.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/content_client.h"
diff --git a/chrome/browser/ui/webui/history_login_handler.cc b/chrome/browser/ui/webui/history_login_handler.cc index 5fe265f..f8db85e 100644 --- a/chrome/browser/ui/webui/history_login_handler.cc +++ b/chrome/browser/ui/webui/history_login_handler.cc
@@ -13,7 +13,7 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/webui/profile_info_watcher.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h"
diff --git a/chrome/browser/ui/webui/management_ui.cc b/chrome/browser/ui/webui/management_ui.cc index d4151d1..fd0d3cb 100644 --- a/chrome/browser/ui/webui/management_ui.cc +++ b/chrome/browser/ui/webui/management_ui.cc
@@ -58,6 +58,7 @@ IDS_MANAGEMENT_REPORT_DEVICE_NETWORK_INTERFACES}, {kManagementReportUsers, IDS_MANAGEMENT_REPORT_DEVICE_USERS}, {kManagementPrinting, IDS_MANAGEMENT_REPORT_PRINTING}, + {kManagementCrostini, IDS_MANAGEMENT_CROSTINI}, #endif // defined(OS_CHROMEOS) {"browserReporting", IDS_MANAGEMENT_BROWSER_REPORTING}, {"browserReportingExplanation",
diff --git a/chrome/browser/ui/webui/management_ui_handler.cc b/chrome/browser/ui/webui/management_ui_handler.cc index f495672..1d379f6 100644 --- a/chrome/browser/ui/webui/management_ui_handler.cc +++ b/chrome/browser/ui/webui/management_ui_handler.cc
@@ -36,6 +36,7 @@ #include "ui/base/webui/web_ui_util.h" #if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/crostini/crostini_pref_names.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/policy/policy_cert_service.h" @@ -117,6 +118,7 @@ "managementReportNetworkInterfaces"; const char kManagementReportUsers[] = "managementReportUsers"; const char kManagementPrinting[] = "managementPrinting"; +const char kManagementCrostini[] = "managementCrostini"; const char kAccountManagedInfo[] = "accountManagedInfo"; const char kDeviceManagedInfo[] = "deviceManagedInfo"; const char kOverview[] = "overview"; @@ -153,7 +155,8 @@ kDeviceStatistics, kDevice, kLogs, - kPrint + kPrint, + kCrostini }; // Corresponds to DeviceReportingType in management_browser_proxy.js @@ -171,6 +174,8 @@ return "logs"; case DeviceReportingType::kPrint: return "print"; + case DeviceReportingType::kCrostini: + return "crostini"; default: NOTREACHED() << "Unknown device reporting type"; return "device"; @@ -232,6 +237,12 @@ AddDeviceReportingElement(report_sources, kManagementPrinting, DeviceReportingType::kPrint); } + + if (profile->GetPrefs()->GetBoolean( + crostini::prefs::kReportCrostiniUsageEnabled)) { + AddDeviceReportingElement(report_sources, kManagementCrostini, + DeviceReportingType::kCrostini); + } } #endif // defined(OS_CHROMEOS)
diff --git a/chrome/browser/ui/webui/management_ui_handler.h b/chrome/browser/ui/webui/management_ui_handler.h index dc1f39f..1d40707 100644 --- a/chrome/browser/ui/webui/management_ui_handler.h +++ b/chrome/browser/ui/webui/management_ui_handler.h
@@ -32,6 +32,7 @@ extern const char kManagementReportNetworkInterfaces[]; extern const char kManagementReportUsers[]; extern const char kManagementPrinting[]; +extern const char kManagementCrostini[]; #endif // defined(OS_CHROMEOS) extern const char kCloudReportingExtensionId[];
diff --git a/chrome/browser/ui/webui/net_export_ui.cc b/chrome/browser/ui/webui/net_export_ui.cc index 35f21ae..88704cb 100644 --- a/chrome/browser/ui/webui/net_export_ui.cc +++ b/chrome/browser/ui/webui/net_export_ui.cc
@@ -216,7 +216,7 @@ const base::Value::ListStorage& params = list->GetList(); // Determine the capture mode. - capture_mode_ = net::NetLogCaptureMode::Default(); + capture_mode_ = net::NetLogCaptureMode::kDefault; if (!params.empty() && params[0].is_string()) { capture_mode_ = net_log::NetExportFileWriter::CaptureModeFromString( params[0].GetString());
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler.cc b/chrome/browser/ui/webui/print_preview/print_preview_handler.cc index 41c93a7..77fbf24 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler.cc
@@ -62,7 +62,7 @@ #include "components/printing/browser/printer_capabilities.h" #include "components/printing/common/cloud_print_cdd_conversion.h" #include "components/printing/common/print_messages.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h" #include "components/url_formatter/url_formatter.h"
diff --git a/chrome/browser/ui/webui/profile_helper_browsertest.cc b/chrome/browser/ui/webui/profile_helper_browsertest.cc index b5c8ba75..5e9302e5 100644 --- a/chrome/browser/ui/webui/profile_helper_browsertest.cc +++ b/chrome/browser/ui/webui/profile_helper_browsertest.cc
@@ -6,7 +6,6 @@ #include "base/run_loop.h" #include "base/scoped_observer.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" @@ -14,8 +13,8 @@ #include "chrome/browser/ui/browser_list_observer.h" #include "chrome/browser/ui/webui/profile_helper.h" #include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browsing_data_remover.h" -#include "content/public/browser/notification_service.h" #include "content/public/test/browsing_data_remover_test_util.h" #include "content/public/test/test_utils.h" #include "content/public/test/test_web_ui.h" @@ -124,15 +123,9 @@ EXPECT_EQ(1u, storage.GetNumberOfProfiles()); // Original browser will be closed, and browser with the new profile created. - content::WindowedNotificationObserver open_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); - content::WindowedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(browser())); webui::DeleteProfileAtPath(original_browser->profile()->GetPath(), ProfileMetrics::DELETE_PROFILE_SETTINGS); - open_observer.Wait(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(original_browser); EXPECT_EQ(1u, browser_list->size()); EXPECT_FALSE(base::Contains(*browser_list, original_browser)); @@ -154,15 +147,9 @@ EXPECT_EQ(2u, storage.GetNumberOfProfiles()); // Original browser will be closed, and browser with the new profile created. - content::WindowedNotificationObserver open_observer( - chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); - content::WindowedNotificationObserver close_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(browser())); webui::DeleteProfileAtPath(original_browser->profile()->GetPath(), ProfileMetrics::DELETE_PROFILE_SETTINGS); - open_observer.Wait(); - close_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(original_browser); EXPECT_EQ(1u, browser_list->size()); EXPECT_EQ(additional_profile, browser_list->get(0)->profile());
diff --git a/chrome/browser/ui/webui/profile_info_watcher.cc b/chrome/browser/ui/webui/profile_info_watcher.cc index c04989c1..3fa52f1 100644 --- a/chrome/browser/ui/webui/profile_info_watcher.cc +++ b/chrome/browser/ui/webui/profile_info_watcher.cc
@@ -12,7 +12,7 @@ #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" ProfileInfoWatcher::ProfileInfoWatcher(
diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc index b867bd1..5e8a491 100644 --- a/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chrome/browser/ui/webui/settings/people_handler.cc
@@ -35,11 +35,11 @@ #include "chrome/grit/generated_resources.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/signin_error_controller.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/primary_account_mutator.h"
diff --git a/chrome/browser/ui/webui/settings/people_handler.h b/chrome/browser/ui/webui/settings/people_handler.h index 9fc6f779..a89e03e 100644 --- a/chrome/browser/ui/webui/settings/people_handler.h +++ b/chrome/browser/ui/webui/settings/people_handler.h
@@ -20,7 +20,7 @@ #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "components/prefs/pref_change_registrar.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/sync/driver/sync_service_observer.h" #include "content/public/browser/web_contents_observer.h"
diff --git a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 64abc6b..41ceadb 100644 --- a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -45,7 +45,7 @@ #include "components/password_manager/core/browser/manage_passwords_referrer.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" #include "components/strings/grit/components_strings.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h" #include "components/sync/driver/sync_service.h" @@ -534,6 +534,8 @@ IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_TITLE}, {"crostiniImportConfirmationDialogMessage", IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_MESSAGE}, + {"crostiniImportConfirmationDialogConfirmationButton", + IDS_SETTINGS_CROSTINI_IMPORT}, {"crostiniRemoveButton", IDS_SETTINGS_CROSTINI_REMOVE_BUTTON}, {"crostiniSharedUsbDevicesLabel", IDS_SETTINGS_CROSTINI_SHARED_USB_DEVICES_LABEL}, @@ -2497,18 +2499,16 @@ Profile* profile) { static constexpr LocalizedString kLocalizedStrings[] = { {"googleAssistantPageTitle", IDS_SETTINGS_GOOGLE_ASSISTANT}, - {"googleAssistantEnableContext", - IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_CONTEXT}, + {"googleAssistantEnableContext", IDS_ASSISTANT_SCREEN_CONTEXT_TITLE}, {"googleAssistantEnableContextDescription", - IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_CONTEXT_DESCRIPTION}, - {"googleAssistantEnableHotword", - IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD}, + IDS_ASSISTANT_SCREEN_CONTEXT_DESC}, + {"googleAssistantEnableHotword", IDS_ASSISTANT_HOTWORD_TITLE}, {"googleAssistantEnableHotwordDescription", IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD_DESCRIPTION}, {"googleAssistantVoiceSettings", IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS}, {"googleAssistantVoiceSettingsDescription", - IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS_DESCRIPTION}, + IDS_ASSISTANT_VOICE_MATCH_RECORDING}, {"googleAssistantVoiceSettingsRetrainButton", IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS_RETRAIN}, {"googleAssistantEnableHotwordWithoutDspDescription",
diff --git a/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc b/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc index fd96a72..6c74ff6 100644 --- a/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc +++ b/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc
@@ -30,7 +30,7 @@ #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_ui.h"
diff --git a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc index ff1b5a81..6df14f0 100644 --- a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc +++ b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc
@@ -31,10 +31,10 @@ #include "components/keyed_service/content/browser_context_keyed_service_shutdown_notifier_factory.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/primary_account_mutator.h"
diff --git a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h index 84007e3..7f73e734 100644 --- a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h +++ b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h
@@ -16,8 +16,8 @@ #include "chrome/browser/sync/sync_startup_tracker.h" #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "components/keyed_service/core/keyed_service_shutdown_notifier.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/identity_manager/account_info.h" class Browser;
diff --git a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc index 7bcf5ba..9c686bb4 100644 --- a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc +++ b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc
@@ -29,8 +29,8 @@ #include "chrome/test/base/testing_profile.h" #include "components/account_id/account_id.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/sync/driver/mock_sync_service.h"
diff --git a/chrome/browser/ui/webui/signin/inline_login_handler.cc b/chrome/browser/ui/webui/signin/inline_login_handler.cc index 48580497..d0aee56 100644 --- a/chrome/browser/ui/webui/signin/inline_login_handler.cc +++ b/chrome/browser/ui/webui/signin/inline_login_handler.cc
@@ -26,7 +26,7 @@ #include "chrome/common/pref_names.h" #include "components/metrics/metrics_pref_names.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h"
diff --git a/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc b/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc index 98c10c5..dd52c8a 100644 --- a/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc +++ b/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc
@@ -16,7 +16,7 @@ #include "chrome/browser/ui/webui/signin/inline_login_handler.h" #include "chromeos/components/account_manager/account_manager.h" #include "chromeos/components/account_manager/account_manager_factory.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "google_apis/gaia/gaia_urls.h" #include "services/network/public/cpp/shared_url_loader_factory.h"
diff --git a/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc b/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc index 24ec93f5..f4be871 100644 --- a/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc +++ b/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc
@@ -60,8 +60,8 @@ #include "components/signin/core/browser/about_signin_internals.h" #include "components/signin/core/browser/signin_header_helper.h" #include "components/signin/core/browser/signin_investigator.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_cookie_mutator.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h"
diff --git a/chrome/browser/ui/webui/signin/inline_login_ui.cc b/chrome/browser/ui/webui/signin/inline_login_ui.cc index f39a238..ce4cd88 100644 --- a/chrome/browser/ui/webui/signin/inline_login_ui.cc +++ b/chrome/browser/ui/webui/signin/inline_login_ui.cc
@@ -21,7 +21,7 @@ #include "chrome/grit/browser_resources.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/common/content_switches.h"
diff --git a/chrome/browser/ui/webui/signin/login_ui_service.cc b/chrome/browser/ui/webui/signin/login_ui_service.cc index bf458dc..c271654f 100644 --- a/chrome/browser/ui/webui/signin/login_ui_service.cc +++ b/chrome/browser/ui/webui/signin/login_ui_service.cc
@@ -16,8 +16,8 @@ #include "chrome/browser/ui/scoped_tabbed_browser_displayer.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/url_constants.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/signin_header_helper.h" +#include "components/signin/public/base/account_consistency_method.h" #if !defined(OS_CHROMEOS) #include "chrome/browser/ui/user_manager.h"
diff --git a/chrome/browser/ui/webui/signin/login_ui_test_utils.h b/chrome/browser/ui/webui/signin/login_ui_test_utils.h index 439d50c..8478e11 100644 --- a/chrome/browser/ui/webui/signin/login_ui_test_utils.h +++ b/chrome/browser/ui/webui/signin/login_ui_test_utils.h
@@ -9,7 +9,7 @@ #include <vector> #include "base/time/time.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" class Browser;
diff --git a/chrome/browser/ui/webui/signin/signin_error_ui.cc b/chrome/browser/ui/webui/signin/signin_error_ui.cc index 1eb9149..b7fc877 100644 --- a/chrome/browser/ui/webui/signin/signin_error_ui.cc +++ b/chrome/browser/ui/webui/signin/signin_error_ui.cc
@@ -22,7 +22,7 @@ #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h"
diff --git a/chrome/browser/ui/webui/signin/signin_utils_desktop.cc b/chrome/browser/ui/webui/signin/signin_utils_desktop.cc index 08d4a7e..56abf43 100644 --- a/chrome/browser/ui/webui/signin/signin_utils_desktop.cc +++ b/chrome/browser/ui/webui/signin/signin_utils_desktop.cc
@@ -18,9 +18,9 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/guest_view/browser/guest_view_manager.h" -#include "components/signin/core/browser/identity_utils.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" +#include "components/signin/public/identity_manager/identity_utils.h" #include "google_apis/gaia/gaia_auth_util.h" #include "ui/base/l10n/l10n_util.h"
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc b/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc index 540133c..5985972 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc +++ b/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc
@@ -22,8 +22,8 @@ #include "chrome/browser/ui/webui/signin/sync_confirmation_ui.h" #include "chrome/common/webui_url_constants.h" #include "components/consent_auditor/consent_auditor.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/avatar_icon_util.h" +#include "components/signin/public/base/avatar_icon_util.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/unified_consent/feature.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h"
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc b/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc index de704d7..b039d906 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc +++ b/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc
@@ -29,7 +29,7 @@ #include "chrome/test/base/dialog_test_browser_window.h" #include "chrome/test/base/testing_profile.h" #include "components/consent_auditor/fake_consent_auditor.h" -#include "components/signin/core/browser/avatar_icon_util.h" +#include "components/signin/public/base/avatar_icon_util.h" #include "components/unified_consent/scoped_unified_consent.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h"
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc b/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc index 83bb5207..d5457932 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc +++ b/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc
@@ -16,7 +16,7 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" -#include "components/signin/core/browser/avatar_icon_util.h" +#include "components/signin/public/base/avatar_icon_util.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/strings/grit/components_strings.h" #include "components/unified_consent/feature.h"
diff --git a/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc b/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc index 91ffa695..e7c1cf9e 100644 --- a/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc +++ b/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc
@@ -51,7 +51,7 @@ #include "chrome/grit/generated_resources.h" #include "components/account_id/account_id.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/storage_partition.h"
diff --git a/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc b/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc index decbaaf0..1d1135c 100644 --- a/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc +++ b/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc
@@ -24,7 +24,7 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/ui_test_utils.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/chrome/browser/ui/webui/welcome/welcome_handler.cc b/chrome/browser/ui/webui/welcome/welcome_handler.cc index 58b367e..222a102 100644 --- a/chrome/browser/ui/webui/welcome/welcome_handler.cc +++ b/chrome/browser/ui/webui/welcome/welcome_handler.cc
@@ -15,7 +15,7 @@ #include "chrome/browser/ui/profile_chooser_constants.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/url_constants.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "ui/base/page_transition_types.h"
diff --git a/chrome/browser/ui/webui/welcome/welcome_ui.cc b/chrome/browser/ui/webui/welcome/welcome_ui.cc index 5002a57..43eb3a9 100644 --- a/chrome/browser/ui/webui/welcome/welcome_ui.cc +++ b/chrome/browser/ui/webui/welcome/welcome_ui.cc
@@ -25,7 +25,7 @@ #include "chrome/grit/onboarding_welcome_resources.h" #include "chrome/grit/onboarding_welcome_resources_map.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_contents.h" #include "net/base/url_util.h"
diff --git a/chrome/browser/ui/zoom/zoom_controller_browsertest.cc b/chrome/browser/ui/zoom/zoom_controller_browsertest.cc index eac9522..6db4559cb1 100644 --- a/chrome/browser/ui/zoom/zoom_controller_browsertest.cc +++ b/chrome/browser/ui/zoom/zoom_controller_browsertest.cc
@@ -17,7 +17,7 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/zoom/test/zoom_test_utils.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_entry.h"
diff --git a/chrome/browser/unload_browsertest.cc b/chrome/browser/unload_browsertest.cc index 9f6a4a1..d6c9830 100644 --- a/chrome/browser/unload_browsertest.cc +++ b/chrome/browser/unload_browsertest.cc
@@ -208,6 +208,27 @@ browser->tab_strip_model()->GetWebContentsAt(i)); } } + + void CloseBrowsersVerifyUnloadSuccess(bool force) { + UnloadResults unload_results; + BrowserList::CloseAllBrowsersWithProfile( + browser()->profile(), + base::Bind(&UnloadResults::AddSuccess, + base::Unretained(&unload_results)), + base::Bind(&UnloadResults::AddAbort, base::Unretained(&unload_results)), + force); + ui_test_utils::WaitForBrowserToClose(); + EXPECT_EQ(1, unload_results.get_successes()); + EXPECT_EQ(0, unload_results.get_aborts()); + } + + // The test harness cannot close the window automatically, because it requires + // confirmation. We close the window manually instead. + void ManuallyCloseWindow() { + chrome::CloseWindow(browser()); + ClickModalDialogButton(true); + ui_test_utils::WaitForBrowserToClose(); + } }; // Navigate to a page with an infinite unload handler. @@ -288,12 +309,9 @@ NavigateToDataURL(BEFORE_UNLOAD_HTML, "beforeunload"); PrepareForDialog(browser()); - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); chrome::CloseWindow(browser()); ClickModalDialogButton(true); - window_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); } // Tests closing the browser with a beforeunload handler and clicking @@ -314,14 +332,7 @@ ClickModalDialogButton(false); ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); - // The test harness cannot close the window automatically, because it requires - // confirmation. We close the window manually instead. - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); - chrome::CloseWindow(browser()); - ClickModalDialogButton(true); - window_observer.Wait(); + ManuallyCloseWindow(); } // Tests closing the browser by BrowserList::CloseAllBrowsersWithProfile, @@ -329,18 +340,7 @@ IN_PROC_BROWSER_TEST_F(UnloadTest, BrowserListCloseNoUnloadListeners) { NavigateToDataURL(NOLISTENERS_HTML, "nolisteners"); - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); - UnloadResults unload_results; - BrowserList::CloseAllBrowsersWithProfile( - browser()->profile(), - base::Bind(&UnloadResults::AddSuccess, base::Unretained(&unload_results)), - base::Bind(&UnloadResults::AddAbort, base::Unretained(&unload_results)), - false); - window_observer.Wait(); - EXPECT_EQ(1, unload_results.get_successes()); - EXPECT_EQ(0, unload_results.get_aborts()); + CloseBrowsersVerifyUnloadSuccess(false); } // Tests closing the browser by BrowserList::CloseAllBrowsersWithProfile, with a @@ -349,9 +349,6 @@ NavigateToDataURL(BEFORE_UNLOAD_HTML, "beforeunload"); PrepareForDialog(browser()); - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); UnloadResults unload_results; BrowserList::CloseAllBrowsersWithProfile( browser()->profile(), @@ -359,11 +356,23 @@ base::Bind(&UnloadResults::AddAbort, base::Unretained(&unload_results)), false); ClickModalDialogButton(true); - window_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_EQ(1, unload_results.get_successes()); EXPECT_EQ(0, unload_results.get_aborts()); } +IN_PROC_BROWSER_TEST_F(UnloadTest, BrowserListForceCloseNoUnloadListeners) { + NavigateToDataURL(NOLISTENERS_HTML, "nolisteners"); + + CloseBrowsersVerifyUnloadSuccess(true); +} + +IN_PROC_BROWSER_TEST_F(UnloadTest, BrowserListForceCloseWithBeforeUnload) { + NavigateToDataURL(BEFORE_UNLOAD_HTML, "beforeunload"); + + CloseBrowsersVerifyUnloadSuccess(true); +} + // Tests closing the browser by BrowserList::CloseAllBrowsersWithProfile, with a // beforeunload handler and clicking Stay in the beforeunload confirm dialog. IN_PROC_BROWSER_TEST_F(UnloadTest, BrowserListCloseBeforeUnloadCancel) { @@ -390,14 +399,7 @@ EXPECT_EQ(0, unload_results.get_successes()); EXPECT_EQ(1, unload_results.get_aborts()); - // The test harness cannot close the window automatically, because it requires - // confirmation. We close the window manually instead. - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); - chrome::CloseWindow(browser()); - ClickModalDialogButton(true); - window_observer.Wait(); + ManuallyCloseWindow(); } // Tests double calls to BrowserList::CloseAllBrowsersWithProfile, with a @@ -406,9 +408,6 @@ NavigateToDataURL(BEFORE_UNLOAD_HTML, "beforeunload"); PrepareForDialog(browser()); - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); UnloadResults unload_results; BrowserList::CloseAllBrowsersWithProfile( browser()->profile(), @@ -421,7 +420,7 @@ base::Bind(&UnloadResults::AddAbort, base::Unretained(&unload_results)), false); ClickModalDialogButton(true); - window_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_EQ(1, unload_results.get_successes()); EXPECT_EQ(0, unload_results.get_aborts()); } @@ -457,14 +456,7 @@ EXPECT_EQ(0, unload_results.get_successes()); EXPECT_EQ(1, unload_results.get_aborts()); - // The test harness cannot close the window automatically, because it requires - // confirmation. We close the window manually instead. - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); - chrome::CloseWindow(browser()); - ClickModalDialogButton(true); - window_observer.Wait(); + ManuallyCloseWindow(); } // Tests closing the browser by BrowserList::CloseAllBrowsersWithProfile, with @@ -474,15 +466,12 @@ NavigateToDataURL(BEFORE_UNLOAD_HTML, "beforeunload"); PrepareForDialog(browser()); - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); UnloadResults unload_results; BrowserList::CloseAllBrowsersWithProfile(browser()->profile(), BrowserList::CloseCallback(), BrowserList::CloseCallback(), false); ClickModalDialogButton(true); - window_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); } // Tests closing the browser by BrowserList::CloseAllBrowsersWithProfile, with @@ -508,14 +497,7 @@ ClickModalDialogButton(false); ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); - // The test harness cannot close the window automatically, because it requires - // confirmation. We close the window manually instead. - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); - chrome::CloseWindow(browser()); - ClickModalDialogButton(true); - window_observer.Wait(); + ManuallyCloseWindow(); } // Tests terminating the browser with a beforeunload handler. @@ -534,12 +516,7 @@ NavigateToDataURL(INNER_FRAME_WITH_FOCUS_HTML, "innerframewithfocus"); PrepareForDialog(browser()); - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); - chrome::CloseWindow(browser()); - ClickModalDialogButton(true); - window_observer.Wait(); + ManuallyCloseWindow(); } // Tests closing the browser with a beforeunload handler that takes forever @@ -629,46 +606,9 @@ CheckTitle("only_one_unload"); } -IN_PROC_BROWSER_TEST_F(UnloadTest, BrowserListForceCloseNoUnloadListeners) { - NavigateToDataURL(NOLISTENERS_HTML, "nolisteners"); - - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); - UnloadResults unload_results; - BrowserList::CloseAllBrowsersWithProfile( - browser()->profile(), - base::Bind(&UnloadResults::AddSuccess, base::Unretained(&unload_results)), - base::Bind(&UnloadResults::AddAbort, base::Unretained(&unload_results)), - true); - window_observer.Wait(); - EXPECT_EQ(1, unload_results.get_successes()); - EXPECT_EQ(0, unload_results.get_aborts()); -} - -IN_PROC_BROWSER_TEST_F(UnloadTest, BrowserListForceCloseWithBeforeUnload) { - NavigateToDataURL(BEFORE_UNLOAD_HTML, "beforeunload"); - - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); - UnloadResults unload_results; - BrowserList::CloseAllBrowsersWithProfile( - browser()->profile(), - base::Bind(&UnloadResults::AddSuccess, base::Unretained(&unload_results)), - base::Bind(&UnloadResults::AddAbort, base::Unretained(&unload_results)), - true); - window_observer.Wait(); - EXPECT_EQ(1, unload_results.get_successes()); - EXPECT_EQ(0, unload_results.get_aborts()); -} - IN_PROC_BROWSER_TEST_F(UnloadTest, BrowserListForceCloseAfterNormalClose) { NavigateToDataURL(BEFORE_UNLOAD_HTML, "beforeunload"); - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); UnloadResults unload_results; BrowserList::CloseAllBrowsersWithProfile( browser()->profile(), @@ -680,7 +620,7 @@ base::Bind(&UnloadResults::AddSuccess, base::Unretained(&unload_results)), base::Bind(&UnloadResults::AddAbort, base::Unretained(&unload_results)), true); - window_observer.Wait(); + ui_test_utils::WaitForBrowserToClose(); EXPECT_EQ(1, unload_results.get_successes()); EXPECT_EQ(0, unload_results.get_aborts()); } @@ -709,12 +649,7 @@ // Close the browser and make sure the beforeunload dialog is shown and can // be clicked. PrepareForDialog(browser()); - content::WindowedNotificationObserver window_observer( - chrome::NOTIFICATION_BROWSER_CLOSED, - content::NotificationService::AllSources()); - chrome::CloseWindow(browser()); - ClickModalDialogButton(true); - window_observer.Wait(); + ManuallyCloseWindow(); } // TODO(ojan): Add tests for unload/beforeunload that have multiple tabs
diff --git a/chrome/browser/web_applications/components/policy/web_app_policy_manager.cc b/chrome/browser/web_applications/components/policy/web_app_policy_manager.cc index 53f16f37..43bc65ad 100644 --- a/chrome/browser/web_applications/components/policy/web_app_policy_manager.cc +++ b/chrome/browser/web_applications/components/policy/web_app_policy_manager.cc
@@ -55,15 +55,11 @@ install_options->launch_container = LaunchContainer::kWindow; } - bool create_shortcut = false; - if (create_desktop_shortcut) - create_shortcut = create_desktop_shortcut->GetBool(); - install_options->add_to_applications_menu = true; - install_options->add_to_desktop = create_shortcut; - - // It's not yet clear how pinning to shelf will work for policy installed - // Web Apps, but for now never pin them. See crbug.com/880125. + install_options->add_to_desktop = + create_desktop_shortcut ? create_desktop_shortcut->GetBool() : false; + // Pinning apps to the ChromeOS shelf is done through the PinnedLauncherApps + // policy. install_options->add_to_quick_launch_bar = false; }
diff --git a/chrome/browser/webauth_interactive_uitest.cc b/chrome/browser/webauth_interactive_uitest.cc index 821b33b86..00e790d6 100644 --- a/chrome/browser/webauth_interactive_uitest.cc +++ b/chrome/browser/webauth_interactive_uitest.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/webauthn/chrome_authenticator_request_delegate.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/ui_test_utils.h" #include "components/network_session_configurator/common/network_switches.h" #include "content/public/browser/authenticator_environment.h" #include "content/public/test/browser_test_utils.h"
diff --git a/chrome/common/crash_keys.cc b/chrome/common/crash_keys.cc index e0a8398..8072b8aa 100644 --- a/chrome/common/crash_keys.cc +++ b/chrome/common/crash_keys.cc
@@ -26,6 +26,7 @@ namespace crash_keys { +// Return true if we DON'T want to upload this flag to the crash server. static bool IsBoringSwitch(const std::string& flag) { static const char* const kIgnoreSwitches[] = { switches::kEnableLogging, @@ -38,6 +39,10 @@ #if defined(OS_MACOSX) switches::kMetricsClientID, #elif defined(OS_CHROMEOS) + // --crash-loop-before is a "boring" switch because it is redundant; + // crash_reporter separately informs the crash server if it is doing + // crash-loop handling. + switches::kCrashLoopBefore, switches::kPpapiFlashArgs, switches::kPpapiFlashPath, switches::kRegisterPepperPlugins,
diff --git a/chrome/common/extensions/api/input_method_private.json b/chrome/common/extensions/api/input_method_private.json index 4d4cc4a..d2a61cc3 100644 --- a/chrome/common/extensions/api/input_method_private.json +++ b/chrome/common/extensions/api/input_method_private.json
@@ -37,7 +37,7 @@ "id": "UnderlineStyle", "type": "string", "description": "The type of the underline to modify a composition segment.", - "enum": ["underline"] + "enum": ["underline", "doubleUnderline", "noUnderline"] }, { "id": "FocusReason",
diff --git a/chrome/common/heap_profiler_controller.cc b/chrome/common/heap_profiler_controller.cc index a2f0e08..a727a2f6 100644 --- a/chrome/common/heap_profiler_controller.cc +++ b/chrome/common/heap_profiler_controller.cc
@@ -13,6 +13,7 @@ #include "base/sampling_heap_profiler/module_cache.h" #include "base/sampling_heap_profiler/sampling_heap_profiler.h" #include "base/task/post_task.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "components/metrics/call_stack_profile_builder.h" #include "components/metrics/call_stack_profile_metrics_provider.h" @@ -49,34 +50,25 @@ base::SamplingHeapProfiler::Get()->SetSamplingInterval(sampling_rate); base::SamplingHeapProfiler::Get()->Start(); } - ScheduleNextSnapshot(task_runner_ ? std::move(task_runner_) - : base::CreateTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT}), - stopped_); + ScheduleNextSnapshot(stopped_); } // static void HeapProfilerController::ScheduleNextSnapshot( - scoped_refptr<base::TaskRunner> task_runner, scoped_refptr<StoppedFlag> stopped) { - // TODO(https://crbug.com/946657): Remove the task_runner and replace the call - // with base::PostDelayedTaskWithTraits once test::ScopedTaskEnvironment - // supports mock time in thread pools. - task_runner->PostDelayedTask( - FROM_HERE, - base::BindOnce(&HeapProfilerController::TakeSnapshot, - std::move(task_runner), std::move(stopped)), + base::PostDelayedTask( + FROM_HERE, {base::TaskPriority::BEST_EFFORT}, + base::BindOnce(&HeapProfilerController::TakeSnapshot, std::move(stopped)), RandomInterval(kHeapCollectionInterval)); } // static void HeapProfilerController::TakeSnapshot( - scoped_refptr<base::TaskRunner> task_runner, scoped_refptr<StoppedFlag> stopped) { if (stopped->data.IsSet()) return; RetrieveAndSendSnapshot(); - ScheduleNextSnapshot(std::move(task_runner), std::move(stopped)); + ScheduleNextSnapshot(std::move(stopped)); } // static
diff --git a/chrome/common/heap_profiler_controller.h b/chrome/common/heap_profiler_controller.h index aae5e915..a2c1511f 100644 --- a/chrome/common/heap_profiler_controller.h +++ b/chrome/common/heap_profiler_controller.h
@@ -9,10 +9,6 @@ #include "base/memory/ref_counted.h" #include "base/synchronization/atomic_flag.h" -namespace base { -class TaskRunner; -} // namespace base - // HeapProfilerController controls collection of sampled heap allocation // snapshots for the current process. class HeapProfilerController { @@ -23,20 +19,13 @@ // Starts periodic heap snapshot collection. void Start(); - void SetTaskRunnerForTest(scoped_refptr<base::TaskRunner> task_runner) { - task_runner_ = std::move(task_runner); - } - private: using StoppedFlag = base::RefCountedData<base::AtomicFlag>; - static void ScheduleNextSnapshot(scoped_refptr<base::TaskRunner> task_runner, - scoped_refptr<StoppedFlag> stopped); - static void TakeSnapshot(scoped_refptr<base::TaskRunner> task_runner, - scoped_refptr<StoppedFlag> stopped); + static void ScheduleNextSnapshot(scoped_refptr<StoppedFlag> stopped); + static void TakeSnapshot(scoped_refptr<StoppedFlag> stopped); static void RetrieveAndSendSnapshot(); - scoped_refptr<base::TaskRunner> task_runner_; scoped_refptr<StoppedFlag> stopped_; DISALLOW_COPY_AND_ASSIGN(HeapProfilerController);
diff --git a/chrome/common/heap_profiler_controller_unittest.cc b/chrome/common/heap_profiler_controller_unittest.cc index 5056f36..fec229c 100644 --- a/chrome/common/heap_profiler_controller_unittest.cc +++ b/chrome/common/heap_profiler_controller_unittest.cc
@@ -6,7 +6,7 @@ #include "base/sampling_heap_profiler/sampling_heap_profiler.h" #include "base/test/bind_test_util.h" -#include "base/test/test_mock_time_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "components/metrics/call_stack_profile_builder.h" #include "testing/gtest/include/gtest/gtest.h" @@ -19,31 +19,31 @@ #define MAYBE_EmptyProfileIsNotEmitted EmptyProfileIsNotEmitted #endif -TEST(HeapProfilerControllerTest, MAYBE_EmptyProfileIsNotEmitted) { - auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>(); - base::TestMockTimeTaskRunner::ScopedContext scoped_context(task_runner.get()); +class HeapProfilerControllerTest : public testing::Test { + protected: + base::test::ScopedTaskEnvironment scoped_task_environment{ + base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME, + base::test::ScopedTaskEnvironment::NowSource::MAIN_THREAD_MOCK_TIME}; +}; +TEST_F(HeapProfilerControllerTest, MAYBE_EmptyProfileIsNotEmitted) { HeapProfilerController controller; metrics::CallStackProfileBuilder::SetBrowserProcessReceiverCallback( base::BindLambdaForTesting( [](base::TimeTicks time, metrics::SampledProfile profile) { ADD_FAILURE(); })); - controller.SetTaskRunnerForTest(task_runner); controller.Start(); - task_runner->FastForwardBy(base::TimeDelta::FromDays(365)); + scoped_task_environment.FastForwardBy(base::TimeDelta::FromDays(365)); } // Sampling profiler is not capable of unwinding stack on Android under tests. #if !defined(OS_ANDROID) -TEST(HeapProfilerControllerTest, ProfileCollectionsScheduler) { +TEST_F(HeapProfilerControllerTest, ProfileCollectionsScheduler) { constexpr size_t kAllocationSize = 42 * 1024; constexpr int kSnapshotsToCollect = 3; - auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>(); - base::TestMockTimeTaskRunner::ScopedContext scoped_context(task_runner.get()); - auto controller = std::make_unique<HeapProfilerController>(); int profile_count = 0; @@ -75,7 +75,6 @@ metrics::CallStackProfileBuilder::SetBrowserProcessReceiverCallback( base::BindLambdaForTesting(check_profile)); - controller->SetTaskRunnerForTest(task_runner); controller->Start(); auto* sampler = base::PoissonAllocationSampler::Get(); @@ -85,7 +84,7 @@ sampler->RecordAlloc(reinterpret_cast<void*>(0x7331), kAllocationSize, base::PoissonAllocationSampler::kMalloc, nullptr); - task_runner->FastForwardUntilNoTasksRemain(); + scoped_task_environment.FastForwardUntilNoTasksRemain(); EXPECT_LE(kSnapshotsToCollect, profile_count); } #endif
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index 6e0de1f..d0ef285 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -2684,13 +2684,13 @@ const char kAllowPopupsDuringPageUnload[] = "allow_popups_during_page_unload"; #if defined(OS_CHROMEOS) -// Enum that specifies certificate management permissions for user. It can have -// one of the following values. -// 0: Users can manage all certificates. +// Enum that specifies client certificate management permissions for user. It +// can have one of the following values. 0: Users can manage all certificates. // 1: Users can manage user certificates, but not device certificates. // 2: Disallow users from managing certificates -// Controlled by CertificateManagementAllowed policy. -const char kCertificateManagementAllowed[] = "certificate_management_allowed"; +// Controlled by ClientCertificateManagementAllowed policy. +const char kClientCertificateManagementAllowed[] = + "certificate_management_allowed"; #endif const char kSharingVapidKey[] = "sharing.vapid_key";
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index 8560cdee..5696f2b 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h
@@ -948,7 +948,7 @@ #endif #if defined(OS_CHROMEOS) -extern const char kCertificateManagementAllowed[]; +extern const char kClientCertificateManagementAllowed[]; #endif extern const char kSharingVapidKey[];
diff --git a/chrome/common/thread_profiler.cc b/chrome/common/thread_profiler.cc index bfdb6c4..b8333d3a 100644 --- a/chrome/common/thread_profiler.cc +++ b/chrome/common/thread_profiler.cc
@@ -245,7 +245,7 @@ std::make_unique<CallStackProfileBuilder>( CallStackProfileParams(GetProcess(), thread, CallStackProfileParams::PROCESS_STARTUP), - work_id_recorder_.get(), base::GetSampleMetadataRecorder())); + work_id_recorder_.get())); startup_profiler_->Start(); @@ -305,7 +305,7 @@ std::make_unique<CallStackProfileBuilder>( CallStackProfileParams(GetProcess(), thread_, CallStackProfileParams::PERIODIC_COLLECTION), - work_id_recorder_.get(), base::GetSampleMetadataRecorder(), + work_id_recorder_.get(), base::BindOnce(&ThreadProfiler::OnPeriodicCollectionCompleted, owning_thread_task_runner_, weak_factory_.GetWeakPtr())));
diff --git a/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc b/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc index f7d6156e..c6dabe3 100644 --- a/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc +++ b/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc
@@ -101,12 +101,12 @@ } } -void MetricsRenderFrameObserver::DidObserveLayoutJank( - double jank_fraction, +void MetricsRenderFrameObserver::DidObserveLayoutShift( + double score, bool after_input_or_scroll) { if (page_timing_metrics_sender_) - page_timing_metrics_sender_->DidObserveLayoutJank(jank_fraction, - after_input_or_scroll); + page_timing_metrics_sender_->DidObserveLayoutShift(score, + after_input_or_scroll); } void MetricsRenderFrameObserver::DidObserveLazyLoadBehavior(
diff --git a/chrome/renderer/page_load_metrics/metrics_render_frame_observer.h b/chrome/renderer/page_load_metrics/metrics_render_frame_observer.h index 3ecc1a7..7c58d451 100644 --- a/chrome/renderer/page_load_metrics/metrics_render_frame_observer.h +++ b/chrome/renderer/page_load_metrics/metrics_render_frame_observer.h
@@ -48,8 +48,7 @@ void DidObserveNewFeatureUsage(blink::mojom::WebFeature feature) override; void DidObserveNewCssPropertyUsage(int css_property, bool is_animated) override; - void DidObserveLayoutJank(double jank_fraction, - bool after_input_or_scroll) override; + void DidObserveLayoutShift(double score, bool after_input_or_scroll) override; void DidObserveLazyLoadBehavior( blink::WebLocalFrameClient::LazyLoadBehavior lazy_load_behavior) override; void DidStartResponse(const GURL& response_url,
diff --git a/chrome/renderer/page_load_metrics/page_timing_metrics_sender.cc b/chrome/renderer/page_load_metrics/page_timing_metrics_sender.cc index 8462cdc..757f26aa 100644 --- a/chrome/renderer/page_load_metrics/page_timing_metrics_sender.cc +++ b/chrome/renderer/page_load_metrics/page_timing_metrics_sender.cc
@@ -94,12 +94,13 @@ } } -void PageTimingMetricsSender::DidObserveLayoutJank(double jank_fraction, - bool after_input_or_scroll) { - DCHECK(jank_fraction > 0); - render_data_.layout_jank_delta += jank_fraction; +void PageTimingMetricsSender::DidObserveLayoutShift( + double score, + bool after_input_or_scroll) { + DCHECK(score > 0); + render_data_.layout_jank_delta += score; if (!after_input_or_scroll) - render_data_.layout_jank_delta_before_input_or_scroll += jank_fraction; + render_data_.layout_jank_delta_before_input_or_scroll += score; EnsureSendTimer(); }
diff --git a/chrome/renderer/page_load_metrics/page_timing_metrics_sender.h b/chrome/renderer/page_load_metrics/page_timing_metrics_sender.h index e75d48c..466b4d7 100644 --- a/chrome/renderer/page_load_metrics/page_timing_metrics_sender.h +++ b/chrome/renderer/page_load_metrics/page_timing_metrics_sender.h
@@ -48,7 +48,7 @@ void DidObserveLoadingBehavior(blink::WebLoadingBehaviorFlag behavior); void DidObserveNewFeatureUsage(blink::mojom::WebFeature feature); void DidObserveNewCssPropertyUsage(int css_property, bool is_animated); - void DidObserveLayoutJank(double jank_fraction, bool after_input_or_scroll); + void DidObserveLayoutShift(double score, bool after_input_or_scroll); void DidObserveLazyLoadBehavior( blink::WebLocalFrameClient::LazyLoadBehavior lazy_load_behavior);
diff --git a/chrome/renderer/page_load_metrics/page_timing_metrics_sender_unittest.cc b/chrome/renderer/page_load_metrics/page_timing_metrics_sender_unittest.cc index 40503b1..e22bba6 100644 --- a/chrome/renderer/page_load_metrics/page_timing_metrics_sender_unittest.cc +++ b/chrome/renderer/page_load_metrics/page_timing_metrics_sender_unittest.cc
@@ -351,9 +351,9 @@ metrics_sender_->Send(timing.Clone()); validator_.ExpectPageLoadTiming(timing); - metrics_sender_->DidObserveLayoutJank(0.5, false); - metrics_sender_->DidObserveLayoutJank(0.5, false); - metrics_sender_->DidObserveLayoutJank(0.5, true); + metrics_sender_->DidObserveLayoutShift(0.5, false); + metrics_sender_->DidObserveLayoutShift(0.5, false); + metrics_sender_->DidObserveLayoutShift(0.5, true); mojom::FrameRenderDataUpdate render_data(1.5, 1.0); validator_.UpdateExpectFrameRenderDataUpdate(render_data);
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 449567d..c50a31d 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -187,7 +187,7 @@ "//components/safe_browsing/db:v4_test_util", "//components/search_engines:test_support", "//components/sessions:test_support", - "//components/signin/core/browser:internals_test_support", + "//components/signin/public/base:test_support", "//components/subresource_filter/content/browser:test_support", "//components/subresource_filter/core/common", "//components/sync:test_support", @@ -1015,6 +1015,7 @@ "../browser/prerender/prerender_test_utils.cc", "../browser/prerender/prerender_test_utils.h", "../browser/previews/defer_all_script_browsertest.cc", + "../browser/previews/defer_all_script_priority_browsertest.cc", "../browser/previews/hints_fetcher_browsertest.cc", "../browser/previews/lazyload_browsertest.cc", "../browser/previews/previews_browsertest.cc", @@ -1806,7 +1807,9 @@ "../browser/ui/views/media_router/media_router_dialog_controller_views_browsertest.cc", "../browser/ui/views/media_router/media_router_ui_browsertest.cc", "../browser/ui/views/media_router/presentation_receiver_window_view_browsertest.cc", + "../browser/ui/views/native_file_system/native_file_system_directory_access_confirmation_view_browsertest.cc", "../browser/ui/views/native_file_system/native_file_system_permission_view_browsertest.cc", + "../browser/ui/views/native_file_system/native_file_system_restricted_directory_dialog_view_browsertest.cc", "../browser/ui/views/omnibox/omnibox_popup_contents_view_browsertest.cc", "../browser/ui/views/page_action/pwa_install_view_browsertest.cc", "../browser/ui/views/page_action/zoom_view_browsertest.cc", @@ -2427,11 +2430,17 @@ if (enable_service_discovery) { sources += [ "../browser/extensions/api/mdns/mdns_apitest.cc" ] } - if (enable_supervised_users) { + + # TODO(crbug.com/980869): Remove is_chromeos once + # enable_supervised_users is only enabled on chromeos + # (and android, which is excluded from browser_tests). + if (enable_supervised_users && is_chromeos) { sources += [ "../browser/supervised_user/supervised_user_browsertest.cc", "../browser/supervised_user/supervised_user_navigation_throttle_browsertest.cc", "../browser/supervised_user/supervised_user_service_browsertest.cc", + "../browser/supervised_user/supervised_user_test_base.cc", + "../browser/supervised_user/supervised_user_test_base.h", ] } if (is_linux && is_asan && is_lsan) { @@ -2793,6 +2802,7 @@ "../browser/component_updater/subresource_filter_component_installer_unittest.cc", "../browser/component_updater/supervised_user_whitelist_installer_unittest.cc", "../browser/component_updater/sw_reporter_installer_win_unittest.cc", + "../browser/content_index/content_index_provider_unittest.cc", "../browser/content_settings/content_settings_default_provider_unittest.cc", "../browser/content_settings/content_settings_mock_observer.cc", "../browser/content_settings/content_settings_mock_observer.h", @@ -3425,7 +3435,6 @@ "../browser/offline_pages/download_archive_manager_unittest.cc", "../browser/offline_pages/offline_page_mhtml_archiver_unittest.cc", "../browser/offline_pages/offline_page_tab_helper_unittest.cc", - "../browser/offline_pages/offline_page_utils_unittest.cc", "../browser/offline_pages/prefetch/offline_metrics_collector_impl_unittest.cc", "../browser/offline_pages/prefetch/prefetch_background_task_handler_impl_unittest.cc", "../browser/offline_pages/prefetch/prefetched_pages_notifier_unittest.cc", @@ -3449,6 +3458,7 @@ } else { sources += [ "../browser/offline_pages/offline_page_request_handler_unittest.cc", + "../browser/offline_pages/offline_page_utils_unittest.cc", "../browser/offline_pages/prefetch/prefetch_instance_id_proxy_unittest.cc", ] } @@ -3782,7 +3792,7 @@ "//components/chrome_cleaner/test:test_name_helper", "//components/feature_engagement/test:test_support", "//components/send_tab_to_self:test_support", - "//components/signin/core/browser:signin_buildflags", + "//components/signin/public/base:signin_buildflags", "//components/sync:test_support", "//services/metrics/public/cpp:ukm_builders", "//third_party/libaddressinput", @@ -4423,12 +4433,6 @@ deps += [ "//chrome/browser/ui/libgtkui" ] } - if (is_desktop_linux && use_dbus) { - sources += [ - "../browser/ui/views/status_icons/success_barrier_callback_unittest.cc", - ] - } - if (enable_service_discovery) { sources += [ "../browser/devtools/device/cast_device_provider_unittest.cc",
diff --git a/chrome/test/base/interactive_test_utils.cc b/chrome/test/base/interactive_test_utils.cc index c7db984..121f423 100644 --- a/chrome/test/base/interactive_test_utils.cc +++ b/chrome/test/base/interactive_test_utils.cc
@@ -11,6 +11,7 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" +#include "content/public/test/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/display/display.h" #include "ui/display/screen.h" @@ -161,23 +162,6 @@ return !testing::Test::HasFatalFailure(); } -bool SendKeyPressAndWait(const Browser* browser, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - int type, - const content::NotificationSource& source) { - content::WindowedNotificationObserver observer(type, source); - - if (!SendKeyPressSync(browser, key, control, shift, alt, command)) - return false; - - observer.Wait(); - return !testing::Test::HasFatalFailure(); -} - bool SendMouseMoveSync(const gfx::Point& location) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner;
diff --git a/chrome/test/base/interactive_test_utils.h b/chrome/test/base/interactive_test_utils.h index 5bf1c12..2eb2c0bba 100644 --- a/chrome/test/base/interactive_test_utils.h +++ b/chrome/test/base/interactive_test_utils.h
@@ -10,20 +10,14 @@ #include "build/build_config.h" #include "chrome/browser/ui/browser_list_observer.h" #include "chrome/browser/ui/view_ids.h" -#include "chrome/test/base/ui_test_utils.h" -#include "content/public/test/test_utils.h" #include "ui/base/test/ui_controls.h" -#include "ui/events/event_constants.h" +#include "ui/display/display.h" +#include "ui/gfx/geometry/point.h" namespace display { -class Display; class Screen; } // namespace display -namespace gfx { -class Point; -} - #if defined(TOOLKIT_VIEWS) namespace views { class View; @@ -122,20 +116,6 @@ bool alt, bool command) WARN_UNUSED_RESULT; -// Sends a key press, blocking until both the key press and a notification from -// |source| of type |type| are received, or until the test times out. This uses -// ui_controls::SendKeyPress, see it for details. Returns true if the event was -// successfully sent and both the event and notification were received. -bool SendKeyPressAndWait(const Browser* browser, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - int type, - const content::NotificationSource& source) - WARN_UNUSED_RESULT; - // Sends a move event blocking until received. Returns true if the event was // successfully received. This uses ui_controls::SendMouse***NotifyWhenDone, // see it for details. @@ -143,45 +123,6 @@ bool SendMouseEventsSync(ui_controls::MouseButton type, int button_state) WARN_UNUSED_RESULT; -// See SendKeyPressAndWait. This function additionally performs a check on the -// NotificationDetails using the provided Details<U>. -template <class U> -bool SendKeyPressAndWaitWithDetails( - const Browser* browser, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - int type, - const content::NotificationSource& source, - const content::Details<U>& details) WARN_UNUSED_RESULT; - -template <class U> -bool SendKeyPressAndWaitWithDetails( - const Browser* browser, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - int type, - const content::NotificationSource& source, - const content::Details<U>& details) { - WindowedNotificationObserverWithDetails<U> observer(type, source); - - if (!SendKeyPressSync(browser, key, control, shift, alt, command)) - return false; - - observer.Wait(); - - U my_details; - if (!observer.GetDetailsFor(source.map_key(), &my_details)) - return false; - - return *details.ptr() == my_details && !testing::Test::HasFatalFailure(); -} - // A combination of SendMouseMove to the middle of the view followed by // SendMouseEvents. Only exposed for toolkit-views. // Alternatives: ClickOnView() and ui::test::EventGenerator.
diff --git a/chrome/test/base/interactive_test_utils_mac.mm b/chrome/test/base/interactive_test_utils_mac.mm index 6d6ac28..d461e02 100644 --- a/chrome/test/base/interactive_test_utils_mac.mm +++ b/chrome/test/base/interactive_test_utils_mac.mm
@@ -15,6 +15,7 @@ #include "chrome/browser/chrome_browser_application_mac.h" #import "ui/base/test/windowed_nsnotification_observer.h" #include "ui/events/cocoa/cocoa_event_utils.h" +#include "ui/events/event_constants.h" namespace {
diff --git a/chrome/test/base/ui_test_utils.cc b/chrome/test/base/ui_test_utils.cc index 196d219..b6b8ee0 100644 --- a/chrome/test/base/ui_test_utils.cc +++ b/chrome/test/base/ui_test_utils.cc
@@ -33,6 +33,7 @@ #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" +#include "chrome/browser/ui/browser_list_observer.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_navigator_params.h" #include "chrome/browser/ui/browser_window.h" @@ -162,6 +163,44 @@ DISALLOW_COPY_AND_ASSIGN(AppModalDialogWaiter); }; +class BrowserChangeObserver : public BrowserListObserver { + public: + enum class ChangeType { + kAdded, + kRemoved, + }; + + BrowserChangeObserver(const Browser* browser, ChangeType type) + : browser_(browser), type_(type) { + BrowserList::AddObserver(this); + } + + ~BrowserChangeObserver() override { BrowserList::RemoveObserver(this); } + + void Wait() { run_loop_.Run(); } + + // BrowserListObserver: + void OnBrowserAdded(Browser* browser) override { + if (type_ == ChangeType::kAdded) + run_loop_.Quit(); + } + + void OnBrowserRemoved(Browser* browser) override { + if (browser_ && browser_ != browser) + return; + + if (type_ == ChangeType::kRemoved) + run_loop_.Quit(); + } + + private: + const Browser* browser_; + ChangeType type_; + base::RunLoop run_loop_; + + DISALLOW_COPY_AND_ASSIGN(BrowserChangeObserver); +}; + class AutocompleteChangeObserver : public OmniboxControllerEmitter::Observer { public: explicit AutocompleteChangeObserver(Profile* profile) { @@ -597,4 +636,14 @@ } } +void WaitForBrowserToOpen() { + BrowserChangeObserver(nullptr, BrowserChangeObserver::ChangeType::kAdded) + .Wait(); +} + +void WaitForBrowserToClose(const Browser* browser) { + BrowserChangeObserver(browser, BrowserChangeObserver::ChangeType::kRemoved) + .Wait(); +} + } // namespace ui_test_utils
diff --git a/chrome/test/base/ui_test_utils.h b/chrome/test/base/ui_test_utils.h index 09902e1a..4c753339 100644 --- a/chrome/test/base/ui_test_utils.h +++ b/chrome/test/base/ui_test_utils.h
@@ -184,6 +184,14 @@ // Blocks until the |history_service|'s history finishes loading. void WaitForHistoryToLoad(history::HistoryService* history_service); +// Blocks until a Browser is added to the BrowserList. +void WaitForBrowserToOpen(); + +// Blocks until a Browser is removed from the BrowserList. If |browser| is null, +// the removal of any browser will suffice; otherwise the removed browser must +// match |browser|. +void WaitForBrowserToClose(const Browser* browser = nullptr); + // Download the given file and waits for the download to complete. void DownloadURL(Browser* browser, const GURL& download_url);
diff --git a/chrome/test/data/android/render_tests/ArticleSnippetsTest.NightModeDisabled-hot_state_personalized_signin_promo.Nexus_5-19.png.sha1 b/chrome/test/data/android/render_tests/ArticleSnippetsTest.NightModeDisabled-hot_state_personalized_signin_promo.Nexus_5-19.png.sha1 index b057ae4..0afc084 100644 --- a/chrome/test/data/android/render_tests/ArticleSnippetsTest.NightModeDisabled-hot_state_personalized_signin_promo.Nexus_5-19.png.sha1 +++ b/chrome/test/data/android/render_tests/ArticleSnippetsTest.NightModeDisabled-hot_state_personalized_signin_promo.Nexus_5-19.png.sha1
@@ -1 +1 @@ -eae9550ca69292f9a365f2916cf3492515f9dad5 \ No newline at end of file +cd127efdb08111be0465f3295ab31cbecc212c3a \ No newline at end of file
diff --git a/chrome/test/data/android/render_tests/ArticleSnippetsTest.NightModeEnabled-hot_state_personalized_signin_promo.Nexus_5-19.png.sha1 b/chrome/test/data/android/render_tests/ArticleSnippetsTest.NightModeEnabled-hot_state_personalized_signin_promo.Nexus_5-19.png.sha1 index 3ef1e43b..834e60a 100644 --- a/chrome/test/data/android/render_tests/ArticleSnippetsTest.NightModeEnabled-hot_state_personalized_signin_promo.Nexus_5-19.png.sha1 +++ b/chrome/test/data/android/render_tests/ArticleSnippetsTest.NightModeEnabled-hot_state_personalized_signin_promo.Nexus_5-19.png.sha1
@@ -1 +1 @@ -ad5789d58a727b600a90d36d5c5787a98024465a \ No newline at end of file +724ea7b467165f03bc2f5c9ec92b1c6c6d9d5dac \ No newline at end of file
diff --git a/chrome/test/data/local_ntp/customize_menu_browsertest.js b/chrome/test/data/local_ntp/customize_menu_browsertest.js index 5874f55..715faf7c 100644 --- a/chrome/test/data/local_ntp/customize_menu_browsertest.js +++ b/chrome/test/data/local_ntp/customize_menu_browsertest.js
@@ -23,6 +23,8 @@ COLORS_BUTTON: 'colors-button', COLORS_DEFAULT: 'colors-default', COLORS_MENU: 'colors-menu', + COLORS_THEME: 'colors-theme', + COLORS_THEME_UNINSTALL: 'colors-theme-uninstall', CUSTOMIZATION_MENU: 'customization-menu', DONE: 'menu-done', EDIT_BG: 'edit-bg', @@ -89,6 +91,13 @@ /** * The number of times + * chrome.embeddedSearch.newTabPage.useDefaultTheme is called. + * @type {number} + */ +test.customizeMenu.useDefaultThemeCount = 0; + +/** + * The number of times * chrome.embeddedSearch.newTabPage.toggleMostVisitedOrCustomLinks is called. * @type {number} */ @@ -109,6 +118,13 @@ test.customizeMenu.timesCustomBackgroundWasSet = 0; /** + * Themed properties for testing to be used instead of + * chrome.embeddedSearch.newTabPage.themeBackgroundInfo. + * @type {?Object} + */ +test.customizeMenu.mockThemeBackgroundInfo = {}; + +/** * Sets up the page for each individual test. */ test.customizeMenu.setUp = function() { @@ -118,7 +134,7 @@ // populate using base::test::ScopedFeatureList. configData.richerPicker = true; configData.chromeColors = true; - customize.colorMenuLoaded = false; + customize.colorsMenuLoaded = false; customize.builtTiles = false; // Reset variable values. @@ -128,9 +144,11 @@ test.customizeMenu.applyAutogeneratedThemeCount = 0; test.customizeMenu.confirmThemeChangesCount = 0; test.customizeMenu.revertThemeChangesCount = 0; + test.customizeMenu.useDefaultThemeCount = 0; test.customizeMenu.toggleMostVisitedOrCustomLinksCount = 0; test.customizeMenu.toggleShortcutsVisibilityCount = 0; test.customizeMenu.timesCustomBackgroundWasSet = 0; + test.customizeMenu.mockThemeBackgroundInfo = {}; }; // ******************************* SIMPLE TESTS ******************************* @@ -201,7 +219,7 @@ // Select a background. setupFakeAsyncImageLoad('coll_tile_0'); $('coll_tile_0').click(); - const background = $('img_tile_0'); + const background = $('coll_0_img_tile_0'); background.click(); assertTrue(background.parentElement.classList.contains( test.customizeMenu.CLASSES.SELECTED)); @@ -259,7 +277,7 @@ // Select a background. setupFakeAsyncImageLoad('coll_tile_0'); $('coll_tile_0').click(); - $('img_tile_0').click(); + $('coll_0_img_tile_0').click(); // Select a shortcut option. $(test.customizeMenu.IDS.SHORTCUTS_BUTTON).click(); @@ -292,7 +310,7 @@ // Select a background. setupFakeAsyncImageLoad('coll_tile_0'); $('coll_tile_0').click(); - $('img_tile_0').click(); + $('coll_0_img_tile_0').click(); // Select a shortcut option. $(test.customizeMenu.IDS.SHORTCUTS_BUTTON).click(); @@ -536,6 +554,60 @@ assertTrue(!!$('color_0').style.backgroundImage); }; +/** + * Test that at theme info is not visible when no theme id is available. + */ +test.customizeMenu.testColors_ThemeInfo_NoThemeID = function() { + test.customizeMenu.mockThemeBackgroundInfo = {themeName: 'test theme name'}; + init(); + $(test.customizeMenu.IDS.EDIT_BG).click(); + $(test.customizeMenu.IDS.COLORS_BUTTON).click(); + assertFalse(elementIsVisible($(test.customizeMenu.IDS.COLORS_THEME))); +}; + +/** + * Test that at theme info is not visible when no theme name is available. + */ +test.customizeMenu.testColors_ThemeInfo_NoThemeName = function() { + test.customizeMenu.mockThemeBackgroundInfo = {themeId: 'test theme id'}; + init(); + $(test.customizeMenu.IDS.EDIT_BG).click(); + $(test.customizeMenu.IDS.COLORS_BUTTON).click(); + assertFalse(elementIsVisible($(test.customizeMenu.IDS.COLORS_THEME))); +}; + +/** + * Test that at theme info is visible. + */ +test.customizeMenu.testColors_ThemeInfo_Visible = function() { + test.customizeMenu.mockThemeBackgroundInfo = { + themeId: 'test theme id', + themeName: 'test theme name' + }; + init(); + $(test.customizeMenu.IDS.EDIT_BG).click(); + $(test.customizeMenu.IDS.COLORS_BUTTON).click(); + assertTrue(elementIsVisible($(test.customizeMenu.IDS.COLORS_THEME))); +}; + +/** + * Test that at theme uninstall triggers correct calls. + */ +test.customizeMenu.testColors_ThemeInfo_Uninstall = function() { + test.customizeMenu.mockThemeBackgroundInfo = { + themeId: 'test theme id', + themeName: 'test theme name' + }; + init(); + $(test.customizeMenu.IDS.EDIT_BG).click(); + $(test.customizeMenu.IDS.COLORS_BUTTON).click(); + assertTrue(elementIsVisible($(test.customizeMenu.IDS.COLORS_THEME))); + assertEquals(0, test.customizeMenu.useDefaultThemeCount); + + $(test.customizeMenu.IDS.COLORS_THEME_UNINSTALL).click(); + assertEquals(1, test.customizeMenu.useDefaultThemeCount); +}; + //// BACKGROUND SUBMENU TESTS //// /* @@ -571,7 +643,7 @@ .getElementsByClassName('bg-sel-tile') .length === 4); - $('img_tile_0').click(); + $('coll_0_img_tile_0').click(); $(test.customizeMenu.IDS.MENU_DONE).click(); // No menu should be open, and setCustomBackground should have been called. @@ -615,7 +687,7 @@ .getElementsByClassName('bg-sel-tile') .length === 4); - $('img_tile_0').click(); + $('coll_0_img_tile_0').click(); $(test.customizeMenu.IDS.MENU_CANCEL).click(); // No menu should be open, and setCustomBackground should NOT have been @@ -658,7 +730,7 @@ .getElementsByClassName('bg-sel-tile') .length === 4); - $('img_tile_0').click(); + $('coll_0_img_tile_0').click(); $(test.customizeMenu.IDS.MENU_BACK).click(); // The main backgrounds menu should be open, and no custom background set. @@ -666,7 +738,7 @@ assertFalse(elementIsVisible(backgroundImageSubmenu)); assertEquals(0, test.customizeMenu.timesCustomBackgroundWasSet); - // Reopen the images menu, the selection should be cleared. + // Reopen the images menu, the selection should still be present. $('coll_tile_0').click(); assertFalse(elementIsVisible(backgroundSubmenu)); @@ -678,7 +750,11 @@ assertTrue( $(test.customizeMenu.IDS.BACKGROUNDS_IMAGE_MENU) .getElementsByClassName('selected') - .length === 0); + .length === 1); + assertTrue( + $(test.customizeMenu.IDS.BACKGROUNDS_IMAGE_MENU) + .getElementsByClassName('selected')[0] + .firstChild.id === 'coll_0_img_tile_0'); }; // ******************************* HELPERS ******************************* @@ -698,6 +774,9 @@ const revertThemeChanges = () => { test.customizeMenu.revertThemeChangesCount++ }; + const useDefaultTheme = () => { + test.customizeMenu.useDefaultThemeCount++; + }; const toggleMostVisitedOrCustomLinks = () => { test.customizeMenu.toggleMostVisitedOrCustomLinksCount++ }; @@ -710,8 +789,13 @@ // We want to keep some EmbeddedSearchAPI functions, so save and add them to // our mock API. const getColorsInfo = chrome.embeddedSearch.newTabPage.getColorsInfo; - const themeBackgroundInfo = + let themeBackgroundInfo = chrome.embeddedSearch.newTabPage.themeBackgroundInfo; + // Override theme background properties with testing values. + for (const property in test.customizeMenu.mockThemeBackgroundInfo) { + themeBackgroundInfo[property] = + test.customizeMenu.mockThemeBackgroundInfo[property]; + }; test.customizeMenu.stubs.replace(chrome.embeddedSearch, 'newTabPage', { applyAutogeneratedTheme: applyAutogeneratedTheme, @@ -728,6 +812,7 @@ themeBackgroundInfo: themeBackgroundInfo, toggleMostVisitedOrCustomLinks: toggleMostVisitedOrCustomLinks, toggleShortcutsVisibility: toggleShortcutsVisibility, + useDefaultTheme: useDefaultTheme, }); initLocalNTP(/*isGooglePage=*/ true);
diff --git a/chrome/test/data/pdf/accessibility/hello-world-expected-auralinux.txt b/chrome/test/data/pdf/accessibility/hello-world-expected-auralinux.txt new file mode 100644 index 0000000..ee8c26c --- /dev/null +++ b/chrome/test/data/pdf/accessibility/hello-world-expected-auralinux.txt
@@ -0,0 +1,5 @@ +[embedded component] +++[panel] +++++[landmark] name='Page 1' +++++++[paragraph] +++++++++[text] name='Hello, world!'
diff --git a/chrome/test/data/pdf/accessibility/hello-world-expected-blink.txt b/chrome/test/data/pdf/accessibility/hello-world-expected-blink.txt new file mode 100644 index 0000000..6fad2681 --- /dev/null +++ b/chrome/test/data/pdf/accessibility/hello-world-expected-blink.txt
@@ -0,0 +1,6 @@ +embeddedObject +++group restriction=readOnly +++++region name='Page 1' restriction=readOnly +++++++paragraph restriction=readOnly +++++++++staticText name='Hello, world!' restriction=readOnly +++++++++++inlineTextBox name='Hello, world!' restriction=readOnly
diff --git a/chrome/test/data/pdf/accessibility/hello-world-expected-mac.txt b/chrome/test/data/pdf/accessibility/hello-world-expected-mac.txt new file mode 100644 index 0000000..f048994c --- /dev/null +++ b/chrome/test/data/pdf/accessibility/hello-world-expected-mac.txt
@@ -0,0 +1,5 @@ +AXGroup AXDescription='Page 1' +++AXGroup +++++AXGroup AXDescription='Page 1' +++++++AXGroup +++++++++AXStaticText AXValue='Hello, world!'
diff --git a/chrome/test/data/pdf/accessibility/hello-world-expected-uia-win.txt b/chrome/test/data/pdf/accessibility/hello-world-expected-uia-win.txt new file mode 100644 index 0000000..ebda394 --- /dev/null +++ b/chrome/test/data/pdf/accessibility/hello-world-expected-uia-win.txt
@@ -0,0 +1,4 @@ +group +++group +++++region Name='Page 1' +++++++group
diff --git a/chrome/test/data/pdf/accessibility/hello-world-expected-win.txt b/chrome/test/data/pdf/accessibility/hello-world-expected-win.txt new file mode 100644 index 0000000..c33fc42 --- /dev/null +++ b/chrome/test/data/pdf/accessibility/hello-world-expected-win.txt
@@ -0,0 +1,5 @@ +ROLE_SYSTEM_GROUPING FOCUSABLE +++ROLE_SYSTEM_GROUPING READONLY +++++IA2_ROLE_LANDMARK name='Page 1' READONLY +++++++IA2_ROLE_PARAGRAPH READONLY +++++++++ROLE_SYSTEM_STATICTEXT name='Hello, world!' READONLY
diff --git a/chrome/test/data/pdf/accessibility/hello-world.in b/chrome/test/data/pdf/accessibility/hello-world.in new file mode 100644 index 0000000..2c44a25 --- /dev/null +++ b/chrome/test/data/pdf/accessibility/hello-world.in
@@ -0,0 +1,44 @@ +{{header}} +{{object 1 0}} << + /Type /Catalog + /Pages 2 0 R +>> +endobj +{{object 2 0}} << + /Type /Pages + /MediaBox [ 0 0 200 200 ] + /Count 1 + /Kids [ 3 0 R ] +>> +endobj +{{object 3 0}} << + /Type /Page + /Parent 2 0 R + /Resources << + /Font << + /F1 4 0 R + >> + >> + /Contents 5 0 R +>> +endobj +{{object 4 0}} << + /Type /Font + /Subtype /Type1 + /BaseFont /Helvetica +>> +endobj +{{object 5 0}} << +>> +stream +BT +20 100 Td +/F1 16 Tf +(Hello, world!) Tj +ET +endstream +endobj +{{xref}} +{{trailer}} +{{startxref}} +%%EOF
diff --git a/chrome/test/data/pdf/accessibility/hello-world.pdf b/chrome/test/data/pdf/accessibility/hello-world.pdf new file mode 100644 index 0000000..16c94e4 --- /dev/null +++ b/chrome/test/data/pdf/accessibility/hello-world.pdf
@@ -0,0 +1,56 @@ +%PDF-1.7 +% ò¤ô +1 0 obj << + /Type /Catalog + /Pages 2 0 R +>> +endobj +2 0 obj << + /Type /Pages + /MediaBox [ 0 0 200 200 ] + /Count 1 + /Kids [ 3 0 R ] +>> +endobj +3 0 obj << + /Type /Page + /Parent 2 0 R + /Resources << + /Font << + /F1 4 0 R + >> + >> + /Contents 5 0 R +>> +endobj +4 0 obj << + /Type /Font + /Subtype /Type1 + /BaseFont /Helvetica +>> +endobj +5 0 obj << +>> +stream +BT +20 100 Td +/F1 16 Tf +(Hello, world!) Tj +ET +endstream +endobj +xref +0 6 +0000000000 65535 f +0000000015 00000 n +0000000068 00000 n +0000000161 00000 n +0000000287 00000 n +0000000363 00000 n +trailer << + /Root 1 0 R + /Size 6 +>> +startxref +446 +%%EOF
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index 65525b5..d3f11c00 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -3139,6 +3139,18 @@ ] }, + "SelectToSpeakEnabled": { + "os": ["chromeos"], + "test_policy": { "SelectToSpeakEnabled": true }, + "pref_mappings": [ + { "pref": "settings.a11y.select_to_speak", + "indicator_tests": [ + { "policy": { "SelectToSpeakEnabled": true } } + ] + } + ] + }, + "ScreenMagnifierType": { "os": ["chromeos"], "test_policy": { "ScreenMagnifierType": 1 }, @@ -4443,9 +4455,9 @@ "pref_mappings": [{ "pref": "child_user.parent_access_code.config" }] }, - "CertificateManagementAllowed": { + "ClientCertificateManagementAllowed": { "os": ["chromeos"], - "test_policy": { "CertificateManagementAllowed": 2 }, + "test_policy": { "ClientCertificateManagementAllowed": 2 }, "pref_mappings": [{ "pref": "certificate_management_allowed" }] },
diff --git a/chrome/test/data/webui/app_management/managed_apps_test.js b/chrome/test/data/webui/app_management/managed_apps_test.js index d78f054..d075dd4 100644 --- a/chrome/test/data/webui/app_management/managed_apps_test.js +++ b/chrome/test/data/webui/app_management/managed_apps_test.js
@@ -63,9 +63,9 @@ }); test('Pin to shelf toggle effected by policy', () => { - const shelfSwitch = - appDetailView.$$('app-management-metadata-view').$$('#shelf-switch'); - expectTrue(!!shelfSwitch.querySelector('#policy-indicator')); - expectTrue(shelfSwitch.querySelector('#pin-to-shelf-toggle').disabled); + const pinToShelfSetting = appDetailView.$$('#pin-to-shelf-setting') + .$$('app-management-toggle-row'); + expectTrue(!!pinToShelfSetting.$$('#policy-indicator')); + expectTrue(pinToShelfSetting.$$('cr-toggle').disabled); }); });
diff --git a/chrome/test/data/webui/settings/certificate_manager_test.js b/chrome/test/data/webui/settings/certificate_manager_test.js index 7f722a0..0efb082 100644 --- a/chrome/test/data/webui/settings/certificate_manager_test.js +++ b/chrome/test/data/webui/settings/certificate_manager_test.js
@@ -762,6 +762,43 @@ certificateType: CertificateType.CA })); }); + + if (cr.isChromeOS) { + // Test that ClientCertificateManagementAllowed policy is applied to the + // UI. + test('ImportButton_ClientPolicy', function() { + const paperTabsElement = page.shadowRoot.querySelector('cr-tabs'); + paperTabsElement.selected = CertificateCategoryIndex.PERSONAL; + Polymer.dom.flush(); + paperTabsElement.selected = CertificateCategoryIndex.CA; + Polymer.dom.flush(); + const certificateLists = + page.shadowRoot.querySelectorAll('certificate-list'); + // Import buttons are shown in the client and CA certificate tabs. + let clientImportButton = certificateLists[0].$$('#import'); + assertFalse(clientImportButton.hidden); + let clientImportAndBindButton = + certificateLists[0].$$('#importAndBind'); + assertFalse(clientImportAndBindButton.hidden); + let caImportButton = certificateLists[1].$$('#import'); + assertFalse(caImportButton.hidden); + + return browserProxy.whenCalled('refreshCertificates').then(function() { + cr.webUIListenerCallback( + 'certificates-model-ready', false /* clientImportAllowed */); + // Verify that import buttons are hidden in the client certificate + // tab. + clientImportButton = certificateLists[0].$$('#import'); + assertTrue(clientImportButton.hidden); + clientImportAndBindButton = certificateLists[0].$$('#importAndBind'); + assertTrue(clientImportAndBindButton.hidden); + // Verify that import button is shown in the CA certificate tab. + caImportButton = certificateLists[1].$$('#import'); + assertFalse(caImportButton.hidden); + }); + }); + } + }); suite('CertificateListTests', function() {
diff --git a/chrome/test/media_router/media_router_ui_for_test.cc b/chrome/test/media_router/media_router_ui_for_test.cc index 8478efd..7adb45d 100644 --- a/chrome/test/media_router/media_router_ui_for_test.cc +++ b/chrome/test/media_router/media_router_ui_for_test.cc
@@ -263,9 +263,9 @@ MediaRouterUiForTest::MediaRouterUiForTest(content::WebContents* web_contents) : web_contents_(web_contents), - dialog_controller_( - MediaRouterDialogControllerViews::GetOrCreateForWebContents( - web_contents)), + dialog_controller_(static_cast<MediaRouterDialogControllerViews*>( + MediaRouterDialogController::GetOrCreateForWebContents( + web_contents))), weak_factory_(this) { dialog_controller_->SetDialogCreationCallbackForTesting(base::BindRepeating( &MediaRouterUiForTest::OnDialogCreated, weak_factory_.GetWeakPtr()));
diff --git a/chromecast/browser/cast_browser_main_parts.h b/chromecast/browser/cast_browser_main_parts.h index 99ed6d2..7364022 100644 --- a/chromecast/browser/cast_browser_main_parts.h +++ b/chromecast/browser/cast_browser_main_parts.h
@@ -14,6 +14,7 @@ #include "chromecast/chromecast_buildflags.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_main_parts.h" +#include "content/public/common/main_function_params.h" #if defined(OS_ANDROID) #include "base/timer/timer.h" @@ -21,10 +22,6 @@ class PrefService; -namespace content { -struct MainFunctionParams; -} - namespace extensions { class ExtensionsClient; class ExtensionsBrowserClient; @@ -93,7 +90,7 @@ private: std::unique_ptr<CastBrowserProcess> cast_browser_process_; - const content::MainFunctionParams& parameters_; // For running browser tests. + const content::MainFunctionParams parameters_; // For running browser tests. // Caches a pointer of the CastContentBrowserClient. CastContentBrowserClient* const cast_content_browser_client_ = nullptr; URLRequestContextFactory* const url_request_context_factory_;
diff --git a/chromecast/browser/cast_net_log.cc b/chromecast/browser/cast_net_log.cc index 4dca463..4a0c9e6 100644 --- a/chromecast/browser/cast_net_log.cc +++ b/chromecast/browser/cast_net_log.cc
@@ -49,7 +49,7 @@ if (command_line->HasSwitch(network::switches::kLogNetLog)) { base::FilePath log_path = command_line->GetSwitchValuePath(network::switches::kLogNetLog); - net::NetLogCaptureMode capture_mode = net::NetLogCaptureMode::Default(); + net::NetLogCaptureMode capture_mode = net::NetLogCaptureMode::kDefault; file_net_log_observer_ = net::FileNetLogObserver::CreateUnbounded(log_path, GetShellConstants());
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index 1179c35..df73bb2 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -12317.0.0 \ No newline at end of file +12334.0.0 \ No newline at end of file
diff --git a/chromeos/components/multidevice/OWNERS b/chromeos/components/multidevice/OWNERS index 2579c1c..8700e6f3 100644 --- a/chromeos/components/multidevice/OWNERS +++ b/chromeos/components/multidevice/OWNERS
@@ -1,3 +1,4 @@ khorimoto@chromium.org jlklein@chromium.org hansberry@chromium.org +nohle@chromium.org
diff --git a/chromeos/constants/chromeos_features.cc b/chromeos/constants/chromeos_features.cc index 30098ec..79ab114 100644 --- a/chromeos/constants/chromeos_features.cc +++ b/chromeos/constants/chromeos_features.cc
@@ -23,6 +23,10 @@ "BlueZLongTermKeyBlocklist", base::FEATURE_DISABLED_BY_DEFAULT}; const char kBlueZLongTermKeyBlocklistParamName[] = "ltk_blocklist"; +// Enable or disables running the Camera App as a System Web App. +const base::Feature kCameraSystemWebApp{"CameraSystemWebApp", + base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables or disables Crostini Backup. const base::Feature kCrostiniBackup{"CrostiniBackup", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/chromeos/constants/chromeos_features.h b/chromeos/constants/chromeos_features.h index 128f9b0..efe724f 100644 --- a/chromeos/constants/chromeos_features.h +++ b/chromeos/constants/chromeos_features.h
@@ -23,6 +23,8 @@ extern const base::Feature kBlueZLongTermKeyBlocklist; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const char kBlueZLongTermKeyBlocklistParamName[]; +COMPONENT_EXPORT(CHROMEOS_CONSTANTS) +extern const base::Feature kCameraSystemWebApp; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCrostiniBackup; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCrostiniGpuSupport;
diff --git a/chromeos/printing/ppd_provider.cc b/chromeos/printing/ppd_provider.cc index 44b035d..7958605 100644 --- a/chromeos/printing/ppd_provider.cc +++ b/chromeos/printing/ppd_provider.cc
@@ -491,17 +491,9 @@ RunPpdReferenceResolutionSucceeded(std::move(next.cb), kEpsonGenericPPD); } else { - // We don't have anything else left to try. - if (search_data.discovery_type == - PrinterSearchData::PrinterDiscoveryType::kUsb) { - // We've reached unsupported USB printer, try to grab the manufacturer - // name. - ResolveUsbManufacturer(std::move(next.cb), search_data.usb_vendor_id); - } else { - // Non-USB printer, so we fail resolution normally. - RunPpdReferenceResolutionNotFound(std::move(next.cb), - "" /* Empty Manufacturer */); - } + // We don't have anything else left to try. We've reached unsupported + // USB printer, try to grab the manufacturer name. + ResolveUsbManufacturer(std::move(next.cb), search_data.usb_vendor_id); } } // Didn't start any fetches.
diff --git a/chromeos/printing/ppd_provider_unittest.cc b/chromeos/printing/ppd_provider_unittest.cc index e00bb23b..3ea200b 100644 --- a/chromeos/printing/ppd_provider_unittest.cc +++ b/chromeos/printing/ppd_provider_unittest.cc
@@ -954,7 +954,6 @@ auto provider = CreateProvider("en", false); PrinterSearchData search_data; - search_data.discovery_type = PrinterSearchData::PrinterDiscoveryType::kUsb; // Vendor id that exists, nonexistent device id, should get a NOT_FOUND. // Although this is an unsupported printer model, we can still expect to get
diff --git a/chromeos/services/device_sync/cryptauth_device.cc b/chromeos/services/device_sync/cryptauth_device.cc index 88cb89b..d515873 100644 --- a/chromeos/services/device_sync/cryptauth_device.cc +++ b/chromeos/services/device_sync/cryptauth_device.cc
@@ -93,11 +93,15 @@ return base::nullopt; base::Optional<cryptauthv2::BetterTogetherDeviceMetadata> - better_together_device_metadata = util::DecodeProtoMessageFromValueString< - cryptauthv2::BetterTogetherDeviceMetadata>( - dict.FindKey(kBetterTogetherDeviceMetadataDictKey)); - if (!better_together_device_metadata) - return base::nullopt; + better_together_device_metadata; + const base::Value* metadata_value = + dict.FindKey(kBetterTogetherDeviceMetadataDictKey); + if (metadata_value) { + better_together_device_metadata = util::DecodeProtoMessageFromValueString< + cryptauthv2::BetterTogetherDeviceMetadata>(metadata_value); + if (!better_together_device_metadata) + return base::nullopt; + } base::Optional< std::map<multidevice::SoftwareFeature, multidevice::SoftwareFeatureState>> @@ -108,7 +112,7 @@ return CryptAuthDevice(*instance_id, *device_name, *device_better_together_public_key, *last_update_time, - *better_together_device_metadata, *feature_states); + better_together_device_metadata, *feature_states); } CryptAuthDevice::CryptAuthDevice(const std::string& instance_id) @@ -121,7 +125,7 @@ const std::string& device_name, const std::string& device_better_together_public_key, const base::Time& last_update_time, - const cryptauthv2::BetterTogetherDeviceMetadata& + const base::Optional<cryptauthv2::BetterTogetherDeviceMetadata>& better_together_device_metadata, const std::map<multidevice::SoftwareFeature, multidevice::SoftwareFeatureState>& feature_states) @@ -145,22 +149,30 @@ dict.SetKey(kDeviceBetterTogetherPublicKeyDictKey, util::EncodeAsValueString(device_better_together_public_key)); dict.SetKey(kLastUpdateTimeDictKey, ::util::TimeToValue(last_update_time)); - dict.SetKey( - kBetterTogetherDeviceMetadataDictKey, - util::EncodeProtoMessageAsValueString(&better_together_device_metadata)); dict.SetKey(kFeatureStatesDictKey, FeatureStatesToDictionary(feature_states)); + if (better_together_device_metadata) { + dict.SetKey(kBetterTogetherDeviceMetadataDictKey, + util::EncodeProtoMessageAsValueString( + &better_together_device_metadata.value())); + } return dict; } bool CryptAuthDevice::operator==(const CryptAuthDevice& other) const { - return instance_id_ == other.instance_id_ && + bool does_metadata_match = + (!better_together_device_metadata && + !other.better_together_device_metadata) || + (better_together_device_metadata.has_value() && + better_together_device_metadata.has_value() && + better_together_device_metadata->SerializeAsString() == + other.better_together_device_metadata->SerializeAsString()); + + return does_metadata_match && instance_id_ == other.instance_id_ && device_name == other.device_name && device_better_together_public_key == other.device_better_together_public_key && last_update_time == other.last_update_time && - better_together_device_metadata.SerializeAsString() == - other.better_together_device_metadata.SerializeAsString() && feature_states == other.feature_states; }
diff --git a/chromeos/services/device_sync/cryptauth_device.h b/chromeos/services/device_sync/cryptauth_device.h index c9ca6e2..296cb42 100644 --- a/chromeos/services/device_sync/cryptauth_device.h +++ b/chromeos/services/device_sync/cryptauth_device.h
@@ -27,14 +27,14 @@ const base::Value& dict); // |instance_id|: The Instance ID, used as a unique device identifier. Cannot - // be empty. + // be empty. explicit CryptAuthDevice(const std::string& instance_id); CryptAuthDevice( const std::string& instance_id, const std::string& device_name, const std::string& device_better_together_public_key, const base::Time& last_update_time, - const cryptauthv2::BetterTogetherDeviceMetadata& + const base::Optional<cryptauthv2::BetterTogetherDeviceMetadata>& better_together_device_metadata, const std::map<multidevice::SoftwareFeature, multidevice::SoftwareFeatureState>& feature_states); @@ -75,8 +75,9 @@ base::Time last_update_time; // Device metadata relevant to the suite of multi-device ("Better Together") - // features. - cryptauthv2::BetterTogetherDeviceMetadata better_together_device_metadata; + // features. Null if metadata could not be decrypted. + base::Optional<cryptauthv2::BetterTogetherDeviceMetadata> + better_together_device_metadata; // A map from the multi-device feature type (example: kBetterTogetherHost) to // feature state (example: kEnabled).
diff --git a/chromeos/services/device_sync/cryptauth_device_registry_impl_unittest.cc b/chromeos/services/device_sync/cryptauth_device_registry_impl_unittest.cc index 08ea263..98274ff 100644 --- a/chromeos/services/device_sync/cryptauth_device_registry_impl_unittest.cc +++ b/chromeos/services/device_sync/cryptauth_device_registry_impl_unittest.cc
@@ -78,7 +78,7 @@ kFakeFeatureStates0), CryptAuthDevice(kInstanceId1, kDeviceName1, kDeviceBetterTogetherPublicKey1, kLastUpdateTime1, - cryptauthv2::GetBetterTogetherDeviceMetadataForTest(), + base::nullopt /* better_together_device_metadata */, kFakeFeatureStates1)}; }());
diff --git a/chromeos/services/device_sync/device_sync_impl.h b/chromeos/services/device_sync/device_sync_impl.h index 5f6b545aa..bc8e70e 100644 --- a/chromeos/services/device_sync/device_sync_impl.h +++ b/chromeos/services/device_sync/device_sync_impl.h
@@ -16,7 +16,7 @@ #include "chromeos/services/device_sync/network_request_error.h" #include "chromeos/services/device_sync/public/mojom/device_sync.mojom.h" #include "chromeos/services/device_sync/remote_device_provider.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "services/preferences/public/cpp/pref_service_factory.h" #include "services/preferences/public/mojom/preferences.mojom.h"
diff --git a/chromeos/services/network_config/public/cpp/cros_network_config_test_helper.cc b/chromeos/services/network_config/public/cpp/cros_network_config_test_helper.cc index e7bacda8..3eed9fb 100644 --- a/chromeos/services/network_config/public/cpp/cros_network_config_test_helper.cc +++ b/chromeos/services/network_config/public/cpp/cros_network_config_test_helper.cc
@@ -14,16 +14,31 @@ namespace network_config { CrosNetworkConfigTestHelper::CrosNetworkConfigTestHelper() { + SetupCrosNetworkConfig(); + // Create a local service manager connector to handle requests. + service_manager::mojom::ConnectorRequest request; + owned_connector_ = service_manager::Connector::Create(&request); + connector_ = owned_connector_.get(); + SetupService(); +} + +CrosNetworkConfigTestHelper::CrosNetworkConfigTestHelper( + service_manager::Connector* connector) + : connector_(connector) { + SetupCrosNetworkConfig(); + SetupService(); +} + +CrosNetworkConfigTestHelper::~CrosNetworkConfigTestHelper() = default; + +void CrosNetworkConfigTestHelper::SetupCrosNetworkConfig() { network_device_handler_ = NetworkDeviceHandler::InitializeForTesting( network_state_helper_.network_state_handler()); cros_network_config_impl_ = std::make_unique<CrosNetworkConfig>( network_state_helper_.network_state_handler(), network_device_handler_.get()); - SetupService(); } -CrosNetworkConfigTestHelper::~CrosNetworkConfigTestHelper() = default; - void CrosNetworkConfigTestHelper::SetupServiceInterface() { DCHECK(connector_); connector_->BindInterface(chromeos::network_config::mojom::kServiceName, @@ -37,9 +52,6 @@ } void CrosNetworkConfigTestHelper::SetupService() { - // Create a local service manager connector to handle requests. - service_manager::mojom::ConnectorRequest request; - connector_ = service_manager::Connector::Create(&request); connector_->OverrideBinderForTesting( service_manager::ServiceFilter::ByName( chromeos::network_config::mojom::kServiceName),
diff --git a/chromeos/services/network_config/public/cpp/cros_network_config_test_helper.h b/chromeos/services/network_config/public/cpp/cros_network_config_test_helper.h index 0f2c356..25121103 100644 --- a/chromeos/services/network_config/public/cpp/cros_network_config_test_helper.h +++ b/chromeos/services/network_config/public/cpp/cros_network_config_test_helper.h
@@ -28,7 +28,11 @@ class CrosNetworkConfigTestHelper { public: + // Default constructor for unit tests. CrosNetworkConfigTestHelper(); + // Constructor used by ash_shell_with_content providing the Shell connector. + explicit CrosNetworkConfigTestHelper(service_manager::Connector* connector); + ~CrosNetworkConfigTestHelper(); // Binds |service_interface_ptr_|. Must be called before using @@ -45,12 +49,13 @@ mojom::CrosNetworkConfig* service_interface_ptr() { return service_interface_ptr_.get(); } - service_manager::Connector* connector() { return connector_.get(); } + service_manager::Connector* connector() { return connector_; } CrosNetworkConfigTestObserver* observer() { return observer_.get(); } void FlushForTesting(); private: + void SetupCrosNetworkConfig(); void SetupService(); void AddBinding(mojo::ScopedMessagePipeHandle handle); @@ -59,8 +64,11 @@ std::unique_ptr<NetworkDeviceHandler> network_device_handler_; std::unique_ptr<CrosNetworkConfig> cros_network_config_impl_; - // Service connector for testing. - std::unique_ptr<service_manager::Connector> connector_; + // Unowned pointer to the service connector. + service_manager::Connector* connector_; + + // Owned connector for unit tests. |connector_| is set to the raw pointer. + std::unique_ptr<service_manager::Connector> owned_connector_; // Interface to |cros_network_config_| through service connector. mojom::CrosNetworkConfigPtr service_interface_ptr_;
diff --git a/components/BUILD.gn b/components/BUILD.gn index 84f29bf..95fb670f 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -140,6 +140,7 @@ "//components/sessions:unit_tests", "//components/signin/core/browser:unit_tests", "//components/signin/core/browser/webdata:unit_tests", + "//components/signin/public/base:unit_tests", "//components/signin/public/identity_manager:unit_tests", "//components/ssl_errors:unit_tests", "//components/subresource_filter/core/browser:unit_tests", @@ -377,6 +378,10 @@ ] } + if (use_dbus) { + deps += [ "//components/dbus/menu:unit_tests" ] + } + # No components should depend on Chrome. assert_no_deps = [ "//chrome/*" ]
diff --git a/components/arc/rotation_lock/arc_rotation_lock_bridge.h b/components/arc/rotation_lock/arc_rotation_lock_bridge.h index 889580c..7f2acfa 100644 --- a/components/arc/rotation_lock/arc_rotation_lock_bridge.h +++ b/components/arc/rotation_lock/arc_rotation_lock_bridge.h
@@ -6,7 +6,7 @@ #define COMPONENTS_ARC_ROTATION_LOCK_ARC_ROTATION_LOCK_BRIDGE_H_ #include "ash/display/screen_orientation_controller.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "base/macros.h" #include "base/threading/thread_checker.h" #include "components/arc/common/rotation_lock.mojom.h"
diff --git a/components/autofill/content/renderer/page_passwords_analyser.cc b/components/autofill/content/renderer/page_passwords_analyser.cc index 91c67ea..98179a65 100644 --- a/components/autofill/content/renderer/page_passwords_analyser.cc +++ b/components/autofill/content/renderer/page_passwords_analyser.cc
@@ -23,6 +23,18 @@ #include "third_party/blink/public/web/web_node.h" #include "third_party/re2/src/re2/re2.h" +using blink::WebDocument; +using blink::WebElement; +using blink::WebElementCollection; +using blink::WebFormControlElement; +using blink::WebFormElement; +using blink::WebInputElement; +using blink::WebLabelElement; +using blink::WebLocalFrame; +using blink::WebNode; +using blink::WebString; +using blink::WebVector; + namespace autofill { namespace { @@ -48,7 +60,7 @@ // during the DOM traversal (e.g. whether it lies within a <form> // element, which is necessary for some of the warnings). struct TraversalInfo { - const blink::WebNode node; + const WebNode node; const bool in_form; }; @@ -56,8 +68,8 @@ // relevant to the Password Manager, which consists of the text and password // inputs in a form, as well as their ordering. struct FormInputCollection { - blink::WebFormElement form; - std::vector<blink::WebFormControlElement> inputs; + WebFormElement form; + std::vector<WebFormControlElement> inputs; std::vector<size_t> text_inputs; std::vector<size_t> password_inputs; std::vector<size_t> explicit_password_inputs; @@ -67,7 +79,7 @@ // username and password fields respectively. This is used to quickly match // against well-known <input> patterns to guess what kind of form we are // dealing with, and provide intelligent autocomplete suggestions. - void AddInput(const blink::WebFormControlElement& input) { + void AddInput(const WebFormControlElement& input) { std::string type( input.HasAttribute("type") ? input.GetAttribute("type").Utf8() : ""); signature += @@ -141,9 +153,8 @@ } // Stores an element's id in |ids| for duplicity-checking. -void TrackElementId( - const blink::WebElement& element, - std::map<std::string, std::vector<blink::WebNode>>* nodes_for_id) { +void TrackElementId(const WebElement& element, + std::map<std::string, std::vector<WebNode>>* nodes_for_id) { if (element.HasAttribute("id")) { std::string id_attr = element.GetAttribute("id").Utf8(); (*nodes_for_id)[id_attr].push_back(element); @@ -156,10 +167,10 @@ // to be rare, and are ignored for the sake of simplicity. // The id of |node| will additionally be added to the corresponding |ids| set. bool TrackElementByRendererIdIfUntracked( - const blink::WebElement& element, + const WebElement& element, const uint32_t renderer_id, std::set<uint32_t>* skip_renderer_ids, - std::map<std::string, std::vector<blink::WebNode>>* nodes_for_id) { + std::map<std::string, std::vector<WebNode>>* nodes_for_id) { if (skip_renderer_ids->count(renderer_id)) return true; skip_renderer_ids->insert(renderer_id); @@ -171,7 +182,7 @@ // duplicate ids, etc. Returns a list of the forms found in the DOM for further // analysis. std::vector<FormInputCollection> ExtractFormsForAnalysis( - const blink::WebDocument& document, + const WebDocument& document, std::set<uint32_t>* skip_form_ids, std::set<uint32_t>* skip_control_ids, PageFormAnalyserLogger* logger) { @@ -179,17 +190,17 @@ // Keep track of inputs that are inside <form> elements to find the complement // for warnings afterwards. - std::set<blink::WebFormControlElement> inputs_with_forms; - std::map<std::string, std::vector<blink::WebNode>> nodes_for_id; + std::set<WebFormControlElement> inputs_with_forms; + std::map<std::string, std::vector<WebNode>> nodes_for_id; - blink::WebVector<blink::WebFormElement> forms; + WebVector<WebFormElement> forms; document.Forms(forms); - for (const blink::WebFormElement& form : forms) { + for (const WebFormElement& form : forms) { form_input_collections.push_back(FormInputCollection{form}); // Collect all the inputs in the form. - blink::WebVector<blink::WebFormControlElement> form_control_elements; + WebVector<WebFormControlElement> form_control_elements; form.GetFormControlElements(form_control_elements); - for (const blink::WebFormControlElement& input : form_control_elements) { + for (const WebFormControlElement& input : form_control_elements) { if (TrackElementByRendererIdIfUntracked( input, input.UniqueRendererFormControlId(), skip_control_ids, &nodes_for_id)) @@ -211,10 +222,12 @@ // Check for password fields that are not contained inside forms. auto password_inputs = document.QuerySelectorAll("input[type=\"password\"]"); for (unsigned i = 0; i < password_inputs.size(); ++i) { + const WebInputElement* input_element = + ToWebInputElement(&password_inputs[i]); + if (!input_element || input_element->IsNull()) + continue; if (TrackElementByRendererIdIfUntracked( - password_inputs[i], - blink::ToWebInputElement(&password_inputs[i]) - ->UniqueRendererFormControlId(), + password_inputs[i], input_element->UniqueRendererFormControlId(), skip_control_ids, &nodes_for_id)) continue; // Any password fields inside <form> elements will have been skipped, @@ -229,21 +242,22 @@ std::string selector = "input:not([type])"; for (const char* text_type : kTypeTextAttributes) selector += ", input[type=\"" + std::string(text_type) + "\"]"; - auto text_inputs = - document.QuerySelectorAll(blink::WebString::FromUTF8(selector)); - for (const blink::WebElement& text_input : text_inputs) + auto text_inputs = document.QuerySelectorAll(WebString::FromUTF8(selector)); + for (const WebElement& text_input : text_inputs) { + const WebInputElement* input_element = ToWebInputElement(&text_input); + if (!input_element || input_element->IsNull()) + continue; TrackElementByRendererIdIfUntracked( - text_input, - blink::ToWebInputElement(&text_input)->UniqueRendererFormControlId(), + text_input, input_element->UniqueRendererFormControlId(), skip_control_ids, &nodes_for_id); - + } // Warn against elements sharing an id attribute. Duplicate id attributes both // are against the HTML specification and can cause issues with password // saving/filling, as the Password Manager makes the assumption that ids may // be used as a unique identifier for nodes. for (const auto& pair : nodes_for_id) { const std::string& id_attr = pair.first; - const std::vector<blink::WebNode>& nodes = pair.second; + const std::vector<WebNode>& nodes = pair.second; if (nodes.size() <= 1) continue; if (!id_attr.empty()) { @@ -270,11 +284,11 @@ // likely to indicate the desired field, and will be prioritised over // other fields. void InferUsernameField( - const blink::WebFormElement& form, - const std::vector<blink::WebFormControlElement>& inputs, + const WebFormElement& form, + const std::vector<WebFormControlElement>& inputs, size_t username_field_guess, std::map<size_t, std::string>* autocomplete_suggestions) { - blink::WebElementCollection labels(form.GetElementsByHTMLTagName("label")); + WebElementCollection labels(form.GetElementsByHTMLTagName("label")); DCHECK(!labels.IsNull()); std::vector<InputHint> input_hints; @@ -283,13 +297,12 @@ input_hints.push_back(InputHint(email_matcher.Pointer())); input_hints.push_back(InputHint(telephone_matcher.Pointer())); - for (blink::WebElement item = labels.FirstItem(); !item.IsNull(); + for (WebElement item = labels.FirstItem(); !item.IsNull(); item = labels.NextItem()) { - blink::WebLabelElement label(item.To<blink::WebLabelElement>()); - blink::WebElement control(label.CorrespondingControl()); + WebLabelElement label(item.To<WebLabelElement>()); + WebElement control(label.CorrespondingControl()); if (!control.IsNull() && control.IsFormControlElement()) { - blink::WebFormControlElement form_control( - control.To<blink::WebFormControlElement>()); + WebFormControlElement form_control(control.To<WebFormControlElement>()); auto found = std::find(inputs.begin(), inputs.end(), form_control); if (found != inputs.end()) { std::string label_content( @@ -342,8 +355,8 @@ // autocomplete attributes, or missing username fields, etc.). void AnalyseForm(const FormInputCollection& form_input_collection, PageFormAnalyserLogger* logger) { - const blink::WebFormElement& form = form_input_collection.form; - const std::vector<blink::WebFormControlElement>& inputs = + const WebFormElement& form = form_input_collection.form; + const std::vector<WebFormControlElement>& inputs = form_input_collection.inputs; const std::vector<size_t>& text_inputs = form_input_collection.text_inputs; const std::vector<size_t>& explicit_password_inputs = @@ -437,11 +450,11 @@ skip_form_element_renderer_ids_.clear(); } -void PagePasswordsAnalyser::AnalyseDocumentDOM(blink::WebLocalFrame* frame, +void PagePasswordsAnalyser::AnalyseDocumentDOM(WebLocalFrame* frame, PageFormAnalyserLogger* logger) { DCHECK(frame); - blink::WebDocument document(frame->GetDocument()); + WebDocument document(frame->GetDocument()); // Extract all the forms from the DOM, and provide relevant warnings. std::vector<FormInputCollection> forms( ExtractFormsForAnalysis(document, &skip_form_element_renderer_ids_, @@ -456,7 +469,7 @@ logger->Flush(); } -void PagePasswordsAnalyser::AnalyseDocumentDOM(blink::WebLocalFrame* frame) { +void PagePasswordsAnalyser::AnalyseDocumentDOM(WebLocalFrame* frame) { PageFormAnalyserLogger logger(frame); AnalyseDocumentDOM(frame, &logger); }
diff --git a/components/autofill/content/renderer/password_form_conversion_utils.cc b/components/autofill/content/renderer/password_form_conversion_utils.cc index baf455cb..4cf26f3e 100644 --- a/components/autofill/content/renderer/password_form_conversion_utils.cc +++ b/components/autofill/content/renderer/password_form_conversion_utils.cc
@@ -769,16 +769,16 @@ } } - // Populate |other_possible_usernames| in |password_form|. - ValueElementVector other_possible_usernames; + // Populate |all_possible_usernames| in |password_form|. + ValueElementVector all_possible_usernames; for (const FormFieldData* plausible_username : plausible_usernames) { if (plausible_username == username_field) continue; auto pair = MakePossibleUsernamePair(plausible_username); if (!pair.first.empty()) - other_possible_usernames.push_back(std::move(pair)); + all_possible_usernames.push_back(std::move(pair)); } - password_form->other_possible_usernames = std::move(other_possible_usernames); + password_form->all_possible_usernames = std::move(all_possible_usernames); password_form->origin = std::move(form_origin); password_form->signon_realm = GetSignOnRealm(password_form->origin);
diff --git a/components/autofill/content/renderer/password_form_conversion_utils_browsertest.cc b/components/autofill/content/renderer/password_form_conversion_utils_browsertest.cc index 67bd03c..53988a9 100644 --- a/components/autofill/content/renderer/password_form_conversion_utils_browsertest.cc +++ b/components/autofill/content/renderer/password_form_conversion_utils_browsertest.cc
@@ -750,7 +750,7 @@ const char* autocomplete[3]; const char* expected_username_element; const char* expected_username_value; - const char* expected_other_possible_usernames; + const char* expected_all_possible_usernames; } cases[] = { // When no elements are marked with autocomplete='username', the text-type // input field before the first password element should get selected as @@ -761,7 +761,7 @@ "John+usrname1, Smith+usrname3"}, // When a sole element is marked with autocomplete='username', it should // be treated as the username, but other text fields should be added to - // |other_possible_usernames|. + // |all_possible_usernames|. {{"username", nullptr, nullptr}, "usrname1", "John", @@ -775,7 +775,7 @@ "Smith", "John+usrname1, William+usrname2"}, // When >=2 elements have the attribute, the first should be selected as - // the username, and the rest should go to |other_possible_usernames|. + // the username, and the rest should go to |all_possible_usernames|. {{"username", "username", nullptr}, "usrname1", "John", @@ -821,7 +821,7 @@ << (nonempty_username_fields ? "nonempty" : "empty")); // Repeat each test once with empty, and once with non-empty usernames. - // In the former case, no empty other_possible_usernames should be saved. + // In the former case, no empty all_possible_usernames should be saved. const char* names[3]; if (nonempty_username_fields) { names[0] = "John"; @@ -851,12 +851,12 @@ if (nonempty_username_fields) { EXPECT_EQ(base::UTF8ToUTF16(cases[i].expected_username_value), password_form->username_value); - EXPECT_EQ(base::UTF8ToUTF16(cases[i].expected_other_possible_usernames), - ValueElementVectorToString( - password_form->other_possible_usernames)); + EXPECT_EQ( + base::UTF8ToUTF16(cases[i].expected_all_possible_usernames), + ValueElementVectorToString(password_form->all_possible_usernames)); } else { EXPECT_TRUE(password_form->username_value.empty()); - EXPECT_TRUE(password_form->other_possible_usernames.empty()); + EXPECT_TRUE(password_form->all_possible_usernames.empty()); } // Do a basic sanity check that we are still having a password field. @@ -921,7 +921,7 @@ EXPECT_EQ(base::UTF8ToUTF16("usrname1"), password_form->username_element); EXPECT_EQ(base::UTF8ToUTF16("William"), password_form->username_value); EXPECT_THAT( - password_form->other_possible_usernames, + password_form->all_possible_usernames, testing::ElementsAre(ValueElementPair(base::UTF8ToUTF16("Smith"), base::UTF8ToUTF16("usrname2")))); } @@ -991,7 +991,7 @@ EXPECT_EQ(base::UTF8ToUTF16("usrname1"), password_form->username_element); EXPECT_EQ(base::UTF8ToUTF16("William"), password_form->username_value); EXPECT_THAT( - password_form->other_possible_usernames, + password_form->all_possible_usernames, testing::ElementsAre(ValueElementPair(base::UTF8ToUTF16("Smith"), base::UTF8ToUTF16("usrname2")))); } @@ -1350,12 +1350,12 @@ password_form->username_value); if (strcmp(cases[i].expected_username_value, "William") == 0) { EXPECT_THAT( - password_form->other_possible_usernames, + password_form->all_possible_usernames, testing::ElementsAre(ValueElementPair( base::UTF8ToUTF16("Smith"), base::UTF8ToUTF16("usrname2")))); } else { EXPECT_THAT( - password_form->other_possible_usernames, + password_form->all_possible_usernames, testing::ElementsAre(ValueElementPair( base::UTF8ToUTF16("William"), base::UTF8ToUTF16("usrname1")))); }
diff --git a/components/autofill/core/browser/BUILD.gn b/components/autofill/core/browser/BUILD.gn index 21d6b0b3..39eeaed0 100644 --- a/components/autofill/core/browser/BUILD.gn +++ b/components/autofill/core/browser/BUILD.gn
@@ -331,7 +331,7 @@ "//components/os_crypt", "//components/pref_registry", "//components/prefs", - "//components/signin/core/browser:shared", + "//components/signin/public/base", "//components/signin/public/identity_manager", "//components/strings", "//components/sync", @@ -509,6 +509,7 @@ "autofill_experiments_unittest.cc", "autofill_external_delegate_unittest.cc", "autofill_ie_toolbar_import_win_unittest.cc", + "autofill_internals_logging_unittest.cc", "autofill_manager_unittest.cc", "autofill_merge_unittest.cc", "autofill_metrics_unittest.cc",
diff --git a/components/autofill/core/browser/autofill_and_password_manager_internals/autofill_and_password_manager_internals.css b/components/autofill/core/browser/autofill_and_password_manager_internals/autofill_and_password_manager_internals.css index c6c649ae..2df889c0 100644 --- a/components/autofill/core/browser/autofill_and_password_manager_internals/autofill_and_password_manager_internals.css +++ b/components/autofill/core/browser/autofill_and_password_manager_internals/autofill_and_password_manager_internals.css
@@ -28,3 +28,35 @@ [data-incognito=true] #logging-note-incognito { display: block; } + +/* + * Colors can be taken from + * https://material.io/design/color/#tools-for-picking-colors + * Pick the rows of entries labeled with 100 + */ + +.log-entry[scope='Context'] { + background-color: #F5F5F5; +} + +.log-entry[scope='Parsing'] { + background-color: #FFCDD2; +} + +.log-entry[scope='Filling'] { + background-color: #D1C4E9; +} + +.log-entry[scope='Submission'] { + background-color: #BBDEFB; +} + +.form { + padding: 3px; + margin: 3px; + border: 1px black solid; +} + +.form td { + vertical-align: text-top; +}
diff --git a/components/autofill/core/browser/autofill_and_password_manager_internals/autofill_and_password_manager_internals.js b/components/autofill/core/browser/autofill_and_password_manager_internals/autofill_and_password_manager_internals.js index b84cdde..23203db 100644 --- a/components/autofill/core/browser/autofill_and_password_manager_internals/autofill_and_password_manager_internals.js +++ b/components/autofill/core/browser/autofill_and_password_manager_internals/autofill_and_password_manager_internals.js
@@ -13,6 +13,43 @@ logDiv.appendChild(textDiv); } +// Converts an internal representation of nodes to actual DOM nodes that can +// be attached to the DOM. The internal representation has the following +// properties for each node: +// - type: 'node' | 'text' +// - value: name of tag | text content +// - children (opt): list of child nodes +// - attributes (opt): dictionary of name/value pairs +function nodeToDomNode(node) { + if (node.type === 'text') { + return document.createTextNode(node.value); + } + // Else the node is of type 'node'. + var domNode = document.createElement(node.value); + if ('children' in node) { + node.children.forEach((child) => { + domNode.appendChild(nodeToDomNode(child)); + }); + } + if ('attributes' in node) { + for (var attribute in node.attributes) { + domNode.setAttribute(attribute, node.attributes[attribute]); + } + } + return domNode; +} + +// TODO(crbug.com/928595) Rename this to "addStructuredLog". Punting on this +// to simplify an existing CL that shall be merged. +function addRawLog(node) { + const logDiv = $('log-entries'); + if (!logDiv) { + return; + } + logDiv.appendChild(document.createElement('hr')); + logDiv.appendChild(nodeToDomNode(node)); +} + function setUpAutofillInternals() { document.title = "Autofill Internals"; document.getElementById("h1-title").innerHTML = "Autofill Internals"; @@ -36,4 +73,4 @@ function notifyAboutIncognito(isIncognito) { document.body.dataset.incognito = isIncognito; -} \ No newline at end of file +}
diff --git a/components/autofill/core/browser/autofill_external_delegate.cc b/components/autofill/core/browser/autofill_external_delegate.cc index 039d71f..de417bf8 100644 --- a/components/autofill/core/browser/autofill_external_delegate.cc +++ b/components/autofill/core/browser/autofill_external_delegate.cc
@@ -24,7 +24,7 @@ #include "components/autofill/core/browser/ui/popup_item_ids.h" #include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_util.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/strings/grit/components_strings.h" #include "ui/accessibility/platform/ax_platform_node.h" #include "ui/base/l10n/l10n_util.h"
diff --git a/components/autofill/core/browser/autofill_internals_logging.cc b/components/autofill/core/browser/autofill_internals_logging.cc index fcf6bea..cb309e4 100644 --- a/components/autofill/core/browser/autofill_internals_logging.cc +++ b/components/autofill/core/browser/autofill_internals_logging.cc
@@ -6,10 +6,187 @@ #include <string> +#include "base/logging.h" #include "base/no_destructor.h" +#include "base/strings/strcat.h" +#include "base/strings/utf_string_conversions.h" +#include "net/base/escape.h" namespace autofill { +namespace { + +void AppendChildToLastNode(std::vector<base::Value>* buffer, + base::Value&& new_child) { + if (buffer->empty()) { + buffer->push_back(std::move(new_child)); + return; + } + + base::Value& parent = buffer->back(); + + if (auto* children = parent.FindListKey("children")) { + children->GetList().push_back(std::move(new_child)); + return; + } + + base::Value::ListStorage list; + list.emplace_back(std::move(new_child)); + parent.SetKey("children", base::Value(std::move(list))); +} + +} // namespace + +AutofillInternalsBuffer::AutofillInternalsBuffer() = default; +AutofillInternalsBuffer::AutofillInternalsBuffer( + AutofillInternalsBuffer&& other) noexcept = default; +AutofillInternalsBuffer::~AutofillInternalsBuffer() = default; + +base::Value AutofillInternalsBuffer::RetrieveResult() { + if (buffer_.empty()) + return base::Value(); + + // Close not-yet-closed tags. + while (buffer_.size() > 1) + *this << CTag{}; + + return std::exchange(buffer_.back(), base::Value()); +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, Tag&& tag) { + if (!buf.active()) + return buf; + + base::Value::DictStorage storage; + storage.try_emplace("type", std::make_unique<base::Value>("node")); + storage.try_emplace("value", + std::make_unique<base::Value>(std::move(tag.name))); + buf.buffer_.emplace_back(std::move(storage)); + return buf; +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, CTag&& tag) { + if (!buf.active()) + return buf; + // Don't close the very first opened tag. It stays and gets returned in the + // end. + if (buf.buffer_.size() <= 1) + return buf; + + base::Value node_to_add = std::move(buf.buffer_.back()); + buf.buffer_.pop_back(); + + AppendChildToLastNode(&buf.buffer_, std::move(node_to_add)); + return buf; +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + Attrib&& attrib) { + if (!buf.active()) + return buf; + + base::Value& node = buf.buffer_.back(); + + if (auto* attributes = node.FindDictKey("attributes")) { + attributes->SetKey(std::move(attrib.name), + base::Value(std::move(attrib.value))); + } else { + base::Value::DictStorage dict; + dict.try_emplace(std::move(attrib.name), + std::make_unique<base::Value>(std::move(attrib.value))); + node.SetKey("attributes", base::Value(std::move(dict))); + } + + return buf; +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, Br&& tag) { + if (!buf.active()) + return buf; + return buf << Tag{"br"} << CTag{}; +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + base::StringPiece text) { + if (!buf.active()) + return buf; + + base::Value::DictStorage storage; + storage.try_emplace("type", std::make_unique<base::Value>("text")); + storage.try_emplace("value", + std::make_unique<base::Value>(net::EscapeForHTML(text))); + base::Value node_to_add(std::move(storage)); + AppendChildToLastNode(&buf.buffer_, std::move(node_to_add)); + return buf; +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + base::StringPiece16 text) { + return buf << base::UTF16ToUTF8(text); +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + AutofillInternalsBuffer&& buffer) { + if (!buf.active()) + return buf; + + base::Value node_to_add(buffer.RetrieveResult()); + if (node_to_add.is_none()) + return buf; + AppendChildToLastNode(&buf.buffer_, std::move(node_to_add)); + return buf; +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + LoggingScope scope) { + if (!buf.active()) + return buf; + return buf << Tag{"div"} << Attrib{"scope", LoggingScopeToString(scope)} + << Attrib{"class", "log-entry"}; +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + LogMessage message) { + if (!buf.active()) + return buf; + return buf << Tag{"div"} << Attrib{"message", LogMessageToString(message)} + << Attrib{"class", "log-message"} << LogMessageValue(message); +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + const GURL& url) { + if (!buf.active()) + return buf; + if (!url.is_valid()) + return buf << "Invalid URL"; + return buf << net::EscapeForHTML(url.GetOrigin().spec()); +} + +// Implementation of AutofillInternalsMessage. + +AutofillInternalsMessage::AutofillInternalsMessage(Destination destination) + : destination_(destination) { + if (destination_ == Destination::kAutofillInternals) + buffer_.set_active(IsLogAutofillInternalsActive()); +} + +AutofillInternalsMessage::~AutofillInternalsMessage() { + base::Value message = buffer_.RetrieveResult(); + if (message.is_none()) + return; + + switch (destination_) { + case Destination::kAutofillInternals: + AutofillInternalsLogging::LogRaw(std::move(message)); + break; + case Destination::kPasswordManagerInternals: + LOG(ERROR) << "Not implemented, logging to password manager internals"; + break; + } +} + +// Implementation of AutofillInternalsLogging. + AutofillInternalsLogging::AutofillInternalsLogging() = default; AutofillInternalsLogging::~AutofillInternalsLogging() = default; @@ -24,10 +201,22 @@ GetAutofillInternalLogging().swap(logger); } -void AutofillInternalsLogging::Log(const std::string& message) { - if (GetAutofillInternalLogging()) { - GetAutofillInternalLogging()->LogHelper(base::Value(message)); - } +// static +void AutofillInternalsLogging::Log(std::string message) { + if (GetAutofillInternalLogging()) + GetAutofillInternalLogging()->LogHelper(base::Value(std::move(message))); +} + +// static +void AutofillInternalsLogging::LogRaw(base::Value&& message) { + if (GetAutofillInternalLogging()) + GetAutofillInternalLogging()->LogRawHelper(std::move(message)); +} + +// Implementation of other methods. + +bool IsLogAutofillInternalsActive() { + return !!GetAutofillInternalLogging(); } } // namespace autofill
diff --git a/components/autofill/core/browser/autofill_internals_logging.h b/components/autofill/core/browser/autofill_internals_logging.h index 23787d2..bad1313 100644 --- a/components/autofill/core/browser/autofill_internals_logging.h +++ b/components/autofill/core/browser/autofill_internals_logging.h
@@ -6,27 +6,267 @@ #define COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_INTERNALS_LOGGING_H_ #include <string> +#include <type_traits> +#include <vector> #include "base/macros.h" +#include "base/strings/string16.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_piece.h" #include "base/values.h" +#include "components/autofill/core/common/autofill_internals/log_message.h" +#include "components/autofill/core/common/autofill_internals/logging_scope.h" +#include "url/gurl.h" + +// +// Autofill Internals Logging +// -------------------------- +// This framework serves the purpose of exposing log messages of Chrome Autofill +// (and in the future also Chrome's Password Manager) via +// chrome://autofill-internals (and in the future also +// chrome://password-manager-internals). +// +// The framework uses a so called LoggingScope as a mechanism to indicate during +// which phase of processing a website a message was generated. Logging scopes +// comprise for example the phase of parsing forms, or filling forms. Each +// logging scope is displayed in a visually distinct color. +// +// The framework also uses predefined LogMessages. Each message consists of a +// fixed label and a string. The labels allow for specialized styling (e.g. +// highlighting specific messages because they indicate failures). +// +// The desired pattern to generate log messages is to pass a scope, a log +// message and then parameters. +// +// LOG_AF_INTERNALS << LoggingScope::kSomeScope << LogMessage::kSomeLogMessage +// << Br{} << more << Br{} << parameters; +// +// Extra parameters can be: +// +// - numeric: +// LOG_AF_INTERNALS << ... << 42; +// +// - inline strings: +// LOG_AF_INTERNALS << ... << "foobar"; +// +// - tags: +// LOG_AF_INTERNALS << Tag{"div"} << ... << CTag{}; +// Note that tags need to be closed (even for <br> - use Br{} as it takes care +// of generating an opening and closing tag). You may optionally specify what +// tag is closed: CTag{"div"}. +// Tags can get attributes via Attrib: +// LOG_AF_INTERNALS << Tag{"div"} << Attrib{"class", "foobar"}... << CTag{}; +// +// - objects that can have an overloaded operator: +// AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, +// const SampleObject& value) {...} +// LOG_AF_INTERNALS << ... << my_sample_object; +// +// - complex messages that require for loops: +// AutofillInternalsBuffer buffer; +// for (...) { buffer << something; } +// LOG_AF_INTERNALS << std::move(buffer); +// +// Note that each call of LOG_AF_INTERNALS spawns a new log entry. +// +// See components/autofill/core/common/autofill_internals/logging_scope.h for +// the definition of scopes. +// See components/autofill/core/common/autofill_internals/log_message.h for +// the definition of messages. namespace autofill { +// Tag of HTML Element (e.g. <div> would be represented by Tag{"div"}). Note +// that every element needs to be closed with a CTag{}. +struct Tag { + std::string name; +}; + +// The closing tag of an HTML Element. +struct CTag { + CTag() = default; + // |opt_name| is not used, and only exists for readability. + explicit CTag(base::StringPiece opt_name) {} +}; + +// Attribute of an HTML Tag (e.g. class="foo" would be represented by +// Attrib{"class", "foo"}. +struct Attrib { + std::string name; + std::string value; +}; + +// An <br> HTML tag, note that this does not need to be closed. +struct Br {}; + +// A table row containing two cells. This generates +// <tr><td>%1</td><td>%2</td></tr> +template <typename T1, typename T2> +struct Tr2Cells { + T1 cell1; + T2 cell2; +}; + +// Helper function to create Tr2Cells entries w/o specifying the type names. +template <typename T1, typename T2> +Tr2Cells<T1, T2> MakeTr2Cells(T1&& cell1, T2&& cell2) { + return Tr2Cells<T1, T2>{std::forward<T1>(cell1), std::forward<T2>(cell2)}; +} + +// A buffer into which you can stream values. See the top of this header file +// for samples. +class AutofillInternalsBuffer { + public: + AutofillInternalsBuffer(); + AutofillInternalsBuffer(AutofillInternalsBuffer&& other) noexcept; + ~AutofillInternalsBuffer(); + + // Returns the contents of the buffer and empties it. + base::Value RetrieveResult(); + + // Returns whether an active WebUI is listening. If false, the buffer may + // not do any logging. + bool active() const { return active_; } + void set_active(bool active) { active_ = active; } + + private: + friend AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + Tag&& tag); + friend AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + CTag&& tag); + friend AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + Attrib&& attrib); + friend AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + base::StringPiece text); + friend AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + AutofillInternalsBuffer&& buffer); + + // The stack of values being constructed. Each item is a dictionary with the + // following attributes: + // - type: 'node' | 'text' + // - value: name of tag | text content + // - children (opt): list of child nodes + // - attributes (opt): dictionary of name/value pairs + // The |buffer_| serves as a stack where the last element is being + // constructed. Once it is read (i.e. closed via a CTag), it is popped from + // the stack and attached as a child of the previously second last element. + std::vector<base::Value> buffer_; + + bool active_ = true; + + DISALLOW_COPY_AND_ASSIGN(AutofillInternalsBuffer); +}; + +// Enable streaming numbers of all types. +template <typename T, + typename = std::enable_if_t<std::is_arithmetic<T>::value, T>> +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, T number) { + return buf << base::NumberToString(number); +} + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, Tag&& tag); + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, CTag&& tag); + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + Attrib&& attrib); + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, Br&& tag); + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + base::StringPiece text); + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + base::StringPiece16 text); + +// Sometimes you may want to fill a buffer that you then stream as a whole +// to LOG_AF_INTERNALS, which commits the data to chrome://autofill-internals: +// +// AutofillInternalsBuffer buffer; +// for (FormStructure* form : forms) +// buffer << *form; +// LOG_AF_INTERNALS << LoggingScope::kParsing << std::move(buffer); +// +// It would not be possible to report all |forms| into a single log entry +// without this. +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + AutofillInternalsBuffer&& buffer); + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + LoggingScope scope); + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + LogMessage message); + +// Streams only the security origin of the URL. This is done for privacy +// reasons. +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + const GURL& url); + +template <typename T1, typename T2> +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + Tr2Cells<T1, T2>&& row) { + return buf << Tag{"tr"} << Tag{"td"} << std::move(row.cell1) << CTag{} + << Tag{"td"} << std::move(row.cell2) << CTag{} << CTag{}; +} + +// A container for a AutofillInternalsBuffer that submits the buffer to the +// corresponding internals page on destruction. +class AutofillInternalsMessage { + public: + // Whether the message will be sent to chrome://autofill-internals or + // chrome://password-manager-internals. + enum class Destination { + kAutofillInternals, + kPasswordManagerInternals, + }; + + explicit AutofillInternalsMessage(Destination destination); + ~AutofillInternalsMessage(); + + AutofillInternalsBuffer& buffer() { return buffer_; } + + private: + Destination destination_; + AutofillInternalsBuffer buffer_; + DISALLOW_COPY_AND_ASSIGN(AutofillInternalsMessage); +}; + +// Class that forwards log messages to the WebUI for display. class AutofillInternalsLogging { public: AutofillInternalsLogging(); virtual ~AutofillInternalsLogging(); // Main API function that is called when something is logged. - static void Log(const std::string& message); + static void Log(std::string message); static void SetAutofillInternalsLogger( std::unique_ptr<AutofillInternalsLogging> logger); private: + static void LogRaw(base::Value&& message); virtual void LogHelper(const base::Value& message) = 0; + virtual void LogRawHelper(const base::Value& message) = 0; + + // Grant access to LogRaw(). + friend class AutofillInternalsMessage; + + DISALLOW_COPY_AND_ASSIGN(AutofillInternalsLogging); }; +bool IsLogAutofillInternalsActive(); + +#define LOG_AF_INTERNALS \ + AutofillInternalsMessage( \ + AutofillInternalsMessage::Destination::kAutofillInternals) \ + .buffer() + +#define LOG_PWMGR_INTERNALS \ + AutofillInternalsMessage( \ + AutofillInternalsMessage::Destination::kPasswordManagerInternals) \ + .buffer() + } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_INTERNALS_LOGGING_H_
diff --git a/components/autofill/core/browser/autofill_internals_logging_unittest.cc b/components/autofill/core/browser/autofill_internals_logging_unittest.cc new file mode 100644 index 0000000..7a8a3bf --- /dev/null +++ b/components/autofill/core/browser/autofill_internals_logging_unittest.cc
@@ -0,0 +1,204 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/autofill/core/browser/autofill_internals_logging.h" + +#include "base/json/json_writer.h" +#include "base/strings/string_piece.h" +#include "base/strings/utf_string_conversions.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest-death-test.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace autofill { + +TEST(AutofillInternalsBuffer, EscapeStrings) { + AutofillInternalsBuffer buffer; + buffer << "<foo><!--\""; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"type":"text","value":"<foo><!--""})", json); +} + +TEST(AutofillInternalsBuffer, EscapeUtf16Strings) { + AutofillInternalsBuffer buffer; + buffer << base::ASCIIToUTF16("<foo><!--\""); + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"type":"text","value":"<foo><!--""})", json); +} + +TEST(AutofillInternalsBuffer, SupportNumbers) { + AutofillInternalsBuffer buffer; + buffer << 42; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"type":"text","value":"42"})", json); +} + +TEST(AutofillInternalsBuffer, SanitizeURLs) { + AutofillInternalsBuffer buffer; + buffer << GURL("https://user:pw@www.example.com:80/foo?bar=1#foo"); + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + // Verify that the url gets scrubbed. + EXPECT_EQ(R"({"type":"text","value":"https://www.example.com:80/"})", json); +} + +TEST(AutofillInternalsBuffer, Empty) { + AutofillInternalsBuffer buffer; + EXPECT_EQ(base::Value(), buffer.RetrieveResult()); +} + +TEST(AutofillInternalsBuffer, UnclosedTag) { + AutofillInternalsBuffer buffer; + buffer << Tag{"foo"}; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"type":"node","value":"foo"})", json); +} + +TEST(AutofillInternalsBuffer, ClosedTag) { + AutofillInternalsBuffer buffer; + buffer << Tag{"foo"} << CTag{}; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"type":"node","value":"foo"})", json); +} + +TEST(AutofillInternalsBuffer, NestedTag) { + AutofillInternalsBuffer buffer; + buffer << Tag{"foo"} << Tag{"bar"} << CTag{} << CTag{}; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"children":[{"type":"node","value":"bar"}],)" + R"("type":"node","value":"foo"})", + json); +} + +TEST(AutofillInternalsBuffer, NestedTagClosingTooOften) { + AutofillInternalsBuffer buffer; + buffer << Tag{"foo"} << Tag{"bar"} << CTag{} << CTag{} << CTag{}; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"children":[{"type":"node","value":"bar"}],)" + R"("type":"node","value":"foo"})", + json); +} + +TEST(AutofillInternalsBuffer, NestedTagClosingNotAtAll) { + AutofillInternalsBuffer buffer; + buffer << Tag{"foo"} << Tag{"bar"}; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"children":[{"type":"node","value":"bar"}],)" + R"("type":"node","value":"foo"})", + json); +} + +TEST(AutofillInternalsBuffer, NestedTagWithAttributes) { + AutofillInternalsBuffer buffer; + buffer << Tag{"foo"} << Tag{"bar"} << Attrib{"b1", "1"} << Attrib{"b2", "2"} + << CTag{} << Attrib{"f1", "1"}; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"attributes":{"f1":"1"},"children":[)" + R"({"attributes":{"b1":"1","b2":"2"},"type":"node","value":"bar"})" + R"(],"type":"node","value":"foo"})", + json); +} + +TEST(AutofillInternalsBuffer, DivWithBr) { + AutofillInternalsBuffer buffer; + buffer << Tag{"div"} << "foo" << Br{} << "bar" << CTag{}; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"children":[{"type":"text","value":"foo"},)" + R"({"type":"node","value":"br"},{"type":"text","value":"bar"}],)" + R"("type":"node","value":"div"})", + json); +} + +TEST(AutofillInternalsBuffer, Scope) { + AutofillInternalsBuffer buffer; + buffer << LoggingScope::kContext; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"attributes":{"class":"log-entry","scope":"Context"},)" + R"("type":"node","value":"div"})", + json); +} + +TEST(AutofillInternalsBuffer, Message) { + AutofillInternalsBuffer buffer; + buffer << LogMessage::kParsedForms; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ(R"({"attributes":{"class":"log-message","message":"ParsedForms"},)" + R"("children":[{"type":"text","value":"Parsed forms:"}],)" + R"("type":"node","value":"div"})", + json); +} + +struct SampleObject { + int x; + std::string y; +}; + +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buf, + const SampleObject& value) { + buf << Tag{"table"}; + buf << Tag{"tr"} << Tag{"td"} << "x" << CTag{"td"} << Tag{"td"} << value.x + << CTag{"td"} << CTag{"tr"}; + buf << Tag{"tr"} << Tag{"td"} << "y" << CTag{"td"} << Tag{"td"} << value.y + << CTag{"td"} << CTag{"tr"}; + buf << CTag{"table"}; + return buf; +} + +TEST(AutofillInternalsBuffer, CanStreamCustomObjects) { + AutofillInternalsBuffer buffer; + SampleObject o{42, "foobar<!--"}; + buffer << o; + std::string json; + EXPECT_TRUE(base::JSONWriter::Write(buffer.RetrieveResult(), &json)); + EXPECT_EQ( + R"({"children":[)" // table + /**/ R"({"children":[)" // tr + /****/ R"({"children":[{"type":"text","value":"x"}],)" // td + /******/ R"("type":"node","value":"td"},)" + /****/ R"({"children":[{"type":"text","value":"42"}],)" // td + /******/ R"("type":"node","value":"td"}],)" + /****/ R"("type":"node","value":"tr"},)" // continuation of tr + /**/ R"({"children":[)" // tr + /****/ R"({"children":[{"type":"text","value":"y"}],)" + /******/ R"("type":"node","value":"td"},)" + /****/ R"({"children":[{"type":"text","value":"foobar<!--"}],)" + /******/ R"("type":"node","value":"td"}],)" + /**/ R"("type":"node","value":"tr"}],"type":"node","value":"table"})", + json); +} + +class MockAutofillInternalsLogging : public AutofillInternalsLogging { + public: + MOCK_METHOD1(LogHelper, void(const base::Value&)); + MOCK_METHOD1(LogRawHelper, void(const base::Value&)); +}; + +// Don't add further tests to this. AutofillInternalsLogging uses a global +// pointer to the AutofillInternalsLogging instance and if more tests are +// executed in parallel, these can interfere. +TEST(AutofillInternalsMessage, VerifySubmissionOnDestruction) { + AutofillInternalsBuffer buffer; + buffer << LoggingScope::kContext; + base::Value expected = buffer.RetrieveResult(); + + auto logging = std::make_unique<MockAutofillInternalsLogging>(); + EXPECT_CALL(*logging, LogRawHelper(testing::Eq(testing::ByRef(expected)))); + AutofillInternalsLogging::SetAutofillInternalsLogger(std::move(logging)); + LOG_AF_INTERNALS << LoggingScope::kContext; + AutofillInternalsLogging::SetAutofillInternalsLogger(nullptr); +} + +} // namespace autofill
diff --git a/components/autofill/core/browser/autofill_manager.cc b/components/autofill/core/browser/autofill_manager.cc index a2f720d..bbcd79b4 100644 --- a/components/autofill/core/browser/autofill_manager.cc +++ b/components/autofill/core/browser/autofill_manager.cc
@@ -41,6 +41,7 @@ #include "components/autofill/core/browser/autofill_data_util.h" #include "components/autofill/core/browser/autofill_external_delegate.h" #include "components/autofill/core/browser/autofill_field.h" +#include "components/autofill/core/browser/autofill_internals_logging.h" #include "components/autofill/core/browser/autofill_manager_test_delegate.h" #include "components/autofill/core/browser/autofill_metrics.h" #include "components/autofill/core/browser/autofill_type.h" @@ -236,6 +237,19 @@ return false; } +void LogAutofillTypePredictionsAvailable( + const std::vector<FormStructure*>& forms) { + if (!IsLogAutofillInternalsActive()) + return; + + AutofillInternalsBuffer buffer; + for (FormStructure* form : forms) + buffer << *form; + + LOG_AF_INTERNALS << LoggingScope::kParsing << LogMessage::kParsedForms + << std::move(buffer); +} + } // namespace AutofillManager::FillingContext::FillingContext() = default; @@ -1164,6 +1178,8 @@ // Send field type predictions to the renderer so that it can possibly // annotate forms with the predicted types or add console warnings. driver()->SendAutofillTypePredictionsToRenderer(queried_forms); + + LogAutofillTypePredictionsAvailable(queried_forms); } void AutofillManager::OnCreditCardFetched(bool did_succeed, @@ -1742,6 +1758,8 @@ // queryable forms will be updated once the field type query is complete. driver()->SendAutofillTypePredictionsToRenderer(non_queryable_forms); driver()->SendAutofillTypePredictionsToRenderer(queryable_forms); + LogAutofillTypePredictionsAvailable(non_queryable_forms); + LogAutofillTypePredictionsAvailable(queryable_forms); // Query the server if at least one of the forms was parsed. if (!queryable_forms.empty() && download_manager_) {
diff --git a/components/autofill/core/browser/form_structure.cc b/components/autofill/core/browser/form_structure.cc index 5507589..020fd9f 100644 --- a/components/autofill/core/browser/form_structure.cc +++ b/components/autofill/core/browser/form_structure.cc
@@ -20,6 +20,7 @@ #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" +#include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" @@ -28,6 +29,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "components/autofill/core/browser/autofill_data_util.h" +#include "components/autofill/core/browser/autofill_internals_logging.h" #include "components/autofill/core/browser/autofill_metrics.h" #include "components/autofill/core/browser/autofill_type.h" #include "components/autofill/core/browser/field_types.h" @@ -2158,4 +2160,42 @@ } } +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buffer, + const FormStructure& form) { + buffer << Tag{"div"} << Attrib{"class", "form"}; + buffer << Tag{"table"}; + buffer << MakeTr2Cells("Form signature:", form.form_signature()); + buffer << MakeTr2Cells("Form name:", form.form_name()); + buffer << MakeTr2Cells("Target URL:", form.target_url()); + for (size_t i = 0; i < form.field_count(); ++i) { + buffer << Tag{"tr"}; + buffer << Tag{"td"} << "Field " << i << ": " << CTag{}; + const AutofillField* field = form.field(i); + buffer << Tag{"td"}; + buffer << Tag{"table"}; + buffer << MakeTr2Cells("Signature:", field->GetFieldSignature()); + buffer << MakeTr2Cells("Name:", field->parseable_name()); + + auto type = field->Type().ToString(); + auto heuristic_type = AutofillType(field->heuristic_type()).ToString(); + auto server_type = AutofillType(field->server_type()).ToString(); + + buffer << MakeTr2Cells("Type:", + base::StrCat({type, " (heuristic: ", heuristic_type, + ", server: ", server_type, ")"})); + buffer << MakeTr2Cells("Section:", field->section); + + constexpr size_t kMaxLabelSize = 100; + const base::string16 truncated_label = + field->label.substr(0, std::min(field->label.length(), kMaxLabelSize)); + buffer << MakeTr2Cells("Label:", truncated_label); + buffer << CTag{"table"}; + buffer << CTag{"td"}; + buffer << CTag{"tr"}; + } + buffer << CTag{"table"}; + buffer << CTag{"div"}; + return buffer; +} + } // namespace autofill
diff --git a/components/autofill/core/browser/form_structure.h b/components/autofill/core/browser/form_structure.h index 296c1f3..63c5916 100644 --- a/components/autofill/core/browser/form_structure.h +++ b/components/autofill/core/browser/form_structure.h
@@ -38,6 +38,8 @@ namespace autofill { +class AutofillInternalsBuffer; + // Password attributes (whether a password has special symbols, numeric, etc.) enum class PasswordAttribute { kHasLowercaseLetter, @@ -628,6 +630,9 @@ DISALLOW_COPY_AND_ASSIGN(FormStructure); }; +AutofillInternalsBuffer& operator<<(AutofillInternalsBuffer& buffer, + const FormStructure& form); + } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_FORM_STRUCTURE_H_
diff --git a/components/autofill/core/browser/payments/account_info_getter.h b/components/autofill/core/browser/payments/account_info_getter.h index 42bf2fe3..8e91ad1 100644 --- a/components/autofill/core/browser/payments/account_info_getter.h +++ b/components/autofill/core/browser/payments/account_info_getter.h
@@ -7,7 +7,7 @@ #include <string> -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" namespace autofill {
diff --git a/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.cc b/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.cc index 4d62c34..f978f1d 100644 --- a/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.cc +++ b/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.cc
@@ -14,6 +14,7 @@ #include "components/autofill/core/browser/payments/legal_message_line.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/grit/components_scaled_resources.h" #include "components/infobars/core/infobar.h" @@ -145,17 +146,29 @@ LogUserAction(AutofillMetrics::INFOBAR_DENIED); } +bool AutofillSaveCardInfoBarDelegateMobile::Cancel() { + RunSaveCardPromptCallbackWithUserDecision(AutofillClient::DECLINED); + LogUserAction(AutofillMetrics::INFOBAR_DENIED); + return true; +} + int AutofillSaveCardInfoBarDelegateMobile::GetButtons() const { - return BUTTON_OK; + if (base::FeatureList::IsEnabled(features::kAutofillSaveCardShowNoThanks)) { + return BUTTON_OK | BUTTON_CANCEL; + } else { + return BUTTON_OK; + } } base::string16 AutofillSaveCardInfoBarDelegateMobile::GetButtonLabel( InfoBarButton button) const { - if (button != BUTTON_OK) { + if (button != BUTTON_OK && button != BUTTON_CANCEL) { NOTREACHED() << "Unsupported button label requested."; return base::string16(); } - + if (button == BUTTON_CANCEL) { + return l10n_util::GetStringUTF16(IDS_NO_THANKS); + } // Requesting name or expiration date from the user makes the save prompt a // 2-step fix flow. return options_.should_request_name_from_user ||
diff --git a/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.h b/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.h index 62742f8..bd7e72e 100644 --- a/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.h +++ b/components/autofill/core/browser/payments/autofill_save_card_infobar_delegate_mobile.h
@@ -72,6 +72,7 @@ int GetButtons() const override; base::string16 GetButtonLabel(InfoBarButton button) const override; bool Accept() override; + bool Cancel() override; private: // Runs the appropriate local or upload save callback with the given
diff --git a/components/autofill/core/browser/personal_data_manager.h b/components/autofill/core/browser/personal_data_manager.h index 4a7e94b..d5be83b2 100644 --- a/components/autofill/core/browser/personal_data_manager.h +++ b/components/autofill/core/browser/personal_data_manager.h
@@ -36,7 +36,7 @@ #include "components/keyed_service/core/keyed_service.h" #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_member.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/sync/driver/sync_service_observer.h" #include "components/webdata/common/web_data_service_consumer.h"
diff --git a/components/autofill/core/browser/test_personal_data_manager.h b/components/autofill/core/browser/test_personal_data_manager.h index 6f7be17..688fe7fc 100644 --- a/components/autofill/core/browser/test_personal_data_manager.h +++ b/components/autofill/core/browser/test_personal_data_manager.h
@@ -12,7 +12,7 @@ #include "components/autofill/core/browser/data_model/credit_card.h" #include "components/autofill/core/browser/payments/payments_customer_data.h" #include "components/autofill/core/browser/personal_data_manager.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" namespace autofill {
diff --git a/components/autofill/core/browser/ui/payments/DEPS b/components/autofill/core/browser/ui/payments/DEPS index ed07b2d..04111f6 100644 --- a/components/autofill/core/browser/ui/payments/DEPS +++ b/components/autofill/core/browser/ui/payments/DEPS
@@ -1,5 +1,5 @@ specific_include_rules = { "save_card_bubble_controller\.h": [ - "+components/signin/core/browser/account_info.h", + "+components/signin/public/identity_manager/account_info.h", ] }
diff --git a/components/autofill/core/browser/ui/payments/save_card_bubble_controller.h b/components/autofill/core/browser/ui/payments/save_card_bubble_controller.h index 03c1c1b..fe735b6e 100644 --- a/components/autofill/core/browser/ui/payments/save_card_bubble_controller.h +++ b/components/autofill/core/browser/ui/payments/save_card_bubble_controller.h
@@ -13,7 +13,7 @@ #include "components/autofill/core/browser/autofill_client.h" #include "components/autofill/core/browser/payments/legal_message_line.h" #include "components/autofill/core/browser/sync_utils.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "url/gurl.h" class Profile;
diff --git a/components/autofill/core/common/BUILD.gn b/components/autofill/core/common/BUILD.gn index 17b0348..0bb58c9 100644 --- a/components/autofill/core/common/BUILD.gn +++ b/components/autofill/core/common/BUILD.gn
@@ -13,6 +13,10 @@ "autofill_data_validation.h", "autofill_features.cc", "autofill_features.h", + "autofill_internals/log_message.cc", + "autofill_internals/log_message.h", + "autofill_internals/logging_scope.cc", + "autofill_internals/logging_scope.h", "autofill_l10n_util.cc", "autofill_l10n_util.h", "autofill_payments_features.cc",
diff --git a/components/autofill/core/common/autofill_internals/log_message.cc b/components/autofill/core/common/autofill_internals/log_message.cc new file mode 100644 index 0000000..450258c6 --- /dev/null +++ b/components/autofill/core/common/autofill_internals/log_message.cc
@@ -0,0 +1,53 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/autofill/core/common/autofill_internals/log_message.h" + +#include "base/logging.h" + +namespace autofill { + +const char* LogMessageToString(LogMessage message) { + // Define template to generate case-statements: +#define AUTOFILL_TEMPLATE(NAME, STRING) \ + case LogMessage::k##NAME: \ + return #NAME; + + // The actual implementation of this function. + switch (message) { + AUTOFILL_LOG_MESSAGE_TEMPLATES(AUTOFILL_TEMPLATE) + case LogMessage::kLastMessage: + return ""; + // No default here to cover all cases. + } + + // Clean up. +#undef AUTOFILL_TEMPLATE + + NOTREACHED(); + return ""; +} + +const char* LogMessageValue(LogMessage message) { + // Define template to generate case-statements: +#define AUTOFILL_TEMPLATE(NAME, STRING) \ + case LogMessage::k##NAME: \ + return STRING; + + // The actual implementation of this function. + switch (message) { + AUTOFILL_LOG_MESSAGE_TEMPLATES(AUTOFILL_TEMPLATE) + case LogMessage::kLastMessage: + return ""; + // No default here to cover all cases. + } + + // Clean up. +#undef AUTOFILL_TEMPLATE + + NOTREACHED(); + return ""; +} + +} // namespace autofill
diff --git a/components/autofill/core/common/autofill_internals/log_message.h b/components/autofill/core/common/autofill_internals/log_message.h new file mode 100644 index 0000000..828420fb --- /dev/null +++ b/components/autofill/core/common/autofill_internals/log_message.h
@@ -0,0 +1,31 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_AUTOFILL_CORE_COMMON_AUTOFILL_INTERNALS_LOG_MESSAGE_H_ +#define COMPONENTS_AUTOFILL_CORE_COMMON_AUTOFILL_INTERNALS_LOG_MESSAGE_H_ + +namespace autofill { + +/////////////// Log Messages ///////////// + +// Generator for log message. If you need to find the call site for a log +// message, take the first parameter (e.g. ParsedForms) and search for +// that name prefixed with a k (e.g. kParsedForms) in code search. +#define AUTOFILL_LOG_MESSAGE_TEMPLATES(T) T(ParsedForms, "Parsed forms:") + +// Log messages for chrome://autofill-internals. +#define AUTOFILL_TEMPLATE(NAME, MESSAGE) k##NAME, +enum class LogMessage { + AUTOFILL_LOG_MESSAGE_TEMPLATES(AUTOFILL_TEMPLATE) kLastMessage +}; +#undef AUTOFILL_TEMPLATE + +// Returns the enum value of |message| as a string (without the leading k). +const char* LogMessageToString(LogMessage message); +// Returns the actual string to be presented to the user for |message|. +const char* LogMessageValue(LogMessage message); + +} // namespace autofill + +#endif // COMPONENTS_AUTOFILL_CORE_COMMON_AUTOFILL_INTERNALS_LOG_MESSAGE_H_
diff --git a/components/autofill/core/common/autofill_internals/logging_scope.cc b/components/autofill/core/common/autofill_internals/logging_scope.cc new file mode 100644 index 0000000..ab962d5 --- /dev/null +++ b/components/autofill/core/common/autofill_internals/logging_scope.cc
@@ -0,0 +1,32 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/autofill/core/common/autofill_internals/logging_scope.h" + +#include "base/logging.h" + +namespace autofill { + +const char* LoggingScopeToString(LoggingScope scope) { + // Define template to generate case-statements: +#define AUTOFILL_TEMPLATE(NAME) \ + case LoggingScope::k##NAME: \ + return #NAME; + + // The actual implementation of this function. + switch (scope) { + AUTOFILL_LOGGING_SCOPE_TEMPLATES(AUTOFILL_TEMPLATE) + case LoggingScope::kLastScope: + return ""; + // No default here to cover all cases. + } + + // Clean up. +#undef AUTOFILL_TEMPLATE + + NOTREACHED(); + return ""; +} + +} // namespace autofill
diff --git a/components/autofill/core/common/autofill_internals/logging_scope.h b/components/autofill/core/common/autofill_internals/logging_scope.h new file mode 100644 index 0000000..53ded12 --- /dev/null +++ b/components/autofill/core/common/autofill_internals/logging_scope.h
@@ -0,0 +1,36 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_AUTOFILL_CORE_COMMON_AUTOFILL_INTERNALS_LOGGING_SCOPE_H_ +#define COMPONENTS_AUTOFILL_CORE_COMMON_AUTOFILL_INTERNALS_LOGGING_SCOPE_H_ + +namespace autofill { + +/////////////// Logging Scopes ///////////// + +// Generator for source code related to logging scopes. Pass a template T which +// takes a single parameter, the name of the logging scope. +#define AUTOFILL_LOGGING_SCOPE_TEMPLATES(T) \ + /* Information about the sync status, existence of profiles, etc. */ \ + T(Context) \ + /* Log messages related to the discovery and parsing of forms. */ \ + T(Parsing) \ + /* Log messages related to filling of forms. */ \ + T(Filling) \ + /* Log messages related to the submission of forms. */ \ + T(Submission) + +// Define a bunch of logging scopes: kContext, kParsing, ... +#define AUTOFILL_TEMPLATE(NAME) k##NAME, +enum class LoggingScope { + AUTOFILL_LOGGING_SCOPE_TEMPLATES(AUTOFILL_TEMPLATE) kLastScope +}; +#undef AUTOFILL_TEMPLATE + +// Returns the enum value of |scope| as a string (without the leading k). +const char* LoggingScopeToString(LoggingScope scope); + +} // namespace autofill + +#endif // COMPONENTS_AUTOFILL_CORE_COMMON_AUTOFILL_INTERNALS_LOGGING_SCOPE_H_
diff --git a/components/autofill/core/common/autofill_payments_features.cc b/components/autofill/core/common/autofill_payments_features.cc index 696b94b..1c08af9 100644 --- a/components/autofill/core/common/autofill_payments_features.cc +++ b/components/autofill/core/common/autofill_payments_features.cc
@@ -105,6 +105,13 @@ const base::Feature kAutofillSaveCardImprovedUserConsent{ "AutofillSaveCardImprovedUserConsent", base::FEATURE_DISABLED_BY_DEFAULT}; +// When enabled, local and upload credit card save dialogs will add a +// [No thanks] cancel button option. This is intended to bring the +// AutofillSaveCardImprovedUserConsent functionality to Chrome OS, Android, and +// iOS without bringing the extended title string change with it. +const base::Feature kAutofillSaveCardShowNoThanks{ + "AutofillSaveCardShowNoThanks", base::FEATURE_DISABLED_BY_DEFAULT}; + // Controls what title and bubble label for the credit card upload bubble are // shown to users. const base::Feature kAutofillSaveCreditCardUsesImprovedMessaging{
diff --git a/components/autofill/core/common/autofill_payments_features.h b/components/autofill/core/common/autofill_payments_features.h index 084e1cd7..69b3ef0d 100644 --- a/components/autofill/core/common/autofill_payments_features.h +++ b/components/autofill/core/common/autofill_payments_features.h
@@ -33,6 +33,7 @@ extern const base::Feature kAutofillNoLocalSaveOnUnmaskSuccess; extern const base::Feature kAutofillNoLocalSaveOnUploadSuccess; extern const base::Feature kAutofillSaveCardImprovedUserConsent; +extern const base::Feature kAutofillSaveCardShowNoThanks; extern const base::Feature kAutofillSaveCreditCardUsesImprovedMessaging; extern const base::Feature kAutofillSendExperimentIdsInPaymentsRPCs; extern const base::Feature kAutofillUpstream;
diff --git a/components/autofill/core/common/mojom/autofill_types.mojom b/components/autofill/core/common/mojom/autofill_types.mojom index 6091a04..eeb4d233 100644 --- a/components/autofill/core/common/mojom/autofill_types.mojom +++ b/components/autofill/core/common/mojom/autofill_types.mojom
@@ -272,7 +272,7 @@ mojo_base.mojom.String16 username_element; bool username_marked_by_site; mojo_base.mojom.String16 username_value; - array<ValueElementPair> other_possible_usernames; + array<ValueElementPair> all_possible_usernames; array<ValueElementPair> all_possible_passwords; bool form_has_autofilled_value; mojo_base.mojom.String16 password_element;
diff --git a/components/autofill/core/common/mojom/autofill_types_struct_traits.cc b/components/autofill/core/common/mojom/autofill_types_struct_traits.cc index 90c3d50..992cd1e 100644 --- a/components/autofill/core/common/mojom/autofill_types_struct_traits.cc +++ b/components/autofill/core/common/mojom/autofill_types_struct_traits.cc
@@ -245,7 +245,7 @@ out->username_marked_by_site = data.username_marked_by_site(); if (!data.ReadUsernameValue(&out->username_value) || - !data.ReadOtherPossibleUsernames(&out->other_possible_usernames) || + !data.ReadAllPossibleUsernames(&out->all_possible_usernames) || !data.ReadAllPossiblePasswords(&out->all_possible_passwords) || !data.ReadPasswordElement(&out->password_element) || !data.ReadPasswordValue(&out->password_value))
diff --git a/components/autofill/core/common/mojom/autofill_types_struct_traits.h b/components/autofill/core/common/mojom/autofill_types_struct_traits.h index 249b3c929..cc857943 100644 --- a/components/autofill/core/common/mojom/autofill_types_struct_traits.h +++ b/components/autofill/core/common/mojom/autofill_types_struct_traits.h
@@ -453,9 +453,9 @@ return r.username_value; } - static const std::vector<autofill::ValueElementPair>& - other_possible_usernames(const autofill::PasswordForm& r) { - return r.other_possible_usernames; + static const std::vector<autofill::ValueElementPair>& all_possible_usernames( + const autofill::PasswordForm& r) { + return r.all_possible_usernames; } static const std::vector<autofill::ValueElementPair>& all_possible_passwords(
diff --git a/components/autofill/core/common/mojom/autofill_types_struct_traits_unittest.cc b/components/autofill/core/common/mojom/autofill_types_struct_traits_unittest.cc index 3fa3da3..7dec3980 100644 --- a/components/autofill/core/common/mojom/autofill_types_struct_traits_unittest.cc +++ b/components/autofill/core/common/mojom/autofill_types_struct_traits_unittest.cc
@@ -74,9 +74,9 @@ form->username_element = base::ASCIIToUTF16("username"); form->username_marked_by_site = true; form->username_value = base::ASCIIToUTF16("test@gmail.com"); - form->other_possible_usernames.push_back(ValueElementPair( + form->all_possible_usernames.push_back(ValueElementPair( base::ASCIIToUTF16("Jerry_1"), base::ASCIIToUTF16("id1"))); - form->other_possible_usernames.push_back(ValueElementPair( + form->all_possible_usernames.push_back(ValueElementPair( base::ASCIIToUTF16("Jerry_2"), base::ASCIIToUTF16("id2"))); form->all_possible_passwords.push_back( ValueElementPair(base::ASCIIToUTF16("pass1"), base::ASCIIToUTF16("el1")));
diff --git a/components/autofill/core/common/password_form.cc b/components/autofill/core/common/password_form.cc index 421aecf..e5562e3 100644 --- a/components/autofill/core/common/password_form.cc +++ b/components/autofill/core/common/password_form.cc
@@ -57,8 +57,8 @@ form.confirmation_password_element); target->SetInteger("confirmation_password_element_renderer_id", form.confirmation_password_element_renderer_id); - target->SetString("other_possible_usernames", - ValueElementVectorToString(form.other_possible_usernames)); + target->SetString("all_possible_usernames", + ValueElementVectorToString(form.all_possible_usernames)); target->SetString("all_possible_passwords", ValueElementVectorToString(form.all_possible_passwords)); target->SetBoolean("blacklisted", form.blacklisted_by_user); @@ -127,7 +127,7 @@ username_element_renderer_id == form.username_element_renderer_id && username_marked_by_site == form.username_marked_by_site && username_value == form.username_value && - other_possible_usernames == form.other_possible_usernames && + all_possible_usernames == form.all_possible_usernames && all_possible_passwords == form.all_possible_passwords && form_has_autofilled_value == form.form_has_autofilled_value && password_element == form.password_element &&
diff --git a/components/autofill/core/common/password_form.h b/components/autofill/core/common/password_form.h index f67af1d..60e14d43 100644 --- a/components/autofill/core/common/password_form.h +++ b/components/autofill/core/common/password_form.h
@@ -146,9 +146,7 @@ // This member is populated in cases where we there are multiple input // elements that could possibly be the username. Used when our heuristics for // determining the username are incorrect. Optional. - // - // When parsing an HTML form, this is typically empty. - ValueElementVector other_possible_usernames; + ValueElementVector all_possible_usernames; // This member is populated in cases where we there are multiple possible // password values. Used in pending password state, to populate a dropdown
diff --git a/components/autofill_assistant/browser/DEPS b/components/autofill_assistant/browser/DEPS index 11ea8bf..b272266ed 100644 --- a/components/autofill_assistant/browser/DEPS +++ b/components/autofill_assistant/browser/DEPS
@@ -11,6 +11,8 @@ "+services/network/public/cpp", "+third_party/blink/public/mojom/payments/payment_request.mojom.h", "+third_party/icu/source/common/unicode", + "+third_party/libaddressinput/chromium/addressinput_util.h", + "+third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h", "+third_party/re2", "+ui/base/l10n/l10n_util.h", "+ui/events/keycodes/dom",
diff --git a/components/autofill_assistant/browser/actions/get_payment_information_action.cc b/components/autofill_assistant/browser/actions/get_payment_information_action.cc index 4a80d64..1e766d6 100644 --- a/components/autofill_assistant/browser/actions/get_payment_information_action.cc +++ b/components/autofill_assistant/browser/actions/get_payment_information_action.cc
@@ -7,18 +7,22 @@ #include <algorithm> #include <utility> +#include "base/android/locale_utils.h" #include "base/bind.h" #include "base/callback.h" #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/browser/autofill_data_util.h" #include "components/autofill/core/browser/data_model/autofill_profile.h" #include "components/autofill/core/browser/data_model/credit_card.h" -#include "components/autofill/core/browser/personal_data_manager.h" +#include "components/autofill/core/browser/geo/address_i18n.h" #include "components/autofill_assistant/browser/actions/action_delegate.h" #include "components/autofill_assistant/browser/client_memory.h" +#include "components/autofill_assistant/browser/metrics.h" #include "components/autofill_assistant/browser/service.pb.h" #include "components/strings/grit/components_strings.h" #include "third_party/blink/public/mojom/payments/payment_request.mojom.h" +#include "third_party/libaddressinput/chromium/addressinput_util.h" +#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h" #include "ui/base/l10n/l10n_util.h" namespace autofill_assistant { @@ -30,7 +34,13 @@ DCHECK(proto_.has_get_payment_information()); } -GetPaymentInformationAction::~GetPaymentInformationAction() {} +GetPaymentInformationAction::~GetPaymentInformationAction() { + // Report UMA histograms. + if (presented_to_user_) { + Metrics::RecordPaymentRequestPrefilledSuccess(initially_prefilled, + action_successful_); + } +} void GetPaymentInformationAction::InternalProcessAction( ProcessActionCallback callback) { @@ -79,6 +89,12 @@ payment_options->initial_terms_and_conditions = REQUIRES_REVIEW; break; } + // Gather info for UMA histograms. + if (!presented_to_user_) { + presented_to_user_ = true; + initially_prefilled = IsInitialAutofillDataComplete( + delegate_->GetPersonalDataManager(), *payment_options); + } payment_options->callback = base::BindOnce(&GetPaymentInformationAction::OnGetPaymentInformation, @@ -164,7 +180,113 @@ } UpdateProcessedAction(succeed ? ACTION_APPLIED : PAYMENT_REQUEST_ERROR); + action_successful_ = succeed; std::move(callback).Run(std::move(processed_action_proto_)); } +bool GetPaymentInformationAction::IsInitialAutofillDataComplete( + autofill::PersonalDataManager* personal_data_manager, + const PaymentRequestOptions& payment_options) const { + bool request_contact = payment_options.request_payer_name || + payment_options.request_payer_email || + payment_options.request_payer_phone; + if (request_contact || payment_options.request_shipping) { + auto profiles = personal_data_manager->GetProfiles(); + if (request_contact) { + auto completeContactIter = + std::find_if(profiles.begin(), profiles.end(), + [&payment_options](const auto& profile) { + return IsCompleteContact(profile, payment_options); + }); + if (completeContactIter == profiles.end()) { + return false; + } + } + + if (payment_options.request_shipping) { + auto completeAddressIter = + std::find_if(profiles.begin(), profiles.end(), + [&payment_options](const auto& profile) { + return IsCompleteAddress(profile, payment_options); + }); + if (completeAddressIter == profiles.end()) { + return false; + } + } + } + + if (payment_options.request_payment_method) { + auto credit_cards = personal_data_manager->GetCreditCards(); + auto completeCardIter = std::find_if( + credit_cards.begin(), credit_cards.end(), + [&payment_options](const auto& credit_card) { + return IsCompleteCreditCard(credit_card, payment_options); + }); + if (completeCardIter == credit_cards.end()) { + return false; + } + } + return true; +} + +bool GetPaymentInformationAction::IsCompleteContact( + const autofill::AutofillProfile* profile, + const PaymentRequestOptions& payment_options) { + if (payment_options.request_payer_name && + profile->GetRawInfo(autofill::NAME_FULL).empty()) { + return false; + } + + if (payment_options.request_payer_email && + profile->GetRawInfo(autofill::EMAIL_ADDRESS).empty()) { + return false; + } + + if (payment_options.request_payer_phone && + profile->GetRawInfo(autofill::PHONE_HOME_WHOLE_NUMBER).empty()) { + return false; + } + return true; +} + +bool GetPaymentInformationAction::IsCompleteAddress( + const autofill::AutofillProfile* profile, + const PaymentRequestOptions& payment_options) { + if (!payment_options.request_shipping) { + return true; + } + + auto address_data = autofill::i18n::CreateAddressDataFromAutofillProfile( + *profile, base::android::GetDefaultLocaleString()); + return autofill::addressinput::HasAllRequiredFields(*address_data); +} + +bool GetPaymentInformationAction::IsCompleteCreditCard( + const autofill::CreditCard* credit_card, + const PaymentRequestOptions& payment_options) { + if (credit_card->record_type() != autofill::CreditCard::MASKED_SERVER_CARD && + !credit_card->HasValidCardNumber()) { + // Can't check validity of masked server card numbers because they are + // incomplete until decrypted. + return false; + } + + if (!credit_card->HasValidExpirationDate() || + credit_card->billing_address_id().empty()) { + return false; + } + + std::string basic_card_network = + autofill::data_util::GetPaymentRequestData(credit_card->network()) + .basic_card_issuer_network; + if (!payment_options.supported_basic_card_networks.empty() && + std::find(payment_options.supported_basic_card_networks.begin(), + payment_options.supported_basic_card_networks.end(), + basic_card_network) == + payment_options.supported_basic_card_networks.end()) { + return false; + } + return true; +} + } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/actions/get_payment_information_action.h b/components/autofill_assistant/browser/actions/get_payment_information_action.h index ef6afab7..8c66e4d0 100644 --- a/components/autofill_assistant/browser/actions/get_payment_information_action.h +++ b/components/autofill_assistant/browser/actions/get_payment_information_action.h
@@ -11,6 +11,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill_assistant/browser/actions/action.h" #include "components/autofill_assistant/browser/payment_request.h" @@ -31,6 +32,20 @@ ProcessActionCallback callback, std::unique_ptr<PaymentInformation> payment_information); + bool IsInitialAutofillDataComplete( + autofill::PersonalDataManager* personal_data_manager, + const PaymentRequestOptions& payment_options) const; + static bool IsCompleteContact(const autofill::AutofillProfile* profile, + const PaymentRequestOptions& payment_options); + static bool IsCompleteAddress(const autofill::AutofillProfile* profile, + const PaymentRequestOptions& payment_options); + static bool IsCompleteCreditCard( + const autofill::CreditCard* credit_card, + const PaymentRequestOptions& payment_options); + + bool presented_to_user_ = false; + bool initially_prefilled = false; + bool action_successful_ = false; base::WeakPtrFactory<GetPaymentInformationAction> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(GetPaymentInformationAction);
diff --git a/components/autofill_assistant/browser/controller.cc b/components/autofill_assistant/browser/controller.cc index 361ae15..cfc8a4c8 100644 --- a/components/autofill_assistant/browser/controller.cc +++ b/components/autofill_assistant/browser/controller.cc
@@ -507,7 +507,7 @@ if (!result) { DVLOG(1) << "Failed to get assistant scripts for " << script_domain_; OnFatalError(l10n_util::GetStringUTF8(IDS_AUTOFILL_ASSISTANT_DEFAULT_ERROR), - Metrics::GET_SCRIPTS_FAILED); + Metrics::DropOutReason::GET_SCRIPTS_FAILED); return; } @@ -516,7 +516,7 @@ DVLOG(2) << __func__ << " from " << script_domain_ << " returned " << "unparseable response"; OnFatalError(l10n_util::GetStringUTF8(IDS_AUTOFILL_ASSISTANT_DEFAULT_ERROR), - Metrics::GET_SCRIPTS_UNPARSABLE); + Metrics::DropOutReason::GET_SCRIPTS_UNPARSABLE); return; } if (response_proto.has_client_settings()) @@ -585,7 +585,7 @@ if (!result.success) { DVLOG(1) << "Failed to execute script " << script_path; OnFatalError(l10n_util::GetStringUTF8(IDS_AUTOFILL_ASSISTANT_DEFAULT_ERROR), - Metrics::SCRIPT_FAILED); + Metrics::DropOutReason::SCRIPT_FAILED); return; } @@ -595,16 +595,16 @@ switch (result.at_end) { case ScriptExecutor::SHUTDOWN: - client_->Shutdown(Metrics::SCRIPT_SHUTDOWN); + client_->Shutdown(Metrics::DropOutReason::SCRIPT_SHUTDOWN); return; case ScriptExecutor::SHUTDOWN_GRACEFULLY: EnterStoppedState(); - client_->Shutdown(Metrics::SCRIPT_SHUTDOWN); + client_->Shutdown(Metrics::DropOutReason::SCRIPT_SHUTDOWN); return; case ScriptExecutor::CLOSE_CUSTOM_TAB: - client_->Shutdown(Metrics::CUSTOM_TAB_CLOSED); + client_->Shutdown(Metrics::DropOutReason::CUSTOM_TAB_CLOSED); return; case ScriptExecutor::RESTART: @@ -922,14 +922,14 @@ // any scripts or didn't get scripts that could possibly become runnable // with a DOM change. OnFatalError(l10n_util::GetStringUTF8(IDS_AUTOFILL_ASSISTANT_DEFAULT_ERROR), - Metrics::NO_INITIAL_SCRIPTS); + Metrics::DropOutReason::NO_INITIAL_SCRIPTS); return; } // We're navigated to a page that has no scripts or the scripts have reached a // state from which they cannot recover through a DOM change. OnFatalError(l10n_util::GetStringUTF8(IDS_AUTOFILL_ASSISTANT_GIVE_UP), - Metrics::NO_SCRIPTS); + Metrics::DropOutReason::NO_SCRIPTS); } void Controller::OnRunnableScriptsChanged( @@ -984,7 +984,7 @@ } void Controller::DidAttachInterstitialPage() { - client_->Shutdown(Metrics::INTERSTITIAL_PAGE); + client_->Shutdown(Metrics::DropOutReason::INTERSTITIAL_PAGE); } void Controller::DidFinishLoad(content::RenderFrameHost* render_frame_host, @@ -1025,7 +1025,7 @@ !navigation_handle->WasServerRedirect() && !navigation_handle->IsRendererInitiated()) { OnFatalError(l10n_util::GetStringUTF8(IDS_AUTOFILL_ASSISTANT_GIVE_UP), - Metrics::NAVIGATION); + Metrics::DropOutReason::NAVIGATION); } } @@ -1055,7 +1055,7 @@ } void Controller::RenderProcessGone(base::TerminationStatus status) { - client_->Shutdown(Metrics::RENDER_PROCESS_GONE); + client_->Shutdown(Metrics::DropOutReason::RENDER_PROCESS_GONE); } void Controller::OnWebContentsFocused(
diff --git a/components/autofill_assistant/browser/controller_unittest.cc b/components/autofill_assistant/browser/controller_unittest.cc index 57c6bec..119d6f4 100644 --- a/components/autofill_assistant/browser/controller_unittest.cc +++ b/components/autofill_assistant/browser/controller_unittest.cc
@@ -475,12 +475,13 @@ ASSERT_THAT(controller_->GetUserActions(), SizeIs(1)); testing::InSequence seq; - EXPECT_CALL(fake_client_, Shutdown(Metrics::SCRIPT_SHUTDOWN)); + EXPECT_CALL(fake_client_, Shutdown(Metrics::DropOutReason::SCRIPT_SHUTDOWN)); EXPECT_TRUE(controller_->PerformUserAction(0)); // Simulates Client::Shutdown(SCRIPT_SHUTDOWN) - EXPECT_CALL(mock_ui_controller_, WillShutdown(Metrics::SCRIPT_SHUTDOWN)); - controller_->WillShutdown(Metrics::SCRIPT_SHUTDOWN); + EXPECT_CALL(mock_ui_controller_, + WillShutdown(Metrics::DropOutReason::SCRIPT_SHUTDOWN)); + controller_->WillShutdown(Metrics::DropOutReason::SCRIPT_SHUTDOWN); } TEST_F(ControllerTest, Reset) { @@ -657,7 +658,7 @@ EXPECT_CALL(fake_client_, ShowUI()); SimulateWebContentsFocused(); // must call ShowUI - controller_->OnFatalError("test", Metrics::TAB_CHANGED); + controller_->OnFatalError("test", Metrics::DropOutReason::TAB_CHANGED); SimulateWebContentsFocused(); // must not call ShowUI }
diff --git a/components/autofill_assistant/browser/metrics.cc b/components/autofill_assistant/browser/metrics.cc index 4be484a..3c01152f 100644 --- a/components/autofill_assistant/browser/metrics.cc +++ b/components/autofill_assistant/browser/metrics.cc
@@ -4,18 +4,40 @@ #include "components/autofill_assistant/browser/metrics.h" -#include "base/metrics/histogram_macros.h" +#include "base/metrics/histogram_functions.h" namespace autofill_assistant { namespace { -const char* const kDropOutEnumName = "Android.AutofillAssistant.DropOutReason"; +const char kDropOutEnumName[] = "Android.AutofillAssistant.DropOutReason"; +const char kPaymentRequestPrefilledName[] = + "Android.AutofillAssistant.PaymentRequest.Prefilled"; } // namespace // static void Metrics::RecordDropOut(DropOutReason reason) { - DCHECK_LE(reason, DropOutReason::NUM_ENTRIES); - UMA_HISTOGRAM_ENUMERATION(kDropOutEnumName, reason, NUM_ENTRIES); + DCHECK_LE(reason, DropOutReason::kMaxValue); + base::UmaHistogramEnumeration(kDropOutEnumName, reason); +} + +// static +void Metrics::RecordPaymentRequestPrefilledSuccess(bool initially_complete, + bool success) { + if (initially_complete && success) { + base::UmaHistogramEnumeration(kPaymentRequestPrefilledName, + PaymentRequestPrefilled::PREFILLED_SUCCESS); + } else if (initially_complete && !success) { + base::UmaHistogramEnumeration(kPaymentRequestPrefilledName, + PaymentRequestPrefilled::PREFILLED_FAILURE); + } else if (!initially_complete && success) { + base::UmaHistogramEnumeration( + kPaymentRequestPrefilledName, + PaymentRequestPrefilled::NOTPREFILLED_SUCCESS); + } else if (!initially_complete && !success) { + base::UmaHistogramEnumeration( + kPaymentRequestPrefilledName, + PaymentRequestPrefilled::NOTPREFILLED_FAILURE); + } } } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/metrics.h b/components/autofill_assistant/browser/metrics.h index fa5608a..01093da6 100644 --- a/components/autofill_assistant/browser/metrics.h +++ b/components/autofill_assistant/browser/metrics.h
@@ -19,10 +19,10 @@ // GENERATED_JAVA_CLASS_NAME_OVERRIDE: DropOutReason // // This enum is used in histograms, do not remove/renumber entries. Only add - // at the end just before NUM_ENTRIES. Also remember to update the + // at the end and update kMaxValue. Also remember to update the // AutofillAssistantDropOutReason enum listing in // tools/metrics/histograms/enums.xml. - enum DropOutReason { + enum class DropOutReason { AA_START = 0, AUTOSTART_TIMEOUT = 1, NO_SCRIPTS = 2, @@ -45,7 +45,7 @@ NO_INITIAL_SCRIPTS = 19, DFM_INSTALL_FAILED = 20, - NUM_ENTRIES = 21, + kMaxValue = DFM_INSTALL_FAILED }; // The different ways that autofill assistant can stop. @@ -55,19 +55,38 @@ // GENERATED_JAVA_CLASS_NAME_OVERRIDE: OnBoarding // // This enum is used in histograms, do not remove/renumber entries. Only add - // at the end just before OB_NUM_ENTRIES. Also remember to update the + // at the end and update kMaxValue. Also remember to update the // AutofillAssistantOnBoarding enum listing in // tools/metrics/histograms/enums.xml. - enum OnBoarding { + enum class OnBoarding { OB_SHOWN = 0, OB_NOT_SHOWN = 1, OB_ACCEPTED = 2, OB_CANCELLED = 3, - OB_NUM_ENTRIES = 4, + kMaxValue = OB_CANCELLED + }; + + // The different ways for payment request to succeed or fail, broken down by + // whether the PR initially presented to the user was completely pre-filled + // or not. + // + // This enum is used in histograms, do not remove/renumber entries. Only add + // at the end and update kMaxValue. Also remember to update the + // AutofillAssistantPaymentRequestPrefilled enum listing in + // tools/metrics/histograms/enums.xml. + enum class PaymentRequestPrefilled { + PREFILLED_SUCCESS = 0, + NOTPREFILLED_SUCCESS = 1, + PREFILLED_FAILURE = 2, + NOTPREFILLED_FAILURE = 3, + + kMaxValue = NOTPREFILLED_FAILURE }; static void RecordDropOut(DropOutReason reason); + static void RecordPaymentRequestPrefilledSuccess(bool initially_complete, + bool success); // Intended for debugging: writes string representation of |reason| to |out|. friend std::ostream& operator<<(std::ostream& out, @@ -79,80 +98,72 @@ #else // Debugging builds write a string representation of |reason|. switch (reason) { - case AA_START: + case DropOutReason::AA_START: out << "AA_START"; break; - case AUTOSTART_TIMEOUT: + case DropOutReason::AUTOSTART_TIMEOUT: out << "AUTOSTART_TIMEOUT"; break; - case NO_SCRIPTS: + case DropOutReason::NO_SCRIPTS: out << "NO_SCRIPTS"; break; - case CUSTOM_TAB_CLOSED: + case DropOutReason::CUSTOM_TAB_CLOSED: out << "CUSTOM_TAB_CLOSED"; break; - case DECLINED: + case DropOutReason::DECLINED: out << "DECLINED"; break; - case SHEET_CLOSED: + case DropOutReason::SHEET_CLOSED: out << "SHEET_CLOSED"; break; - case SCRIPT_FAILED: + case DropOutReason::SCRIPT_FAILED: out << "SCRIPT_FAILED"; break; - case NAVIGATION: + case DropOutReason::NAVIGATION: out << "NAVIGATION"; break; - case OVERLAY_STOP: + case DropOutReason::OVERLAY_STOP: out << "OVERLAY_STOP"; break; - case PR_FAILED: + case DropOutReason::PR_FAILED: out << "PR_FAILED"; break; - case CONTENT_DESTROYED: + case DropOutReason::CONTENT_DESTROYED: out << "CONTENT_DESTROYED"; break; - case RENDER_PROCESS_GONE: + case DropOutReason::RENDER_PROCESS_GONE: out << "RENDER_PROCESS_GONE"; break; - case INTERSTITIAL_PAGE: + case DropOutReason::INTERSTITIAL_PAGE: out << "INTERSTITIAL_PAGE"; break; - case SCRIPT_SHUTDOWN: + case DropOutReason::SCRIPT_SHUTDOWN: out << "SCRIPT_SHUTDOWN"; break; - case SAFETY_NET_TERMINATE: + case DropOutReason::SAFETY_NET_TERMINATE: out << "SAFETY_NET_TERMINATE"; break; - case TAB_DETACHED: + case DropOutReason::TAB_DETACHED: out << "TAB_DETACHED"; break; - case TAB_CHANGED: + case DropOutReason::TAB_CHANGED: out << "TAB_CHANGED"; break; - - case NUM_ENTRIES: - out << "NUM_ENTRIES"; - break; - - case GET_SCRIPTS_FAILED: + case DropOutReason::GET_SCRIPTS_FAILED: out << "GET_SCRIPTS_FAILED"; break; - - case GET_SCRIPTS_UNPARSABLE: + case DropOutReason::GET_SCRIPTS_UNPARSABLE: out << "GET_SCRIPTS_UNPARSEABLE"; break; - - case NO_INITIAL_SCRIPTS: + case DropOutReason::NO_INITIAL_SCRIPTS: out << "NO_INITIAL_SCRIPTS"; break; - - case DFM_INSTALL_FAILED: + case DropOutReason::DFM_INSTALL_FAILED: out << "DFM_INSTALL_FAILED"; break; - // Intentionally no default case to make compilation fail if a new value - // was added to the enum but not to this list. + // Intentionally no default case to make compilation fail + // if a new value was added to the enum but not to this list. } return out; #endif // NDEBUG @@ -167,25 +178,18 @@ #else // Debugging builds write a string representation of |metric|. switch (metric) { - case OB_SHOWN: + case OnBoarding::OB_SHOWN: out << "OB_SHOWN"; break; - - case OB_NOT_SHOWN: + case OnBoarding::OB_NOT_SHOWN: out << "OB_NOT_SHOWN"; break; - - case OB_ACCEPTED: + case OnBoarding::OB_ACCEPTED: out << "OB_ACCEPTED"; break; - - case OB_CANCELLED: + case OnBoarding::OB_CANCELLED: out << "OB_CANCELLED"; break; - - case OB_NUM_ENTRIES: - out << "OB_NUM_ENTRIES"; - break; } return out; #endif // NDEBUG
diff --git a/components/browser_sync/BUILD.gn b/components/browser_sync/BUILD.gn index d194fc1..b2d469e 100644 --- a/components/browser_sync/BUILD.gn +++ b/components/browser_sync/BUILD.gn
@@ -87,7 +87,7 @@ "//components/bookmarks/browser", "//components/history/core/browser", "//components/signin/core/browser", - "//components/signin/core/browser:internals_test_support", + "//components/signin/public/base:test_support", "//components/sync", "//components/sync:test_support", "//components/sync_preferences:test_support",
diff --git a/components/browser_sync/profile_sync_components_factory_impl.cc b/components/browser_sync/profile_sync_components_factory_impl.cc index 5dec17bb..cf35dc19 100644 --- a/components/browser_sync/profile_sync_components_factory_impl.cc +++ b/components/browser_sync/profile_sync_components_factory_impl.cc
@@ -288,10 +288,13 @@ // disabled. if (!disabled_types.Has(syncer::PASSWORDS)) { if (base::FeatureList::IsEnabled(switches::kSyncUSSPasswords)) { - controllers.push_back( - std::make_unique<password_manager::PasswordModelTypeController>( - password_store_->CreateSyncControllerDelegate(), sync_service, - sync_client_->GetPasswordStateChangedCallback())); + if (password_store_) { + // |password_store_| can be null in tests. + controllers.push_back( + std::make_unique<password_manager::PasswordModelTypeController>( + password_store_->CreateSyncControllerDelegate(), sync_service, + sync_client_->GetPasswordStateChangedCallback())); + } } else { controllers.push_back(std::make_unique<PasswordDataTypeController>( dump_stack, sync_service, sync_client_,
diff --git a/components/crash/content/app/BUILD.gn b/components/crash/content/app/BUILD.gn index bfa3552d..f6a8b7d 100644 --- a/components/crash/content/app/BUILD.gn +++ b/components/crash/content/app/BUILD.gn
@@ -81,7 +81,10 @@ ] if (is_linux) { - deps += [ "//third_party/breakpad:client" ] + deps += [ + "//content/public/common", + "//third_party/breakpad:client", + ] } }
diff --git a/components/crash/content/app/DEPS b/components/crash/content/app/DEPS index d97ebb39..d89b50ec 100644 --- a/components/crash/content/app/DEPS +++ b/components/crash/content/app/DEPS
@@ -6,7 +6,9 @@ "+components/gwp_asan/buildflags/buildflags.h", "+components/gwp_asan/crash_handler/crash_handler.h", "+content/public/common/content_descriptors.h", + "+content/public/common/content_switches.h", "+content/public/common/result_codes.h", + "+services/service_manager/embedder/switches.h", "+third_party/crashpad", "+third_party/lss/linux_syscall_support.h", ]
diff --git a/components/crash/content/app/breakpad_linux.cc b/components/crash/content/app/breakpad_linux.cc index 3ab8ad2..bb5ee46 100644 --- a/components/crash/content/app/breakpad_linux.cc +++ b/components/crash/content/app/breakpad_linux.cc
@@ -36,6 +36,7 @@ #include "base/posix/eintr_wrapper.h" #include "base/posix/global_descriptors.h" #include "base/process/memory.h" +#include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/threading/thread_checker.h" @@ -44,6 +45,8 @@ #include "components/crash/content/app/crash_reporter_client.h" #include "components/crash/core/common/crash_keys.h" #include "content/public/common/content_descriptors.h" +#include "content/public/common/content_switches.h" +#include "services/service_manager/embedder/switches.h" #include "third_party/breakpad/breakpad/src/client/linux/crash_generation/crash_generation_client.h" #include "third_party/breakpad/breakpad/src/client/linux/handler/exception_handler.h" #include "third_party/breakpad/breakpad/src/client/linux/minidump_writer/directory_reader.h" @@ -87,7 +90,16 @@ namespace { -#if !defined(OS_CHROMEOS) +#if defined(OS_CHROMEOS) +// An optional UNIX timestamp passed to us from session_manager. If set, +// session_manager thinks we are in a possible crash-loop and will log the user +// out if we crash again before the indicated time. We don't actually do much +// with this value, just pass it along to crash_reporter. This should really +// be a time_t, but it's basically an opaque value (we don't anything with it +// except pass it along) and we don't have functions to deal with time_t's well, +// while we do have functions to deal with uint64_t's. +uint64_t g_crash_loop_before_time = 0; +#else const char kUploadURL[] = "https://clients2.google.com/cr/report"; #endif @@ -1131,11 +1143,35 @@ g_crash_key_white_list = GetCrashReporterClient()->GetCrashKeyWhiteList(); } +void SetCrashLoopBeforeTime(const std::string& process_type, + const base::CommandLine& parsed_command_line) { +#if defined(OS_CHROMEOS) + if (!ShouldPassCrashLoopBefore(process_type)) { + return; + } + + std::string crash_loop_before = + parsed_command_line.GetSwitchValueASCII(switches::kCrashLoopBefore); + if (crash_loop_before.empty()) { + return; + } + + if (!base::StringToUint64(crash_loop_before, &g_crash_loop_before_time)) { + LOG(WARNING) << "Could not convert --crash-loop-before=" + << crash_loop_before << " to integer"; + g_crash_loop_before_time = 0; + } +#endif // defined(OS_CHROMEOS) +} + // Miscellaneous initialization functions to call after Breakpad has been // enabled. -void PostEnableBreakpadInitialization() { +void PostEnableBreakpadInitialization( + const std::string& process_type, + const base::CommandLine& parsed_command_line) { SetProcessStartTime(); g_pid = getpid(); + SetCrashLoopBeforeTime(process_type, parsed_command_line); base::debug::SetDumpWithoutCrashingFunction(&DumpProcess); #if defined(ADDRESS_SANITIZER) @@ -1265,13 +1301,20 @@ my_strlcat(exe_flag, kExeBuf, buf_len); my_strlcat(exe_flag, exe_buf, buf_len); + char* crash_loop_before_flag = nullptr; + if (g_crash_loop_before_time != 0) { + crash_loop_before_flag = StringFromPrefixAndUint( + "--crash_loop_before=", g_crash_loop_before_time, allocator); + } + const char* args[] = { - kCrashReporterBinary, - chrome_flag, - pid_flag, - uid_flag, - exe_flag, - nullptr, + kCrashReporterBinary, + chrome_flag, + pid_flag, + uid_flag, + exe_flag, + crash_loop_before_flag, // Leave last, might be nullptr. + nullptr, }; static const char msg[] = "Cannot upload crash dump: cannot exec " "/sbin/crash_reporter\n"; @@ -1509,7 +1552,7 @@ // Either way too long, or a read error. return "chrome-crash-unknown-process"; } -#endif +#endif // defined(OS_CHROMEOS) // Attempts to close all open file descriptors other than stdin, stdout and // stderr (0, 1, and 2). @@ -2024,7 +2067,7 @@ #endif // #if defined(OS_ANDROID) } - PostEnableBreakpadInitialization(); + PostEnableBreakpadInitialization(process_type, parsed_command_line); } void SetChannelCrashKey(const std::string& channel) { @@ -2118,6 +2161,21 @@ } #endif // OS_ANDROID +#if defined(OS_CHROMEOS) +bool ShouldPassCrashLoopBefore(const std::string& process_type) { + if (process_type == ::switches::kRendererProcess || + process_type == ::switches::kUtilityProcess || + process_type == ::switches::kPpapiPluginProcess || + process_type == service_manager::switches::kZygoteProcess) { + // These process types never cause a log-out, even if they crash. So the + // normal crash handling process should work fine; we shouldn't need to + // invoke the special crash-loop mode. + return false; + } + return true; +} +#endif // defined(OS_CHROMEOS) + bool IsCrashReporterEnabled() { return g_is_crash_reporter_enabled; }
diff --git a/components/crash/content/app/breakpad_linux.h b/components/crash/content/app/breakpad_linux.h index 6e95af6..fb7f0a8a 100644 --- a/components/crash/content/app/breakpad_linux.h +++ b/components/crash/content/app/breakpad_linux.h
@@ -58,6 +58,13 @@ extern void SuppressDumpGeneration(); #endif // defined(OS_ANDROID) +#if defined(OS_CHROMEOS) +// If true, processes of this type should pass crash-loop-before down to the +// crash reporter and to their children (if the children's type is a process +// type that wants crash-loop-before). +bool ShouldPassCrashLoopBefore(const std::string& process_type); +#endif + // Checks if crash reporting is enabled. Note that this is not the same as // being opted into metrics reporting (and crash reporting), which controls // whether InitCrashReporter() is called.
diff --git a/components/cronet/cronet_url_request_context.cc b/components/cronet/cronet_url_request_context.cc index 54e410e..d9dec9b9 100644 --- a/components/cronet/cronet_url_request_context.cc +++ b/components/cronet/cronet_url_request_context.cc
@@ -632,8 +632,8 @@ CreateNetLogEntriesForActiveObjects({context_.get()}, net_log_file_observer_.get()); net::NetLogCaptureMode capture_mode = - include_socket_bytes ? net::NetLogCaptureMode::IncludeSocketBytes() - : net::NetLogCaptureMode::Default(); + include_socket_bytes ? net::NetLogCaptureMode::kEverything + : net::NetLogCaptureMode::kDefault; net_log_file_observer_->StartObserving(g_net_log.Get().net_log(), capture_mode); } @@ -671,8 +671,8 @@ net_log_file_observer_.get()); net::NetLogCaptureMode capture_mode = - include_socket_bytes ? net::NetLogCaptureMode::IncludeSocketBytes() - : net::NetLogCaptureMode::Default(); + include_socket_bytes ? net::NetLogCaptureMode::kEverything + : net::NetLogCaptureMode::kDefault; net_log_file_observer_->StartObserving(g_net_log.Get().net_log(), capture_mode); }
diff --git a/components/cronet/ios/cronet_environment.mm b/components/cronet/ios/cronet_environment.mm index 57b1dba..70f954c 100644 --- a/components/cronet/ios/cronet_environment.mm +++ b/components/cronet/ios/cronet_environment.mm
@@ -175,8 +175,8 @@ return; net::NetLogCaptureMode capture_mode = - log_bytes ? net::NetLogCaptureMode::IncludeSocketBytes() - : net::NetLogCaptureMode::Default(); + log_bytes ? net::NetLogCaptureMode::kEverything + : net::NetLogCaptureMode::kDefault; file_net_log_observer_ = net::FileNetLogObserver::CreateUnbounded(path, nullptr);
diff --git a/components/dbus/menu/BUILD.gn b/components/dbus/menu/BUILD.gn new file mode 100644 index 0000000..cad56081 --- /dev/null +++ b/components/dbus/menu/BUILD.gn
@@ -0,0 +1,48 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +component("menu") { + sources = [ + "menu.cc", + "menu.h", + "properties_interface.cc", + "properties_interface.h", + "types.cc", + "types.h", + ] + defines = [ "IS_DBUS_IMPL" ] + deps = [ + "//base:i18n", + "//dbus", + "//skia", + "//ui/base", + "//ui/gfx", + ] + public_deps = [ + ":success_barrier_callback", + ] +} + +source_set("success_barrier_callback") { + sources = [ + "success_barrier_callback.cc", + "success_barrier_callback.h", + ] + defines = [ "IS_DBUS_IMPL" ] + deps = [ + "//base", + ] +} + +source_set("unit_tests") { + testonly = true + sources = [ + "success_barrier_callback_unittest.cc", + ] + deps = [ + ":success_barrier_callback", + "//base", + "//testing/gtest", + ] +}
diff --git a/components/dbus/menu/DEPS b/components/dbus/menu/DEPS new file mode 100644 index 0000000..153f3f4 --- /dev/null +++ b/components/dbus/menu/DEPS
@@ -0,0 +1,4 @@ +include_rules = [ + "+dbus", + "+ui/base", +]
diff --git a/components/dbus/menu/OWNERS b/components/dbus/menu/OWNERS new file mode 100644 index 0000000..296dc0d --- /dev/null +++ b/components/dbus/menu/OWNERS
@@ -0,0 +1,2 @@ +thestig@chromium.org +thomasanderson@chromium.org
diff --git a/chrome/browser/ui/views/status_icons/dbus_menu.cc b/components/dbus/menu/menu.cc similarity index 97% rename from chrome/browser/ui/views/status_icons/dbus_menu.cc rename to components/dbus/menu/menu.cc index b0c4ec2..cf71ca02 100644 --- a/chrome/browser/ui/views/status_icons/dbus_menu.cc +++ b/components/dbus/menu/menu.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/views/status_icons/dbus_menu.h" +#include "components/dbus/menu/menu.h" #include <limits> #include <memory> @@ -14,9 +14,8 @@ #include "base/memory/scoped_refptr.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/ui/views/status_icons/dbus_properties_interface.h" -#include "chrome/browser/ui/views/status_icons/dbus_types.h" -#include "chrome/browser/ui/views/status_icons/success_barrier_callback.h" +#include "components/dbus/menu/properties_interface.h" +#include "components/dbus/menu/success_barrier_callback.h" #include "ui/base/accelerators/accelerator.h" #include "ui/base/accelerators/menu_label_accelerator_util_linux.h" #include "ui/base/models/menu_model.h"
diff --git a/chrome/browser/ui/views/status_icons/dbus_menu.h b/components/dbus/menu/menu.h similarity index 93% rename from chrome/browser/ui/views/status_icons/dbus_menu.h rename to components/dbus/menu/menu.h index 8360e04..077aed4 100644 --- a/chrome/browser/ui/views/status_icons/dbus_menu.h +++ b/components/dbus/menu/menu.h
@@ -2,17 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_DBUS_MENU_H_ -#define CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_DBUS_MENU_H_ +#ifndef COMPONENTS_DBUS_MENU_MENU_H_ +#define COMPONENTS_DBUS_MENU_MENU_H_ #include <map> #include <memory> #include <vector> #include "base/callback_forward.h" +#include "base/component_export.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/ui/views/status_icons/dbus_types.h" +#include "components/dbus/menu/types.h" #include "dbus/bus.h" #include "dbus/exported_object.h" #include "dbus/message.h" @@ -24,7 +25,7 @@ class DbusPropertiesInterface; // Implements the com.canonical.dbusmenu interface. -class DbusMenu { +class COMPONENT_EXPORT(DBUS) DbusMenu { public: using InitializedCallback = base::OnceCallback<void(bool success)>; @@ -135,4 +136,4 @@ DISALLOW_COPY_AND_ASSIGN(DbusMenu); }; -#endif // CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_DBUS_MENU_H_ +#endif // COMPONENTS_DBUS_MENU_MENU_H_
diff --git a/chrome/browser/ui/views/status_icons/dbus_properties_interface.cc b/components/dbus/menu/properties_interface.cc similarity index 96% rename from chrome/browser/ui/views/status_icons/dbus_properties_interface.cc rename to components/dbus/menu/properties_interface.cc index 2dd2241..01c17ac0 100644 --- a/chrome/browser/ui/views/status_icons/dbus_properties_interface.cc +++ b/components/dbus/menu/properties_interface.cc
@@ -2,13 +2,13 @@ // 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/status_icons/dbus_properties_interface.h" +#include "components/dbus/menu/properties_interface.h" #include <dbus/dbus-shared.h> #include "base/bind.h" #include "base/stl_util.h" -#include "chrome/browser/ui/views/status_icons/success_barrier_callback.h" +#include "components/dbus/menu/success_barrier_callback.h" #include "dbus/exported_object.h" #include "dbus/message.h"
diff --git a/chrome/browser/ui/views/status_icons/dbus_properties_interface.h b/components/dbus/menu/properties_interface.h similarity index 88% rename from chrome/browser/ui/views/status_icons/dbus_properties_interface.h rename to components/dbus/menu/properties_interface.h index c9a6007..aafa011 100644 --- a/chrome/browser/ui/views/status_icons/dbus_properties_interface.h +++ b/components/dbus/menu/properties_interface.h
@@ -2,19 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_DBUS_PROPERTIES_INTERFACE_H_ -#define CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_DBUS_PROPERTIES_INTERFACE_H_ +#ifndef COMPONENTS_DBUS_MENU_PROPERTIES_INTERFACE_H_ +#define COMPONENTS_DBUS_MENU_PROPERTIES_INTERFACE_H_ #include "base/callback_forward.h" +#include "base/component_export.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/stl_util.h" -#include "chrome/browser/ui/views/status_icons/dbus_types.h" +#include "components/dbus/menu/types.h" #include "dbus/bus.h" #include "dbus/exported_object.h" // https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties -class DbusPropertiesInterface { +class COMPONENT_EXPORT(DBUS) DbusPropertiesInterface { public: using InitializedCallback = base::OnceCallback<void(bool success)>; @@ -68,4 +69,4 @@ DISALLOW_COPY_AND_ASSIGN(DbusPropertiesInterface); }; -#endif // CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_DBUS_PROPERTIES_INTERFACE_H_ +#endif // COMPONENTS_DBUS_MENU_PROPERTIES_INTERFACE_H_
diff --git a/chrome/browser/ui/views/status_icons/success_barrier_callback.cc b/components/dbus/menu/success_barrier_callback.cc similarity index 94% rename from chrome/browser/ui/views/status_icons/success_barrier_callback.cc rename to components/dbus/menu/success_barrier_callback.cc index 73d85e8..2f6e35a 100644 --- a/chrome/browser/ui/views/status_icons/success_barrier_callback.cc +++ b/components/dbus/menu/success_barrier_callback.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/views/status_icons/success_barrier_callback.h" +#include "components/dbus/menu/success_barrier_callback.h" #include "base/bind.h" #include "base/callback.h"
diff --git a/chrome/browser/ui/views/status_icons/success_barrier_callback.h b/components/dbus/menu/success_barrier_callback.h similarity index 74% rename from chrome/browser/ui/views/status_icons/success_barrier_callback.h rename to components/dbus/menu/success_barrier_callback.h index 80d3eef7..b65944a 100644 --- a/chrome/browser/ui/views/status_icons/success_barrier_callback.h +++ b/components/dbus/menu/success_barrier_callback.h
@@ -2,20 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_SUCCESS_BARRIER_CALLBACK_H_ -#define CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_SUCCESS_BARRIER_CALLBACK_H_ +#ifndef COMPONENTS_DBUS_MENU_SUCCESS_BARRIER_CALLBACK_H_ +#define COMPONENTS_DBUS_MENU_SUCCESS_BARRIER_CALLBACK_H_ #include <cstddef> #include "base/callback_forward.h" +#include "base/component_export.h" // A callback wrapper that must be called |num_calls| times with an argument of // true (indicates success) for |done_callback| to be called with true. If the // wrapper is called with false, |done_callback| is immediately run with an // argument of false. Further calls after |done_callback| has already been run // will have no effect. +COMPONENT_EXPORT(DBUS) base::RepeatingCallback<void(bool)> SuccessBarrierCallback( size_t num_calls, base::OnceCallback<void(bool)> done_callback); -#endif // CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_SUCCESS_BARRIER_CALLBACK_H_ +#endif // COMPONENTS_DBUS_MENU_SUCCESS_BARRIER_CALLBACK_H_
diff --git a/chrome/browser/ui/views/status_icons/success_barrier_callback_unittest.cc b/components/dbus/menu/success_barrier_callback_unittest.cc similarity index 89% rename from chrome/browser/ui/views/status_icons/success_barrier_callback_unittest.cc rename to components/dbus/menu/success_barrier_callback_unittest.cc index 44b3bf1..6a8f2d1 100644 --- a/chrome/browser/ui/views/status_icons/success_barrier_callback_unittest.cc +++ b/components/dbus/menu/success_barrier_callback_unittest.cc
@@ -2,10 +2,10 @@ // 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/status_icons/success_barrier_callback.h" +#include "components/dbus/menu/success_barrier_callback.h" #include "base/bind.h" -#include "chrome/browser/ui/views/status_icons/status_icon_linux_dbus.h" +#include "base/callback.h" #include "testing/gtest/include/gtest/gtest.h" namespace {
diff --git a/chrome/browser/ui/views/status_icons/dbus_types.cc b/components/dbus/menu/types.cc similarity index 97% rename from chrome/browser/ui/views/status_icons/dbus_types.cc rename to components/dbus/menu/types.cc index 07c8123..5694f2dc 100644 --- a/chrome/browser/ui/views/status_icons/dbus_types.cc +++ b/components/dbus/menu/types.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/views/status_icons/dbus_types.h" +#include "components/dbus/menu/types.h" #include "dbus/message.h" #include "dbus/object_path.h"
diff --git a/chrome/browser/ui/views/status_icons/dbus_types.h b/components/dbus/menu/types.h similarity index 87% rename from chrome/browser/ui/views/status_icons/dbus_types.h rename to components/dbus/menu/types.h index 6ffbd6a..3ba18d5d 100644 --- a/chrome/browser/ui/views/status_icons/dbus_types.h +++ b/components/dbus/menu/types.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_UI_VIEWS_STATUS_ICONS_DBUS_TYPES_H_ -#define CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_DBUS_TYPES_H_ +#ifndef COMPONENTS_DBUS_MENU_TYPES_H_ +#define COMPONENTS_DBUS_MENU_TYPES_H_ #include <stdint.h> @@ -13,6 +13,7 @@ #include <type_traits> #include <utility> +#include "base/component_export.h" #include "base/memory/ref_counted_memory.h" #include "dbus/message.h" @@ -60,7 +61,7 @@ } // namespace detail -class DbusType { +class COMPONENT_EXPORT(DBUS) DbusType { public: virtual ~DbusType(); @@ -85,7 +86,7 @@ std::string GetSignatureDynamic() const override { return T::GetSignature(); } }; -class DbusBoolean : public DbusTypeImpl<DbusBoolean> { +class COMPONENT_EXPORT(DBUS) DbusBoolean : public DbusTypeImpl<DbusBoolean> { public: explicit DbusBoolean(bool value); DbusBoolean(DbusBoolean&& other); @@ -100,7 +101,7 @@ bool value_; }; -class DbusInt32 : public DbusTypeImpl<DbusInt32> { +class COMPONENT_EXPORT(DBUS) DbusInt32 : public DbusTypeImpl<DbusInt32> { public: explicit DbusInt32(int32_t value); DbusInt32(DbusInt32&& other); @@ -115,7 +116,7 @@ int32_t value_; }; -class DbusUint32 : public DbusTypeImpl<DbusUint32> { +class COMPONENT_EXPORT(DBUS) DbusUint32 : public DbusTypeImpl<DbusUint32> { public: explicit DbusUint32(uint32_t value); DbusUint32(DbusUint32&& other); @@ -130,7 +131,7 @@ uint32_t value_; }; -class DbusString : public DbusTypeImpl<DbusString> { +class COMPONENT_EXPORT(DBUS) DbusString : public DbusTypeImpl<DbusString> { public: explicit DbusString(const std::string& value); DbusString(DbusString&& other); @@ -145,7 +146,8 @@ std::string value_; }; -class DbusObjectPath : public DbusTypeImpl<DbusObjectPath> { +class COMPONENT_EXPORT(DBUS) DbusObjectPath + : public DbusTypeImpl<DbusObjectPath> { public: explicit DbusObjectPath(const dbus::ObjectPath& value); DbusObjectPath(DbusObjectPath&& other); @@ -160,7 +162,7 @@ dbus::ObjectPath value_; }; -class DbusVariant : public DbusTypeImpl<DbusVariant> { +class COMPONENT_EXPORT(DBUS) DbusVariant : public DbusTypeImpl<DbusVariant> { public: DbusVariant(); explicit DbusVariant(std::unique_ptr<DbusType> value); @@ -186,7 +188,7 @@ } template <typename T> -class DbusArray : public DbusTypeImpl<DbusArray<T>> { +class COMPONENT_EXPORT(DBUS) DbusArray : public DbusTypeImpl<DbusArray<T>> { public: explicit DbusArray(std::vector<T>&& value) : value_(std::move(value)) {} DbusArray(DbusArray<T>&& other) = default; @@ -224,7 +226,8 @@ // (If DbusByte was defined) this is the same as DbusArray<DbusByte>. This // class avoids having to create a bunch of heavy virtual objects just to wrap // individual bytes. -class DbusByteArray : public DbusTypeImpl<DbusByteArray> { +class COMPONENT_EXPORT(DBUS) DbusByteArray + : public DbusTypeImpl<DbusByteArray> { public: DbusByteArray(); explicit DbusByteArray(scoped_refptr<base::RefCountedMemory> value); @@ -241,7 +244,8 @@ }; template <typename... Ts> -class DbusStruct : public DbusTypeImpl<DbusStruct<Ts...>> { +class COMPONENT_EXPORT(DBUS) DbusStruct + : public DbusTypeImpl<DbusStruct<Ts...>> { public: explicit DbusStruct(Ts&&... ts) : value_(std::move(ts)...) {} DbusStruct(DbusStruct<Ts...>&& other) = default; @@ -269,7 +273,8 @@ } template <typename K, typename V> -class DbusDictEntry : public DbusTypeImpl<DbusDictEntry<K, V>> { +class COMPONENT_EXPORT(DBUS) DbusDictEntry + : public DbusTypeImpl<DbusDictEntry<K, V>> { public: DbusDictEntry(K&& k, V&& v) : k_(std::move(k)), v_(std::move(v)) {} DbusDictEntry(DbusDictEntry<K, V>&& other) = default; @@ -298,4 +303,4 @@ return DbusDictEntry<K, V>(std::move(k), std::move(v)); } -#endif // CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_DBUS_TYPES_H_ +#endif // COMPONENTS_DBUS_MENU_TYPES_H_
diff --git a/components/dbus/BUILD.gn b/components/dbus/thread_linux/BUILD.gn similarity index 89% rename from components/dbus/BUILD.gn rename to components/dbus/thread_linux/BUILD.gn index 97b3a61..9e4cb76 100644 --- a/components/dbus/BUILD.gn +++ b/components/dbus/thread_linux/BUILD.gn
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -component("dbus_thread_linux") { +component("thread_linux") { sources = [ "dbus_thread_linux.cc", "dbus_thread_linux.h",
diff --git a/components/dbus/dbus_thread_linux.cc b/components/dbus/thread_linux/dbus_thread_linux.cc similarity index 94% rename from components/dbus/dbus_thread_linux.cc rename to components/dbus/thread_linux/dbus_thread_linux.cc index 0ac8b64..3bb7423 100644 --- a/components/dbus/dbus_thread_linux.cc +++ b/components/dbus/thread_linux/dbus_thread_linux.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/dbus/dbus_thread_linux.h" +#include "components/dbus/thread_linux/dbus_thread_linux.h" #include "base/task/lazy_task_runner.h"
diff --git a/components/dbus/dbus_thread_linux.h b/components/dbus/thread_linux/dbus_thread_linux.h similarity index 81% rename from components/dbus/dbus_thread_linux.h rename to components/dbus/thread_linux/dbus_thread_linux.h index e2d1aa05..81c976a 100644 --- a/components/dbus/dbus_thread_linux.h +++ b/components/dbus/thread_linux/dbus_thread_linux.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 COMPONENTS_DBUS_DBUS_THREAD_LINUX_H_ -#define COMPONENTS_DBUS_DBUS_THREAD_LINUX_H_ +#ifndef COMPONENTS_DBUS_THREAD_LINUX_DBUS_THREAD_LINUX_H_ +#define COMPONENTS_DBUS_THREAD_LINUX_DBUS_THREAD_LINUX_H_ #include "base/component_export.h" #include "base/memory/ref_counted.h" @@ -26,4 +26,4 @@ } // namespace dbus_thread_linux -#endif // COMPONENTS_DBUS_DBUS_THREAD_LINUX_H_ +#endif // COMPONENTS_DBUS_THREAD_LINUX_DBUS_THREAD_LINUX_H_
diff --git a/components/download/internal/common/download_response_handler.cc b/components/download/internal/common/download_response_handler.cc index ad205b8..a4734db 100644 --- a/components/download/internal/common/download_response_handler.cc +++ b/components/download/internal/common/download_response_handler.cc
@@ -232,7 +232,8 @@ completed_ = true; DownloadInterruptReason reason = HandleRequestCompletionStatus( static_cast<net::Error>(status.error_code), - ignore_content_length_mismatch_, cert_status_, abort_reason_); + ignore_content_length_mismatch_, cert_status_, is_partial_request_, + abort_reason_); if (client_ptr_) { client_ptr_->OnStreamCompleted(
diff --git a/components/download/internal/common/download_utils.cc b/components/download/internal/common/download_utils.cc index b2100e5..b1c816f 100644 --- a/components/download/internal/common/download_utils.cc +++ b/components/download/internal/common/download_utils.cc
@@ -55,6 +55,7 @@ net::Error error_code, bool ignore_content_length_mismatch, net::CertStatus cert_status, + bool is_partial_request, DownloadInterruptReason abort_reason) { if (error_code == net::ERR_CONTENT_LENGTH_MISMATCH && ignore_content_length_mismatch) { @@ -82,6 +83,12 @@ return abort_reason; } + // For some servers, a range request could cause the server to send + // wrongly encoded content and cause decoding failures. Restart the download + // in that case. + if (is_partial_request && error_code == net::ERR_CONTENT_DECODING_FAILED) + return DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE; + return ConvertNetErrorToInterruptReason(error_code, DOWNLOAD_INTERRUPT_FROM_NETWORK); } @@ -179,12 +186,8 @@ (save_info->length > 0 && last_byte != save_info->offset + save_info->length - 1)) { // The server returned a different range than the one we requested. Assume - // the response is bad. - // - // In the future we should consider allowing offsets that are less than - // the offset we've requested, since in theory we can truncate the partial - // file at the offset and continue. - return DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT; + // the server doesn't support range request. + return DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE; } return DOWNLOAD_INTERRUPT_REASON_NONE;
diff --git a/components/download/public/common/download_utils.h b/components/download/public/common/download_utils.h index c803699..69f4824 100644 --- a/components/download/public/common/download_utils.h +++ b/components/download/public/common/download_utils.h
@@ -41,6 +41,7 @@ HandleRequestCompletionStatus(net::Error error_code, bool ignore_content_length_mismatch, net::CertStatus cert_status, + bool is_partial_request, DownloadInterruptReason abort_reason); // Parse the HTTP server response code.
diff --git a/components/exo/wayland/fuzzer/harness.cc.tmpl b/components/exo/wayland/fuzzer/harness.cc.tmpl index 7707b93..9d8f14f 100644 --- a/components/exo/wayland/fuzzer/harness.cc.tmpl +++ b/components/exo/wayland/fuzzer/harness.cc.tmpl
@@ -211,12 +211,14 @@ int Harness::GetFileDescriptor(int id) { if (shared_memory_map_.count(id) == 0) { - auto shared_mem = std::make_unique<base::SharedMemory>(); - shared_mem->CreateAndMapAnonymous(1); - shared_memory_map_.emplace(id, std::move(shared_mem)); + base::UnsafeSharedMemoryRegion region = + base::UnsafeSharedMemoryRegion::Create(1); + shared_memory_map_.emplace(id, std::move(region)); } - return base::SharedMemory::GetFdFromSharedMemoryHandle( - base::SharedMemory::DuplicateHandle(shared_memory_map_[id]->handle())); + base::subtle::ScopedFDPair fd_pair = + base::UnsafeSharedMemoryRegion::TakeHandleForSerialization( + shared_memory_map_[id].Duplicate()).PassPlatformHandle(); + return fd_pair.fd.release(); } } // namespace wayland_fuzzer
diff --git a/components/exo/wayland/fuzzer/harness.h.tmpl b/components/exo/wayland/fuzzer/harness.h.tmpl index 30e0ce2..924fb30 100644 --- a/components/exo/wayland/fuzzer/harness.h.tmpl +++ b/components/exo/wayland/fuzzer/harness.h.tmpl
@@ -10,7 +10,7 @@ #include <wayland-util.h> #include "base/macros.h" -#include "base/memory/shared_memory.h" +#include "base/memory/unsafe_shared_memory_region.h" #include "components/exo/wayland/fuzzer/actions.pb.h" // Forwards declarations for the wayland-defined structs. @@ -60,7 +60,7 @@ int GetFileDescriptor(int id); private: - std::map<int, std::unique_ptr<base::SharedMemory>> shared_memory_map_; + std::map<int, base::UnsafeSharedMemoryRegion> shared_memory_map_; DISALLOW_COPY_AND_ASSIGN(Harness); };
diff --git a/components/exo/wayland/zcr_remote_shell.cc b/components/exo/wayland/zcr_remote_shell.cc index 711fd8a..0ab01749 100644 --- a/components/exo/wayland/zcr_remote_shell.cc +++ b/components/exo/wayland/zcr_remote_shell.cc
@@ -9,13 +9,13 @@ #include <wayland-server-protocol-core.h> #include "ash/public/cpp/shell_window_ids.h" +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/public/cpp/window_pin_type.h" #include "ash/public/cpp/window_properties.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shell.h" #include "ash/wm/desks/desks_util.h" -#include "ash/wm/tablet_mode/tablet_mode_observer.h" #include "ash/wm/window_resizer.h" #include "ash/wm/window_state.h" #include "ash/wm/work_area_insets.h"
diff --git a/components/flags_ui/resources/flags.html b/components/flags_ui/resources/flags.html index bc99d2a..4fcd53d 100644 --- a/components/flags_ui/resources/flags.html +++ b/components/flags_ui/resources/flags.html
@@ -89,14 +89,16 @@ : 'experiment-switched flex-container'"> <div class="flex"> <h3 class="experiment-name" jscontent="name" - jsvalues="title: is_default ? '' : 'Experiment enabled'"></h3> + jsvalues="title: is_default ? '' : 'Experiment enabled'; + id:internal_name + '_name'"></h3> <p> <span jsvalues=".innerHTML:description"></span> – <span class="platforms" jscontent="supported_platforms.join(', ')"></span> </p> <div jsdisplay="origin_list_value!==null"> <textarea class="experiment-origin-list-value" - jsvalues=".internal_name:internal_name; .value:origin_list_value" + jsvalues=".internal_name:internal_name; .value:origin_list_value; + aria-labelledby:internal_name + '_name'" tabindex="7"></textarea> </div> <a class="permalink" jsvalues="href: '#' + internal_name" @@ -105,7 +107,8 @@ <div class="flex experiment-actions"> <div jsdisplay="options && options.length > 0"> <select class="experiment-select" tabindex="6" - jsvalues=".internal_name:internal_name;.disabled:!enabled;"> + jsvalues=".internal_name:internal_name;.disabled:!enabled; + aria-labelledby:internal_name + '_name'"> <option jsvalues=".selected:selected;" jsselect="options" jscontent="description"> @@ -114,12 +117,12 @@ </div> <select class="experiment-enable-disable" tabindex="6" jsdisplay="enabled !== undefined" - jsvalues=".internal_name:internal_name;"> + jsvalues=".internal_name:internal_name; + aria-labelledby:internal_name + '_name'"> <option jsvalues=".selected:!enabled; data-default: enabled ? 1 : 0" value="disabled">Disabled</option> <option jsvalues=".selected:enabled; data-default: !enabled ? 1 : 0" value="enabled">Enabled</option> - </option> </select> </div> </div> @@ -133,14 +136,16 @@ : 'experiment-switched flex-container'"> <div class="flex"> <h3 class="experiment-name" jscontent="name" - jsvalues="title: is_default ? '' : 'Experiment enabled'"></h3> + jsvalues="title: is_default ? '' : 'Experiment enabled'; + id:internal_name + '_name'"></h3> <p> <span jsvalues=".innerHTML:description"></span> – <span class="platforms" jscontent="supported_platforms.join(', ')"></span> </p> <div jsdisplay="origin_list_value!==null"> <textarea class="experiment-origin-list-value" - jsvalues=".internal_name:internal_name; .value:origin_list_value" + jsvalues=".internal_name:internal_name; .value:origin_list_value; + aria-labelledby:internal_name + '_name'" tabindex="7"></textarea> </div> <a class="permalink" jsvalues="href: '#' + internal_name" @@ -149,7 +154,8 @@ <div class="flex experiment-actions"> <div jsdisplay="options && options.length > 0"> <select class="experiment-select" tabindex="6" - jsvalues=".internal_name:internal_name;.disabled:!enabled"> + jsvalues=".internal_name:internal_name;.disabled:!enabled; + aria-labelledby:internal_name + '_name'"> <option jsvalues=".selected:selected;" jsselect="options" jscontent="description"> @@ -159,7 +165,8 @@ <!-- Represent enabled / disabled options in a drop down --> <select class="experiment-enable-disable" tabindex="6" jsdisplay="enabled !== undefined" - jsvalues=".internal_name:internal_name;"> + jsvalues=".internal_name:internal_name; + aria-labelledby:internal_name + '_name'"> <option jsvalues=".selected:!enabled; data-default:!enabled ? 1 : 0" value="disabled">Disabled</option> <option jsvalues=".selected:enabled; data-default: enabled ? 1 : 0"
diff --git a/components/invalidation/impl/BUILD.gn b/components/invalidation/impl/BUILD.gn index 28a2696..3d4d86a 100644 --- a/components/invalidation/impl/BUILD.gn +++ b/components/invalidation/impl/BUILD.gn
@@ -146,7 +146,7 @@ "//components/gcm_driver/instance_id:test_support", "//components/prefs", "//components/prefs:test_support", - "//components/signin/core/browser:internals_test_support", + "//components/signin/public/base:test_support", "//components/signin/public/identity_manager:test_support", "//components/sync_preferences:test_support", "//google_apis:test_support",
diff --git a/components/management_strings.grdp b/components/management_strings.grdp index 5156b468..9cebc28 100644 --- a/components/management_strings.grdp +++ b/components/management_strings.grdp
@@ -104,6 +104,9 @@ <message name="IDS_MANAGEMENT_REPORT_PRINTING" desc="Message stating that administrators can see names of printed files."> Names of files that you print </message> + <message name="IDS_MANAGEMENT_CROSTINI" desc="Message stating that administrators can see Crostini usage"> + Linux apps installed and when they were last used + </message> </if> <!-- Strings related to extension reporting section of the management page -->
diff --git a/components/metrics/call_stack_profile_builder.cc b/components/metrics/call_stack_profile_builder.cc index b35165d..0b40e5b0 100644 --- a/components/metrics/call_stack_profile_builder.cc +++ b/components/metrics/call_stack_profile_builder.cc
@@ -48,7 +48,7 @@ } std::map<uint64_t, int64_t> CreateMetadataMap( - base::MetadataRecorder::ItemArray items, + base::ProfileBuilder::MetadataItemArray items, size_t item_count) { std::map<uint64_t, int64_t> item_map; for (size_t i = 0; i < item_count; ++i) { @@ -102,10 +102,8 @@ CallStackProfileBuilder::CallStackProfileBuilder( const CallStackProfileParams& profile_params, const WorkIdRecorder* work_id_recorder, - const base::MetadataRecorder* metadata_recorder, base::OnceClosure completed_callback) : work_id_recorder_(work_id_recorder), - metadata_recorder_(metadata_recorder), profile_start_time_(base::TimeTicks::Now()) { completed_callback_ = std::move(completed_callback); sampled_profile_.set_process( @@ -124,7 +122,8 @@ // This function is invoked on the profiler thread while the target thread is // suspended so must not take any locks, including indirectly through use of // heap allocation, LOG, CHECK, or DCHECK. -void CallStackProfileBuilder::RecordMetadata() { +void CallStackProfileBuilder::RecordMetadata( + base::ProfileBuilder::MetadataProvider* metadata_provider) { if (work_id_recorder_) { unsigned int work_id = work_id_recorder_->RecordWorkId(); // A work id of 0 indicates that the message loop has not yet started. @@ -134,8 +133,8 @@ } } - if (metadata_recorder_) - metadata_item_count_ = metadata_recorder_->GetItems(&metadata_items_); + if (metadata_provider) + metadata_item_count_ = metadata_provider->GetItems(&metadata_items_); } void CallStackProfileBuilder::OnSampleCompleted(
diff --git a/components/metrics/call_stack_profile_builder.h b/components/metrics/call_stack_profile_builder.h index d141670..9de8401 100644 --- a/components/metrics/call_stack_profile_builder.h +++ b/components/metrics/call_stack_profile_builder.h
@@ -57,7 +57,6 @@ explicit CallStackProfileBuilder( const CallStackProfileParams& profile_params, const WorkIdRecorder* work_id_recorder = nullptr, - const base::MetadataRecorder* metadata_recorder = nullptr, base::OnceClosure completed_callback = base::OnceClosure()); ~CallStackProfileBuilder() override; @@ -69,7 +68,8 @@ // base::ProfileBuilder: base::ModuleCache* GetModuleCache() override; - void RecordMetadata() override; + void RecordMetadata(base::ProfileBuilder::MetadataProvider* + metadata_provider = nullptr) override; void OnSampleCompleted(std::vector<base::Frame> frames) override; void OnProfileCompleted(base::TimeDelta profile_duration, base::TimeDelta sampling_period) override; @@ -113,7 +113,6 @@ unsigned int last_work_id_ = std::numeric_limits<unsigned int>::max(); bool is_continued_work_ = false; const WorkIdRecorder* const work_id_recorder_; - const base::MetadataRecorder* const metadata_recorder_; // The SampledProfile protobuf message which contains the collected stack // samples. @@ -135,7 +134,7 @@ const base::TimeTicks profile_start_time_; // The data fetched from the MetadataRecorder for the next sample. - base::MetadataRecorder::ItemArray metadata_items_; + base::ProfileBuilder::MetadataItemArray metadata_items_; size_t metadata_item_count_ = 0; // The data fetched from the MetadataRecorder for the previous sample. std::map<uint64_t, int64_t> previous_items_;
diff --git a/components/metrics/call_stack_profile_builder_unittest.cc b/components/metrics/call_stack_profile_builder_unittest.cc index 2d4900bb..c3788bf 100644 --- a/components/metrics/call_stack_profile_builder_unittest.cc +++ b/components/metrics/call_stack_profile_builder_unittest.cc
@@ -53,7 +53,6 @@ TestingCallStackProfileBuilder( const CallStackProfileParams& profile_params, const WorkIdRecorder* work_id_recorder = nullptr, - const base::MetadataRecorder* metadata_recorder = nullptr, base::OnceClosure completed_callback = base::OnceClosure()); ~TestingCallStackProfileBuilder() override; @@ -72,11 +71,9 @@ TestingCallStackProfileBuilder::TestingCallStackProfileBuilder( const CallStackProfileParams& profile_params, const WorkIdRecorder* work_id_recorder, - const base::MetadataRecorder* metadata_recorder, base::OnceClosure completed_callback) : CallStackProfileBuilder(profile_params, work_id_recorder, - metadata_recorder, std::move(completed_callback)) {} TestingCallStackProfileBuilder::~TestingCallStackProfileBuilder() = default; @@ -94,7 +91,7 @@ EXPECT_CALL(mock_closure, Run()).Times(1); auto profile_builder = std::make_unique<TestingCallStackProfileBuilder>( - kProfileParams, nullptr, nullptr, mock_closure.Get()); + kProfileParams, nullptr, mock_closure.Get()); #if defined(OS_WIN) uint64_t module_md5 = 0x46C3E4166659AC02ULL; @@ -436,8 +433,8 @@ TEST(CallStackProfileBuilderTest, MetadataRecorder_NoItems) { base::MetadataRecorder metadata_recorder; - auto profile_builder = std::make_unique<TestingCallStackProfileBuilder>( - kProfileParams, nullptr, &metadata_recorder); + auto profile_builder = + std::make_unique<TestingCallStackProfileBuilder>(kProfileParams, nullptr); TestModule module; base::Frame frame = {0x10, &module}; @@ -460,16 +457,22 @@ TEST(CallStackProfileBuilderTest, MetadataRecorder_RepeatItem) { base::MetadataRecorder metadata_recorder; - auto profile_builder = std::make_unique<TestingCallStackProfileBuilder>( - kProfileParams, nullptr, &metadata_recorder); + auto profile_builder = + std::make_unique<TestingCallStackProfileBuilder>(kProfileParams, nullptr); TestModule module; base::Frame frame = {0x10, &module}; metadata_recorder.Set(100, 10); - profile_builder->RecordMetadata(); + { + auto get_items = metadata_recorder.CreateMetadataProvider(); + profile_builder->RecordMetadata(get_items.get()); + } profile_builder->OnSampleCompleted({frame}); - profile_builder->RecordMetadata(); + { + auto get_items = metadata_recorder.CreateMetadataProvider(); + profile_builder->RecordMetadata(get_items.get()); + } profile_builder->OnSampleCompleted({frame}); profile_builder->OnProfileCompleted(base::TimeDelta::FromMilliseconds(500), @@ -496,17 +499,23 @@ TEST(CallStackProfileBuilderTest, MetadataRecorder_ModifiedItem) { base::MetadataRecorder metadata_recorder; - auto profile_builder = std::make_unique<TestingCallStackProfileBuilder>( - kProfileParams, nullptr, &metadata_recorder); + auto profile_builder = + std::make_unique<TestingCallStackProfileBuilder>(kProfileParams, nullptr); TestModule module; base::Frame frame = {0x10, &module}; metadata_recorder.Set(100, 10); - profile_builder->RecordMetadata(); + { + auto get_items = metadata_recorder.CreateMetadataProvider(); + profile_builder->RecordMetadata(get_items.get()); + } profile_builder->OnSampleCompleted({frame}); metadata_recorder.Set(100, 11); - profile_builder->RecordMetadata(); + { + auto get_items = metadata_recorder.CreateMetadataProvider(); + profile_builder->RecordMetadata(get_items.get()); + } profile_builder->OnSampleCompleted({frame}); profile_builder->OnProfileCompleted(base::TimeDelta::FromMilliseconds(500), @@ -536,19 +545,25 @@ TEST(CallStackProfileBuilderTest, MetadataRecorder_NewItem) { base::MetadataRecorder metadata_recorder; - auto profile_builder = std::make_unique<TestingCallStackProfileBuilder>( - kProfileParams, nullptr, &metadata_recorder); + auto profile_builder = + std::make_unique<TestingCallStackProfileBuilder>(kProfileParams, nullptr); TestModule module; base::Frame frame = {0x10, &module}; metadata_recorder.Set(100, 10); - profile_builder->RecordMetadata(); + { + auto get_items = metadata_recorder.CreateMetadataProvider(); + profile_builder->RecordMetadata(get_items.get()); + } profile_builder->OnSampleCompleted({frame}); metadata_recorder.Set(100, 11); metadata_recorder.Set(200, 20); - profile_builder->RecordMetadata(); + { + auto get_items = metadata_recorder.CreateMetadataProvider(); + profile_builder->RecordMetadata(get_items.get()); + } profile_builder->OnSampleCompleted({frame}); profile_builder->OnProfileCompleted(base::TimeDelta::FromMilliseconds(500), @@ -582,17 +597,23 @@ TEST(CallStackProfileBuilderTest, MetadataRecorder_RemovedItem) { base::MetadataRecorder metadata_recorder; - auto profile_builder = std::make_unique<TestingCallStackProfileBuilder>( - kProfileParams, nullptr, &metadata_recorder); + auto profile_builder = + std::make_unique<TestingCallStackProfileBuilder>(kProfileParams, nullptr); TestModule module; base::Frame frame = {0x10, &module}; metadata_recorder.Set(100, 10); - profile_builder->RecordMetadata(); + { + auto get_items = metadata_recorder.CreateMetadataProvider(); + profile_builder->RecordMetadata(get_items.get()); + } profile_builder->OnSampleCompleted({frame}); metadata_recorder.Remove(100); - profile_builder->RecordMetadata(); + { + auto get_items = metadata_recorder.CreateMetadataProvider(); + profile_builder->RecordMetadata(get_items.get()); + } profile_builder->OnSampleCompleted({frame}); profile_builder->OnProfileCompleted(base::TimeDelta::FromMilliseconds(500),
diff --git a/components/net_log/net_export_file_writer.cc b/components/net_log/net_export_file_writer.cc index 81e0d164..6a2d6d16 100644 --- a/components/net_log/net_export_file_writer.cc +++ b/components/net_log/net_export_file_writer.cc
@@ -86,7 +86,7 @@ : state_(STATE_UNINITIALIZED), log_exists_(false), log_capture_mode_known_(false), - log_capture_mode_(net::NetLogCaptureMode::Default()), + log_capture_mode_(net::NetLogCaptureMode::kDefault), default_log_base_dir_getter_(base::Bind(&base::GetTempDir)), weak_ptr_factory_(this) {} @@ -294,11 +294,11 @@ std::string NetExportFileWriter::CaptureModeToString( net::NetLogCaptureMode capture_mode) { - if (capture_mode == net::NetLogCaptureMode::Default()) + if (capture_mode == net::NetLogCaptureMode::kDefault) return "STRIP_PRIVATE_DATA"; - if (capture_mode == net::NetLogCaptureMode::IncludeCookiesAndCredentials()) + if (capture_mode == net::NetLogCaptureMode::kIncludeSensitive) return "NORMAL"; - if (capture_mode == net::NetLogCaptureMode::IncludeSocketBytes()) + if (capture_mode == net::NetLogCaptureMode::kEverything) return "LOG_BYTES"; NOTREACHED(); return "STRIP_PRIVATE_DATA"; @@ -307,13 +307,13 @@ net::NetLogCaptureMode NetExportFileWriter::CaptureModeFromString( const std::string& capture_mode_string) { if (capture_mode_string == "STRIP_PRIVATE_DATA") - return net::NetLogCaptureMode::Default(); + return net::NetLogCaptureMode::kDefault; if (capture_mode_string == "NORMAL") - return net::NetLogCaptureMode::IncludeCookiesAndCredentials(); + return net::NetLogCaptureMode::kIncludeSensitive; if (capture_mode_string == "LOG_BYTES") - return net::NetLogCaptureMode::IncludeSocketBytes(); + return net::NetLogCaptureMode::kEverything; NOTREACHED(); - return net::NetLogCaptureMode::Default(); + return net::NetLogCaptureMode::kDefault; } void NetExportFileWriter::SetDefaultLogBaseDirectoryGetterForTest(
diff --git a/components/net_log/net_export_file_writer_unittest.cc b/components/net_log/net_export_file_writer_unittest.cc index 2d628d7..2d41be3 100644 --- a/components/net_log/net_export_file_writer_unittest.cc +++ b/components/net_log/net_export_file_writer_unittest.cc
@@ -48,8 +48,8 @@ FILE_PATH_LITERAL("net-export/chrome-net-export-log.json"); const char kCaptureModeDefaultString[] = "STRIP_PRIVATE_DATA"; -const char kCaptureModeIncludeCookiesAndCredentialsString[] = "NORMAL"; -const char kCaptureModeIncludeSocketBytesString[] = "LOG_BYTES"; +const char kCaptureModeIncludeSensitiveString[] = "NORMAL"; +const char kCaptureModeIncludeEverythingString[] = "LOG_BYTES"; const char kStateUninitializedString[] = "UNINITIALIZED"; const char kStateInitializingString[] = "INITIALIZING"; @@ -499,13 +499,13 @@ TEST_F(NetExportFileWriterTest, StartAndStopWithAllCaptureModes) { const net::NetLogCaptureMode capture_modes[3] = { - net::NetLogCaptureMode::Default(), - net::NetLogCaptureMode::IncludeCookiesAndCredentials(), - net::NetLogCaptureMode::IncludeSocketBytes()}; + net::NetLogCaptureMode::kDefault, + net::NetLogCaptureMode::kIncludeSensitive, + net::NetLogCaptureMode::kEverything}; const std::string capture_mode_strings[3] = { - kCaptureModeDefaultString, kCaptureModeIncludeCookiesAndCredentialsString, - kCaptureModeIncludeSocketBytesString}; + kCaptureModeDefaultString, kCaptureModeIncludeSensitiveString, + kCaptureModeIncludeEverythingString}; ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); @@ -555,7 +555,7 @@ ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); ASSERT_TRUE(StartThenVerifyNewState( - base::FilePath(), net::NetLogCaptureMode::Default(), + base::FilePath(), net::NetLogCaptureMode::kDefault, kCaptureModeDefaultString, network_context())); ASSERT_TRUE(StopThenVerifyNewStateAndFile(base::FilePath(), nullptr, @@ -576,7 +576,7 @@ // Start and stop again and make sure the file is back to the size it was // before adding the junk data. ASSERT_TRUE(StartThenVerifyNewState( - base::FilePath(), net::NetLogCaptureMode::Default(), + base::FilePath(), net::NetLogCaptureMode::kDefault, kCaptureModeDefaultString, network_context())); ASSERT_TRUE(StopThenVerifyNewStateAndFile(base::FilePath(), nullptr, @@ -594,7 +594,7 @@ ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); ASSERT_TRUE(StartThenVerifyNewState( - base::FilePath(), net::NetLogCaptureMode::Default(), + base::FilePath(), net::NetLogCaptureMode::kDefault, kCaptureModeDefaultString, network_context())); ASSERT_TRUE(StopThenVerifyNewStateAndFile(base::FilePath(), nullptr, @@ -605,7 +605,7 @@ EXPECT_TRUE(base::GetFileSize(default_log_path(), &stop_file_size)); ASSERT_TRUE(StartThenVerifyNewState( - base::FilePath(), net::NetLogCaptureMode::Default(), + base::FilePath(), net::NetLogCaptureMode::kDefault, kCaptureModeDefaultString, network_context())); net_log()->AddGlobalEntry(net::NetLogEventType::CANCELLED); @@ -631,9 +631,9 @@ EXPECT_TRUE( base::CreateDirectoryAndGetError(custom_log_path.DirName(), nullptr)); - ASSERT_TRUE(StartThenVerifyNewState( - custom_log_path, net::NetLogCaptureMode::Default(), - kCaptureModeDefaultString, network_context())); + ASSERT_TRUE( + StartThenVerifyNewState(custom_log_path, net::NetLogCaptureMode::kDefault, + kCaptureModeDefaultString, network_context())); ASSERT_TRUE(StopThenVerifyNewStateAndFile(custom_log_path, nullptr, kCaptureModeDefaultString)); @@ -642,9 +642,9 @@ int64_t stop_file_size; EXPECT_TRUE(base::GetFileSize(custom_log_path, &stop_file_size)); - ASSERT_TRUE(StartThenVerifyNewState( - custom_log_path, net::NetLogCaptureMode::Default(), - kCaptureModeDefaultString, network_context())); + ASSERT_TRUE( + StartThenVerifyNewState(custom_log_path, net::NetLogCaptureMode::kDefault, + kCaptureModeDefaultString, network_context())); net_log()->AddGlobalEntry(net::NetLogEventType::CANCELLED); @@ -668,7 +668,7 @@ dummy_polled_data->SetString(kDummyPolledDataPath, kDummyPolledDataString); ASSERT_TRUE(StartThenVerifyNewState( - base::FilePath(), net::NetLogCaptureMode::Default(), + base::FilePath(), net::NetLogCaptureMode::kDefault, kCaptureModeDefaultString, network_context())); ASSERT_TRUE(StopThenVerifyNewStateAndFile(base::FilePath(), @@ -753,7 +753,7 @@ // thing since the post-redirect URL will get blocked by the custom handler. run_loop.Run(); ASSERT_TRUE(StartThenVerifyNewState( - base::FilePath(), net::NetLogCaptureMode::Default(), + base::FilePath(), net::NetLogCaptureMode::kDefault, kCaptureModeDefaultString, network_context())); ASSERT_TRUE(StopThenVerifyNewStateAndFile(base::FilePath(), nullptr, @@ -789,9 +789,9 @@ // process from completing, so this ensures that StartNetLog() is received // before |file_writer_| finishes initialization, which means this // should be a no-op. - file_writer()->StartNetLog( - base::FilePath(), net::NetLogCaptureMode::Default(), kMaxLogSizeBytes, - base::CommandLine::StringType(), kChannelString, network_context()); + file_writer()->StartNetLog(base::FilePath(), net::NetLogCaptureMode::kDefault, + kMaxLogSizeBytes, base::CommandLine::StringType(), + kChannelString, network_context()); // Now run the main message loop. Make sure StartNetLog() was ignored by // checking that the next two states are "initializing" followed by @@ -809,8 +809,8 @@ // Call StartNetLog() on |file_writer_| and wait for the state change. ASSERT_TRUE(StartThenVerifyNewState( - base::FilePath(), net::NetLogCaptureMode::IncludeSocketBytes(), - kCaptureModeIncludeSocketBytesString, network_context())); + base::FilePath(), net::NetLogCaptureMode::kEverything, + kCaptureModeIncludeEverythingString, network_context())); // Tell |file_writer_| to stop logging. file_writer()->StopNetLog(nullptr); @@ -820,9 +820,9 @@ // from completing, so this ensures StartNetLog() is received before // |file_writer_| finishes stopping, which means this should be a // no-op. - file_writer()->StartNetLog( - base::FilePath(), net::NetLogCaptureMode::Default(), kMaxLogSizeBytes, - base::CommandLine::StringType(), kChannelString, network_context()); + file_writer()->StartNetLog(base::FilePath(), net::NetLogCaptureMode::kDefault, + kMaxLogSizeBytes, base::CommandLine::StringType(), + kChannelString, network_context()); // Now run the main message loop. Make sure the last StartNetLog() was // ignored by checking that the next two states are "stopping-log" followed by @@ -833,7 +833,7 @@ ASSERT_TRUE(VerifyState(std::move(state), kStateStoppingLogString)); state = test_state_observer()->WaitForNewState(); ASSERT_TRUE(VerifyState(std::move(state), kStateNotLoggingString, true, true, - kCaptureModeIncludeSocketBytesString)); + kCaptureModeIncludeEverythingString)); } TEST_F(NetExportFileWriterTest, HandleCrash) { @@ -841,8 +841,8 @@ ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); ASSERT_TRUE(StartThenVerifyNewState( - base::FilePath(), net::NetLogCaptureMode::IncludeSocketBytes(), - kCaptureModeIncludeSocketBytesString, &fake_network_context)); + base::FilePath(), net::NetLogCaptureMode::kEverything, + kCaptureModeIncludeEverythingString, &fake_network_context)); // Break the pipe, as if network service crashed. fake_network_context.Disconnect();
diff --git a/components/page_info_strings.grdp b/components/page_info_strings.grdp index 8244923..03db48688 100644 --- a/components/page_info_strings.grdp +++ b/components/page_info_strings.grdp
@@ -150,7 +150,7 @@ <message name="IDS_PAGE_INFO_PARTIAL_ADDRESS" desc="Locality with missing state as reported in the EV identity text."> <ph name="CITY">$1<ex>Mountain View</ex></ph>, <ph name="COUNTRY">$2<ex>US</ex></ph> </message> - <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED" desc="The text of the identity section when the page is secured with a valid EV cert."> + <message name="IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED" desc="Describes the legal entity that the current page's HTTPS certificate was issued to. Shown in the certificate area in the Page Info bubble when a HTTPS site with a valid EV certificate is loaded."> Issued to: <ph name="ORGANIZATION">$1<ex>Google LLC</ex></ph> [<ph name="JURISDICTION">$2<ex>US</ex></ph>] </message>
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED.png.sha1 new file mode 100644 index 0000000..439286b --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED.png.sha1
@@ -0,0 +1 @@ +16209fd58d62d7d3b127414833a9b7d304e03e15 \ No newline at end of file
diff --git a/components/password_manager/core/browser/BUILD.gn b/components/password_manager/core/browser/BUILD.gn index bd2db9c9..1c22859 100644 --- a/components/password_manager/core/browser/BUILD.gn +++ b/components/password_manager/core/browser/BUILD.gn
@@ -287,9 +287,14 @@ sources = [ "import/csv_field_parser.cc", "import/csv_field_parser.h", + "import/csv_password.cc", + "import/csv_password.h", ] deps = [ + ":affiliation", "//base", + "//components/autofill/core/common", + "//url", ] } @@ -297,6 +302,7 @@ testonly = true sources = [ "import/csv_field_parser_unittest.cc", + "import/csv_password_unittest.cc", ] deps = [ ":csv",
diff --git a/components/password_manager/core/browser/credential_manager_impl.cc b/components/password_manager/core/browser/credential_manager_impl.cc index 141237c..e24acea3 100644 --- a/components/password_manager/core/browser/credential_manager_impl.cc +++ b/components/password_manager/core/browser/credential_manager_impl.cc
@@ -56,17 +56,16 @@ std::unique_ptr<autofill::PasswordForm> form( CreatePasswordFormFromCredentialInfo(credential, origin)); - std::unique_ptr<autofill::PasswordForm> observed_form = - CreateObservedPasswordFormFromOrigin(origin); - // Create a custom form fetcher without HTTP->HTTPS migration, as well as - // without fetching of suppressed HTTPS credentials on HTTP origins as the API - // is only available on HTTPS origins. - auto form_fetcher = std::make_unique<FormFetcherImpl>( - PasswordStore::FormDigest(*observed_form), client_, false); + std::string signon_realm = origin.GetOrigin().spec(); + PasswordStore::FormDigest observed_digest( + autofill::PasswordForm::Scheme::kHtml, signon_realm, origin); + + // Create a custom form fetcher without HTTP->HTTPS migration as the API is + // only available on HTTPS origins. + auto form_fetcher = + std::make_unique<FormFetcherImpl>(observed_digest, client_, false); form_manager_ = std::make_unique<CredentialManagerPasswordFormManager>( - client_, *observed_form, std::move(form), this, nullptr, - std::move(form_fetcher)); - form_manager_->Init(nullptr); + client_, std::move(form), this, nullptr, std::move(form_fetcher)); } void CredentialManagerImpl::PreventSilentAccess(
diff --git a/components/password_manager/core/browser/credential_manager_password_form_manager.cc b/components/password_manager/core/browser/credential_manager_password_form_manager.cc index f60b3ee16..f72e4f98 100644 --- a/components/password_manager/core/browser/credential_manager_password_form_manager.cc +++ b/components/password_manager/core/browser/credential_manager_password_form_manager.cc
@@ -22,39 +22,26 @@ CredentialManagerPasswordFormManager::CredentialManagerPasswordFormManager( PasswordManagerClient* client, - const PasswordForm& observed_form, - std::unique_ptr<autofill::PasswordForm> saved_form, + std::unique_ptr<PasswordForm> saved_form, CredentialManagerPasswordFormManagerDelegate* delegate, std::unique_ptr<FormSaver> form_saver, std::unique_ptr<FormFetcher> form_fetcher) - : PasswordFormManager(client->GetPasswordManager(), - client, - nullptr, - observed_form, - (form_saver ? std::move(form_saver) - : std::make_unique<FormSaverImpl>( - client->GetPasswordStore())), - form_fetcher.get()), + : NewPasswordFormManager(client, + std::move(saved_form), + std::move(form_fetcher), + (form_saver ? std::move(form_saver) + : std::make_unique<FormSaverImpl>( + client->GetPasswordStore()))), delegate_(delegate), - saved_form_(std::move(saved_form)), - weak_factory_(this) { - DCHECK(saved_form_); - // This condition is only false on iOS. - if (form_fetcher) - form_fetcher->Fetch(); - GrabFetcher(std::move(form_fetcher)); -} + weak_factory_(this) {} -CredentialManagerPasswordFormManager::~CredentialManagerPasswordFormManager() { -} +CredentialManagerPasswordFormManager::~CredentialManagerPasswordFormManager() = + default; void CredentialManagerPasswordFormManager::OnFetchCompleted() { - PasswordFormManager::OnFetchCompleted(); + NewPasswordFormManager::OnFetchCompleted(); - // Mark the form as "preferred", as we've been told by the API that this is - // indeed the credential set that the user used to sign into the site. - saved_form_->preferred = true; - ProvisionallySave(*saved_form_); + CreatePendingCredentials(); // Notify the delegate. This might result in deleting |this|, while // OnFetchCompleted is being called from FormFetcherImpl, owned by |this|. If
diff --git a/components/password_manager/core/browser/credential_manager_password_form_manager.h b/components/password_manager/core/browser/credential_manager_password_form_manager.h index 8dd80c66..d7ae34d 100644 --- a/components/password_manager/core/browser/credential_manager_password_form_manager.h +++ b/components/password_manager/core/browser/credential_manager_password_form_manager.h
@@ -7,7 +7,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "components/password_manager/core/browser/password_form_manager.h" +#include "components/password_manager/core/browser/new_password_form_manager.h" namespace autofill { struct PasswordForm; @@ -27,7 +27,7 @@ // A PasswordFormManager built to handle PasswordForm objects synthesized // by the Credential Manager API. -class CredentialManagerPasswordFormManager : public PasswordFormManager { +class CredentialManagerPasswordFormManager : public NewPasswordFormManager { public: // Given a |client| and an |observed_form|, kick off the process of fetching // matching logins from the password store; if |observed_form| doesn't map to @@ -39,7 +39,6 @@ // This class does not take ownership of |delegate|. CredentialManagerPasswordFormManager( PasswordManagerClient* client, - const autofill::PasswordForm& observed_form, std::unique_ptr<autofill::PasswordForm> saved_form, CredentialManagerPasswordFormManagerDelegate* delegate, std::unique_ptr<FormSaver> form_saver, @@ -57,7 +56,6 @@ void NotifyDelegate(); CredentialManagerPasswordFormManagerDelegate* delegate_; - std::unique_ptr<autofill::PasswordForm> saved_form_; base::WeakPtrFactory<CredentialManagerPasswordFormManager> weak_factory_;
diff --git a/components/password_manager/core/browser/credential_manager_password_form_manager_unittest.cc b/components/password_manager/core/browser/credential_manager_password_form_manager_unittest.cc index e14e727..25bd809 100644 --- a/components/password_manager/core/browser/credential_manager_password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/credential_manager_password_form_manager_unittest.cc
@@ -8,6 +8,7 @@ #include "base/macros.h" #include "base/run_loop.h" +#include "base/strings/utf_string_conversions.h" #include "base/test/scoped_task_environment.h" #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/fake_form_fetcher.h" @@ -17,7 +18,9 @@ #include "testing/gtest/include/gtest/gtest.h" using autofill::PasswordForm; -using ::testing::Invoke; +using base::ASCIIToUTF16; +using testing::_; +using testing::Invoke; namespace password_manager { @@ -28,30 +31,89 @@ MOCK_METHOD0(OnProvisionalSaveComplete, void()); }; +class MockFormSaver : public StubFormSaver { + public: + MockFormSaver() = default; + ~MockFormSaver() override = default; + + // FormSaver: + MOCK_METHOD3(Save, + void(PasswordForm pending, + const std::vector<const PasswordForm*>& matches, + const base::string16& old_password)); + MOCK_METHOD3(Update, + void(PasswordForm pending, + const std::vector<const PasswordForm*>& matches, + const base::string16& old_password)); + + // Convenience downcasting method. + static MockFormSaver& Get(NewPasswordFormManager* form_manager) { + return *static_cast<MockFormSaver*>(form_manager->form_saver()); + } + + private: + DISALLOW_COPY_AND_ASSIGN(MockFormSaver); +}; + +MATCHER_P(FormMatches, form, "") { + return form.signon_realm == arg.signon_realm && form.origin == arg.origin && + form.username_value == arg.username_value && + form.password_value == arg.password_value && + form.scheme == arg.scheme && form.type == arg.type; +} + } // namespace class CredentialManagerPasswordFormManagerTest : public testing::Test { public: - CredentialManagerPasswordFormManagerTest() = default; + CredentialManagerPasswordFormManagerTest() { + form_to_save_.origin = GURL("https://example.com/path"); + form_to_save_.signon_realm = "https://example.com/"; + form_to_save_.username_value = ASCIIToUTF16("user1"); + form_to_save_.password_value = ASCIIToUTF16("pass1"); + form_to_save_.scheme = PasswordForm::Scheme::kHtml; + form_to_save_.type = PasswordForm::Type::kApi; + } protected: + std::unique_ptr<CredentialManagerPasswordFormManager> CreateFormManager( + const PasswordForm& form_to_save) { + std::unique_ptr<FakeFormFetcher> fetcher(new FakeFormFetcher()); + std::unique_ptr<MockFormSaver> saver(new MockFormSaver()); + return std::make_unique<CredentialManagerPasswordFormManager>( + &client_, std::make_unique<PasswordForm>(form_to_save), &delegate_, + std::make_unique<MockFormSaver>(), std::make_unique<FakeFormFetcher>()); + } + + void SetNonFederatedAndNotifyFetchCompleted( + FormFetcher* fetcher, + const std::vector<const PasswordForm*>& non_federated) { + auto* fake_fetcher = static_cast<FakeFormFetcher*>(fetcher); + fake_fetcher->SetNonFederated(non_federated); + fake_fetcher->NotifyFetchCompleted(); + // It is required because of PostTask in + // CredentialManagerPasswordFormManager::OnFetchCompleted + base::RunLoop().RunUntilIdle(); + } + // Necessary for callbacks, and for TestAutofillDriver. base::test::ScopedTaskEnvironment task_environment_; StubPasswordManagerClient client_; + MockDelegate delegate_; + PasswordForm form_to_save_; DISALLOW_COPY_AND_ASSIGN(CredentialManagerPasswordFormManagerTest); }; // Test that aborting early does not cause use after free. TEST_F(CredentialManagerPasswordFormManagerTest, AbortEarly) { - PasswordForm observed_form; + auto saved_form = std::make_unique<PasswordForm>(); + saved_form->password_value = base::ASCIIToUTF16("password"); MockDelegate delegate; auto form_manager = std::make_unique<CredentialManagerPasswordFormManager>( - &client_, observed_form, std::make_unique<PasswordForm>(observed_form), - &delegate, std::make_unique<StubFormSaver>(), - std::make_unique<FakeFormFetcher>()); - form_manager->Init(nullptr); + &client_, std::move(saved_form), &delegate, + std::make_unique<StubFormSaver>(), std::make_unique<FakeFormFetcher>()); auto deleter = [&form_manager]() { form_manager.reset(); }; @@ -75,15 +137,68 @@ // Ensure that GetCredentialSource is actually overriden and returns the proper // value. TEST_F(CredentialManagerPasswordFormManagerTest, GetCredentialSource) { - PasswordForm observed_form; MockDelegate delegate; auto form_manager = std::make_unique<CredentialManagerPasswordFormManager>( - &client_, observed_form, std::make_unique<PasswordForm>(observed_form), - &delegate, std::make_unique<StubFormSaver>(), - std::make_unique<FakeFormFetcher>()); - form_manager->Init(nullptr); + &client_, std::make_unique<PasswordForm>(), &delegate, + std::make_unique<StubFormSaver>(), std::make_unique<FakeFormFetcher>()); ASSERT_EQ(metrics_util::CredentialSourceType::kCredentialManagementAPI, form_manager->GetCredentialSource()); } +TEST_F(CredentialManagerPasswordFormManagerTest, SaveCredentialAPIEmptyStore) { + std::unique_ptr<CredentialManagerPasswordFormManager> form_manager = + CreateFormManager(form_to_save_); + MockFormSaver& form_saver = MockFormSaver::Get(form_manager.get()); + EXPECT_CALL(delegate_, OnProvisionalSaveComplete()); + SetNonFederatedAndNotifyFetchCompleted(form_manager->GetFormFetcher(), {}); + EXPECT_TRUE(form_manager->IsNewLogin()); + EXPECT_TRUE(form_manager->is_submitted()); + + EXPECT_CALL(form_saver, Save(FormMatches(form_to_save_), _, _)); + form_manager->Save(); +} + +TEST_F(CredentialManagerPasswordFormManagerTest, + SaveCredentialAPINonEmptyStore) { + // Simulate that the password store has crendentials with different + // username/password as a submitted one. + PasswordForm saved_match = form_to_save_; + saved_match.username_value += ASCIIToUTF16("1"); + saved_match.password_value += ASCIIToUTF16("1"); + + std::unique_ptr<CredentialManagerPasswordFormManager> form_manager = + CreateFormManager(form_to_save_); + MockFormSaver& form_saver = MockFormSaver::Get(form_manager.get()); + + EXPECT_CALL(delegate_, OnProvisionalSaveComplete()); + SetNonFederatedAndNotifyFetchCompleted(form_manager->GetFormFetcher(), + {&saved_match}); + EXPECT_TRUE(form_manager->IsNewLogin()); + EXPECT_TRUE(form_manager->is_submitted()); + EXPECT_EQ(form_to_save_.origin, form_manager->GetOrigin()); + + EXPECT_CALL(form_saver, Save(FormMatches(form_to_save_), _, _)); + form_manager->Save(); +} + +TEST_F(CredentialManagerPasswordFormManagerTest, UpdatePasswordCredentialAPI) { + // Simulate that the submitted credential has the same username but the + // different password from already saved one. + PasswordForm saved_match = form_to_save_; + saved_match.password_value += ASCIIToUTF16("1"); + + std::unique_ptr<CredentialManagerPasswordFormManager> form_manager = + CreateFormManager(form_to_save_); + MockFormSaver& form_saver = MockFormSaver::Get(form_manager.get()); + + EXPECT_CALL(delegate_, OnProvisionalSaveComplete()); + SetNonFederatedAndNotifyFetchCompleted(form_manager->GetFormFetcher(), + {&saved_match}); + EXPECT_FALSE(form_manager->IsNewLogin()); + EXPECT_TRUE(form_manager->is_submitted()); + + EXPECT_CALL(form_saver, Update(FormMatches(form_to_save_), _, _)); + form_manager->Save(); +} + } // namespace password_manager
diff --git a/components/password_manager/core/browser/form_parsing/form_parser.cc b/components/password_manager/core/browser/form_parsing/form_parser.cc index 26bcf770..0903d07 100644 --- a/components/password_manager/core/browser/form_parsing/form_parser.cc +++ b/components/password_manager/core/browser/form_parsing/form_parser.cc
@@ -901,9 +901,7 @@ result->action = form_data.action; result->form_data = form_data; result->all_possible_passwords = std::move(all_possible_passwords); - // TODO(crbug.com/881346) Rename PasswordForm::other_possible_usernames to - // all_possible_usernames once the old parser is gone. - result->other_possible_usernames = std::move(all_possible_usernames); + result->all_possible_usernames = std::move(all_possible_usernames); result->scheme = PasswordForm::Scheme::kHtml; result->preferred = false; result->blacklisted_by_user = false;
diff --git a/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc b/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc index cdae5c0c1..fad8926f 100644 --- a/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc +++ b/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc
@@ -377,7 +377,7 @@ CheckPasswordFormFields(*parsed_form, form_data, expected_ids); CheckAllValuesUnique(parsed_form->all_possible_passwords); - CheckAllValuesUnique(parsed_form->other_possible_usernames); + CheckAllValuesUnique(parsed_form->all_possible_usernames); if (test_case.number_of_all_possible_passwords >= 0) { EXPECT_EQ( static_cast<size_t>(test_case.number_of_all_possible_passwords), @@ -390,11 +390,11 @@ if (test_case.number_of_all_possible_usernames >= 0) { EXPECT_EQ( static_cast<size_t>(test_case.number_of_all_possible_usernames), - parsed_form->other_possible_usernames.size()); + parsed_form->all_possible_usernames.size()); } if (test_case.all_possible_usernames) { EXPECT_EQ(*test_case.all_possible_usernames, - parsed_form->other_possible_usernames); + parsed_form->all_possible_usernames); } if (mode == FormDataParser::Mode::kSaving) { EXPECT_EQ(test_case.fallback_only, parsed_form->only_for_fallback);
diff --git a/components/password_manager/core/browser/form_saver_impl_unittest.cc b/components/password_manager/core/browser/form_saver_impl_unittest.cc index f1f8dbe7..d117476 100644 --- a/components/password_manager/core/browser/form_saver_impl_unittest.cc +++ b/components/password_manager/core/browser/form_saver_impl_unittest.cc
@@ -367,7 +367,7 @@ observed.username_element = ASCIIToUTF16("user"); observed.password_value = ASCIIToUTF16("12345"); observed.password_element = ASCIIToUTF16("password"); - observed.other_possible_usernames = { + observed.all_possible_usernames = { {ASCIIToUTF16("user2"), ASCIIToUTF16("field")}}; observed.origin = GURL("https://www.example.com/foobar");
diff --git a/components/password_manager/core/browser/import/csv_password.cc b/components/password_manager/core/browser/import/csv_password.cc new file mode 100644 index 0000000..4b0cf86 --- /dev/null +++ b/components/password_manager/core/browser/import/csv_password.cc
@@ -0,0 +1,99 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/password_manager/core/browser/import/csv_password.h" + +#include <utility> + +#include "base/logging.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" +#include "components/password_manager/core/browser/import/csv_field_parser.h" +#include "url/gurl.h" + +namespace password_manager { + +using ::autofill::PasswordForm; + +CSVPassword::CSVPassword() = default; + +CSVPassword::CSVPassword(ColumnMap map, base::StringPiece csv_row) + : map_(std::move(map)), row_(csv_row) {} + +CSVPassword::CSVPassword(const CSVPassword&) = default; + +CSVPassword::CSVPassword(CSVPassword&&) = default; + +CSVPassword& CSVPassword::operator=(const CSVPassword&) = default; + +CSVPassword& CSVPassword::operator=(CSVPassword&&) = default; + +CSVPassword::~CSVPassword() = default; + +bool CSVPassword::Parse(PasswordForm* form) const { + // |map_| must be an (1) injective and (2) surjective (3) partial map. (3) is + // enforced by its type, (2) is checked later in the code and (1) follows from + // (2) and the following size() check. + if (map_.size() != kLabelCount) + return false; + + size_t field_idx = 0; + CSVFieldParser parser(row_); + GURL origin; + base::StringPiece username; + base::StringPiece password; + bool username_set = false; + while (parser.HasMoreFields()) { + base::StringPiece field; + if (!parser.NextField(&field)) + return false; + auto meaning_it = map_.find(field_idx++); + if (meaning_it == map_.end()) + continue; + switch (meaning_it->second) { + case Label::kOrigin: + if (!base::IsStringASCII(field)) + return false; + origin = GURL(field); + break; + case Label::kUsername: + username = field; + username_set = true; + break; + case Label::kPassword: + password = field; + break; + } + } + // While all of origin, username and password must be set in the CSV data row, + // username is permitted to be an empty string, while password and origin are + // not. + if (!origin.is_valid() || !username_set || password.empty()) + return false; + if (!form) + return true; + // There is currently no way to import non-HTML credentials. + form->scheme = PasswordForm::Scheme::kHtml; + // GURL::GetOrigin() returns an empty GURL for Android credentials due + // to the non-standard scheme ("android://"). Hence the following + // explicit check is necessary to set |signon_realm| correctly for both + // regular and Android credentials. + form->signon_realm = IsValidAndroidFacetURI(origin.spec()) + ? origin.spec() + : origin.GetOrigin().spec(); + form->origin = std::move(origin); + form->username_value = base::UTF8ToUTF16(username); + form->password_value = base::UTF8ToUTF16(password); + return true; +} + +PasswordForm CSVPassword::ParseValid() const { + PasswordForm result; + bool success = Parse(&result); + DCHECK(success); + return result; +} + +} // namespace password_manager
diff --git a/components/password_manager/core/browser/import/csv_password.h b/components/password_manager/core/browser/import/csv_password.h new file mode 100644 index 0000000..e36162d0 --- /dev/null +++ b/components/password_manager/core/browser/import/csv_password.h
@@ -0,0 +1,56 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_IMPORT_CSV_PASSWORD_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_IMPORT_CSV_PASSWORD_H_ + +#include <stddef.h> + +#include "base/containers/flat_map.h" +#include "base/strings/string_piece.h" +#include "components/autofill/core/common/password_form.h" + +namespace password_manager { + +// CSVPassword is a wrapper around one CSV line representing a credential. +// For more details, see +// https://docs.google.com/document/d/1wsZBl93S_WGaXZqrqq5SP08LVZ0zDKf6e9nlptyl9AY/edit?usp=sharing. +class CSVPassword { + public: + enum class Label { kOrigin, kUsername, kPassword }; + using ColumnMap = base::flat_map<size_t, Label>; + + // Number of values in the Label enum. + static constexpr size_t kLabelCount = 3; + + CSVPassword(); + explicit CSVPassword(ColumnMap map, base::StringPiece csv_row); + CSVPassword(const CSVPassword&); + CSVPassword(CSVPassword&&); + CSVPassword& operator=(const CSVPassword&); + CSVPassword& operator=(CSVPassword&&); + ~CSVPassword(); + + // Returns whether the associated CSV row can be parsed successfully. + // If returning true and |form| is not null, it also stores the parsed result + // in |*form|. It does not return base::Optional<PasswordForm> for efficiency + // reasons in cases when the parsed form is not needed. + bool Parse(autofill::PasswordForm* form) const; + // Convenience wrapper around Parse() for cases known to be correctly + // parseable. + autofill::PasswordForm ParseValid() const; + + private: + // The members |map_| and |row_| are only modified in constructor or + // operator=(). + + // |map_| stores the meaning of particular columns in the row. + ColumnMap map_; + // |row_| contains the CSV row from which the PasswordForm is parsed. + base::StringPiece row_; +}; + +} // namespace password_manager + +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_IMPORT_CSV_PASSWORD_H_
diff --git a/components/password_manager/core/browser/import/csv_password_unittest.cc b/components/password_manager/core/browser/import/csv_password_unittest.cc new file mode 100644 index 0000000..df6970b --- /dev/null +++ b/components/password_manager/core/browser/import/csv_password_unittest.cc
@@ -0,0 +1,247 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/password_manager/core/browser/import/csv_password.h" + +#include <string> +#include <utility> + +#include "base/strings/utf_string_conversions.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace password_manager { + +using ::autofill::PasswordForm; + +TEST(CSVPassword, Construction) { + // Default. + CSVPassword empty; + EXPECT_FALSE(empty.Parse(nullptr)); + + // From CSV. + CSVPassword::ColumnMap col_map = { + {0, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kUsername}, + {2, CSVPassword::Label::kPassword}, + }; + CSVPassword csv_pwd(col_map, "http://example.com,user,password"); + PasswordForm result = csv_pwd.ParseValid(); + GURL expected_origin("http://example.com"); + EXPECT_EQ(expected_origin, result.origin); + EXPECT_EQ(expected_origin.GetOrigin().spec(), result.signon_realm); + EXPECT_EQ(base::ASCIIToUTF16("user"), result.username_value); + EXPECT_EQ(base::ASCIIToUTF16("password"), result.password_value); + + // Copy, move and operator=. + CSVPassword copy = csv_pwd; + EXPECT_EQ(copy.ParseValid(), csv_pwd.ParseValid()); + + CSVPassword moved = std::move(copy); + EXPECT_EQ(moved.ParseValid(), csv_pwd.ParseValid()); + + CSVPassword target; + target = csv_pwd; + EXPECT_EQ(target.ParseValid(), csv_pwd.ParseValid()); + target = std::move(moved); + EXPECT_EQ(target.ParseValid(), csv_pwd.ParseValid()); +} + +struct TestCase { + std::string name; + // Input. + CSVPassword::ColumnMap map; + std::string csv; + // Expected. + std::string origin; + std::string signon_realm; + std::string username; + std::string password; +}; + +class TestCaseBuilder { + public: + TestCaseBuilder(std::string name) { test_case_.name = std::move(name); } + + ~TestCaseBuilder() = default; + + TestCaseBuilder& Map(CSVPassword::ColumnMap map) { + test_case_.map = std::move(map); + return *this; + } + + TestCaseBuilder& CSV(std::string csv) { + test_case_.csv = std::move(csv); + return *this; + } + + TestCaseBuilder& Origin(std::string origin) { + test_case_.origin = std::move(origin); + return *this; + } + + TestCaseBuilder& SignonRealm(std::string signon_realm) { + test_case_.signon_realm = std::move(signon_realm); + return *this; + } + + TestCaseBuilder& Username(std::string username) { + test_case_.username = std::move(username); + return *this; + } + + TestCaseBuilder& Password(std::string password) { + test_case_.password = std::move(password); + return *this; + } + + TestCase Build() { return std::move(test_case_); } + + private: + TestCase test_case_; +}; + +class CSVPasswordTestSuccess : public ::testing::TestWithParam<TestCase> {}; + +TEST_P(CSVPasswordTestSuccess, Parse) { + const TestCase& test_case = GetParam(); + SCOPED_TRACE(test_case.name); + CSVPassword csv_pwd(test_case.map, test_case.csv); + EXPECT_TRUE(csv_pwd.Parse(nullptr)); + + PasswordForm result = csv_pwd.ParseValid(); + + GURL expected_origin(test_case.origin); + EXPECT_EQ(expected_origin, result.origin); + EXPECT_EQ(expected_origin.GetOrigin().spec(), result.signon_realm); + + EXPECT_EQ(base::ASCIIToUTF16(test_case.username), result.username_value); + EXPECT_EQ(base::ASCIIToUTF16(test_case.password), result.password_value); + + PasswordForm result2 = csv_pwd.ParseValid(); + EXPECT_EQ(result, result2); +} + +INSTANTIATE_TEST_SUITE_P( + , + CSVPasswordTestSuccess, + ::testing::Values(TestCaseBuilder("all columns specified") + .Map({{0, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kUsername}, + {2, CSVPassword::Label::kPassword}}) + .CSV("http://example.com,user,password") + .Origin("http://example.com") + .SignonRealm("http://example.com/") + .Username("user") + .Password("password") + .Build(), + TestCaseBuilder("empty username") + .Map({{0, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kPassword}, + {2, CSVPassword::Label::kUsername}}) + .CSV("http://example.com,password,") + .Origin("http://example.com") + .SignonRealm("http://example.com/") + .Username("") + .Password("password") + .Build(), + TestCaseBuilder("permuted and inserted columns") + .Map({{2, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kUsername}, + {4, CSVPassword::Label::kPassword}}) + .CSV("X,the-user,https://example.org,Y,pwd") + .Origin("https://example.org") + .SignonRealm("https://example.org/") + .Username("the-user") + .Password("pwd") + .Build(), + TestCaseBuilder("Android") + .Map({{2, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kUsername}, + {0, CSVPassword::Label::kPassword}}) + .CSV("pwd,the-user,android://example,Y,X") + .Origin("android://example") + .SignonRealm("android://example") + .Username("the-user") + .Password("pwd") + .Build(), + TestCaseBuilder("path discarded") + .Map({{2, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kUsername}, + {0, CSVPassword::Label::kPassword}}) + .CSV("password,user,http://example.com/path") + .Origin("http://example.com/path") + .SignonRealm("http://example.com/") + .Username("user") + .Password("password") + .Build())); + +class CSVPasswordTestFailure : public ::testing::TestWithParam<TestCase> {}; + +TEST_P(CSVPasswordTestFailure, Parse) { + const TestCase& test_case = GetParam(); + SCOPED_TRACE(test_case.name); + EXPECT_FALSE(CSVPassword(test_case.map, test_case.csv).Parse(nullptr)); +} + +INSTANTIATE_TEST_SUITE_P( + , + CSVPasswordTestFailure, + ::testing::Values(TestCaseBuilder("no columns specified") + .Map({}) + .CSV("http://example.com,user,password") + .Build(), + TestCaseBuilder("not ASCII") + .Map({{0, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kUsername}, + {2, CSVPassword::Label::kPassword}}) + .CSV("http://example.com/Å™,user,password") + .Build(), + TestCaseBuilder("no origin in map") + .Map({{1, CSVPassword::Label::kUsername}, + {2, CSVPassword::Label::kPassword}}) + .CSV("http://example.com,user,password") + .Build(), + TestCaseBuilder("no username in map") + .Map({{0, CSVPassword::Label::kOrigin}, + {2, CSVPassword::Label::kPassword}}) + .CSV("http://example.com,user,password") + .Build(), + TestCaseBuilder("no password in map") + .Map({{0, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kUsername}}) + .CSV("http://example.com,user,password") + .Build(), + TestCaseBuilder("no origin in CSV") + .Map({{0, CSVPassword::Label::kUsername}, + {1, CSVPassword::Label::kPassword}, + {2, CSVPassword::Label::kOrigin}}) + .CSV("user,password") + .Build(), + TestCaseBuilder("no username in CSV") + .Map({{0, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kPassword}, + {2, CSVPassword::Label::kUsername}}) + .CSV("http://example.com,password") + .Build(), + TestCaseBuilder("no password in CSV") + .Map({{0, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kUsername}, + {2, CSVPassword::Label::kPassword}}) + .CSV("http://example.com,user") + .Build(), + TestCaseBuilder("malformed CSV") + .Map({{0, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kUsername}, + {2, CSVPassword::Label::kPassword}}) + .CSV("\"") + .Build(), + TestCaseBuilder("map not injective") + .Map({{0, CSVPassword::Label::kOrigin}, + {1, CSVPassword::Label::kUsername}, + {2, CSVPassword::Label::kPassword}, + {3, CSVPassword::Label::kUsername}}) + .CSV("http://example.com,user,pwd,user2") + .Build())); + +} // namespace password_manager
diff --git a/components/password_manager/core/browser/login_database.cc b/components/password_manager/core/browser/login_database.cc index b99abea2..0735964 100644 --- a/components/password_manager/core/browser/login_database.cc +++ b/components/password_manager/core/browser/login_database.cc
@@ -188,7 +188,7 @@ s->BindInt(COLUMN_GENERATION_UPLOAD_STATUS, static_cast<int>(form.generation_upload_status)); base::Pickle usernames_pickle = - SerializeValueElementPairs(form.other_possible_usernames); + SerializeValueElementPairs(form.all_possible_usernames); s->BindBlob(COLUMN_POSSIBLE_USERNAME_PAIRS, usernames_pickle.data(), usernames_pickle.size()); } @@ -1077,7 +1077,7 @@ s.BindInt(next_param++, form.skip_zero_click); s.BindInt(next_param++, static_cast<int>(form.generation_upload_status)); base::Pickle username_pickle = - SerializeValueElementPairs(form.other_possible_usernames); + SerializeValueElementPairs(form.all_possible_usernames); s.BindBlob(next_param++, username_pickle.data(), username_pickle.size()); // NOTE: Add new fields here unless the field is a part of the unique key. // If so, add new field below. @@ -1279,7 +1279,7 @@ base::Pickle pickle( static_cast<const char*>(s.ColumnBlob(COLUMN_POSSIBLE_USERNAME_PAIRS)), s.ColumnByteLength(COLUMN_POSSIBLE_USERNAME_PAIRS)); - form->other_possible_usernames = DeserializeValueElementPairs(pickle); + form->all_possible_usernames = DeserializeValueElementPairs(pickle); } form->times_used = s.ColumnInt(COLUMN_TIMES_USED); if (s.ColumnByteLength(COLUMN_FORM_DATA)) {
diff --git a/components/password_manager/core/browser/login_database_unittest.cc b/components/password_manager/core/browser/login_database_unittest.cc index 22609bf..e150ca1 100644 --- a/components/password_manager/core/browser/login_database_unittest.cc +++ b/components/password_manager/core/browser/login_database_unittest.cc
@@ -1287,7 +1287,7 @@ form.action = GURL("http://accounts.google.com/login"); form.password_value = ASCIIToUTF16("my_new_password"); form.preferred = false; - form.other_possible_usernames.push_back(autofill::ValueElementPair( + form.all_possible_usernames.push_back(autofill::ValueElementPair( ASCIIToUTF16("my_new_username"), ASCIIToUTF16("new_username_id"))); form.times_used = 20; form.submit_element = ASCIIToUTF16("submit_element");
diff --git a/components/password_manager/core/browser/new_password_form_manager.cc b/components/password_manager/core/browser/new_password_form_manager.cc index ceda1d6..14d42c2 100644 --- a/components/password_manager/core/browser/new_password_form_manager.cc +++ b/components/password_manager/core/browser/new_password_form_manager.cc
@@ -62,7 +62,7 @@ ValueElementPair PasswordToSave(const PasswordForm& form) { if (form.new_password_value.empty()) { - DCHECK(!form.password_value.empty()); + DCHECK(!form.password_value.empty() || form.IsFederatedCredential()); return {form.password_value, form.password_element}; } return {form.new_password_value, form.new_password_element}; @@ -84,9 +84,9 @@ } // Filter sensitive information, duplicates and |username_value| out from -// |form->other_possible_usernames|. +// |form->all_possible_usernames|. void SanitizePossibleUsernames(PasswordForm* form) { - auto& usernames = form->other_possible_usernames; + auto& usernames = form->all_possible_usernames; // Deduplicate. std::sort(usernames.begin(), usernames.end()); @@ -155,7 +155,7 @@ std::move(form_saver), nullptr /* metrics_recorder */, observed_http_auth_digest) { - observed_http_auth_digest_ = std::move(observed_http_auth_digest); + observed_not_web_form_digest_ = std::move(observed_http_auth_digest); form_fetcher_->AddConsumer(this); } @@ -208,9 +208,8 @@ } const GURL& NewPasswordFormManager::GetOrigin() const { - if (IsHttpAuth()) - return observed_http_auth_digest_->origin; - return observed_form_.url; + return observed_not_web_form_digest_ ? observed_not_web_form_digest_->origin + : observed_form_.url; } const std::map<base::string16, const PasswordForm*>& @@ -325,11 +324,11 @@ // uploaded. votes_uploader_.set_has_username_edited_vote(false); if (!new_username.empty()) { - // |other_possible_usernames| has all possible usernames. + // |all_possible_usernames| has all possible usernames. // TODO(crbug.com/831123): rename to |all_possible_usernames| when the old // parser is gone. for (const auto& possible_username : - parsed_submitted_form_->other_possible_usernames) { + parsed_submitted_form_->all_possible_usernames) { if (possible_username.first == new_username) { parsed_submitted_form_->username_element = possible_username.second; votes_uploader_.set_has_username_edited_vote(true); @@ -392,16 +391,17 @@ if (!new_blacklisted_) { new_blacklisted_ = std::make_unique<PasswordForm>(); - if (IsHttpAuth()) { - new_blacklisted_->origin = observed_http_auth_digest_->origin; + if (observed_not_web_form_digest_) { + new_blacklisted_->origin = observed_not_web_form_digest_->origin; // GetSignonRealm is not suitable for http auth credentials. - new_blacklisted_->signon_realm = observed_http_auth_digest_->signon_realm; - new_blacklisted_->scheme = observed_http_auth_digest_->scheme; + new_blacklisted_->signon_realm = + IsHttpAuth() ? observed_not_web_form_digest_->signon_realm + : GetSignonRealm(observed_not_web_form_digest_->origin); } else { new_blacklisted_->origin = observed_form_.url; new_blacklisted_->signon_realm = GetSignonRealm(observed_form_.url); - new_blacklisted_->scheme = PasswordForm::Scheme::kHtml; } + new_blacklisted_->scheme = GetScheme(); blacklisted_matches_.push_back(new_blacklisted_.get()); } *new_blacklisted_ = form_saver_->PermanentlyBlacklist( @@ -567,12 +567,29 @@ return result; } +NewPasswordFormManager::NewPasswordFormManager( + PasswordManagerClient* client, + std::unique_ptr<PasswordForm> saved_form, + std::unique_ptr<FormFetcher> form_fetcher, + std::unique_ptr<FormSaver> form_saver) + : NewPasswordFormManager(client, + form_fetcher.get(), + std::move(form_saver), + nullptr /* metrics_recorder */, + PasswordStore::FormDigest(*saved_form)) { + observed_not_web_form_digest_ = PasswordStore::FormDigest(*saved_form); + parsed_submitted_form_ = std::move(saved_form); + is_submitted_ = true; + owned_form_fetcher_ = std::move(form_fetcher), + form_fetcher_->AddConsumer(this); + if (form_fetcher_) + form_fetcher_->Fetch(); +} + void NewPasswordFormManager::OnFetchCompleted() { received_stored_credentials_time_ = TimeTicks::Now(); std::vector<const PasswordForm*> matches; - PasswordForm::Scheme observed_form_scheme = - observed_http_auth_digest_ ? observed_http_auth_digest_->scheme - : PasswordForm::Scheme::kHtml; + PasswordForm::Scheme observed_form_scheme = GetScheme(); for (const auto* match : form_fetcher_->GetNonFederatedMatches()) { if (match->scheme == observed_form_scheme) matches.push_back(match); @@ -587,6 +604,12 @@ autofills_left_ = kMaxTimesAutofill; + if (IsCredentialAPISave()) { + // This is saving with credential API, there is no form to fill, so no + // filling required. + return; + } + if (IsHttpAuth()) { // No server prediction for http auth, so no need to wait. FillHttpAuth(); @@ -636,7 +659,7 @@ const PasswordForm& submitted_form) { if (!IsHttpAuth()) return false; - if (!(*observed_http_auth_digest_ == + if (!(*observed_not_web_form_digest_ == PasswordStore::FormDigest(submitted_form))) return false; @@ -647,7 +670,16 @@ } bool NewPasswordFormManager::IsHttpAuth() const { - return !!observed_http_auth_digest_; + return GetScheme() != PasswordForm::Scheme::kHtml; +} + +bool NewPasswordFormManager::IsCredentialAPISave() const { + return observed_not_web_form_digest_ && !IsHttpAuth(); +} + +PasswordForm::Scheme NewPasswordFormManager::GetScheme() const { + return observed_not_web_form_digest_ ? observed_not_web_form_digest_->scheme + : PasswordForm::Scheme::kHtml; } void NewPasswordFormManager::ProcessServerPredictions( @@ -851,6 +883,8 @@ } } +// TODO(https://crbug.com/831123): move this function to the proper place +// corresponding to its place in the header. void NewPasswordFormManager::CreatePendingCredentials() { DCHECK(is_submitted_); // TODO(https://crbug.com/831123): Process correctly the case when saved @@ -948,10 +982,11 @@ void NewPasswordFormManager::CreatePendingCredentialsForNewCredentials( const PasswordForm& submitted_password_form, const base::string16& password_element) { - if (IsHttpAuth()) { + if (IsHttpAuth() || IsCredentialAPISave()) { pending_credentials_ = submitted_password_form; return; } + // TODO(https://crbug.com/831123): Replace parsing of the observed form with // usage of already parsed submitted form. std::unique_ptr<PasswordForm> parsed_observed_form = @@ -962,8 +997,8 @@ pending_credentials_.username_element = submitted_password_form.username_element; pending_credentials_.username_value = submitted_password_form.username_value; - pending_credentials_.other_possible_usernames = - submitted_password_form.other_possible_usernames; + pending_credentials_.all_possible_usernames = + submitted_password_form.all_possible_usernames; pending_credentials_.all_possible_passwords = submitted_password_form.all_possible_passwords; @@ -978,7 +1013,7 @@ void NewPasswordFormManager::ProcessUpdate() { DCHECK_EQ(FormFetcher::State::NOT_WAITING, form_fetcher_->GetState()); - DCHECK(preferred_match_ || !pending_credentials_.federation_origin.opaque()); + DCHECK(preferred_match_ || pending_credentials_.IsFederatedCredential()); // If we're doing an Update, we either autofilled correctly and need to // update the stats, or the user typed in a new password for autofilled // username, or the user selected one of the non-preferred matches, @@ -1103,9 +1138,7 @@ std::vector<const PasswordForm*> NewPasswordFormManager::GetAllMatches() const { std::vector<const autofill::PasswordForm*> result = form_fetcher_->GetNonFederatedMatches(); - PasswordForm::Scheme observed_form_scheme = - observed_http_auth_digest_ ? observed_http_auth_digest_->scheme - : PasswordForm::Scheme::kHtml; + PasswordForm::Scheme observed_form_scheme = GetScheme(); base::EraseIf(result, [observed_form_scheme](const auto* form) { return form->scheme != observed_form_scheme; }); @@ -1115,8 +1148,10 @@ void NewPasswordFormManager::SavePendingToStore(bool update) { const PasswordForm* saved_form = password_manager_util::GetMatchForUpdating( *parsed_submitted_form_, best_matches_); - if (update || password_overridden_) + if ((update || password_overridden_) && + !pending_credentials_.IsFederatedCredential()) { DCHECK(saved_form); + } base::string16 old_password = saved_form ? saved_form->password_value : base::string16(); if (HasGeneratedPassword()) {
diff --git a/components/password_manager/core/browser/new_password_form_manager.h b/components/password_manager/core/browser/new_password_form_manager.h index b00cb5d..a52bd19 100644 --- a/components/password_manager/core/browser/new_password_form_manager.h +++ b/components/password_manager/core/browser/new_password_form_manager.h
@@ -109,6 +109,13 @@ // Returns true if |*this| manages http authentication. bool IsHttpAuth() const; + // Returns true if |*this| manages saving with Credentials API. This class is + // not used for filling with Credentials API. + bool IsCredentialAPISave() const; + + // Returns scheme of the observed form or http authentication. + autofill::PasswordForm::Scheme GetScheme() const; + // Selects from |predictions| predictions that corresponds to // |observed_form_|, initiates filling and stores predictions in // |predictions_|. @@ -209,9 +216,19 @@ } protected: + // Constructor for Credentials API. + NewPasswordFormManager(PasswordManagerClient* client, + std::unique_ptr<autofill::PasswordForm> saved_form, + std::unique_ptr<FormFetcher> form_fetcher, + std::unique_ptr<FormSaver> form_saver); + // FormFetcher::Consumer: void OnFetchCompleted() override; + // Create pending credentials from |parsed_submitted_form_| and forms received + // from the password store. + void CreatePendingCredentials(); + private: // Delegating constructor. NewPasswordFormManager( @@ -239,10 +256,6 @@ // the autofill server responding to the lookup request. void ReportTimeBetweenStoreAndServerUMA(); - // Create pending credentials from |submitted_form_| and forms received from - // the password store. - void CreatePendingCredentials(); - // Create pending credentials from provisionally saved form when this form // represents credentials that were not previosly saved. void CreatePendingCredentialsForNewCredentials( @@ -290,10 +303,12 @@ base::WeakPtr<PasswordManagerDriver> driver_; // TODO(https://crbug.com/943045): use std::variant for keeping - // |observed_form_| and |observed_http_auth_digest_|. + // |observed_form_| and |observed_not_web_form_digest_|. autofill::FormData observed_form_; - base::Optional<PasswordStore::FormDigest> observed_http_auth_digest_; + // Used for retrieving credentials in case http authentication or Credentials + // API. + base::Optional<PasswordStore::FormDigest> observed_not_web_form_digest_; // Set of nonblacklisted PasswordForms from the DB that best match the form // being managed by |this|, indexed by username. The PasswordForms are owned
diff --git a/components/password_manager/core/browser/new_password_form_manager_unittest.cc b/components/password_manager/core/browser/new_password_form_manager_unittest.cc index 86e4129..30b4ad3 100644 --- a/components/password_manager/core/browser/new_password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/new_password_form_manager_unittest.cc
@@ -374,7 +374,7 @@ // Creates NewPasswordFormManager and sets it to |form_manager_| for // |base_auth_observed_form|. Along the way a new |fetcher_| is created. - void CreateFormManagerForHttpAuthForm( + void CreateFormManagerForNonWebForm( const PasswordForm& base_auth_observed_form) { fetcher_.reset(new FakeFormFetcher()); fetcher_->Fetch(); @@ -1871,7 +1871,7 @@ EXPECT_CALL(driver_, FillPasswordForm(_)).Times(0); EXPECT_CALL(client_, AutofillHttpAuth(_, _)).Times(0); - CreateFormManagerForHttpAuthForm(http_auth_form); + CreateFormManagerForNonWebForm(http_auth_form); MockFormSaver& form_saver = MockFormSaver::Get(form_manager_.get()); std::vector<const PasswordForm*> saved_matches; @@ -1903,7 +1903,7 @@ PasswordForm http_auth_form = parsed_observed_form_; http_auth_form.scheme = PasswordForm::Scheme::kBasic; - CreateFormManagerForHttpAuthForm(http_auth_form); + CreateFormManagerForNonWebForm(http_auth_form); const base::string16 username = ASCIIToUTF16("user1"); const base::string16 password = ASCIIToUTF16("pass1"); @@ -1924,7 +1924,7 @@ PasswordForm http_auth_form = parsed_observed_form_; http_auth_form.scheme = PasswordForm::Scheme::kBasic; - CreateFormManagerForHttpAuthForm(http_auth_form); + CreateFormManagerForNonWebForm(http_auth_form); MockFormSaver& form_saver = MockFormSaver::Get(form_manager_.get()); PasswordForm saved_http_auth_form = http_auth_form; @@ -1963,7 +1963,7 @@ http_auth_form.signon_realm += "my-auth-realm"; http_auth_form.scheme = PasswordForm::Scheme::kBasic; - CreateFormManagerForHttpAuthForm(http_auth_form); + CreateFormManagerForNonWebForm(http_auth_form); MockFormSaver& form_saver = MockFormSaver::Get(form_manager_.get()); // Simulate that the user submits http auth credentials.
diff --git a/components/password_manager/core/browser/password_form_manager.cc b/components/password_manager/core/browser/password_form_manager.cc index 81a50d01..3a0a2e1 100644 --- a/components/password_manager/core/browser/password_form_manager.cc +++ b/components/password_manager/core/browser/password_form_manager.cc
@@ -56,9 +56,9 @@ namespace password_form_manager_helpers { // Filter sensitive information, duplicates and |username_value| out from -// |form->other_possible_usernames|. +// |form->all_possible_usernames|. void SanitizePossibleUsernames(PasswordForm* form) { - auto& usernames = form->other_possible_usernames; + auto& usernames = form->all_possible_usernames; // Deduplicate. std::sort(usernames.begin(), usernames.end()); @@ -348,7 +348,7 @@ void PasswordFormManager::UpdateUsername(const base::string16& new_username) { PasswordForm credential(*submitted_form_); credential.username_value = new_username; - // If |new_username| is not found in |other_possible_usernames|, store empty + // If |new_username| is not found in |all_possible_usernames|, store empty // |username_element|. credential.username_element.clear(); @@ -357,13 +357,13 @@ // uploaded. votes_uploader_.set_has_username_edited_vote(false); if (!new_username.empty()) { - for (size_t i = 0; i < credential.other_possible_usernames.size(); ++i) { - if (credential.other_possible_usernames[i].first == new_username) { + for (size_t i = 0; i < credential.all_possible_usernames.size(); ++i) { + if (credential.all_possible_usernames[i].first == new_username) { credential.username_element = - credential.other_possible_usernames[i].second; + credential.all_possible_usernames[i].second; - credential.other_possible_usernames.erase( - credential.other_possible_usernames.begin() + i); + credential.all_possible_usernames.erase( + credential.all_possible_usernames.begin() + i); // Set |corrected_username_element_| to upload a username vote. votes_uploader_.set_has_username_edited_vote(true); @@ -375,7 +375,7 @@ // |username_value| and |username_element| of the submitted form. When the // user has to override the username, Chrome will send a username vote. if (!submitted_form_->username_value.empty()) { - credential.other_possible_usernames.push_back(ValueElementPair( + credential.all_possible_usernames.push_back(ValueElementPair( submitted_form_->username_value, submitted_form_->username_element)); } @@ -817,8 +817,8 @@ pending_credentials_ = observed_form_; pending_credentials_.username_element = submitted_form_->username_element; pending_credentials_.username_value = submitted_form_->username_value; - pending_credentials_.other_possible_usernames = - submitted_form_->other_possible_usernames; + pending_credentials_.all_possible_usernames = + submitted_form_->all_possible_usernames; pending_credentials_.all_possible_passwords = submitted_form_->all_possible_passwords;
diff --git a/components/password_manager/core/browser/password_form_manager_unittest.cc b/components/password_manager/core/browser/password_form_manager_unittest.cc index d785b395..26d3af01 100644 --- a/components/password_manager/core/browser/password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/password_form_manager_unittest.cc
@@ -374,7 +374,7 @@ saved_match_.preferred = true; saved_match_.username_value = ASCIIToUTF16("test@gmail.com"); saved_match_.password_value = ASCIIToUTF16("test1"); - saved_match_.other_possible_usernames.push_back(ValueElementPair( + saved_match_.all_possible_usernames.push_back(ValueElementPair( ASCIIToUTF16("test2@gmail.com"), ASCIIToUTF16("full_name"))); saved_match_.all_possible_passwords = { {ASCIIToUTF16("password"), base::string16()}, @@ -1223,7 +1223,7 @@ PasswordForm expected_saved_form(submitted_form); expected_saved_form.times_used = 1; - expected_saved_form.other_possible_usernames.clear(); + expected_saved_form.all_possible_usernames.clear(); expected_saved_form.form_data = saved_match()->form_data; expected_saved_form.origin = observed_form()->origin; expected_saved_form.is_public_suffix_match = true; @@ -1449,7 +1449,7 @@ // update. TEST_F(PasswordFormManagerTest, TestAlternateUsername_NoChange) { PasswordForm saved_form = *saved_match(); - saved_form.other_possible_usernames.push_back( + saved_form.all_possible_usernames.push_back( ValueElementPair(ASCIIToUTF16("other_possible@gmail.com"), ASCIIToUTF16("other_username"))); @@ -1473,9 +1473,9 @@ form_manager()->Save(); // Should be only one password stored, and should not have - // |other_possible_usernames| set anymore. + // |all_possible_usernames| set anymore. EXPECT_EQ(saved_match()->username_value, saved_result.username_value); - EXPECT_TRUE(saved_result.other_possible_usernames.empty()); + EXPECT_TRUE(saved_result.all_possible_usernames.empty()); } @@ -1555,11 +1555,11 @@ fake_form_fetcher()->NotifyFetchCompleted(); PasswordForm credentials(*observed_form()); - credentials.other_possible_usernames.push_back( + credentials.all_possible_usernames.push_back( ValueElementPair(ASCIIToUTF16("543-43-1234"), ASCIIToUTF16("id1"))); - credentials.other_possible_usernames.push_back( + credentials.all_possible_usernames.push_back( ValueElementPair(ASCIIToUTF16("378282246310005"), ASCIIToUTF16("id2"))); - credentials.other_possible_usernames.push_back(kUsernameOther); + credentials.all_possible_usernames.push_back(kUsernameOther); credentials.username_value = ASCIIToUTF16("test@gmail.com"); credentials.preferred = true; @@ -1571,7 +1571,7 @@ form_manager()->Save(); // Possible credit card number and SSN are stripped. - EXPECT_THAT(saved_result.other_possible_usernames, + EXPECT_THAT(saved_result.all_possible_usernames, UnorderedElementsAre(kUsernameOther)); } @@ -1588,11 +1588,11 @@ fake_form_fetcher()->NotifyFetchCompleted(); PasswordForm credentials(*observed_form()); - credentials.other_possible_usernames.push_back(kUsernameSsn); - credentials.other_possible_usernames.push_back(kUsernameDuplicate); - credentials.other_possible_usernames.push_back(kUsernameDuplicate); - credentials.other_possible_usernames.push_back(kUsernameRandom); - credentials.other_possible_usernames.push_back(kUsernameEmail); + credentials.all_possible_usernames.push_back(kUsernameSsn); + credentials.all_possible_usernames.push_back(kUsernameDuplicate); + credentials.all_possible_usernames.push_back(kUsernameDuplicate); + credentials.all_possible_usernames.push_back(kUsernameRandom); + credentials.all_possible_usernames.push_back(kUsernameEmail); credentials.username_value = kUsernameEmail.first; credentials.preferred = true; @@ -1603,9 +1603,9 @@ .WillOnce(SaveArg<0>(&saved_result)); form_manager()->Save(); - // SSN, duplicate in |other_possible_usernames| and duplicate of + // SSN, duplicate in |all_possible_usernames| and duplicate of // |username_value| all removed. - EXPECT_THAT(saved_result.other_possible_usernames, + EXPECT_THAT(saved_result.all_possible_usernames, UnorderedElementsAre(kUsernameDuplicate, kUsernameRandom)); } @@ -2318,7 +2318,7 @@ ? base::string16() : ASCIIToUTF16("typed_username"); credential.password_value = ASCIIToUTF16("password"); - credential.other_possible_usernames.push_back( + credential.all_possible_usernames.push_back( ValueElementPair(ASCIIToUTF16("edited_username"), ASCIIToUTF16("correct_username_element"))); form_manager.ProvisionallySave(credential); @@ -2362,10 +2362,10 @@ saved_result.username_element); EXPECT_EQ(ASCIIToUTF16("password"), saved_result.password_value); if (captured_username_is_empty) { - EXPECT_TRUE(saved_result.other_possible_usernames.empty()); + EXPECT_TRUE(saved_result.all_possible_usernames.empty()); } else { EXPECT_THAT( - saved_result.other_possible_usernames, + saved_result.all_possible_usernames, ElementsAre(ValueElementPair(ASCIIToUTF16("typed_username"), observed_form()->username_element))); } @@ -2475,7 +2475,7 @@ if (!captured_username_is_empty) { // A non-empty captured username value should be saved to recover later if // a user makes a mistake in username editing. - expected_pending.other_possible_usernames.push_back(ValueElementPair( + expected_pending.all_possible_usernames.push_back(ValueElementPair( ASCIIToUTF16("captured_username"), ASCIIToUTF16("Email"))); } @@ -2511,7 +2511,7 @@ PasswordForm credential(observed); credential.username_value = ASCIIToUTF16("pin_code"); credential.password_value = ASCIIToUTF16("password"); - credential.other_possible_usernames.push_back( + credential.all_possible_usernames.push_back( ValueElementPair(base::string16(), ASCIIToUTF16("empty_field"))); form_manager.ProvisionallySave(credential); @@ -2535,7 +2535,7 @@ EXPECT_TRUE(saved_result.username_value.empty()); EXPECT_TRUE(saved_result.username_element.empty()); EXPECT_EQ(ASCIIToUTF16("password"), saved_result.password_value); - EXPECT_THAT(saved_result.other_possible_usernames, + EXPECT_THAT(saved_result.all_possible_usernames, ElementsAre(ValueElementPair(ASCIIToUTF16("pin_code"), observed_form()->username_element))); } @@ -3515,7 +3515,7 @@ is_pending_credential_psl_match ? psl_saved_match() : saved_match(); new_login.username_value = - saved_credential->other_possible_usernames[0].first; + saved_credential->all_possible_usernames[0].first; new_login.password_value = saved_credential->password_value; PasswordFormManager form_manager( @@ -3534,7 +3534,7 @@ // Checks the username correction vote is saved. PasswordForm expected_username_vote(*saved_credential); expected_username_vote.username_element = - saved_credential->other_possible_usernames[0].second; + saved_credential->all_possible_usernames[0].second; // Checks the upload. autofill::ServerFieldTypeSet expected_available_field_types; @@ -3580,7 +3580,7 @@ TEST_F(PasswordFormManagerTest, NoUsernameCorrectionVote) { SetNonFederatedAndNotifyFetchCompleted({saved_match()}); PasswordForm new_login = *observed_form(); - // The username is from |saved_match_.other_possible_usernames|, but the + // The username is from |saved_match_.all_possible_usernames|, but the // password is different. So, no username correction found. new_login.username_value = ASCIIToUTF16("test2@gmail.com"); new_login.password_value = ASCIIToUTF16("newpass"); @@ -3611,7 +3611,7 @@ // for this element even if |username_element| has a non-empty value. } - saved_match()->other_possible_usernames.push_back( + saved_match()->all_possible_usernames.push_back( ValueElementPair(base::string16(), ASCIIToUTF16("empty_field"))); SetNonFederatedAndNotifyFetchCompleted({saved_match()}); @@ -3626,10 +3626,10 @@ // Create the expected credential to be saved. PasswordForm expected_pending(*saved_match()); expected_pending.times_used = 1; - // As a credential is reused, |other_possible_usernames| will be cleared. + // As a credential is reused, |all_possible_usernames| will be cleared. // In fact, the username wasn't reused, only password, but for the sake of - // simplicity |other_possible_usernames| is cleared even in this case. - expected_pending.other_possible_usernames.clear(); + // simplicity |all_possible_usernames| is cleared even in this case. + expected_pending.all_possible_usernames.clear(); EXPECT_CALL(MockFormSaver::Get(form_manager()), Update(expected_pending, ElementsAre(Pointee(*saved_match())),
diff --git a/components/password_manager/core/browser/password_manager_util.cc b/components/password_manager/core/browser/password_manager_util.cc index 6ca5bc1..2f64e92 100644 --- a/components/password_manager/core/browser/password_manager_util.cc +++ b/components/password_manager/core/browser/password_manager_util.cc
@@ -57,7 +57,7 @@ // Remove alternate usernames. At this point we assume that we have found // the right username. - credential->other_possible_usernames.clear(); + credential->all_possible_usernames.clear(); } password_manager::SyncState GetPasswordSyncState(
diff --git a/components/password_manager/core/browser/password_store_unittest.cc b/components/password_manager/core/browser/password_store_unittest.cc index fd60f5c..b7f291e 100644 --- a/components/password_manager/core/browser/password_store_unittest.cc +++ b/components/password_manager/core/browser/password_store_unittest.cc
@@ -29,6 +29,7 @@ #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" +#include "components/sync/driver/sync_driver_switches.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -237,6 +238,9 @@ } TEST_F(PasswordStoreTest, StartSyncFlare) { + // This test isn't relevant for USS code path. + if (base::FeatureList::IsEnabled(switches::kSyncUSSPasswords)) + return; scoped_refptr<PasswordStoreDefault> store(new PasswordStoreDefault( std::make_unique<LoginDatabase>(test_login_db_file_path()))); StartSyncFlareMock mock;
diff --git a/components/password_manager/core/browser/votes_uploader.cc b/components/password_manager/core/browser/votes_uploader.cc index 57cb2289..bdd4ee5 100644 --- a/components/password_manager/core/browser/votes_uploader.cc +++ b/components/password_manager/core/browser/votes_uploader.cc
@@ -482,7 +482,7 @@ const base::string16& username) { DCHECK(!username_correction_vote_); - for (const ValueElementPair& pair : match.other_possible_usernames) { + for (const ValueElementPair& pair : match.all_possible_usernames) { if (pair.first == username) { username_correction_vote_ = match; username_correction_vote_->username_element = pair.second;
diff --git a/components/password_manager/core/browser/votes_uploader.h b/components/password_manager/core/browser/votes_uploader.h index e40b72d..2eb9565 100644 --- a/components/password_manager/core/browser/votes_uploader.h +++ b/components/password_manager/core/browser/votes_uploader.h
@@ -70,9 +70,9 @@ const autofill::PasswordForm& pending_credentials, const autofill::PasswordForm& form_to_upload); - // Searches for |username| in |other_possible_usernames| of |best_matches| + // Searches for |username| in |all_possible_usernames| of |best_matches| // and |not_best_matches|. If the username value is found in - // |other_possible_usernames| and the password value of the match is equal to + // |all_possible_usernames| and the password value of the match is equal to // |password|, the match is saved to |username_correction_vote_| and the // method returns true. bool FindCorrectedUsernameElement( @@ -152,7 +152,7 @@ best_matches, autofill::FormStructure* form_to_upload); - // Searches for |username| in |other_possible_usernames| of |match|. If the + // Searches for |username| in |all_possible_usernames| of |match|. If the // username value is found, the match is saved to |username_correction_vote_| // and the function returns true. bool FindUsernameInOtherPossibleUsernames(const autofill::PasswordForm& match, @@ -175,7 +175,7 @@ bool has_username_edited_vote_ = false; // If the user typed username that doesn't match any saved credentials, but - // matches an entry from |other_possible_usernames| of a saved credential, + // matches an entry from |all_possible_usernames| of a saved credential, // |username_correction_vote_| stores the credential with matched username. // The matched credential is copied to |username_correction_vote_|, but // |username_correction_vote_.username_element| is set to the name of the
diff --git a/components/password_manager/core/common/credential_manager_types.cc b/components/password_manager/core/common/credential_manager_types.cc index 676ed668..15d20d9 100644 --- a/components/password_manager/core/common/credential_manager_types.cc +++ b/components/password_manager/core/common/credential_manager_types.cc
@@ -87,14 +87,4 @@ return form; } -std::unique_ptr<autofill::PasswordForm> CreateObservedPasswordFormFromOrigin( - const GURL& origin) { - std::unique_ptr<autofill::PasswordForm> form(new autofill::PasswordForm); - form->origin = origin; - form->scheme = autofill::PasswordForm::Scheme::kHtml; - form->type = autofill::PasswordForm::Type::kApi; - form->signon_realm = origin.GetOrigin().spec(); - return form; -} - } // namespace password_manager
diff --git a/components/password_manager/core/common/credential_manager_types.h b/components/password_manager/core/common/credential_manager_types.h index aa37364e..b50567f 100644 --- a/components/password_manager/core/common/credential_manager_types.h +++ b/components/password_manager/core/common/credential_manager_types.h
@@ -82,11 +82,6 @@ const CredentialInfo& info, const GURL& origin); -// Create a new autofill::PasswordForm object based on |origin|. The result -// plays the role of an observed form on that page. -std::unique_ptr<autofill::PasswordForm> CreateObservedPasswordFormFromOrigin( - const GURL& origin); - } // namespace password_manager #endif // COMPONENTS_PASSWORD_MANAGER_CORE_COMMON_CREDENTIAL_MANAGER_TYPES_H_
diff --git a/components/password_manager/core/common/credential_manager_types_unittest.cc b/components/password_manager/core/common/credential_manager_types_unittest.cc index 93d1868..e0ccf39f 100644 --- a/components/password_manager/core/common/credential_manager_types_unittest.cc +++ b/components/password_manager/core/common/credential_manager_types_unittest.cc
@@ -86,18 +86,4 @@ EXPECT_EQ(origin_.spec(), form->signon_realm); } -TEST_F(CredentialManagerTypesTest, CreateObservedPasswordForm) { - std::unique_ptr<autofill::PasswordForm> form = - CreateObservedPasswordFormFromOrigin(origin_); - - ASSERT_TRUE(form); - EXPECT_EQ(GURL(), form->icon_url); - EXPECT_EQ(base::string16(), form->display_name); - EXPECT_EQ(origin_, form->origin); - EXPECT_EQ(autofill::PasswordForm::Scheme::kHtml, form->scheme); - EXPECT_TRUE(form->federation_origin.opaque()); - EXPECT_EQ(base::string16(), form->password_value); - EXPECT_EQ(origin_.spec(), form->signon_realm); -} - } // namespace password_manager
diff --git a/components/policy/core/common/cloud/enterprise_metrics.cc b/components/policy/core/common/cloud/enterprise_metrics.cc index 08da70c..83e1f1c 100644 --- a/components/policy/core/common/cloud/enterprise_metrics.cc +++ b/components/policy/core/common/cloud/enterprise_metrics.cc
@@ -7,11 +7,38 @@ namespace policy { const char kMetricUserPolicyRefresh[] = "Enterprise.PolicyRefresh"; +const char kMetricUserPolicyRefreshFcm[] = + "Enterprise.FCMInvalidationService.PolicyRefresh"; +const char kMetricUserPolicyRefreshTicl[] = + "Enterprise.TiclInvalidationService.PolicyRefresh"; + const char kMetricUserPolicyInvalidations[] = "Enterprise.PolicyInvalidations"; +const char kMetricUserPolicyInvalidationsFcm[] = + "Enterprise.FCMInvalidationService.PolicyInvalidations"; +const char kMetricUserPolicyInvalidationsTicl[] = + "Enterprise.TiclInvalidationService.PolicyInvalidations"; + const char kMetricUserPolicyChromeOSSessionAbort[] = "Enterprise.UserPolicyChromeOS.SessionAbort"; + const char kMetricDevicePolicyRefresh[] = "Enterprise.DevicePolicyRefresh"; +const char kMetricDevicePolicyRefreshFcm[] = + "Enterprise.FCMInvalidationService.DevicePolicyRefresh"; +const char kMetricDevicePolicyRefreshTicl[] = + "Enterprise.TiclInvalidationService.DevicePolicyRefresh"; + const char kMetricDevicePolicyInvalidations[] = "Enterprise.DevicePolicyInvalidations"; +const char kMetricDevicePolicyInvalidationsFcm[] = + "Enterprise.FCMInvalidationService.DevicePolicyInvalidations"; +const char kMetricDevicePolicyInvalidationsTicl[] = + "Enterprise.TiclInvalidationService.DevicePolicyInvalidations"; + +const char kMetricPolicyInvalidationRegistration[] = + "Enterprise.PolicyInvalidationsRegistrationResult"; +const char kMetricPolicyInvalidationRegistrationFcm[] = + "Enterprise.FCMInvalidationService.PolicyInvalidationsRegistrationResult"; +const char kMetricPolicyInvalidationRegistrationTicl[] = + "Enterprise.TiclInvalidationService.PolicyInvalidationsRegistrationResult"; } // namespace policy
diff --git a/components/policy/core/common/cloud/enterprise_metrics.h b/components/policy/core/common/cloud/enterprise_metrics.h index 3cbe6e8..6146f968 100644 --- a/components/policy/core/common/cloud/enterprise_metrics.h +++ b/components/policy/core/common/cloud/enterprise_metrics.h
@@ -212,10 +212,21 @@ // from the same enum above can be triggered in different files, and must use // the same UMA histogram name. POLICY_EXPORT extern const char kMetricUserPolicyRefresh[]; +POLICY_EXPORT extern const char kMetricUserPolicyRefreshFcm[]; +POLICY_EXPORT extern const char kMetricUserPolicyRefreshTicl[]; POLICY_EXPORT extern const char kMetricUserPolicyInvalidations[]; +POLICY_EXPORT extern const char kMetricUserPolicyInvalidationsFcm[]; +POLICY_EXPORT extern const char kMetricUserPolicyInvalidationsTicl[]; POLICY_EXPORT extern const char kMetricUserPolicyChromeOSSessionAbort[]; POLICY_EXPORT extern const char kMetricDevicePolicyRefresh[]; +POLICY_EXPORT extern const char kMetricDevicePolicyRefreshFcm[]; +POLICY_EXPORT extern const char kMetricDevicePolicyRefreshTicl[]; POLICY_EXPORT extern const char kMetricDevicePolicyInvalidations[]; +POLICY_EXPORT extern const char kMetricDevicePolicyInvalidationsFcm[]; +POLICY_EXPORT extern const char kMetricDevicePolicyInvalidationsTicl[]; +POLICY_EXPORT extern const char kMetricPolicyInvalidationRegistration[]; +POLICY_EXPORT extern const char kMetricPolicyInvalidationRegistrationFcm[]; +POLICY_EXPORT extern const char kMetricPolicyInvalidationRegistrationTicl[]; } // namespace policy
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 23a51602..e11ac8ed 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -7883,12 +7883,14 @@ 'dynamic_refresh': True, 'per_profile': True, }, - 'example_value': ['pjkljhegncpnkpknbcohdijeoejaedia', 'com.google.android.gm'], + 'example_value': ['pjkljhegncpnkpknbcohdijeoejaedia', 'com.google.android.gm', 'https://google.com/maps'], 'id': 144, 'caption': '''List of pinned apps to show in the launcher''', 'tags': [], 'desc': '''Lists the application identifiers <ph name="PRODUCT_OS_NAME">$2<ex>Google Chrome OS</ex></ph> shows as pinned apps in the launcher bar. + Chrome Apps are specified by their Id, e.g. "pjkljhegncpnkpknbcohdijeoejaedia", Android Apps by their package name, e.g. "com.google.android.gm", and Web Apps are specified by the URL used in WebAppInstallForceList e.g. "https://google.com/maps". + If this policy is configured, the set of applications is fixed and can't be changed by the user. If this policy is left unset, the user may change the list of pinned apps in the launcher.''', @@ -9363,6 +9365,30 @@ If this policy is left unset, the sticky keys is disabled initially but can be enabled by the user anytime.''' }, { + 'name': 'SelectToSpeakEnabled', + 'type': 'main', + 'schema': { 'type': 'boolean' }, + 'supported_on': ['chrome_os:77-'], + 'features': { + 'can_be_recommended': True, + 'dynamic_refresh': True, + 'per_profile': True, + }, + 'example_value': True, + 'id': 573, + 'caption': '''Enable select to speak''', + 'tags': [], + 'desc': '''Enable the select to speak accessibility feature. + + If this policy is set to true, the select to speak will always be enabled. + + If this policy is set to false, the select to speak will always be disabled. + + If you set this policy, users cannot change or override it. + + If this policy is left unset, the select to speak is disabled initially but can be enabled by the user anytime.''' + }, + { 'name': 'KeyboardDefaultToFunctionKeys', 'type': 'main', 'schema': { 'type': 'boolean' }, @@ -14412,7 +14438,7 @@ 'tags': [], 'desc': '''Specifies a list of websites that are installed silently, without user interaction, and which cannot be uninstalled nor disabled by the user. - Each list item of the policy is an object with a mandatory member: "url" and two optional members: "default_launch_container" and "create_desktop_shortcut". "url" should be the URL of the web app to install, "launch_container" should be either "window" or "tab" to indicate how the Web App will be opened once installed, and "create_desktop_shortcut" should be true if a desktop shortcut should be created on Linux and Windows. If "default_launch_container" is omitted, the app will open in a tab by default. Regardless of the value of "default_launch_container", users are able to change which container the app will open in. If "create_desktop_shortcuts" is omitted, no desktop shortcuts will be created.''', + Each list item of the policy is an object with a mandatory member: "url" and two optional members: "default_launch_container" and "create_desktop_shortcut". "url" should be the URL of the web app to install, "launch_container" should be either "window" or "tab" to indicate how the Web App will be opened once installed, and "create_desktop_shortcut" should be true if a desktop shortcut should be created on Linux and Windows. If "default_launch_container" is omitted, the app will open in a tab by default. Regardless of the value of "default_launch_container", users are able to change which container the app will open in. If "create_desktop_shortcuts" is omitted, no desktop shortcuts will be created. See <ph name="PINNED_LAUNCHER_APPS_POLICY_NAME">PinnedLauncherApps</ph> policy for pinning apps to the ChromeOS shelf.''', 'label': '''URLs for Web Apps to be silently installed.''', }, { @@ -15202,7 +15228,7 @@ When this policy is unset it is not possible to verify Parent Access Code on child user's device.''' }, { - 'name': 'CertificateManagementAllowed', + 'name': 'ClientCertificateManagementAllowed', 'type': 'int-enum', 'schema': { 'type': 'integer', @@ -15233,8 +15259,8 @@ }, 'example_value': 1, 'id': 518, - 'caption': '''Allow users to manage installed certificates.''', - 'desc': '''This policy controls whether user are able to import and remove certificates via Certificate Manager. + 'caption': '''Allow users to manage installed client certificates.''', + 'desc': '''This policy controls whether user are able to import and remove client certificates via Certificate Manager. If this policy is set to ''Allow users to manage all certificates'' or left not set, users will be able to manage certificates. @@ -16980,6 +17006,6 @@ ], 'placeholders': [], 'deleted_policy_ids': [412, 546, 562], - 'highest_id_currently_used': 572, + 'highest_id_currently_used': 573, 'highest_atomic_group_id_currently_used': 37 }
diff --git a/components/safe_browsing/password_protection/BUILD.gn b/components/safe_browsing/password_protection/BUILD.gn index 44b703dd..928a9da5 100644 --- a/components/safe_browsing/password_protection/BUILD.gn +++ b/components/safe_browsing/password_protection/BUILD.gn
@@ -37,7 +37,8 @@ "//components/safe_browsing/db:v4_protocol_manager_util", "//components/safe_browsing/web_ui:web_ui", "//components/sessions", - "//components/signin/core/browser:shared", + "//components/signin/public/base", + "//components/signin/public/identity_manager", "//components/zoom", "//content/public/browser:browser", "//net:net", @@ -81,7 +82,8 @@ "//components/safe_browsing:verdict_cache_manager", "//components/safe_browsing/common:interfaces", "//components/safe_browsing/db:test_database_manager", - "//components/signin/core/browser:shared", + "//components/signin/public/base", + "//components/signin/public/identity_manager", "//components/sync_preferences:test_support", "//content/test:test_support", "//net:test_support",
diff --git a/components/safe_browsing/password_protection/DEPS b/components/safe_browsing/password_protection/DEPS index a66dd1f..e745435 100644 --- a/components/safe_browsing/password_protection/DEPS +++ b/components/safe_browsing/password_protection/DEPS
@@ -4,7 +4,7 @@ "+components/password_manager/core/browser/password_manager_metrics_util.h", "+components/password_manager/core/browser/password_reuse_detector.h", "+components/sessions", - "+components/signin/core/browser/account_info.h", + "+components/signin/public/identity_manager/account_info.h", "+components/sync_preferences/testing_pref_service_syncable.h", "+components/zoom", "+content/public/test",
diff --git a/components/safe_browsing/password_protection/password_protection_service.h b/components/safe_browsing/password_protection/password_protection_service.h index b9a3b36c..f8eb7de 100644 --- a/components/safe_browsing/password_protection/password_protection_service.h +++ b/components/safe_browsing/password_protection/password_protection_service.h
@@ -25,7 +25,7 @@ #include "components/safe_browsing/password_protection/metrics_util.h" #include "components/safe_browsing/proto/csd.pb.h" #include "components/sessions/core/session_id.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/protobuf/src/google/protobuf/repeated_field.h"
diff --git a/components/safe_browsing/password_protection/password_protection_service_unittest.cc b/components/safe_browsing/password_protection/password_protection_service_unittest.cc index 7c7282d..d3d49ce6 100644 --- a/components/safe_browsing/password_protection/password_protection_service_unittest.cc +++ b/components/safe_browsing/password_protection/password_protection_service_unittest.cc
@@ -22,7 +22,7 @@ #include "components/safe_browsing/password_protection/password_protection_request.h" #include "components/safe_browsing/proto/csd.pb.h" #include "components/safe_browsing/verdict_cache_manager.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/browser/web_contents.h" #include "content/public/test/test_browser_context.h"
diff --git a/components/search_provider_logos/BUILD.gn b/components/search_provider_logos/BUILD.gn index c95e6f3e..e4ff83bc 100644 --- a/components/search_provider_logos/BUILD.gn +++ b/components/search_provider_logos/BUILD.gn
@@ -97,7 +97,7 @@ "//components/image_fetcher/core", "//components/search_engines", "//components/signin/core/browser", - "//components/signin/core/browser:internals_test_support", + "//components/signin/public/base:test_support", "//components/signin/public/identity_manager:test_support", "//components/sync_preferences:test_support", "//net:test_support",
diff --git a/components/services/quarantine/BUILD.gn b/components/services/quarantine/BUILD.gn index 15d15dd..1fe5d0f 100644 --- a/components/services/quarantine/BUILD.gn +++ b/components/services/quarantine/BUILD.gn
@@ -46,6 +46,8 @@ source_set("common") { sources = [ + "common.cc", + "common.h", "common_mac.h", "common_mac.mm", "common_win.cc", @@ -54,6 +56,7 @@ deps = [ "//base", + "//url", ] if (is_mac) { @@ -93,6 +96,7 @@ testonly = true sources = [ + "common_unittests.cc", "quarantine_mac_unittest.mm", "quarantine_service_unittest.cc", "quarantine_win_unittest.cc",
diff --git a/components/services/quarantine/common.cc b/components/services/quarantine/common.cc new file mode 100644 index 0000000..4158eb9 --- /dev/null +++ b/components/services/quarantine/common.cc
@@ -0,0 +1,35 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/services/quarantine/common.h" + +#include "url/origin.h" +#include "url/url_canon.h" + +namespace quarantine { + +GURL SanitizeUrlForQuarantine(const GURL& source_url) { + // Invalid URLs and 'data' URLs don't confer an authority. + if (!source_url.is_valid() || source_url.SchemeIs("data")) { + return GURL(); + } + + // The full content of these URLs are only meaningful within the confines of + // the browser. Origin extracts the inner URL for both of these schemes. + if (source_url.SchemeIsBlob() || source_url.SchemeIsFileSystem()) { + return url::Origin::Create(source_url).GetURL(); + } + + if (!source_url.SchemeIsHTTPOrHTTPS() && !source_url.SchemeIsWSOrWSS()) { + return source_url; + } + + url::Replacements<char> replacements; + replacements.ClearUsername(); + replacements.ClearPassword(); + + return source_url.ReplaceComponents(replacements); +} + +} // namespace quarantine
diff --git a/components/services/quarantine/common.h b/components/services/quarantine/common.h new file mode 100644 index 0000000..08735e01 --- /dev/null +++ b/components/services/quarantine/common.h
@@ -0,0 +1,27 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_SERVICES_QUARANTINE_COMMON_H_ +#define COMPONENTS_SERVICES_QUARANTINE_COMMON_H_ + +#include "url/gurl.h" + +namespace quarantine { + +// Return a sanitized URL to use as a source or referrer for the purpose of +// annotating the source of a downloaded file. +// +// For privacy reasons, it's best to not URLs as-is when annotating or +// informing third parties about the source of a download. Hence this function +// is used to strip out any unnecessary or excessive parts from the URL. +// +// See https://crbug.com/917842 for justification for the types of sanitization +// performed here. In particular, stripping fragments, query, and path from URLs +// was discussed and rejected due to that information being pertinent to +// evaluating whether the downloaded file is safe. +GURL SanitizeUrlForQuarantine(const GURL& source_url); + +} // namespace quarantine + +#endif // COMPONENTS_SERVICES_QUARANTINE_COMMON_H_
diff --git a/components/services/quarantine/common_unittests.cc b/components/services/quarantine/common_unittests.cc new file mode 100644 index 0000000..479bcb2 --- /dev/null +++ b/components/services/quarantine/common_unittests.cc
@@ -0,0 +1,55 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/services/quarantine/common.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +TEST(QuarantineCommonTest, SanitizeUrlForQuarantine) { + struct { + const char* input; + const char* expected_output; + } kTestCases[] = { + // Credentials stripped from http URL. + {"http://foo:bar@s.example/x/y/z", "http://s.example/x/y/z"}, + + // Preserve query and fragment of http{s} URL. + {"http://a.example/x/y?q=f&r=g#blah", + "http://a.example/x/y?q=f&r=g#blah"}, + {"https://a.example/x/y?q=f#h", "https://a.example/x/y?q=f#h"}, + + // Ditto for ws{s} URL. + {"ws://a.example/x/y?q=f", "ws://a.example/x/y?q=f"}, + {"wss://a.example/x/y?q=f", "wss://a.example/x/y?q=f"}, + + // Credentials stripped from wss URL. + {"wss://foo:bar@a.example/x/y?q=f", "wss://a.example/x/y?q=f"}, + + // blob URLs get reduced to origin. + {"blob:https://b.example/x/y/z", "https://b.example/"}, + {"blob:https://foo:bar@b.example/x/y/z?q", "https://b.example/"}, + + // filesystem URLs get reduced to origin. + {"filesystem:https://example.com/temporary/m", "https://example.com/"}, + {"filesystem:https://foo:bar@example.com/temporary/m", + "https://example.com/"}, + + // Unknown scheme is passed through as-is. + {"some-random-scheme:randomdata", "some-random-scheme:randomdata"}, + + // data URL is dropped. + {"data:text/plain,hello%20world!", ""}, + + // Invalid URL is dropped. + {"1|\\|\\/4L||>", ""}, + }; + + for (const auto test_case : kTestCases) { + GURL input_url{test_case.input}; + GURL output = quarantine::SanitizeUrlForQuarantine(input_url); + EXPECT_EQ(test_case.expected_output, output) + << "Input : " << test_case.input; + } +}
diff --git a/components/services/quarantine/quarantine.h b/components/services/quarantine/quarantine.h index 7ec0eac..3c3bf14 100644 --- a/components/services/quarantine/quarantine.h +++ b/components/services/quarantine/quarantine.h
@@ -60,6 +60,12 @@ // |referrer_url|: Referring URL. This is empty for off-the-record download. // |client_guid|: Only used on Windows. Identifies the client application // that downloaded the file. +// +// Note: The |source_url| and |referrer_url| will be stripped of unnecessary +// parts using SanitizeUrlForQuarantine() before they are used for annotation +// or notification purposes. If the URLs are sensitive -- e.g. because the +// download was made using an off-the-record profile -- then pass in an empty +// GURL() instead. QuarantineFileResult QuarantineFile(const base::FilePath& file, const GURL& source_url, const GURL& referrer_url,
diff --git a/components/services/quarantine/quarantine_mac.mm b/components/services/quarantine/quarantine_mac.mm index 48b07f1..1673e9b 100644 --- a/components/services/quarantine/quarantine_mac.mm +++ b/components/services/quarantine/quarantine_mac.mm
@@ -17,6 +17,7 @@ #include "base/mac/scoped_nsobject.h" #include "base/strings/sys_string_conversions.h" #include "base/threading/scoped_blocking_call.h" +#include "components/services/quarantine/common.h" #include "components/services/quarantine/common_mac.h" #include "url/gurl.h" @@ -194,12 +195,15 @@ } // namespace QuarantineFileResult QuarantineFile(const base::FilePath& file, - const GURL& source_url, - const GURL& referrer_url, + const GURL& source_url_unsafe, + const GURL& referrer_url_unsafe, const std::string& client_guid) { if (!base::PathExists(file)) return QuarantineFileResult::FILE_MISSING; + GURL source_url = SanitizeUrlForQuarantine(source_url_unsafe); + GURL referrer_url = SanitizeUrlForQuarantine(referrer_url_unsafe); + // Don't consider it an error if we fail to add origin metadata. AddOriginMetadataToFile(file, source_url, referrer_url); bool quarantine_succeeded =
diff --git a/components/services/quarantine/quarantine_mac_unittest.mm b/components/services/quarantine/quarantine_mac_unittest.mm index dde7389..21109473 100644 --- a/components/services/quarantine/quarantine_mac_unittest.mm +++ b/components/services/quarantine/quarantine_mac_unittest.mm
@@ -55,8 +55,8 @@ base::ScopedTempDir temp_dir_; base::FilePath test_file_; - GURL source_url_; - GURL referrer_url_; + const GURL source_url_; + const GURL referrer_url_; base::scoped_nsobject<NSURL> file_url_; }; @@ -105,6 +105,18 @@ EXPECT_FALSE(IsFileQuarantined(test_file_, referrer_url_, referrer_url_)); } +TEST_F(QuarantineMacTest, IsFileQuarantined_Sanitize) { + GURL host_url{"https://user:pass@example.com/foo/bar?x#y"}; + GURL host_url_clean{"https://example.com/foo/bar?x#y"}; + GURL referrer_url{"https://user:pass@example.com/foo/index?x#y"}; + GURL referrer_url_clean{"https://example.com/foo/index?x#y"}; + + ASSERT_EQ(QuarantineFileResult::OK, + QuarantineFile(test_file_, host_url, referrer_url, std::string())); + EXPECT_TRUE( + IsFileQuarantined(test_file_, host_url_clean, referrer_url_clean)); +} + TEST_F(QuarantineMacTest, NoWhereFromsKeyIfNoURLs) { ASSERT_EQ(QuarantineFileResult::OK, QuarantineFile(test_file_, GURL(), GURL(), std::string()));
diff --git a/components/services/quarantine/quarantine_win.cc b/components/services/quarantine/quarantine_win.cc index adc0c82..3ff31d9 100644 --- a/components/services/quarantine/quarantine_win.cc +++ b/components/services/quarantine/quarantine_win.cc
@@ -30,6 +30,7 @@ #include "base/win/scoped_handle.h" #include "base/win/win_util.h" #include "base/win/windows_version.h" +#include "components/services/quarantine/common.h" #include "components/services/quarantine/common_win.h" #include "components/services/quarantine/public/cpp/quarantine_features_win.h" #include "url/gurl.h" @@ -229,8 +230,8 @@ } QuarantineFileResult QuarantineFile(const base::FilePath& file, - const GURL& source_url, - const GURL& referrer_url, + const GURL& source_url_unsafe, + const GURL& referrer_url_unsafe, const std::string& client_guid) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::MAY_BLOCK); @@ -247,6 +248,9 @@ guid = GUID_NULL; } + GURL source_url = SanitizeUrlForQuarantine(source_url_unsafe); + GURL referrer_url = SanitizeUrlForQuarantine(referrer_url_unsafe); + if (file_size == 0 || IsEqualGUID(guid, GUID_NULL)) { // Calling InvokeAttachmentServices on an empty file can result in the file // being deleted. Also an anti-virus scan doesn't make a lot of sense to
diff --git a/components/services/quarantine/quarantine_win_unittest.cc b/components/services/quarantine/quarantine_win_unittest.cc index a004539..de648483 100644 --- a/components/services/quarantine/quarantine_win_unittest.cc +++ b/components/services/quarantine/quarantine_win_unittest.cc
@@ -18,6 +18,7 @@ #include "base/win/windows_version.h" #include "components/services/quarantine/public/cpp/quarantine_features_win.h" #include "components/services/quarantine/quarantine.h" +#include "components/services/quarantine/test_support.h" #include "net/base/filename_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -36,7 +37,7 @@ "ftp://example.com/foo", "ftp://example.com:2121/foo", "data:text/plain,Hello%20world", - "blob://example.com/126278b3-58f3-4b4a-a914-1d1185d634f6", + "blob:https://example.com/126278b3-58f3-4b4a-a914-1d1185d634f6", "about:internet", ""}; @@ -139,6 +140,9 @@ scoped_zone_for_restricted_site_ = std::make_unique<ScopedZoneForSite>( GetRestrictedSite(), L"https", ScopedZoneForSite::ZoneIdentifierType::kRestrictedSitesZone); + scoped_zone_for_internet_site_ = std::make_unique<ScopedZoneForSite>( + GetInternetSite(), L"https", + ScopedZoneForSite::ZoneIdentifierType::kInternetZone); } base::FilePath GetTempDir() { return scoped_temp_dir_.GetPath(); } @@ -147,6 +151,8 @@ const wchar_t* GetRestrictedSite() { return L"thisisarestrictedsite.com"; } + const wchar_t* GetInternetSite() { return L"example.com"; } + private: registry_util::RegistryOverrideManager registry_override_; @@ -155,6 +161,7 @@ // Due to caching, these sites zone must be set for all tests, so that the // order the tests are run does not matter. std::unique_ptr<ScopedZoneForSite> scoped_zone_for_trusted_site_; + std::unique_ptr<ScopedZoneForSite> scoped_zone_for_internet_site_; std::unique_ptr<ScopedZoneForSite> scoped_zone_for_restricted_site_; DISALLOW_COPY_AND_ASSIGN(QuarantineWinTest); @@ -404,4 +411,46 @@ EXPECT_FALSE(GetZoneIdentifierStreamContents(test_file, &zone_identifier)); } +TEST_F(QuarantineWinTest, MetaData_ApplyMOTW_Directly) { + base::FilePath test_file = GetTempDir().AppendASCII("foo.exe"); + ASSERT_TRUE(CreateFile(test_file)); + + GURL host_url = GURL(base::StringPrintf( + L"https://user:pass@%ls/folder/foo.exe?x#y", GetInternetSite())); + GURL host_url_clean = GURL( + base::StringPrintf(L"https://%ls/folder/foo.exe?x#y", GetInternetSite())); + GURL referrer_url = GURL(base::StringPrintf( + L"https://user:pass@%ls/folder/index?x#y", GetInternetSite())); + GURL referrer_url_clean = GURL( + base::StringPrintf(L"https://%ls/folder/index?x#y", GetInternetSite())); + + EXPECT_EQ(QuarantineFileResult::OK, + QuarantineFile(test_file, host_url, referrer_url, std::string())); + + EXPECT_TRUE(IsFileQuarantined(test_file, host_url_clean, referrer_url_clean)); +} + +TEST_F(QuarantineWinTest, MetaData_InvokeAS) { + base::test::ScopedFeatureList invoke_as_feature; + invoke_as_feature.InitAndEnableFeature(kInvokeAttachmentServices); + + base::FilePath test_file = GetTempDir().AppendASCII("foo.exe"); + ASSERT_TRUE(CreateFile(test_file)); + + GURL host_url = GURL( + base::StringPrintf(L"https://%ls/folder/foo.exe?x#y", GetInternetSite())); + GURL host_url_clean = GURL( + base::StringPrintf(L"https://%ls/folder/foo.exe?x#y", GetInternetSite())); + GURL referrer_url = GURL(base::StringPrintf( + L"https://user:pass@%ls/folder/index?x#y", GetInternetSite())); + GURL referrer_url_clean = GURL( + base::StringPrintf(L"https://%ls/folder/index?x#y", GetInternetSite())); + + EXPECT_EQ( + QuarantineFileResult::OK, + QuarantineFile(test_file, host_url, referrer_url, kDummyClientGuid)); + + EXPECT_TRUE(IsFileQuarantined(test_file, host_url_clean, referrer_url_clean)); +} + } // namespace quarantine
diff --git a/components/services/quarantine/test_support_mac.mm b/components/services/quarantine/test_support_mac.mm index 40b9382..315a4c8e 100644 --- a/components/services/quarantine/test_support_mac.mm +++ b/components/services/quarantine/test_support_mac.mm
@@ -12,14 +12,15 @@ #include "base/mac/scoped_nsobject.h" #include "base/strings/sys_string_conversions.h" #include "base/threading/scoped_blocking_call.h" +#include "components/services/quarantine/common.h" #include "components/services/quarantine/common_mac.h" #include "url/gurl.h" namespace quarantine { bool IsFileQuarantined(const base::FilePath& file, - const GURL& expected_source_url, - const GURL& referrer_url) { + const GURL& expected_source_url_unsafe, + const GURL& expected_referrer_url_unsafe) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::MAY_BLOCK); @@ -32,6 +33,11 @@ if (!success || !properties) return false; + GURL expected_source_url = + SanitizeUrlForQuarantine(expected_source_url_unsafe); + GURL expected_referrer_url = + SanitizeUrlForQuarantine(expected_referrer_url_unsafe); + NSString* source_url = [[properties valueForKey:(NSString*)kLSQuarantineDataURLKey] description]; @@ -43,10 +49,11 @@ return false; } - return !referrer_url.is_valid() || + return !expected_referrer_url.is_valid() || [[[properties valueForKey:(NSString*)kLSQuarantineOriginURLKey] description] - isEqualToString:base::SysUTF8ToNSString(referrer_url.spec())]; + isEqualToString:base::SysUTF8ToNSString( + expected_referrer_url.spec())]; } } // namespace quarantine
diff --git a/components/services/quarantine/test_support_win.cc b/components/services/quarantine/test_support_win.cc index c8a0689b..18ff19a 100644 --- a/components/services/quarantine/test_support_win.cc +++ b/components/services/quarantine/test_support_win.cc
@@ -2,24 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/services/quarantine/test_support.h" - #include <windows.h> #include <string> #include <vector> #include "base/files/file_path.h" +#include "base/logging.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" #include "base/win/scoped_handle.h" +#include "base/win/windows_version.h" +#include "components/services/quarantine/common.h" #include "components/services/quarantine/common_win.h" +#include "components/services/quarantine/test_support.h" namespace quarantine { namespace { -bool ZoneIdentifierPresentForFile(const base::FilePath& path) { +bool ZoneIdentifierPresentForFile(const base::FilePath& path, + const GURL source_url, + const GURL referrer_url) { const DWORD kShare = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; base::FilePath::StringType zone_identifier_path = path.value() + kZoneIdentifierStreamSuffix; @@ -29,10 +33,8 @@ if (!file.IsValid()) return false; - // The zone identifier contents is expected to be: - // "[ZoneTransfer]\r\nZoneId=3\r\n". The actual ZoneId can be different. A - // buffer of 32 bytes is sufficient for verifying the contents. - std::vector<char> zone_identifier_contents_buffer(32); + // During testing, the zone identifier is expected to be under this limit. + std::vector<char> zone_identifier_contents_buffer(4096); DWORD actual_length = 0; if (!::ReadFile(file.Get(), &zone_identifier_contents_buffer.front(), zone_identifier_contents_buffer.size(), &actual_length, @@ -46,8 +48,30 @@ std::vector<base::StringPiece> lines = base::SplitStringPiece(zone_identifier_contents, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - return lines.size() > 1 && lines[0] == "[ZoneTransfer]" && - lines[1].find("ZoneId=") == 0; + if (lines.size() < 2 || lines[0] != "[ZoneTransfer]" != 0) + return false; + + base::StringPiece found_zone_id; + base::StringPiece found_host_url; + base::StringPiece found_referrer_url; + + // Note that we don't try too hard to parse the zone identifier here. This is + // a test. If Windows starts adding whitespace or doing anything fancier than + // ASCII, then we'd have to update this. + for (const auto& line : lines) { + if (line.starts_with("ZoneId=")) + found_zone_id = line.substr(7); + else if (line.starts_with("HostUrl=")) + found_host_url = line.substr(8); + else if (line.starts_with("ReferrerUrl=")) + found_referrer_url = line.substr(12); + } + + return !found_zone_id.empty() && + (source_url.is_empty() || + SanitizeUrlForQuarantine(source_url).spec() == found_host_url) && + (referrer_url.is_empty() || + SanitizeUrlForQuarantine(referrer_url).spec() == found_referrer_url); } } // namespace @@ -55,7 +79,11 @@ bool IsFileQuarantined(const base::FilePath& file, const GURL& source_url, const GURL& referrer_url) { - return ZoneIdentifierPresentForFile(file); + if (base::win::GetVersion() >= base::win::Version::WIN10) + return ZoneIdentifierPresentForFile(file, source_url, referrer_url); + else + return ZoneIdentifierPresentForFile(file, GURL::EmptyGURL(), + GURL::EmptyGURL()); } } // namespace quarantine
diff --git a/components/signin/OWNERS b/components/signin/OWNERS index 184a152c..e4b8e297 100644 --- a/components/signin/OWNERS +++ b/components/signin/OWNERS
@@ -1,6 +1,7 @@ bsazonov@chromium.org droger@chromium.org msarda@chromium.org +sdefresne@chromium.org # TEAM: chrome-signin@chromium.org # COMPONENT: Services>SignIn
diff --git a/components/signin/core/browser/BUILD.gn b/components/signin/core/browser/BUILD.gn index 740611af..afe9ac56 100644 --- a/components/signin/core/browser/BUILD.gn +++ b/components/signin/core/browser/BUILD.gn
@@ -9,60 +9,6 @@ import("//build/config/android/rules.gni") } -buildflag_header("signin_buildflags") { - header = "signin_buildflags.h" - flags = [ - "ENABLE_DICE_SUPPORT=$enable_dice_support", - "ENABLE_MIRROR=$enable_mirror", - ] -} - -# This target contains code that is used both by the IdentityManager -# implementation and by clients of the //components/signin public code. -static_library("shared") { - sources = [ - "account_consistency_method.cc", - "account_consistency_method.h", - "account_info.cc", - "account_info.h", - "avatar_icon_util.cc", - "avatar_icon_util.h", - "device_id_helper.cc", - "device_id_helper.h", - "identity_utils.cc", - "identity_utils.h", - "set_accounts_in_cookie_result.h", - "signin_client.cc", - "signin_client.h", - "signin_metrics.cc", - "signin_metrics.h", - "signin_pref_names.cc", - "signin_pref_names.h", - "signin_switches.cc", - "signin_switches.h", - "ubertoken_fetcher.cc", - "ubertoken_fetcher.h", - ] - deps = [ - ":signin_buildflags", - "//components/account_id", - "//components/prefs:prefs", - "//third_party/icu:icui18n", - "//third_party/re2", - "//ui/gfx", - "//url", - ] - public_deps = [ - "//base", - "//components/keyed_service/core", - "//google_apis", - ] - - if (is_chromeos) { - deps += [ "//components/user_manager" ] - } -} - # This target forms the core of the IdentityManager implementation # (//components/signin/public/identity_manager/identity_manager.*). We are # actively converting the codebase away from using the code in this target @@ -109,13 +55,13 @@ } deps = [ - ":shared", - ":signin_buildflags", "//base", "//components/image_fetcher/core", "//components/keyed_service/core", "//components/prefs", "//components/signin/core/browser/webdata", + "//components/signin/public/base", + "//components/signin/public/base:signin_buildflags", "//components/webdata/common", "//google_apis", "//net", @@ -180,14 +126,14 @@ public_deps = [ ":internals", - ":shared", - ":signin_buildflags", "//base", "//components/account_id", "//components/content_settings/core/browser", "//components/content_settings/core/common", "//components/keyed_service/core", "//components/prefs", + "//components/signin/public/base", + "//components/signin/public/base:signin_buildflags", "//google_apis", "//net", "//services/network/public/cpp", @@ -243,44 +189,30 @@ sources = [ "fake_profile_oauth2_token_service.cc", "fake_profile_oauth2_token_service.h", - - # TODO(https://crbug.com/907782): Move list_accounts_test_utils to - # //components/signin/public/identity_manager once FakeGCMS no longer - # depends on it. - "list_accounts_test_utils.cc", - "list_accounts_test_utils.h", - "test_signin_client.cc", - "test_signin_client.h", ] deps = [ "//base/test:test_support", - "//components/prefs", "//google_apis:test_support", + "//services/network/public/cpp", ] public_deps = [ ":internals", - ":shared", "//base", - "//services/network:test_support", ] } source_set("unit_tests") { testonly = true sources = [ - "account_info_unittest.cc", "account_info_util_unittest.cc", "account_investigator_unittest.cc", "account_reconcilor_delegate_unittest.cc", "account_reconcilor_unittest.cc", "account_tracker_service_unittest.cc", - "avatar_icon_util_unittest.cc", - "device_id_helper_unittest.cc", "dice_account_reconcilor_delegate_unittest.cc", "gaia_cookie_manager_service_unittest.cc", - "identity_utils_unittest.cc", "mice_account_reconcilor_delegate_unittest.cc", "mutable_profile_oauth2_token_service_delegate_unittest.cc", "oauth_multilogin_helper_unittest.cc", @@ -291,7 +223,6 @@ "signin_error_controller_unittest.cc", "signin_header_helper_unittest.cc", "signin_investigator_unittest.cc", - "signin_metrics_unittest.cc", "signin_status_metrics_provider_unittest.cc", "ubertoken_fetcher_impl_unittest.cc", ] @@ -299,7 +230,6 @@ deps = [ ":browser", ":internals_test_support", - ":signin_buildflags", "//base/test:test_support", "//components/content_settings/core/browser", "//components/image_fetcher/core", @@ -308,6 +238,8 @@ "//components/prefs", "//components/prefs:test_support", "//components/signin/core/browser/webdata", + "//components/signin/public/base:signin_buildflags", + "//components/signin/public/base:test_support", "//components/signin/public/identity_manager:test_support", "//components/sync_preferences", "//components/sync_preferences:test_support",
diff --git a/components/signin/core/browser/about_signin_internals.cc b/components/signin/core/browser/about_signin_internals.cc index 015e8c70..8d23fe0 100644 --- a/components/signin/core/browser/about_signin_internals.cc +++ b/components/signin/core/browser/about_signin_internals.cc
@@ -18,8 +18,8 @@ #include "build/build_config.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_client.h" -#include "components/signin/core/browser/signin_switches.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_switches.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/diagnostics_provider.h" #include "components/signin/public/identity_manager/identity_manager.h"
diff --git a/components/signin/core/browser/about_signin_internals.h b/components/signin/core/browser/about_signin_internals.h index 9ac5fec..1fcdc99 100644 --- a/components/signin/core/browser/about_signin_internals.h +++ b/components/signin/core/browser/about_signin_internals.h
@@ -17,9 +17,9 @@ #include "base/values.h" #include "components/content_settings/core/browser/content_settings_observer.h" #include "components/keyed_service/core/keyed_service.h" -#include "components/signin/core/browser/signin_client.h" #include "components/signin/core/browser/signin_error_controller.h" #include "components/signin/core/browser/signin_internals_util.h" +#include "components/signin/public/base/signin_client.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "services/identity/public/cpp/scope_set.h"
diff --git a/components/signin/core/browser/account_fetcher_service.cc b/components/signin/core/browser/account_fetcher_service.cc index f712944..c68907d 100644 --- a/components/signin/core/browser/account_fetcher_service.cc +++ b/components/signin/core/browser/account_fetcher_service.cc
@@ -19,10 +19,10 @@ #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_info_fetcher.h" #include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/avatar_icon_util.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_client.h" -#include "components/signin/core/browser/signin_switches.h" +#include "components/signin/public/base/avatar_icon_util.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_switches.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #if defined(OS_ANDROID)
diff --git a/components/signin/core/browser/account_info_util.cc b/components/signin/core/browser/account_info_util.cc index 878adeb5..d6386f7 100644 --- a/components/signin/core/browser/account_info_util.cc +++ b/components/signin/core/browser/account_info_util.cc
@@ -4,7 +4,7 @@ #include "components/signin/core/browser/account_info_util.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" namespace { // Keys used to store the different values in the JSON dictionary received
diff --git a/components/signin/core/browser/account_info_util.h b/components/signin/core/browser/account_info_util.h index fb2058a..f240b79 100644 --- a/components/signin/core/browser/account_info_util.h +++ b/components/signin/core/browser/account_info_util.h
@@ -7,7 +7,7 @@ #include "base/optional.h" #include "base/values.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" // Builds an AccountInfo from the JSON data returned by the gaia servers (the // data should have been converted to base::Value), if possible.
diff --git a/components/signin/core/browser/account_info_util_unittest.cc b/components/signin/core/browser/account_info_util_unittest.cc index da0c76f..b5b2a67303 100644 --- a/components/signin/core/browser/account_info_util_unittest.cc +++ b/components/signin/core/browser/account_info_util_unittest.cc
@@ -4,7 +4,7 @@ #include "components/signin/core/browser/account_info_util.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "testing/platform_test.h" namespace {
diff --git a/components/signin/core/browser/account_investigator.cc b/components/signin/core/browser/account_investigator.cc index c45d8cb..0343af6a 100644 --- a/components/signin/core/browser/account_investigator.cc +++ b/components/signin/core/browser/account_investigator.cc
@@ -13,8 +13,8 @@ #include "base/time/time.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/google_service_auth_error.h"
diff --git a/components/signin/core/browser/account_investigator_unittest.cc b/components/signin/core/browser/account_investigator_unittest.cc index a7505a4..8acfa51 100644 --- a/components/signin/core/browser/account_investigator_unittest.cc +++ b/components/signin/core/browser/account_investigator_unittest.cc
@@ -10,8 +10,8 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_task_environment.h" #include "components/prefs/pref_registry_simple.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/sync_preferences/testing_pref_service_syncable.h"
diff --git a/components/signin/core/browser/account_reconcilor.cc b/components/signin/core/browser/account_reconcilor.cc index f8b9189..a95657d 100644 --- a/components/signin/core/browser/account_reconcilor.cc +++ b/components/signin/core/browser/account_reconcilor.cc
@@ -20,15 +20,15 @@ #include "base/stl_util.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor_delegate.h" #include "components/signin/core/browser/consistency_cookie_manager_base.h" -#include "components/signin/core/browser/set_accounts_in_cookie_result.h" -#include "components/signin/core/browser/signin_client.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/accounts_cookie_mutator.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/accounts_mutator.h" +#include "components/signin/public/identity_manager/set_accounts_in_cookie_result.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/google_service_auth_error.h"
diff --git a/components/signin/core/browser/account_reconcilor.h b/components/signin/core/browser/account_reconcilor.h index cc29fce..6dce3b27 100644 --- a/components/signin/core/browser/account_reconcilor.h +++ b/components/signin/core/browser/account_reconcilor.h
@@ -23,9 +23,9 @@ #include "components/content_settings/core/common/content_settings_pattern.h" #include "components/keyed_service/core/keyed_service.h" #include "components/signin/core/browser/account_reconcilor_delegate.h" -#include "components/signin/core/browser/signin_client.h" #include "components/signin/core/browser/signin_header_helper.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "google_apis/gaia/google_service_auth_error.h"
diff --git a/components/signin/core/browser/account_reconcilor_unittest.cc b/components/signin/core/browser/account_reconcilor_unittest.cc index 498a475e..05ffdd3 100644 --- a/components/signin/core/browser/account_reconcilor_unittest.cc +++ b/components/signin/core/browser/account_reconcilor_unittest.cc
@@ -21,20 +21,20 @@ #include "build/build_config.h" #include "components/image_fetcher/core/fake_image_decoder.h" #include "components/prefs/pref_registry_simple.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor.h" -#include "components/signin/core/browser/list_accounts_test_utils.h" #include "components/signin/core/browser/mice_account_reconcilor_delegate.h" #include "components/signin/core/browser/mirror_account_reconcilor_delegate.h" -#include "components/signin/core/browser/set_accounts_in_cookie_result.h" -#include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/list_accounts_test_utils.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" +#include "components/signin/public/identity_manager/set_accounts_in_cookie_result.h" #include "components/sync_preferences/pref_service_syncable.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/gaia_constants.h"
diff --git a/components/signin/core/browser/account_tracker_service.cc b/components/signin/core/browser/account_tracker_service.cc index 4c2ed3d..9a38acca 100644 --- a/components/signin/core/browser/account_tracker_service.cc +++ b/components/signin/core/browser/account_tracker_service.cc
@@ -24,7 +24,7 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/signin/core/browser/account_info_util.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #if defined(OS_ANDROID) #include "base/android/jni_array.h"
diff --git a/components/signin/core/browser/account_tracker_service.h b/components/signin/core/browser/account_tracker_service.h index 563c459..ee877690 100644 --- a/components/signin/core/browser/account_tracker_service.h +++ b/components/signin/core/browser/account_tracker_service.h
@@ -19,7 +19,7 @@ #include "base/timer/timer.h" #include "build/build_config.h" #include "components/keyed_service/core/keyed_service.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "google_apis/gaia/core_account_id.h" #include "google_apis/gaia/gaia_auth_util.h" #include "ui/gfx/image/image.h"
diff --git a/components/signin/core/browser/account_tracker_service_unittest.cc b/components/signin/core/browser/account_tracker_service_unittest.cc index 02a9d2f..aec99585 100644 --- a/components/signin/core/browser/account_tracker_service_unittest.cc +++ b/components/signin/core/browser/account_tracker_service_unittest.cc
@@ -19,12 +19,12 @@ #include "components/prefs/scoped_user_pref_update.h" #include "components/prefs/testing_pref_service.h" #include "components/signin/core/browser/account_fetcher_service.h" -#include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/avatar_icon_util.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/avatar_icon_util.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/test_signin_client.h" +#include "components/signin/public/identity_manager/account_info.h" #include "google_apis/gaia/gaia_oauth_client.h" #include "google_apis/gaia/gaia_urls.h" #include "net/http/http_status_code.h"
diff --git a/components/signin/core/browser/chrome_connected_header_helper.h b/components/signin/core/browser/chrome_connected_header_helper.h index 6060562..81831b2 100644 --- a/components/signin/core/browser/chrome_connected_header_helper.h +++ b/components/signin/core/browser/chrome_connected_header_helper.h
@@ -7,8 +7,8 @@ #include <string> -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/signin_header_helper.h" +#include "components/signin/public/base/account_consistency_method.h" class GURL;
diff --git a/components/signin/core/browser/consistency_cookie_manager_base.cc b/components/signin/core/browser/consistency_cookie_manager_base.cc index 03eabca..92dee2a0 100644 --- a/components/signin/core/browser/consistency_cookie_manager_base.cc +++ b/components/signin/core/browser/consistency_cookie_manager_base.cc
@@ -6,7 +6,7 @@ #include "base/logging.h" #include "base/time/time.h" -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/signin_client.h" #include "google_apis/gaia/gaia_urls.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_options.h"
diff --git a/components/signin/core/browser/consistency_cookie_manager_base.h b/components/signin/core/browser/consistency_cookie_manager_base.h index 63408695..7c1d551 100644 --- a/components/signin/core/browser/consistency_cookie_manager_base.h +++ b/components/signin/core/browser/consistency_cookie_manager_base.h
@@ -8,7 +8,7 @@ #include "base/macros.h" #include "base/scoped_observer.h" #include "components/signin/core/browser/account_reconcilor.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" class SigninClient;
diff --git a/components/signin/core/browser/consistency_cookie_manager_unittest.cc b/components/signin/core/browser/consistency_cookie_manager_unittest.cc index 5eec907f..c28fda9 100644 --- a/components/signin/core/browser/consistency_cookie_manager_unittest.cc +++ b/components/signin/core/browser/consistency_cookie_manager_unittest.cc
@@ -9,10 +9,10 @@ #include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/account_reconcilor_delegate.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/gaia_urls.h"
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate.cc b/components/signin/core/browser/dice_account_reconcilor_delegate.cc index 9ae6112..f57af3f 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate.cc +++ b/components/signin/core/browser/dice_account_reconcilor_delegate.cc
@@ -10,8 +10,8 @@ #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_client.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_pref_names.h" namespace signin {
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate.h b/components/signin/core/browser/dice_account_reconcilor_delegate.h index e532986..57e09ae 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate.h +++ b/components/signin/core/browser/dice_account_reconcilor_delegate.h
@@ -8,8 +8,8 @@ #include <string> #include "base/macros.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor_delegate.h" +#include "components/signin/public/base/account_consistency_method.h" class SigninClient;
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc b/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc index b14cc2f..c270b74 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc +++ b/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc
@@ -7,9 +7,9 @@ #include <vector> #include "components/prefs/pref_registry_simple.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/gaia_auth_util.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/components/signin/core/browser/dice_header_helper.h b/components/signin/core/browser/dice_header_helper.h index cd725f2..d4711431 100644 --- a/components/signin/core/browser/dice_header_helper.h +++ b/components/signin/core/browser/dice_header_helper.h
@@ -8,8 +8,8 @@ #include <string> #include "base/macros.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/signin_header_helper.h" +#include "components/signin/public/base/account_consistency_method.h" class GURL;
diff --git a/components/signin/core/browser/gaia_cookie_manager_service.cc b/components/signin/core/browser/gaia_cookie_manager_service.cc index f50601e..f4364b4 100644 --- a/components/signin/core/browser/gaia_cookie_manager_service.cc +++ b/components/signin/core/browser/gaia_cookie_manager_service.cc
@@ -24,9 +24,9 @@ #include "build/build_config.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/oauth_multilogin_helper.h" -#include "components/signin/core/browser/set_accounts_in_cookie_result.h" -#include "components/signin/core/browser/signin_metrics.h" #include "components/signin/core/browser/ubertoken_fetcher_impl.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/identity_manager/set_accounts_in_cookie_result.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/oauth2_token_service.h"
diff --git a/components/signin/core/browser/gaia_cookie_manager_service.h b/components/signin/core/browser/gaia_cookie_manager_service.h index b37e51d..c9f6eff6 100644 --- a/components/signin/core/browser/gaia_cookie_manager_service.h +++ b/components/signin/core/browser/gaia_cookie_manager_service.h
@@ -19,7 +19,7 @@ #include "base/observer_list.h" #include "base/timer/timer.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/signin_client.h" #include "google_apis/gaia/gaia_auth_consumer.h" #include "google_apis/gaia/gaia_auth_fetcher.h" #include "google_apis/gaia/gaia_auth_util.h"
diff --git a/components/signin/core/browser/gaia_cookie_manager_service_unittest.cc b/components/signin/core/browser/gaia_cookie_manager_service_unittest.cc index c13406f5..99b23ef 100644 --- a/components/signin/core/browser/gaia_cookie_manager_service_unittest.cc +++ b/components/signin/core/browser/gaia_cookie_manager_service_unittest.cc
@@ -25,8 +25,8 @@ #include "components/prefs/testing_pref_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/test_signin_client.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/gaia_urls.h" #include "services/network/test/test_url_loader_factory.h"
diff --git a/components/signin/core/browser/mice_account_reconcilor_delegate.cc b/components/signin/core/browser/mice_account_reconcilor_delegate.cc index 1c29d03a..8b8c936 100644 --- a/components/signin/core/browser/mice_account_reconcilor_delegate.cc +++ b/components/signin/core/browser/mice_account_reconcilor_delegate.cc
@@ -5,7 +5,6 @@ #include "components/signin/core/browser/mice_account_reconcilor_delegate.h" #include "base/logging.h" -#include "components/signin/core/browser/account_reconcilor.h" namespace signin {
diff --git a/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.cc b/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.cc index 066d0bc..e77d9937 100644 --- a/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.cc +++ b/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.cc
@@ -16,11 +16,11 @@ #include "build/build_config.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/signin_client.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" #include "components/signin/core/browser/webdata/token_web_data.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/webdata/common/web_data_service_base.h" #include "google_apis/gaia/gaia_auth_fetcher.h" #include "google_apis/gaia/gaia_auth_util.h"
diff --git a/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.h b/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.h index 9960cd30..5edfc4e 100644 --- a/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.h +++ b/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate.h
@@ -12,10 +12,10 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/threading/thread_checker.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/webdata/token_web_data.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/webdata/common/web_data_service_base.h" #include "components/webdata/common/web_data_service_consumer.h" #include "google_apis/gaia/oauth2_token_service_delegate.h"
diff --git a/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate_unittest.cc b/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate_unittest.cc index fb5463a..2b8c030c 100644 --- a/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate_unittest.cc +++ b/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate_unittest.cc
@@ -22,15 +22,15 @@ #include "components/os_crypt/os_crypt_mocker.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/device_id_helper.h" #include "components/signin/core/browser/primary_account_manager.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" #include "components/signin/core/browser/webdata/token_web_data.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/device_id_helper.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/test_signin_client.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/webdata/common/web_data_service_base.h" #include "components/webdata/common/web_database_service.h"
diff --git a/components/signin/core/browser/oauth2_token_service_delegate_android.cc b/components/signin/core/browser/oauth2_token_service_delegate_android.cc index b92719e8..6cfddbe5 100644 --- a/components/signin/core/browser/oauth2_token_service_delegate_android.cc +++ b/components/signin/core/browser/oauth2_token_service_delegate_android.cc
@@ -14,9 +14,9 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/android/jni_headers/OAuth2TokenService_jni.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/identity_manager/account_info.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/oauth2_access_token_fetcher.h"
diff --git a/components/signin/core/browser/oauth_multilogin_helper.cc b/components/signin/core/browser/oauth_multilogin_helper.cc index 98cbb26..f15ed62 100644 --- a/components/signin/core/browser/oauth_multilogin_helper.cc +++ b/components/signin/core/browser/oauth_multilogin_helper.cc
@@ -13,8 +13,8 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "components/signin/core/browser/oauth_multilogin_token_fetcher.h" -#include "components/signin/core/browser/set_accounts_in_cookie_result.h" -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/identity_manager/set_accounts_in_cookie_result.h" #include "google_apis/gaia/google_service_auth_error.h" #include "google_apis/gaia/oauth_multilogin_result.h" #include "mojo/public/cpp/bindings/callback_helpers.h"
diff --git a/components/signin/core/browser/oauth_multilogin_helper_unittest.cc b/components/signin/core/browser/oauth_multilogin_helper_unittest.cc index 03b41c0..f121bc1 100644 --- a/components/signin/core/browser/oauth_multilogin_helper_unittest.cc +++ b/components/signin/core/browser/oauth_multilogin_helper_unittest.cc
@@ -10,8 +10,8 @@ #include "base/test/scoped_task_environment.h" #include "components/prefs/testing_pref_service.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" -#include "components/signin/core/browser/set_accounts_in_cookie_result.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/test_signin_client.h" +#include "components/signin/public/identity_manager/set_accounts_in_cookie_result.h" #include "google_apis/gaia/gaia_urls.h" #include "services/network/test/test_cookie_manager.h" #include "services/network/test/test_url_loader_factory.h"
diff --git a/components/signin/core/browser/oauth_multilogin_token_fetcher.cc b/components/signin/core/browser/oauth_multilogin_token_fetcher.cc index 2ee0967..2579548 100644 --- a/components/signin/core/browser/oauth_multilogin_token_fetcher.cc +++ b/components/signin/core/browser/oauth_multilogin_token_fetcher.cc
@@ -13,7 +13,7 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/signin_client.h" namespace {
diff --git a/components/signin/core/browser/oauth_multilogin_token_fetcher_unittest.cc b/components/signin/core/browser/oauth_multilogin_token_fetcher_unittest.cc index c601ba6..e5e18df 100644 --- a/components/signin/core/browser/oauth_multilogin_token_fetcher_unittest.cc +++ b/components/signin/core/browser/oauth_multilogin_token_fetcher_unittest.cc
@@ -13,7 +13,7 @@ #include "base/test/scoped_task_environment.h" #include "components/prefs/testing_pref_service.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/test_signin_client.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/gaia_urls.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/signin/core/browser/primary_account_manager.cc b/components/signin/core/browser/primary_account_manager.cc index 42af5f3..8a3f5674 100644 --- a/components/signin/core/browser/primary_account_manager.cc +++ b/components/signin/core/browser/primary_account_manager.cc
@@ -14,14 +14,14 @@ #include "base/metrics/histogram_macros.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/primary_account_policy_manager.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_client.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/signin_switches.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/signin_switches.h" +#include "components/signin/public/identity_manager/account_info.h" PrimaryAccountManager::PrimaryAccountManager( SigninClient* client,
diff --git a/components/signin/core/browser/primary_account_manager.h b/components/signin/core/browser/primary_account_manager.h index 8c554d0b..cf556a6a 100644 --- a/components/signin/core/browser/primary_account_manager.h +++ b/components/signin/core/browser/primary_account_manager.h
@@ -24,8 +24,8 @@ #include "base/callback.h" #include "base/callback_list.h" #include "base/macros.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_client.h" #include "google_apis/gaia/oauth2_token_service_observer.h" struct AccountInfo;
diff --git a/components/signin/core/browser/primary_account_manager_unittest.cc b/components/signin/core/browser/primary_account_manager_unittest.cc index efc60bf..90f7a42 100644 --- a/components/signin/core/browser/primary_account_manager_unittest.cc +++ b/components/signin/core/browser/primary_account_manager_unittest.cc
@@ -17,13 +17,13 @@ #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/prefs/testing_pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_fetcher_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/primary_account_policy_manager.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/fake_oauth2_token_service_delegate.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/signin/core/browser/primary_account_policy_manager_impl.cc b/components/signin/core/browser/primary_account_policy_manager_impl.cc index 5e474841..437ee68 100644 --- a/components/signin/core/browser/primary_account_policy_manager_impl.cc +++ b/components/signin/core/browser/primary_account_policy_manager_impl.cc
@@ -11,12 +11,12 @@ #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_member.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/identity_utils.h" #include "components/signin/core/browser/primary_account_manager.h" -#include "components/signin/core/browser/signin_client.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/identity_manager/account_info.h" +#include "components/signin/public/identity_manager/identity_utils.h" PrimaryAccountPolicyManagerImpl::PrimaryAccountPolicyManagerImpl( SigninClient* client)
diff --git a/components/signin/core/browser/primary_account_policy_manager_impl_unittest.cc b/components/signin/core/browser/primary_account_policy_manager_impl_unittest.cc index 7597152..f81a959 100644 --- a/components/signin/core/browser/primary_account_policy_manager_impl_unittest.cc +++ b/components/signin/core/browser/primary_account_policy_manager_impl_unittest.cc
@@ -10,13 +10,13 @@ #include "base/test/scoped_task_environment.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/primary_account_manager.h" #include "components/signin/core/browser/primary_account_policy_manager_impl.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/fake_oauth2_token_service_delegate.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/signin/core/browser/profile_oauth2_token_service.cc b/components/signin/core/browser/profile_oauth2_token_service.cc index 4c083563..9b964d78 100644 --- a/components/signin/core/browser/profile_oauth2_token_service.cc +++ b/components/signin/core/browser/profile_oauth2_token_service.cc
@@ -8,8 +8,8 @@ #include "base/logging.h" #include "build/build_config.h" #include "components/prefs/pref_registry_simple.h" -#include "components/signin/core/browser/device_id_helper.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/device_id_helper.h" +#include "components/signin/public/base/signin_pref_names.h" using signin_metrics::SourceForRefreshTokenOperation;
diff --git a/components/signin/core/browser/profile_oauth2_token_service.h b/components/signin/core/browser/profile_oauth2_token_service.h index fd04ed8..6addfb0e 100644 --- a/components/signin/core/browser/profile_oauth2_token_service.h +++ b/components/signin/core/browser/profile_oauth2_token_service.h
@@ -12,8 +12,8 @@ #include "base/macros.h" #include "build/buildflag.h" #include "components/keyed_service/core/keyed_service.h" -#include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_buildflags.h" +#include "components/signin/public/base/signin_metrics.h" #include "google_apis/gaia/oauth2_token_service.h" #include "google_apis/gaia/oauth2_token_service_delegate.h" #include "net/base/backoff_entry.h"
diff --git a/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc index 438b76d..a100390e 100644 --- a/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc +++ b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc
@@ -16,10 +16,10 @@ #include "base/stl_util.h" #include "base/test/scoped_task_environment.h" #include "chromeos/components/account_manager/account_manager.h" -#include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/test_signin_client.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/oauth2_access_token_consumer.h"
diff --git a/components/signin/core/browser/signin_error_controller.cc b/components/signin/core/browser/signin_error_controller.cc index e3e4668..45c63c1 100644 --- a/components/signin/core/browser/signin_error_controller.cc +++ b/components/signin/core/browser/signin_error_controller.cc
@@ -4,7 +4,7 @@ #include "components/signin/core/browser/signin_error_controller.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" SigninErrorController::SigninErrorController( AccountMode mode,
diff --git a/components/signin/core/browser/signin_header_helper.h b/components/signin/core/browser/signin_header_helper.h index c202229..265698b 100644 --- a/components/signin/core/browser/signin_header_helper.h +++ b/components/signin/core/browser/signin_header_helper.h
@@ -10,8 +10,8 @@ #include <vector> #include "components/prefs/pref_member.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_buildflags.h" #include "url/gurl.h" namespace content_settings {
diff --git a/components/signin/core/browser/signin_header_helper_unittest.cc b/components/signin/core/browser/signin_header_helper_unittest.cc index 61487c8..c36fd26 100644 --- a/components/signin/core/browser/signin_header_helper_unittest.cc +++ b/components/signin/core/browser/signin_header_helper_unittest.cc
@@ -14,9 +14,9 @@ #include "build/build_config.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "components/prefs/pref_member.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/chrome_connected_header_helper.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_buildflags.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/gaia_urls.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
diff --git a/components/signin/core/browser/signin_investigator.cc b/components/signin/core/browser/signin_investigator.cc index 7dc1236e..e069fb2 100644 --- a/components/signin/core/browser/signin_investigator.cc +++ b/components/signin/core/browser/signin_investigator.cc
@@ -6,8 +6,8 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "google_apis/gaia/gaia_auth_util.h" using signin_metrics::AccountEquality;
diff --git a/components/signin/core/browser/signin_investigator_unittest.cc b/components/signin/core/browser/signin_investigator_unittest.cc index de525a6..b11e32f 100644 --- a/components/signin/core/browser/signin_investigator_unittest.cc +++ b/components/signin/core/browser/signin_investigator_unittest.cc
@@ -8,8 +8,8 @@ #include "base/test/scoped_task_environment.h" #include "components/prefs/pref_registry_simple.h" #include "components/signin/core/browser/signin_investigator.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/signin/core/browser/ubertoken_fetcher_impl.h b/components/signin/core/browser/ubertoken_fetcher_impl.h index 35f436d..e9d3c19 100644 --- a/components/signin/core/browser/ubertoken_fetcher_impl.h +++ b/components/signin/core/browser/ubertoken_fetcher_impl.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "base/timer/timer.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/ubertoken_fetcher.h" +#include "components/signin/public/identity_manager/ubertoken_fetcher.h" #include "google_apis/gaia/gaia_auth_consumer.h" #include "google_apis/gaia/gaia_auth_fetcher.h"
diff --git a/components/signin/internal/identity_manager/BUILD.gn b/components/signin/internal/identity_manager/BUILD.gn index 6e8f541..b96d8a9 100644 --- a/components/signin/internal/identity_manager/BUILD.gn +++ b/components/signin/internal/identity_manager/BUILD.gn
@@ -21,8 +21,8 @@ deps = [ "//components/prefs", "//components/signin/core/browser:internals", - "//components/signin/core/browser:shared", - "//components/signin/core/browser:signin_buildflags", + "//components/signin/public/base", + "//components/signin/public/base:signin_buildflags", "//google_apis", ] @@ -32,4 +32,11 @@ "accounts_mutator_impl.h", ] } + + if (is_ios) { + sources += [ + "device_accounts_synchronizer_impl.cc", + "device_accounts_synchronizer_impl.h", + ] + } }
diff --git a/components/signin/internal/identity_manager/accounts_mutator_impl.cc b/components/signin/internal/identity_manager/accounts_mutator_impl.cc index 85dc462..da3c96e 100644 --- a/components/signin/internal/identity_manager/accounts_mutator_impl.cc +++ b/components/signin/internal/identity_manager/accounts_mutator_impl.cc
@@ -6,12 +6,12 @@ #include "base/optional.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/device_id_helper.h" #include "components/signin/core/browser/primary_account_manager.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/device_id_helper.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/identity_manager/account_info.h" #include "google_apis/gaia/core_account_id.h" namespace identity {
diff --git a/components/signin/internal/identity_manager/accounts_mutator_impl.h b/components/signin/internal/identity_manager/accounts_mutator_impl.h index f0b2ef8..353220e 100644 --- a/components/signin/internal/identity_manager/accounts_mutator_impl.h +++ b/components/signin/internal/identity_manager/accounts_mutator_impl.h
@@ -8,7 +8,7 @@ #include <string> #include "base/macros.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" #include "components/signin/public/identity_manager/accounts_mutator.h" namespace signin_metrics {
diff --git a/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc new file mode 100644 index 0000000..4e234eaf --- /dev/null +++ b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc
@@ -0,0 +1,30 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h" + +#include "base/logging.h" +#include "google_apis/gaia/oauth2_token_service_delegate.h" + +namespace identity { + +DeviceAccountsSynchronizerImpl::DeviceAccountsSynchronizerImpl( + OAuth2TokenServiceDelegate* token_service_delegate) + : token_service_delegate_(token_service_delegate) { + DCHECK(token_service_delegate_); +} + +DeviceAccountsSynchronizerImpl::~DeviceAccountsSynchronizerImpl() = default; + +void DeviceAccountsSynchronizerImpl::ReloadAllAccountsFromSystem() { + token_service_delegate_->ReloadAccountsFromSystem( + /*primary_account_id=*/CoreAccountId()); +} + +void DeviceAccountsSynchronizerImpl::ReloadAccountFromSystem( + const CoreAccountId& account_id) { + token_service_delegate_->AddAccountFromSystem(account_id); +} + +} // namespace identity
diff --git a/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h new file mode 100644 index 0000000..32dff8ea --- /dev/null +++ b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h
@@ -0,0 +1,31 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_IMPL_H_ +#define COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_IMPL_H_ + +#include "components/signin/public/identity_manager/device_accounts_synchronizer.h" + +class OAuth2TokenServiceDelegate; + +namespace identity { + +// Concrete implementation of DeviceAccountsSynchronizer interface. +class DeviceAccountsSynchronizerImpl : public DeviceAccountsSynchronizer { + public: + explicit DeviceAccountsSynchronizerImpl( + OAuth2TokenServiceDelegate* token_service_delegate); + ~DeviceAccountsSynchronizerImpl() override; + + // DeviceAccountsSynchronizer implementation. + void ReloadAllAccountsFromSystem() override; + void ReloadAccountFromSystem(const CoreAccountId& account_id) override; + + private: + OAuth2TokenServiceDelegate* token_service_delegate_ = nullptr; +}; + +} // namespace identity + +#endif // COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_IMPL_H_
diff --git a/components/signin/internal/identity_manager/primary_account_mutator_impl.cc b/components/signin/internal/identity_manager/primary_account_mutator_impl.cc index 8479687f..b3862476 100644 --- a/components/signin/internal/identity_manager/primary_account_mutator_impl.cc +++ b/components/signin/internal/identity_manager/primary_account_mutator_impl.cc
@@ -10,8 +10,8 @@ #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/primary_account_manager.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "google_apis/gaia/core_account_id.h" namespace identity { @@ -30,25 +30,38 @@ PrimaryAccountMutatorImpl::~PrimaryAccountMutatorImpl() {} -#if !defined(OS_CHROMEOS) bool PrimaryAccountMutatorImpl::SetPrimaryAccount( const CoreAccountId& account_id) { + AccountInfo account_info = account_tracker_->GetAccountInfo(account_id); + +#if !defined(OS_CHROMEOS) if (!pref_service_->GetBoolean(prefs::kSigninAllowed)) return false; if (primary_account_manager_->IsAuthenticated()) return false; - AccountInfo account_info = account_tracker_->GetAccountInfo(account_id); if (account_info.account_id != account_id || account_info.email.empty()) return false; // TODO(crbug.com/889899): should check that the account email is allowed. +#endif primary_account_manager_->SignIn(account_info.email); return true; } +#if defined(OS_CHROMEOS) +bool PrimaryAccountMutatorImpl::SetPrimaryAccountAndUpdateAccountInfo( + const std::string& gaia_id, + const std::string& email) { + CoreAccountId account_id = account_tracker_->SeedAccountInfo(gaia_id, email); + SetPrimaryAccount(account_id); + return true; +} +#endif + +#if !defined(OS_CHROMEOS) bool PrimaryAccountMutatorImpl::ClearPrimaryAccount( ClearAccountsAction action, signin_metrics::ProfileSignout source_metric, @@ -72,14 +85,6 @@ return true; } -#else -bool PrimaryAccountMutatorImpl::SetPrimaryAccountAndUpdateAccountInfo( - const std::string& gaia_id, - const std::string& email) { - account_tracker_->SeedAccountInfo(gaia_id, email); - primary_account_manager_->SignIn(email); - return true; -} #endif } // namespace identity
diff --git a/components/signin/internal/identity_manager/primary_account_mutator_impl.h b/components/signin/internal/identity_manager/primary_account_mutator_impl.h index 14bc379..d8ec968 100644 --- a/components/signin/internal/identity_manager/primary_account_mutator_impl.h +++ b/components/signin/internal/identity_manager/primary_account_mutator_impl.h
@@ -25,15 +25,16 @@ ~PrimaryAccountMutatorImpl() override; // PrimaryAccountMutator implementation. -#if !defined(OS_CHROMEOS) bool SetPrimaryAccount(const CoreAccountId& account_id) override; +#if defined(OS_CHROMEOS) + bool SetPrimaryAccountAndUpdateAccountInfo(const std::string& gaia_id, + const std::string& email) override; +#endif +#if !defined(OS_CHROMEOS) bool ClearPrimaryAccount( ClearAccountsAction action, signin_metrics::ProfileSignout source_metric, signin_metrics::SignoutDelete delete_metric) override; -#else - bool SetPrimaryAccountAndUpdateAccountInfo(const std::string& gaia_id, - const std::string& email) override; #endif private:
diff --git a/components/signin/ios/browser/BUILD.gn b/components/signin/ios/browser/BUILD.gn index cbc35a2..7e5c85e 100644 --- a/components/signin/ios/browser/BUILD.gn +++ b/components/signin/ios/browser/BUILD.gn
@@ -75,7 +75,7 @@ ":test_support", "//components/prefs:test_support", "//components/signin/core/browser", - "//components/signin/core/browser:internals_test_support", + "//components/signin/public/base:test_support", "//components/signin/public/identity_manager:test_support", "//components/sync_preferences:test_support", "//ios/web",
diff --git a/components/signin/ios/browser/account_consistency_service.mm b/components/signin/ios/browser/account_consistency_service.mm index 043e016..d6adff9 100644 --- a/components/signin/ios/browser/account_consistency_service.mm +++ b/components/signin/ios/browser/account_consistency_service.mm
@@ -14,9 +14,9 @@ #include "components/google/core/common/google_util.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/signin_header_helper.h" +#include "components/signin/public/base/account_consistency_method.h" #include "ios/web/public/browser_state.h" #include "ios/web/public/web_state/web_state_policy_decider.h" #include "ios/web/public/web_view_creation_util.h"
diff --git a/components/signin/ios/browser/account_consistency_service_unittest.mm b/components/signin/ios/browser/account_consistency_service_unittest.mm index 0e6134e0..99196ea 100644 --- a/components/signin/ios/browser/account_consistency_service_unittest.mm +++ b/components/signin/ios/browser/account_consistency_service_unittest.mm
@@ -13,8 +13,8 @@ #include "base/values.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/account_reconcilor_delegate.h" -#include "components/signin/core/browser/list_accounts_test_utils.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/list_accounts_test_utils.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/signin/public/identity_manager/test_identity_manager_observer.h"
diff --git a/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.mm b/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.mm index 360ec8b..8e2cb1f 100644 --- a/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.mm +++ b/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.mm
@@ -18,11 +18,11 @@ #include "base/values.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/signin_client.h" -#include "components/signin/core/browser/signin_pref_names.h" #include "components/signin/ios/browser/device_accounts_provider.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/identity_manager/account_info.h" #include "google_apis/gaia/oauth2_access_token_fetcher.h" #include "net/url_request/url_request_status.h"
diff --git a/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate_unittest.mm b/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate_unittest.mm index db4e3a3..29a4649 100644 --- a/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate_unittest.mm +++ b/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate_unittest.mm
@@ -11,9 +11,9 @@ #include "components/prefs/testing_pref_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" #include "components/signin/ios/browser/fake_device_accounts_provider.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/test_signin_client.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/oauth2_access_token_consumer.h" #include "google_apis/gaia/oauth2_access_token_fetcher.h"
diff --git a/components/signin/public/base/BUILD.gn b/components/signin/public/base/BUILD.gn new file mode 100644 index 0000000..55b7f13 --- /dev/null +++ b/components/signin/public/base/BUILD.gn
@@ -0,0 +1,97 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/buildflag_header.gni") +import("//components/signin/features.gni") + +if (is_android) { + import("//build/config/android/rules.gni") +} + +buildflag_header("signin_buildflags") { + header = "signin_buildflags.h" + flags = [ + "ENABLE_DICE_SUPPORT=$enable_dice_support", + "ENABLE_MIRROR=$enable_mirror", + ] +} + +static_library("base") { + sources = [ + "account_consistency_method.cc", + "account_consistency_method.h", + "avatar_icon_util.cc", + "avatar_icon_util.h", + "device_id_helper.cc", + "device_id_helper.h", + "signin_client.cc", + "signin_client.h", + "signin_metrics.cc", + "signin_metrics.h", + "signin_pref_names.cc", + "signin_pref_names.h", + "signin_switches.cc", + "signin_switches.h", + ] + deps = [ + ":signin_buildflags", + "//components/account_id", + "//components/keyed_service/core", + "//components/prefs", + "//third_party/icu:icui18n", + "//third_party/re2", + "//ui/gfx", + "//url", + ] + public_deps = [ + "//base", + "//google_apis", + ] + + if (is_chromeos) { + deps += [ "//components/user_manager" ] + } +} + +static_library("test_support") { + testonly = true + sources = [ + "list_accounts_test_utils.cc", + "list_accounts_test_utils.h", + "test_signin_client.cc", + "test_signin_client.h", + ] + + deps = [ + "//base/test:test_support", + "//components/prefs", + "//google_apis:test_support", + ] + + public_deps = [ + ":base", + "//base", + "//services/network:test_support", + ] +} + +source_set("unit_tests") { + testonly = true + sources = [ + "avatar_icon_util_unittest.cc", + "device_id_helper_unittest.cc", + "signin_metrics_unittest.cc", + ] + + deps = [ + ":base", + ":signin_buildflags", + "//base/test:test_support", + "//components/sync_preferences:test_support", + "//testing/gmock", + "//testing/gtest", + "//ui/gfx:test_support", + "//url", + ] +}
diff --git a/components/signin/public/base/DEPS b/components/signin/public/base/DEPS new file mode 100644 index 0000000..9ddadaf --- /dev/null +++ b/components/signin/public/base/DEPS
@@ -0,0 +1,5 @@ +include_rules = [ + "+components/account_id", + "+components/user_manager/known_user.h", + "+third_party/re2/src/re2/re2.h", +]
diff --git a/components/signin/core/browser/account_consistency_method.cc b/components/signin/public/base/account_consistency_method.cc similarity index 92% rename from components/signin/core/browser/account_consistency_method.cc rename to components/signin/public/base/account_consistency_method.cc index b0b031a..ba77c9a7 100644 --- a/components/signin/core/browser/account_consistency_method.cc +++ b/components/signin/public/base/account_consistency_method.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "base/logging.h"
diff --git a/components/signin/core/browser/account_consistency_method.h b/components/signin/public/base/account_consistency_method.h similarity index 87% rename from components/signin/core/browser/account_consistency_method.h rename to components/signin/public/base/account_consistency_method.h index c46becf..5ca1dfea 100644 --- a/components/signin/core/browser/account_consistency_method.h +++ b/components/signin/public/base/account_consistency_method.h
@@ -6,8 +6,8 @@ // possible overrides from Experiements. This is done inside chrome/common // because it is accessed by files through the chrome/ directory tree. -#ifndef COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_CONSISTENCY_METHOD_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_CONSISTENCY_METHOD_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_BASE_ACCOUNT_CONSISTENCY_METHOD_H_ +#define COMPONENTS_SIGNIN_PUBLIC_BASE_ACCOUNT_CONSISTENCY_METHOD_H_ #include "base/feature_list.h" #include "build/build_config.h" @@ -47,4 +47,4 @@ } // namespace signin -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_CONSISTENCY_METHOD_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_BASE_ACCOUNT_CONSISTENCY_METHOD_H_
diff --git a/components/signin/core/browser/avatar_icon_util.cc b/components/signin/public/base/avatar_icon_util.cc similarity index 98% rename from components/signin/core/browser/avatar_icon_util.cc rename to components/signin/public/base/avatar_icon_util.cc index 2a74566..ff2dfa3 100644 --- a/components/signin/core/browser/avatar_icon_util.cc +++ b/components/signin/public/base/avatar_icon_util.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/avatar_icon_util.h" +#include "components/signin/public/base/avatar_icon_util.h" #include <string> #include <vector>
diff --git a/components/signin/core/browser/avatar_icon_util.h b/components/signin/public/base/avatar_icon_util.h similarity index 83% rename from components/signin/core/browser/avatar_icon_util.h rename to components/signin/public/base/avatar_icon_util.h index 4209820a..26b6b83 100644 --- a/components/signin/core/browser/avatar_icon_util.h +++ b/components/signin/public/base/avatar_icon_util.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 COMPONENTS_SIGNIN_CORE_BROWSER_AVATAR_ICON_UTIL_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_AVATAR_ICON_UTIL_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_BASE_AVATAR_ICON_UTIL_H_ +#define COMPONENTS_SIGNIN_PUBLIC_BASE_AVATAR_ICON_UTIL_H_ class GURL; @@ -24,4 +24,4 @@ } // namespace signin -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_AVATAR_ICON_UTIL_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_BASE_AVATAR_ICON_UTIL_H_
diff --git a/components/signin/core/browser/avatar_icon_util_unittest.cc b/components/signin/public/base/avatar_icon_util_unittest.cc similarity index 98% rename from components/signin/core/browser/avatar_icon_util_unittest.cc rename to components/signin/public/base/avatar_icon_util_unittest.cc index f368624..0c8f7ce7 100644 --- a/components/signin/core/browser/avatar_icon_util_unittest.cc +++ b/components/signin/public/base/avatar_icon_util_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/avatar_icon_util.h" +#include "components/signin/public/base/avatar_icon_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h"
diff --git a/components/signin/core/browser/device_id_helper.cc b/components/signin/public/base/device_id_helper.cc similarity index 88% rename from components/signin/core/browser/device_id_helper.cc rename to components/signin/public/base/device_id_helper.cc index 6f0dcbb..99c262a 100644 --- a/components/signin/core/browser/device_id_helper.cc +++ b/components/signin/public/base/device_id_helper.cc
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/device_id_helper.h" +#include "components/signin/public/base/device_id_helper.h" #include "base/command_line.h" #include "base/guid.h" #include "base/logging.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/signin_switches.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/base/signin_switches.h" namespace signin {
diff --git a/components/signin/core/browser/device_id_helper.h b/components/signin/public/base/device_id_helper.h similarity index 87% rename from components/signin/core/browser/device_id_helper.h rename to components/signin/public/base/device_id_helper.h index 8e9980c9..6bda97cd 100644 --- a/components/signin/core/browser/device_id_helper.h +++ b/components/signin/public/base/device_id_helper.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 COMPONENTS_SIGNIN_CORE_BROWSER_DEVICE_ID_HELPER_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_DEVICE_ID_HELPER_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_BASE_DEVICE_ID_HELPER_H_ +#define COMPONENTS_SIGNIN_PUBLIC_BASE_DEVICE_ID_HELPER_H_ #include <string> @@ -39,4 +39,4 @@ } // namespace signin -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_DEVICE_ID_HELPER_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_BASE_DEVICE_ID_HELPER_H_
diff --git a/components/signin/core/browser/device_id_helper_unittest.cc b/components/signin/public/base/device_id_helper_unittest.cc similarity index 94% rename from components/signin/core/browser/device_id_helper_unittest.cc rename to components/signin/public/base/device_id_helper_unittest.cc index df36320..1a0e3003 100644 --- a/components/signin/core/browser/device_id_helper_unittest.cc +++ b/components/signin/public/base/device_id_helper_unittest.cc
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/device_id_helper.h" +#include "components/signin/public/base/device_id_helper.h" #include <string> #include "build/build_config.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/signin/core/browser/list_accounts_test_utils.cc b/components/signin/public/base/list_accounts_test_utils.cc similarity index 97% rename from components/signin/core/browser/list_accounts_test_utils.cc rename to components/signin/public/base/list_accounts_test_utils.cc index a8a41b2..a07af3a 100644 --- a/components/signin/core/browser/list_accounts_test_utils.cc +++ b/components/signin/public/base/list_accounts_test_utils.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/list_accounts_test_utils.h" +#include "components/signin/public/base/list_accounts_test_utils.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h"
diff --git a/components/signin/core/browser/list_accounts_test_utils.h b/components/signin/public/base/list_accounts_test_utils.h similarity index 90% rename from components/signin/core/browser/list_accounts_test_utils.h rename to components/signin/public/base/list_accounts_test_utils.h index 9a5d897..6b9d0f1 100644 --- a/components/signin/core/browser/list_accounts_test_utils.h +++ b/components/signin/public/base/list_accounts_test_utils.h
@@ -1,8 +1,8 @@ // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_SIGNIN_CORE_BROWSER_LIST_ACCOUNTS_TEST_UTILS_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_LIST_ACCOUNTS_TEST_UTILS_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_BASE_LIST_ACCOUNTS_TEST_UTILS_H_ +#define COMPONENTS_SIGNIN_PUBLIC_BASE_LIST_ACCOUNTS_TEST_UTILS_H_ #include <string> #include <vector> @@ -64,4 +64,4 @@ } // namespace signin -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_LIST_ACCOUNTS_TEST_UTILS_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_BASE_LIST_ACCOUNTS_TEST_UTILS_H_
diff --git a/components/signin/core/browser/signin_client.cc b/components/signin/public/base/signin_client.cc similarity index 90% rename from components/signin/core/browser/signin_client.cc rename to components/signin/public/base/signin_client.cc index b6741ad..8a358e0 100644 --- a/components/signin/core/browser/signin_client.cc +++ b/components/signin/public/base/signin_client.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/signin_client.h" void SigninClient::PreSignOut( base::OnceCallback<void(SignoutDecision)> on_signout_decision_reached,
diff --git a/components/signin/core/browser/signin_client.h b/components/signin/public/base/signin_client.h similarity index 90% rename from components/signin/core/browser/signin_client.h rename to components/signin/public/base/signin_client.h index 10f1e32..d5c7889 100644 --- a/components/signin/core/browser/signin_client.h +++ b/components/signin/public/base/signin_client.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 COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_CLIENT_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_CLIENT_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_CLIENT_H_ +#define COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_CLIENT_H_ #include <memory> @@ -12,8 +12,8 @@ #include "base/time/time.h" #include "build/build_config.h" #include "components/keyed_service/core/keyed_service.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_metrics.h" #include "google_apis/gaia/gaia_auth_fetcher.h" #include "url/gurl.h" @@ -29,7 +29,7 @@ namespace mojom { class CookieManager; } -} +} // namespace network // An interface that needs to be supplied to the Signin component by its // embedder. @@ -97,4 +97,4 @@ virtual void SetReadyForDiceMigration(bool is_ready) {} }; -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_CLIENT_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_CLIENT_H_
diff --git a/components/signin/core/browser/signin_metrics.cc b/components/signin/public/base/signin_metrics.cc similarity index 98% rename from components/signin/core/browser/signin_metrics.cc rename to components/signin/public/base/signin_metrics.cc index 2184d81..64a04cb 100644 --- a/components/signin/core/browser/signin_metrics.cc +++ b/components/signin/public/base/signin_metrics.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include <limits.h> @@ -723,13 +723,11 @@ UMA_HISTOGRAM_BOOLEAN("Signin.Reconciler.AllExternalCcResultCompleted", fetches_completed); if (fetches_completed) { - UMA_HISTOGRAM_TIMES( - "Signin.Reconciler.ExternalCcResultTime.Completed", - time_to_check_connections); + UMA_HISTOGRAM_TIMES("Signin.Reconciler.ExternalCcResultTime.Completed", + time_to_check_connections); } else { - UMA_HISTOGRAM_TIMES( - "Signin.Reconciler.ExternalCcResultTime.NotCompleted", - time_to_check_connections); + UMA_HISTOGRAM_TIMES("Signin.Reconciler.ExternalCcResultTime.NotCompleted", + time_to_check_connections); } }
diff --git a/components/signin/core/browser/signin_metrics.h b/components/signin/public/base/signin_metrics.h similarity index 98% rename from components/signin/core/browser/signin_metrics.h rename to components/signin/public/base/signin_metrics.h index e713ede..77fe702 100644 --- a/components/signin/core/browser/signin_metrics.h +++ b/components/signin/public/base/signin_metrics.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 COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_METRICS_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_METRICS_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_METRICS_H_ +#define COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_METRICS_H_ #include <limits.h> @@ -429,4 +429,4 @@ } // namespace signin_metrics -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_METRICS_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_METRICS_H_
diff --git a/components/signin/core/browser/signin_metrics_unittest.cc b/components/signin/public/base/signin_metrics_unittest.cc similarity index 99% rename from components/signin/core/browser/signin_metrics_unittest.cc rename to components/signin/public/base/signin_metrics_unittest.cc index ab16ec15..3a56f94 100644 --- a/components/signin/core/browser/signin_metrics_unittest.cc +++ b/components/signin/public/base/signin_metrics_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include <string> #include <vector>
diff --git a/components/signin/core/browser/signin_pref_names.cc b/components/signin/public/base/signin_pref_names.cc similarity index 98% rename from components/signin/core/browser/signin_pref_names.cc rename to components/signin/public/base/signin_pref_names.cc index 75a77be..39197c71 100644 --- a/components/signin/core/browser/signin_pref_names.cc +++ b/components/signin/public/base/signin_pref_names.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" namespace prefs {
diff --git a/components/signin/core/browser/signin_pref_names.h b/components/signin/public/base/signin_pref_names.h similarity index 87% rename from components/signin/core/browser/signin_pref_names.h rename to components/signin/public/base/signin_pref_names.h index 61391ea9..54af1c04 100644 --- a/components/signin/core/browser/signin_pref_names.h +++ b/components/signin/public/base/signin_pref_names.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 COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_PREF_NAMES_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_PREF_NAMES_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_PREF_NAMES_H_ +#define COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_PREF_NAMES_H_ namespace prefs { @@ -34,4 +34,4 @@ } // namespace prefs -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_PREF_NAMES_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_PREF_NAMES_H_
diff --git a/components/signin/core/browser/signin_switches.cc b/components/signin/public/base/signin_switches.cc similarity index 94% rename from components/signin/core/browser/signin_switches.cc rename to components/signin/public/base/signin_switches.cc index 7d99de9b..fb905755 100644 --- a/components/signin/core/browser/signin_switches.cc +++ b/components/signin/public/base/signin_switches.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/signin_switches.h" +#include "components/signin/public/base/signin_switches.h" namespace switches {
diff --git a/components/signin/core/browser/signin_switches.h b/components/signin/public/base/signin_switches.h similarity index 79% rename from components/signin/core/browser/signin_switches.h rename to components/signin/public/base/signin_switches.h index 6c2752eb..1397cbf 100644 --- a/components/signin/core/browser/signin_switches.h +++ b/components/signin/public/base/signin_switches.h
@@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_SWITCHES_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_SWITCHES_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_SWITCHES_H_ +#define COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_SWITCHES_H_ -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" namespace switches { @@ -28,4 +28,4 @@ } // namespace switches -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_SWITCHES_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_BASE_SIGNIN_SWITCHES_H_
diff --git a/components/signin/core/browser/test_signin_client.cc b/components/signin/public/base/test_signin_client.cc similarity index 93% rename from components/signin/core/browser/test_signin_client.cc rename to components/signin/public/base/test_signin_client.cc index f62d1b5..cfa57bc 100644 --- a/components/signin/core/browser/test_signin_client.cc +++ b/components/signin/public/base/test_signin_client.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/test_signin_client.h" #include <memory> @@ -68,7 +68,9 @@ test_url_loader_factory_ = factory; } -std::string TestSigninClient::GetProductVersion() { return ""; } +std::string TestSigninClient::GetProductVersion() { + return ""; +} void TestSigninClient::SetNetworkCallsDelayed(bool value) { network_calls_delayed_ = value; @@ -89,12 +91,10 @@ } void TestSigninClient::AddContentSettingsObserver( - content_settings::Observer* observer) { -} + content_settings::Observer* observer) {} void TestSigninClient::RemoveContentSettingsObserver( - content_settings::Observer* observer) { -} + content_settings::Observer* observer) {} void TestSigninClient::DelayNetworkCall(base::OnceClosure callback) { if (network_calls_delayed_) {
diff --git a/components/signin/core/browser/test_signin_client.h b/components/signin/public/base/test_signin_client.h similarity index 93% rename from components/signin/core/browser/test_signin_client.h rename to components/signin/public/base/test_signin_client.h index f92beac..5ea2dee 100644 --- a/components/signin/core/browser/test_signin_client.h +++ b/components/signin/public/base/test_signin_client.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 COMPONENTS_SIGNIN_CORE_BROWSER_TEST_SIGNIN_CLIENT_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_TEST_SIGNIN_CLIENT_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_BASE_TEST_SIGNIN_CLIENT_H_ +#define COMPONENTS_SIGNIN_PUBLIC_BASE_TEST_SIGNIN_CLIENT_H_ #include <memory> #include <string> @@ -14,7 +14,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/signin_client.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/cookie_manager.mojom.h" @@ -36,7 +36,7 @@ void DoFinalInit() override; - // Returns NULL. + // Returns nullptr. // NOTE: This should be changed to return a properly-initalized PrefService // once there is a unit test that requires it. PrefService* GetPrefs() override; @@ -110,4 +110,4 @@ DISALLOW_COPY_AND_ASSIGN(TestSigninClient); }; -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_TEST_SIGNIN_CLIENT_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_BASE_TEST_SIGNIN_CLIENT_H_
diff --git a/components/signin/public/identity_manager/BUILD.gn b/components/signin/public/identity_manager/BUILD.gn index f97e430..5a804656 100644 --- a/components/signin/public/identity_manager/BUILD.gn +++ b/components/signin/public/identity_manager/BUILD.gn
@@ -8,42 +8,61 @@ "access_token_fetcher.h", "access_token_info.cc", "access_token_info.h", + "account_info.cc", + "account_info.h", "accounts_cookie_mutator.h", "accounts_in_cookie_jar_info.cc", "accounts_in_cookie_jar_info.h", "accounts_mutator.h", + "device_accounts_synchronizer.h", "diagnostics_provider.h", "identity_manager.cc", "identity_manager.h", "identity_manager_builder.cc", "identity_manager_builder.h", + "identity_utils.cc", + "identity_utils.h", "primary_account_access_token_fetcher.cc", "primary_account_access_token_fetcher.h", "primary_account_mutator.h", + "set_accounts_in_cookie_result.h", + "ubertoken_fetcher.cc", + "ubertoken_fetcher.h", ] configs += [ "//build/config/compiler:wexit_time_destructors" ] public_deps = [ "//base", + "//components/account_id", "//components/keyed_service/core", - "//components/signin/core/browser:shared", - "//components/signin/core/browser:signin_buildflags", + "//components/signin/public/base", + "//components/signin/public/base:signin_buildflags", "//google_apis", "//services/identity/public/cpp:cpp_types", + "//ui/gfx", ] deps = [ "//components/image_fetcher/core", + "//components/prefs", "//components/signin/core/browser:internals", + "//components/signin/core/browser/webdata", "//components/signin/internal/identity_manager", "//services/network/public/cpp", ] + if (is_chromeos) { + deps += [ "//components/user_manager" ] + } + allow_circular_includes_from = [ # This target is a pair with internal/identity_manager. They always go # together and include headers from each other. "//components/signin/internal/identity_manager", + + # TODO(blundell): Remove once this target no longer exists. + "//components/signin/core/browser:internals", ] } @@ -69,8 +88,9 @@ "//components/prefs:test_support", "//components/signin/core/browser:internals", "//components/signin/core/browser:internals_test_support", - "//components/signin/core/browser:shared", "//components/signin/internal/identity_manager", + "//components/signin/public/base", + "//components/signin/public/base:test_support", "//components/signin/public/identity_manager", "//components/sync_preferences:test_support", "//google_apis", @@ -98,7 +118,7 @@ public_deps = [ "//base", - "//components/signin/core/browser:shared", + "//components/signin/public/base", "//components/signin/public/identity_manager", "//google_apis", ] @@ -108,6 +128,7 @@ "//components/signin/core/browser:internals", "//components/signin/core/browser:internals_test_support", "//components/signin/internal/identity_manager", + "//components/signin/public/base:test_support", "//components/sync_preferences:test_support", "//testing/gtest", ]
diff --git a/components/signin/public/identity_manager/DEPS b/components/signin/public/identity_manager/DEPS new file mode 100644 index 0000000..a0327c7d --- /dev/null +++ b/components/signin/public/identity_manager/DEPS
@@ -0,0 +1,5 @@ +include_rules = [ + "+components/account_id", + "+components/user_manager/known_user.h", + "+ui/gfx", +]
diff --git a/components/signin/public/identity_manager/access_token_fetcher_unittest.cc b/components/signin/public/identity_manager/access_token_fetcher_unittest.cc index 743d64d8..6a774b2 100644 --- a/components/signin/public/identity_manager/access_token_fetcher_unittest.cc +++ b/components/signin/public/identity_manager/access_token_fetcher_unittest.cc
@@ -13,7 +13,7 @@ #include "components/prefs/testing_pref_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/access_token_info.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/oauth2_access_token_consumer.h"
diff --git a/components/signin/core/browser/account_info.cc b/components/signin/public/identity_manager/account_info.cc similarity index 98% rename from components/signin/core/browser/account_info.cc rename to components/signin/public/identity_manager/account_info.cc index 1c5b9ff..8a4bf493 100644 --- a/components/signin/core/browser/account_info.cc +++ b/components/signin/public/identity_manager/account_info.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "google_apis/gaia/gaia_auth_util.h" #if defined(OS_CHROMEOS)
diff --git a/components/signin/core/browser/account_info.h b/components/signin/public/identity_manager/account_info.h similarity index 92% rename from components/signin/core/browser/account_info.h rename to components/signin/public/identity_manager/account_info.h index ca47ac7..597c8a6 100644 --- a/components/signin/core/browser/account_info.h +++ b/components/signin/public/identity_manager/account_info.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 COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_INFO_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_INFO_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_ACCOUNT_INFO_H_ +#define COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_ACCOUNT_INFO_H_ #include <string> @@ -78,4 +78,4 @@ // Returns AccountID populated from |account_info|. AccountId AccountIdFromAccountInfo(const CoreAccountInfo& account_info); -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_INFO_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_ACCOUNT_INFO_H_
diff --git a/components/signin/core/browser/account_info_unittest.cc b/components/signin/public/identity_manager/account_info_unittest.cc similarity index 98% rename from components/signin/core/browser/account_info_unittest.cc rename to components/signin/public/identity_manager/account_info_unittest.cc index b18426f6..539278e 100644 --- a/components/signin/core/browser/account_info_unittest.cc +++ b/components/signin/public/identity_manager/account_info_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "testing/gtest/include/gtest/gtest.h" class AccountInfoTest : public testing::Test {};
diff --git a/components/signin/public/identity_manager/accounts_cookie_mutator_unittest.cc b/components/signin/public/identity_manager/accounts_cookie_mutator_unittest.cc index 6b9f7859..5f424b2 100644 --- a/components/signin/public/identity_manager/accounts_cookie_mutator_unittest.cc +++ b/components/signin/public/identity_manager/accounts_cookie_mutator_unittest.cc
@@ -12,12 +12,12 @@ #include "base/test/bind_test_util.h" #include "base/test/gtest_util.h" #include "base/test/scoped_task_environment.h" -#include "components/signin/core/browser/list_accounts_test_utils.h" -#include "components/signin/core/browser/set_accounts_in_cookie_result.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/list_accounts_test_utils.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_environment.h" +#include "components/signin/public/identity_manager/set_accounts_in_cookie_result.h" #include "components/signin/public/identity_manager/test_identity_manager_observer.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/gaia_auth_fetcher.h"
diff --git a/components/signin/public/identity_manager/accounts_mutator.h b/components/signin/public/identity_manager/accounts_mutator.h index 277dbac..92b105c 100644 --- a/components/signin/public/identity_manager/accounts_mutator.h +++ b/components/signin/public/identity_manager/accounts_mutator.h
@@ -9,7 +9,7 @@ #include "base/macros.h" #include "base/optional.h" -#include "components/signin/core/browser/signin_buildflags.h" +#include "components/signin/public/base/signin_buildflags.h" namespace signin_metrics { enum class SourceForRefreshTokenOperation;
diff --git a/components/signin/public/identity_manager/accounts_mutator_unittest.cc b/components/signin/public/identity_manager/accounts_mutator_unittest.cc index b8bb4c59..9f6e6b3 100644 --- a/components/signin/public/identity_manager/accounts_mutator_unittest.cc +++ b/components/signin/public/identity_manager/accounts_mutator_unittest.cc
@@ -8,8 +8,8 @@ #include "base/optional.h" #include "base/test/gtest_util.h" #include "base/test/scoped_task_environment.h" -#include "components/signin/core/browser/device_id_helper.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/device_id_helper.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/signin/public/identity_manager/identity_test_utils.h"
diff --git a/components/signin/public/identity_manager/device_accounts_synchronizer.h b/components/signin/public/identity_manager/device_accounts_synchronizer.h new file mode 100644 index 0000000..a31976b --- /dev/null +++ b/components/signin/public/identity_manager/device_accounts_synchronizer.h
@@ -0,0 +1,41 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_H_ +#define COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_H_ + +#include "google_apis/gaia/core_account_id.h" + +namespace identity { + +// DeviceAccountsSynchronizer is the interface to support seeding the accounts +// information from a device-level store. +class DeviceAccountsSynchronizer { + public: + DeviceAccountsSynchronizer() = default; + virtual ~DeviceAccountsSynchronizer() = default; + + // Reloads the information of all device-level accounts. All device-level + // accounts will be visible in IdentityManager::GetAccountsWithRefreshTokens() + // with any persistent errors cleared after this method is called. + virtual void ReloadAllAccountsFromSystem() = 0; + + // Reloads the information of the device-level account with |account_id|. The + // account will be visible in IdentityManager::GetAccountsWithRefreshTokens() + // with any persistent error cleared after this method is called. + virtual void ReloadAccountFromSystem(const CoreAccountId& account_id) = 0; + + // Class is non-copyable, non-moveable. + DeviceAccountsSynchronizer(const DeviceAccountsSynchronizer&) = delete; + DeviceAccountsSynchronizer& operator=(const DeviceAccountsSynchronizer&) = + delete; + + DeviceAccountsSynchronizer(DeviceAccountsSynchronizer&&) noexcept = delete; + DeviceAccountsSynchronizer& operator=(DeviceAccountsSynchronizer&&) noexcept = + delete; +}; + +} // namespace identity + +#endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_H_
diff --git a/components/signin/public/identity_manager/identity_manager.cc b/components/signin/public/identity_manager/identity_manager.cc index 557c6d1..dced8861 100644 --- a/components/signin/public/identity_manager/identity_manager.cc +++ b/components/signin/public/identity_manager/identity_manager.cc
@@ -17,6 +17,7 @@ #include "components/signin/public/identity_manager/accounts_cookie_mutator.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/accounts_mutator.h" +#include "components/signin/public/identity_manager/device_accounts_synchronizer.h" #include "components/signin/public/identity_manager/diagnostics_provider.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" #include "services/network/public/cpp/shared_url_loader_factory.h" @@ -53,7 +54,8 @@ std::unique_ptr<PrimaryAccountMutator> primary_account_mutator, std::unique_ptr<AccountsMutator> accounts_mutator, std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator, - std::unique_ptr<DiagnosticsProvider> diagnostics_provider) + std::unique_ptr<DiagnosticsProvider> diagnostics_provider, + std::unique_ptr<DeviceAccountsSynchronizer> device_accounts_synchronizer) : account_tracker_service_(std::move(account_tracker_service)), token_service_(std::move(token_service)), gaia_cookie_manager_service_(std::move(gaia_cookie_manager_service)), @@ -62,11 +64,15 @@ primary_account_mutator_(std::move(primary_account_mutator)), accounts_mutator_(std::move(accounts_mutator)), accounts_cookie_mutator_(std::move(accounts_cookie_mutator)), - diagnostics_provider_(std::move(diagnostics_provider)) { + diagnostics_provider_(std::move(diagnostics_provider)), + device_accounts_synchronizer_(std::move(device_accounts_synchronizer)) { DCHECK(account_fetcher_service_); DCHECK(accounts_cookie_mutator_); DCHECK(diagnostics_provider_); + DCHECK(!accounts_mutator_ || !device_accounts_synchronizer_) + << "Cannot have both an AccountsMutator and a DeviceAccountsSynchronizer"; + // IdentityManager will outlive the PrimaryAccountManager, so base::Unretained // is safe. primary_account_manager_->SetGoogleSigninSucceededCallback( @@ -354,6 +360,10 @@ return accounts_cookie_mutator_.get(); } +DeviceAccountsSynchronizer* IdentityManager::GetDeviceAccountsSynchronizer() { + return device_accounts_synchronizer_.get(); +} + void IdentityManager::AddDiagnosticsObserver(DiagnosticsObserver* observer) { diagnostics_observer_list_.AddObserver(observer); } @@ -415,21 +425,14 @@ void IdentityManager::ForceTriggerOnCookieChange() { gaia_cookie_manager_service_->ForceOnCookieChangeProcessing(); } - -void IdentityManager::LegacyAddAccountFromSystem( - const CoreAccountId& account_id) { - token_service_->GetDelegate()->AddAccountFromSystem(account_id); -} #endif -#if defined(OS_ANDROID) || defined(OS_IOS) +#if defined(OS_ANDROID) void IdentityManager::LegacyReloadAccountsFromSystem() { token_service_->GetDelegate()->ReloadAccountsFromSystem( GetPrimaryAccountId()); } -#endif -#if defined(OS_ANDROID) base::android::ScopedJavaLocalRef<jobject> IdentityManager::LegacyGetAccountTrackerServiceJavaObject() { return account_tracker_service_->GetJavaObject();
diff --git a/components/signin/public/identity_manager/identity_manager.h b/components/signin/public/identity_manager/identity_manager.h index 4d26ae6..fbc6192a 100644 --- a/components/signin/public/identity_manager/identity_manager.h +++ b/components/signin/public/identity_manager/identity_manager.h
@@ -12,9 +12,9 @@ #include "base/observer_list.h" #include "build/build_config.h" #include "components/keyed_service/core/keyed_service.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/ubertoken_fetcher.h" #include "components/signin/public/identity_manager/access_token_fetcher.h" +#include "components/signin/public/identity_manager/account_info.h" +#include "components/signin/public/identity_manager/ubertoken_fetcher.h" #include "google_apis/gaia/oauth2_access_token_manager.h" #include "google_apis/gaia/oauth2_token_service_observer.h" #include "services/identity/public/cpp/scope_set.h" @@ -50,6 +50,7 @@ struct AccountsInCookieJarInfo; class IdentityManagerTest; class IdentityTestEnvironment; +class DeviceAccountsSynchronizer; class DiagnosticsProvider; class PrimaryAccountMutator; enum class ClearPrimaryAccountPolicy; @@ -291,6 +292,10 @@ // accounts associated with them. Guaranteed to be non-null. AccountsCookieMutator* GetAccountsCookieMutator(); + // Returns pointer to the object used to seed accounts information from the + // device-level accounts. May be null if the system has no such notion. + DeviceAccountsSynchronizer* GetDeviceAccountsSynchronizer(); + // Observer interface for classes that want to monitor status of various // requests. Mostly useful in tests and debugging contexts (e.g., WebUI). class DiagnosticsObserver { @@ -350,7 +355,8 @@ std::unique_ptr<PrimaryAccountMutator> primary_account_mutator, std::unique_ptr<AccountsMutator> accounts_mutator, std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator, - std::unique_ptr<DiagnosticsProvider> diagnostics_provider); + std::unique_ptr<DiagnosticsProvider> diagnostics_provider, + std::unique_ptr<DeviceAccountsSynchronizer> device_accounts_synchronizer); ~IdentityManager() override; // Performs initialization that is dependent on the network being @@ -407,25 +413,16 @@ // TODO(https://crbug.com/930582) : Remove the need to expose this method // or move it to the network::CookieManager. void ForceTriggerOnCookieChange(); - - // Adds a given account to the token service from a system account. This - // API calls OAuth2TokenServiceDelegate::AddAccountFromSystem and it - // triggers platform specific implementation for IOS. - // NOTE: In normal usage, this method SHOULD NOT be called. - // TODO(https://crbug.com/930094): Eliminate the need to expose this. - void LegacyAddAccountFromSystem(const CoreAccountId& account_id); -#endif - -#if defined(OS_ANDROID) || defined(OS_IOS) - // Reloads the accounts in the token service from the system accounts. This - // API calls OAuth2TokenServiceDelegate::ReloadAccountsFromSystem and it - // triggers platform specific implementation for Android and IOS. - // NOTE: In normal usage, this method SHOULD NOT be called. - // TODO(https://crbug.com/930094): Eliminate the need to expose this. - void LegacyReloadAccountsFromSystem(); #endif #if defined(OS_ANDROID) + // Reloads the accounts in the token service from the system accounts. This + // API calls OAuth2TokenServiceDelegate::ReloadAccountsFromSystem and it + // triggers platform specific implementation for Android. + // NOTE: In normal usage, this method SHOULD NOT be called. + // TODO(https://crbug.com/930094): Eliminate the need to expose this. + void LegacyReloadAccountsFromSystem(); + // Returns a pointer to the AccountTrackerService Java instance associated // with this object. // TODO(https://crbug.com/934688): Eliminate this method once @@ -638,6 +635,9 @@ // DiagnosticsProvider instance. std::unique_ptr<DiagnosticsProvider> diagnostics_provider_; + // DeviceAccountsSynchronizer instance. + std::unique_ptr<DeviceAccountsSynchronizer> device_accounts_synchronizer_; + // Lists of observers. // Makes sure lists are empty on destruction. base::ObserverList<Observer, true>::Unchecked observer_list_;
diff --git a/components/signin/public/identity_manager/identity_manager_builder.cc b/components/signin/public/identity_manager/identity_manager_builder.cc index d131e97..f233a4f0 100644 --- a/components/signin/public/identity_manager/identity_manager_builder.cc +++ b/components/signin/public/identity_manager/identity_manager_builder.cc
@@ -13,13 +13,22 @@ #include "components/signin/core/browser/primary_account_manager.h" #include "components/signin/core/browser/primary_account_policy_manager.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_client.h" #include "components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h" #include "components/signin/internal/identity_manager/diagnostics_provider_impl.h" #include "components/signin/internal/identity_manager/primary_account_mutator_impl.h" +#include "components/signin/public/base/signin_client.h" #include "components/signin/public/identity_manager/accounts_mutator.h" +#include "components/signin/public/identity_manager/device_accounts_synchronizer.h" #include "components/signin/public/identity_manager/identity_manager.h" +#if !defined(OS_ANDROID) +#include "components/signin/core/browser/webdata/token_web_data.h" +#endif + +#if defined(OS_IOS) +#include "components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h" +#endif + #if !defined(OS_ANDROID) && !defined(OS_IOS) #include "components/signin/internal/identity_manager/accounts_mutator_impl.h" #endif @@ -118,12 +127,20 @@ account_tracker_service.get(), std::move(params->image_decoder)); + std::unique_ptr<DeviceAccountsSynchronizer> device_accounts_synchronizer; +#if defined(OS_IOS) + device_accounts_synchronizer = + std::make_unique<DeviceAccountsSynchronizerImpl>( + token_service->GetDelegate()); +#endif + return std::make_unique<IdentityManager>( std::move(account_tracker_service), std::move(token_service), std::move(gaia_cookie_manager_service), std::move(primary_account_manager), std::move(account_fetcher_service), std::move(primary_account_mutator), std::move(accounts_mutator), - std::move(accounts_cookie_mutator), std::move(diagnostics_provider)); + std::move(accounts_cookie_mutator), std::move(diagnostics_provider), + std::move(device_accounts_synchronizer)); } } // namespace identity
diff --git a/components/signin/public/identity_manager/identity_manager_builder.h b/components/signin/public/identity_manager/identity_manager_builder.h index a6a77b3..ee46af5d 100644 --- a/components/signin/public/identity_manager/identity_manager_builder.h +++ b/components/signin/public/identity_manager/identity_manager_builder.h
@@ -7,12 +7,18 @@ #include <memory> +#include "base/memory/scoped_refptr.h" #include "build/build_config.h" +#if defined(OS_WIN) +#include "base/callback.h" +#endif + class AccountTrackerService; class PrefService; class ProfileOAuth2TokenService; class SigninClient; +class TokenWebData; namespace image_fetcher { class ImageDecoder; @@ -48,10 +54,19 @@ SigninClient* signin_client; std::unique_ptr<ProfileOAuth2TokenService> token_service; +#if !defined(OS_ANDROID) + bool delete_signin_cookies_on_exit; + scoped_refptr<TokenWebData> token_web_data; +#endif + #if defined(OS_CHROMEOS) chromeos::AccountManager* account_manager; bool is_regular_profile; #endif + +#if defined(OS_WIN) + base::RepeatingCallback<bool()> reauth_callback; +#endif }; // Builds an IdentityManager instance from the supplied embedder-level
diff --git a/components/signin/public/identity_manager/identity_manager_unittest.cc b/components/signin/public/identity_manager/identity_manager_unittest.cc index 945402f..9cbcfc7 100644 --- a/components/signin/public/identity_manager/identity_manager_unittest.cc +++ b/components/signin/public/identity_manager/identity_manager_unittest.cc
@@ -17,24 +17,25 @@ #include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "components/image_fetcher/core/fake_image_decoder.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_fetcher_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" #include "components/signin/core/browser/gaia_cookie_manager_service.h" -#include "components/signin/core/browser/list_accounts_test_utils.h" #include "components/signin/core/browser/primary_account_manager.h" #include "components/signin/core/browser/primary_account_policy_manager_impl.h" -#include "components/signin/core/browser/set_accounts_in_cookie_result.h" -#include "components/signin/core/browser/signin_switches.h" -#include "components/signin/core/browser/test_signin_client.h" #include "components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h" #include "components/signin/internal/identity_manager/diagnostics_provider_impl.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/list_accounts_test_utils.h" +#include "components/signin/public/base/signin_switches.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/access_token_info.h" #include "components/signin/public/identity_manager/accounts_cookie_mutator.h" #include "components/signin/public/identity_manager/accounts_mutator.h" +#include "components/signin/public/identity_manager/device_accounts_synchronizer.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" +#include "components/signin/public/identity_manager/set_accounts_in_cookie_result.h" #include "components/signin/public/identity_manager/test_identity_manager_observer.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/core_account_id.h" @@ -360,7 +361,7 @@ std::move(gaia_cookie_manager_service), std::move(primary_account_manager), std::move(account_fetcher_service), nullptr, nullptr, std::move(accounts_cookie_mutator), - std::move(diagnostics_provider))); + std::move(diagnostics_provider), nullptr)); identity_manager_observer_.reset( new TestIdentityManagerObserver(identity_manager_.get())); identity_manager_diagnostics_observer_.reset(
diff --git a/components/signin/public/identity_manager/identity_test_environment.cc b/components/signin/public/identity_manager/identity_test_environment.cc index a307951f..1611d46 100644 --- a/components/signin/public/identity_manager/identity_test_environment.cc +++ b/components/signin/public/identity_manager/identity_test_environment.cc
@@ -20,11 +20,12 @@ #include "components/signin/core/browser/gaia_cookie_manager_service.h" #include "components/signin/core/browser/primary_account_manager.h" #include "components/signin/core/browser/primary_account_policy_manager_impl.h" -#include "components/signin/core/browser/test_signin_client.h" #include "components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h" #include "components/signin/internal/identity_manager/diagnostics_provider_impl.h" #include "components/signin/internal/identity_manager/primary_account_mutator_impl.h" +#include "components/signin/public/base/test_signin_client.h" #include "components/signin/public/identity_manager/accounts_mutator.h" +#include "components/signin/public/identity_manager/device_accounts_synchronizer.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" @@ -33,6 +34,7 @@ #include "google_apis/gaia/oauth2_access_token_consumer.h" #if defined(OS_IOS) +#include "components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h" #include "components/signin/ios/browser/device_accounts_provider.h" #include "components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.h" #endif @@ -235,12 +237,20 @@ auto accounts_cookie_mutator = std::make_unique<AccountsCookieMutatorImpl>( gaia_cookie_manager_service.get(), account_tracker_service.get()); + std::unique_ptr<DeviceAccountsSynchronizer> device_accounts_synchronizer; +#if defined(OS_IOS) + device_accounts_synchronizer = + std::make_unique<DeviceAccountsSynchronizerImpl>( + token_service->GetDelegate()); +#endif + return std::make_unique<IdentityManager>( std::move(account_tracker_service), std::move(token_service), std::move(gaia_cookie_manager_service), std::move(primary_account_manager), std::move(account_fetcher_service), std::move(primary_account_mutator), std::move(accounts_mutator), - std::move(accounts_cookie_mutator), std::move(diagnostics_provider)); + std::move(accounts_cookie_mutator), std::move(diagnostics_provider), + std::move(device_accounts_synchronizer)); } IdentityTestEnvironment::~IdentityTestEnvironment() {
diff --git a/components/signin/public/identity_manager/identity_test_environment.h b/components/signin/public/identity_manager/identity_test_environment.h index fdd73aa..c3693c8 100644 --- a/components/signin/public/identity_manager/identity_test_environment.h +++ b/components/signin/public/identity_manager/identity_test_environment.h
@@ -10,8 +10,8 @@ #include "base/callback.h" #include "base/optional.h" #include "build/build_config.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_client.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h"
diff --git a/components/signin/public/identity_manager/identity_test_utils.cc b/components/signin/public/identity_manager/identity_test_utils.cc index 2fbcd30..f94e1df2 100644 --- a/components/signin/public/identity_manager/identity_test_utils.cc +++ b/components/signin/public/identity_manager/identity_test_utils.cc
@@ -10,9 +10,9 @@ #include "build/build_config.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/gaia_cookie_manager_service.h" -#include "components/signin/core/browser/list_accounts_test_utils.h" #include "components/signin/core/browser/primary_account_manager.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" +#include "components/signin/public/base/list_accounts_test_utils.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/test_identity_manager_observer.h" #include "google_apis/gaia/gaia_auth_util.h"
diff --git a/components/signin/public/identity_manager/identity_test_utils.h b/components/signin/public/identity_manager/identity_test_utils.h index 4f82a8e..804f839 100644 --- a/components/signin/public/identity_manager/identity_test_utils.h +++ b/components/signin/public/identity_manager/identity_test_utils.h
@@ -8,7 +8,7 @@ #include <string> #include "build/build_config.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" namespace network { class TestURLLoaderFactory;
diff --git a/components/signin/core/browser/identity_utils.cc b/components/signin/public/identity_manager/identity_utils.cc similarity index 93% rename from components/signin/core/browser/identity_utils.cc rename to components/signin/public/identity_manager/identity_utils.cc index 57ea8f1..d603019 100644 --- a/components/signin/core/browser/identity_utils.cc +++ b/components/signin/public/identity_manager/identity_utils.cc
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/identity_utils.h" +#include "components/signin/public/identity_manager/identity_utils.h" #include <string> #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "third_party/icu/source/i18n/unicode/regex.h" namespace identity {
diff --git a/components/signin/core/browser/identity_utils.h b/components/signin/public/identity_manager/identity_utils.h similarity index 82% rename from components/signin/core/browser/identity_utils.h rename to components/signin/public/identity_manager/identity_utils.h index b28d452..3806aca 100644 --- a/components/signin/core/browser/identity_utils.h +++ b/components/signin/public/identity_manager/identity_utils.h
@@ -9,8 +9,8 @@ // to //services/identity, these functions should correspondingly be moved to // //services/identity/public/cpp. -#ifndef COMPONENTS_SIGNIN_CORE_BROWSER_IDENTITY_UTILS_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_IDENTITY_UTILS_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_UTILS_H_ +#define COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_UTILS_H_ #include "base/strings/string_piece.h" @@ -25,4 +25,4 @@ const std::string& username); } // namespace identity -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_IDENTITY_UTILS_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_UTILS_H_
diff --git a/components/signin/core/browser/identity_utils_unittest.cc b/components/signin/public/identity_manager/identity_utils_unittest.cc similarity index 96% rename from components/signin/core/browser/identity_utils_unittest.cc rename to components/signin/public/identity_manager/identity_utils_unittest.cc index e0cd47e5..b3d58fe 100644 --- a/components/signin/core/browser/identity_utils_unittest.cc +++ b/components/signin/public/identity_manager/identity_utils_unittest.cc
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/identity_utils.h" +#include "components/signin/public/identity_manager/identity_utils.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/testing_pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "testing/gtest/include/gtest/gtest.h" namespace {
diff --git a/components/signin/public/identity_manager/primary_account_mutator.h b/components/signin/public/identity_manager/primary_account_mutator.h index 59189ab..0aec24a6 100644 --- a/components/signin/public/identity_manager/primary_account_mutator.h +++ b/components/signin/public/identity_manager/primary_account_mutator.h
@@ -45,15 +45,33 @@ PrimaryAccountMutator const& operator=(const PrimaryAccountMutator& other) = delete; -#if !defined(OS_CHROMEOS) // Marks the account with |account_id| as the primary account, and returns // whether the operation succeeded or not. To succeed, this requires that: + // - the account is known by the IdentityManager. + // On non-ChromeOS platforms, this additionally requires that: // - setting the primary account is allowed, // - the account username is allowed by policy, - // - there is not already a primary account set, - // - the account is known by the IdentityManager. + // - there is not already a primary account set. + // TODO(https://crbug.com/983124): Investigate adding all the extra + // requirements on ChromeOS as well. virtual bool SetPrimaryAccount(const CoreAccountId& account_id) = 0; +#if defined(OS_CHROMEOS) + // Updates the info of the account corresponding to (|gaia_id|, |email|), + // marks it as the primary account, and returns whether the operation + // succeeded or not. Currently, this method is guaranteed to succeed. + // NOTE: Unlike SetPrimaryAccount(), this method does not require that the + // account is known by IdentityManager. The reason is that there are + // contexts on ChromeOS where the primary account is not guaranteed to be + // known by IdentityManager when it is set. + // TODO(https://crbug.com/967605): Port callers to SetPrimaryAccount() once + // https://crbug.com/867602 is fixed. + virtual bool SetPrimaryAccountAndUpdateAccountInfo( + const std::string& gaia_id, + const std::string& email) = 0; +#endif + +#if !defined(OS_CHROMEOS) // Clears the primary account, and returns whether the operation // succeeded or not. Depending on |action|, the other accounts // known to the IdentityManager may be deleted. @@ -61,18 +79,6 @@ ClearAccountsAction action, signin_metrics::ProfileSignout source_metric, signin_metrics::SignoutDelete delete_metric) = 0; -#else - // Updates the info of the account corresponding to (|gaia_id|, |email|), - // marks it as the primary account, and returns whether the operation - // succeeded or not. Currently, this method is guaranteed to succeed. - // NOTE: Unlike SetPrimaryAccount(), this method does not require that the - // account is known by IdentityManager. The reason is that on ChromeOS the - // primary account is in fact not guaranteed to be known by IdentityManager - // when it is set. TODO(https://crbug.com/967605): Port callers to - // SetPrimaryAccount() once https://crbug.com/867602 is fixed." - virtual bool SetPrimaryAccountAndUpdateAccountInfo( - const std::string& gaia_id, - const std::string& email) = 0; #endif };
diff --git a/components/signin/public/identity_manager/primary_account_mutator_unittest.cc b/components/signin/public/identity_manager/primary_account_mutator_unittest.cc index 1418cc3..603c46e 100644 --- a/components/signin/public/identity_manager/primary_account_mutator_unittest.cc +++ b/components/signin/public/identity_manager/primary_account_mutator_unittest.cc
@@ -9,8 +9,8 @@ #include "base/run_loop.h" #include "base/scoped_observer.h" #include "base/test/scoped_task_environment.h" -#include "components/signin/core/browser/signin_metrics.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/sync_preferences/testing_pref_service_syncable.h"
diff --git a/components/signin/core/browser/set_accounts_in_cookie_result.h b/components/signin/public/identity_manager/set_accounts_in_cookie_result.h similarity index 65% rename from components/signin/core/browser/set_accounts_in_cookie_result.h rename to components/signin/public/identity_manager/set_accounts_in_cookie_result.h index 6adba69..c5e4044 100644 --- a/components/signin/core/browser/set_accounts_in_cookie_result.h +++ b/components/signin/public/identity_manager/set_accounts_in_cookie_result.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 COMPONENTS_SIGNIN_CORE_BROWSER_SET_ACCOUNTS_IN_COOKIE_RESULT_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_SET_ACCOUNTS_IN_COOKIE_RESULT_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_SET_ACCOUNTS_IN_COOKIE_RESULT_H_ +#define COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_SET_ACCOUNTS_IN_COOKIE_RESULT_H_ namespace signin { @@ -19,4 +19,4 @@ } // namespace signin -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_SET_ACCOUNTS_IN_COOKIE_RESULT_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_SET_ACCOUNTS_IN_COOKIE_RESULT_H_
diff --git a/components/signin/public/identity_manager/test_identity_manager_observer.h b/components/signin/public/identity_manager/test_identity_manager_observer.h index 14e43978..7bac3fc 100644 --- a/components/signin/public/identity_manager/test_identity_manager_observer.h +++ b/components/signin/public/identity_manager/test_identity_manager_observer.h
@@ -8,7 +8,7 @@ #include <vector> #include "base/callback.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "google_apis/gaia/google_service_auth_error.h"
diff --git a/components/signin/core/browser/ubertoken_fetcher.cc b/components/signin/public/identity_manager/ubertoken_fetcher.cc similarity index 87% rename from components/signin/core/browser/ubertoken_fetcher.cc rename to components/signin/public/identity_manager/ubertoken_fetcher.cc index 6eea8ba..e3377be 100644 --- a/components/signin/core/browser/ubertoken_fetcher.cc +++ b/components/signin/public/identity_manager/ubertoken_fetcher.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/ubertoken_fetcher.h" +#include "components/signin/public/identity_manager/ubertoken_fetcher.h" namespace signin {
diff --git a/components/signin/core/browser/ubertoken_fetcher.h b/components/signin/public/identity_manager/ubertoken_fetcher.h similarity index 79% rename from components/signin/core/browser/ubertoken_fetcher.h rename to components/signin/public/identity_manager/ubertoken_fetcher.h index cc4f169..f79d635 100644 --- a/components/signin/core/browser/ubertoken_fetcher.h +++ b/components/signin/public/identity_manager/ubertoken_fetcher.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 COMPONENTS_SIGNIN_CORE_BROWSER_UBERTOKEN_FETCHER_H_ -#define COMPONENTS_SIGNIN_CORE_BROWSER_UBERTOKEN_FETCHER_H_ +#ifndef COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_UBERTOKEN_FETCHER_H_ +#define COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_UBERTOKEN_FETCHER_H_ #include <memory> @@ -32,4 +32,4 @@ } // namespace signin -#endif // COMPONENTS_SIGNIN_CORE_BROWSER_UBERTOKEN_FETCHER_H_ +#endif // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_UBERTOKEN_FETCHER_H_
diff --git a/components/sync/BUILD.gn b/components/sync/BUILD.gn index 54591fc..5c83c456 100644 --- a/components/sync/BUILD.gn +++ b/components/sync/BUILD.gn
@@ -671,7 +671,7 @@ "//components/invalidation/impl", "//components/os_crypt:test_support", "//components/prefs:test_support", - "//components/signin/core/browser:internals_test_support", + "//components/signin/public/base:test_support", "//components/signin/public/identity_manager:test_support", "//components/sync/base:test_support", "//components/sync/driver:test_support",
diff --git a/components/sync/driver/BUILD.gn b/components/sync/driver/BUILD.gn index 6502941..f2be4fc 100644 --- a/components/sync/driver/BUILD.gn +++ b/components/sync/driver/BUILD.gn
@@ -177,7 +177,7 @@ deps = [ "//components/invalidation/impl:test_support", "//components/pref_registry", - "//components/signin/core/browser:shared", + "//components/signin/public/base", "//components/signin/public/identity_manager:test_support", "//components/sync", "//components/sync:test_support_engine",
diff --git a/components/sync/driver/about_sync_util.h b/components/sync/driver/about_sync_util.h index 20bdae58..ad2b307c 100644 --- a/components/sync/driver/about_sync_util.h +++ b/components/sync/driver/about_sync_util.h
@@ -7,7 +7,7 @@ #include <memory> -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/version_info/version_info.h" namespace base {
diff --git a/components/sync/driver/fake_sync_service.cc b/components/sync/driver/fake_sync_service.cc index d6290e1..4047984 100644 --- a/components/sync/driver/fake_sync_service.cc +++ b/components/sync/driver/fake_sync_service.cc
@@ -5,7 +5,7 @@ #include "components/sync/driver/fake_sync_service.h" #include "base/values.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/sync/driver/sync_token_status.h" #include "components/sync/engine/cycle/sync_cycle_snapshot.h" #include "components/sync/syncable/user_share.h"
diff --git a/components/sync/driver/mock_sync_service.h b/components/sync/driver/mock_sync_service.h index 55042672..15a1dd5 100644 --- a/components/sync/driver/mock_sync_service.h +++ b/components/sync/driver/mock_sync_service.h
@@ -9,7 +9,7 @@ #include <string> #include "base/values.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/sync/driver/sync_service.h" #include "components/sync/driver/sync_token_status.h" #include "components/sync/driver/sync_user_settings_mock.h"
diff --git a/components/sync/driver/model_type_controller.cc b/components/sync/driver/model_type_controller.cc index 456bef1..0b917a86 100644 --- a/components/sync/driver/model_type_controller.cc +++ b/components/sync/driver/model_type_controller.cc
@@ -9,7 +9,7 @@ #include "base/bind.h" #include "base/location.h" #include "base/threading/sequenced_task_runner_handle.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/sync/base/data_type_histogram.h" #include "components/sync/driver/configure_context.h" #include "components/sync/engine/data_type_activation_response.h"
diff --git a/components/sync/driver/profile_sync_service.cc b/components/sync/driver/profile_sync_service.cc index 1cffedb..925408e6 100644 --- a/components/sync/driver/profile_sync_service.cc +++ b/components/sync/driver/profile_sync_service.cc
@@ -15,8 +15,8 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "components/invalidation/public/invalidation_service.h" -#include "components/signin/core/browser/account_info.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/primary_account_mutator.h"
diff --git a/components/sync/driver/profile_sync_service_unittest.cc b/components/sync/driver/profile_sync_service_unittest.cc index 98e53b2..aa64000 100644 --- a/components/sync/driver/profile_sync_service_unittest.cc +++ b/components/sync/driver/profile_sync_service_unittest.cc
@@ -16,7 +16,7 @@ #include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" #include "base/values.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" #include "components/sync/base/pref_names.h"
diff --git a/components/sync/driver/sync_auth_manager.h b/components/sync/driver/sync_auth_manager.h index 551110d..3022e73 100644 --- a/components/sync/driver/sync_auth_manager.h +++ b/components/sync/driver/sync_auth_manager.h
@@ -14,7 +14,7 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/timer/timer.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/sync/driver/sync_auth_util.h" #include "components/sync/driver/sync_token_status.h"
diff --git a/components/sync/driver/sync_auth_util.h b/components/sync/driver/sync_auth_util.h index 13475c9..6190dad 100644 --- a/components/sync/driver/sync_auth_util.h +++ b/components/sync/driver/sync_auth_util.h
@@ -5,7 +5,7 @@ #ifndef COMPONENTS_SYNC_DRIVER_SYNC_AUTH_UTIL_H_ #define COMPONENTS_SYNC_DRIVER_SYNC_AUTH_UTIL_H_ -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" class GoogleServiceAuthError;
diff --git a/components/sync/driver/test_sync_service.h b/components/sync/driver/test_sync_service.h index 8a1e8873..d6a1c44b 100644 --- a/components/sync/driver/test_sync_service.h +++ b/components/sync/driver/test_sync_service.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "base/observer_list.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/sync/driver/sync_service.h" #include "components/sync/driver/test_sync_user_settings.h" #include "components/sync/engine/cycle/sync_cycle_snapshot.h"
diff --git a/components/sync_user_events/BUILD.gn b/components/sync_user_events/BUILD.gn index 718a175..a4dbf15 100644 --- a/components/sync_user_events/BUILD.gn +++ b/components/sync_user_events/BUILD.gn
@@ -27,7 +27,7 @@ "//components/sync/protocol", ] deps = [ - "//components/signin/core/browser:shared", + "//components/signin/public/base", "//google_apis", ] }
diff --git a/components/user_manager/BUILD.gn b/components/user_manager/BUILD.gn index 07b8044..4132923e4 100644 --- a/components/user_manager/BUILD.gn +++ b/components/user_manager/BUILD.gn
@@ -14,14 +14,16 @@ "user_type.h", ] - deps = [ + public_deps = [ "//base", "//components/account_id", - "//google_apis", - "//skia", "//ui/gfx", ] + deps = [ + "//google_apis", + ] + defines = [ "USER_MANAGER_IMPLEMENTATION" ] if (is_chromeos) { @@ -40,8 +42,10 @@ "user_manager_base.cc", "user_manager_base.h", ] + deps += [ "//components/prefs", + "//skia", "//url", ] } @@ -54,13 +58,15 @@ "fake_user_manager.cc", "fake_user_manager.h", ] - deps = [ + + public_deps = [ ":user_manager", "//base", - "//chromeos:chromeos", "//components/account_id", - "//skia", - "//ui/base", + ] + + deps = [ + "//chromeos/constants", ] } @@ -72,9 +78,7 @@ deps = [ ":user_manager", "//components/account_id", - "//skia", "//testing/gtest", - "//ui/gfx", ] } }
diff --git a/components/user_manager/user.h b/components/user_manager/user.h index 9dc31a0..41462a9 100644 --- a/components/user_manager/user.h +++ b/components/user_manager/user.h
@@ -18,8 +18,6 @@ #include "components/user_manager/user_info.h" #include "components/user_manager/user_manager_export.h" #include "components/user_manager/user_type.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/gfx/image/image_skia.h" namespace chromeos { class ChromeUserManagerImpl; @@ -31,6 +29,10 @@ class UserSessionManager; } +namespace gfx { +class ImageSkia; +} + namespace policy { class ProfilePolicyConnectorTest; }
diff --git a/components/vector_icons/BUILD.gn b/components/vector_icons/BUILD.gn index 477c20d..e13a263 100644 --- a/components/vector_icons/BUILD.gn +++ b/components/vector_icons/BUILD.gn
@@ -51,6 +51,7 @@ "screen_share.icon", "search.icon", "serial_port.icon", + "settings.icon", "usb.icon", "videocam.icon", "warning.icon",
diff --git a/chrome/app/vector_icons/settings.icon b/components/vector_icons/settings.icon similarity index 100% rename from chrome/app/vector_icons/settings.icon rename to components/vector_icons/settings.icon
diff --git a/components/viz/service/display/overlay_processor.cc b/components/viz/service/display/overlay_processor.cc index 545f2c99..384c921 100644 --- a/components/viz/service/display/overlay_processor.cc +++ b/components/viz/service/display/overlay_processor.cc
@@ -275,16 +275,16 @@ bool previous_frame_underlay_was_unoccluded, const QuadList* quad_list, gfx::Rect* damage_rect) { - gfx::Rect output_surface_overlay_damage_rect; gfx::Rect this_frame_underlay_rect; for (const OverlayCandidate& overlay : *candidates) { if (overlay.plane_z_order >= 0) { const gfx::Rect overlay_display_rect = ToEnclosedRect(overlay.display_rect); - if (overlay.use_output_surface_for_resource) { - if (overlay.plane_z_order > 0) - output_surface_overlay_damage_rect.Union(overlay_display_rect); - } else { + // If an overlay candidate comes from output surface, its z-order should + // be 0. + DCHECK(!overlay.use_output_surface_for_resource || + overlay.plane_z_order == 0); + if (!overlay.use_output_surface_for_resource) { overlay_damage_rect_.Union(overlay_display_rect); if (overlay.is_opaque) damage_rect->Subtract(overlay_display_rect); @@ -336,8 +336,6 @@ damage_rect->Union(previous_frame_underlay_rect); previous_frame_underlay_rect_ = this_frame_underlay_rect; - - damage_rect->Union(output_surface_overlay_damage_rect); } bool OverlayProcessor::NeedsSurfaceOccludingDamageRect() const {
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 2cc7918..9c396ae5 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -1798,6 +1798,8 @@ "service_worker/service_worker_navigation_handle_core.h", "service_worker/service_worker_navigation_loader.cc", "service_worker/service_worker_navigation_loader.h", + "service_worker/service_worker_navigation_loader_interceptor.cc", + "service_worker/service_worker_navigation_loader_interceptor.h", "service_worker/service_worker_new_script_loader.cc", "service_worker/service_worker_new_script_loader.h", "service_worker/service_worker_object_host.cc",
diff --git a/content/browser/accessibility/accessibility_action_browsertest.cc b/content/browser/accessibility/accessibility_action_browsertest.cc index b38f11a..5a2d7d2 100644 --- a/content/browser/accessibility/accessibility_action_browsertest.cc +++ b/content/browser/accessibility/accessibility_action_browsertest.cc
@@ -56,6 +56,15 @@ png_data.size(), bitmap)); } + void LoadInitialAccessibilityTreeFromHtml(const std::string& html) { + AccessibilityNotificationWaiter waiter(shell()->web_contents(), + ui::kAXModeComplete, + ax::mojom::Event::kLoadComplete); + GURL html_data_url("data:text/html," + html); + NavigateToURL(shell(), html_data_url); + waiter.WaitForNotification(); + } + private: BrowserAccessibility* FindNodeInSubtree(BrowserAccessibility& node, ax::mojom::Role role, @@ -93,18 +102,11 @@ }; IN_PROC_BROWSER_TEST_F(AccessibilityActionBrowserTest, FocusAction) { - NavigateToURL(shell(), GURL(url::kAboutBlankURL)); - - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kLoadComplete); - GURL url( - "data:text/html," - "<button>One</button>" - "<button>Two</button>" - "<button>Three</button>"); - NavigateToURL(shell(), url); - waiter.WaitForNotification(); + LoadInitialAccessibilityTreeFromHtml(R"HTML( + <button>One</button> + <button>Two</button> + <button>Three</button> + )HTML"); BrowserAccessibility* target = FindNode(ax::mojom::Role::kButton, "One"); ASSERT_NE(nullptr, target); @@ -121,16 +123,9 @@ IN_PROC_BROWSER_TEST_F(AccessibilityActionBrowserTest, IncrementDecrementActions) { - NavigateToURL(shell(), GURL(url::kAboutBlankURL)); - - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kLoadComplete); - GURL url( - "data:text/html," - "<input type=range min=2 value=8 max=10 step=2>"); - NavigateToURL(shell(), url); - waiter.WaitForNotification(); + LoadInitialAccessibilityTreeFromHtml(R"HTML( + <input type=range min=2 value=8 max=10 step=2> + )HTML"); BrowserAccessibility* target = FindNode(ax::mojom::Role::kSlider, ""); ASSERT_NE(nullptr, target); @@ -172,20 +167,12 @@ } IN_PROC_BROWSER_TEST_F(AccessibilityActionBrowserTest, Scroll) { - NavigateToURL(shell(), GURL(url::kAboutBlankURL)); - - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kLoadComplete); - GURL url( - "data:text/html," - "<div style='width:100; height:50; overflow:scroll' " - "aria-label='shakespeare'>" - "To be or not to be, that is the question." - "</div>"); - - NavigateToURL(shell(), url); - waiter.WaitForNotification(); + LoadInitialAccessibilityTreeFromHtml(R"HTML( + <div style="width:100; height:50; overflow:scroll" + aria-label="shakespeare"> + To be or not to be, that is the question. + </div> + )HTML"); BrowserAccessibility* target = FindNode(ax::mojom::Role::kGenericContainer, "shakespeare"); @@ -210,32 +197,25 @@ } IN_PROC_BROWSER_TEST_F(AccessibilityCanvasActionBrowserTest, CanvasGetImage) { - NavigateToURL(shell(), GURL(url::kAboutBlankURL)); - - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kLoadComplete); - GURL url( - "data:text/html," - "<body>" - "<canvas aria-label='canvas' id='c' width='4' height='2'></canvas>" - "<script>\n" - " var c = document.getElementById('c').getContext('2d');\n" - " c.beginPath();\n" - " c.moveTo(0, 0.5);\n" - " c.lineTo(4, 0.5);\n" - " c.strokeStyle = '%23ff0000';\n" - " c.stroke();\n" - " c.beginPath();\n" - " c.moveTo(0, 1.5);\n" - " c.lineTo(4, 1.5);\n" - " c.strokeStyle = '%230000ff';\n" - " c.stroke();\n" - "</script>" - "</body>"); - - NavigateToURL(shell(), url); - waiter.WaitForNotification(); + LoadInitialAccessibilityTreeFromHtml(R"HTML( + <body> + <canvas aria-label="canvas" id="c" width="4" height="2"> + </canvas> + <script> + var c = document.getElementById('c').getContext('2d'); + c.beginPath(); + c.moveTo(0, 0.5); + c.lineTo(4, 0.5); + c.strokeStyle = '%23ff0000'; + c.stroke(); + c.beginPath(); + c.moveTo(0, 1.5); + c.lineTo(4, 1.5); + c.strokeStyle = '%230000ff'; + c.stroke(); + </script> + </body> + )HTML"); BrowserAccessibility* target = FindNode(ax::mojom::Role::kCanvas, "canvas"); ASSERT_NE(nullptr, target); @@ -262,26 +242,19 @@ IN_PROC_BROWSER_TEST_F(AccessibilityCanvasActionBrowserTest, CanvasGetImageScale) { - NavigateToURL(shell(), GURL(url::kAboutBlankURL)); - - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kLoadComplete); - GURL url( - "data:text/html," - "<body>" - "<canvas aria-label='canvas' id='c' width='40' height='20'></canvas>" - "<script>\n" - " var c = document.getElementById('c').getContext('2d');\n" - " c.fillStyle = '%2300ff00';\n" - " c.fillRect(0, 0, 40, 10);\n" - " c.fillStyle = '%23ff00ff';\n" - " c.fillRect(0, 10, 40, 10);\n" - "</script>" - "</body>"); - - NavigateToURL(shell(), url); - waiter.WaitForNotification(); + LoadInitialAccessibilityTreeFromHtml(R"HTML( + <body> + <canvas aria-label="canvas" id="c" width="40" height="20"> + </canvas> + <script> + var c = document.getElementById('c').getContext('2d'); + c.fillStyle = '%2300ff00'; + c.fillRect(0, 0, 40, 10); + c.fillStyle = '%23ff00ff'; + c.fillRect(0, 10, 40, 10); + </script> + </body> + )HTML"); BrowserAccessibility* target = FindNode(ax::mojom::Role::kCanvas, "canvas"); ASSERT_NE(nullptr, target); @@ -345,18 +318,11 @@ IN_PROC_BROWSER_TEST_F(AccessibilityActionBrowserTest, DoDefaultActionFocusesContentEditable) { - NavigateToURL(shell(), GURL(url::kAboutBlankURL)); - - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kLoadComplete); - GURL url( - "data:text/html," - "<div><button>Before</button></div>" - "<div contenteditable>Editable text</div>" - "<div><button>After</button></div>"); - NavigateToURL(shell(), url); - waiter.WaitForNotification(); + LoadInitialAccessibilityTreeFromHtml(R"HTML( + <div><button>Before</button></div> + <div contenteditable>Editable text</div> + <div><button>After</button></div> + )HTML"); BrowserAccessibility* target = FindNode(ax::mojom::Role::kGenericContainer, "Editable text"); @@ -372,16 +338,9 @@ } IN_PROC_BROWSER_TEST_F(AccessibilityActionBrowserTest, InputSetValue) { - NavigateToURL(shell(), GURL(url::kAboutBlankURL)); - - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kLoadComplete); - GURL url( - "data:text/html," - "<input aria-label='Answer' value='Before'>"); - NavigateToURL(shell(), url); - waiter.WaitForNotification(); + LoadInitialAccessibilityTreeFromHtml(R"HTML( + <input aria-label="Answer" value="Before"> + )HTML"); BrowserAccessibility* target = FindNode(ax::mojom::Role::kTextField, "Answer"); @@ -400,16 +359,9 @@ } IN_PROC_BROWSER_TEST_F(AccessibilityActionBrowserTest, TextareaSetValue) { - NavigateToURL(shell(), GURL(url::kAboutBlankURL)); - - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kLoadComplete); - GURL url( - "data:text/html," - "<textarea aria-label='Answer'>Before</textarea>"); - NavigateToURL(shell(), url); - waiter.WaitForNotification(); + LoadInitialAccessibilityTreeFromHtml(R"HTML( + <textarea aria-label="Answer">Before</textarea> + )HTML"); BrowserAccessibility* target = FindNode(ax::mojom::Role::kTextField, "Answer"); @@ -441,16 +393,9 @@ IN_PROC_BROWSER_TEST_F(AccessibilityActionBrowserTest, ContenteditableSetValue) { - NavigateToURL(shell(), GURL(url::kAboutBlankURL)); - - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kLoadComplete); - GURL url( - "data:text/html," - "<div contenteditable aria-label='Answer'>Before</div>"); - NavigateToURL(shell(), url); - waiter.WaitForNotification(); + LoadInitialAccessibilityTreeFromHtml(R"HTML( + <div contenteditable aria-label="Answer">Before</div> + )HTML"); BrowserAccessibility* target = FindNode(ax::mojom::Role::kGenericContainer, "Answer"); @@ -481,18 +426,10 @@ } IN_PROC_BROWSER_TEST_F(AccessibilityActionBrowserTest, ShowContextMenu) { - NavigateToURL(shell(), GURL(url::kAboutBlankURL)); - - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kLoadComplete); - GURL url( - "data:text/html," - "<a href='about:blank'>1</a>" - "<a href='about:blank'>2</a>"); - - NavigateToURL(shell(), url); - waiter.WaitForNotification(); + LoadInitialAccessibilityTreeFromHtml(R"HTML( + <a href="about:blank">1</a> + <a href="about:blank">2</a> + )HTML"); BrowserAccessibility* target_node = FindNode(ax::mojom::Role::kLink, "2"); EXPECT_NE(target_node, nullptr);
diff --git a/content/browser/accessibility/accessibility_tree_formatter_base.cc b/content/browser/accessibility/accessibility_tree_formatter_base.cc index 6734ee8..2a231537 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_base.cc +++ b/content/browser/accessibility/accessibility_tree_formatter_base.cc
@@ -32,6 +32,14 @@ } // namespace +AccessibilityTreeFormatter::TestPass AccessibilityTreeFormatter::GetTestPass( + size_t index) { + std::vector<content::AccessibilityTreeFormatter::TestPass> passes = + content::AccessibilityTreeFormatter::GetTestPasses(); + CHECK_LT(index, passes.size()); + return passes[index]; +} + base::string16 AccessibilityTreeFormatter::DumpAccessibilityTreeFromManager( BrowserAccessibilityManager* ax_mgr, bool internal) {
diff --git a/content/browser/accessibility/browser_accessibility_manager_android.cc b/content/browser/accessibility/browser_accessibility_manager_android.cc index e177c46..4368ff3 100644 --- a/content/browser/accessibility/browser_accessibility_manager_android.cc +++ b/content/browser/accessibility/browser_accessibility_manager_android.cc
@@ -213,6 +213,7 @@ case ui::AXEventGenerator::Event::DROPEFFECT_CHANGED: case ui::AXEventGenerator::Event::EXPANDED: case ui::AXEventGenerator::Event::ENABLED_CHANGED: + case ui::AXEventGenerator::Event::FOCUS_CHANGED: case ui::AXEventGenerator::Event::FLOW_FROM_CHANGED: case ui::AXEventGenerator::Event::FLOW_TO_CHANGED: case ui::AXEventGenerator::Event::GRABBED_CHANGED:
diff --git a/content/browser/accessibility/browser_accessibility_manager_mac.mm b/content/browser/accessibility/browser_accessibility_manager_mac.mm index ff366b2..d81f5142 100644 --- a/content/browser/accessibility/browser_accessibility_manager_mac.mm +++ b/content/browser/accessibility/browser_accessibility_manager_mac.mm
@@ -383,6 +383,7 @@ case ui::AXEventGenerator::Event::DOCUMENT_TITLE_CHANGED: case ui::AXEventGenerator::Event::DROPEFFECT_CHANGED: case ui::AXEventGenerator::Event::ENABLED_CHANGED: + case ui::AXEventGenerator::Event::FOCUS_CHANGED: case ui::AXEventGenerator::Event::FLOW_FROM_CHANGED: case ui::AXEventGenerator::Event::FLOW_TO_CHANGED: case ui::AXEventGenerator::Event::GRABBED_CHANGED:
diff --git a/content/browser/accessibility/browser_accessibility_manager_win.cc b/content/browser/accessibility/browser_accessibility_manager_win.cc index f832e1bee..b61efe06 100644 --- a/content/browser/accessibility/browser_accessibility_manager_win.cc +++ b/content/browser/accessibility/browser_accessibility_manager_win.cc
@@ -191,10 +191,20 @@ FireUiaPropertyChangedEvent(UIA_ToggleToggleStatePropertyId, node); aria_properties_events_.insert(node); break; - case ui::AXEventGenerator::Event::CHILDREN_CHANGED: - FireWinAccessibilityEvent(EVENT_OBJECT_REORDER, node); - FireUiaStructureChangedEvent(StructureChangeType_ChildrenReordered, node); + case ui::AXEventGenerator::Event::CHILDREN_CHANGED: { + // If this node is ignored, notify from the platform parent if available, + // since it will be unignored. + BrowserAccessibility* target_node = + node->GetData().HasState(ax::mojom::State::kIgnored) + ? node->PlatformGetParent() + : node; + if (target_node) { + FireWinAccessibilityEvent(EVENT_OBJECT_REORDER, target_node); + FireUiaStructureChangedEvent(StructureChangeType_ChildrenReordered, + target_node); + } break; + } case ui::AXEventGenerator::Event::CLASS_NAME_CHANGED: FireUiaPropertyChangedEvent(UIA_ClassNamePropertyId, node); break; @@ -252,7 +262,6 @@ FireWinAccessibilityEvent(EVENT_OBJECT_SHOW, node); FireUiaStructureChangedEvent(StructureChangeType_ChildAdded, node); } - aria_properties_events_.insert(node); break; case ui::AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED: FireWinAccessibilityEvent(EVENT_OBJECT_NAMECHANGE, node); @@ -396,6 +405,7 @@ break; case ui::AXEventGenerator::Event::AUTO_COMPLETE_CHANGED: case ui::AXEventGenerator::Event::DOCUMENT_TITLE_CHANGED: + case ui::AXEventGenerator::Event::FOCUS_CHANGED: case ui::AXEventGenerator::Event::LIVE_REGION_NODE_CHANGED: case ui::AXEventGenerator::Event::LOAD_START: case ui::AXEventGenerator::Event::MENU_ITEM_SELECTED: @@ -464,16 +474,10 @@ return; if (!ShouldFireEventForNode(node)) return; - - // Suppress events when |IGNORED_CHANGED| with the exception for firing - // UIA_AriaPropertiesPropertyId-hidden event on non-text node marked as - // ignored. + // Suppress events when |IGNORED_CHANGED| if (node->HasState(ax::mojom::State::kIgnored) || - base::Contains(ignored_changed_nodes_, node)) { - if (uia_property != UIA_AriaPropertiesPropertyId || - node->IsTextOnlyObject()) - return; - } + base::Contains(ignored_changed_nodes_, node)) + return; // The old value is not used by the system VARIANT old_value = {};
diff --git a/content/browser/accessibility/dump_accessibility_browsertest_base.cc b/content/browser/accessibility/dump_accessibility_browsertest_base.cc index 9fa59908..9f1e6322 100644 --- a/content/browser/accessibility/dump_accessibility_browsertest_base.cc +++ b/content/browser/accessibility/dump_accessibility_browsertest_base.cc
@@ -23,7 +23,6 @@ #include "content/browser/accessibility/browser_accessibility.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/accessibility/browser_accessibility_state_impl.h" -#include "content/browser/accessibility/dump_accessibility_test_helper.h" #include "content/browser/renderer_host/render_widget_host_view_child_frame.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/web_contents.h" @@ -34,6 +33,7 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" +#include "content/public/test/dump_accessibility_test_helper.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" #include "content/test/accessibility_browser_test_utils.h"
diff --git a/content/browser/accessibility/dump_accessibility_events_browsertest.cc b/content/browser/accessibility/dump_accessibility_events_browsertest.cc index 5c99258..28353c7 100644 --- a/content/browser/accessibility/dump_accessibility_events_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_events_browsertest.cc
@@ -283,11 +283,6 @@ } IN_PROC_BROWSER_TEST_P(DumpAccessibilityEventsTest, - AccessibilityEventsAriaHiddenChanged) { - RunEventTest(FILE_PATH_LITERAL("aria-hidden-changed.html")); -} - -IN_PROC_BROWSER_TEST_P(DumpAccessibilityEventsTest, AccessibilityEventsAriaInvalidChanged) { RunEventTest(FILE_PATH_LITERAL("aria-invalid-changed.html")); } @@ -488,8 +483,16 @@ RunEventTest(FILE_PATH_LITERAL("disabled-state-changed.html")); } +// http://crbug.com/982998 +#if defined(OS_WIN) +#define MAYBE_AccessibilityEventsExpandedChange \ + DISABLED_AccessibilityEventsExpandedChange +#else +#define MAYBE_AccessibilityEventsExpandedChange \ + AccessibilityEventsExpandedChange +#endif IN_PROC_BROWSER_TEST_P(DumpAccessibilityEventsTest, - AccessibilityEventsExpandedChange) { + MAYBE_AccessibilityEventsExpandedChange) { RunEventTest(FILE_PATH_LITERAL("expanded-change.html")); } @@ -726,11 +729,6 @@ RunEventTest(FILE_PATH_LITERAL("tbody-focus.html")); } -IN_PROC_BROWSER_TEST_P(DumpAccessibilityEventsTest, - AccessibilityEventsVisibilityHiddenChanged) { - RunEventTest(FILE_PATH_LITERAL("visibility-hidden-changed.html")); -} - // Even with the deflaking in WaitForAccessibilityTreeToContainNodeWithName, // this test is still flaky on Windows. // TODO(aboxhall, dmazzoni, meredithl): re-enable with better fix for above.
diff --git a/content/browser/accessibility/web_contents_accessibility_android.cc b/content/browser/accessibility/web_contents_accessibility_android.cc index b40338c..0fecfc9a 100644 --- a/content/browser/accessibility/web_contents_accessibility_android.cc +++ b/content/browser/accessibility/web_contents_accessibility_android.cc
@@ -7,6 +7,7 @@ #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" +#include "base/debug/crash_logging.h" #include "base/feature_list.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" @@ -645,6 +646,18 @@ return node->GetSelectionEnd(); } +static size_t ActualUnignoredChildCount(const ui::AXNode* node) { + size_t count = 0; + for (const ui::AXNode* child : node->children()) { + if (child->data().HasState(ax::mojom::State::kIgnored)) { + count += ActualUnignoredChildCount(child); + } else { + ++count; + } + } + return count; +} + jboolean WebContentsAccessibilityAndroid::PopulateAccessibilityNodeInfo( JNIEnv* env, const JavaParamRef<jobject>& obj, @@ -654,17 +667,59 @@ if (!node) return false; + // TODO(crbug.com/974444): This crash key string is temporary in order + // to get some useful information about the state when the crash occurs. + // Remove the crash key string and additional logic once resolved. + static auto* crbug_974444_crash_key = base::debug::AllocateCrashKeyString( + "crbug_974444", base::debug::CrashKeySize::Size64); + std::stringstream base_message; + base_message << "node_role: " << node->GetData().role; + std::string tag; + if (node->GetData().GetStringAttribute(ax::mojom::StringAttribute::kHtmlTag, + &tag)) + base_message << ", node_tag: <" << tag.c_str() << ">"; + if (node->GetData().HasState(ax::mojom::State::kIgnored)) + base_message << ", IGNORED"; + if (BrowserAccessibilityManager* manager = node->manager()) { + if (ui::AXTree* tree = manager->ax_tree()) { + if (tree->GetTreeUpdateInProgressState()) + base_message << ", TREE_UPDATE_IN_PROGRESS"; + } else { + base_message << ", NO_AX_TREE"; + } + } else { + base_message << ", NO_MANAGER"; + } + if (node->PlatformGetParent()) { auto* android_node = static_cast<BrowserAccessibilityAndroid*>(node->PlatformGetParent()); + std::stringstream message; + message << base_message.str() << ", PlatformGetParent"; + base::debug::SetCrashKeyString(crbug_974444_crash_key, message.str()); Java_WebContentsAccessibilityImpl_setAccessibilityNodeInfoParent( env, obj, info, android_node->unique_id()); + base::debug::ClearCrashKeyString(crbug_974444_crash_key); } for (unsigned i = 0; i < node->PlatformChildCount(); ++i) { auto* android_node = static_cast<BrowserAccessibilityAndroid*>(node->PlatformGetChild(i)); + if (!android_node) { + std::stringstream message; + message << base_message.str() << ", PlatformGetChild [" << i << "/" + << node->PlatformChildCount() << "]"; + const size_t actual_unignored_child_count = + ActualUnignoredChildCount(node->node()); + if (actual_unignored_child_count != node->PlatformChildCount()) { + message << ", unignored_child_count_ [found: " + << node->PlatformChildCount() + << ", expected: " << actual_unignored_child_count << "]"; + } + base::debug::SetCrashKeyString(crbug_974444_crash_key, message.str()); + } Java_WebContentsAccessibilityImpl_addAccessibilityNodeInfoChild( env, obj, info, android_node->unique_id()); + base::debug::ClearCrashKeyString(crbug_974444_crash_key); } Java_WebContentsAccessibilityImpl_setAccessibilityNodeInfoBooleanAttributes( env, obj, info, unique_id, node->IsCheckable(), node->IsChecked(),
diff --git a/content/browser/appcache/appcache_disk_cache.cc b/content/browser/appcache/appcache_disk_cache.cc index ff87c13..e98c37e 100644 --- a/content/browser/appcache/appcache_disk_cache.cc +++ b/content/browser/appcache/appcache_disk_cache.cc
@@ -320,8 +320,7 @@ : use_simple_cache_(use_simple_cache), is_disabled_(false), is_waiting_to_initialize_(false), - uma_name_(uma_name), - weak_factory_(this) {} + uma_name_(uma_name) {} AppCacheDiskCache::PendingCall::PendingCall() : call_type(CREATE), key(0), entry(nullptr) {}
diff --git a/content/browser/appcache/appcache_disk_cache.h b/content/browser/appcache/appcache_disk_cache.h index 8fd333f2..ab0a2f0 100644 --- a/content/browser/appcache/appcache_disk_cache.h +++ b/content/browser/appcache/appcache_disk_cache.h
@@ -161,7 +161,7 @@ std::unique_ptr<disk_cache::Backend> disk_cache_; const char* const uma_name_; - base::WeakPtrFactory<AppCacheDiskCache> weak_factory_; + base::WeakPtrFactory<AppCacheDiskCache> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/appcache/appcache_host.cc b/content/browser/appcache/appcache_host.cc index c21ac69..23b4dc5 100644 --- a/content/browser/appcache/appcache_host.cc +++ b/content/browser/appcache/appcache_host.cc
@@ -92,8 +92,7 @@ main_resource_was_namespace_entry_(false), main_resource_blocked_(false), associated_cache_info_pending_(false), - binding_(this), - weak_factory_(this) { + binding_(this) { service_->AddObserver(this); }
diff --git a/content/browser/appcache/appcache_host.h b/content/browser/appcache/appcache_host.h index 8d01646..e4d2604 100644 --- a/content/browser/appcache/appcache_host.h +++ b/content/browser/appcache/appcache_host.h
@@ -390,7 +390,7 @@ mojo::Binding<blink::mojom::AppCacheHost> binding_; - base::WeakPtrFactory<AppCacheHost> weak_factory_; + base::WeakPtrFactory<AppCacheHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AppCacheHost); };
diff --git a/content/browser/appcache/appcache_internals_ui.cc b/content/browser/appcache/appcache_internals_ui.cc index 5948fc27..0a713e2 100644 --- a/content/browser/appcache/appcache_internals_ui.cc +++ b/content/browser/appcache/appcache_internals_ui.cc
@@ -351,7 +351,7 @@ } AppCacheInternalsUI::AppCacheInternalsUI(WebUI* web_ui) - : WebUIController(web_ui), weak_ptr_factory_(this) { + : WebUIController(web_ui) { web_ui->RegisterMessageCallback( kRequestGetAllAppCacheInfo, base::BindRepeating(&AppCacheInternalsUI::GetAllAppCache, AsWeakPtr()));
diff --git a/content/browser/appcache/appcache_internals_ui.h b/content/browser/appcache/appcache_internals_ui.h index 62a17bcd..c2fa6b0e 100644 --- a/content/browser/appcache/appcache_internals_ui.h +++ b/content/browser/appcache/appcache_internals_ui.h
@@ -126,7 +126,7 @@ Proxy* GetProxyForPartitionPath(const base::FilePath& path); std::list<scoped_refptr<Proxy>> appcache_proxies_; - base::WeakPtrFactory<AppCacheInternalsUI> weak_ptr_factory_; + base::WeakPtrFactory<AppCacheInternalsUI> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AppCacheInternalsUI); };
diff --git a/content/browser/appcache/appcache_quota_client_unittest.cc b/content/browser/appcache/appcache_quota_client_unittest.cc index 2eef1c61..79de6c660 100644 --- a/content/browser/appcache/appcache_quota_client_unittest.cc +++ b/content/browser/appcache/appcache_quota_client_unittest.cc
@@ -38,8 +38,7 @@ delete_status_(blink::mojom::QuotaStatusCode::kUnknown), num_get_origin_usage_completions_(0), num_get_origins_completions_(0), - num_delete_origins_completions_(0), - weak_factory_(this) {} + num_delete_origins_completions_(0) {} int64_t GetOriginUsage(storage::QuotaClient* client, const url::Origin& origin, @@ -155,7 +154,7 @@ int num_get_origins_completions_; int num_delete_origins_completions_; MockAppCacheService mock_service_; - base::WeakPtrFactory<AppCacheQuotaClientTest> weak_factory_; + base::WeakPtrFactory<AppCacheQuotaClientTest> weak_factory_{this}; };
diff --git a/content/browser/appcache/appcache_request_handler.cc b/content/browser/appcache/appcache_request_handler.cc index 42b2110f..45c95b6 100644 --- a/content/browser/appcache/appcache_request_handler.cc +++ b/content/browser/appcache/appcache_request_handler.cc
@@ -51,8 +51,7 @@ maybe_load_resource_executed_(false), cache_id_(blink::mojom::kAppCacheNoCacheId), service_(host_->service()), - request_(std::move(request)), - weak_factory_(this) { + request_(std::move(request)) { DCHECK(host_); DCHECK(service_); host_->AddObserver(this);
diff --git a/content/browser/appcache/appcache_request_handler.h b/content/browser/appcache/appcache_request_handler.h index 5179daf3..555832e 100644 --- a/content/browser/appcache/appcache_request_handler.h +++ b/content/browser/appcache/appcache_request_handler.h
@@ -263,7 +263,7 @@ // AppCacheSubresourceURLFactory instance on creation. base::WeakPtr<AppCacheHost> appcache_host_; - base::WeakPtrFactory<AppCacheRequestHandler> weak_factory_; + base::WeakPtrFactory<AppCacheRequestHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AppCacheRequestHandler); };
diff --git a/content/browser/appcache/appcache_response.cc b/content/browser/appcache/appcache_response.cc index 3cf8dbf39..22cdb5b 100644 --- a/content/browser/appcache/appcache_response.cc +++ b/content/browser/appcache/appcache_response.cc
@@ -193,8 +193,7 @@ range_offset_(0), range_length_(std::numeric_limits<int32_t>::max()), read_position_(0), - reading_metadata_size_(0), - weak_factory_(this) {} + reading_metadata_size_(0) {} AppCacheResponseReader::~AppCacheResponseReader() = default; @@ -325,8 +324,7 @@ info_size_(0), write_position_(0), write_amount_(0), - creation_phase_(INITIAL_ATTEMPT), - weak_factory_(this) {} + creation_phase_(INITIAL_ATTEMPT) {} AppCacheResponseWriter::~AppCacheResponseWriter() = default; @@ -490,8 +488,7 @@ int64_t response_id, base::WeakPtr<AppCacheDiskCache> disk_cache) : AppCacheResponseIO(response_id, std::move(disk_cache)), - write_amount_(0), - weak_factory_(this) {} + write_amount_(0) {} AppCacheResponseMetadataWriter::~AppCacheResponseMetadataWriter() = default;
diff --git a/content/browser/appcache/appcache_response.h b/content/browser/appcache/appcache_response.h index 492b00f..746ed00 100644 --- a/content/browser/appcache/appcache_response.h +++ b/content/browser/appcache/appcache_response.h
@@ -176,7 +176,7 @@ int read_position_; int reading_metadata_size_; - base::WeakPtrFactory<AppCacheResponseReader> weak_factory_; + base::WeakPtrFactory<AppCacheResponseReader> weak_factory_{this}; }; // Writes new response data to storage. If the object is deleted @@ -246,7 +246,7 @@ int write_position_; int write_amount_; CreationPhase creation_phase_; - base::WeakPtrFactory<AppCacheResponseWriter> weak_factory_; + base::WeakPtrFactory<AppCacheResponseWriter> weak_factory_{this}; }; // Writes metadata of the existing response to storage. If the object is deleted @@ -287,7 +287,7 @@ base::WeakPtr<AppCacheResponseIO> GetWeakPtr() override; int write_amount_; - base::WeakPtrFactory<AppCacheResponseMetadataWriter> weak_factory_; + base::WeakPtrFactory<AppCacheResponseMetadataWriter> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/appcache/appcache_service_impl.cc b/content/browser/appcache/appcache_service_impl.cc index 5248567..6ac5ed1 100644 --- a/content/browser/appcache/appcache_service_impl.cc +++ b/content/browser/appcache/appcache_service_impl.cc
@@ -379,8 +379,7 @@ quota_client_(nullptr), quota_manager_proxy_(quota_manager_proxy), request_context_(nullptr), - force_keep_session_state_(false), - weak_factory_(this) { + force_keep_session_state_(false) { if (quota_manager_proxy_.get()) { // The operator new is used here because this AppCacheQuotaClient instance // deletes itself after both the QuotaManager and the AppCacheService are
diff --git a/content/browser/appcache/appcache_service_impl.h b/content/browser/appcache/appcache_service_impl.h index 8d1629d..006fbbc 100644 --- a/content/browser/appcache/appcache_service_impl.h +++ b/content/browser/appcache/appcache_service_impl.h
@@ -257,7 +257,7 @@ std::map<base::UnguessableToken, std::unique_ptr<AppCacheHost>>; AppCacheHostProcessMap hosts_; - base::WeakPtrFactory<AppCacheServiceImpl> weak_factory_; + base::WeakPtrFactory<AppCacheServiceImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AppCacheServiceImpl); };
diff --git a/content/browser/appcache/appcache_storage.cc b/content/browser/appcache/appcache_storage.cc index d0cf584..6b4afff 100644 --- a/content/browser/appcache/appcache_storage.cc +++ b/content/browser/appcache/appcache_storage.cc
@@ -24,8 +24,7 @@ : last_cache_id_(kUnitializedId), last_group_id_(kUnitializedId), last_response_id_(kUnitializedId), - service_(service), - weak_factory_(this) {} + service_(service) {} AppCacheStorage::~AppCacheStorage() { DCHECK(delegate_references_.empty());
diff --git a/content/browser/appcache/appcache_storage.h b/content/browser/appcache/appcache_storage.h index 7d6ad74..50515fa 100644 --- a/content/browser/appcache/appcache_storage.h +++ b/content/browser/appcache/appcache_storage.h
@@ -349,7 +349,7 @@ // The WeakPtrFactory below must occur last in the class definition so they // get destroyed last. - base::WeakPtrFactory<AppCacheStorage> weak_factory_; + base::WeakPtrFactory<AppCacheStorage> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AppCacheStorage); };
diff --git a/content/browser/appcache/appcache_storage_impl.cc b/content/browser/appcache/appcache_storage_impl.cc index 74ad962..c9b42b0a 100644 --- a/content/browser/appcache/appcache_storage_impl.cc +++ b/content/browser/appcache/appcache_storage_impl.cc
@@ -1377,8 +1377,7 @@ database_(nullptr), is_disabled_(false), delete_and_start_over_pending_(false), - expecting_cleanup_complete_on_disable_(false), - weak_factory_(this) {} + expecting_cleanup_complete_on_disable_(false) {} AppCacheStorageImpl::~AppCacheStorageImpl() { for (StoreGroupAndCacheTask* task : pending_quota_queries_)
diff --git a/content/browser/appcache/appcache_storage_impl.h b/content/browser/appcache/appcache_storage_impl.h index 4e9f73d..27ed1a9 100644 --- a/content/browser/appcache/appcache_storage_impl.h +++ b/content/browser/appcache/appcache_storage_impl.h
@@ -203,7 +203,7 @@ // Used to short-circuit certain operations without having to schedule // any tasks on the background database thread. base::circular_deque<base::OnceClosure> pending_simple_tasks_; - base::WeakPtrFactory<AppCacheStorageImpl> weak_factory_; + base::WeakPtrFactory<AppCacheStorageImpl> weak_factory_{this}; friend class content::AppCacheStorageImplTest; friend class content::ChromeAppCacheServiceTest;
diff --git a/content/browser/appcache/appcache_subresource_url_factory.cc b/content/browser/appcache/appcache_subresource_url_factory.cc index d728d1d3..3232aae4 100644 --- a/content/browser/appcache/appcache_subresource_url_factory.cc +++ b/content/browser/appcache/appcache_subresource_url_factory.cc
@@ -64,8 +64,7 @@ traffic_annotation_(annotation), network_loader_factory_(std::move(network_loader_factory)), local_client_binding_(this), - host_(appcache_host), - weak_factory_(this) { + host_(appcache_host) { DCHECK_CURRENTLY_ON(BrowserThread::IO); remote_binding_.set_connection_error_handler(base::BindOnce( &SubresourceLoader::OnConnectionError, base::Unretained(this))); @@ -316,7 +315,7 @@ base::WeakPtr<AppCacheHost> host_; - base::WeakPtrFactory<SubresourceLoader> weak_factory_; + base::WeakPtrFactory<SubresourceLoader> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SubresourceLoader); }; @@ -327,8 +326,7 @@ scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory, base::WeakPtr<AppCacheHost> host) : network_loader_factory_(std::move(network_loader_factory)), - appcache_host_(host), - weak_factory_(this) { + appcache_host_(host) { bindings_.set_connection_error_handler( base::BindRepeating(&AppCacheSubresourceURLFactory::OnConnectionError, base::Unretained(this)));
diff --git a/content/browser/appcache/appcache_subresource_url_factory.h b/content/browser/appcache/appcache_subresource_url_factory.h index c66b2ccb..097ae61 100644 --- a/content/browser/appcache/appcache_subresource_url_factory.h +++ b/content/browser/appcache/appcache_subresource_url_factory.h
@@ -64,7 +64,7 @@ mojo::BindingSet<network::mojom::URLLoaderFactory> bindings_; scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory_; base::WeakPtr<AppCacheHost> appcache_host_; - base::WeakPtrFactory<AppCacheSubresourceURLFactory> weak_factory_; + base::WeakPtrFactory<AppCacheSubresourceURLFactory> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AppCacheSubresourceURLFactory); };
diff --git a/content/browser/appcache/appcache_update_job.cc b/content/browser/appcache/appcache_update_job.cc index 49a6342..ee87609 100644 --- a/content/browser/appcache/appcache_update_job.cc +++ b/content/browser/appcache/appcache_update_job.cc
@@ -239,8 +239,7 @@ manifest_fetcher_(nullptr), manifest_has_valid_mime_type_(false), stored_state_(UNSTORED), - storage_(service->storage()), - weak_factory_(this) { + storage_(service->storage()) { service_->AddObserver(this); }
diff --git a/content/browser/appcache/appcache_update_job.h b/content/browser/appcache/appcache_update_job.h index 18a1a37..41f6dc4 100644 --- a/content/browser/appcache/appcache_update_job.h +++ b/content/browser/appcache/appcache_update_job.h
@@ -304,7 +304,7 @@ StoredState stored_state_; AppCacheStorage* storage_; - base::WeakPtrFactory<AppCacheUpdateJob> weak_factory_; + base::WeakPtrFactory<AppCacheUpdateJob> weak_factory_{this}; FRIEND_TEST_ALL_PREFIXES(content::AppCacheGroupTest, QueueUpdate);
diff --git a/content/browser/appcache/appcache_url_loader_job.cc b/content/browser/appcache/appcache_url_loader_job.cc index 6c6a0be..03c23a09 100644 --- a/content/browser/appcache/appcache_url_loader_job.cc +++ b/content/browser/appcache/appcache_url_loader_job.cc
@@ -162,8 +162,7 @@ loader_callback_(std::move(loader_callback)), appcache_request_(appcache_request->GetWeakPtr()), is_main_resource_load_(IsResourceTypeFrame(static_cast<ResourceType>( - appcache_request->GetResourceRequest()->resource_type))), - weak_factory_(this) {} + appcache_request->GetResourceRequest()->resource_type))) {} void AppCacheURLLoaderJob::CallLoaderCallback() { DCHECK(loader_callback_);
diff --git a/content/browser/appcache/appcache_url_loader_job.h b/content/browser/appcache/appcache_url_loader_job.h index 1091ba3..1e2d3a21 100644 --- a/content/browser/appcache/appcache_url_loader_job.h +++ b/content/browser/appcache/appcache_url_loader_job.h
@@ -136,7 +136,7 @@ bool is_deleting_soon_ = false; bool is_main_resource_load_; - base::WeakPtrFactory<AppCacheURLLoaderJob> weak_factory_; + base::WeakPtrFactory<AppCacheURLLoaderJob> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AppCacheURLLoaderJob); };
diff --git a/content/browser/appcache/appcache_url_loader_request.cc b/content/browser/appcache/appcache_url_loader_request.cc index 0fbd841..c7f2392 100644 --- a/content/browser/appcache/appcache_url_loader_request.cc +++ b/content/browser/appcache/appcache_url_loader_request.cc
@@ -11,7 +11,7 @@ AppCacheURLLoaderRequest::AppCacheURLLoaderRequest( const network::ResourceRequest& request) - : request_(request), weak_factory_(this) {} + : request_(request) {} AppCacheURLLoaderRequest::~AppCacheURLLoaderRequest() = default;
diff --git a/content/browser/appcache/appcache_url_loader_request.h b/content/browser/appcache/appcache_url_loader_request.h index 17120ba43..497f4a2 100644 --- a/content/browser/appcache/appcache_url_loader_request.h +++ b/content/browser/appcache/appcache_url_loader_request.h
@@ -48,7 +48,7 @@ private: network::ResourceRequest request_; network::ResourceResponseHead response_; - base::WeakPtrFactory<AppCacheURLLoaderRequest> weak_factory_; + base::WeakPtrFactory<AppCacheURLLoaderRequest> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AppCacheURLLoaderRequest); };
diff --git a/content/browser/appcache/appcache_url_request_job.cc b/content/browser/appcache/appcache_url_request_job.cc index 6080c72..b473d747 100644 --- a/content/browser/appcache/appcache_url_request_job.cc +++ b/content/browser/appcache/appcache_url_request_job.cc
@@ -118,8 +118,7 @@ cache_id_(blink::mojom::kAppCacheNoCacheId), is_fallback_(false), is_main_resource_(is_main_resource), - on_prepare_to_restart_callback_(std::move(restart_callback)), - weak_factory_(this) { + on_prepare_to_restart_callback_(std::move(restart_callback)) { DCHECK(storage_); }
diff --git a/content/browser/appcache/appcache_url_request_job.h b/content/browser/appcache/appcache_url_request_job.h index 5b453e6..5490033b 100644 --- a/content/browser/appcache/appcache_url_request_job.h +++ b/content/browser/appcache/appcache_url_request_job.h
@@ -133,7 +133,7 @@ scoped_refptr<AppCache> cache_; scoped_refptr<AppCacheGroup> group_; OnPrepareToRestartCallback on_prepare_to_restart_callback_; - base::WeakPtrFactory<AppCacheURLRequestJob> weak_factory_; + base::WeakPtrFactory<AppCacheURLRequestJob> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AppCacheURLRequestJob); };
diff --git a/content/browser/appcache/mock_appcache_storage.cc b/content/browser/appcache/mock_appcache_storage.cc index 4d34052..293b0432 100644 --- a/content/browser/appcache/mock_appcache_storage.cc +++ b/content/browser/appcache/mock_appcache_storage.cc
@@ -40,8 +40,7 @@ simulate_find_sub_resource_(false), simulated_found_cache_id_(blink::mojom::kAppCacheNoCacheId), simulated_found_group_id_(0), - simulated_found_network_namespace_(false), - weak_factory_(this) { + simulated_found_network_namespace_(false) { last_cache_id_ = 0; last_group_id_ = 0; last_response_id_ = 0;
diff --git a/content/browser/appcache/mock_appcache_storage.h b/content/browser/appcache/mock_appcache_storage.h index a89ae697..dee5793 100644 --- a/content/browser/appcache/mock_appcache_storage.h +++ b/content/browser/appcache/mock_appcache_storage.h
@@ -226,7 +226,7 @@ scoped_refptr<AppCacheInfoCollection> simulated_appcache_info_; std::unique_ptr<AppCacheResponseReader> simulated_reader_; - base::WeakPtrFactory<MockAppCacheStorage> weak_factory_; + base::WeakPtrFactory<MockAppCacheStorage> weak_factory_{this}; FRIEND_TEST_ALL_PREFIXES(MockAppCacheStorageTest, BasicFindMainResponse);
diff --git a/content/browser/background_fetch/background_fetch_context.cc b/content/browser/background_fetch/background_fetch_context.cc index c33451a..6b46e94 100644 --- a/content/browser/background_fetch/background_fetch_context.cc +++ b/content/browser/background_fetch/background_fetch_context.cc
@@ -42,8 +42,7 @@ devtools_context_(std::move(devtools_context)), registration_notifier_( std::make_unique<BackgroundFetchRegistrationNotifier>()), - delegate_proxy_(browser_context_), - weak_factory_(this) { + delegate_proxy_(browser_context_) { // Although this lives only on the IO thread, it is constructed on UI thread. DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(service_worker_context_);
diff --git a/content/browser/background_fetch/background_fetch_context.h b/content/browser/background_fetch/background_fetch_context.h index 969e01e20..00990a2 100644 --- a/content/browser/background_fetch/background_fetch_context.h +++ b/content/browser/background_fetch/background_fetch_context.h
@@ -209,7 +209,8 @@ blink::mojom::BackgroundFetchService::FetchCallback> fetch_callbacks_; - base::WeakPtrFactory<BackgroundFetchContext> weak_factory_; // Must be last. + base::WeakPtrFactory<BackgroundFetchContext> weak_factory_{ + this}; // Must be last. DISALLOW_COPY_AND_ASSIGN(BackgroundFetchContext); };
diff --git a/content/browser/background_fetch/background_fetch_data_manager.cc b/content/browser/background_fetch/background_fetch_data_manager.cc index 33b6420..24dad7b 100644 --- a/content/browser/background_fetch/background_fetch_data_manager.cc +++ b/content/browser/background_fetch/background_fetch_data_manager.cc
@@ -43,8 +43,7 @@ scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy) : service_worker_context_(std::move(service_worker_context)), cache_storage_context_(std::move(cache_storage_context)), - quota_manager_proxy_(std::move(quota_manager_proxy)), - weak_ptr_factory_(this) { + quota_manager_proxy_(std::move(quota_manager_proxy)) { // Constructed on the UI thread, then used on the IO thread. DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(browser_context);
diff --git a/content/browser/background_fetch/background_fetch_data_manager.h b/content/browser/background_fetch/background_fetch_data_manager.h index ee08e52b..f1a2e91d 100644 --- a/content/browser/background_fetch/background_fetch_data_manager.h +++ b/content/browser/background_fetch/background_fetch_data_manager.h
@@ -265,7 +265,7 @@ // TODO(crbug.com/711354): Possibly update key when CORS support is added. std::map<std::string, CacheStorageHandle> cache_storage_handle_map_; - base::WeakPtrFactory<BackgroundFetchDataManager> weak_ptr_factory_; + base::WeakPtrFactory<BackgroundFetchDataManager> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundFetchDataManager); };
diff --git a/content/browser/background_fetch/background_fetch_delegate_proxy.cc b/content/browser/background_fetch/background_fetch_delegate_proxy.cc index 5d963130..6383d5b 100644 --- a/content/browser/background_fetch/background_fetch_delegate_proxy.cc +++ b/content/browser/background_fetch/background_fetch_delegate_proxy.cc
@@ -29,9 +29,7 @@ public: Core(const base::WeakPtr<BackgroundFetchDelegateProxy>& io_parent, BrowserContext* browser_context) - : io_parent_(io_parent), - browser_context_(browser_context), - weak_ptr_factory_(this) { + : io_parent_(io_parent), browser_context_(browser_context) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(browser_context_); } @@ -216,7 +214,7 @@ BrowserContext* browser_context_; - base::WeakPtrFactory<Core> weak_ptr_factory_; + base::WeakPtrFactory<Core> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(Core); }; @@ -313,8 +311,7 @@ } BackgroundFetchDelegateProxy::BackgroundFetchDelegateProxy( - BrowserContext* browser_context) - : weak_ptr_factory_(this) { + BrowserContext* browser_context) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Normally it would be unsafe to obtain a weak pointer on the UI thread from
diff --git a/content/browser/background_fetch/background_fetch_delegate_proxy.h b/content/browser/background_fetch/background_fetch_delegate_proxy.h index 4b1ad84d..8fb029b 100644 --- a/content/browser/background_fetch/background_fetch_delegate_proxy.h +++ b/content/browser/background_fetch/background_fetch_delegate_proxy.h
@@ -174,7 +174,7 @@ update_ui_callback_map_; DispatchClickEventCallback click_event_dispatcher_callback_; - base::WeakPtrFactory<BackgroundFetchDelegateProxy> weak_ptr_factory_; + base::WeakPtrFactory<BackgroundFetchDelegateProxy> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundFetchDelegateProxy); };
diff --git a/content/browser/background_fetch/background_fetch_delegate_proxy_unittest.cc b/content/browser/background_fetch/background_fetch_delegate_proxy_unittest.cc index 7d3c650..2a7095f 100644 --- a/content/browser/background_fetch/background_fetch_delegate_proxy_unittest.cc +++ b/content/browser/background_fetch/background_fetch_delegate_proxy_unittest.cc
@@ -140,7 +140,7 @@ class FakeController : public BackgroundFetchDelegateProxy::Controller { public: - FakeController() : weak_ptr_factory_(this) {} + FakeController() {} void DidStartRequest( const std::string& guid, @@ -167,7 +167,7 @@ bool request_started_ = false; bool request_completed_ = false; - base::WeakPtrFactory<FakeController> weak_ptr_factory_; + base::WeakPtrFactory<FakeController> weak_ptr_factory_{this}; }; class BackgroundFetchDelegateProxyTest : public BackgroundFetchTestBase {
diff --git a/content/browser/background_fetch/background_fetch_job_controller.cc b/content/browser/background_fetch/background_fetch_job_controller.cc index a3e41e00..4f4e481a 100644 --- a/content/browser/background_fetch/background_fetch_job_controller.cc +++ b/content/browser/background_fetch/background_fetch_job_controller.cc
@@ -87,8 +87,7 @@ complete_requests_uploaded_bytes_cache_(bytes_uploaded), upload_total_(upload_total), progress_callback_(std::move(progress_callback)), - finished_callback_(std::move(finished_callback)), - weak_ptr_factory_(this) { + finished_callback_(std::move(finished_callback)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); }
diff --git a/content/browser/background_fetch/background_fetch_job_controller.h b/content/browser/background_fetch/background_fetch_job_controller.h index 200aa5f..a3700848 100644 --- a/content/browser/background_fetch/background_fetch_job_controller.h +++ b/content/browser/background_fetch/background_fetch_job_controller.h
@@ -212,7 +212,7 @@ // Custom callback that runs after the controller is finished. FinishedCallback finished_callback_; - base::WeakPtrFactory<BackgroundFetchJobController> weak_ptr_factory_; + base::WeakPtrFactory<BackgroundFetchJobController> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundFetchJobController); };
diff --git a/content/browser/background_fetch/background_fetch_registration_notifier.cc b/content/browser/background_fetch/background_fetch_registration_notifier.cc index bfa25c56..5608432 100644 --- a/content/browser/background_fetch/background_fetch_registration_notifier.cc +++ b/content/browser/background_fetch/background_fetch_registration_notifier.cc
@@ -12,8 +12,7 @@ namespace content { -BackgroundFetchRegistrationNotifier::BackgroundFetchRegistrationNotifier() - : weak_factory_(this) {} +BackgroundFetchRegistrationNotifier::BackgroundFetchRegistrationNotifier() {} BackgroundFetchRegistrationNotifier::~BackgroundFetchRegistrationNotifier() {}
diff --git a/content/browser/background_fetch/background_fetch_registration_notifier.h b/content/browser/background_fetch/background_fetch_registration_notifier.h index 73f7734..c974108 100644 --- a/content/browser/background_fetch/background_fetch_registration_notifier.h +++ b/content/browser/background_fetch/background_fetch_registration_notifier.h
@@ -79,7 +79,7 @@ // This is used for UMA recording. std::map<std::string, std::pair<int, int>> num_requests_and_updates_; - base::WeakPtrFactory<BackgroundFetchRegistrationNotifier> weak_factory_; + base::WeakPtrFactory<BackgroundFetchRegistrationNotifier> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundFetchRegistrationNotifier); };
diff --git a/content/browser/background_fetch/background_fetch_request_info.h b/content/browser/background_fetch/background_fetch_request_info.h index 70593c44..115c610 100644 --- a/content/browser/background_fetch/background_fetch_request_info.h +++ b/content/browser/background_fetch/background_fetch_request_info.h
@@ -21,6 +21,7 @@ #include "content/common/content_export.h" #include "content/common/service_worker/service_worker_types.h" #include "content/public/browser/background_fetch_response.h" +#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h" #include "url/gurl.h" namespace storage {
diff --git a/content/browser/background_fetch/background_fetch_request_match_params.h b/content/browser/background_fetch/background_fetch_request_match_params.h index e1b0def..26bcc64 100644 --- a/content/browser/background_fetch/background_fetch_request_match_params.h +++ b/content/browser/background_fetch/background_fetch_request_match_params.h
@@ -6,7 +6,7 @@ #define CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_REQUEST_MATCH_PARAMS_H_ #include "base/optional.h" -#include "content/common/service_worker/service_worker_types.h" +#include "content/common/content_export.h" #include "third_party/blink/public/mojom/cache_storage/cache_storage.mojom.h" namespace content {
diff --git a/content/browser/background_fetch/background_fetch_scheduler.cc b/content/browser/background_fetch/background_fetch_scheduler.cc index 539f145..a4a9ccc1 100644 --- a/content/browser/background_fetch/background_fetch_scheduler.cc +++ b/content/browser/background_fetch/background_fetch_scheduler.cc
@@ -71,8 +71,7 @@ devtools_context_(devtools_context), event_dispatcher_(background_fetch_context, std::move(service_worker_context), - devtools_context), - weak_ptr_factory_(this) { + devtools_context) { DCHECK(delegate_proxy_); DCHECK(devtools_context_); delegate_proxy_->SetClickEventDispatcher(
diff --git a/content/browser/background_fetch/background_fetch_scheduler.h b/content/browser/background_fetch/background_fetch_scheduler.h index 0159718c..f48e974 100644 --- a/content/browser/background_fetch/background_fetch_scheduler.h +++ b/content/browser/background_fetch/background_fetch_scheduler.h
@@ -186,7 +186,7 @@ int num_active_registrations_ = 0; int num_running_downloads_ = 0; - base::WeakPtrFactory<BackgroundFetchScheduler> weak_ptr_factory_; + base::WeakPtrFactory<BackgroundFetchScheduler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundFetchScheduler); };
diff --git a/content/browser/background_fetch/storage/cache_entry_handler_impl.cc b/content/browser/background_fetch/storage/cache_entry_handler_impl.cc index 5c87a76..c0ae740 100644 --- a/content/browser/background_fetch/storage/cache_entry_handler_impl.cc +++ b/content/browser/background_fetch/storage/cache_entry_handler_impl.cc
@@ -12,8 +12,7 @@ CacheEntryHandlerImpl::CacheEntryHandlerImpl( base::WeakPtr<storage::BlobStorageContext> blob_context) - : CacheStorageCacheEntryHandler(std::move(blob_context)), - weak_ptr_factory_(this) {} + : CacheStorageCacheEntryHandler(std::move(blob_context)) {} CacheEntryHandlerImpl::~CacheEntryHandlerImpl() = default;
diff --git a/content/browser/background_fetch/storage/cache_entry_handler_impl.h b/content/browser/background_fetch/storage/cache_entry_handler_impl.h index 73e2c65..d6326fe4 100644 --- a/content/browser/background_fetch/storage/cache_entry_handler_impl.h +++ b/content/browser/background_fetch/storage/cache_entry_handler_impl.h
@@ -32,7 +32,7 @@ private: base::WeakPtr<CacheStorageCacheEntryHandler> GetWeakPtr() override; - base::WeakPtrFactory<CacheEntryHandlerImpl> weak_ptr_factory_; + base::WeakPtrFactory<CacheEntryHandlerImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CacheEntryHandlerImpl); };
diff --git a/content/browser/background_fetch/storage/cleanup_task.cc b/content/browser/background_fetch/storage/cleanup_task.cc index 9175a70..5d0321f 100644 --- a/content/browser/background_fetch/storage/cleanup_task.cc +++ b/content/browser/background_fetch/storage/cleanup_task.cc
@@ -22,8 +22,7 @@ void EmptyErrorHandler(blink::mojom::BackgroundFetchError) {} } // namespace -CleanupTask::CleanupTask(DatabaseTaskHost* host) - : DatabaseTask(host), weak_factory_(this) {} +CleanupTask::CleanupTask(DatabaseTaskHost* host) : DatabaseTask(host) {} CleanupTask::~CleanupTask() = default;
diff --git a/content/browser/background_fetch/storage/cleanup_task.h b/content/browser/background_fetch/storage/cleanup_task.h index 520cbb6..37d5665c 100644 --- a/content/browser/background_fetch/storage/cleanup_task.h +++ b/content/browser/background_fetch/storage/cleanup_task.h
@@ -38,7 +38,7 @@ std::string HistogramName() const override; - base::WeakPtrFactory<CleanupTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<CleanupTask> weak_factory_{this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(CleanupTask); };
diff --git a/content/browser/background_fetch/storage/create_metadata_task.cc b/content/browser/background_fetch/storage/create_metadata_task.cc index cfbd087..d3dc274 100644 --- a/content/browser/background_fetch/storage/create_metadata_task.cc +++ b/content/browser/background_fetch/storage/create_metadata_task.cc
@@ -45,10 +45,7 @@ CanCreateRegistrationTask(DatabaseTaskHost* host, const url::Origin& origin, CanCreateRegistrationCallback callback) - : DatabaseTask(host), - origin_(origin), - callback_(std::move(callback)), - weak_factory_(this) {} + : DatabaseTask(host), origin_(origin), callback_(std::move(callback)) {} ~CanCreateRegistrationTask() override = default; @@ -122,8 +119,8 @@ // The number of existing registrations found for |origin_|. size_t num_active_registrations_ = 0u; - base::WeakPtrFactory<CanCreateRegistrationTask> - weak_factory_; // Keep as last. + base::WeakPtrFactory<CanCreateRegistrationTask> weak_factory_{ + this}; // Keep as last. }; } // namespace @@ -142,8 +139,7 @@ options_(std::move(options)), icon_(icon), start_paused_(start_paused), - callback_(std::move(callback)), - weak_factory_(this) {} + callback_(std::move(callback)) {} CreateMetadataTask::~CreateMetadataTask() = default;
diff --git a/content/browser/background_fetch/storage/create_metadata_task.h b/content/browser/background_fetch/storage/create_metadata_task.h index 572107b..bf70616 100644 --- a/content/browser/background_fetch/storage/create_metadata_task.h +++ b/content/browser/background_fetch/storage/create_metadata_task.h
@@ -80,7 +80,8 @@ std::string serialized_icon_; - base::WeakPtrFactory<CreateMetadataTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<CreateMetadataTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(CreateMetadataTask); };
diff --git a/content/browser/background_fetch/storage/database_task.cc b/content/browser/background_fetch/storage/database_task.cc index 69213ef..3f34d2b 100644 --- a/content/browser/background_fetch/storage/database_task.cc +++ b/content/browser/background_fetch/storage/database_task.cc
@@ -40,8 +40,7 @@ DatabaseTaskHost::~DatabaseTaskHost() = default; -DatabaseTask::DatabaseTask(DatabaseTaskHost* host) - : host_(host), weak_ptr_factory_(this) { +DatabaseTask::DatabaseTask(DatabaseTaskHost* host) : host_(host) { DCHECK(host_); // Hold a reference to the CacheStorageManager. cache_manager_ = data_manager()->cache_manager();
diff --git a/content/browser/background_fetch/storage/database_task.h b/content/browser/background_fetch/storage/database_task.h index 9109d89..b9aa561 100644 --- a/content/browser/background_fetch/storage/database_task.h +++ b/content/browser/background_fetch/storage/database_task.h
@@ -164,7 +164,7 @@ BackgroundFetchStorageError storage_error_ = BackgroundFetchStorageError::kNone; - base::WeakPtrFactory<DatabaseTask> weak_ptr_factory_; + base::WeakPtrFactory<DatabaseTask> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DatabaseTask); };
diff --git a/content/browser/background_fetch/storage/delete_registration_task.cc b/content/browser/background_fetch/storage/delete_registration_task.cc index 8700b4a..55869ae 100644 --- a/content/browser/background_fetch/storage/delete_registration_task.cc +++ b/content/browser/background_fetch/storage/delete_registration_task.cc
@@ -51,8 +51,7 @@ service_worker_registration_id_(service_worker_registration_id), origin_(origin), unique_id_(unique_id), - callback_(std::move(callback)), - weak_factory_(this) {} + callback_(std::move(callback)) {} DeleteRegistrationTask::~DeleteRegistrationTask() = default;
diff --git a/content/browser/background_fetch/storage/delete_registration_task.h b/content/browser/background_fetch/storage/delete_registration_task.h index 175377cf..199ee2a 100644 --- a/content/browser/background_fetch/storage/delete_registration_task.h +++ b/content/browser/background_fetch/storage/delete_registration_task.h
@@ -50,7 +50,8 @@ std::string unique_id_; HandleBackgroundFetchErrorCallback callback_; - base::WeakPtrFactory<DeleteRegistrationTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<DeleteRegistrationTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(DeleteRegistrationTask); };
diff --git a/content/browser/background_fetch/storage/get_developer_ids_task.cc b/content/browser/background_fetch/storage/get_developer_ids_task.cc index 84aa534..2044512 100644 --- a/content/browser/background_fetch/storage/get_developer_ids_task.cc +++ b/content/browser/background_fetch/storage/get_developer_ids_task.cc
@@ -21,8 +21,7 @@ : DatabaseTask(host), service_worker_registration_id_(service_worker_registration_id), origin_(origin), - callback_(std::move(callback)), - weak_factory_(this) {} + callback_(std::move(callback)) {} GetDeveloperIdsTask::~GetDeveloperIdsTask() = default;
diff --git a/content/browser/background_fetch/storage/get_developer_ids_task.h b/content/browser/background_fetch/storage/get_developer_ids_task.h index 0966fc3..eb5710c 100644 --- a/content/browser/background_fetch/storage/get_developer_ids_task.h +++ b/content/browser/background_fetch/storage/get_developer_ids_task.h
@@ -48,7 +48,8 @@ std::vector<std::string> developer_ids_; - base::WeakPtrFactory<GetDeveloperIdsTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<GetDeveloperIdsTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(GetDeveloperIdsTask); };
diff --git a/content/browser/background_fetch/storage/get_initialization_data_task.cc b/content/browser/background_fetch/storage/get_initialization_data_task.cc index 75977e7..8a7f963 100644 --- a/content/browser/background_fetch/storage/get_initialization_data_task.cc +++ b/content/browser/background_fetch/storage/get_initialization_data_task.cc
@@ -78,8 +78,7 @@ GetUIOptionsTask(DatabaseTaskHost* host, const SubTaskInit& sub_task_init, base::OnceClosure done_closure) - : InitializationSubTask(host, sub_task_init, std::move(done_closure)), - weak_factory_(this) {} + : InitializationSubTask(host, sub_task_init, std::move(done_closure)) {} ~GetUIOptionsTask() override = default; @@ -132,7 +131,7 @@ FinishWithError(blink::mojom::BackgroundFetchError::NONE); } - base::WeakPtrFactory<GetUIOptionsTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<GetUIOptionsTask> weak_factory_{this}; // Keep as last. }; // Gets the number of completed fetches, the number of active fetches, @@ -146,8 +145,7 @@ GetRequestsTask(DatabaseTaskHost* host, const SubTaskInit& sub_task_init, base::OnceClosure done_closure) - : InitializationSubTask(host, sub_task_init, std::move(done_closure)), - weak_factory_(this) {} + : InitializationSubTask(host, sub_task_init, std::move(done_closure)) {} ~GetRequestsTask() override = default; @@ -276,7 +274,7 @@ FinishWithError(blink::mojom::BackgroundFetchError::NONE); } - base::WeakPtrFactory<GetRequestsTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<GetRequestsTask> weak_factory_{this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(GetRequestsTask); }; @@ -288,8 +286,7 @@ FillFromMetadataTask(DatabaseTaskHost* host, const SubTaskInit& sub_task_init, base::OnceClosure done_closure) - : InitializationSubTask(host, sub_task_init, std::move(done_closure)), - weak_factory_(this) {} + : InitializationSubTask(host, sub_task_init, std::move(done_closure)) {} ~FillFromMetadataTask() override = default; @@ -375,7 +372,8 @@ FinishWithError(blink::mojom::BackgroundFetchError::NONE); } - base::WeakPtrFactory<FillFromMetadataTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<FillFromMetadataTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(FillFromMetadataTask); }; @@ -387,8 +385,7 @@ FillBackgroundFetchInitializationDataTask(DatabaseTaskHost* host, const SubTaskInit& sub_task_init, base::OnceClosure done_closure) - : InitializationSubTask(host, sub_task_init, std::move(done_closure)), - weak_factory_(this) {} + : InitializationSubTask(host, sub_task_init, std::move(done_closure)) {} ~FillBackgroundFetchInitializationDataTask() override = default; @@ -415,8 +412,8 @@ } private: - base::WeakPtrFactory<FillBackgroundFetchInitializationDataTask> - weak_factory_; // Keep as last. + base::WeakPtrFactory<FillBackgroundFetchInitializationDataTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(FillBackgroundFetchInitializationDataTask); }; @@ -435,7 +432,7 @@ GetInitializationDataTask::GetInitializationDataTask( DatabaseTaskHost* host, GetInitializationDataCallback callback) - : DatabaseTask(host), callback_(std::move(callback)), weak_factory_(this) {} + : DatabaseTask(host), callback_(std::move(callback)) {} GetInitializationDataTask::~GetInitializationDataTask() = default;
diff --git a/content/browser/background_fetch/storage/get_initialization_data_task.h b/content/browser/background_fetch/storage/get_initialization_data_task.h index b65eabd..7051337 100644 --- a/content/browser/background_fetch/storage/get_initialization_data_task.h +++ b/content/browser/background_fetch/storage/get_initialization_data_task.h
@@ -94,8 +94,8 @@ // Map from the unique_id to the initialization data. InitializationDataMap initialization_data_map_; - base::WeakPtrFactory<GetInitializationDataTask> - weak_factory_; // Keep as last. + base::WeakPtrFactory<GetInitializationDataTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(GetInitializationDataTask); };
diff --git a/content/browser/background_fetch/storage/get_metadata_task.cc b/content/browser/background_fetch/storage/get_metadata_task.cc index 334f135..d904b5a 100644 --- a/content/browser/background_fetch/storage/get_metadata_task.cc +++ b/content/browser/background_fetch/storage/get_metadata_task.cc
@@ -23,8 +23,7 @@ service_worker_registration_id_(service_worker_registration_id), origin_(origin), developer_id_(developer_id), - callback_(std::move(callback)), - weak_factory_(this) {} + callback_(std::move(callback)) {} GetMetadataTask::~GetMetadataTask() = default;
diff --git a/content/browser/background_fetch/storage/get_metadata_task.h b/content/browser/background_fetch/storage/get_metadata_task.h index 130e1a3..b18f253 100644 --- a/content/browser/background_fetch/storage/get_metadata_task.h +++ b/content/browser/background_fetch/storage/get_metadata_task.h
@@ -55,7 +55,7 @@ std::unique_ptr<proto::BackgroundFetchMetadata> metadata_proto_; - base::WeakPtrFactory<GetMetadataTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<GetMetadataTask> weak_factory_{this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(GetMetadataTask); };
diff --git a/content/browser/background_fetch/storage/get_registration_task.cc b/content/browser/background_fetch/storage/get_registration_task.cc index cc1e7a7..cceac07c 100644 --- a/content/browser/background_fetch/storage/get_registration_task.cc +++ b/content/browser/background_fetch/storage/get_registration_task.cc
@@ -20,8 +20,7 @@ service_worker_registration_id_(service_worker_registration_id), origin_(origin), developer_id_(developer_id), - callback_(std::move(callback)), - weak_factory_(this) {} + callback_(std::move(callback)) {} GetRegistrationTask::~GetRegistrationTask() = default;
diff --git a/content/browser/background_fetch/storage/get_registration_task.h b/content/browser/background_fetch/storage/get_registration_task.h index 229d0df4..b8b79ab 100644 --- a/content/browser/background_fetch/storage/get_registration_task.h +++ b/content/browser/background_fetch/storage/get_registration_task.h
@@ -54,7 +54,8 @@ std::unique_ptr<proto::BackgroundFetchMetadata> metadata_proto_; - base::WeakPtrFactory<GetRegistrationTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<GetRegistrationTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(GetRegistrationTask); };
diff --git a/content/browser/background_fetch/storage/get_request_blob_task.cc b/content/browser/background_fetch/storage/get_request_blob_task.cc index 18dafadf..d12246e 100644 --- a/content/browser/background_fetch/storage/get_request_blob_task.cc +++ b/content/browser/background_fetch/storage/get_request_blob_task.cc
@@ -21,8 +21,7 @@ : DatabaseTask(host), registration_id_(registration_id), request_info_(request_info), - callback_(std::move(callback)), - weak_factory_(this) {} + callback_(std::move(callback)) {} GetRequestBlobTask::~GetRequestBlobTask() = default;
diff --git a/content/browser/background_fetch/storage/get_request_blob_task.h b/content/browser/background_fetch/storage/get_request_blob_task.h index a11625e2..ee600220 100644 --- a/content/browser/background_fetch/storage/get_request_blob_task.h +++ b/content/browser/background_fetch/storage/get_request_blob_task.h
@@ -53,7 +53,8 @@ blink::mojom::SerializedBlobPtr blob_; - base::WeakPtrFactory<GetRequestBlobTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<GetRequestBlobTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(GetRequestBlobTask); };
diff --git a/content/browser/background_fetch/storage/mark_registration_for_deletion_task.cc b/content/browser/background_fetch/storage/mark_registration_for_deletion_task.cc index 0fc90a5..483b7a1 100644 --- a/content/browser/background_fetch/storage/mark_registration_for_deletion_task.cc +++ b/content/browser/background_fetch/storage/mark_registration_for_deletion_task.cc
@@ -23,8 +23,7 @@ : DatabaseTask(host), registration_id_(registration_id), check_for_failure_(check_for_failure), - callback_(std::move(callback)), - weak_factory_(this) {} + callback_(std::move(callback)) {} MarkRegistrationForDeletionTask::~MarkRegistrationForDeletionTask() = default;
diff --git a/content/browser/background_fetch/storage/mark_registration_for_deletion_task.h b/content/browser/background_fetch/storage/mark_registration_for_deletion_task.h index 5f340a1..6762e5b 100644 --- a/content/browser/background_fetch/storage/mark_registration_for_deletion_task.h +++ b/content/browser/background_fetch/storage/mark_registration_for_deletion_task.h
@@ -53,8 +53,8 @@ blink::mojom::BackgroundFetchFailureReason failure_reason_ = blink::mojom::BackgroundFetchFailureReason::NONE; - base::WeakPtrFactory<MarkRegistrationForDeletionTask> - weak_factory_; // Keep as last. + base::WeakPtrFactory<MarkRegistrationForDeletionTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(MarkRegistrationForDeletionTask); };
diff --git a/content/browser/background_fetch/storage/mark_request_complete_task.cc b/content/browser/background_fetch/storage/mark_request_complete_task.cc index 055e637..42f5434 100644 --- a/content/browser/background_fetch/storage/mark_request_complete_task.cc +++ b/content/browser/background_fetch/storage/mark_request_complete_task.cc
@@ -45,8 +45,7 @@ : DatabaseTask(host), registration_id_(registration_id), request_info_(std::move(request_info)), - callback_(std::move(callback)), - weak_factory_(this) {} + callback_(std::move(callback)) {} MarkRequestCompleteTask::~MarkRequestCompleteTask() = default;
diff --git a/content/browser/background_fetch/storage/mark_request_complete_task.h b/content/browser/background_fetch/storage/mark_request_complete_task.h index 9e03b2e..d5739f8 100644 --- a/content/browser/background_fetch/storage/mark_request_complete_task.h +++ b/content/browser/background_fetch/storage/mark_request_complete_task.h
@@ -81,7 +81,8 @@ proto::BackgroundFetchRegistration::BackgroundFetchFailureReason failure_reason_ = proto::BackgroundFetchRegistration::NONE; - base::WeakPtrFactory<MarkRequestCompleteTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<MarkRequestCompleteTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(MarkRequestCompleteTask); };
diff --git a/content/browser/background_fetch/storage/match_requests_task.cc b/content/browser/background_fetch/storage/match_requests_task.cc index 4d4617c..21114c10 100644 --- a/content/browser/background_fetch/storage/match_requests_task.cc +++ b/content/browser/background_fetch/storage/match_requests_task.cc
@@ -29,8 +29,7 @@ : DatabaseTask(host), registration_id_(registration_id), match_params_(std::move(match_params)), - callback_(std::move(callback)), - weak_factory_(this) {} + callback_(std::move(callback)) {} MatchRequestsTask::~MatchRequestsTask() = default;
diff --git a/content/browser/background_fetch/storage/match_requests_task.h b/content/browser/background_fetch/storage/match_requests_task.h index 61661035..4e45b618 100644 --- a/content/browser/background_fetch/storage/match_requests_task.h +++ b/content/browser/background_fetch/storage/match_requests_task.h
@@ -65,7 +65,7 @@ CacheStorageCacheHandle handle_; std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> settled_fetches_; - base::WeakPtrFactory<MatchRequestsTask> weak_factory_; // Keep as last. + base::WeakPtrFactory<MatchRequestsTask> weak_factory_{this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(MatchRequestsTask); };
diff --git a/content/browser/background_fetch/storage/start_next_pending_request_task.cc b/content/browser/background_fetch/storage/start_next_pending_request_task.cc index 33394639..69c8fcb 100644 --- a/content/browser/background_fetch/storage/start_next_pending_request_task.cc +++ b/content/browser/background_fetch/storage/start_next_pending_request_task.cc
@@ -19,8 +19,7 @@ NextRequestCallback callback) : DatabaseTask(host), registration_id_(registration_id), - callback_(std::move(callback)), - weak_factory_(this) { + callback_(std::move(callback)) { DCHECK(!registration_id_.is_null()); }
diff --git a/content/browser/background_fetch/storage/start_next_pending_request_task.h b/content/browser/background_fetch/storage/start_next_pending_request_task.h index e3925f43..5bd780a 100644 --- a/content/browser/background_fetch/storage/start_next_pending_request_task.h +++ b/content/browser/background_fetch/storage/start_next_pending_request_task.h
@@ -60,8 +60,8 @@ scoped_refptr<BackgroundFetchRequestInfo> next_request_; - base::WeakPtrFactory<StartNextPendingRequestTask> - weak_factory_; // Keep as last. + base::WeakPtrFactory<StartNextPendingRequestTask> weak_factory_{ + this}; // Keep as last. DISALLOW_COPY_AND_ASSIGN(StartNextPendingRequestTask); };
diff --git a/content/browser/background_sync/background_sync_manager.cc b/content/browser/background_sync/background_sync_manager.cc index 0dcae47..823d43a 100644 --- a/content/browser/background_sync/background_sync_manager.cc +++ b/content/browser/background_sync/background_sync_manager.cc
@@ -501,8 +501,7 @@ parameters_(std::make_unique<BackgroundSyncParameters>()), disabled_(false), num_firing_registrations_(0), - clock_(base::DefaultClock::GetInstance()), - weak_ptr_factory_(this) { + clock_(base::DefaultClock::GetInstance()) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(devtools_context_);
diff --git a/content/browser/background_sync/background_sync_manager.h b/content/browser/background_sync/background_sync_manager.h index 3f9d06d..c9beff4 100644 --- a/content/browser/background_sync/background_sync_manager.h +++ b/content/browser/background_sync/background_sync_manager.h
@@ -387,7 +387,7 @@ std::map<int64_t, int> emulated_offline_sw_; - base::WeakPtrFactory<BackgroundSyncManager> weak_ptr_factory_; + base::WeakPtrFactory<BackgroundSyncManager> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundSyncManager); };
diff --git a/content/browser/background_sync/background_sync_network_observer.cc b/content/browser/background_sync/background_sync_network_observer.cc index e155d23..00c7b463 100644 --- a/content/browser/background_sync/background_sync_network_observer.cc +++ b/content/browser/background_sync/background_sync_network_observer.cc
@@ -27,8 +27,7 @@ const base::RepeatingClosure& connection_changed_callback) : network_connection_tracker_(nullptr), connection_type_(network::mojom::ConnectionType::CONNECTION_UNKNOWN), - connection_changed_callback_(connection_changed_callback), - weak_ptr_factory_(this) { + connection_changed_callback_(connection_changed_callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(connection_changed_callback_);
diff --git a/content/browser/background_sync/background_sync_network_observer.h b/content/browser/background_sync/background_sync_network_observer.h index 8768cae..6652916 100644 --- a/content/browser/background_sync/background_sync_network_observer.h +++ b/content/browser/background_sync/background_sync_network_observer.h
@@ -66,7 +66,7 @@ // (to prevent flakes in tests). static bool ignore_network_changes_; - base::WeakPtrFactory<BackgroundSyncNetworkObserver> weak_ptr_factory_; + base::WeakPtrFactory<BackgroundSyncNetworkObserver> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundSyncNetworkObserver); };
diff --git a/content/browser/background_sync/background_sync_registration_helper.cc b/content/browser/background_sync/background_sync_registration_helper.cc index dd33f54..a8b2a42 100644 --- a/content/browser/background_sync/background_sync_registration_helper.cc +++ b/content/browser/background_sync/background_sync_registration_helper.cc
@@ -14,8 +14,7 @@ BackgroundSyncRegistrationHelper::BackgroundSyncRegistrationHelper( BackgroundSyncContextImpl* background_sync_context) - : background_sync_context_(background_sync_context), - weak_ptr_factory_(this) { + : background_sync_context_(background_sync_context) { DCHECK(background_sync_context_); }
diff --git a/content/browser/background_sync/background_sync_registration_helper.h b/content/browser/background_sync/background_sync_registration_helper.h index 34006c0..414e4aee 100644 --- a/content/browser/background_sync/background_sync_registration_helper.h +++ b/content/browser/background_sync/background_sync_registration_helper.h
@@ -53,7 +53,8 @@ private: // |background_sync_context_| (indirectly) owns |this|. BackgroundSyncContextImpl* const background_sync_context_; - base::WeakPtrFactory<BackgroundSyncRegistrationHelper> weak_ptr_factory_; + base::WeakPtrFactory<BackgroundSyncRegistrationHelper> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(BackgroundSyncRegistrationHelper); };
diff --git a/content/browser/background_sync/one_shot_background_sync_service_impl.cc b/content/browser/background_sync/one_shot_background_sync_service_impl.cc index 20e10480..8b2dfbd 100644 --- a/content/browser/background_sync/one_shot_background_sync_service_impl.cc +++ b/content/browser/background_sync/one_shot_background_sync_service_impl.cc
@@ -18,8 +18,7 @@ BackgroundSyncContextImpl* background_sync_context, mojo::InterfaceRequest<blink::mojom::OneShotBackgroundSyncService> request) : background_sync_context_(background_sync_context), - binding_(this, std::move(request)), - weak_ptr_factory_(this) { + binding_(this, std::move(request)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(background_sync_context_);
diff --git a/content/browser/background_sync/one_shot_background_sync_service_impl.h b/content/browser/background_sync/one_shot_background_sync_service_impl.h index 67ef7d1..b191b3c 100644 --- a/content/browser/background_sync/one_shot_background_sync_service_impl.h +++ b/content/browser/background_sync/one_shot_background_sync_service_impl.h
@@ -54,7 +54,7 @@ mojo::Binding<blink::mojom::OneShotBackgroundSyncService> binding_; base::WeakPtrFactory<blink::mojom::OneShotBackgroundSyncService> - weak_ptr_factory_; + weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(OneShotBackgroundSyncServiceImpl); };
diff --git a/content/browser/background_sync/periodic_background_sync_service_impl.cc b/content/browser/background_sync/periodic_background_sync_service_impl.cc index 628b672a..7c81bb5c 100644 --- a/content/browser/background_sync/periodic_background_sync_service_impl.cc +++ b/content/browser/background_sync/periodic_background_sync_service_impl.cc
@@ -16,8 +16,7 @@ BackgroundSyncContextImpl* background_sync_context, mojo::InterfaceRequest<blink::mojom::PeriodicBackgroundSyncService> request) : background_sync_context_(background_sync_context), - binding_(this, std::move(request)), - weak_ptr_factory_(this) { + binding_(this, std::move(request)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(background_sync_context_);
diff --git a/content/browser/background_sync/periodic_background_sync_service_impl.h b/content/browser/background_sync/periodic_background_sync_service_impl.h index d2d8b38..5ce59fa 100644 --- a/content/browser/background_sync/periodic_background_sync_service_impl.h +++ b/content/browser/background_sync/periodic_background_sync_service_impl.h
@@ -58,7 +58,8 @@ std::unique_ptr<BackgroundSyncRegistrationHelper> registration_helper_; mojo::Binding<blink::mojom::PeriodicBackgroundSyncService> binding_; - base::WeakPtrFactory<PeriodicBackgroundSyncServiceImpl> weak_ptr_factory_; + base::WeakPtrFactory<PeriodicBackgroundSyncServiceImpl> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(PeriodicBackgroundSyncServiceImpl); };
diff --git a/content/browser/bluetooth/bluetooth_device_chooser_controller.cc b/content/browser/bluetooth/bluetooth_device_chooser_controller.cc index ddbebfa..0dc035c 100644 --- a/content/browser/bluetooth/bluetooth_device_chooser_controller.cc +++ b/content/browser/bluetooth/bluetooth_device_chooser_controller.cc
@@ -237,8 +237,7 @@ base::Bind(&BluetoothDeviceChooserController::StopDeviceDiscovery, // base::Timer guarantees it won't call back after its // destructor starts. - base::Unretained(this))), - weak_ptr_factory_(this) { + base::Unretained(this))) { CHECK(adapter_); }
diff --git a/content/browser/bluetooth/bluetooth_device_chooser_controller.h b/content/browser/bluetooth/bluetooth_device_chooser_controller.h index 383477d9..b5f5c4c 100644 --- a/content/browser/bluetooth/bluetooth_device_chooser_controller.h +++ b/content/browser/bluetooth/bluetooth_device_chooser_controller.h
@@ -165,7 +165,8 @@ // than we do. // Note: This should remain the last member so it'll be destroyed and // invalidate its weak pointers before any other members are destroyed. - base::WeakPtrFactory<BluetoothDeviceChooserController> weak_ptr_factory_; + base::WeakPtrFactory<BluetoothDeviceChooserController> weak_ptr_factory_{ + this}; }; } // namespace content
diff --git a/content/browser/bluetooth/web_bluetooth_service_impl.cc b/content/browser/bluetooth/web_bluetooth_service_impl.cc index be704d8..72ffc0a 100644 --- a/content/browser/bluetooth/web_bluetooth_service_impl.cc +++ b/content/browser/bluetooth/web_bluetooth_service_impl.cc
@@ -229,8 +229,7 @@ : WebContentsObserver(WebContents::FromRenderFrameHost(render_frame_host)), connected_devices_(new FrameConnectedBluetoothDevices(render_frame_host)), render_frame_host_(render_frame_host), - binding_(this, std::move(request)), - weak_ptr_factory_(this) { + binding_(this, std::move(request)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); CHECK(web_contents()); }
diff --git a/content/browser/bluetooth/web_bluetooth_service_impl.h b/content/browser/bluetooth/web_bluetooth_service_impl.h index 5291874..450b4b1 100644 --- a/content/browser/bluetooth/web_bluetooth_service_impl.h +++ b/content/browser/bluetooth/web_bluetooth_service_impl.h
@@ -412,7 +412,7 @@ // the service on pipe connection errors. mojo::Binding<blink::mojom::WebBluetoothService> binding_; - base::WeakPtrFactory<WebBluetoothServiceImpl> weak_ptr_factory_; + base::WeakPtrFactory<WebBluetoothServiceImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WebBluetoothServiceImpl); };
diff --git a/content/browser/browser_child_process_host_impl.cc b/content/browser/browser_child_process_host_impl.cc index 347700f..26c2631 100644 --- a/content/browser/browser_child_process_host_impl.cc +++ b/content/browser/browser_child_process_host_impl.cc
@@ -160,8 +160,7 @@ delegate_(delegate), channel_(nullptr), is_channel_connected_(false), - notify_child_disconnected_(false), - weak_factory_(this) { + notify_child_disconnected_(false) { data_.id = ChildProcessHostImpl::GenerateChildProcessUniqueId(); child_process_host_ = ChildProcessHost::Create(this);
diff --git a/content/browser/browser_child_process_host_impl.h b/content/browser/browser_child_process_host_impl.h index 75a1015..4582047 100644 --- a/content/browser/browser_child_process_host_impl.h +++ b/content/browser/browser_child_process_host_impl.h
@@ -204,7 +204,7 @@ bool can_use_warm_up_connection_ = false; #endif - base::WeakPtrFactory<BrowserChildProcessHostImpl> weak_factory_; + base::WeakPtrFactory<BrowserChildProcessHostImpl> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/browser_plugin/browser_plugin_embedder.cc b/content/browser/browser_plugin/browser_plugin_embedder.cc index 792d471a..7fbcff29 100644 --- a/content/browser/browser_plugin/browser_plugin_embedder.cc +++ b/content/browser/browser_plugin/browser_plugin_embedder.cc
@@ -20,10 +20,7 @@ namespace content { BrowserPluginEmbedder::BrowserPluginEmbedder(WebContentsImpl* web_contents) - : WebContentsObserver(web_contents), - guest_drag_ending_(false), - weak_ptr_factory_(this) { -} + : WebContentsObserver(web_contents), guest_drag_ending_(false) {} BrowserPluginEmbedder::~BrowserPluginEmbedder() { }
diff --git a/content/browser/browser_plugin/browser_plugin_embedder.h b/content/browser/browser_plugin/browser_plugin_embedder.h index 326a9ac..55b8846f6 100644 --- a/content/browser/browser_plugin/browser_plugin_embedder.h +++ b/content/browser/browser_plugin/browser_plugin_embedder.h
@@ -120,7 +120,7 @@ // Keeps track of "dragend" state. bool guest_drag_ending_; - base::WeakPtrFactory<BrowserPluginEmbedder> weak_ptr_factory_; + base::WeakPtrFactory<BrowserPluginEmbedder> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BrowserPluginEmbedder); };
diff --git a/content/browser/browser_plugin/browser_plugin_guest.cc b/content/browser/browser_plugin/browser_plugin_guest.cc index 245ca7b..ddb17ac7 100644 --- a/content/browser/browser_plugin/browser_plugin_guest.cc +++ b/content/browser/browser_plugin/browser_plugin_guest.cc
@@ -132,8 +132,7 @@ seen_embedder_drag_source_ended_at_(false), ignore_dragged_url_(true), delegate_(delegate), - can_use_cross_process_frames_(delegate->CanUseCrossProcessFrames()), - weak_ptr_factory_(this) { + can_use_cross_process_frames_(delegate->CanUseCrossProcessFrames()) { DCHECK(web_contents); DCHECK(delegate); RecordAction(base::UserMetricsAction("BrowserPlugin.Guest.Create"));
diff --git a/content/browser/browser_plugin/browser_plugin_guest.h b/content/browser/browser_plugin/browser_plugin_guest.h index dbc5aa6..65db3e6 100644 --- a/content/browser/browser_plugin/browser_plugin_guest.h +++ b/content/browser/browser_plugin/browser_plugin_guest.h
@@ -471,7 +471,7 @@ // Weak pointer used to ask GeolocationPermissionContext about geolocation // permission. - base::WeakPtrFactory<BrowserPluginGuest> weak_ptr_factory_; + base::WeakPtrFactory<BrowserPluginGuest> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BrowserPluginGuest); };
diff --git a/content/browser/browsing_data/browsing_data_remover_impl.cc b/content/browser/browsing_data/browsing_data_remover_impl.cc index 32d2b5c..33c84c4 100644 --- a/content/browser/browsing_data/browsing_data_remover_impl.cc +++ b/content/browser/browsing_data/browsing_data_remover_impl.cc
@@ -111,8 +111,7 @@ remove_mask_(-1), origin_type_mask_(-1), is_removing_(false), - storage_partition_for_testing_(nullptr), - weak_ptr_factory_(this) { + storage_partition_for_testing_(nullptr) { DCHECK(browser_context_); }
diff --git a/content/browser/browsing_data/browsing_data_remover_impl.h b/content/browser/browsing_data/browsing_data_remover_impl.h index 261b2aee..8879c0f 100644 --- a/content/browser/browsing_data/browsing_data_remover_impl.h +++ b/content/browser/browsing_data/browsing_data_remover_impl.h
@@ -228,7 +228,7 @@ // We do not own this. StoragePartition* storage_partition_for_testing_; - base::WeakPtrFactory<BrowsingDataRemoverImpl> weak_ptr_factory_; + base::WeakPtrFactory<BrowsingDataRemoverImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BrowsingDataRemoverImpl); };
diff --git a/content/browser/browsing_data/clear_site_data_throttle.cc b/content/browser/browsing_data/clear_site_data_throttle.cc index 2ab93d4..1f468c8 100644 --- a/content/browser/browsing_data/clear_site_data_throttle.cc +++ b/content/browser/browsing_data/clear_site_data_throttle.cc
@@ -222,9 +222,7 @@ ClearSiteDataThrottle::ClearSiteDataThrottle( net::URLRequest* request, std::unique_ptr<ConsoleMessagesDelegate> delegate) - : request_(request), - delegate_(std::move(delegate)), - weak_ptr_factory_(this) { + : request_(request), delegate_(std::move(delegate)) { DCHECK(request_); DCHECK(delegate_); }
diff --git a/content/browser/browsing_data/clear_site_data_throttle.h b/content/browser/browsing_data/clear_site_data_throttle.h index 2238a69..fe74eff 100644 --- a/content/browser/browsing_data/clear_site_data_throttle.h +++ b/content/browser/browsing_data/clear_site_data_throttle.h
@@ -155,7 +155,7 @@ base::TimeTicks clearing_started_; // Needed for asynchronous parsing and deletion tasks. - base::WeakPtrFactory<ClearSiteDataThrottle> weak_ptr_factory_; + base::WeakPtrFactory<ClearSiteDataThrottle> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ClearSiteDataThrottle); };
diff --git a/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc b/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc index f8d230d..d8617e1 100644 --- a/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc +++ b/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc
@@ -24,8 +24,7 @@ : handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, base::SequencedTaskRunnerHandle::Get()), - client_binding_(this), - weak_ptr_factory_(this) {} + client_binding_(this) {} CacheStorageBlobToDiskCache::~CacheStorageBlobToDiskCache() = default;
diff --git a/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h b/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h index 89964d86..f008022 100644 --- a/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h +++ b/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h
@@ -71,7 +71,7 @@ uint64_t expected_total_size_ = 0; bool data_pipe_closed_ = false; - base::WeakPtrFactory<CacheStorageBlobToDiskCache> weak_ptr_factory_; + base::WeakPtrFactory<CacheStorageBlobToDiskCache> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CacheStorageBlobToDiskCache); };
diff --git a/content/browser/cache_storage/cache_storage_cache_entry_handler.cc b/content/browser/cache_storage/cache_storage_cache_entry_handler.cc index e7ad8f4..120a9325 100644 --- a/content/browser/cache_storage/cache_storage_cache_entry_handler.cc +++ b/content/browser/cache_storage/cache_storage_cache_entry_handler.cc
@@ -277,8 +277,7 @@ public: CacheStorageCacheEntryHandlerImpl( base::WeakPtr<storage::BlobStorageContext> blob_context) - : CacheStorageCacheEntryHandler(std::move(blob_context)), - weak_ptr_factory_(this) {} + : CacheStorageCacheEntryHandler(std::move(blob_context)) {} ~CacheStorageCacheEntryHandlerImpl() override = default; std::unique_ptr<PutContext> CreatePutContext( @@ -321,7 +320,8 @@ return weak_ptr_factory_.GetWeakPtr(); } - base::WeakPtrFactory<CacheStorageCacheEntryHandlerImpl> weak_ptr_factory_; + base::WeakPtrFactory<CacheStorageCacheEntryHandlerImpl> weak_ptr_factory_{ + this}; }; CacheStorageCacheEntryHandler::CacheStorageCacheEntryHandler(
diff --git a/content/browser/cache_storage/cache_storage_context_impl.cc b/content/browser/cache_storage/cache_storage_context_impl.cc index 52ef3da..6bfe06f8 100644 --- a/content/browser/cache_storage/cache_storage_context_impl.cc +++ b/content/browser/cache_storage/cache_storage_context_impl.cc
@@ -5,6 +5,7 @@ #include "content/browser/cache_storage/cache_storage_context_impl.h" #include "base/bind.h" +#include "base/feature_list.h" #include "base/files/file_path.h" #include "base/sequenced_task_runner.h" #include "base/task/post_task.h" @@ -24,10 +25,23 @@ namespace content { +namespace { + +const base::Feature kCacheStorageSequenceFeature{ + "CacheStorageSequence", base::FEATURE_DISABLED_BY_DEFAULT}; + +scoped_refptr<base::SequencedTaskRunner> CreateSchedulerTaskRunner() { + if (!base::FeatureList::IsEnabled(kCacheStorageSequenceFeature)) + return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}); + return base::CreateSequencedTaskRunnerWithTraits( + {base::TaskPriority::USER_VISIBLE}); +} + +} // namespace + CacheStorageContextImpl::CacheStorageContextImpl( BrowserContext* browser_context) - : task_runner_( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})), + : task_runner_(CreateSchedulerTaskRunner()), observers_(base::MakeRefCounted<ObserverList>()) { DCHECK_CURRENTLY_ON(BrowserThread::UI); }
diff --git a/content/browser/cache_storage/cache_storage_dispatcher_host.cc b/content/browser/cache_storage/cache_storage_dispatcher_host.cc index eb3a7cd..953d44bd 100644 --- a/content/browser/cache_storage/cache_storage_dispatcher_host.cc +++ b/content/browser/cache_storage/cache_storage_dispatcher_host.cc
@@ -356,7 +356,7 @@ : public blink::mojom::CacheStorage { public: CacheStorageImpl(CacheStorageDispatcherHost* owner, const url::Origin& origin) - : owner_(owner), origin_(origin), weak_factory_(this) { + : owner_(owner), origin_(origin) { // The CacheStorageHandle is empty to start and lazy initialized on first // use via GetOrCreateCacheStorage(). In the future we could eagerly create // the backend when the mojo connection is created. @@ -629,7 +629,7 @@ CacheStorageHandle cache_storage_handle_; SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<CacheStorageImpl> weak_factory_; + base::WeakPtrFactory<CacheStorageImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CacheStorageImpl); };
diff --git a/content/browser/cache_storage/cache_storage_operation.cc b/content/browser/cache_storage/cache_storage_operation.cc index 01bde84..d9084936 100644 --- a/content/browser/cache_storage/cache_storage_operation.cc +++ b/content/browser/cache_storage/cache_storage_operation.cc
@@ -21,8 +21,7 @@ creation_ticks_(base::TimeTicks::Now()), client_type_(client_type), op_type_(op_type), - task_runner_(std::move(task_runner)), - weak_ptr_factory_(this) {} + task_runner_(std::move(task_runner)) {} CacheStorageOperation::~CacheStorageOperation() { RecordCacheStorageSchedulerUMA(CacheStorageSchedulerUMA::kOperationDuration,
diff --git a/content/browser/cache_storage/cache_storage_operation.h b/content/browser/cache_storage/cache_storage_operation.h index cf101328..84a6663 100644 --- a/content/browser/cache_storage/cache_storage_operation.h +++ b/content/browser/cache_storage/cache_storage_operation.h
@@ -54,7 +54,7 @@ const CacheStorageSchedulerClient client_type_; const CacheStorageSchedulerOp op_type_; scoped_refptr<base::SequencedTaskRunner> task_runner_; - base::WeakPtrFactory<CacheStorageOperation> weak_ptr_factory_; + base::WeakPtrFactory<CacheStorageOperation> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CacheStorageOperation); };
diff --git a/content/browser/cache_storage/cache_storage_scheduler.cc b/content/browser/cache_storage/cache_storage_scheduler.cc index 0a0f31d..9ea8838d 100644 --- a/content/browser/cache_storage/cache_storage_scheduler.cc +++ b/content/browser/cache_storage/cache_storage_scheduler.cc
@@ -19,9 +19,7 @@ CacheStorageScheduler::CacheStorageScheduler( CacheStorageSchedulerClient client_type, scoped_refptr<base::SequencedTaskRunner> task_runner) - : task_runner_(std::move(task_runner)), - client_type_(client_type), - weak_ptr_factory_(this) {} + : task_runner_(std::move(task_runner)), client_type_(client_type) {} CacheStorageScheduler::~CacheStorageScheduler() {}
diff --git a/content/browser/cache_storage/cache_storage_scheduler.h b/content/browser/cache_storage/cache_storage_scheduler.h index 3f0fbf7..09bbb71f 100644 --- a/content/browser/cache_storage/cache_storage_scheduler.h +++ b/content/browser/cache_storage/cache_storage_scheduler.h
@@ -78,7 +78,7 @@ std::unique_ptr<CacheStorageOperation> running_operation_; const CacheStorageSchedulerClient client_type_; - base::WeakPtrFactory<CacheStorageScheduler> weak_ptr_factory_; + base::WeakPtrFactory<CacheStorageScheduler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CacheStorageScheduler); };
diff --git a/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage.cc b/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage.cc index 666521dd..936f726 100644 --- a/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage.cc +++ b/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage.cc
@@ -152,8 +152,10 @@ scoped_refptr<CacheStorageContextWithManager> context) : CacheStorage(origin), target_task_runner_(std::move(target_task_runner)), - inner_(target_task_runner_, origin, std::move(owner), std::move(context)), - weak_factory_(this) {} + inner_(target_task_runner_, + origin, + std::move(owner), + std::move(context)) {} CacheStorageHandle CrossSequenceCacheStorage::CreateHandle() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage.h b/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage.h index 1f7e7de..fc32d53 100644 --- a/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage.h +++ b/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage.h
@@ -81,7 +81,7 @@ int handle_ref_count_ = 0; SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<CrossSequenceCacheStorage> weak_factory_; + base::WeakPtrFactory<CrossSequenceCacheStorage> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CrossSequenceCacheStorage); };
diff --git a/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_cache.cc b/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_cache.cc index 75d3e9a..84ffbe5 100644 --- a/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_cache.cc +++ b/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_cache.cc
@@ -129,7 +129,7 @@ CrossSequenceCacheStorageCache::CrossSequenceCacheStorageCache( scoped_refptr<base::SequencedTaskRunner> target_task_runner) - : inner_(std::move(target_task_runner)), weak_factory_(this) {} + : inner_(std::move(target_task_runner)) {} void CrossSequenceCacheStorageCache::SetHandleOnTaskRunner( CacheStorageCacheHandle handle) {
diff --git a/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_cache.h b/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_cache.h index e7817cf..1b0c7a83 100644 --- a/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_cache.h +++ b/content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_cache.h
@@ -92,7 +92,7 @@ int handle_ref_count_ = 0; SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<CrossSequenceCacheStorageCache> weak_factory_; + base::WeakPtrFactory<CrossSequenceCacheStorageCache> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CrossSequenceCacheStorageCache); };
diff --git a/content/browser/cache_storage/legacy/legacy_cache_storage.cc b/content/browser/cache_storage/legacy/legacy_cache_storage.cc index b085b463..b30684d 100644 --- a/content/browser/cache_storage/legacy/legacy_cache_storage.cc +++ b/content/browser/cache_storage/legacy/legacy_cache_storage.cc
@@ -249,8 +249,7 @@ cache_storage, origin, owner), - origin_path_(origin_path), - weak_ptr_factory_(this) {} + origin_path_(origin_path) {} std::unique_ptr<LegacyCacheStorageCache> CreateCache( const std::string& cache_name, @@ -547,7 +546,7 @@ std::map<CacheStorageCache*, std::string> doomed_cache_to_path_; SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<SimpleCacheLoader> weak_ptr_factory_; + base::WeakPtrFactory<SimpleCacheLoader> weak_ptr_factory_{this}; }; LegacyCacheStorage::LegacyCacheStorage( @@ -571,8 +570,7 @@ cache_task_runner_(cache_task_runner), quota_manager_proxy_(quota_manager_proxy), owner_(owner), - cache_storage_manager_(cache_storage_manager), - weak_factory_(this) { + cache_storage_manager_(cache_storage_manager) { if (memory_only) cache_loader_.reset(new MemoryLoader( cache_task_runner_.get(), std::move(scheduler_task_runner),
diff --git a/content/browser/cache_storage/legacy/legacy_cache_storage.h b/content/browser/cache_storage/legacy/legacy_cache_storage.h index 09f3fa68..f0985a7 100644 --- a/content/browser/cache_storage/legacy/legacy_cache_storage.h +++ b/content/browser/cache_storage/legacy/legacy_cache_storage.h
@@ -303,7 +303,7 @@ size_t handle_ref_count_ = 0; SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<LegacyCacheStorage> weak_factory_; + base::WeakPtrFactory<LegacyCacheStorage> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LegacyCacheStorage); };
diff --git a/content/browser/cache_storage/legacy/legacy_cache_storage_cache.cc b/content/browser/cache_storage/legacy/legacy_cache_storage_cache.cc index 28ed4f3..03d198c0 100644 --- a/content/browser/cache_storage/legacy/legacy_cache_storage_cache.cc +++ b/content/browser/cache_storage/legacy/legacy_cache_storage_cache.cc
@@ -937,8 +937,7 @@ CacheStorageCacheEntryHandler::CreateCacheEntryHandler( owner, std::move(blob_context))), - memory_only_(path.empty()), - weak_ptr_factory_(this) { + memory_only_(path.empty()) { DCHECK(!origin_.opaque()); DCHECK(quota_manager_proxy_.get()); DCHECK(cache_padding_key_.get());
diff --git a/content/browser/cache_storage/legacy/legacy_cache_storage_cache.h b/content/browser/cache_storage/legacy/legacy_cache_storage_cache.h index d4175914..5d9ab7de 100644 --- a/content/browser/cache_storage/legacy/legacy_cache_storage_cache.h +++ b/content/browser/cache_storage/legacy/legacy_cache_storage_cache.h
@@ -540,7 +540,7 @@ base::OnceClosure post_backend_closed_callback_; SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<LegacyCacheStorageCache> weak_ptr_factory_; + base::WeakPtrFactory<LegacyCacheStorageCache> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LegacyCacheStorageCache); };
diff --git a/content/browser/child_process_launcher.cc b/content/browser/child_process_launcher.cc index 84da2e4..98ef88a 100644 --- a/content/browser/child_process_launcher.cc +++ b/content/browser/child_process_launcher.cc
@@ -43,11 +43,11 @@ #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \ defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \ defined(UNDEFINED_SANITIZER) || BUILDFLAG(CLANG_COVERAGE) - terminate_child_on_shutdown_(false), + terminate_child_on_shutdown_(false) #else - terminate_child_on_shutdown_(terminate_on_shutdown), + terminate_child_on_shutdown_(terminate_on_shutdown) #endif - weak_factory_(this) { +{ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); CHECK(BrowserThread::GetCurrentThreadIdentifier(&client_thread_id_));
diff --git a/content/browser/child_process_launcher.h b/content/browser/child_process_launcher.h index d90446a..79daec1 100644 --- a/content/browser/child_process_launcher.h +++ b/content/browser/child_process_launcher.h
@@ -244,7 +244,7 @@ SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<ChildProcessLauncher> weak_factory_; + base::WeakPtrFactory<ChildProcessLauncher> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ChildProcessLauncher); };
diff --git a/content/browser/code_cache/generated_code_cache.cc b/content/browser/code_cache/generated_code_cache.cc index f22bea51..082fd7be 100644 --- a/content/browser/code_cache/generated_code_cache.cc +++ b/content/browser/code_cache/generated_code_cache.cc
@@ -183,8 +183,7 @@ : backend_state_(kInitializing), path_(path), max_size_bytes_(max_size_bytes), - cache_type_(cache_type), - weak_ptr_factory_(this) { + cache_type_(cache_type) { CreateBackend(); }
diff --git a/content/browser/code_cache/generated_code_cache.h b/content/browser/code_cache/generated_code_cache.h index c9f4813..d87b9b6 100644 --- a/content/browser/code_cache/generated_code_cache.h +++ b/content/browser/code_cache/generated_code_cache.h
@@ -192,7 +192,7 @@ int max_size_bytes_; CodeCacheType cache_type_; - base::WeakPtrFactory<GeneratedCodeCache> weak_ptr_factory_; + base::WeakPtrFactory<GeneratedCodeCache> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(GeneratedCodeCache); };
diff --git a/content/browser/compositor/gpu_browser_compositor_output_surface.cc b/content/browser/compositor/gpu_browser_compositor_output_surface.cc index a25b060..a22be20 100644 --- a/content/browser/compositor/gpu_browser_compositor_output_surface.cc +++ b/content/browser/compositor/gpu_browser_compositor_output_surface.cc
@@ -25,8 +25,7 @@ GpuBrowserCompositorOutputSurface::GpuBrowserCompositorOutputSurface( scoped_refptr<viz::ContextProviderCommandBuffer> context) - : BrowserCompositorOutputSurface(std::move(context)), - weak_ptr_factory_(this) { + : BrowserCompositorOutputSurface(std::move(context)) { if (capabilities_.uses_default_gl_framebuffer) { capabilities_.flipped_output_surface = context_provider()->ContextCapabilities().flips_vertically;
diff --git a/content/browser/compositor/gpu_browser_compositor_output_surface.h b/content/browser/compositor/gpu_browser_compositor_output_surface.h index ab5ffc7..f9511d1 100644 --- a/content/browser/compositor/gpu_browser_compositor_output_surface.h +++ b/content/browser/compositor/gpu_browser_compositor_output_surface.h
@@ -83,7 +83,8 @@ ui::LatencyTracker latency_tracker_; private: - base::WeakPtrFactory<GpuBrowserCompositorOutputSurface> weak_ptr_factory_; + base::WeakPtrFactory<GpuBrowserCompositorOutputSurface> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(GpuBrowserCompositorOutputSurface); };
diff --git a/content/browser/compositor/gpu_process_transport_factory.cc b/content/browser/compositor/gpu_process_transport_factory.cc index 51499807..c9ec907 100644 --- a/content/browser/compositor/gpu_process_transport_factory.cc +++ b/content/browser/compositor/gpu_process_transport_factory.cc
@@ -180,8 +180,7 @@ viz::command_buffer_metrics::ContextType::BROWSER_WORKER), gpu_channel_factory_(gpu_channel_factory), compositing_mode_reporter_(compositing_mode_reporter), - server_shared_bitmap_manager_(server_shared_bitmap_manager), - callback_factory_(this) { + server_shared_bitmap_manager_(server_shared_bitmap_manager) { DCHECK(gpu_channel_factory_); base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
diff --git a/content/browser/compositor/gpu_process_transport_factory.h b/content/browser/compositor/gpu_process_transport_factory.h index f0322048..6937448 100644 --- a/content/browser/compositor/gpu_process_transport_factory.h +++ b/content/browser/compositor/gpu_process_transport_factory.h
@@ -167,7 +167,7 @@ // Manages a mapping of SharedBitmapId to shared memory objects. viz::ServerSharedBitmapManager* const server_shared_bitmap_manager_; - base::WeakPtrFactory<GpuProcessTransportFactory> callback_factory_; + base::WeakPtrFactory<GpuProcessTransportFactory> callback_factory_{this}; DISALLOW_COPY_AND_ASSIGN(GpuProcessTransportFactory); };
diff --git a/content/browser/compositor/offscreen_browser_compositor_output_surface.cc b/content/browser/compositor/offscreen_browser_compositor_output_surface.cc index 0eae968..000056d2 100644 --- a/content/browser/compositor/offscreen_browser_compositor_output_surface.cc +++ b/content/browser/compositor/offscreen_browser_compositor_output_surface.cc
@@ -32,8 +32,7 @@ OffscreenBrowserCompositorOutputSurface:: OffscreenBrowserCompositorOutputSurface( scoped_refptr<viz::ContextProviderCommandBuffer> context) - : BrowserCompositorOutputSurface(std::move(context)), - weak_ptr_factory_(this) { + : BrowserCompositorOutputSurface(std::move(context)) { capabilities_.uses_default_gl_framebuffer = false; }
diff --git a/content/browser/compositor/offscreen_browser_compositor_output_surface.h b/content/browser/compositor/offscreen_browser_compositor_output_surface.h index 4a96855d..c20f09b 100644 --- a/content/browser/compositor/offscreen_browser_compositor_output_surface.h +++ b/content/browser/compositor/offscreen_browser_compositor_output_surface.h
@@ -64,7 +64,7 @@ std::unique_ptr<ReflectorTexture> reflector_texture_; ui::LatencyTracker latency_tracker_; base::WeakPtrFactory<OffscreenBrowserCompositorOutputSurface> - weak_ptr_factory_; + weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(OffscreenBrowserCompositorOutputSurface); };
diff --git a/content/browser/compositor/owned_mailbox.cc b/content/browser/compositor/owned_mailbox.cc index 0969eca..b7cb536 100644 --- a/content/browser/compositor/owned_mailbox.cc +++ b/content/browser/compositor/owned_mailbox.cc
@@ -10,7 +10,7 @@ namespace content { OwnedMailbox::OwnedMailbox(gpu::gles2::GLES2Interface* gl) - : gl_(gl), texture_id_(0), weak_ptr_factory_(this) { + : gl_(gl), texture_id_(0) { DCHECK(gl_); // Create the texture.
diff --git a/content/browser/compositor/owned_mailbox.h b/content/browser/compositor/owned_mailbox.h index 084e28f..f73f258 100644 --- a/content/browser/compositor/owned_mailbox.h +++ b/content/browser/compositor/owned_mailbox.h
@@ -50,7 +50,7 @@ gpu::gles2::GLES2Interface* const gl_; uint32_t texture_id_; gpu::MailboxHolder mailbox_holder_; - base::WeakPtrFactory<OwnedMailbox> weak_ptr_factory_; + base::WeakPtrFactory<OwnedMailbox> weak_ptr_factory_{this}; }; } // namespace content
diff --git a/content/browser/compositor/software_browser_compositor_output_surface.cc b/content/browser/compositor/software_browser_compositor_output_surface.cc index 415d703..31b6c038 100644 --- a/content/browser/compositor/software_browser_compositor_output_surface.cc +++ b/content/browser/compositor/software_browser_compositor_output_surface.cc
@@ -22,8 +22,7 @@ SoftwareBrowserCompositorOutputSurface::SoftwareBrowserCompositorOutputSurface( std::unique_ptr<viz::SoftwareOutputDevice> software_device) - : BrowserCompositorOutputSurface(std::move(software_device)), - weak_factory_(this) {} + : BrowserCompositorOutputSurface(std::move(software_device)) {} SoftwareBrowserCompositorOutputSurface:: ~SoftwareBrowserCompositorOutputSurface() {
diff --git a/content/browser/compositor/software_browser_compositor_output_surface.h b/content/browser/compositor/software_browser_compositor_output_surface.h index d4550f6..45fed95 100644 --- a/content/browser/compositor/software_browser_compositor_output_surface.h +++ b/content/browser/compositor/software_browser_compositor_output_surface.h
@@ -59,7 +59,8 @@ bool needs_swap_size_notifications_ = false; #endif - base::WeakPtrFactory<SoftwareBrowserCompositorOutputSurface> weak_factory_; + base::WeakPtrFactory<SoftwareBrowserCompositorOutputSurface> weak_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(SoftwareBrowserCompositorOutputSurface); };
diff --git a/content/browser/compositor/viz_process_transport_factory.cc b/content/browser/compositor/viz_process_transport_factory.cc index ddccbc3d..803d06c 100644 --- a/content/browser/compositor/viz_process_transport_factory.cc +++ b/content/browser/compositor/viz_process_transport_factory.cc
@@ -124,8 +124,7 @@ context_factory_private_( kBrowserClientId, BrowserMainLoop::GetInstance()->host_frame_sink_manager(), - resize_task_runner), - weak_ptr_factory_(this) { + resize_task_runner) { DCHECK(gpu_channel_establish_factory_); task_graph_runner_->Start("CompositorTileWorker1", base::SimpleThread::Options());
diff --git a/content/browser/compositor/viz_process_transport_factory.h b/content/browser/compositor/viz_process_transport_factory.h index 1b96114..28770e8 100644 --- a/content/browser/compositor/viz_process_transport_factory.h +++ b/content/browser/compositor/viz_process_transport_factory.h
@@ -134,7 +134,7 @@ std::unique_ptr<viz::VizCompositorThreadRunner> viz_compositor_thread_; ui::HostContextFactoryPrivate context_factory_private_; - base::WeakPtrFactory<VizProcessTransportFactory> weak_ptr_factory_; + base::WeakPtrFactory<VizProcessTransportFactory> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VizProcessTransportFactory); };
diff --git a/content/browser/content_index/content_index_context.cc b/content/browser/content_index/content_index_context.cc index 5ac9c74..44410d0 100644 --- a/content/browser/content_index/content_index_context.cc +++ b/content/browser/content_index/content_index_context.cc
@@ -5,6 +5,7 @@ #include "content/browser/content_index/content_index_context.h" #include "base/task/post_task.h" +#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" namespace content { @@ -13,24 +14,22 @@ BrowserContext* browser_context, scoped_refptr<ServiceWorkerContextWrapper> service_worker_context) : content_index_database_(browser_context, - std::move(service_worker_context)) { + std::move(service_worker_context)), + should_initialize_(browser_context->GetContentIndexProvider()) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } void ContentIndexContext::InitializeOnIOThread() { DCHECK_CURRENTLY_ON(BrowserThread::IO); + + if (!should_initialize_) + return; + content_index_database_.InitializeProviderWithEntries(); } void ContentIndexContext::Shutdown() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&ContentIndexContext::ShutdownOnIO, this)); -} - -void ContentIndexContext::ShutdownOnIO() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); content_index_database_.Shutdown(); }
diff --git a/content/browser/content_index/content_index_context.h b/content/browser/content_index/content_index_context.h index 8c9b873..840430a 100644 --- a/content/browser/content_index/content_index_context.h +++ b/content/browser/content_index/content_index_context.h
@@ -36,11 +36,13 @@ BrowserThread::DeleteOnIOThread>; friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>; - void ShutdownOnIO(); ~ContentIndexContext(); ContentIndexDatabase content_index_database_; + // Whether initialization DB tasks should run on start-up. + bool should_initialize_ = false; + DISALLOW_COPY_AND_ASSIGN(ContentIndexContext); };
diff --git a/content/browser/content_index/content_index_database.cc b/content/browser/content_index/content_index_database.cc index 3f73bbde..1c30465 100644 --- a/content/browser/content_index/content_index_database.cc +++ b/content/browser/content_index/content_index_database.cc
@@ -6,10 +6,12 @@ #include <string> +#include "base/task/post_task.h" #include "base/time/time.h" #include "content/browser/background_fetch/storage/image_helpers.h" #include "content/browser/content_index/content_index.pb.h" #include "content/public/browser/browser_context.h" +#include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "url/origin.h" @@ -81,7 +83,8 @@ scoped_refptr<ServiceWorkerContextWrapper> service_worker_context) : provider_(browser_context->GetContentIndexProvider()), service_worker_context_(std::move(service_worker_context)), - weak_ptr_factory_(this) {} + weak_ptr_factory_io_(this), + weak_ptr_factory_ui_(this) {} ContentIndexDatabase::~ContentIndexDatabase() = default; @@ -93,7 +96,7 @@ blink::mojom::ContentIndexService::AddCallback callback) { SerializeIcon(icon, base::BindOnce(&ContentIndexDatabase::DidSerializeIcon, - weak_ptr_factory_.GetWeakPtr(), + weak_ptr_factory_io_.GetWeakPtr(), service_worker_registration_id, origin, std::move(description), std::move(callback))); } @@ -119,7 +122,7 @@ {{std::move(entry_key), std::move(entry_value)}, {std::move(icon_key), std::move(serialized_icon)}}, base::BindOnce(&ContentIndexDatabase::DidAddEntry, - weak_ptr_factory_.GetWeakPtr(), std::move(callback), + weak_ptr_factory_io_.GetWeakPtr(), std::move(callback), std::move(entry))); } @@ -134,8 +137,12 @@ std::move(callback).Run(blink::mojom::ContentIndexError::NONE); - if (provider_) - provider_->OnContentAdded(std::move(entry), weak_ptr_factory_.GetWeakPtr()); + std::vector<ContentIndexEntry> entries; + entries.push_back(std::move(entry)); + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ContentIndexDatabase::NotifyProviderContentAdded, + weak_ptr_factory_ui_.GetWeakPtr(), std::move(entries))); } void ContentIndexDatabase::DeleteEntry( @@ -144,9 +151,10 @@ blink::mojom::ContentIndexService::DeleteCallback callback) { service_worker_context_->ClearRegistrationUserData( service_worker_registration_id, {EntryKey(entry_id), IconKey(entry_id)}, - base::BindOnce( - &ContentIndexDatabase::DidDeleteEntry, weak_ptr_factory_.GetWeakPtr(), - service_worker_registration_id, entry_id, std::move(callback))); + base::BindOnce(&ContentIndexDatabase::DidDeleteEntry, + weak_ptr_factory_io_.GetWeakPtr(), + service_worker_registration_id, entry_id, + std::move(callback))); } void ContentIndexDatabase::DidDeleteEntry( @@ -160,8 +168,12 @@ } std::move(callback).Run(blink::mojom::ContentIndexError::NONE); - if (provider_) - provider_->OnContentDeleted(service_worker_registration_id, entry_id); + + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ContentIndexDatabase::NotifyProviderContentDeleted, + weak_ptr_factory_ui_.GetWeakPtr(), + service_worker_registration_id, entry_id)); } void ContentIndexDatabase::GetDescriptions( @@ -170,7 +182,7 @@ service_worker_context_->GetRegistrationUserDataByKeyPrefix( service_worker_registration_id, kEntryPrefix, base::BindOnce(&ContentIndexDatabase::DidGetDescriptions, - weak_ptr_factory_.GetWeakPtr(), std::move(callback))); + weak_ptr_factory_io_.GetWeakPtr(), std::move(callback))); } void ContentIndexDatabase::DidGetDescriptions( @@ -214,12 +226,9 @@ } void ContentIndexDatabase::InitializeProviderWithEntries() { - if (!provider_) - return; - service_worker_context_->GetUserDataForAllRegistrationsByKeyPrefix( kEntryPrefix, base::BindOnce(&ContentIndexDatabase::DidGetAllEntries, - weak_ptr_factory_.GetWeakPtr())); + weak_ptr_factory_io_.GetWeakPtr())); } void ContentIndexDatabase::DidGetAllEntries( @@ -230,7 +239,7 @@ return; } - if (!provider_ || user_data.empty()) + if (user_data.empty()) return; std::vector<ContentIndexEntry> entries; @@ -252,18 +261,37 @@ registration_time); } - for (auto& entry : entries) - provider_->OnContentAdded(std::move(entry), weak_ptr_factory_.GetWeakPtr()); + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ContentIndexDatabase::NotifyProviderContentAdded, + weak_ptr_factory_ui_.GetWeakPtr(), std::move(entries))); } void ContentIndexDatabase::GetIcon( int64_t service_worker_registration_id, const std::string& description_id, base::OnceCallback<void(SkBitmap)> icon_callback) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&ContentIndexDatabase::GetIconOnIO, + weak_ptr_factory_io_.GetWeakPtr(), + service_worker_registration_id, description_id, + std::move(icon_callback))); +} + +void ContentIndexDatabase::GetIconOnIO( + int64_t service_worker_registration_id, + const std::string& description_id, + base::OnceCallback<void(SkBitmap)> icon_callback) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + service_worker_context_->GetRegistrationUserData( service_worker_registration_id, {IconKey(description_id)}, base::BindOnce(&ContentIndexDatabase::DidGetSerializedIcon, - weak_ptr_factory_.GetWeakPtr(), std::move(icon_callback))); + weak_ptr_factory_io_.GetWeakPtr(), + std::move(icon_callback))); } void ContentIndexDatabase::DidGetSerializedIcon( @@ -277,14 +305,40 @@ DCHECK_EQ(data.size(), 1u); - DeserializeIcon(std::make_unique<std::string>(data[0]), - std::move(icon_callback)); + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&DeserializeIcon, std::make_unique<std::string>(data[0]), + std::move(icon_callback))); } void ContentIndexDatabase::Shutdown() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CURRENTLY_ON(BrowserThread::UI); provider_ = nullptr; } +void ContentIndexDatabase::NotifyProviderContentAdded( + std::vector<ContentIndexEntry> entries) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + if (!provider_) + return; + + for (auto& entry : entries) { + provider_->OnContentAdded(std::move(entry), + weak_ptr_factory_ui_.GetWeakPtr()); + } +} + +void ContentIndexDatabase::NotifyProviderContentDeleted( + int64_t service_worker_registration_id, + const std::string& entry_id) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + if (!provider_) + return; + + provider_->OnContentDeleted(service_worker_registration_id, entry_id); +} + } // namespace content
diff --git a/content/browser/content_index/content_index_database.h b/content/browser/content_index/content_index_database.h index debb8fa..c76d2e0 100644 --- a/content/browser/content_index/content_index_database.h +++ b/content/browser/content_index/content_index_database.h
@@ -75,13 +75,24 @@ void DidGetAllEntries( const std::vector<std::pair<int64_t, std::string>>& user_data, blink::ServiceWorkerStatusCode status); + void GetIconOnIO(int64_t service_worker_registration_id, + const std::string& description_id, + base::OnceCallback<void(SkBitmap)> icon_callback); void DidGetSerializedIcon(base::OnceCallback<void(SkBitmap)> icon_callback, const std::vector<std::string>& data, blink::ServiceWorkerStatusCode status); + // Callbacks on the UI thread to notify |provider_| of updates. + void NotifyProviderContentAdded(std::vector<ContentIndexEntry> entries); + void NotifyProviderContentDeleted(int64_t service_worker_registration_id, + const std::string& entry_id); + + // Lives on the UI thread. ContentIndexProvider* provider_; + scoped_refptr<ServiceWorkerContextWrapper> service_worker_context_; - base::WeakPtrFactory<ContentIndexDatabase> weak_ptr_factory_; + base::WeakPtrFactory<ContentIndexDatabase> weak_ptr_factory_io_; + base::WeakPtrFactory<ContentIndexDatabase> weak_ptr_factory_ui_; DISALLOW_COPY_AND_ASSIGN(ContentIndexDatabase); };
diff --git a/content/browser/content_index/content_index_database_unittest.cc b/content/browser/content_index/content_index_database_unittest.cc index e0c58f17..62a8431 100644 --- a/content/browser/content_index/content_index_database_unittest.cc +++ b/content/browser/content_index/content_index_database_unittest.cc
@@ -303,6 +303,10 @@ })); EXPECT_EQ(AddEntry(CreateDescription("id")), blink::mojom::ContentIndexError::NONE); + + // Wait for the provider to receive the OnContentAdded event. + thread_bundle().RunUntilIdle(); + ASSERT_TRUE(out_entry); ASSERT_TRUE(out_entry->description); EXPECT_EQ(out_entry->service_worker_registration_id, @@ -316,6 +320,7 @@ EXPECT_CALL(*provider(), OnContentDeleted(service_worker_registration_id(), "id")); EXPECT_EQ(DeleteEntry("id"), blink::mojom::ContentIndexError::NONE); + thread_bundle().RunUntilIdle(); } } @@ -334,6 +339,7 @@ blink::mojom::ContentIndexError::NONE); EXPECT_EQ(AddEntry(CreateDescription("id2")), blink::mojom::ContentIndexError::NONE); + thread_bundle().RunUntilIdle(); } // Simulate initialization.
diff --git a/content/browser/cookie_store/cookie_store_manager.cc b/content/browser/cookie_store/cookie_store_manager.cc index 9dc3ac79..1533891 100644 --- a/content/browser/cookie_store/cookie_store_manager.cc +++ b/content/browser/cookie_store/cookie_store_manager.cc
@@ -46,8 +46,7 @@ scoped_refptr<ServiceWorkerContextWrapper> service_worker_context) : service_worker_context_(std::move(service_worker_context)), cookie_change_listener_binding_(this), - registration_user_data_key_(kSubscriptionsUserKey), - weak_factory_(this) { + registration_user_data_key_(kSubscriptionsUserKey) { service_worker_context_->AddObserver(this); }
diff --git a/content/browser/cookie_store/cookie_store_manager.h b/content/browser/cookie_store/cookie_store_manager.h index ce506e74..36cf78f 100644 --- a/content/browser/cookie_store/cookie_store_manager.h +++ b/content/browser/cookie_store/cookie_store_manager.h
@@ -218,7 +218,7 @@ SEQUENCE_CHECKER(sequence_checker_); // Supports having the manager destroyed while waiting for disk I/O. - base::WeakPtrFactory<CookieStoreManager> weak_factory_; + base::WeakPtrFactory<CookieStoreManager> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CookieStoreManager); };
diff --git a/content/browser/devtools/devtools_http_handler.cc b/content/browser/devtools/devtools_http_handler.cc index 30b2a43..83772ae8 100644 --- a/content/browser/devtools/devtools_http_handler.cc +++ b/content/browser/devtools/devtools_http_handler.cc
@@ -784,7 +784,7 @@ std::unique_ptr<DevToolsSocketFactory> socket_factory, const base::FilePath& output_directory, const base::FilePath& debug_frontend_dir) - : delegate_(delegate), weak_factory_(this) { + : delegate_(delegate) { browser_guid_ = delegate_->IsBrowserTargetDiscoverable() ? kBrowserUrlPrefix : base::StringPrintf("%s/%s", kBrowserUrlPrefix,
diff --git a/content/browser/devtools/devtools_http_handler.h b/content/browser/devtools/devtools_http_handler.h index 68260a28..590c226c 100644 --- a/content/browser/devtools/devtools_http_handler.h +++ b/content/browser/devtools/devtools_http_handler.h
@@ -115,7 +115,7 @@ ConnectionToClientMap connection_to_client_; DevToolsManagerDelegate* delegate_; std::unique_ptr<DevToolsSocketFactory> socket_factory_; - base::WeakPtrFactory<DevToolsHttpHandler> weak_factory_; + base::WeakPtrFactory<DevToolsHttpHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DevToolsHttpHandler); };
diff --git a/content/browser/devtools/devtools_interceptor_controller.cc b/content/browser/devtools/devtools_interceptor_controller.cc index e23bb9c1..db271624 100644 --- a/content/browser/devtools/devtools_interceptor_controller.cc +++ b/content/browser/devtools/devtools_interceptor_controller.cc
@@ -100,9 +100,7 @@ base::WeakPtr<DevToolsNetworkInterceptor> interceptor, std::unique_ptr<DevToolsTargetRegistry> target_registry, BrowserContext* browser_context) - : interceptor_(interceptor), - target_registry_(std::move(target_registry)), - weak_factory_(this) { + : interceptor_(interceptor), target_registry_(std::move(target_registry)) { browser_context->SetUserData( kDevToolsInterceptorController, std::unique_ptr<DevToolsInterceptorController>(this));
diff --git a/content/browser/devtools/devtools_interceptor_controller.h b/content/browser/devtools/devtools_interceptor_controller.h index eca3620..5911017 100644 --- a/content/browser/devtools/devtools_interceptor_controller.h +++ b/content/browser/devtools/devtools_interceptor_controller.h
@@ -70,7 +70,7 @@ std::unique_ptr<DevToolsTargetRegistry> target_registry_; base::flat_map<std::string, GlobalRequestID> navigation_requests_; base::flat_set<GlobalRequestID> canceled_navigation_requests_; - base::WeakPtrFactory<DevToolsInterceptorController> weak_factory_; + base::WeakPtrFactory<DevToolsInterceptorController> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DevToolsInterceptorController); };
diff --git a/content/browser/devtools/devtools_pipe_handler.cc b/content/browser/devtools/devtools_pipe_handler.cc index c03af15..d03bacc 100644 --- a/content/browser/devtools/devtools_pipe_handler.cc +++ b/content/browser/devtools/devtools_pipe_handler.cc
@@ -245,7 +245,7 @@ // DevToolsPipeHandler --------------------------------------------------- DevToolsPipeHandler::DevToolsPipeHandler() - : read_fd_(kReadFD), write_fd_(kWriteFD), weak_factory_(this) { + : read_fd_(kReadFD), write_fd_(kWriteFD) { read_thread_.reset(new base::Thread(kDevToolsPipeHandlerReadThreadName)); base::Thread::Options options; options.message_loop_type = base::MessageLoop::TYPE_IO;
diff --git a/content/browser/devtools/devtools_pipe_handler.h b/content/browser/devtools/devtools_pipe_handler.h index 61738bc..8c9c0c08 100644 --- a/content/browser/devtools/devtools_pipe_handler.h +++ b/content/browser/devtools/devtools_pipe_handler.h
@@ -50,7 +50,7 @@ int read_fd_; int write_fd_; bool shutting_down_ = false; - base::WeakPtrFactory<DevToolsPipeHandler> weak_factory_; + base::WeakPtrFactory<DevToolsPipeHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DevToolsPipeHandler); };
diff --git a/content/browser/devtools/devtools_renderer_channel.cc b/content/browser/devtools/devtools_renderer_channel.cc index 97951ee4..1f00194 100644 --- a/content/browser/devtools/devtools_renderer_channel.cc +++ b/content/browser/devtools/devtools_renderer_channel.cc
@@ -21,8 +21,7 @@ : owner_(owner), binding_(this), associated_binding_(this), - process_id_(ChildProcessHost::kInvalidUniqueID), - weak_factory_(this) {} + process_id_(ChildProcessHost::kInvalidUniqueID) {} DevToolsRendererChannel::~DevToolsRendererChannel() = default;
diff --git a/content/browser/devtools/devtools_renderer_channel.h b/content/browser/devtools/devtools_renderer_channel.h index 1818a06..a27e63e3 100644 --- a/content/browser/devtools/devtools_renderer_channel.h +++ b/content/browser/devtools/devtools_renderer_channel.h
@@ -89,7 +89,7 @@ base::flat_set<protocol::TargetAutoAttacher*> wait_for_debugger_attachers_; base::flat_set<WorkerDevToolsAgentHost*> child_workers_; base::OnceClosure set_report_callback_; - base::WeakPtrFactory<DevToolsRendererChannel> weak_factory_; + base::WeakPtrFactory<DevToolsRendererChannel> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DevToolsRendererChannel); };
diff --git a/content/browser/devtools/devtools_session.cc b/content/browser/devtools/devtools_session.cc index 1c47409..65c5b1e 100644 --- a/content/browser/devtools/devtools_session.cc +++ b/content/browser/devtools/devtools_session.cc
@@ -46,8 +46,7 @@ DevToolsSession::DevToolsSession(DevToolsAgentHostClient* client) : binding_(this), client_(client), - dispatcher_(new protocol::UberDispatcher(this)), - weak_factory_(this) {} + dispatcher_(new protocol::UberDispatcher(this)) {} DevToolsSession::~DevToolsSession() { if (proxy_delegate_)
diff --git a/content/browser/devtools/devtools_session.h b/content/browser/devtools/devtools_session.h index 413d757..1a90add0 100644 --- a/content/browser/devtools/devtools_session.h +++ b/content/browser/devtools/devtools_session.h
@@ -139,7 +139,7 @@ base::OnceClosure runtime_resume_; DevToolsExternalAgentProxyDelegate* proxy_delegate_ = nullptr; - base::WeakPtrFactory<DevToolsSession> weak_factory_; + base::WeakPtrFactory<DevToolsSession> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/devtools/devtools_target_registry.cc b/content/browser/devtools/devtools_target_registry.cc index f9fea65..01032ddf 100644 --- a/content/browser/devtools/devtools_target_registry.cc +++ b/content/browser/devtools/devtools_target_registry.cc
@@ -107,7 +107,7 @@ Add(std::move(new_info)); } - Impl() : weak_factory_(this) { DETACH_FROM_THREAD(thread_checker_); } + Impl() { DETACH_FROM_THREAD(thread_checker_); } ~Impl() override = default; private: @@ -118,7 +118,7 @@ base::flat_map<int, const TargetInfo*> target_info_by_ftn_id_; THREAD_CHECKER(thread_checker_); - base::WeakPtrFactory<DevToolsTargetRegistry::Impl> weak_factory_; + base::WeakPtrFactory<DevToolsTargetRegistry::Impl> weak_factory_{this}; }; class DevToolsTargetRegistry::ContentsObserver : public ObserverBase,
diff --git a/content/browser/devtools/devtools_url_interceptor_request_job.cc b/content/browser/devtools/devtools_url_interceptor_request_job.cc index 59c1e5c1..1c0e734 100644 --- a/content/browser/devtools/devtools_url_interceptor_request_job.cc +++ b/content/browser/devtools/devtools_url_interceptor_request_job.cc
@@ -565,8 +565,7 @@ devtools_token_(devtools_token), callback_(callback), resource_type_(resource_type), - stage_to_intercept_(stage_to_intercept), - weak_ptr_factory_(this) { + stage_to_intercept_(stage_to_intercept) { DCHECK_CURRENTLY_ON(BrowserThread::IO); }
diff --git a/content/browser/devtools/devtools_url_interceptor_request_job.h b/content/browser/devtools/devtools_url_interceptor_request_job.h index 08d163f..af6135c 100644 --- a/content/browser/devtools/devtools_url_interceptor_request_job.h +++ b/content/browser/devtools/devtools_url_interceptor_request_job.h
@@ -168,7 +168,8 @@ net::RequestHeadersCallback request_headers_callback_; net::ResponseHeadersCallback response_headers_callback_; - base::WeakPtrFactory<DevToolsURLInterceptorRequestJob> weak_ptr_factory_; + base::WeakPtrFactory<DevToolsURLInterceptorRequestJob> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(DevToolsURLInterceptorRequestJob); };
diff --git a/content/browser/devtools/devtools_url_request_interceptor.cc b/content/browser/devtools/devtools_url_request_interceptor.cc index 2118d74a..f5531d495 100644 --- a/content/browser/devtools/devtools_url_request_interceptor.cc +++ b/content/browser/devtools/devtools_url_request_interceptor.cc
@@ -45,7 +45,7 @@ DevToolsURLRequestInterceptor::DevToolsURLRequestInterceptor( BrowserContext* browser_context) - : next_id_(0), weak_factory_(this) { + : next_id_(0) { DCHECK_CURRENTLY_ON(BrowserThread::UI); auto target_registry = std::make_unique<DevToolsTargetRegistry>( base::CreateSingleThreadTaskRunnerWithTraits(
diff --git a/content/browser/devtools/devtools_url_request_interceptor.h b/content/browser/devtools/devtools_url_request_interceptor.h index e40d6d14..f855d85 100644 --- a/content/browser/devtools/devtools_url_request_interceptor.h +++ b/content/browser/devtools/devtools_url_request_interceptor.h
@@ -106,7 +106,7 @@ size_t next_id_; - base::WeakPtrFactory<DevToolsURLRequestInterceptor> weak_factory_; + base::WeakPtrFactory<DevToolsURLRequestInterceptor> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DevToolsURLRequestInterceptor); };
diff --git a/content/browser/devtools/devtools_video_consumer_unittest.cc b/content/browser/devtools/devtools_video_consumer_unittest.cc index 91403b1..801eea2 100644 --- a/content/browser/devtools/devtools_video_consumer_unittest.cc +++ b/content/browser/devtools/devtools_video_consumer_unittest.cc
@@ -145,7 +145,7 @@ MOCK_METHOD1(OnFrameFromVideoConsumerMock, void(scoped_refptr<media::VideoFrame> frame)); - MockDevToolsVideoFrameReceiver() : weak_factory_(this) {} + MockDevToolsVideoFrameReceiver() {} scoped_refptr<media::VideoFrame> TakeFrameAt(int i) { return std::move(frames_[i]); @@ -164,12 +164,12 @@ private: std::vector<scoped_refptr<media::VideoFrame>> frames_; - base::WeakPtrFactory<MockDevToolsVideoFrameReceiver> weak_factory_; + base::WeakPtrFactory<MockDevToolsVideoFrameReceiver> weak_factory_{this}; }; class DevToolsVideoConsumerTest : public testing::Test { public: - DevToolsVideoConsumerTest() : weak_factory_(this) {} + DevToolsVideoConsumerTest() {} void SetUp() override { consumer_ = receiver_.CreateDevToolsVideoConsumer(); @@ -234,7 +234,7 @@ } base::test::ScopedTaskEnvironment task_environment_; - base::WeakPtrFactory<DevToolsVideoConsumerTest> weak_factory_; + base::WeakPtrFactory<DevToolsVideoConsumerTest> weak_factory_{this}; }; // Tests that the OnFrameFromVideoConsumer callbacks is called when
diff --git a/content/browser/devtools/protocol/background_service_handler.cc b/content/browser/devtools/protocol/background_service_handler.cc index ae1bd79a..eca7132 100644 --- a/content/browser/devtools/protocol/background_service_handler.cc +++ b/content/browser/devtools/protocol/background_service_handler.cc
@@ -91,8 +91,7 @@ BackgroundServiceHandler::BackgroundServiceHandler() : DevToolsDomainHandler(BackgroundService::Metainfo::domainName), - devtools_context_(nullptr), - weak_ptr_factory_(this) {} + devtools_context_(nullptr) {} BackgroundServiceHandler::~BackgroundServiceHandler() { DCHECK(enabled_services_.empty());
diff --git a/content/browser/devtools/protocol/background_service_handler.h b/content/browser/devtools/protocol/background_service_handler.h index 5bd4a70..1c5d1df7 100644 --- a/content/browser/devtools/protocol/background_service_handler.h +++ b/content/browser/devtools/protocol/background_service_handler.h
@@ -63,7 +63,7 @@ base::flat_set<devtools::proto::BackgroundService> enabled_services_; - base::WeakPtrFactory<BackgroundServiceHandler> weak_ptr_factory_; + base::WeakPtrFactory<BackgroundServiceHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundServiceHandler); };
diff --git a/content/browser/devtools/protocol/fetch_handler.cc b/content/browser/devtools/protocol/fetch_handler.cc index 0f69893..806e0f89 100644 --- a/content/browser/devtools/protocol/fetch_handler.cc +++ b/content/browser/devtools/protocol/fetch_handler.cc
@@ -35,8 +35,7 @@ : DevToolsDomainHandler(Fetch::Metainfo::domainName), io_context_(io_context), update_loader_factories_callback_( - std::move(update_loader_factories_callback)), - weak_factory_(this) {} + std::move(update_loader_factories_callback)) {} FetchHandler::~FetchHandler() = default;
diff --git a/content/browser/devtools/protocol/fetch_handler.h b/content/browser/devtools/protocol/fetch_handler.h index fc8d0433..2126503 100644 --- a/content/browser/devtools/protocol/fetch_handler.h +++ b/content/browser/devtools/protocol/fetch_handler.h
@@ -91,7 +91,7 @@ std::unique_ptr<Fetch::Frontend> frontend_; std::unique_ptr<DevToolsURLLoaderInterceptor> interceptor_; UpdateLoaderFactoriesCallback update_loader_factories_callback_; - base::WeakPtrFactory<FetchHandler> weak_factory_; + base::WeakPtrFactory<FetchHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FetchHandler); };
diff --git a/content/browser/devtools/protocol/input_handler.cc b/content/browser/devtools/protocol/input_handler.cc index 5f1e02d8..34c79c8 100644 --- a/content/browser/devtools/protocol/input_handler.cc +++ b/content/browser/devtools/protocol/input_handler.cc
@@ -477,8 +477,7 @@ : DevToolsDomainHandler(Input::Metainfo::domainName), host_(nullptr), page_scale_factor_(1.0), - last_id_(0), - weak_factory_(this) {} + last_id_(0) {} InputHandler::~InputHandler() { }
diff --git a/content/browser/devtools/protocol/input_handler.h b/content/browser/devtools/protocol/input_handler.h index daac09a..bf1d117 100644 --- a/content/browser/devtools/protocol/input_handler.h +++ b/content/browser/devtools/protocol/input_handler.h
@@ -192,7 +192,7 @@ std::set<int> pointer_ids_; std::unique_ptr<SyntheticPointerDriver> synthetic_pointer_driver_; base::flat_map<int, blink::WebTouchPoint> touch_points_; - base::WeakPtrFactory<InputHandler> weak_factory_; + base::WeakPtrFactory<InputHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(InputHandler); };
diff --git a/content/browser/devtools/protocol/io_handler.cc b/content/browser/devtools/protocol/io_handler.cc index 57c61cd0..88be9a29 100644 --- a/content/browser/devtools/protocol/io_handler.cc +++ b/content/browser/devtools/protocol/io_handler.cc
@@ -27,8 +27,7 @@ : DevToolsDomainHandler(IO::Metainfo::domainName), io_context_(io_context), browser_context_(nullptr), - storage_partition_(nullptr), - weak_factory_(this) {} + storage_partition_(nullptr) {} IOHandler::~IOHandler() {}
diff --git a/content/browser/devtools/protocol/io_handler.h b/content/browser/devtools/protocol/io_handler.h index 7a25cae..e47c4f1 100644 --- a/content/browser/devtools/protocol/io_handler.h +++ b/content/browser/devtools/protocol/io_handler.h
@@ -45,7 +45,7 @@ DevToolsIOContext* io_context_; BrowserContext* browser_context_; StoragePartition* storage_partition_; - base::WeakPtrFactory<IOHandler> weak_factory_; + base::WeakPtrFactory<IOHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(IOHandler); };
diff --git a/content/browser/devtools/protocol/memory_handler.cc b/content/browser/devtools/protocol/memory_handler.cc index e54548c3..6fb7a8c7 100644 --- a/content/browser/devtools/protocol/memory_handler.cc +++ b/content/browser/devtools/protocol/memory_handler.cc
@@ -20,8 +20,7 @@ MemoryHandler::MemoryHandler() : DevToolsDomainHandler(Memory::Metainfo::domainName), - process_host_id_(ChildProcessHost::kInvalidUniqueID), - weak_factory_(this) {} + process_host_id_(ChildProcessHost::kInvalidUniqueID) {} MemoryHandler::~MemoryHandler() {}
diff --git a/content/browser/devtools/protocol/memory_handler.h b/content/browser/devtools/protocol/memory_handler.h index 21fa2b9..0c933e5b 100644 --- a/content/browser/devtools/protocol/memory_handler.h +++ b/content/browser/devtools/protocol/memory_handler.h
@@ -38,7 +38,7 @@ int process_host_id_; blink::mojom::LeakDetectorPtr leak_detector_; std::unique_ptr<PrepareForLeakDetectionCallback> leak_detection_callback_; - base::WeakPtrFactory<MemoryHandler> weak_factory_; + base::WeakPtrFactory<MemoryHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MemoryHandler); };
diff --git a/content/browser/devtools/protocol/network_handler.cc b/content/browser/devtools/protocol/network_handler.cc index 9a5a0ea..3e5e145 100644 --- a/content/browser/devtools/protocol/network_handler.cc +++ b/content/browser/devtools/protocol/network_handler.cc
@@ -917,8 +917,7 @@ bypass_service_worker_(false), cache_disabled_(false), update_loader_factories_callback_( - std::move(update_loader_factories_callback)), - weak_factory_(this) { + std::move(update_loader_factories_callback)) { DCHECK(io_context_); static bool have_configured_service_worker_context = false; if (have_configured_service_worker_context)
diff --git a/content/browser/devtools/protocol/network_handler.h b/content/browser/devtools/protocol/network_handler.h index 4f9e936..b7c1f8f 100644 --- a/content/browser/devtools/protocol/network_handler.h +++ b/content/browser/devtools/protocol/network_handler.h
@@ -234,7 +234,7 @@ bool cache_disabled_; std::unique_ptr<BackgroundSyncRestorer> background_sync_restorer_; base::RepeatingClosure update_loader_factories_callback_; - base::WeakPtrFactory<NetworkHandler> weak_factory_; + base::WeakPtrFactory<NetworkHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(NetworkHandler); };
diff --git a/content/browser/devtools/protocol/page_handler.cc b/content/browser/devtools/protocol/page_handler.cc index f000418..c5705ca 100644 --- a/content/browser/devtools/protocol/page_handler.cc +++ b/content/browser/devtools/protocol/page_handler.cc
@@ -206,8 +206,7 @@ active_file_chooser_interceptor_(active_file_chooser_interceptor), allow_set_download_behavior_(allow_set_download_behavior), allow_file_access_(allow_file_access), - observer_(this), - weak_factory_(this) { + observer_(this) { bool create_video_consumer = true; #ifdef OS_ANDROID // Video capture doesn't work on Android WebView. Use CopyFromSurface instead.
diff --git a/content/browser/devtools/protocol/page_handler.h b/content/browser/devtools/protocol/page_handler.h index e86d824..ebfa0c391 100644 --- a/content/browser/devtools/protocol/page_handler.h +++ b/content/browser/devtools/protocol/page_handler.h
@@ -247,7 +247,7 @@ std::unique_ptr<blink::mojom::FileChooserParams> file_chooser_params_; base::Optional<std::pair<int, int>> file_chooser_rfh_id_; - base::WeakPtrFactory<PageHandler> weak_factory_; + base::WeakPtrFactory<PageHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PageHandler); };
diff --git a/content/browser/devtools/protocol/service_worker_handler.cc b/content/browser/devtools/protocol/service_worker_handler.cc index 593c377..a6a66e5 100644 --- a/content/browser/devtools/protocol/service_worker_handler.cc +++ b/content/browser/devtools/protocol/service_worker_handler.cc
@@ -153,8 +153,7 @@ : DevToolsDomainHandler(ServiceWorker::Metainfo::domainName), enabled_(false), browser_context_(nullptr), - storage_partition_(nullptr), - weak_factory_(this) {} + storage_partition_(nullptr) {} ServiceWorkerHandler::~ServiceWorkerHandler() { }
diff --git a/content/browser/devtools/protocol/service_worker_handler.h b/content/browser/devtools/protocol/service_worker_handler.h index 13f2533..ed154407 100644 --- a/content/browser/devtools/protocol/service_worker_handler.h +++ b/content/browser/devtools/protocol/service_worker_handler.h
@@ -77,7 +77,7 @@ BrowserContext* browser_context_; StoragePartitionImpl* storage_partition_; - base::WeakPtrFactory<ServiceWorkerHandler> weak_factory_; + base::WeakPtrFactory<ServiceWorkerHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerHandler); };
diff --git a/content/browser/devtools/protocol/storage_handler.cc b/content/browser/devtools/protocol/storage_handler.cc index 03c26a86..40421045 100644 --- a/content/browser/devtools/protocol/storage_handler.cc +++ b/content/browser/devtools/protocol/storage_handler.cc
@@ -233,8 +233,7 @@ StorageHandler::StorageHandler() : DevToolsDomainHandler(Storage::Metainfo::domainName), - storage_partition_(nullptr), - weak_ptr_factory_(this) {} + storage_partition_(nullptr) {} StorageHandler::~StorageHandler() { DCHECK(!cache_storage_observer_);
diff --git a/content/browser/devtools/protocol/storage_handler.h b/content/browser/devtools/protocol/storage_handler.h index d9df1114..037d4f16 100644 --- a/content/browser/devtools/protocol/storage_handler.h +++ b/content/browser/devtools/protocol/storage_handler.h
@@ -70,7 +70,7 @@ std::unique_ptr<CacheStorageObserver> cache_storage_observer_; std::unique_ptr<IndexedDBObserver> indexed_db_observer_; - base::WeakPtrFactory<StorageHandler> weak_ptr_factory_; + base::WeakPtrFactory<StorageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(StorageHandler); };
diff --git a/content/browser/devtools/protocol/system_info_handler.cc b/content/browser/devtools/protocol/system_info_handler.cc index db89e209..11fdeabe 100644 --- a/content/browser/devtools/protocol/system_info_handler.cc +++ b/content/browser/devtools/protocol/system_info_handler.cc
@@ -258,8 +258,7 @@ public: explicit SystemInfoHandlerGpuObserver( std::unique_ptr<GetInfoCallback> callback) - : callback_(std::move(callback)), - weak_factory_(this) { + : callback_(std::move(callback)) { base::PostDelayedTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&SystemInfoHandlerGpuObserver::ObserverWatchdogCallback, @@ -301,7 +300,7 @@ private: std::unique_ptr<GetInfoCallback> callback_; - base::WeakPtrFactory<SystemInfoHandlerGpuObserver> weak_factory_; + base::WeakPtrFactory<SystemInfoHandlerGpuObserver> weak_factory_{this}; }; SystemInfoHandler::SystemInfoHandler()
diff --git a/content/browser/devtools/protocol/target_handler.cc b/content/browser/devtools/protocol/target_handler.cc index 310015b..693edd13 100644 --- a/content/browser/devtools/protocol/target_handler.cc +++ b/content/browser/devtools/protocol/target_handler.cc
@@ -450,8 +450,7 @@ discover_(false), access_mode_(access_mode), owner_target_id_(owner_target_id), - root_session_(root_session), - weak_factory_(this) {} + root_session_(root_session) {} TargetHandler::~TargetHandler() { }
diff --git a/content/browser/devtools/protocol/target_handler.h b/content/browser/devtools/protocol/target_handler.h index 3be9739..26361d3 100644 --- a/content/browser/devtools/protocol/target_handler.h +++ b/content/browser/devtools/protocol/target_handler.h
@@ -137,7 +137,7 @@ std::string owner_target_id_; DevToolsSession* root_session_; base::flat_set<Throttle*> throttles_; - base::WeakPtrFactory<TargetHandler> weak_factory_; + base::WeakPtrFactory<TargetHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TargetHandler); };
diff --git a/content/browser/devtools/protocol/tethering_handler.cc b/content/browser/devtools/protocol/tethering_handler.cc index 497174f..6d265507 100644 --- a/content/browser/devtools/protocol/tethering_handler.cc +++ b/content/browser/devtools/protocol/tethering_handler.cc
@@ -349,9 +349,7 @@ : DevToolsDomainHandler(Tethering::Metainfo::domainName), socket_callback_(socket_callback), task_runner_(task_runner), - is_active_(false), - weak_factory_(this) { -} + is_active_(false) {} TetheringHandler::~TetheringHandler() { if (is_active_) {
diff --git a/content/browser/devtools/protocol/tethering_handler.h b/content/browser/devtools/protocol/tethering_handler.h index 2c7fe31..b0a83d7 100644 --- a/content/browser/devtools/protocol/tethering_handler.h +++ b/content/browser/devtools/protocol/tethering_handler.h
@@ -49,7 +49,7 @@ CreateServerSocketCallback socket_callback_; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; bool is_active_; - base::WeakPtrFactory<TetheringHandler> weak_factory_; + base::WeakPtrFactory<TetheringHandler> weak_factory_{this}; static TetheringImpl* impl_;
diff --git a/content/browser/devtools/protocol/tracing_handler.cc b/content/browser/devtools/protocol/tracing_handler.cc index 8349a1fc..e3245ee6 100644 --- a/content/browser/devtools/protocol/tracing_handler.cc +++ b/content/browser/devtools/protocol/tracing_handler.cc
@@ -565,8 +565,7 @@ did_initiate_recording_(false), return_as_stream_(false), gzip_compression_(false), - buffer_usage_reporting_interval_(0), - weak_factory_(this) { + buffer_usage_reporting_interval_(0) { bool use_video_capture_api = true; #ifdef OS_ANDROID // Video capture API cannot be used on Android WebView.
diff --git a/content/browser/devtools/protocol/tracing_handler.h b/content/browser/devtools/protocol/tracing_handler.h index 49836ca7b..34ebb5dc 100644 --- a/content/browser/devtools/protocol/tracing_handler.h +++ b/content/browser/devtools/protocol/tracing_handler.h
@@ -144,7 +144,7 @@ int number_of_screenshots_from_video_consumer_ = 0; base::trace_event::TraceConfig trace_config_; std::unique_ptr<TracingSession> session_; - base::WeakPtrFactory<TracingHandler> weak_factory_; + base::WeakPtrFactory<TracingHandler> weak_factory_{this}; FRIEND_TEST_ALL_PREFIXES(TracingHandlerTest, GetTraceConfigFromDevToolsConfig);
diff --git a/content/browser/dom_storage/local_storage_context_mojo.cc b/content/browser/dom_storage/local_storage_context_mojo.cc index 5067dec..00c0b11 100644 --- a/content/browser/dom_storage/local_storage_context_mojo.cc +++ b/content/browser/dom_storage/local_storage_context_mojo.cc
@@ -386,8 +386,7 @@ reinterpret_cast<uintptr_t>(this))), task_runner_(std::move(legacy_task_runner)), old_localstorage_path_(old_localstorage_path), - is_low_end_device_(base::SysInfo::IsLowEndDevice()), - weak_ptr_factory_(this) { + is_low_end_device_(base::SysInfo::IsLowEndDevice()) { base::trace_event::MemoryDumpManager::GetInstance() ->RegisterDumpProviderWithSequencedTaskRunner( this, "LocalStorage", task_runner, MemoryDumpProvider::Options());
diff --git a/content/browser/dom_storage/local_storage_context_mojo.h b/content/browser/dom_storage/local_storage_context_mojo.h index db50fab..84634b3b 100644 --- a/content/browser/dom_storage/local_storage_context_mojo.h +++ b/content/browser/dom_storage/local_storage_context_mojo.h
@@ -193,7 +193,7 @@ // Name of an extra histogram to log open results to, if not null. const char* open_result_histogram_ = nullptr; - base::WeakPtrFactory<LocalStorageContextMojo> weak_ptr_factory_; + base::WeakPtrFactory<LocalStorageContextMojo> weak_ptr_factory_{this}; }; } // namespace content
diff --git a/content/browser/dom_storage/session_storage_context_mojo.cc b/content/browser/dom_storage/session_storage_context_mojo.cc index 45a6655..4a65e35 100644 --- a/content/browser/dom_storage/session_storage_context_mojo.cc +++ b/content/browser/dom_storage/session_storage_context_mojo.cc
@@ -109,8 +109,7 @@ leveldb_name_(std::move(leveldb_name)), memory_dump_id_(base::StringPrintf("SessionStorage/0x%" PRIXPTR, reinterpret_cast<uintptr_t>(this))), - is_low_end_device_(base::SysInfo::IsLowEndDevice()), - weak_ptr_factory_(this) { + is_low_end_device_(base::SysInfo::IsLowEndDevice()) { DCHECK(base::FeatureList::IsEnabled(blink::features::kOnionSoupDOMStorage)); base::trace_event::MemoryDumpManager::GetInstance() ->RegisterDumpProviderWithSequencedTaskRunner(
diff --git a/content/browser/dom_storage/session_storage_context_mojo.h b/content/browser/dom_storage/session_storage_context_mojo.h index e1ebd6bf..de839b0e 100644 --- a/content/browser/dom_storage/session_storage_context_mojo.h +++ b/content/browser/dom_storage/session_storage_context_mojo.h
@@ -273,7 +273,7 @@ // Name of an extra histogram to log open results to, if not null. const char* open_result_histogram_ = nullptr; - base::WeakPtrFactory<SessionStorageContextMojo> weak_ptr_factory_; + base::WeakPtrFactory<SessionStorageContextMojo> weak_ptr_factory_{this}; }; } // namespace content
diff --git a/content/browser/dom_storage/storage_area_impl.cc b/content/browser/dom_storage/storage_area_impl.cc index fd55c52..c5a28778 100644 --- a/content/browser/dom_storage/storage_area_impl.cc +++ b/content/browser/dom_storage/storage_area_impl.cc
@@ -82,8 +82,7 @@ data_rate_limiter_(options.max_bytes_per_hour, base::TimeDelta::FromHours(1)), commit_rate_limiter_(options.max_commits_per_hour, - base::TimeDelta::FromHours(1)), - weak_ptr_factory_(this) { + base::TimeDelta::FromHours(1)) { bindings_.set_connection_error_handler(base::BindRepeating( &StorageAreaImpl::OnConnectionError, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/content/browser/dom_storage/storage_area_impl.h b/content/browser/dom_storage/storage_area_impl.h index b9ba5c7..f44ef67 100644 --- a/content/browser/dom_storage/storage_area_impl.h +++ b/content/browser/dom_storage/storage_area_impl.h
@@ -344,7 +344,7 @@ bool has_committed_data_ = false; std::unique_ptr<CommitBatch> commit_batch_; - base::WeakPtrFactory<StorageAreaImpl> weak_ptr_factory_; + base::WeakPtrFactory<StorageAreaImpl> weak_ptr_factory_{this}; static bool s_aggressive_flushing_enabled_;
diff --git a/content/browser/download/download_browsertest.cc b/content/browser/download/download_browsertest.cc index fdb2aa7..ac8a1a6 100644 --- a/content/browser/download/download_browsertest.cc +++ b/content/browser/download/download_browsertest.cc
@@ -241,7 +241,7 @@ private: std::vector<base::Closure> rename_callbacks_; base::OnceClosure stop_waiting_; - base::WeakPtrFactory<DownloadFileWithDelayFactory> weak_ptr_factory_; + base::WeakPtrFactory<DownloadFileWithDelayFactory> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DownloadFileWithDelayFactory); }; @@ -297,8 +297,7 @@ factory->AddRenameCallback(base::Bind(original_callback, reason, path)); } -DownloadFileWithDelayFactory::DownloadFileWithDelayFactory() - : weak_ptr_factory_(this) {} +DownloadFileWithDelayFactory::DownloadFileWithDelayFactory() {} DownloadFileWithDelayFactory::~DownloadFileWithDelayFactory() {} @@ -454,8 +453,7 @@ // on this class must be called on the UI thread. class ErrorInjectionDownloadFileFactory : public download::DownloadFileFactory { public: - ErrorInjectionDownloadFileFactory() - : download_file_(nullptr), weak_ptr_factory_(this) {} + ErrorInjectionDownloadFileFactory() : download_file_(nullptr) {} ~ErrorInjectionDownloadFileFactory() override = default; // DownloadFileFactory interface. @@ -504,7 +502,8 @@ ErrorInjectionDownloadFile* download_file_; int64_t injected_error_offset_ = -1; int64_t injected_error_length_ = 0; - base::WeakPtrFactory<ErrorInjectionDownloadFileFactory> weak_ptr_factory_; + base::WeakPtrFactory<ErrorInjectionDownloadFileFactory> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(ErrorInjectionDownloadFileFactory); }; @@ -1899,9 +1898,8 @@ } // If the server response for the resumption request specifies a bad range (i.e. -// not the range that was requested or an invalid or missing Content-Range -// header), then the download should be marked as interrupted again without -// discarding the partial state. +// not the range that was requested), then the download should be marked as +// interrupted and restart from the beginning. IN_PROC_BROWSER_TEST_F(DownloadContentTest, BadRangeHeader) { SetupErrorInjectionDownloads(); GURL url = TestDownloadHttpResponse::GetNextURLForDownload(); @@ -1916,15 +1914,35 @@ WaitForInterrupt(download); // Upon resumption, the server starts responding with a bad range header. - TestDownloadHttpResponse::StartServingStaticResponse( + parameters.ClearInjectedErrors(); + parameters.SetResponseForRangeRequest( + 10000, -1, "HTTP/1.1 206 Partial Content\r\n" "Content-Range: bytes 1000000-2000000/3000000\r\n" - "\r\n", - server_url); + "\r\n"); + TestDownloadHttpResponse::StartServing(parameters, server_url); + download->Resume(false); - WaitForInterrupt(download); - EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT, + WaitForCompletion(download); + EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE, download->GetLastReason()); +} + +// If the server response for the resumption request specifies an invalid range, +// then the download should be marked as interrupted and as interrupted again +// without discarding the partial state. +IN_PROC_BROWSER_TEST_F(DownloadContentTest, InvalidRangeHeader) { + SetupErrorInjectionDownloads(); + GURL url = TestDownloadHttpResponse::GetNextURLForDownload(); + GURL server_url = embedded_test_server()->GetURL(url.host(), url.path()); + TestDownloadHttpResponse::Parameters parameters = + TestDownloadHttpResponse::Parameters::WithSingleInterruption( + inject_error_callback()); + TestDownloadHttpResponse::StartServing(parameters, server_url); + + download::DownloadItem* download = + StartDownloadAndReturnItem(shell(), server_url); + WaitForInterrupt(download); // Or this time, the server sends a response with an invalid Content-Range // header. @@ -1969,14 +1987,47 @@ const TestDownloadResponseHandler::CompletedRequests& requests = test_response_handler()->completed_requests(); - ASSERT_EQ(5u, requests.size()); + ASSERT_EQ(4u, requests.size()); // None of the request should have transferred the entire resource. EXPECT_GT(parameters.size, requests[0]->transferred_byte_count); EXPECT_EQ(0, requests[1]->transferred_byte_count); EXPECT_EQ(0, requests[2]->transferred_byte_count); - EXPECT_EQ(0, requests[3]->transferred_byte_count); - EXPECT_GT(parameters.size, requests[4]->transferred_byte_count); + EXPECT_GT(parameters.size, requests[3]->transferred_byte_count); +} + +// If the server response for the resumption request cannot be decoded, +// the download will need to restart. This is to simulate some servers +// that doesn't handle range request properly. +IN_PROC_BROWSER_TEST_F(DownloadContentTest, BadEncoding) { + SetupErrorInjectionDownloads(); + GURL url = TestDownloadHttpResponse::GetNextURLForDownload(); + GURL server_url = embedded_test_server()->GetURL(url.host(), url.path()); + TestDownloadHttpResponse::Parameters parameters = + TestDownloadHttpResponse::Parameters::WithSingleInterruption( + inject_error_callback()); + TestDownloadHttpResponse::StartServing(parameters, server_url); + + download::DownloadItem* download = + StartDownloadAndReturnItem(shell(), server_url); + WaitForInterrupt(download); + + parameters.ClearInjectedErrors(); + // Server's response to range request cannot be decoded. + parameters.SetResponseForRangeRequest( + 10000, -1, + "HTTP/1.1 206 Partial Content\r\n" + "Content-Range: bytes 1000000-2000000/3000000\r\n" + "Content-Encoding: gzip\r\n" + "\r\n" + "x\r\n"); + TestDownloadHttpResponse::StartServing(parameters, server_url); + + // The download will restart and complete successfully. + download->Resume(false); + WaitForCompletion(download); + EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE, + download->GetLastReason()); } // A partial resumption results in an HTTP 200 response. I.e. the server ignored
diff --git a/content/browser/download/download_manager_impl.cc b/content/browser/download/download_manager_impl.cc index c4788179..ef83f466 100644 --- a/content/browser/download/download_manager_impl.cc +++ b/content/browser/download/download_manager_impl.cc
@@ -351,8 +351,7 @@ is_history_download_id_retrieved_(false), should_persist_new_download_(false), cancelled_download_cleared_from_history_(0), - interrupted_download_cleared_from_history_(0), - weak_factory_(this) { + interrupted_download_cleared_from_history_(0) { DCHECK(browser_context); download::SetIOTaskRunner( base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}));
diff --git a/content/browser/download/download_manager_impl.h b/content/browser/download/download_manager_impl.h index 4453f097..abb15b22 100644 --- a/content/browser/download/download_manager_impl.h +++ b/content/browser/download/download_manager_impl.h
@@ -392,7 +392,7 @@ using IdCallbackVector = std::vector<std::unique_ptr<GetNextIdCallback>>; IdCallbackVector id_callbacks_; - base::WeakPtrFactory<DownloadManagerImpl> weak_factory_; + base::WeakPtrFactory<DownloadManagerImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DownloadManagerImpl); };
diff --git a/content/browser/download/download_request_core.cc b/content/browser/download/download_request_core.cc index 411e834..3eb3381 100644 --- a/content/browser/download/download_request_core.cc +++ b/content/browser/download/download_request_core.cc
@@ -412,7 +412,7 @@ download::DownloadInterruptReason reason = download::HandleRequestCompletionStatus( error_code, !has_strong_validators, request()->ssl_info().cert_status, - abort_reason_); + is_partial_request_, abort_reason_); std::string accept_ranges; if (request()->response_headers()) {
diff --git a/content/browser/download/drag_download_file.cc b/content/browser/download/drag_download_file.cc index fd4918d..20084144 100644 --- a/content/browser/download/drag_download_file.cc +++ b/content/browser/download/drag_download_file.cc
@@ -54,8 +54,7 @@ referrer_(referrer), referrer_encoding_(referrer_encoding), web_contents_(web_contents), - download_item_(nullptr), - weak_ptr_factory_(this) { + download_item_(nullptr) { DCHECK(on_completed_task_runner_); DCHECK(!on_completed_.is_null()); DCHECK(web_contents_); @@ -185,7 +184,7 @@ download::DownloadItem* download_item_; // Only used in the callback from DownloadManager::DownloadUrl(). - base::WeakPtrFactory<DragDownloadFileUI> weak_ptr_factory_; + base::WeakPtrFactory<DragDownloadFileUI> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DragDownloadFileUI); }; @@ -200,8 +199,7 @@ file_(std::move(file)), drag_task_runner_(base::ThreadTaskRunnerHandle::Get()), state_(INITIALIZED), - drag_ui_(nullptr), - weak_ptr_factory_(this) { + drag_ui_(nullptr) { drag_ui_ = new DragDownloadFileUI( url, referrer, referrer_encoding, web_contents, drag_task_runner_, base::Bind(&DragDownloadFile::DownloadCompleted,
diff --git a/content/browser/download/drag_download_file.h b/content/browser/download/drag_download_file.h index 635a909..7d43ec4 100644 --- a/content/browser/download/drag_download_file.h +++ b/content/browser/download/drag_download_file.h
@@ -64,7 +64,7 @@ scoped_refptr<ui::DownloadFileObserver> observer_; base::RunLoop nested_loop_; DragDownloadFileUI* drag_ui_; - base::WeakPtrFactory<DragDownloadFile> weak_ptr_factory_; + base::WeakPtrFactory<DragDownloadFile> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DragDownloadFile); };
diff --git a/content/browser/download/mhtml_generation_manager.cc b/content/browser/download/mhtml_generation_manager.cc index 9e524c5..ba2eb1bc5 100644 --- a/content/browser/download/mhtml_generation_manager.cc +++ b/content/browser/download/mhtml_generation_manager.cc
@@ -261,7 +261,7 @@ // Not used when the renderer is writing directly to file. bool waiting_on_data_streaming_; - base::WeakPtrFactory<Job> weak_factory_; + base::WeakPtrFactory<Job> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(Job); }; @@ -276,8 +276,7 @@ salt_(base::GenerateGUID()), callback_(std::move(callback)), is_finished_(false), - waiting_on_data_streaming_(false), - weak_factory_(this) { + waiting_on_data_streaming_(false) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT_NESTABLE_ASYNC_BEGIN2(
diff --git a/content/browser/download/url_downloader.cc b/content/browser/download/url_downloader.cc index 2d29f1e..0033149 100644 --- a/content/browser/download/url_downloader.cc +++ b/content/browser/download/url_downloader.cc
@@ -78,8 +78,7 @@ request_origin, download_source), follow_cross_origin_redirects_(follow_cross_origin_redirects), - upload_callback_(upload_callback), - weak_ptr_factory_(this) {} + upload_callback_(upload_callback) {} UrlDownloader::~UrlDownloader() = default;
diff --git a/content/browser/download/url_downloader.h b/content/browser/download/url_downloader.h index f501c91..8109783 100644 --- a/content/browser/download/url_downloader.h +++ b/content/browser/download/url_downloader.h
@@ -97,7 +97,7 @@ download::DownloadUrlParameters::UploadProgressCallback upload_callback_; std::unique_ptr<network::UploadProgressTracker> upload_progress_tracker_; - base::WeakPtrFactory<UrlDownloader> weak_ptr_factory_; + base::WeakPtrFactory<UrlDownloader> weak_ptr_factory_{this}; }; } // namespace content
diff --git a/content/browser/fileapi/file_system_manager_impl.cc b/content/browser/fileapi/file_system_manager_impl.cc index 930af72a..3d23db0 100644 --- a/content/browser/fileapi/file_system_manager_impl.cc +++ b/content/browser/fileapi/file_system_manager_impl.cc
@@ -126,8 +126,7 @@ : process_id_(process_id), context_(std::move(file_system_context)), security_policy_(ChildProcessSecurityPolicyImpl::GetInstance()), - blob_storage_context_(std::move(blob_storage_context)), - weak_factory_(this) { + blob_storage_context_(std::move(blob_storage_context)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(context_); DCHECK(blob_storage_context_);
diff --git a/content/browser/fileapi/file_system_manager_impl.h b/content/browser/fileapi/file_system_manager_impl.h index 6dc0e8a..400c067 100644 --- a/content/browser/fileapi/file_system_manager_impl.h +++ b/content/browser/fileapi/file_system_manager_impl.h
@@ -223,7 +223,7 @@ base::IDMap<scoped_refptr<storage::ShareableFileReference>> in_transit_snapshot_files_; - base::WeakPtrFactory<FileSystemManagerImpl> weak_factory_; + base::WeakPtrFactory<FileSystemManagerImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FileSystemManagerImpl); };
diff --git a/content/browser/frame_host/interstitial_page_impl.cc b/content/browser/frame_host/interstitial_page_impl.cc index f295ce0f..875ec8c 100644 --- a/content/browser/frame_host/interstitial_page_impl.cc +++ b/content/browser/frame_host/interstitial_page_impl.cc
@@ -186,8 +186,7 @@ create_view_(true), pause_throbber_(false), delegate_(delegate), - widget_observer_(this), - weak_ptr_factory_(this) { + widget_observer_(this) { InitInterstitialPageMap(); }
diff --git a/content/browser/frame_host/interstitial_page_impl.h b/content/browser/frame_host/interstitial_page_impl.h index fdb78ec..dfc8c8c3 100644 --- a/content/browser/frame_host/interstitial_page_impl.h +++ b/content/browser/frame_host/interstitial_page_impl.h
@@ -324,7 +324,7 @@ ScopedObserver<RenderWidgetHost, RenderWidgetHostObserver> widget_observer_; - base::WeakPtrFactory<InterstitialPageImpl> weak_ptr_factory_; + base::WeakPtrFactory<InterstitialPageImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(InterstitialPageImpl); };
diff --git a/content/browser/frame_host/keep_alive_handle_factory.cc b/content/browser/frame_host/keep_alive_handle_factory.cc index 042904d..ffaf0540 100644 --- a/content/browser/frame_host/keep_alive_handle_factory.cc +++ b/content/browser/frame_host/keep_alive_handle_factory.cc
@@ -19,8 +19,7 @@ class KeepAliveHandleFactory::Context final : public base::RefCounted<Context> { public: - explicit Context(int process_id) - : process_id_(process_id), weak_ptr_factory_(this) { + explicit Context(int process_id) : process_id_(process_id) { RenderProcessHost* process_host = RenderProcessHost::FromID(process_id_); if (!process_host || process_host->IsKeepAliveRefCountDisabled()) return; @@ -60,7 +59,7 @@ const int process_id_; bool detached_ = false; - base::WeakPtrFactory<Context> weak_ptr_factory_; + base::WeakPtrFactory<Context> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(Context); };
diff --git a/content/browser/frame_host/navigation_controller_impl_browsertest.cc b/content/browser/frame_host/navigation_controller_impl_browsertest.cc index 387947fd..6aa1956 100644 --- a/content/browser/frame_host/navigation_controller_impl_browsertest.cc +++ b/content/browser/frame_host/navigation_controller_impl_browsertest.cc
@@ -7350,7 +7350,7 @@ class RequestMonitoringNavigationBrowserTest : public ContentBrowserTest { public: - RequestMonitoringNavigationBrowserTest() : weak_factory_(this) {} + RequestMonitoringNavigationBrowserTest() {} const net::test_server::HttpRequest* FindAccumulatedRequest( const GURL& url_to_find) { @@ -7399,7 +7399,8 @@ } std::vector<net::test_server::HttpRequest> accumulated_requests_; - base::WeakPtrFactory<RequestMonitoringNavigationBrowserTest> weak_factory_; + base::WeakPtrFactory<RequestMonitoringNavigationBrowserTest> weak_factory_{ + this}; }; // Helper for waiting until the main frame of |web_contents| has loaded
diff --git a/content/browser/frame_host/navigation_handle_impl.cc b/content/browser/frame_host/navigation_handle_impl.cc index 942be53..aef415fe 100644 --- a/content/browser/frame_host/navigation_handle_impl.cc +++ b/content/browser/frame_host/navigation_handle_impl.cc
@@ -62,8 +62,7 @@ pending_nav_entry_id_(pending_nav_entry_id), navigation_id_(CreateUniqueHandleID()), reload_type_(ReloadType::NONE), - restore_type_(RestoreType::NONE), - weak_factory_(this) { + restore_type_(RestoreType::NONE) { const GURL& url = navigation_request_->common_params().url; TRACE_EVENT_ASYNC_BEGIN2("navigation", "NavigationHandle", this, "frame_tree_node",
diff --git a/content/browser/frame_host/navigation_handle_impl.h b/content/browser/frame_host/navigation_handle_impl.h index 292de745..bd8de94 100644 --- a/content/browser/frame_host/navigation_handle_impl.h +++ b/content/browser/frame_host/navigation_handle_impl.h
@@ -310,7 +310,7 @@ // TODO(clamy): Clean this up once the architecture of unit tests is better. scoped_refptr<net::HttpResponseHeaders> response_headers_for_testing_; - base::WeakPtrFactory<NavigationHandleImpl> weak_factory_; + base::WeakPtrFactory<NavigationHandleImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(NavigationHandleImpl); };
diff --git a/content/browser/frame_host/navigation_handle_impl_browsertest.cc b/content/browser/frame_host/navigation_handle_impl_browsertest.cc index 02aab9b..7986b30 100644 --- a/content/browser/frame_host/navigation_handle_impl_browsertest.cc +++ b/content/browser/frame_host/navigation_handle_impl_browsertest.cc
@@ -176,8 +176,7 @@ will_redirect_result_(will_redirect_result), will_fail_result_(will_fail_result), will_process_result_(will_process_result), - expected_start_url_(expected_start_url), - weak_factory_(this) {} + expected_start_url_(expected_start_url) {} ~TestNavigationThrottleInstaller() override {} // Installs a TestNavigationThrottle whose |method| method will return @@ -334,7 +333,7 @@ // The throttle installer can be deleted before all tasks posted by its // throttles are run, so it must be referenced via weak pointers. - base::WeakPtrFactory<TestNavigationThrottleInstaller> weak_factory_; + base::WeakPtrFactory<TestNavigationThrottleInstaller> weak_factory_{this}; }; // Same as above, but installs NavigationThrottles that do not directly return
diff --git a/content/browser/frame_host/navigation_request.cc b/content/browser/frame_host/navigation_request.cc index 4deb9d7..3667d34 100644 --- a/content/browser/frame_host/navigation_request.cc +++ b/content/browser/frame_host/navigation_request.cc
@@ -661,8 +661,7 @@ expected_render_process_host_id_(ChildProcessHost::kInvalidUniqueID), devtools_navigation_token_(base::UnguessableToken::Create()), request_navigation_client_(nullptr), - commit_navigation_client_(nullptr), - weak_factory_(this) { + commit_navigation_client_(nullptr) { DCHECK(!browser_initiated || (entry != nullptr && frame_entry != nullptr)); DCHECK(!IsRendererDebugURL(common_params_.url)); DCHECK(common_params_.method == "POST" || !common_params_.post_data);
diff --git a/content/browser/frame_host/navigation_request.h b/content/browser/frame_host/navigation_request.h index e97fa85e..090e589 100644 --- a/content/browser/frame_host/navigation_request.h +++ b/content/browser/frame_host/navigation_request.h
@@ -921,7 +921,7 @@ // Set in ReadyToCommitNavigation. bool is_same_process_ = true; - base::WeakPtrFactory<NavigationRequest> weak_factory_; + base::WeakPtrFactory<NavigationRequest> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(NavigationRequest); };
diff --git a/content/browser/frame_host/navigation_throttle_runner.cc b/content/browser/frame_host/navigation_throttle_runner.cc index 22b66cf..43bb09b 100644 --- a/content/browser/frame_host/navigation_throttle_runner.cc +++ b/content/browser/frame_host/navigation_throttle_runner.cc
@@ -58,7 +58,7 @@ NavigationThrottleRunner::NavigationThrottleRunner(Delegate* delegate, NavigationHandle* handle) - : delegate_(delegate), handle_(handle), weak_factory_(this) {} + : delegate_(delegate), handle_(handle) {} NavigationThrottleRunner::~NavigationThrottleRunner() = default;
diff --git a/content/browser/frame_host/navigation_throttle_runner.h b/content/browser/frame_host/navigation_throttle_runner.h index 0752864..916bb85d 100644 --- a/content/browser/frame_host/navigation_throttle_runner.h +++ b/content/browser/frame_host/navigation_throttle_runner.h
@@ -88,7 +88,7 @@ // The event currently being processed. Event current_event_ = Event::NoEvent; - base::WeakPtrFactory<NavigationThrottleRunner> weak_factory_; + base::WeakPtrFactory<NavigationThrottleRunner> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(NavigationThrottleRunner); };
diff --git a/content/browser/frame_host/origin_policy_throttle.cc b/content/browser/frame_host/origin_policy_throttle.cc index b7aee32b..6832219 100644 --- a/content/browser/frame_host/origin_policy_throttle.cc +++ b/content/browser/frame_host/origin_policy_throttle.cc
@@ -142,7 +142,7 @@ } OriginPolicyThrottle::OriginPolicyThrottle(NavigationHandle* handle) - : NavigationThrottle(handle), weak_factory_(this) {} + : NavigationThrottle(handle) {} // TODO(andypaicu): Remove when we have moved reporting logic to the network // service.
diff --git a/content/browser/frame_host/origin_policy_throttle.h b/content/browser/frame_host/origin_policy_throttle.h index 20b53d8..8b2877a5 100644 --- a/content/browser/frame_host/origin_policy_throttle.h +++ b/content/browser/frame_host/origin_policy_throttle.h
@@ -89,7 +89,7 @@ void OnOriginPolicyManagerRetrieveDone( const network::OriginPolicy& origin_policy); - base::WeakPtrFactory<OriginPolicyThrottle> weak_factory_; + base::WeakPtrFactory<OriginPolicyThrottle> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(OriginPolicyThrottle); };
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 8a7483d..28c7c5c 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -883,8 +883,7 @@ keep_alive_timeout_(base::TimeDelta::FromSeconds(30)), subframe_unload_timeout_(base::TimeDelta::FromMilliseconds( RenderViewHostImpl::kUnloadTimeoutMS)), - commit_callback_interceptor_(nullptr), - weak_ptr_factory_(this) { + commit_callback_interceptor_(nullptr) { GetProcess()->AddRoute(routing_id_, this); g_routing_id_frame_map.Get().emplace( RenderFrameHostID(GetProcess()->GetID(), routing_id_), this); @@ -4874,9 +4873,20 @@ if (subresource_loader_params && subresource_loader_params->appcache_loader_factory_info.is_valid()) { // If the caller has supplied a factory for AppCache, use it. - subresource_loader_factories->appcache_factory_info() = + + auto factory_ptr_info = std::move(subresource_loader_params->appcache_loader_factory_info); +#if defined(OS_ANDROID) + GetContentClient() + ->browser() + ->WillCreateURLLoaderFactoryForAppCacheSubresource( + GetProcess()->GetID(), &factory_ptr_info); +#endif + + subresource_loader_factories->appcache_factory_info() = + std::move(factory_ptr_info); + // Inject test intermediary if needed. if (!GetCreateNetworkFactoryCallbackForRenderFrame().is_null()) { network::mojom::URLLoaderFactoryPtrInfo original_factory =
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index d8354e52..6bd4625 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -2216,7 +2216,7 @@ blink::mojom::FrameLifecycleState::kRunning; // NOTE: This must be the last member. - base::WeakPtrFactory<RenderFrameHostImpl> weak_ptr_factory_; + base::WeakPtrFactory<RenderFrameHostImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderFrameHostImpl); };
diff --git a/content/browser/frame_host/render_frame_host_manager.cc b/content/browser/frame_host/render_frame_host_manager.cc index cfc019e..0e5a803 100644 --- a/content/browser/frame_host/render_frame_host_manager.cc +++ b/content/browser/frame_host/render_frame_host_manager.cc
@@ -155,9 +155,7 @@ RenderFrameHostManager::RenderFrameHostManager(FrameTreeNode* frame_tree_node, Delegate* delegate) - : frame_tree_node_(frame_tree_node), - delegate_(delegate), - weak_factory_(this) { + : frame_tree_node_(frame_tree_node), delegate_(delegate) { DCHECK(frame_tree_node_); }
diff --git a/content/browser/frame_host/render_frame_host_manager.h b/content/browser/frame_host/render_frame_host_manager.h index f93cf92..b34a544 100644 --- a/content/browser/frame_host/render_frame_host_manager.h +++ b/content/browser/frame_host/render_frame_host_manager.h
@@ -829,7 +829,7 @@ AttachToInnerDelegateState attach_to_inner_delegate_state_ = AttachToInnerDelegateState::NONE; - base::WeakPtrFactory<RenderFrameHostManager> weak_factory_; + base::WeakPtrFactory<RenderFrameHostManager> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderFrameHostManager); };
diff --git a/content/browser/frame_host/render_frame_host_manager_browsertest.cc b/content/browser/frame_host/render_frame_host_manager_browsertest.cc index 192253c..c5a5abe 100644 --- a/content/browser/frame_host/render_frame_host_manager_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_manager_browsertest.cc
@@ -5526,7 +5526,7 @@ // out of scope. class AssertForegroundHelper { public: - AssertForegroundHelper() : weak_ptr_factory_(this) {} + AssertForegroundHelper() {} #if defined(OS_MACOSX) // Asserts that |renderer_process| isn't backgrounded and reposts self to @@ -5556,7 +5556,7 @@ #endif // defined(OS_MACOSX) private: - base::WeakPtrFactory<AssertForegroundHelper> weak_ptr_factory_; + base::WeakPtrFactory<AssertForegroundHelper> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AssertForegroundHelper); };
diff --git a/content/browser/frame_host/render_widget_host_view_guest.cc b/content/browser/frame_host/render_widget_host_view_guest.cc index 05804d90f..b978972 100644 --- a/content/browser/frame_host/render_widget_host_view_guest.cc +++ b/content/browser/frame_host/render_widget_host_view_guest.cc
@@ -108,8 +108,7 @@ : RenderWidgetHostViewChildFrame(widget_host), // |guest| is NULL during test. guest_(guest ? guest->AsWeakPtr() : base::WeakPtr<BrowserPluginGuest>()), - platform_view_(platform_view), - weak_ptr_factory_(this) { + platform_view_(platform_view) { // In tests |guest_| and therefore |owner| can be null. auto* owner = GetOwnerRenderWidgetHostView(); if (owner)
diff --git a/content/browser/frame_host/render_widget_host_view_guest.h b/content/browser/frame_host/render_widget_host_view_guest.h index f2c0066..794b07f 100644 --- a/content/browser/frame_host/render_widget_host_view_guest.h +++ b/content/browser/frame_host/render_widget_host_view_guest.h
@@ -193,7 +193,7 @@ // session. bool should_forward_text_selection_ = false; - base::WeakPtrFactory<RenderWidgetHostViewGuest> weak_ptr_factory_; + base::WeakPtrFactory<RenderWidgetHostViewGuest> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewGuest); };
diff --git a/content/browser/generic_sensor/sensor_provider_proxy_impl.cc b/content/browser/generic_sensor/sensor_provider_proxy_impl.cc index 5901ce6..7bcfa2e 100644 --- a/content/browser/generic_sensor/sensor_provider_proxy_impl.cc +++ b/content/browser/generic_sensor/sensor_provider_proxy_impl.cc
@@ -30,8 +30,7 @@ PermissionControllerImpl* permission_controller, RenderFrameHost* render_frame_host) : permission_controller_(permission_controller), - render_frame_host_(render_frame_host), - weak_factory_(this) { + render_frame_host_(render_frame_host) { DCHECK(permission_controller); DCHECK(render_frame_host); }
diff --git a/content/browser/generic_sensor/sensor_provider_proxy_impl.h b/content/browser/generic_sensor/sensor_provider_proxy_impl.h index 5df9b44..dc48122 100644 --- a/content/browser/generic_sensor/sensor_provider_proxy_impl.h +++ b/content/browser/generic_sensor/sensor_provider_proxy_impl.h
@@ -43,7 +43,7 @@ RenderFrameHost* render_frame_host_; device::mojom::SensorProviderPtr sensor_provider_; - base::WeakPtrFactory<SensorProviderProxyImpl> weak_factory_; + base::WeakPtrFactory<SensorProviderProxyImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SensorProviderProxyImpl); };
diff --git a/content/browser/geolocation/geolocation_service_impl.cc b/content/browser/geolocation/geolocation_service_impl.cc index ffb3b68..77d51d8e 100644 --- a/content/browser/geolocation/geolocation_service_impl.cc +++ b/content/browser/geolocation/geolocation_service_impl.cc
@@ -16,8 +16,7 @@ GeolocationServiceImplContext::GeolocationServiceImplContext( PermissionControllerImpl* permission_controller) : permission_controller_(permission_controller), - request_id_(PermissionController::kNoPendingOperation), - weak_factory_(this) {} + request_id_(PermissionController::kNoPendingOperation) {} GeolocationServiceImplContext::~GeolocationServiceImplContext() { }
diff --git a/content/browser/geolocation/geolocation_service_impl.h b/content/browser/geolocation/geolocation_service_impl.h index 71d3966..247a0ca 100644 --- a/content/browser/geolocation/geolocation_service_impl.h +++ b/content/browser/geolocation/geolocation_service_impl.h
@@ -40,7 +40,7 @@ const base::Callback<void(blink::mojom::PermissionStatus)>& callback, blink::mojom::PermissionStatus permission_status); - base::WeakPtrFactory<GeolocationServiceImplContext> weak_factory_; + base::WeakPtrFactory<GeolocationServiceImplContext> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(GeolocationServiceImplContext); };
diff --git a/content/browser/gpu/gpu_internals_ui.cc b/content/browser/gpu/gpu_internals_ui.cc index 57d8ebfa..17495646 100644 --- a/content/browser/gpu/gpu_internals_ui.cc +++ b/content/browser/gpu/gpu_internals_ui.cc
@@ -395,6 +395,9 @@ display_info->Append(NewDescriptionValuePair( "Color space information", display.color_space().ToString())); display_info->Append(NewDescriptionValuePair( + "SDR white level in nits", + base::NumberToString(display.sdr_white_level()))); + display_info->Append(NewDescriptionValuePair( "Bits per color component", base::NumberToString(display.depth_per_component()))); display_info->Append(NewDescriptionValuePair(
diff --git a/content/browser/gpu/gpu_process_host.cc b/content/browser/gpu/gpu_process_host.cc index 4165ba00..ca2e5d50 100644 --- a/content/browser/gpu/gpu_process_host.cc +++ b/content/browser/gpu/gpu_process_host.cc
@@ -672,8 +672,7 @@ kind_(kind), process_launched_(false), connection_filter_id_( - ServiceManagerConnection::kInvalidConnectionFilterId), - weak_ptr_factory_(this) { + ServiceManagerConnection::kInvalidConnectionFilterId) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSingleProcess) || base::CommandLine::ForCurrentProcess()->HasSwitch(
diff --git a/content/browser/gpu/gpu_process_host.h b/content/browser/gpu/gpu_process_host.h index ba6822bc..60199ca 100644 --- a/content/browser/gpu/gpu_process_host.h +++ b/content/browser/gpu/gpu_process_host.h
@@ -242,7 +242,7 @@ SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<GpuProcessHost> weak_ptr_factory_; + base::WeakPtrFactory<GpuProcessHost> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(GpuProcessHost); };
diff --git a/content/browser/gpu/viz_devtools_connector.cc b/content/browser/gpu/viz_devtools_connector.cc index 19295f70..f005ec0f 100644 --- a/content/browser/gpu/viz_devtools_connector.cc +++ b/content/browser/gpu/viz_devtools_connector.cc
@@ -41,7 +41,7 @@ } // namespace -VizDevToolsConnector::VizDevToolsConnector() : weak_ptr_factory_(this) {} +VizDevToolsConnector::VizDevToolsConnector() {} VizDevToolsConnector::~VizDevToolsConnector() {}
diff --git a/content/browser/gpu/viz_devtools_connector.h b/content/browser/gpu/viz_devtools_connector.h index 98a6e1e..6f44bb0 100644 --- a/content/browser/gpu/viz_devtools_connector.h +++ b/content/browser/gpu/viz_devtools_connector.h
@@ -26,7 +26,7 @@ int result, int port); - base::WeakPtrFactory<VizDevToolsConnector> weak_ptr_factory_; + base::WeakPtrFactory<VizDevToolsConnector> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VizDevToolsConnector); };
diff --git a/content/browser/idle/idle_manager.cc b/content/browser/idle/idle_manager.cc index 5a77c238..beb0c7a 100644 --- a/content/browser/idle/idle_manager.cc +++ b/content/browser/idle/idle_manager.cc
@@ -62,8 +62,7 @@ } // namespace -IdleManager::IdleManager() - : idle_time_provider_(new DefaultIdleProvider()), weak_factory_(this) {} +IdleManager::IdleManager() : idle_time_provider_(new DefaultIdleProvider()) {} IdleManager::~IdleManager() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/content/browser/idle/idle_manager.h b/content/browser/idle/idle_manager.h index 81d93bf..35b2545d 100644 --- a/content/browser/idle/idle_manager.h +++ b/content/browser/idle/idle_manager.h
@@ -96,7 +96,7 @@ base::LinkedList<IdleMonitor> monitors_; SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<IdleManager> weak_factory_; + base::WeakPtrFactory<IdleManager> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(IdleManager); };
diff --git a/content/browser/indexed_db/indexed_db_active_blob_registry.cc b/content/browser/indexed_db/indexed_db_active_blob_registry.cc index 798604a8..584d42c 100644 --- a/content/browser/indexed_db/indexed_db_active_blob_registry.cc +++ b/content/browser/indexed_db/indexed_db_active_blob_registry.cc
@@ -15,7 +15,7 @@ IndexedDBActiveBlobRegistry::IndexedDBActiveBlobRegistry( IndexedDBBackingStore* backing_store) - : backing_store_(backing_store), weak_factory_(this) {} + : backing_store_(backing_store) {} IndexedDBActiveBlobRegistry::~IndexedDBActiveBlobRegistry() { }
diff --git a/content/browser/indexed_db/indexed_db_active_blob_registry.h b/content/browser/indexed_db/indexed_db_active_blob_registry.h index b4495e2..daec1e0 100644 --- a/content/browser/indexed_db/indexed_db_active_blob_registry.h +++ b/content/browser/indexed_db/indexed_db_active_blob_registry.h
@@ -64,7 +64,7 @@ // backing_store_->factory() will keep backing_store_ alive for us. And // backing_store_ owns us, so we'll stay alive as long as we're needed. IndexedDBBackingStore* backing_store_; - base::WeakPtrFactory<IndexedDBActiveBlobRegistry> weak_factory_; + base::WeakPtrFactory<IndexedDBActiveBlobRegistry> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(IndexedDBActiveBlobRegistry); };
diff --git a/content/browser/indexed_db/indexed_db_backing_store.cc b/content/browser/indexed_db/indexed_db_backing_store.cc index eb3fb99..27fe746 100644 --- a/content/browser/indexed_db/indexed_db_backing_store.cc +++ b/content/browser/indexed_db/indexed_db_backing_store.cc
@@ -2823,8 +2823,7 @@ leveldb_factory_(backing_store ? backing_store->leveldb_factory_ : nullptr), database_id_(-1), - committing_(false), - ptr_factory_(this) {} + committing_(false) {} IndexedDBBackingStore::Transaction::~Transaction() { DCHECK(!committing_);
diff --git a/content/browser/indexed_db/indexed_db_backing_store.h b/content/browser/indexed_db/indexed_db_backing_store.h index 81967100..2bb8a6d4 100644 --- a/content/browser/indexed_db/indexed_db_backing_store.h +++ b/content/browser/indexed_db/indexed_db_backing_store.h
@@ -292,7 +292,7 @@ // has been bumped, and journal cleaning should be deferred. bool committing_; - base::WeakPtrFactory<Transaction> ptr_factory_; + base::WeakPtrFactory<Transaction> ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(Transaction); };
diff --git a/content/browser/indexed_db/indexed_db_cursor.cc b/content/browser/indexed_db/indexed_db_cursor.cc index 23a88af..3c7c2bb 100644 --- a/content/browser/indexed_db/indexed_db_cursor.cc +++ b/content/browser/indexed_db/indexed_db_cursor.cc
@@ -57,8 +57,7 @@ cursor_type_(cursor_type), transaction_(std::move(transaction)), cursor_(std::move(cursor)), - closed_(false), - ptr_factory_(this) { + closed_(false) { IDB_ASYNC_TRACE_BEGIN("IndexedDBCursor::open", this); }
diff --git a/content/browser/indexed_db/indexed_db_cursor.h b/content/browser/indexed_db/indexed_db_cursor.h index 5e0e26f..79b75f4 100644 --- a/content/browser/indexed_db/indexed_db_cursor.h +++ b/content/browser/indexed_db/indexed_db_cursor.h
@@ -90,7 +90,7 @@ bool closed_; - base::WeakPtrFactory<IndexedDBCursor> ptr_factory_; + base::WeakPtrFactory<IndexedDBCursor> ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(IndexedDBCursor); };
diff --git a/content/browser/indexed_db/indexed_db_database.cc b/content/browser/indexed_db/indexed_db_database.cc index fcf6018..65dcb61 100644 --- a/content/browser/indexed_db/indexed_db_database.cc +++ b/content/browser/indexed_db/indexed_db_database.cc
@@ -158,8 +158,7 @@ IndexedDBDatabase* db, std::unique_ptr<IndexedDBPendingConnection> pending_connection) : ConnectionRequest(std::move(origin_state_handle), db), - pending_(std::move(pending_connection)), - weak_factory_(this) { + pending_(std::move(pending_connection)) { db_->metadata_.was_cold_open = pending_->was_cold_open; } @@ -370,7 +369,7 @@ // transferred to the IndexedDBDispatcherHost via OnUpgradeNeeded. std::unique_ptr<IndexedDBConnection> connection_; - base::WeakPtrFactory<OpenRequest> weak_factory_; + base::WeakPtrFactory<OpenRequest> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(OpenRequest); }; @@ -383,8 +382,7 @@ base::OnceClosure on_database_deleted) : ConnectionRequest(std::move(origin_state_handle), db), callbacks_(callbacks), - on_database_deleted_(std::move(on_database_deleted)), - weak_factory_(this) {} + on_database_deleted_(std::move(on_database_deleted)) {} void Perform() override { if (db_->HasNoConnections()) { @@ -452,7 +450,7 @@ scoped_refptr<IndexedDBCallbacks> callbacks_; base::OnceClosure on_database_deleted_; - base::WeakPtrFactory<DeleteRequest> weak_factory_; + base::WeakPtrFactory<DeleteRequest> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DeleteRequest); };
diff --git a/content/browser/indexed_db/indexed_db_dispatcher_host.cc b/content/browser/indexed_db/indexed_db_dispatcher_host.cc index 52257a1..56d7579 100644 --- a/content/browser/indexed_db/indexed_db_dispatcher_host.cc +++ b/content/browser/indexed_db/indexed_db_dispatcher_host.cc
@@ -67,8 +67,7 @@ scoped_refptr<ChromeBlobStorageContext> blob_storage_context) : indexed_db_context_(std::move(indexed_db_context)), blob_storage_context_(std::move(blob_storage_context)), - ipc_process_id_(ipc_process_id), - weak_factory_(this) { + ipc_process_id_(ipc_process_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DETACH_FROM_SEQUENCE(sequence_checker_); DCHECK(indexed_db_context_);
diff --git a/content/browser/indexed_db/indexed_db_dispatcher_host.h b/content/browser/indexed_db/indexed_db_dispatcher_host.h index b12fbea..02891034 100644 --- a/content/browser/indexed_db/indexed_db_dispatcher_host.h +++ b/content/browser/indexed_db/indexed_db_dispatcher_host.h
@@ -139,7 +139,7 @@ SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<IndexedDBDispatcherHost> weak_factory_; + base::WeakPtrFactory<IndexedDBDispatcherHost> weak_factory_{this}; DISALLOW_IMPLICIT_CONSTRUCTORS(IndexedDBDispatcherHost); };
diff --git a/content/browser/indexed_db/indexed_db_pre_close_task_queue.cc b/content/browser/indexed_db/indexed_db_pre_close_task_queue.cc index 50ef46a..46b95bbe 100644 --- a/content/browser/indexed_db/indexed_db_pre_close_task_queue.cc +++ b/content/browser/indexed_db/indexed_db_pre_close_task_queue.cc
@@ -25,8 +25,7 @@ on_done_(std::move(on_complete)), timeout_time_(max_run_time), timeout_timer_(std::move(timer)), - task_runner_(base::SequencedTaskRunnerHandle::Get()), - ptr_factory_(this) {} + task_runner_(base::SequencedTaskRunnerHandle::Get()) {} IndexedDBPreCloseTaskQueue::~IndexedDBPreCloseTaskQueue() {} void IndexedDBPreCloseTaskQueue::StopForNewConnection() {
diff --git a/content/browser/indexed_db/indexed_db_pre_close_task_queue.h b/content/browser/indexed_db/indexed_db_pre_close_task_queue.h index 59ec133..c406dc3 100644 --- a/content/browser/indexed_db/indexed_db_pre_close_task_queue.h +++ b/content/browser/indexed_db/indexed_db_pre_close_task_queue.h
@@ -104,7 +104,7 @@ std::unique_ptr<base::OneShotTimer> timeout_timer_; scoped_refptr<base::SequencedTaskRunner> task_runner_; - base::WeakPtrFactory<IndexedDBPreCloseTaskQueue> ptr_factory_; + base::WeakPtrFactory<IndexedDBPreCloseTaskQueue> ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(IndexedDBPreCloseTaskQueue); };
diff --git a/content/browser/indexed_db/indexed_db_quota_client_unittest.cc b/content/browser/indexed_db/indexed_db_quota_client_unittest.cc index 60672bbc6..d329731 100644 --- a/content/browser/indexed_db/indexed_db_quota_client_unittest.cc +++ b/content/browser/indexed_db/indexed_db_quota_client_unittest.cc
@@ -46,8 +46,7 @@ : kOriginA(url::Origin::Create(GURL("http://host"))), kOriginB(url::Origin::Create(GURL("http://host:8000"))), kOriginOther(url::Origin::Create(GURL("http://other"))), - usage_(0), - weak_factory_(this) { + usage_(0) { browser_context_.reset(new TestBrowserContext()); scoped_refptr<storage::QuotaManager> quota_manager = @@ -164,7 +163,7 @@ scoped_refptr<IndexedDBContextImpl> idb_context_; std::unique_ptr<TestBrowserContext> browser_context_; blink::mojom::QuotaStatusCode delete_status_; - base::WeakPtrFactory<IndexedDBQuotaClientTest> weak_factory_; + base::WeakPtrFactory<IndexedDBQuotaClientTest> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(IndexedDBQuotaClientTest); };
diff --git a/content/browser/indexed_db/indexed_db_tombstone_sweeper.cc b/content/browser/indexed_db/indexed_db_tombstone_sweeper.cc index 6bdcd52..d927cc9 100644 --- a/content/browser/indexed_db/indexed_db_tombstone_sweeper.cc +++ b/content/browser/indexed_db/indexed_db_tombstone_sweeper.cc
@@ -71,8 +71,7 @@ leveldb::DB* database) : max_round_iterations_(round_iterations), max_iterations_(max_iterations), - database_(database), - ptr_factory_(this) { + database_(database) { sweep_state_.start_database_seed = static_cast<size_t>(base::RandUint64()); sweep_state_.start_object_store_seed = static_cast<size_t>(base::RandUint64());
diff --git a/content/browser/indexed_db/indexed_db_tombstone_sweeper.h b/content/browser/indexed_db/indexed_db_tombstone_sweeper.h index c10bf43..1a979dff 100644 --- a/content/browser/indexed_db/indexed_db_tombstone_sweeper.h +++ b/content/browser/indexed_db/indexed_db_tombstone_sweeper.h
@@ -189,7 +189,7 @@ SweepState sweep_state_; SweepMetrics metrics_; - base::WeakPtrFactory<IndexedDBTombstoneSweeper> ptr_factory_; + base::WeakPtrFactory<IndexedDBTombstoneSweeper> ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(IndexedDBTombstoneSweeper); };
diff --git a/content/browser/indexed_db/indexed_db_transaction.cc b/content/browser/indexed_db/indexed_db_transaction.cc index 4f2a1f21..11783f25 100644 --- a/content/browser/indexed_db/indexed_db_transaction.cc +++ b/content/browser/indexed_db/indexed_db_transaction.cc
@@ -116,8 +116,7 @@ mode_(mode), connection_(connection->GetWeakPtr()), error_callback_(std::move(error_callback)), - transaction_(backing_store_transaction), - ptr_factory_(this) { + transaction_(backing_store_transaction) { IDB_ASYNC_TRACE_BEGIN("IndexedDBTransaction::lifetime", this); callbacks_ = connection_->callbacks(); database_ = connection_->database();
diff --git a/content/browser/indexed_db/indexed_db_transaction.h b/content/browser/indexed_db/indexed_db_transaction.h index 90bafc4..4fc08993 100644 --- a/content/browser/indexed_db/indexed_db_transaction.h +++ b/content/browser/indexed_db/indexed_db_transaction.h
@@ -277,7 +277,7 @@ Diagnostics diagnostics_; - base::WeakPtrFactory<IndexedDBTransaction> ptr_factory_; + base::WeakPtrFactory<IndexedDBTransaction> ptr_factory_{this}; }; } // namespace content
diff --git a/content/browser/indexed_db/scopes/disjoint_range_lock_manager.cc b/content/browser/indexed_db/scopes/disjoint_range_lock_manager.cc index a18c6cd..e278ba1 100644 --- a/content/browser/indexed_db/scopes/disjoint_range_lock_manager.cc +++ b/content/browser/indexed_db/scopes/disjoint_range_lock_manager.cc
@@ -28,8 +28,7 @@ DisjointRangeLockManager::Lock&&) = default; DisjointRangeLockManager::DisjointRangeLockManager(int level_count) - : task_runner_(base::SequencedTaskRunnerHandle::Get()), - weak_factory_(this) { + : task_runner_(base::SequencedTaskRunnerHandle::Get()) { locks_.resize(level_count); }
diff --git a/content/browser/indexed_db/scopes/disjoint_range_lock_manager.h b/content/browser/indexed_db/scopes/disjoint_range_lock_manager.h index ed5808e..3e917621 100644 --- a/content/browser/indexed_db/scopes/disjoint_range_lock_manager.h +++ b/content/browser/indexed_db/scopes/disjoint_range_lock_manager.h
@@ -115,7 +115,7 @@ std::vector<LockLevelMap> locks_; SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<DisjointRangeLockManager> weak_factory_; + base::WeakPtrFactory<DisjointRangeLockManager> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DisjointRangeLockManager); };
diff --git a/content/browser/indexed_db/scopes/leveldb_scopes.cc b/content/browser/indexed_db/scopes/leveldb_scopes.cc index bd5ea14..77b287e 100644 --- a/content/browser/indexed_db/scopes/leveldb_scopes.cc +++ b/content/browser/indexed_db/scopes/leveldb_scopes.cc
@@ -36,8 +36,7 @@ max_write_batch_size_bytes_(max_write_batch_size), level_db_(std::move(level_db)), lock_manager_(lock_manager), - failure_callback_(std::move(failure_callback)), - weak_factory_(this) {} + failure_callback_(std::move(failure_callback)) {} LevelDBScopes::~LevelDBScopes() = default;
diff --git a/content/browser/indexed_db/scopes/leveldb_scopes.h b/content/browser/indexed_db/scopes/leveldb_scopes.h index 433ba638..fe20fba 100644 --- a/content/browser/indexed_db/scopes/leveldb_scopes.h +++ b/content/browser/indexed_db/scopes/leveldb_scopes.h
@@ -124,7 +124,7 @@ bool initialize_called_ = false; #endif - base::WeakPtrFactory<LevelDBScopes> weak_factory_; + base::WeakPtrFactory<LevelDBScopes> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LevelDBScopes); };
diff --git a/content/browser/indexed_db/scopes/scopes_lock_manager.cc b/content/browser/indexed_db/scopes/scopes_lock_manager.cc index 709f5798..02ced2a 100644 --- a/content/browser/indexed_db/scopes/scopes_lock_manager.cc +++ b/content/browser/indexed_db/scopes/scopes_lock_manager.cc
@@ -15,7 +15,7 @@ ScopesLocksHolder::ScopesLocksHolder() = default; ScopesLocksHolder::~ScopesLocksHolder() = default; -ScopesLockManager::ScopesLockManager() : weak_factory_(this) {} +ScopesLockManager::ScopesLockManager() {} ScopesLockManager::~ScopesLockManager() = default; ScopesLockManager::ScopeLockRequest::ScopeLockRequest(int level,
diff --git a/content/browser/indexed_db/scopes/scopes_lock_manager.h b/content/browser/indexed_db/scopes/scopes_lock_manager.h index eaa4ace..8d04437b 100644 --- a/content/browser/indexed_db/scopes/scopes_lock_manager.h +++ b/content/browser/indexed_db/scopes/scopes_lock_manager.h
@@ -74,7 +74,7 @@ private: DISALLOW_COPY_AND_ASSIGN(ScopesLockManager); - base::WeakPtrFactory<ScopesLockManager> weak_factory_; + base::WeakPtrFactory<ScopesLockManager> weak_factory_{this}; }; CONTENT_EXPORT bool operator<(const ScopesLockManager::ScopeLockRequest& x,
diff --git a/content/browser/indexed_db/transaction_impl.cc b/content/browser/indexed_db/transaction_impl.cc index 8ba3fc3f..3c3a56b 100644 --- a/content/browser/indexed_db/transaction_impl.cc +++ b/content/browser/indexed_db/transaction_impl.cc
@@ -77,8 +77,7 @@ indexed_db_context_(dispatcher_host->context()), transaction_(std::move(transaction)), origin_(origin), - idb_runner_(std::move(idb_runner)), - weak_factory_(this) { + idb_runner_(std::move(idb_runner)) { DCHECK(idb_runner_->RunsTasksInCurrentSequence()); DCHECK(dispatcher_host_); DCHECK(transaction_);
diff --git a/content/browser/indexed_db/transaction_impl.h b/content/browser/indexed_db/transaction_impl.h index 996398b..7428e22 100644 --- a/content/browser/indexed_db/transaction_impl.h +++ b/content/browser/indexed_db/transaction_impl.h
@@ -64,7 +64,7 @@ SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<TransactionImpl> weak_factory_; + base::WeakPtrFactory<TransactionImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TransactionImpl); };
diff --git a/content/browser/loader/cross_site_document_resource_handler.cc b/content/browser/loader/cross_site_document_resource_handler.cc index 8bbfacaa..8bc3ce2 100644 --- a/content/browser/loader/cross_site_document_resource_handler.cc +++ b/content/browser/loader/cross_site_document_resource_handler.cc
@@ -139,8 +139,7 @@ network::mojom::RequestMode request_mode) : LayeredResourceHandler(request, std::move(next_handler)), weak_next_handler_(next_handler_.get()), - request_mode_(request_mode), - weak_this_(this) {} + request_mode_(request_mode) {} CrossSiteDocumentResourceHandler::~CrossSiteDocumentResourceHandler() {}
diff --git a/content/browser/loader/cross_site_document_resource_handler.h b/content/browser/loader/cross_site_document_resource_handler.h index b2177bf1..86cec927 100644 --- a/content/browser/loader/cross_site_document_resource_handler.h +++ b/content/browser/loader/cross_site_document_resource_handler.h
@@ -163,7 +163,7 @@ // response should fail with net::ERR_BLOCKED_BY_RESPONSE error code). bool blocked_by_cross_origin_resource_policy_ = false; - base::WeakPtrFactory<CrossSiteDocumentResourceHandler> weak_this_; + base::WeakPtrFactory<CrossSiteDocumentResourceHandler> weak_this_{this}; DISALLOW_COPY_AND_ASSIGN(CrossSiteDocumentResourceHandler); };
diff --git a/content/browser/loader/intercepting_resource_handler.cc b/content/browser/loader/intercepting_resource_handler.cc index 2bf460b8..ec1f0060 100644 --- a/content/browser/loader/intercepting_resource_handler.cc +++ b/content/browser/loader/intercepting_resource_handler.cc
@@ -68,9 +68,7 @@ InterceptingResourceHandler::InterceptingResourceHandler( std::unique_ptr<ResourceHandler> next_handler, net::URLRequest* request) - : LayeredResourceHandler(request, std::move(next_handler)), - weak_ptr_factory_(this) { -} + : LayeredResourceHandler(request, std::move(next_handler)) {} InterceptingResourceHandler::~InterceptingResourceHandler() {}
diff --git a/content/browser/loader/intercepting_resource_handler.h b/content/browser/loader/intercepting_resource_handler.h index 2b71045..c791657c 100644 --- a/content/browser/loader/intercepting_resource_handler.h +++ b/content/browser/loader/intercepting_resource_handler.h
@@ -177,7 +177,7 @@ // True if the request was resumed while |in_do_loop_| was true; bool advance_to_next_state_ = false; - base::WeakPtrFactory<InterceptingResourceHandler> weak_ptr_factory_; + base::WeakPtrFactory<InterceptingResourceHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(InterceptingResourceHandler); };
diff --git a/content/browser/loader/mime_sniffing_resource_handler.cc b/content/browser/loader/mime_sniffing_resource_handler.cc index d7e76819..660ae5b 100644 --- a/content/browser/loader/mime_sniffing_resource_handler.cc +++ b/content/browser/loader/mime_sniffing_resource_handler.cc
@@ -132,8 +132,7 @@ intercepting_handler_(intercepting_handler), request_context_type_(request_context_type), in_state_loop_(false), - advance_state_(false), - weak_ptr_factory_(this) { + advance_state_(false) { } MimeSniffingResourceHandler::~MimeSniffingResourceHandler() {}
diff --git a/content/browser/loader/mime_sniffing_resource_handler.h b/content/browser/loader/mime_sniffing_resource_handler.h index 350576d..d314053 100644 --- a/content/browser/loader/mime_sniffing_resource_handler.h +++ b/content/browser/loader/mime_sniffing_resource_handler.h
@@ -209,7 +209,7 @@ // the next state when control returns to the AdvanceState loop. bool advance_state_; - base::WeakPtrFactory<MimeSniffingResourceHandler> weak_ptr_factory_; + base::WeakPtrFactory<MimeSniffingResourceHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MimeSniffingResourceHandler); };
diff --git a/content/browser/loader/mock_resource_loader.cc b/content/browser/loader/mock_resource_loader.cc index a6e1719..c097b5e 100644 --- a/content/browser/loader/mock_resource_loader.cc +++ b/content/browser/loader/mock_resource_loader.cc
@@ -44,7 +44,7 @@ }; MockResourceLoader::MockResourceLoader(ResourceHandler* resource_handler) - : resource_handler_(resource_handler), weak_factory_(this) { + : resource_handler_(resource_handler) { resource_handler_->SetDelegate(this); }
diff --git a/content/browser/loader/mock_resource_loader.h b/content/browser/loader/mock_resource_loader.h index 0615cd6..f739e1ce 100644 --- a/content/browser/loader/mock_resource_loader.h +++ b/content/browser/loader/mock_resource_loader.h
@@ -112,7 +112,7 @@ std::unique_ptr<base::RunLoop> canceled_or_idle_run_loop_; - base::WeakPtrFactory<MockResourceLoader> weak_factory_; + base::WeakPtrFactory<MockResourceLoader> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MockResourceLoader); };
diff --git a/content/browser/loader/mojo_async_resource_handler.cc b/content/browser/loader/mojo_async_resource_handler.cc index 37800b24..6a54037 100644 --- a/content/browser/loader/mojo_async_resource_handler.cc +++ b/content/browser/loader/mojo_async_resource_handler.cc
@@ -117,8 +117,8 @@ mojo::SimpleWatcher::ArmingPolicy::MANUAL, base::SequencedTaskRunnerHandle::Get()), url_loader_client_(std::move(url_loader_client)), - report_transfer_size_async_timer_(std::make_unique<base::OneShotTimer>()), - weak_factory_(this) { + report_transfer_size_async_timer_( + std::make_unique<base::OneShotTimer>()) { DCHECK(IsResourceTypeFrame(resource_type) || resource_type == ResourceType::kServiceWorker || !(url_loader_options_ &
diff --git a/content/browser/loader/mojo_async_resource_handler.h b/content/browser/loader/mojo_async_resource_handler.h index d705c83..6d55e74 100644 --- a/content/browser/loader/mojo_async_resource_handler.h +++ b/content/browser/loader/mojo_async_resource_handler.h
@@ -181,7 +181,7 @@ base::TimeTicks earliest_time_next_transfer_size_report_; int64_t reported_total_received_bytes_ = 0; - base::WeakPtrFactory<MojoAsyncResourceHandler> weak_factory_; + base::WeakPtrFactory<MojoAsyncResourceHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MojoAsyncResourceHandler); };
diff --git a/content/browser/loader/navigation_loader_interceptor.h b/content/browser/loader/navigation_loader_interceptor.h index b8bc73b..73f734d 100644 --- a/content/browser/loader/navigation_loader_interceptor.h +++ b/content/browser/loader/navigation_loader_interceptor.h
@@ -83,6 +83,8 @@ // requests going forward. Subclasses who want to set-up custom loader for // subresource requests may want to override this. // + // This is always called after MaybeCreateLoader(). + // // Note that the handler can return a null callback to MaybeCreateLoader(), // and at the same time can return non-null SubresourceLoaderParams here if it // does NOT want to handle the specific request given to MaybeCreateLoader()
diff --git a/content/browser/loader/navigation_url_loader_impl.cc b/content/browser/loader/navigation_url_loader_impl.cc index e2fcd8d..07a6b22 100644 --- a/content/browser/loader/navigation_url_loader_impl.cc +++ b/content/browser/loader/navigation_url_loader_impl.cc
@@ -363,8 +363,7 @@ proxied_factory_info_(std::move(proxied_factory_info)), known_schemes_(std::move(known_schemes)), bypass_redirect_checks_(bypass_redirect_checks), - browser_context_(browser_context), - weak_factory_(this) {} + browser_context_(browser_context) {} ~URLLoaderRequestController() override { DCHECK_CURRENTLY_ON(GetLoaderRequestControllerThreadID()); @@ -519,29 +518,34 @@ base::Unretained(upload_file_system_context), base::Unretained(appcache_handle_core)); - StartInternal(request_info_.get(), service_worker_navigation_handle_core, - nullptr /* appcache_handle_core */, + StartInternal(request_info_.get(), + /*service_worker_navigation_handle=*/nullptr, + service_worker_navigation_handle_core, + /*appcache_handle_core=*/nullptr, std::move(prefetched_signed_exchange_cache), std::move(signed_exchange_prefetch_metric_recorder), - {} /* factory_for_webui */, url_request_context_getter, + /*factory_for_webui=*/{}, url_request_context_getter, std::move(accept_langs)); } - void Start( - std::unique_ptr<network::SharedURLLoaderFactoryInfo> - network_loader_factory_info, - ServiceWorkerNavigationHandleCore* service_worker_navigation_handle_core, - AppCacheNavigationHandleCore* appcache_handle_core, - scoped_refptr<PrefetchedSignedExchangeCache> - prefetched_signed_exchange_cache, - scoped_refptr<SignedExchangePrefetchMetricRecorder> - signed_exchange_prefetch_metric_recorder, - std::unique_ptr<NavigationRequestInfo> request_info, - std::unique_ptr<NavigationUIData> navigation_ui_data, - network::mojom::URLLoaderFactoryPtrInfo factory_for_webui, - bool needs_loader_factory_interceptor, - base::Time ui_post_time, - std::string accept_langs) { + // This can be called on the UI or IO thread. + void Start(std::unique_ptr<network::SharedURLLoaderFactoryInfo> + network_loader_factory_info, + ServiceWorkerNavigationHandle* + service_worker_navigation_handle /* for UI thread only */, + ServiceWorkerNavigationHandleCore* + service_worker_navigation_handle_core /* for IO thread only */, + AppCacheNavigationHandleCore* appcache_handle_core, + scoped_refptr<PrefetchedSignedExchangeCache> + prefetched_signed_exchange_cache, + scoped_refptr<SignedExchangePrefetchMetricRecorder> + signed_exchange_prefetch_metric_recorder, + std::unique_ptr<NavigationRequestInfo> request_info, + std::unique_ptr<NavigationUIData> navigation_ui_data, + network::mojom::URLLoaderFactoryPtrInfo factory_for_webui, + bool needs_loader_factory_interceptor, + base::Time ui_post_time, + std::string accept_langs) { DCHECK_CURRENTLY_ON(GetLoaderRequestControllerThreadID()); DCHECK(base::FeatureList::IsEnabled(network::features::kNetworkService)); DCHECK(!started_); @@ -583,25 +587,32 @@ CHECK(result && blob_handles_.empty()); } - StartInternal( - request_info.get(), service_worker_navigation_handle_core, - appcache_handle_core, std::move(prefetched_signed_exchange_cache), - std::move(signed_exchange_prefetch_metric_recorder), - std::move(factory_for_webui), nullptr /* url_request_context_getter */, - std::move(accept_langs)); + StartInternal(request_info.get(), service_worker_navigation_handle, + service_worker_navigation_handle_core, appcache_handle_core, + std::move(prefetched_signed_exchange_cache), + std::move(signed_exchange_prefetch_metric_recorder), + std::move(factory_for_webui), + nullptr /* url_request_context_getter */, + std::move(accept_langs)); } // Common setup routines, called by both StartWithoutNetworkService() and - // Start(). Most parameters (except for |request_info| and + // Start() and can be called either on the UI or IO thread. + // + // Most parameters (except for |request_info| and // |url_request_context_getter|) are for setting up feature-specific // loaders and interceptors, and they can be null depending on the flags. // |url_request_context_getter| is non-null only for non-NetworkService // code paths. + // // TODO(kinuko): Merge this back to Start() once NetworkService is fully // shipped. void StartInternal( NavigationRequestInfo* request_info, - ServiceWorkerNavigationHandleCore* service_worker_navigation_handle_core, + ServiceWorkerNavigationHandle* + service_worker_navigation_handle /* ui thread only */, + ServiceWorkerNavigationHandleCore* + service_worker_navigation_handle_core /* io thread only */, AppCacheNavigationHandleCore* appcache_handle_core, scoped_refptr<PrefetchedSignedExchangeCache> prefetched_signed_exchange_cache, @@ -610,6 +621,8 @@ network::mojom::URLLoaderFactoryPtrInfo factory_for_webui, net::URLRequestContextGetter* url_request_context_getter, std::string accept_langs) { + DCHECK_CURRENTLY_ON(GetLoaderRequestControllerThreadID()); + std::string accept_value = network::kFrameAcceptHeader; // TODO(http://crbug.com/824840): Make this work on UI thread. if (!IsNavigationLoaderOnUIEnabled()) { @@ -650,7 +663,7 @@ } if (IsNavigationLoaderOnUIEnabled()) { - CreateInterceptorsForUI(request_info); + CreateInterceptorsForUI(request_info, service_worker_navigation_handle); } else { CreateInterceptorsForIO( request_info, service_worker_navigation_handle_core, @@ -679,7 +692,21 @@ Restart(); } - void CreateInterceptorsForUI(NavigationRequestInfo* request_info) { + void CreateInterceptorsForUI( + NavigationRequestInfo* request_info, + ServiceWorkerNavigationHandle* service_worker_navigation_handle) { + // Set up an interceptor for service workers. + if (service_worker_navigation_handle) { + std::unique_ptr<NavigationLoaderInterceptor> service_worker_interceptor = + ServiceWorkerRequestHandler::CreateForNavigationUI( + resource_request_->url, service_worker_navigation_handle, + *request_info); + // The interceptor may not be created in certain cases (e.g., the origin + // is not secure). + if (service_worker_interceptor) + interceptors_.push_back(std::move(service_worker_interceptor)); + } + // See if embedders want to add interceptors. std::vector<std::unique_ptr<URLLoaderRequestInterceptor>> browser_interceptors = @@ -722,7 +749,7 @@ // Set-up an interceptor for service workers. if (service_worker_navigation_handle_core) { std::unique_ptr<NavigationLoaderInterceptor> service_worker_interceptor = - ServiceWorkerRequestHandler::CreateForNavigation( + ServiceWorkerRequestHandler::CreateForNavigationIO( resource_request_->url, service_worker_navigation_handle_core, *request_info, &service_worker_provider_host_); // The interceptor for service worker may not be created for some @@ -1560,7 +1587,7 @@ network::ResourceResponseHead head_; mojo::ScopedDataPipeConsumerHandle response_body_; - mutable base::WeakPtrFactory<URLLoaderRequestController> weak_factory_; + mutable base::WeakPtrFactory<URLLoaderRequestController> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(URLLoaderRequestController); }; @@ -1581,8 +1608,7 @@ std::vector<std::unique_ptr<NavigationLoaderInterceptor>> initial_interceptors) : delegate_(delegate), - download_policy_(request_info->common_params.download_policy), - weak_factory_(this) { + download_policy_(request_info->common_params.download_policy) { DCHECK_CURRENTLY_ON(BrowserThread::UI); int frame_tree_node_id = request_info->frame_tree_node_id; @@ -1758,7 +1784,7 @@ base::BindOnce( &URLLoaderRequestController::Start, base::Unretained(request_controller_.get()), - std::move(network_factory_info), + std::move(network_factory_info), service_worker_navigation_handle, service_worker_navigation_handle_core, appcache_handle_core, std::move(prefetched_signed_exchange_cache), std::move(signed_exchange_prefetch_metric_recorder),
diff --git a/content/browser/loader/navigation_url_loader_impl.h b/content/browser/loader/navigation_url_loader_impl.h index 523ccbaf..f49c6c5 100644 --- a/content/browser/loader/navigation_url_loader_impl.h +++ b/content/browser/loader/navigation_url_loader_impl.h
@@ -133,7 +133,7 @@ // Counts the time overhead of all the hops from the IO to the UI threads. base::TimeDelta io_to_ui_time_; - base::WeakPtrFactory<NavigationURLLoaderImpl> weak_factory_; + base::WeakPtrFactory<NavigationURLLoaderImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(NavigationURLLoaderImpl); };
diff --git a/content/browser/loader/resource_dispatcher_host_impl.cc b/content/browser/loader/resource_dispatcher_host_impl.cc index c4db9c9..577daea 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.cc +++ b/content/browser/loader/resource_dispatcher_host_impl.cc
@@ -228,7 +228,7 @@ class LoginDelegateProxy : public LoginDelegate { public: explicit LoginDelegateProxy(LoginAuthRequiredCallback callback) - : callback_(std::move(callback)), weak_factory_(this) { + : callback_(std::move(callback)) { delegate_ui_.reset(new DelegateOwnerUI(weak_factory_.GetWeakPtr())); } @@ -309,7 +309,7 @@ std::unique_ptr<DelegateOwnerUI, BrowserThread::DeleteOnUIThread> delegate_ui_; LoginAuthRequiredCallback callback_; - base::WeakPtrFactory<LoginDelegateProxy> weak_factory_; + base::WeakPtrFactory<LoginDelegateProxy> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LoginDelegateProxy); }; @@ -371,8 +371,7 @@ loader_delegate_(nullptr), create_download_handler_intercept_(download_handler_intercept), main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()), - io_thread_task_runner_(io_thread_runner), - weak_factory_on_io_(this) { + io_thread_task_runner_(io_thread_runner) { DCHECK(main_thread_task_runner_->BelongsToCurrentThread()); DCHECK(!g_resource_dispatcher_host); g_resource_dispatcher_host = this;
diff --git a/content/browser/loader/resource_dispatcher_host_impl.h b/content/browser/loader/resource_dispatcher_host_impl.h index e6f8e75..936d45f 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.h +++ b/content/browser/loader/resource_dispatcher_host_impl.h
@@ -707,7 +707,7 @@ // Used on the IO thread to allow PostTaskAndReply replies to the IO thread // to be abandoned if they run after OnShutdown(). - base::WeakPtrFactory<ResourceDispatcherHostImpl> weak_factory_on_io_; + base::WeakPtrFactory<ResourceDispatcherHostImpl> weak_factory_on_io_{this}; DISALLOW_COPY_AND_ASSIGN(ResourceDispatcherHostImpl); };
diff --git a/content/browser/loader/resource_loader.cc b/content/browser/loader/resource_loader.cc index dbec9c9..4296215 100644 --- a/content/browser/loader/resource_loader.cc +++ b/content/browser/loader/resource_loader.cc
@@ -246,8 +246,7 @@ started_request_(false), times_cancelled_after_request_start_(0), resource_context_(resource_context), - throttling_token_(std::move(throttling_token)), - weak_ptr_factory_(this) { + throttling_token_(std::move(throttling_token)) { request_->set_delegate(this); handler_->SetDelegate(this); }
diff --git a/content/browser/loader/resource_loader.h b/content/browser/loader/resource_loader.h index 8c2ae61..f7a24bea 100644 --- a/content/browser/loader/resource_loader.h +++ b/content/browser/loader/resource_loader.h
@@ -210,7 +210,7 @@ base::ThreadChecker thread_checker_; - base::WeakPtrFactory<ResourceLoader> weak_ptr_factory_; + base::WeakPtrFactory<ResourceLoader> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ResourceLoader); };
diff --git a/content/browser/loader/resource_loader_unittest.cc b/content/browser/loader/resource_loader_unittest.cc index 4db6d4d..47ef262 100644 --- a/content/browser/loader/resource_loader_unittest.cc +++ b/content/browser/loader/resource_loader_unittest.cc
@@ -156,8 +156,7 @@ public: MockClientCertURLRequestJob(net::URLRequest* request, net::NetworkDelegate* network_delegate) - : net::URLRequestTestJob(request, network_delegate), - weak_factory_(this) {} + : net::URLRequestTestJob(request, network_delegate) {} static std::vector<std::string> test_authorities() { return std::vector<std::string>(1, "dummy"); @@ -183,7 +182,7 @@ private: ~MockClientCertURLRequestJob() override {} - base::WeakPtrFactory<MockClientCertURLRequestJob> weak_factory_; + base::WeakPtrFactory<MockClientCertURLRequestJob> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MockClientCertURLRequestJob); };
diff --git a/content/browser/loader/resource_message_filter.cc b/content/browser/loader/resource_message_filter.cc index 585999c..8b78d64b 100644 --- a/content/browser/loader/resource_message_filter.cc +++ b/content/browser/loader/resource_message_filter.cc
@@ -54,8 +54,7 @@ file_system_context, get_contexts_callback)), prefetch_url_loader_service_(prefetch_url_loader_service), - io_thread_task_runner_(io_thread_runner), - weak_ptr_factory_(this) {} + io_thread_task_runner_(io_thread_runner) {} ResourceMessageFilter::~ResourceMessageFilter() { DCHECK(io_thread_task_runner_->BelongsToCurrentThread());
diff --git a/content/browser/loader/resource_message_filter.h b/content/browser/loader/resource_message_filter.h index 7be03ea9..c29fa420f 100644 --- a/content/browser/loader/resource_message_filter.h +++ b/content/browser/loader/resource_message_filter.h
@@ -122,7 +122,7 @@ scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner_; // This must come last to make sure weak pointers are invalidated first. - base::WeakPtrFactory<ResourceMessageFilter> weak_ptr_factory_; + base::WeakPtrFactory<ResourceMessageFilter> weak_ptr_factory_{this}; DISALLOW_IMPLICIT_CONSTRUCTORS(ResourceMessageFilter); };
diff --git a/content/browser/loader/source_stream_to_data_pipe.cc b/content/browser/loader/source_stream_to_data_pipe.cc index 8061f61..42793d7 100644 --- a/content/browser/loader/source_stream_to_data_pipe.cc +++ b/content/browser/loader/source_stream_to_data_pipe.cc
@@ -18,8 +18,7 @@ completion_callback_(std::move(completion_callback)), writable_handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, - base::SequencedTaskRunnerHandle::Get()), - weak_factory_(this) { + base::SequencedTaskRunnerHandle::Get()) { writable_handle_watcher_.Watch( dest_.get(), MOJO_HANDLE_SIGNAL_WRITABLE, base::BindRepeating(&SourceStreamToDataPipe::OnDataPipeWritable,
diff --git a/content/browser/loader/source_stream_to_data_pipe.h b/content/browser/loader/source_stream_to_data_pipe.h index 7ba2daf..f909755a 100644 --- a/content/browser/loader/source_stream_to_data_pipe.h +++ b/content/browser/loader/source_stream_to_data_pipe.h
@@ -48,7 +48,7 @@ scoped_refptr<network::NetToMojoPendingBuffer> pending_write_; mojo::SimpleWatcher writable_handle_watcher_; - base::WeakPtrFactory<SourceStreamToDataPipe> weak_factory_; + base::WeakPtrFactory<SourceStreamToDataPipe> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/loader/test_resource_handler.cc b/content/browser/loader/test_resource_handler.cc index 7fc81cd..6dc382e 100644 --- a/content/browser/loader/test_resource_handler.cc +++ b/content/browser/loader/test_resource_handler.cc
@@ -38,8 +38,7 @@ : ResourceHandler(nullptr), request_status_ptr_(request_status), body_ptr_(body), - deferred_run_loop_(new base::RunLoop()), - weak_ptr_factory_(this) { + deferred_run_loop_(new base::RunLoop()) { SetBufferSize(2048); }
diff --git a/content/browser/loader/test_resource_handler.h b/content/browser/loader/test_resource_handler.h index 21ea03c..da30b244 100644 --- a/content/browser/loader/test_resource_handler.h +++ b/content/browser/loader/test_resource_handler.h
@@ -219,7 +219,7 @@ base::RunLoop response_complete_run_loop_; - base::WeakPtrFactory<TestResourceHandler> weak_ptr_factory_; + base::WeakPtrFactory<TestResourceHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TestResourceHandler); };
diff --git a/content/browser/locks/lock_manager.cc b/content/browser/locks/lock_manager.cc index 4fedfea..57f93e4c 100644 --- a/content/browser/locks/lock_manager.cc +++ b/content/browser/locks/lock_manager.cc
@@ -142,7 +142,7 @@ mojo::StrongAssociatedBindingPtr<blink::mojom::LockHandle> handle_; }; -LockManager::LockManager() : weak_ptr_factory_(this) {} +LockManager::LockManager() {} LockManager::~LockManager() = default;
diff --git a/content/browser/locks/lock_manager.h b/content/browser/locks/lock_manager.h index 2afc2b57..d123c0c 100644 --- a/content/browser/locks/lock_manager.h +++ b/content/browser/locks/lock_manager.h
@@ -79,7 +79,7 @@ std::map<url::Origin, OriginState> origins_; SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<LockManager> weak_ptr_factory_; + base::WeakPtrFactory<LockManager> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LockManager); };
diff --git a/content/browser/media/audio_loopback_stream_broker.cc b/content/browser/media/audio_loopback_stream_broker.cc index 474758e..fe58169 100644 --- a/content/browser/media/audio_loopback_stream_broker.cc +++ b/content/browser/media/audio_loopback_stream_broker.cc
@@ -32,8 +32,7 @@ shared_memory_count_(shared_memory_count), deleter_(std::move(deleter)), renderer_factory_client_(std::move(renderer_factory_client)), - observer_binding_(this), - weak_ptr_factory_(this) { + observer_binding_(this) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(source_); DCHECK(renderer_factory_client_);
diff --git a/content/browser/media/audio_loopback_stream_broker.h b/content/browser/media/audio_loopback_stream_broker.h index aa1f6f6..65d8f051 100644 --- a/content/browser/media/audio_loopback_stream_broker.h +++ b/content/browser/media/audio_loopback_stream_broker.h
@@ -76,7 +76,7 @@ mojo::Binding<AudioInputStreamObserver> observer_binding_; media::mojom::AudioInputStreamClientRequest client_request_; - base::WeakPtrFactory<AudioLoopbackStreamBroker> weak_ptr_factory_; + base::WeakPtrFactory<AudioLoopbackStreamBroker> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AudioLoopbackStreamBroker); };
diff --git a/content/browser/media/audio_output_stream_broker.cc b/content/browser/media/audio_output_stream_broker.cc index cf1d1c25..0ce7411 100644 --- a/content/browser/media/audio_output_stream_broker.cc +++ b/content/browser/media/audio_output_stream_broker.cc
@@ -78,8 +78,7 @@ deleter_(std::move(deleter)), client_(std::move(client)), observer_(render_process_id, render_frame_id, stream_id), - observer_receiver_(&observer_), - weak_ptr_factory_(this) { + observer_receiver_(&observer_) { DCHECK(client_); DCHECK(deleter_); DCHECK(group_id_);
diff --git a/content/browser/media/audio_output_stream_broker.h b/content/browser/media/audio_output_stream_broker.h index 8951853..af4f5d9 100644 --- a/content/browser/media/audio_output_stream_broker.h +++ b/content/browser/media/audio_output_stream_broker.h
@@ -75,7 +75,7 @@ DisconnectReason disconnect_reason_ = DisconnectReason::kDocumentDestroyed; - base::WeakPtrFactory<AudioOutputStreamBroker> weak_ptr_factory_; + base::WeakPtrFactory<AudioOutputStreamBroker> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AudioOutputStreamBroker); };
diff --git a/content/browser/media/capture/desktop_capture_device.cc b/content/browser/media/capture/desktop_capture_device.cc index e351d04e..bc04d73 100644 --- a/content/browser/media/capture/desktop_capture_device.cc +++ b/content/browser/media/capture/desktop_capture_device.cc
@@ -197,7 +197,7 @@ // screen from sleeping for the drive-by web. device::mojom::WakeLockPtr wake_lock_; - base::WeakPtrFactory<Core> weak_factory_; + base::WeakPtrFactory<Core> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(Core); }; @@ -213,8 +213,7 @@ capture_in_progress_(false), first_capture_returned_(false), first_permanent_error_logged(false), - capturer_type_(type), - weak_factory_(this) {} + capturer_type_(type) {} DesktopCaptureDevice::Core::~Core() { DCHECK(task_runner_->BelongsToCurrentThread());
diff --git a/content/browser/media/capture/frame_sink_video_capture_device.cc b/content/browser/media/capture/frame_sink_video_capture_device.cc index edb2b9e..ccda5c5 100644 --- a/content/browser/media/capture/frame_sink_video_capture_device.cc +++ b/content/browser/media/capture/frame_sink_video_capture_device.cc
@@ -67,8 +67,7 @@ FrameSinkVideoCaptureDevice::FrameSinkVideoCaptureDevice() : cursor_controller_( - RescopeToUIThread(std::make_unique<MouseCursorOverlayController>())), - weak_factory_(this) { + RescopeToUIThread(std::make_unique<MouseCursorOverlayController>())) { DCHECK(cursor_controller_); }
diff --git a/content/browser/media/capture/frame_sink_video_capture_device.h b/content/browser/media/capture/frame_sink_video_capture_device.h index c130686..1547a01d 100644 --- a/content/browser/media/capture/frame_sink_video_capture_device.h +++ b/content/browser/media/capture/frame_sink_video_capture_device.h
@@ -168,7 +168,7 @@ device::mojom::WakeLockPtr wake_lock_; // Creates WeakPtrs for use on the device thread. - base::WeakPtrFactory<FrameSinkVideoCaptureDevice> weak_factory_; + base::WeakPtrFactory<FrameSinkVideoCaptureDevice> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FrameSinkVideoCaptureDevice); };
diff --git a/content/browser/media/capture/mouse_cursor_overlay_controller.h b/content/browser/media/capture/mouse_cursor_overlay_controller.h index 5902ac6d..100ac4a5 100644 --- a/content/browser/media/capture/mouse_cursor_overlay_controller.h +++ b/content/browser/media/capture/mouse_cursor_overlay_controller.h
@@ -145,7 +145,7 @@ // called on the UI BrowserThread. SEQUENCE_CHECKER(ui_sequence_checker_); - base::WeakPtrFactory<MouseCursorOverlayController> weak_factory_; + base::WeakPtrFactory<MouseCursorOverlayController> weak_factory_{this}; // Minium movement before the cursor has been considered intentionally moved // by the user.
diff --git a/content/browser/media/capture/mouse_cursor_overlay_controller_aura.cc b/content/browser/media/capture/mouse_cursor_overlay_controller_aura.cc index 73768c5..2d642ca6 100644 --- a/content/browser/media/capture/mouse_cursor_overlay_controller_aura.cc +++ b/content/browser/media/capture/mouse_cursor_overlay_controller_aura.cc
@@ -127,7 +127,7 @@ }; MouseCursorOverlayController::MouseCursorOverlayController() - : mouse_move_behavior_atomic_(kNotMoving), weak_factory_(this) { + : mouse_move_behavior_atomic_(kNotMoving) { // MouseCursorOverlayController can be constructed on any thread, but // thereafter must be used according to class-level comments. DETACH_FROM_SEQUENCE(ui_sequence_checker_);
diff --git a/content/browser/media/cdm_file_impl.cc b/content/browser/media/cdm_file_impl.cc index ab55ff4..d20c292 100644 --- a/content/browser/media/cdm_file_impl.cc +++ b/content/browser/media/cdm_file_impl.cc
@@ -215,8 +215,7 @@ origin_(origin), file_system_id_(file_system_id), file_system_root_uri_(file_system_root_uri), - file_system_context_(file_system_context), - weak_factory_(this) { + file_system_context_(file_system_context) { DVLOG(3) << __func__ << " " << file_name_; DCHECK(IsValidName(file_name_)); }
diff --git a/content/browser/media/cdm_file_impl.h b/content/browser/media/cdm_file_impl.h index e34e77c..1133508 100644 --- a/content/browser/media/cdm_file_impl.h +++ b/content/browser/media/cdm_file_impl.h
@@ -110,7 +110,7 @@ std::vector<uint8_t> data_; THREAD_CHECKER(thread_checker_); - base::WeakPtrFactory<CdmFileImpl> weak_factory_; + base::WeakPtrFactory<CdmFileImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CdmFileImpl); };
diff --git a/content/browser/media/cdm_storage_impl.cc b/content/browser/media/cdm_storage_impl.cc index 284cc97..c15e497 100644 --- a/content/browser/media/cdm_storage_impl.cc +++ b/content/browser/media/cdm_storage_impl.cc
@@ -77,8 +77,7 @@ : FrameServiceBase(render_frame_host, std::move(request)), cdm_file_system_id_(cdm_file_system_id), file_system_context_(std::move(file_system_context)), - child_process_id_(render_frame_host->GetProcess()->GetID()), - weak_factory_(this) {} + child_process_id_(render_frame_host->GetProcess()->GetID()) {} CdmStorageImpl::~CdmStorageImpl() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
diff --git a/content/browser/media/cdm_storage_impl.h b/content/browser/media/cdm_storage_impl.h index ce17c8c6..72a289a6 100644 --- a/content/browser/media/cdm_storage_impl.h +++ b/content/browser/media/cdm_storage_impl.h
@@ -95,7 +95,7 @@ // all remaining CdmFile bindings will be closed. mojo::StrongAssociatedBindingSet<media::mojom::CdmFile> cdm_file_bindings_; - base::WeakPtrFactory<CdmStorageImpl> weak_factory_; + base::WeakPtrFactory<CdmStorageImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CdmStorageImpl); };
diff --git a/content/browser/media/forwarding_audio_stream_factory.cc b/content/browser/media/forwarding_audio_stream_factory.cc index ff12ffd6..0ac9c15d 100644 --- a/content/browser/media/forwarding_audio_stream_factory.cc +++ b/content/browser/media/forwarding_audio_stream_factory.cc
@@ -35,8 +35,7 @@ owner_(std::move(owner)), broker_factory_(std::move(broker_factory)), group_id_(base::UnguessableToken::Create()), - connector_(std::move(connector)), - weak_ptr_factory_(this) { + connector_(std::move(connector)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(owner_); DCHECK(broker_factory_); @@ -207,7 +206,7 @@ media::UserInputMonitorBase* user_input_monitor, std::unique_ptr<service_manager::Connector> connector, std::unique_ptr<AudioStreamBrokerFactory> broker_factory) - : WebContentsObserver(web_contents), core_(), weak_ptr_factory_(this) { + : WebContentsObserver(web_contents), core_() { DCHECK_CURRENTLY_ON(BrowserThread::UI); core_ = std::make_unique<Core>(weak_ptr_factory_.GetWeakPtr(), user_input_monitor,
diff --git a/content/browser/media/forwarding_audio_stream_factory.h b/content/browser/media/forwarding_audio_stream_factory.h index 8a995de..6048ba8 100644 --- a/content/browser/media/forwarding_audio_stream_factory.h +++ b/content/browser/media/forwarding_audio_stream_factory.h
@@ -168,7 +168,8 @@ StreamBrokerSet outputs_; base::flat_set<AudioStreamBroker::LoopbackSink*> loopback_sinks_; - base::WeakPtrFactory<ForwardingAudioStreamFactory::Core> weak_ptr_factory_; + base::WeakPtrFactory<ForwardingAudioStreamFactory::Core> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(Core); }; @@ -220,7 +221,7 @@ std::unique_ptr<Core> core_; bool is_muted_ = false; - base::WeakPtrFactory<ForwardingAudioStreamFactory> weak_ptr_factory_; + base::WeakPtrFactory<ForwardingAudioStreamFactory> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ForwardingAudioStreamFactory); };
diff --git a/content/browser/media/forwarding_audio_stream_factory_unittest.cc b/content/browser/media/forwarding_audio_stream_factory_unittest.cc index c7c84bb..3b1c735 100644 --- a/content/browser/media/forwarding_audio_stream_factory_unittest.cc +++ b/content/browser/media/forwarding_audio_stream_factory_unittest.cc
@@ -63,8 +63,7 @@ class MockBroker : public AudioStreamBroker { public: explicit MockBroker(RenderFrameHost* rfh) - : AudioStreamBroker(rfh->GetProcess()->GetID(), rfh->GetRoutingID()), - weak_factory_(this) {} + : AudioStreamBroker(rfh->GetProcess()->GetID(), rfh->GetRoutingID()) {} ~MockBroker() override {} @@ -76,7 +75,7 @@ DeleterCallback deleter; private: - base::WeakPtrFactory<MockBroker> weak_factory_; + base::WeakPtrFactory<MockBroker> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MockBroker); };
diff --git a/content/browser/media/midi_host_unittest.cc b/content/browser/media/midi_host_unittest.cc index d345361..b80cd2ec 100644 --- a/content/browser/media/midi_host_unittest.cc +++ b/content/browser/media/midi_host_unittest.cc
@@ -48,8 +48,7 @@ class FakeMidiManager : public midi::MidiManager { public: - explicit FakeMidiManager(midi::MidiService* service) - : MidiManager(service), weak_factory_(this) {} + explicit FakeMidiManager(midi::MidiService* service) : MidiManager(service) {} ~FakeMidiManager() override = default; base::WeakPtr<FakeMidiManager> GetWeakPtr() { @@ -65,14 +64,14 @@ } std::vector<MidiEvent> events_; - base::WeakPtrFactory<FakeMidiManager> weak_factory_; + base::WeakPtrFactory<FakeMidiManager> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FakeMidiManager); }; class FakeMidiManagerFactory : public midi::MidiService::ManagerFactory { public: - FakeMidiManagerFactory() : weak_factory_(this) {} + FakeMidiManagerFactory() {} ~FakeMidiManagerFactory() override = default; std::unique_ptr<midi::MidiManager> Create( midi::MidiService* service) override { @@ -91,7 +90,7 @@ private: base::WeakPtr<FakeMidiManager> manager_; - base::WeakPtrFactory<FakeMidiManagerFactory> weak_factory_; + base::WeakPtrFactory<FakeMidiManagerFactory> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FakeMidiManagerFactory); };
diff --git a/content/browser/network_service_client.cc b/content/browser/network_service_client.cc index 96a491e..cb60866 100644 --- a/content/browser/network_service_client.cc +++ b/content/browser/network_service_client.cc
@@ -53,7 +53,7 @@ explicit SSLErrorDelegate( network::mojom::NetworkServiceClient::OnSSLCertificateErrorCallback response) - : response_(std::move(response)), weak_factory_(this) {} + : response_(std::move(response)) {} ~SSLErrorDelegate() override {} void CancelSSLRequest(int error, const net::SSLInfo* ssl_info) override { std::move(response_).Run(error); @@ -69,7 +69,7 @@ private: network::mojom::NetworkServiceClient::OnSSLCertificateErrorCallback response_; - base::WeakPtrFactory<SSLErrorDelegate> weak_factory_; + base::WeakPtrFactory<SSLErrorDelegate> weak_factory_{this}; }; // This class lives on the IO thread. It is self-owned and will delete itself @@ -160,8 +160,7 @@ url_(url), response_headers_(std::move(response_headers)), first_auth_attempt_(first_auth_attempt), - web_contents_getter_(web_contents_getter), - weak_factory_(this) { + web_contents_getter_(web_contents_getter) { DCHECK_CURRENTLY_ON(BrowserThread::UI); auth_challenge_responder_.set_connection_error_handler(base::BindOnce( &LoginHandlerDelegate::OnRequestCancelled, base::Unretained(this))); @@ -247,7 +246,7 @@ bool first_auth_attempt_; ResourceRequestInfo::WebContentsGetter web_contents_getter_; std::unique_ptr<LoginDelegate> login_delegate_; - base::WeakPtrFactory<LoginHandlerDelegate> weak_factory_; + base::WeakPtrFactory<LoginHandlerDelegate> weak_factory_{this}; }; void HandleFileUploadRequest(
diff --git a/content/browser/network_service_instance_impl.cc b/content/browser/network_service_instance_impl.cc index 1d8c3893..5915436b 100644 --- a/content/browser/network_service_instance_impl.cc +++ b/content/browser/network_service_instance_impl.cc
@@ -128,16 +128,28 @@ std::string value = command_line.GetSwitchValueASCII(switch_name); if (value == "Default") - return net::NetLogCaptureMode::Default(); - if (value == "IncludeCookiesAndCredentials") - return net::NetLogCaptureMode::IncludeCookiesAndCredentials(); - if (value == "IncludeSocketBytes") - return net::NetLogCaptureMode::IncludeSocketBytes(); + return net::NetLogCaptureMode::kDefault; + if (value == "IncludeSensitive") + return net::NetLogCaptureMode::kIncludeSensitive; + if (value == "Everything") + return net::NetLogCaptureMode::kEverything; + + // Warn when using the old command line switches. + if (value == "IncludeCookiesAndCredentials") { + LOG(ERROR) << "Deprecated value for --" << switch_name + << ". Use IncludeSensitive instead"; + return net::NetLogCaptureMode::kIncludeSensitive; + } + if (value == "IncludeSocketBytes") { + LOG(ERROR) << "Deprecated value for --" << switch_name + << ". Use Everything instead"; + return net::NetLogCaptureMode::kEverything; + } LOG(ERROR) << "Unrecognized value for --" << switch_name; } - return net::NetLogCaptureMode::Default(); + return net::NetLogCaptureMode::kDefault; } } // namespace
diff --git a/content/browser/notifications/notification_storage.cc b/content/browser/notifications/notification_storage.cc index e60e4d9..5e1fa0d 100644 --- a/content/browser/notifications/notification_storage.cc +++ b/content/browser/notifications/notification_storage.cc
@@ -40,8 +40,7 @@ NotificationStorage::NotificationStorage( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context) - : service_worker_context_(std::move(service_worker_context)), - weak_ptr_factory_(this) {} + : service_worker_context_(std::move(service_worker_context)) {} NotificationStorage::~NotificationStorage() = default;
diff --git a/content/browser/notifications/notification_storage.h b/content/browser/notifications/notification_storage.h index 38b92039..7378782 100644 --- a/content/browser/notifications/notification_storage.h +++ b/content/browser/notifications/notification_storage.h
@@ -50,8 +50,8 @@ scoped_refptr<ServiceWorkerContextWrapper> service_worker_context_; - base::WeakPtrFactory<NotificationStorage> - weak_ptr_factory_; // Must be last member. + base::WeakPtrFactory<NotificationStorage> weak_ptr_factory_{ + this}; // Must be last member. }; } // namespace content
diff --git a/content/browser/notifications/platform_notification_service_proxy.cc b/content/browser/notifications/platform_notification_service_proxy.cc index 41c4ac8..c5c1871 100644 --- a/content/browser/notifications/platform_notification_service_proxy.cc +++ b/content/browser/notifications/platform_notification_service_proxy.cc
@@ -25,9 +25,7 @@ browser_context_(browser_context), notification_service_( GetContentClient()->browser()->GetPlatformNotificationService( - browser_context)), - weak_ptr_factory_ui_(this), - weak_ptr_factory_io_(this) {} + browser_context)) {} PlatformNotificationServiceProxy::~PlatformNotificationServiceProxy() = default;
diff --git a/content/browser/notifications/platform_notification_service_proxy.h b/content/browser/notifications/platform_notification_service_proxy.h index 1d0693c..70d20ba 100644 --- a/content/browser/notifications/platform_notification_service_proxy.h +++ b/content/browser/notifications/platform_notification_service_proxy.h
@@ -109,8 +109,10 @@ scoped_refptr<ServiceWorkerContextWrapper> service_worker_context_; BrowserContext* browser_context_; PlatformNotificationService* notification_service_; - base::WeakPtrFactory<PlatformNotificationServiceProxy> weak_ptr_factory_ui_; - base::WeakPtrFactory<PlatformNotificationServiceProxy> weak_ptr_factory_io_; + base::WeakPtrFactory<PlatformNotificationServiceProxy> weak_ptr_factory_ui_{ + this}; + base::WeakPtrFactory<PlatformNotificationServiceProxy> weak_ptr_factory_io_{ + this}; DISALLOW_COPY_AND_ASSIGN(PlatformNotificationServiceProxy); };
diff --git a/content/browser/payments/payment_app_database.cc b/content/browser/payments/payment_app_database.cc index a8e381cb..915a06ab 100644 --- a/content/browser/payments/payment_app_database.cc +++ b/content/browser/payments/payment_app_database.cc
@@ -122,7 +122,7 @@ PaymentAppDatabase::PaymentAppDatabase( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context) - : service_worker_context_(service_worker_context), weak_ptr_factory_(this) { + : service_worker_context_(service_worker_context) { DCHECK_CURRENTLY_ON(BrowserThread::IO); }
diff --git a/content/browser/payments/payment_app_database.h b/content/browser/payments/payment_app_database.h index 2652f8e..9c1cbb4 100644 --- a/content/browser/payments/payment_app_database.h +++ b/content/browser/payments/payment_app_database.h
@@ -225,7 +225,7 @@ blink::ServiceWorkerStatusCode status); scoped_refptr<ServiceWorkerContextWrapper> service_worker_context_; - base::WeakPtrFactory<PaymentAppDatabase> weak_ptr_factory_; + base::WeakPtrFactory<PaymentAppDatabase> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PaymentAppDatabase); };
diff --git a/content/browser/payments/payment_app_provider_impl.cc b/content/browser/payments/payment_app_provider_impl.cc index adc6c6e..f6a4b3f 100644 --- a/content/browser/payments/payment_app_provider_impl.cc +++ b/content/browser/payments/payment_app_provider_impl.cc
@@ -104,8 +104,7 @@ event_type_(event_type), service_worker_version_(service_worker_version), invoke_payment_app_callback_(std::move(callback)), - binding_(this), - weak_ptr_factory_(this) { + binding_(this) { request_id_ = service_worker_version->StartRequest( event_type, base::BindOnce(&RespondWithCallbacks::OnErrorStatus, weak_ptr_factory_.GetWeakPtr())); @@ -122,8 +121,7 @@ event_type_(event_type), service_worker_version_(service_worker_version), payment_event_result_callback_(std::move(callback)), - binding_(this), - weak_ptr_factory_(this) { + binding_(this) { request_id_ = service_worker_version->StartRequest( event_type, base::BindOnce(&RespondWithCallbacks::OnErrorStatus, weak_ptr_factory_.GetWeakPtr())); @@ -250,7 +248,7 @@ PaymentAppProvider::PaymentEventResultCallback payment_event_result_callback_; mojo::Binding<payments::mojom::PaymentHandlerResponseCallback> binding_; - base::WeakPtrFactory<RespondWithCallbacks> weak_ptr_factory_; + base::WeakPtrFactory<RespondWithCallbacks> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RespondWithCallbacks); };
diff --git a/content/browser/payments/payment_manager.cc b/content/browser/payments/payment_manager.cc index f363165..7a5416a3 100644 --- a/content/browser/payments/payment_manager.cc +++ b/content/browser/payments/payment_manager.cc
@@ -26,8 +26,7 @@ PaymentAppContextImpl* payment_app_context, mojo::InterfaceRequest<payments::mojom::PaymentManager> request) : payment_app_context_(payment_app_context), - binding_(this, std::move(request)), - weak_ptr_factory_(this) { + binding_(this, std::move(request)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(payment_app_context);
diff --git a/content/browser/payments/payment_manager.h b/content/browser/payments/payment_manager.h index bb37eca5..b35ec0d2 100644 --- a/content/browser/payments/payment_manager.h +++ b/content/browser/payments/payment_manager.h
@@ -63,7 +63,7 @@ GURL context_url_; GURL scope_; mojo::Binding<payments::mojom::PaymentManager> binding_; - base::WeakPtrFactory<PaymentManager> weak_ptr_factory_; + base::WeakPtrFactory<PaymentManager> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PaymentManager); };
diff --git a/content/browser/permissions/permission_service_impl.cc b/content/browser/permissions/permission_service_impl.cc index 75a05f47..4c5760c 100644 --- a/content/browser/permissions/permission_service_impl.cc +++ b/content/browser/permissions/permission_service_impl.cc
@@ -155,7 +155,7 @@ PermissionServiceImpl::PermissionServiceImpl(PermissionServiceContext* context, const url::Origin& origin) - : context_(context), origin_(origin), weak_factory_(this) {} + : context_(context), origin_(origin) {} PermissionServiceImpl::~PermissionServiceImpl() {}
diff --git a/content/browser/permissions/permission_service_impl.h b/content/browser/permissions/permission_service_impl.h index 8f637196..a1bca4f 100644 --- a/content/browser/permissions/permission_service_impl.h +++ b/content/browser/permissions/permission_service_impl.h
@@ -73,7 +73,7 @@ // context_ owns |this|. PermissionServiceContext* context_; const url::Origin origin_; - base::WeakPtrFactory<PermissionServiceImpl> weak_factory_; + base::WeakPtrFactory<PermissionServiceImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PermissionServiceImpl); };
diff --git a/content/browser/ppapi_plugin_process_host.cc b/content/browser/ppapi_plugin_process_host.cc index 56a1b68..68a9f856 100644 --- a/content/browser/ppapi_plugin_process_host.cc +++ b/content/browser/ppapi_plugin_process_host.cc
@@ -152,9 +152,7 @@ : public network::NetworkConnectionTracker::NetworkConnectionObserver { public: explicit PluginNetworkObserver(PpapiPluginProcessHost* process_host) - : process_host_(process_host), - network_connection_tracker_(nullptr), - weak_factory_(this) { + : process_host_(process_host), network_connection_tracker_(nullptr) { GetNetworkConnectionTrackerFromUIThread( base::BindOnce(&PluginNetworkObserver::SetNetworkConnectionTracker, weak_factory_.GetWeakPtr())); @@ -180,7 +178,7 @@ private: PpapiPluginProcessHost* const process_host_; network::NetworkConnectionTracker* network_connection_tracker_; - base::WeakPtrFactory<PluginNetworkObserver> weak_factory_; + base::WeakPtrFactory<PluginNetworkObserver> weak_factory_{this}; }; PpapiPluginProcessHost::~PpapiPluginProcessHost() {
diff --git a/content/browser/presentation/presentation_service_impl.cc b/content/browser/presentation/presentation_service_impl.cc index e4c81a6ce..7785c39 100644 --- a/content/browser/presentation/presentation_service_impl.cc +++ b/content/browser/presentation/presentation_service_impl.cc
@@ -69,8 +69,7 @@ // TODO(imcheng): Consider using RenderFrameHost* directly instead of IDs. render_process_id_(render_frame_host->GetProcess()->GetID()), render_frame_id_(render_frame_host->GetRoutingID()), - is_main_frame_(!render_frame_host->GetParent()), - weak_factory_(this) { + is_main_frame_(!render_frame_host->GetParent()) { DCHECK(render_frame_host_); DCHECK(web_contents); CHECK(render_frame_host_->IsRenderFrameLive());
diff --git a/content/browser/presentation/presentation_service_impl.h b/content/browser/presentation/presentation_service_impl.h index 2306ba95..d4a44d1 100644 --- a/content/browser/presentation/presentation_service_impl.h +++ b/content/browser/presentation/presentation_service_impl.h
@@ -281,7 +281,7 @@ bool is_main_frame_; // NOTE: Weak pointers must be invalidated before all other member variables. - base::WeakPtrFactory<PresentationServiceImpl> weak_factory_; + base::WeakPtrFactory<PresentationServiceImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PresentationServiceImpl); };
diff --git a/content/browser/push_messaging/push_messaging_manager.cc b/content/browser/push_messaging/push_messaging_manager.cc index 629c2f4..cfcdb90 100644 --- a/content/browser/push_messaging/push_messaging_manager.cc +++ b/content/browser/push_messaging/push_messaging_manager.cc
@@ -241,7 +241,7 @@ bool is_incognito_; - base::WeakPtrFactory<Core> weak_factory_ui_to_ui_; + base::WeakPtrFactory<Core> weak_factory_ui_to_ui_{this}; DISALLOW_COPY_AND_ASSIGN(Core); }; @@ -255,8 +255,7 @@ int render_frame_id) : io_parent_(io_parent), render_process_id_(render_process_id), - render_frame_id_(render_frame_id), - weak_factory_ui_to_ui_(this) { + render_frame_id_(render_frame_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderProcessHost* process_host = RenderProcessHost::FromID(render_process_id_); // Can't be null yet. @@ -270,8 +269,7 @@ int render_frame_id, ServiceWorkerContextWrapper* service_worker_context) : service_worker_context_(service_worker_context), - render_frame_id_(render_frame_id), - weak_factory_(this) { + render_frame_id_(render_frame_id) { // Although this class is used only on the IO thread, it is constructed on UI. DCHECK_CURRENTLY_ON(BrowserThread::UI); // Normally, it would be unsafe to obtain a weak pointer from the UI thread,
diff --git a/content/browser/push_messaging/push_messaging_manager.h b/content/browser/push_messaging/push_messaging_manager.h index c27bab0..c3436f9 100644 --- a/content/browser/push_messaging/push_messaging_manager.h +++ b/content/browser/push_messaging/push_messaging_manager.h
@@ -152,7 +152,7 @@ mojo::ReceiverSet<blink::mojom::PushMessaging> receivers_; - base::WeakPtrFactory<PushMessagingManager> weak_factory_; + base::WeakPtrFactory<PushMessagingManager> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PushMessagingManager); };
diff --git a/content/browser/quota_dispatcher_host.cc b/content/browser/quota_dispatcher_host.cc index f1626f3..91bbbd59 100644 --- a/content/browser/quota_dispatcher_host.cc +++ b/content/browser/quota_dispatcher_host.cc
@@ -83,8 +83,7 @@ : process_id_(process_id), render_frame_id_(render_frame_id), quota_manager_(quota_manager), - permission_context_(std::move(permission_context)), - weak_factory_(this) { + permission_context_(std::move(permission_context)) { DCHECK(quota_manager); // TODO(sashab): Work out the conditions for permission_context to be set and // add a DCHECK for it here.
diff --git a/content/browser/quota_dispatcher_host.h b/content/browser/quota_dispatcher_host.h index 8029c9d..680f491f 100644 --- a/content/browser/quota_dispatcher_host.h +++ b/content/browser/quota_dispatcher_host.h
@@ -87,7 +87,7 @@ scoped_refptr<storage::QuotaManager> quota_manager_; scoped_refptr<QuotaPermissionContext> permission_context_; - base::WeakPtrFactory<QuotaDispatcherHost> weak_factory_; + base::WeakPtrFactory<QuotaDispatcherHost> weak_factory_{this}; DISALLOW_IMPLICIT_CONSTRUCTORS(QuotaDispatcherHost); };
diff --git a/content/browser/renderer_host/code_cache_host_impl.cc b/content/browser/renderer_host/code_cache_host_impl.cc index e32f490..dac52c0 100644 --- a/content/browser/renderer_host/code_cache_host_impl.cc +++ b/content/browser/renderer_host/code_cache_host_impl.cc
@@ -101,8 +101,7 @@ scoped_refptr<GeneratedCodeCacheContext> generated_code_cache_context) : render_process_id_(render_process_id), cache_storage_context_(std::move(cache_storage_context)), - generated_code_cache_context_(std::move(generated_code_cache_context)), - weak_ptr_factory_(this) {} + generated_code_cache_context_(std::move(generated_code_cache_context)) {} CodeCacheHostImpl::~CodeCacheHostImpl() { DCHECK_CURRENTLY_ON(BrowserThread::IO);
diff --git a/content/browser/renderer_host/code_cache_host_impl.h b/content/browser/renderer_host/code_cache_host_impl.h index 74370c1bd..bae531f2 100644 --- a/content/browser/renderer_host/code_cache_host_impl.h +++ b/content/browser/renderer_host/code_cache_host_impl.h
@@ -91,7 +91,7 @@ scoped_refptr<GeneratedCodeCacheContext> generated_code_cache_context_; - base::WeakPtrFactory<CodeCacheHostImpl> weak_ptr_factory_; + base::WeakPtrFactory<CodeCacheHostImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CodeCacheHostImpl); };
diff --git a/content/browser/renderer_host/delegated_frame_host.cc b/content/browser/renderer_host/delegated_frame_host.cc index d749f1c..9b4eccf 100644 --- a/content/browser/renderer_host/delegated_frame_host.cc +++ b/content/browser/renderer_host/delegated_frame_host.cc
@@ -52,8 +52,7 @@ enable_viz_(features::IsVizDisplayCompositorEnabled()), should_register_frame_sink_id_(should_register_frame_sink_id), host_frame_sink_manager_(GetHostFrameSinkManager()), - frame_evictor_(std::make_unique<viz::FrameEvictor>(this)), - weak_factory_(this) { + frame_evictor_(std::make_unique<viz::FrameEvictor>(this)) { ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); factory->GetContextFactory()->AddObserver(this); DCHECK(host_frame_sink_manager_);
diff --git a/content/browser/renderer_host/delegated_frame_host.h b/content/browser/renderer_host/delegated_frame_host.h index ef202d7..3368e61 100644 --- a/content/browser/renderer_host/delegated_frame_host.h +++ b/content/browser/renderer_host/delegated_frame_host.h
@@ -245,7 +245,7 @@ TabSwitchTimeRecorder tab_switch_time_recorder_; - base::WeakPtrFactory<DelegatedFrameHost> weak_factory_; + base::WeakPtrFactory<DelegatedFrameHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DelegatedFrameHost); };
diff --git a/content/browser/renderer_host/input/fling_controller.cc b/content/browser/renderer_host/input/fling_controller.cc index 2fa90a1..80acce8 100644 --- a/content/browser/renderer_host/input/fling_controller.cc +++ b/content/browser/renderer_host/input/fling_controller.cc
@@ -51,8 +51,7 @@ config.touchpad_tap_suppression_config), touchscreen_tap_suppression_controller_( config.touchscreen_tap_suppression_config), - clock_(base::DefaultTickClock::GetInstance()), - weak_ptr_factory_(this) { + clock_(base::DefaultTickClock::GetInstance()) { DCHECK(event_sender_client); DCHECK(scheduler_client); }
diff --git a/content/browser/renderer_host/input/fling_controller.h b/content/browser/renderer_host/input/fling_controller.h index a71152d..cf14c1d 100644 --- a/content/browser/renderer_host/input/fling_controller.h +++ b/content/browser/renderer_host/input/fling_controller.h
@@ -173,7 +173,7 @@ // starting time for a possible fling gesture curve. base::TimeTicks last_seen_scroll_update_; - base::WeakPtrFactory<FlingController> weak_ptr_factory_; + base::WeakPtrFactory<FlingController> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FlingController); };
diff --git a/content/browser/renderer_host/input/input_router_impl.cc b/content/browser/renderer_host/input/input_router_impl.cc index bdf3bb96..b4757203 100644 --- a/content/browser/renderer_host/input/input_router_impl.cc +++ b/content/browser/renderer_host/input/input_router_impl.cc
@@ -90,8 +90,7 @@ config.gesture_config), device_scale_factor_(1.f), compositor_touch_action_enabled_( - base::FeatureList::IsEnabled(features::kCompositorTouchAction)), - weak_ptr_factory_(this) { + base::FeatureList::IsEnabled(features::kCompositorTouchAction)) { weak_this_ = weak_ptr_factory_.GetWeakPtr(); DCHECK(client);
diff --git a/content/browser/renderer_host/input/input_router_impl.h b/content/browser/renderer_host/input/input_router_impl.h index 9d04f90..14c45147 100644 --- a/content/browser/renderer_host/input/input_router_impl.h +++ b/content/browser/renderer_host/input/input_router_impl.h
@@ -263,7 +263,7 @@ mojo::Receiver<mojom::WidgetInputHandlerHost> frame_host_receiver_{this}; base::WeakPtr<InputRouterImpl> weak_this_; - base::WeakPtrFactory<InputRouterImpl> weak_ptr_factory_; + base::WeakPtrFactory<InputRouterImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(InputRouterImpl); };
diff --git a/content/browser/renderer_host/input/synthetic_gesture_controller.cc b/content/browser/renderer_host/input/synthetic_gesture_controller.cc index b6c887fb..dda9d3e 100644 --- a/content/browser/renderer_host/input/synthetic_gesture_controller.cc +++ b/content/browser/renderer_host/input/synthetic_gesture_controller.cc
@@ -19,9 +19,7 @@ SyntheticGestureController::SyntheticGestureController( Delegate* delegate, std::unique_ptr<SyntheticGestureTarget> gesture_target) - : delegate_(delegate), - gesture_target_(std::move(gesture_target)), - weak_ptr_factory_(this) { + : delegate_(delegate), gesture_target_(std::move(gesture_target)) { DCHECK(delegate_); }
diff --git a/content/browser/renderer_host/input/synthetic_gesture_controller.h b/content/browser/renderer_host/input/synthetic_gesture_controller.h index efa6133..578edefe 100644 --- a/content/browser/renderer_host/input/synthetic_gesture_controller.h +++ b/content/browser/renderer_host/input/synthetic_gesture_controller.h
@@ -131,7 +131,7 @@ } pending_gesture_queue_; base::RepeatingTimer dispatch_timer_; - base::WeakPtrFactory<SyntheticGestureController> weak_ptr_factory_; + base::WeakPtrFactory<SyntheticGestureController> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SyntheticGestureController); };
diff --git a/content/browser/renderer_host/media/audio_input_delegate_impl.cc b/content/browser/renderer_host/media/audio_input_delegate_impl.cc index 48a2088..5d6c531 100644 --- a/content/browser/renderer_host/media/audio_input_delegate_impl.cc +++ b/content/browser/renderer_host/media/audio_input_delegate_impl.cc
@@ -181,8 +181,7 @@ controller_(), keyboard_mic_registration_(std::move(keyboard_mic_registration)), stream_id_(stream_id), - render_process_id_(render_process_id), - weak_factory_(this) { + render_process_id_(render_process_id) { // Prevent process backgrounding while audio input is active: base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI},
diff --git a/content/browser/renderer_host/media/audio_input_delegate_impl.h b/content/browser/renderer_host/media/audio_input_delegate_impl.h index a2ef91d8..fc01ed3b 100644 --- a/content/browser/renderer_host/media/audio_input_delegate_impl.h +++ b/content/browser/renderer_host/media/audio_input_delegate_impl.h
@@ -101,7 +101,7 @@ keyboard_mic_registration_; const int stream_id_; const int render_process_id_; - base::WeakPtrFactory<AudioInputDelegateImpl> weak_factory_; + base::WeakPtrFactory<AudioInputDelegateImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AudioInputDelegateImpl); };
diff --git a/content/browser/renderer_host/media/audio_output_authorization_handler.cc b/content/browser/renderer_host/media/audio_output_authorization_handler.cc index 21f3b537..9f7f449 100644 --- a/content/browser/renderer_host/media/audio_output_authorization_handler.cc +++ b/content/browser/renderer_host/media/audio_output_authorization_handler.cc
@@ -132,8 +132,7 @@ int render_process_id) : audio_system_(audio_system), media_stream_manager_(media_stream_manager), - render_process_id_(render_process_id), - weak_factory_(this) { + render_process_id_(render_process_id) { DCHECK(media_stream_manager_); }
diff --git a/content/browser/renderer_host/media/audio_output_authorization_handler.h b/content/browser/renderer_host/media/audio_output_authorization_handler.h index faf06ff1..a6c1efcf 100644 --- a/content/browser/renderer_host/media/audio_output_authorization_handler.h +++ b/content/browser/renderer_host/media/audio_output_authorization_handler.h
@@ -107,7 +107,7 @@ // All access is on the IO thread, and taking a weak pointer to const looks // const, so this can be mutable. mutable base::WeakPtrFactory<const AudioOutputAuthorizationHandler> - weak_factory_; + weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AudioOutputAuthorizationHandler); };
diff --git a/content/browser/renderer_host/media/audio_output_delegate_impl.cc b/content/browser/renderer_host/media/audio_output_delegate_impl.cc index 4c516cd..ed251442 100644 --- a/content/browser/renderer_host/media/audio_output_delegate_impl.cc +++ b/content/browser/renderer_host/media/audio_output_delegate_impl.cc
@@ -139,8 +139,7 @@ reader_(std::move(reader)), foreign_socket_(std::move(foreign_socket)), stream_id_(stream_id), - observer_(std::move(observer)), - weak_factory_(this) { + observer_(std::move(observer)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(subscriber_); DCHECK(audio_manager);
diff --git a/content/browser/renderer_host/media/audio_output_delegate_impl.h b/content/browser/renderer_host/media/audio_output_delegate_impl.h index 59f0fc8..ebbc052a7 100644 --- a/content/browser/renderer_host/media/audio_output_delegate_impl.h +++ b/content/browser/renderer_host/media/audio_output_delegate_impl.h
@@ -102,7 +102,7 @@ // |observer_| is notified about changes in the audible state of the stream. media::mojom::AudioOutputStreamObserverPtr observer_; - base::WeakPtrFactory<AudioOutputDelegateImpl> weak_factory_; + base::WeakPtrFactory<AudioOutputDelegateImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AudioOutputDelegateImpl); };
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 de160ca6..dfeac130 100644 --- a/content/browser/renderer_host/media/media_devices_dispatcher_host.cc +++ b/content/browser/renderer_host/media/media_devices_dispatcher_host.cc
@@ -79,8 +79,7 @@ : render_process_id_(render_process_id), render_frame_id_(render_frame_id), media_stream_manager_(media_stream_manager), - num_pending_audio_input_parameters_(0), - weak_factory_(this) { + num_pending_audio_input_parameters_(0) { DCHECK_CURRENTLY_ON(BrowserThread::IO); }
diff --git a/content/browser/renderer_host/media/media_devices_dispatcher_host.h b/content/browser/renderer_host/media/media_devices_dispatcher_host.h index d02bffb..7d80341 100644 --- a/content/browser/renderer_host/media/media_devices_dispatcher_host.h +++ b/content/browser/renderer_host/media/media_devices_dispatcher_host.h
@@ -126,7 +126,7 @@ std::vector<uint32_t> subscription_ids_; - base::WeakPtrFactory<MediaDevicesDispatcherHost> weak_factory_; + base::WeakPtrFactory<MediaDevicesDispatcherHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MediaDevicesDispatcherHost); };
diff --git a/content/browser/renderer_host/media/media_devices_manager.cc b/content/browser/renderer_host/media/media_devices_manager.cc index 2d04cea..b124bd7b 100644 --- a/content/browser/renderer_host/media/media_devices_manager.cc +++ b/content/browser/renderer_host/media/media_devices_manager.cc
@@ -300,7 +300,7 @@ : public audio::mojom::DeviceListener { public: explicit AudioServiceDeviceListener(service_manager::Connector* connector) - : binding_(this), weak_factory_(this) { + : binding_(this) { TryConnectToService(connector); } ~AudioServiceDeviceListener() override = default; @@ -367,7 +367,7 @@ SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<AudioServiceDeviceListener> weak_factory_; + base::WeakPtrFactory<AudioServiceDeviceListener> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AudioServiceDeviceListener); }; @@ -387,8 +387,7 @@ cache_infos_(blink::NUM_MEDIA_DEVICE_TYPES), monitoring_started_(false), salt_and_origin_callback_( - base::BindRepeating(&GetMediaDeviceSaltAndOrigin)), - weak_factory_(this) { + base::BindRepeating(&GetMediaDeviceSaltAndOrigin)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(audio_system_); DCHECK(video_capture_manager_.get());
diff --git a/content/browser/renderer_host/media/media_devices_manager.h b/content/browser/renderer_host/media/media_devices_manager.h index 450830a..e2db9c4a 100644 --- a/content/browser/renderer_host/media/media_devices_manager.h +++ b/content/browser/renderer_host/media/media_devices_manager.h
@@ -331,7 +331,7 @@ std::map<uint32_t, EnumerationState> enumeration_states_; uint32_t next_enumeration_state_id_ = 0; - base::WeakPtrFactory<MediaDevicesManager> weak_factory_; + base::WeakPtrFactory<MediaDevicesManager> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MediaDevicesManager); };
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 094e166..8e5d07e 100644 --- a/content/browser/renderer_host/media/media_stream_dispatcher_host.cc +++ b/content/browser/renderer_host/media/media_stream_dispatcher_host.cc
@@ -49,8 +49,7 @@ requester_id_(next_requester_id_++), media_stream_manager_(media_stream_manager), salt_and_origin_callback_( - base::BindRepeating(&GetMediaDeviceSaltAndOrigin)), - weak_factory_(this) { + base::BindRepeating(&GetMediaDeviceSaltAndOrigin)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); }
diff --git a/content/browser/renderer_host/media/media_stream_dispatcher_host.h b/content/browser/renderer_host/media/media_stream_dispatcher_host.h index 53b517b..d4b593cd 100644 --- a/content/browser/renderer_host/media/media_stream_dispatcher_host.h +++ b/content/browser/renderer_host/media/media_stream_dispatcher_host.h
@@ -96,7 +96,7 @@ blink::mojom::MediaStreamDeviceObserverPtr media_stream_device_observer_; MediaDeviceSaltAndOriginCallback salt_and_origin_callback_; - base::WeakPtrFactory<MediaStreamDispatcherHost> weak_factory_; + base::WeakPtrFactory<MediaStreamDispatcherHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MediaStreamDispatcherHost); };
diff --git a/content/browser/renderer_host/media/media_stream_ui_proxy.cc b/content/browser/renderer_host/media/media_stream_ui_proxy.cc index e3ea07d..fa85bf5 100644 --- a/content/browser/renderer_host/media/media_stream_ui_proxy.cc +++ b/content/browser/renderer_host/media/media_stream_ui_proxy.cc
@@ -91,7 +91,7 @@ // WeakPtr<> is used to RequestMediaAccessPermission() because there is no way // cancel media requests. - base::WeakPtrFactory<Core> weak_factory_; + base::WeakPtrFactory<Core> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(Core); }; @@ -100,8 +100,7 @@ RenderFrameHostDelegate* test_render_delegate) : proxy_(proxy), tests_use_fake_render_frame_hosts_(test_render_delegate != nullptr), - test_render_delegate_(test_render_delegate), - weak_factory_(this) {} + test_render_delegate_(test_render_delegate) {} MediaStreamUIProxy::Core::~Core() { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -229,8 +228,7 @@ } MediaStreamUIProxy::MediaStreamUIProxy( - RenderFrameHostDelegate* test_render_delegate) - : weak_factory_(this) { + RenderFrameHostDelegate* test_render_delegate) { DCHECK_CURRENTLY_ON(BrowserThread::IO); core_.reset(new Core(weak_factory_.GetWeakPtr(), test_render_delegate)); }
diff --git a/content/browser/renderer_host/media/media_stream_ui_proxy.h b/content/browser/renderer_host/media/media_stream_ui_proxy.h index 7e92847..4032555 100644 --- a/content/browser/renderer_host/media/media_stream_ui_proxy.h +++ b/content/browser/renderer_host/media/media_stream_ui_proxy.h
@@ -80,7 +80,7 @@ base::OnceClosure stop_callback_; MediaStreamUI::SourceCallback source_callback_; - base::WeakPtrFactory<MediaStreamUIProxy> weak_factory_; + base::WeakPtrFactory<MediaStreamUIProxy> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MediaStreamUIProxy); };
diff --git a/content/browser/renderer_host/media/old_render_frame_audio_input_stream_factory.cc b/content/browser/renderer_host/media/old_render_frame_audio_input_stream_factory.cc index 0b4710c2..3440177 100644 --- a/content/browser/renderer_host/media/old_render_frame_audio_input_stream_factory.cc +++ b/content/browser/renderer_host/media/old_render_frame_audio_input_stream_factory.cc
@@ -112,8 +112,7 @@ : create_delegate_callback_(std::move(create_delegate_callback)), media_stream_manager_(media_stream_manager), render_process_id_(render_process_id), - render_frame_id_(render_frame_id), - weak_ptr_factory_(this) { + render_frame_id_(render_frame_id) { DCHECK(create_delegate_callback_); // No thread-hostile state has been initialized yet, so we don't have to bind // to this specific thread.
diff --git a/content/browser/renderer_host/media/old_render_frame_audio_input_stream_factory.h b/content/browser/renderer_host/media/old_render_frame_audio_input_stream_factory.h index 1a7799ba..bcb6c2fb2 100644 --- a/content/browser/renderer_host/media/old_render_frame_audio_input_stream_factory.h +++ b/content/browser/renderer_host/media/old_render_frame_audio_input_stream_factory.h
@@ -106,7 +106,8 @@ InputStreamSet streams_; int next_stream_id_ = 0; - base::WeakPtrFactory<OldRenderFrameAudioInputStreamFactory> weak_ptr_factory_; + base::WeakPtrFactory<OldRenderFrameAudioInputStreamFactory> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(OldRenderFrameAudioInputStreamFactory); };
diff --git a/content/browser/renderer_host/media/old_render_frame_audio_output_stream_factory.cc b/content/browser/renderer_host/media/old_render_frame_audio_output_stream_factory.cc index decde86..6ac3c43 100644 --- a/content/browser/renderer_host/media/old_render_frame_audio_output_stream_factory.cc +++ b/content/browser/renderer_host/media/old_render_frame_audio_output_stream_factory.cc
@@ -62,9 +62,7 @@ OldRenderFrameAudioOutputStreamFactory::OldRenderFrameAudioOutputStreamFactory( int render_frame_id, RendererAudioOutputStreamFactoryContext* context) - : render_frame_id_(render_frame_id), - context_(context), - weak_ptr_factory_(this) { + : render_frame_id_(render_frame_id), context_(context) { DCHECK(context_); }
diff --git a/content/browser/renderer_host/media/old_render_frame_audio_output_stream_factory.h b/content/browser/renderer_host/media/old_render_frame_audio_output_stream_factory.h index f0d2413..3d286dd3 100644 --- a/content/browser/renderer_host/media/old_render_frame_audio_output_stream_factory.h +++ b/content/browser/renderer_host/media/old_render_frame_audio_output_stream_factory.h
@@ -71,7 +71,7 @@ int next_stream_id_ = 0; base::WeakPtrFactory<OldRenderFrameAudioOutputStreamFactory> - weak_ptr_factory_; + weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(OldRenderFrameAudioOutputStreamFactory); };
diff --git a/content/browser/renderer_host/media/ref_counted_video_source_provider.cc b/content/browser/renderer_host/media/ref_counted_video_source_provider.cc index d2782c2b..b02fcc94c 100644 --- a/content/browser/renderer_host/media/ref_counted_video_source_provider.cc +++ b/content/browser/renderer_host/media/ref_counted_video_source_provider.cc
@@ -12,8 +12,7 @@ base::OnceClosure destruction_cb) : source_provider_(std::move(source_provider)), device_factory_provider_(std::move(device_factory_provider)), - destruction_cb_(std::move(destruction_cb)), - weak_ptr_factory_(this) {} + destruction_cb_(std::move(destruction_cb)) {} RefCountedVideoSourceProvider::~RefCountedVideoSourceProvider() { std::move(destruction_cb_).Run();
diff --git a/content/browser/renderer_host/media/ref_counted_video_source_provider.h b/content/browser/renderer_host/media/ref_counted_video_source_provider.h index 5b8bfae..105843f3 100644 --- a/content/browser/renderer_host/media/ref_counted_video_source_provider.h +++ b/content/browser/renderer_host/media/ref_counted_video_source_provider.h
@@ -42,7 +42,7 @@ video_capture::mojom::VideoSourceProviderPtr source_provider_; video_capture::mojom::DeviceFactoryProviderPtr device_factory_provider_; base::OnceClosure destruction_cb_; - base::WeakPtrFactory<RefCountedVideoSourceProvider> weak_ptr_factory_; + base::WeakPtrFactory<RefCountedVideoSourceProvider> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RefCountedVideoSourceProvider); };
diff --git a/content/browser/renderer_host/media/render_frame_audio_input_stream_factory.cc b/content/browser/renderer_host/media/render_frame_audio_input_stream_factory.cc index 1345bb3e..9db19dc 100644 --- a/content/browser/renderer_host/media/render_frame_audio_input_stream_factory.cc +++ b/content/browser/renderer_host/media/render_frame_audio_input_stream_factory.cc
@@ -148,7 +148,7 @@ // Always null-check this weak pointer before dereferencing it. base::WeakPtr<ForwardingAudioStreamFactory::Core> forwarding_factory_; - base::WeakPtrFactory<Core> weak_ptr_factory_; + base::WeakPtrFactory<Core> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(Core); }; @@ -182,8 +182,7 @@ process_id_(render_frame_host->GetProcess()->GetID()), frame_id_(render_frame_host->GetRoutingID()), origin_(render_frame_host->GetLastCommittedOrigin()), - binding_(this), - weak_ptr_factory_(this) { + binding_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ForwardingAudioStreamFactory::Core* tmp_factory =
diff --git a/content/browser/renderer_host/media/render_frame_audio_output_stream_factory.cc b/content/browser/renderer_host/media/render_frame_audio_output_stream_factory.cc index a1c650a..9595d60 100644 --- a/content/browser/renderer_host/media/render_frame_audio_output_stream_factory.cc +++ b/content/browser/renderer_host/media/render_frame_audio_output_stream_factory.cc
@@ -141,7 +141,7 @@ // Weak pointers are used to cancel device authorizations that are in flight // while |this| is destructed. - base::WeakPtrFactory<Core> weak_ptr_factory_; + base::WeakPtrFactory<Core> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(Core); }; @@ -183,8 +183,7 @@ : process_id_(frame->GetProcess()->GetID()), frame_id_(frame->GetRoutingID()), authorization_handler_(audio_system, media_stream_manager, process_id_), - binding_(this), - weak_ptr_factory_(this) { + binding_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ForwardingAudioStreamFactory::Core* tmp_factory =
diff --git a/content/browser/renderer_host/media/service_video_capture_provider.cc b/content/browser/renderer_host/media/service_video_capture_provider.cc index bf0df782..d32c8e6 100644 --- a/content/browser/renderer_host/media/service_video_capture_provider.cc +++ b/content/browser/renderer_host/media/service_video_capture_provider.cc
@@ -57,8 +57,7 @@ : connector_(connector ? connector->Clone() : nullptr), emit_log_message_cb_(std::move(emit_log_message_cb)), launcher_has_connected_to_source_provider_(false), - service_listener_binding_(this), - weak_ptr_factory_(this) { + service_listener_binding_(this) { base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(
diff --git a/content/browser/renderer_host/media/service_video_capture_provider.h b/content/browser/renderer_host/media/service_video_capture_provider.h index 2a25dbcb..7318d84 100644 --- a/content/browser/renderer_host/media/service_video_capture_provider.h +++ b/content/browser/renderer_host/media/service_video_capture_provider.h
@@ -111,7 +111,7 @@ int stashed_retry_count_; #endif - base::WeakPtrFactory<ServiceVideoCaptureProvider> weak_ptr_factory_; + base::WeakPtrFactory<ServiceVideoCaptureProvider> weak_ptr_factory_{this}; }; } // namespace content
diff --git a/content/browser/renderer_host/media/video_capture_controller.cc b/content/browser/renderer_host/media/video_capture_controller.cc index 3a884b6..94e66f23 100644 --- a/content/browser/renderer_host/media/video_capture_controller.cc +++ b/content/browser/renderer_host/media/video_capture_controller.cc
@@ -267,8 +267,7 @@ emit_log_message_cb_(std::move(emit_log_message_cb)), device_launch_observer_(nullptr), state_(blink::VIDEO_CAPTURE_STATE_STARTING), - has_received_frames_(false), - weak_ptr_factory_(this) { + has_received_frames_(false) { DCHECK_CURRENTLY_ON(BrowserThread::IO); }
diff --git a/content/browser/renderer_host/media/video_capture_controller.h b/content/browser/renderer_host/media/video_capture_controller.h index 446a961..f038866ff 100644 --- a/content/browser/renderer_host/media/video_capture_controller.h +++ b/content/browser/renderer_host/media/video_capture_controller.h
@@ -270,7 +270,7 @@ base::Optional<media::VideoCaptureFormat> video_capture_format_; - base::WeakPtrFactory<VideoCaptureController> weak_ptr_factory_; + base::WeakPtrFactory<VideoCaptureController> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VideoCaptureController); };
diff --git a/content/browser/renderer_host/media/video_capture_host.cc b/content/browser/renderer_host/media/video_capture_host.cc index 3d5ebd2..bafba43 100644 --- a/content/browser/renderer_host/media/video_capture_host.cc +++ b/content/browser/renderer_host/media/video_capture_host.cc
@@ -67,8 +67,7 @@ std::unique_ptr<RenderProcessHostDelegate> delegate, MediaStreamManager* media_stream_manager) : render_process_host_delegate_(std::move(delegate)), - media_stream_manager_(media_stream_manager), - weak_factory_(this) { + media_stream_manager_(media_stream_manager) { DVLOG(1) << __func__; DCHECK_CURRENTLY_ON(BrowserThread::IO); }
diff --git a/content/browser/renderer_host/media/video_capture_host.h b/content/browser/renderer_host/media/video_capture_host.h index 95c9678..3aa3dcfb3 100644 --- a/content/browser/renderer_host/media/video_capture_host.h +++ b/content/browser/renderer_host/media/video_capture_host.h
@@ -129,7 +129,7 @@ std::map<int32_t, media::mojom::VideoCaptureObserverPtr> device_id_to_observer_map_; - base::WeakPtrFactory<VideoCaptureHost> weak_factory_; + base::WeakPtrFactory<VideoCaptureHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VideoCaptureHost); };
diff --git a/content/browser/renderer_host/p2p/socket_dispatcher_host.cc b/content/browser/renderer_host/p2p/socket_dispatcher_host.cc index 6bd32e88..8d3f8d2a 100644 --- a/content/browser/renderer_host/p2p/socket_dispatcher_host.cc +++ b/content/browser/renderer_host/p2p/socket_dispatcher_host.cc
@@ -21,9 +21,7 @@ namespace content { P2PSocketDispatcherHost::P2PSocketDispatcherHost(int render_process_id) - : render_process_id_(render_process_id), - binding_(this), - weak_factory_(this) {} + : render_process_id_(render_process_id), binding_(this) {} P2PSocketDispatcherHost::~P2PSocketDispatcherHost() {}
diff --git a/content/browser/renderer_host/p2p/socket_dispatcher_host.h b/content/browser/renderer_host/p2p/socket_dispatcher_host.h index 3802f73e..54d3f86 100644 --- a/content/browser/renderer_host/p2p/socket_dispatcher_host.h +++ b/content/browser/renderer_host/p2p/socket_dispatcher_host.h
@@ -60,7 +60,7 @@ network::mojom::P2PNetworkNotificationClientPtr network_notification_client_; - base::WeakPtrFactory<P2PSocketDispatcherHost> weak_factory_; + base::WeakPtrFactory<P2PSocketDispatcherHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(P2PSocketDispatcherHost); };
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 0f074d9..cc8f129 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
@@ -67,8 +67,7 @@ render_process_id_(render_process_id), task_runner_(base::CreateSequencedTaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::USER_VISIBLE, - base::TaskShutdownBehavior::BLOCK_SHUTDOWN})), - weak_factory_(this) {} + base::TaskShutdownBehavior::BLOCK_SHUTDOWN})) {} PepperExternalFileRefBackend::~PepperExternalFileRefBackend() {}
diff --git a/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.h b/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.h index fa57231..5fa21be 100644 --- a/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.h +++ b/content/browser/renderer_host/pepper/pepper_external_file_ref_backend.h
@@ -71,7 +71,7 @@ scoped_refptr<base::SequencedTaskRunner> task_runner_; - base::WeakPtrFactory<PepperExternalFileRefBackend> weak_factory_; + base::WeakPtrFactory<PepperExternalFileRefBackend> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperExternalFileRefBackend); };
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 a53e3155..24d0a2a 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
@@ -61,8 +61,7 @@ opened_(false), file_system_context_(nullptr), reserved_quota_(0), - reserving_quota_(false), - weak_factory_(this) {} + reserving_quota_(false) {} PepperFileSystemBrowserHost::~PepperFileSystemBrowserHost() { // If |files_| is not empty, the plugin failed to close some files. It must
diff --git a/content/browser/renderer_host/pepper/pepper_file_system_browser_host.h b/content/browser/renderer_host/pepper/pepper_file_system_browser_host.h index e41f2498..57c1eec 100644 --- a/content/browser/renderer_host/pepper/pepper_file_system_browser_host.h +++ b/content/browser/renderer_host/pepper/pepper_file_system_browser_host.h
@@ -167,7 +167,7 @@ std::string fsid_; // used only for isolated filesystems. - base::WeakPtrFactory<PepperFileSystemBrowserHost> weak_factory_; + base::WeakPtrFactory<PepperFileSystemBrowserHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperFileSystemBrowserHost); };
diff --git a/content/browser/renderer_host/pepper/pepper_gamepad_host.cc b/content/browser/renderer_host/pepper/pepper_gamepad_host.cc index d4140d9d..ec613d99 100644 --- a/content/browser/renderer_host/pepper/pepper_gamepad_host.cc +++ b/content/browser/renderer_host/pepper/pepper_gamepad_host.cc
@@ -21,8 +21,7 @@ PP_Resource resource) : ResourceHost(host->GetPpapiHost(), instance, resource), gamepad_service_(device::GamepadService::GetInstance()), - is_started_(false), - weak_factory_(this) {} + is_started_(false) {} PepperGamepadHost::PepperGamepadHost(device::GamepadService* gamepad_service, BrowserPpapiHost* host, @@ -30,8 +29,7 @@ PP_Resource resource) : ResourceHost(host->GetPpapiHost(), instance, resource), gamepad_service_(gamepad_service), - is_started_(false), - weak_factory_(this) {} + is_started_(false) {} PepperGamepadHost::~PepperGamepadHost() { if (is_started_)
diff --git a/content/browser/renderer_host/pepper/pepper_gamepad_host.h b/content/browser/renderer_host/pepper/pepper_gamepad_host.h index 3cec62b2..f7525c6 100644 --- a/content/browser/renderer_host/pepper/pepper_gamepad_host.h +++ b/content/browser/renderer_host/pepper/pepper_gamepad_host.h
@@ -66,7 +66,7 @@ bool is_started_; - base::WeakPtrFactory<PepperGamepadHost> weak_factory_; + base::WeakPtrFactory<PepperGamepadHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperGamepadHost); };
diff --git a/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.cc b/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.cc index 1491a23c..63def00f 100644 --- a/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.cc +++ b/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.cc
@@ -55,8 +55,7 @@ render_process_id_(render_process_id), fs_host_(fs_host), fs_type_(fs_host->GetType()), - path_(path), - weak_factory_(this) { + path_(path) { ppapi::NormalizeInternalPath(&path_); }
diff --git a/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.h b/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.h index deab6c7..8935298 100644 --- a/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.h +++ b/content/browser/renderer_host/pepper/pepper_internal_file_ref_backend.h
@@ -81,7 +81,7 @@ mutable storage::FileSystemURL fs_url_; - base::WeakPtrFactory<PepperInternalFileRefBackend> weak_factory_; + base::WeakPtrFactory<PepperInternalFileRefBackend> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperInternalFileRefBackend); };
diff --git a/content/browser/renderer_host/pepper/pepper_network_monitor_host.cc b/content/browser/renderer_host/pepper/pepper_network_monitor_host.cc index 0ec4233..6e55aaa3 100644 --- a/content/browser/renderer_host/pepper/pepper_network_monitor_host.cc +++ b/content/browser/renderer_host/pepper/pepper_network_monitor_host.cc
@@ -64,8 +64,7 @@ PP_Instance instance, PP_Resource resource) : ResourceHost(host->GetPpapiHost(), instance, resource), - network_connection_tracker_(nullptr), - weak_factory_(this) { + network_connection_tracker_(nullptr) { int render_process_id; int render_frame_id; host->GetRenderFrameIDsForInstance(
diff --git a/content/browser/renderer_host/pepper/pepper_network_monitor_host.h b/content/browser/renderer_host/pepper/pepper_network_monitor_host.h index af48b4bc..626b76e 100644 --- a/content/browser/renderer_host/pepper/pepper_network_monitor_host.h +++ b/content/browser/renderer_host/pepper/pepper_network_monitor_host.h
@@ -44,7 +44,7 @@ network::NetworkConnectionTracker* network_connection_tracker_; - base::WeakPtrFactory<PepperNetworkMonitorHost> weak_factory_; + base::WeakPtrFactory<PepperNetworkMonitorHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperNetworkMonitorHost); };
diff --git a/content/browser/renderer_host/pepper/pepper_network_proxy_host.cc b/content/browser/renderer_host/pepper/pepper_network_proxy_host.cc index e7a74ba..49aa731 100644 --- a/content/browser/renderer_host/pepper/pepper_network_proxy_host.cc +++ b/content/browser/renderer_host/pepper/pepper_network_proxy_host.cc
@@ -57,8 +57,7 @@ render_process_id_(0), render_frame_id_(0), is_allowed_(false), - waiting_for_ui_thread_data_(true), - weak_factory_(this) { + waiting_for_ui_thread_data_(true) { host->GetRenderFrameIDsForInstance(instance, &render_process_id_, &render_frame_id_); base::PostTaskWithTraitsAndReplyWithResult(
diff --git a/content/browser/renderer_host/pepper/pepper_network_proxy_host.h b/content/browser/renderer_host/pepper/pepper_network_proxy_host.h index 081c4045..c45c711 100644 --- a/content/browser/renderer_host/pepper/pepper_network_proxy_host.h +++ b/content/browser/renderer_host/pepper/pepper_network_proxy_host.h
@@ -103,7 +103,7 @@ std::set<std::unique_ptr<PepperProxyLookupHelper>, base::UniquePtrComparator> pending_requests_; - base::WeakPtrFactory<PepperNetworkProxyHost> weak_factory_; + base::WeakPtrFactory<PepperNetworkProxyHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperNetworkProxyHost); };
diff --git a/content/browser/renderer_host/pepper/pepper_printing_host.cc b/content/browser/renderer_host/pepper/pepper_printing_host.cc index 86a2439..deda0fb 100644 --- a/content/browser/renderer_host/pepper/pepper_printing_host.cc +++ b/content/browser/renderer_host/pepper/pepper_printing_host.cc
@@ -22,8 +22,7 @@ PP_Resource resource, std::unique_ptr<PepperPrintSettingsManager> print_settings_manager) : ResourceHost(host, instance, resource), - print_settings_manager_(std::move(print_settings_manager)), - weak_factory_(this) {} + print_settings_manager_(std::move(print_settings_manager)) {} PepperPrintingHost::~PepperPrintingHost() {}
diff --git a/content/browser/renderer_host/pepper/pepper_printing_host.h b/content/browser/renderer_host/pepper/pepper_printing_host.h index 5dd51d1..88edefa6 100644 --- a/content/browser/renderer_host/pepper/pepper_printing_host.h +++ b/content/browser/renderer_host/pepper/pepper_printing_host.h
@@ -41,7 +41,7 @@ std::unique_ptr<PepperPrintSettingsManager> print_settings_manager_; - base::WeakPtrFactory<PepperPrintingHost> weak_factory_; + base::WeakPtrFactory<PepperPrintingHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperPrintingHost); };
diff --git a/content/browser/renderer_host/pepper/pepper_proxy_lookup_helper.cc b/content/browser/renderer_host/pepper/pepper_proxy_lookup_helper.cc index 3822705..c405432 100644 --- a/content/browser/renderer_host/pepper/pepper_proxy_lookup_helper.cc +++ b/content/browser/renderer_host/pepper/pepper_proxy_lookup_helper.cc
@@ -75,7 +75,7 @@ DISALLOW_COPY_AND_ASSIGN(UIThreadHelper); }; -PepperProxyLookupHelper::PepperProxyLookupHelper() : weak_factory_(this) {} +PepperProxyLookupHelper::PepperProxyLookupHelper() {} PepperProxyLookupHelper::~PepperProxyLookupHelper() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/content/browser/renderer_host/pepper/pepper_proxy_lookup_helper.h b/content/browser/renderer_host/pepper/pepper_proxy_lookup_helper.h index f6ea386..b184fb40 100644 --- a/content/browser/renderer_host/pepper/pepper_proxy_lookup_helper.h +++ b/content/browser/renderer_host/pepper/pepper_proxy_lookup_helper.h
@@ -60,7 +60,7 @@ SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<PepperProxyLookupHelper> weak_factory_; + base::WeakPtrFactory<PepperProxyLookupHelper> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperProxyLookupHelper); };
diff --git a/content/browser/renderer_host/pepper/pepper_tcp_server_socket_message_filter.cc b/content/browser/renderer_host/pepper/pepper_tcp_server_socket_message_filter.cc index f0aadfcb..1b1e593 100644 --- a/content/browser/renderer_host/pepper/pepper_tcp_server_socket_message_filter.cc +++ b/content/browser/renderer_host/pepper/pepper_tcp_server_socket_message_filter.cc
@@ -68,8 +68,7 @@ external_plugin_(host->external_plugin()), private_api_(private_api), render_process_id_(0), - render_frame_id_(0), - weak_ptr_factory_(this) { + render_frame_id_(0) { ++g_num_instances; DCHECK(factory_); DCHECK(ppapi_host_);
diff --git a/content/browser/renderer_host/pepper/pepper_tcp_server_socket_message_filter.h b/content/browser/renderer_host/pepper/pepper_tcp_server_socket_message_filter.h index 96456ab0..0e18bc1 100644 --- a/content/browser/renderer_host/pepper/pepper_tcp_server_socket_message_filter.h +++ b/content/browser/renderer_host/pepper/pepper_tcp_server_socket_message_filter.h
@@ -166,7 +166,8 @@ // Vends weak pointers on the UI thread, for callbacks passed through Mojo // pipes not owned by |this|. All weak pointers released in Close(). - base::WeakPtrFactory<PepperTCPServerSocketMessageFilter> weak_ptr_factory_; + base::WeakPtrFactory<PepperTCPServerSocketMessageFilter> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(PepperTCPServerSocketMessageFilter); };
diff --git a/content/browser/renderer_host/pepper/pepper_tcp_socket_message_filter.cc b/content/browser/renderer_host/pepper/pepper_tcp_socket_message_filter.cc index 2e6b9ce1..e46d977 100644 --- a/content/browser/renderer_host/pepper/pepper_tcp_socket_message_filter.cc +++ b/content/browser/renderer_host/pepper/pepper_tcp_socket_message_filter.cc
@@ -88,8 +88,7 @@ pending_write_bytes_written_(0), pending_write_pp_error_(PP_OK_COMPLETIONPENDING), is_potentially_secure_plugin_context_( - host->IsPotentiallySecurePluginContext(instance)), - weak_ptr_factory_(this) { + host->IsPotentiallySecurePluginContext(instance)) { DCHECK(host); DCHECK_CURRENTLY_ON(BrowserThread::IO);
diff --git a/content/browser/renderer_host/pepper/pepper_tcp_socket_message_filter.h b/content/browser/renderer_host/pepper/pepper_tcp_socket_message_filter.h index 9f8c692..8874de1d 100644 --- a/content/browser/renderer_host/pepper/pepper_tcp_socket_message_filter.h +++ b/content/browser/renderer_host/pepper/pepper_tcp_socket_message_filter.h
@@ -367,7 +367,7 @@ // Vends weak pointers on the UI thread, for callbacks passed through Mojo // pipes not owned by |this|. All weak pointers released in Close(). - base::WeakPtrFactory<PepperTCPSocketMessageFilter> weak_ptr_factory_; + base::WeakPtrFactory<PepperTCPSocketMessageFilter> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperTCPSocketMessageFilter); };
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 42a03e77..4d5cabb 100644 --- a/content/browser/renderer_host/pepper/pepper_truetype_font_host.cc +++ b/content/browser/renderer_host/pepper/pepper_truetype_font_host.cc
@@ -26,8 +26,7 @@ PP_Resource resource, const SerializedTrueTypeFontDesc& desc) : ResourceHost(host->GetPpapiHost(), instance, resource), - initialize_completed_(false), - weak_factory_(this) { + initialize_completed_(false) { font_ = PepperTrueTypeFont::Create(); // Initialize the font on a ThreadPool thread. This must complete before // using |font_|.
diff --git a/content/browser/renderer_host/pepper/pepper_truetype_font_host.h b/content/browser/renderer_host/pepper/pepper_truetype_font_host.h index cd1e701..2ecd9ba5 100644 --- a/content/browser/renderer_host/pepper/pepper_truetype_font_host.h +++ b/content/browser/renderer_host/pepper/pepper_truetype_font_host.h
@@ -62,7 +62,7 @@ scoped_refptr<PepperTrueTypeFont> font_; bool initialize_completed_; - base::WeakPtrFactory<PepperTrueTypeFontHost> weak_factory_; + base::WeakPtrFactory<PepperTrueTypeFontHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperTrueTypeFontHost); };
diff --git a/content/browser/renderer_host/plugin_registry_impl.cc b/content/browser/renderer_host/plugin_registry_impl.cc index 77df339..717db15 100644 --- a/content/browser/renderer_host/plugin_registry_impl.cc +++ b/content/browser/renderer_host/plugin_registry_impl.cc
@@ -18,7 +18,7 @@ } // namespace PluginRegistryImpl::PluginRegistryImpl(ResourceContext* resource_context) - : resource_context_(resource_context), weak_factory_(this) {} + : resource_context_(resource_context) {} PluginRegistryImpl::~PluginRegistryImpl() {}
diff --git a/content/browser/renderer_host/plugin_registry_impl.h b/content/browser/renderer_host/plugin_registry_impl.h index 3009401..061dd21c 100644 --- a/content/browser/renderer_host/plugin_registry_impl.h +++ b/content/browser/renderer_host/plugin_registry_impl.h
@@ -35,7 +35,7 @@ ResourceContext* const resource_context_; mojo::BindingSet<PluginRegistry> bindings_; base::TimeTicks last_plugin_refresh_time_; - base::WeakPtrFactory<PluginRegistryImpl> weak_factory_; + base::WeakPtrFactory<PluginRegistryImpl> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/renderer_host/render_frame_metadata_provider_impl.cc b/content/browser/renderer_host/render_frame_metadata_provider_impl.cc index 03a157b..0b18a02 100644 --- a/content/browser/renderer_host/render_frame_metadata_provider_impl.cc +++ b/content/browser/renderer_host/render_frame_metadata_provider_impl.cc
@@ -14,8 +14,7 @@ FrameTokenMessageQueue* frame_token_message_queue) : task_runner_(task_runner), frame_token_message_queue_(frame_token_message_queue), - render_frame_metadata_observer_client_binding_(this), - weak_factory_(this) {} + render_frame_metadata_observer_client_binding_(this) {} RenderFrameMetadataProviderImpl::~RenderFrameMetadataProviderImpl() = default;
diff --git a/content/browser/renderer_host/render_frame_metadata_provider_impl.h b/content/browser/renderer_host/render_frame_metadata_provider_impl.h index 51650fd75..f7d0ca9 100644 --- a/content/browser/renderer_host/render_frame_metadata_provider_impl.h +++ b/content/browser/renderer_host/render_frame_metadata_provider_impl.h
@@ -93,7 +93,7 @@ #endif base::Optional<bool> pending_report_all_frame_submission_for_testing_; - base::WeakPtrFactory<RenderFrameMetadataProviderImpl> weak_factory_; + base::WeakPtrFactory<RenderFrameMetadataProviderImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderFrameMetadataProviderImpl); };
diff --git a/content/browser/renderer_host/render_message_filter.cc b/content/browser/renderer_host/render_message_filter.cc index 9d4d674..2732bc7 100644 --- a/content/browser/renderer_host/render_message_filter.cc +++ b/content/browser/renderer_host/render_message_filter.cc
@@ -95,8 +95,7 @@ resource_context_(browser_context->GetResourceContext()), render_widget_helper_(render_widget_helper), render_process_id_(render_process_id), - media_internals_(media_internals), - weak_ptr_factory_(this) { + media_internals_(media_internals) { if (render_widget_helper) render_widget_helper_->Init(render_process_id_, resource_dispatcher_host_); }
diff --git a/content/browser/renderer_host/render_message_filter.h b/content/browser/renderer_host/render_message_filter.h index ef5bd796..81572a8 100644 --- a/content/browser/renderer_host/render_message_filter.h +++ b/content/browser/renderer_host/render_message_filter.h
@@ -118,7 +118,7 @@ MediaInternals* media_internals_; - base::WeakPtrFactory<RenderMessageFilter> weak_ptr_factory_; + base::WeakPtrFactory<RenderMessageFilter> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderMessageFilter); };
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 10344f3..ffe62c71 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -732,9 +732,7 @@ public: RenderProcessHostIsReadyObserver(RenderProcessHost* render_process_host, base::OnceClosure task) - : render_process_host_(render_process_host), - task_(std::move(task)), - weak_factory_(this) { + : render_process_host_(render_process_host), task_(std::move(task)) { render_process_host_->AddObserver(this); if (render_process_host_->IsReady()) PostTask(); @@ -768,7 +766,7 @@ RenderProcessHost* render_process_host_; base::OnceClosure task_; - base::WeakPtrFactory<RenderProcessHostIsReadyObserver> weak_factory_; + base::WeakPtrFactory<RenderProcessHostIsReadyObserver> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderProcessHostIsReadyObserver); }; @@ -1279,8 +1277,7 @@ std::unique_ptr<service_manager::BinderRegistry> registry) : child_identity_(child_identity), registry_(std::move(registry)), - controller_(new ConnectionFilterController(this)), - weak_factory_(this) { + controller_(new ConnectionFilterController(this)) { // Registration of this filter may race with browser shutdown, in which case // it's possible for this filter to be destroyed on the main thread. This // is fine as long as the filter hasn't been used on the IO thread yet. We @@ -1328,7 +1325,7 @@ base::Lock enabled_lock_; bool enabled_ GUARDED_BY(enabled_lock_) = true; - base::WeakPtrFactory<ConnectionFilterImpl> weak_factory_; + base::WeakPtrFactory<ConnectionFilterImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ConnectionFilterImpl); }; @@ -1527,8 +1524,7 @@ instance_weak_factory_( new base::WeakPtrFactory<RenderProcessHostImpl>(this)), frame_sink_provider_(id_), - shutdown_exit_code_(-1), - weak_factory_(this) { + shutdown_exit_code_(-1) { widget_helper_ = new RenderWidgetHelper(); ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID(), browser_context);
diff --git a/content/browser/renderer_host/render_process_host_impl.h b/content/browser/renderer_host/render_process_host_impl.h index 9284ad76..62e5a72 100644 --- a/content/browser/renderer_host/render_process_host_impl.h +++ b/content/browser/renderer_host/render_process_host_impl.h
@@ -895,7 +895,7 @@ IpcSendWatcher ipc_send_watcher_for_testing_; - base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_; + base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl); };
diff --git a/content/browser/renderer_host/render_view_host_impl.cc b/content/browser/renderer_host/render_view_host_impl.cc index ade78e33..62bde0f 100644 --- a/content/browser/renderer_host/render_view_host_impl.cc +++ b/content/browser/renderer_host/render_view_host_impl.cc
@@ -227,8 +227,7 @@ is_waiting_for_close_ack_(false), sudden_termination_allowed_(false), updating_web_preferences_(false), - has_notified_about_creation_(false), - weak_factory_(this) { + has_notified_about_creation_(false) { DCHECK(instance_.get()); CHECK(delegate_); // http://crbug.com/82827 DCHECK_NE(GetRoutingID(), render_widget_host_->GetRoutingID());
diff --git a/content/browser/renderer_host/render_view_host_impl.h b/content/browser/renderer_host/render_view_host_impl.h index a23d425..78ad7b0 100644 --- a/content/browser/renderer_host/render_view_host_impl.h +++ b/content/browser/renderer_host/render_view_host_impl.h
@@ -349,7 +349,7 @@ // duplicate RenderViewCreated events. bool has_notified_about_creation_; - base::WeakPtrFactory<RenderViewHostImpl> weak_factory_; + base::WeakPtrFactory<RenderViewHostImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderViewHostImpl); };
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index 650b965c..ba406465 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -364,8 +364,7 @@ #endif frame_token_message_queue_.get()), frame_sink_id_(base::checked_cast<uint32_t>(process_->GetID()), - base::checked_cast<uint32_t>(routing_id_)), - weak_factory_(this) { + base::checked_cast<uint32_t>(routing_id_)) { #if defined(OS_MACOSX) fling_scheduler_ = std::make_unique<FlingSchedulerMac>(this); #elif defined(OS_ANDROID)
diff --git a/content/browser/renderer_host/render_widget_host_impl.h b/content/browser/renderer_host/render_widget_host_impl.h index 93a1e1b..655e18f 100644 --- a/content/browser/renderer_host/render_widget_host_impl.h +++ b/content/browser/renderer_host/render_widget_host_impl.h
@@ -1210,7 +1210,7 @@ // Event IDs for touch event acks that should be ignored. std::unordered_set<uint32_t> touch_event_acks_to_ignore_; - base::WeakPtrFactory<RenderWidgetHostImpl> weak_factory_; + base::WeakPtrFactory<RenderWidgetHostImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostImpl); };
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index c7ecfca..c1db0e5 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -459,8 +459,7 @@ last_device_scale_factor_(1.f), active_touches_(0), event_targeter_(std::make_unique<RenderWidgetTargeter>(this)), - touch_event_ack_queue_(new TouchEventAckQueue(this)), - weak_ptr_factory_(this) { + touch_event_ack_queue_(new TouchEventAckQueue(this)) { viz::HostFrameSinkManager* manager = GetHostFrameSinkManager(); DCHECK(manager); manager->AddHitTestRegionObserver(this);
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.h b/content/browser/renderer_host/render_widget_host_input_event_router.h index 27ab31c..f162c4cd 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.h +++ b/content/browser/renderer_host/render_widget_host_input_event_router.h
@@ -398,7 +398,8 @@ std::unique_ptr<TouchEmulator> touch_emulator_; std::unique_ptr<TouchEventAckQueue> touch_event_ack_queue_; - base::WeakPtrFactory<RenderWidgetHostInputEventRouter> weak_ptr_factory_; + base::WeakPtrFactory<RenderWidgetHostInputEventRouter> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostInputEventRouter); friend class RenderWidgetHostInputEventRouterTest;
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index 5e5be87..5000924 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -350,8 +350,7 @@ device_scale_factor_(0.0f), event_handler_(new RenderWidgetHostViewEventHandler(host(), this, this)), frame_sink_id_(is_guest_view_hack_ ? AllocateFrameSinkIdForGuestViewHack() - : host()->GetFrameSinkId()), - weak_ptr_factory_(this) { + : host()->GetFrameSinkId()) { CreateDelegatedFrameHostClient(); if (!is_guest_view_hack_)
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.h b/content/browser/renderer_host/render_widget_host_view_aura.h index 1f696b97..dca3ebf 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.h +++ b/content/browser/renderer_host/render_widget_host_view_aura.h
@@ -707,7 +707,7 @@ // See OnDisplayMetricsChanged() for details. bool needs_to_update_display_metrics_ = false; - base::WeakPtrFactory<RenderWidgetHostViewAura> weak_ptr_factory_; + base::WeakPtrFactory<RenderWidgetHostViewAura> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewAura); };
diff --git a/content/browser/renderer_host/render_widget_host_view_base.cc b/content/browser/renderer_host/render_widget_host_view_base.cc index cd8d45ce..f41270e 100644 --- a/content/browser/renderer_host/render_widget_host_view_base.cc +++ b/content/browser/renderer_host/render_widget_host_view_base.cc
@@ -42,7 +42,7 @@ namespace content { RenderWidgetHostViewBase::RenderWidgetHostViewBase(RenderWidgetHost* host) - : host_(RenderWidgetHostImpl::From(host)), weak_factory_(this) { + : host_(RenderWidgetHostImpl::From(host)) { host_->render_frame_metadata_provider()->AddObserver(this); }
diff --git a/content/browser/renderer_host/render_widget_host_view_base.h b/content/browser/renderer_host/render_widget_host_view_base.h index 5bac450f..39081269 100644 --- a/content/browser/renderer_host/render_widget_host_view_base.h +++ b/content/browser/renderer_host/render_widget_host_view_base.h
@@ -686,7 +686,7 @@ bool is_evicted_ = false; - base::WeakPtrFactory<RenderWidgetHostViewBase> weak_factory_; + base::WeakPtrFactory<RenderWidgetHostViewBase> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewBase); };
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.cc b/content/browser/renderer_host/render_widget_host_view_child_frame.cc index 97b52ad..fbb86a38 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.cc
@@ -68,8 +68,7 @@ frame_connector_(nullptr), enable_viz_(features::IsVizDisplayCompositorEnabled()), enable_surface_synchronization_( - features::IsSurfaceSynchronizationEnabled()), - weak_factory_(this) { + features::IsSurfaceSynchronizationEnabled()) { GetHostFrameSinkManager()->RegisterFrameSinkId( frame_sink_id_, this, enable_surface_synchronization_
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.h b/content/browser/renderer_host/render_widget_host_view_child_frame.h index f79c952a..963a056 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.h +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.h
@@ -320,7 +320,7 @@ // True if there is currently a scroll sequence being bubbled to our parent. bool is_scroll_sequence_bubbling_ = false; - base::WeakPtrFactory<RenderWidgetHostViewChildFrame> weak_factory_; + base::WeakPtrFactory<RenderWidgetHostViewChildFrame> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewChildFrame); };
diff --git a/content/browser/renderer_host/render_widget_targeter.cc b/content/browser/renderer_host/render_widget_targeter.cc index 50bc7544d..0ee1b50 100644 --- a/content/browser/renderer_host/render_widget_targeter.cc +++ b/content/browser/renderer_host/render_widget_targeter.cc
@@ -159,8 +159,7 @@ : trace_id_(base::RandUint64()), is_viz_hit_testing_debug_enabled_( features::IsVizHitTestingDebugEnabled()), - delegate_(delegate), - weak_ptr_factory_(this) { + delegate_(delegate) { DCHECK(delegate_); }
diff --git a/content/browser/renderer_host/render_widget_targeter.h b/content/browser/renderer_host/render_widget_targeter.h index d6b9834..ba4778b 100644 --- a/content/browser/renderer_host/render_widget_targeter.h +++ b/content/browser/renderer_host/render_widget_targeter.h
@@ -247,7 +247,7 @@ std::vector<viz::FrameSinkId> hit_test_async_queried_debug_queue_; Delegate* const delegate_; - base::WeakPtrFactory<RenderWidgetTargeter> weak_ptr_factory_; + base::WeakPtrFactory<RenderWidgetTargeter> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderWidgetTargeter); };
diff --git a/content/browser/renderer_host/web_database_host_impl.cc b/content/browser/renderer_host/web_database_host_impl.cc index 195dd66..b9ecdcfc 100644 --- a/content/browser/renderer_host/web_database_host_impl.cc +++ b/content/browser/renderer_host/web_database_host_impl.cc
@@ -69,8 +69,7 @@ scoped_refptr<storage::DatabaseTracker> db_tracker) : process_id_(process_id), observer_added_(false), - db_tracker_(std::move(db_tracker)), - weak_ptr_factory_(this) { + db_tracker_(std::move(db_tracker)) { DCHECK(db_tracker_); }
diff --git a/content/browser/renderer_host/web_database_host_impl.h b/content/browser/renderer_host/web_database_host_impl.h index 4f4b790..8615c1b 100644 --- a/content/browser/renderer_host/web_database_host_impl.h +++ b/content/browser/renderer_host/web_database_host_impl.h
@@ -158,7 +158,7 @@ // Note: This should remain the last member so it'll be destroyed and // invalidate its weak pointers before any other members are destroyed. - base::WeakPtrFactory<WebDatabaseHostImpl> weak_ptr_factory_; + base::WeakPtrFactory<WebDatabaseHostImpl> weak_ptr_factory_{this}; }; } // namespace content
diff --git a/content/browser/service_worker/embedded_worker_instance.cc b/content/browser/service_worker/embedded_worker_instance.cc index 0ef8879..5c1f584 100644 --- a/content/browser/service_worker/embedded_worker_instance.cc +++ b/content/browser/service_worker/embedded_worker_instance.cc
@@ -429,8 +429,7 @@ is_installed_(false), started_during_browser_startup_(false), skip_recording_startup_time_(instance_->devtools_attached()), - start_time_(start_time), - weak_factory_(this) { + start_time_(start_time) { DCHECK_CURRENTLY_ON(BrowserThread::IO); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("ServiceWorker", "EmbeddedWorkerInstance::Start", this, @@ -635,7 +634,7 @@ base::TimeTicks start_worker_sent_time_; base::TimeDelta thread_hop_time_; - base::WeakPtrFactory<StartTask> weak_factory_; + base::WeakPtrFactory<StartTask> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(StartTask); }; @@ -741,8 +740,7 @@ network_accessed_for_script_(false), foreground_notified_(false), ui_task_runner_( - base::CreateSequencedTaskRunnerWithTraits({BrowserThread::UI})), - weak_factory_(this) { + base::CreateSequencedTaskRunnerWithTraits({BrowserThread::UI})) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(context_); }
diff --git a/content/browser/service_worker/embedded_worker_instance.h b/content/browser/service_worker/embedded_worker_instance.h index 8d3c692..6db7061 100644 --- a/content/browser/service_worker/embedded_worker_instance.h +++ b/content/browser/service_worker/embedded_worker_instance.h
@@ -363,7 +363,7 @@ const scoped_refptr<base::SequencedTaskRunner> ui_task_runner_; - base::WeakPtrFactory<EmbeddedWorkerInstance> weak_factory_; + base::WeakPtrFactory<EmbeddedWorkerInstance> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(EmbeddedWorkerInstance); };
diff --git a/content/browser/service_worker/fake_embedded_worker_instance_client.cc b/content/browser/service_worker/fake_embedded_worker_instance_client.cc index 80b8b33..7c32736 100644 --- a/content/browser/service_worker/fake_embedded_worker_instance_client.cc +++ b/content/browser/service_worker/fake_embedded_worker_instance_client.cc
@@ -15,7 +15,7 @@ FakeEmbeddedWorkerInstanceClient::FakeEmbeddedWorkerInstanceClient( EmbeddedWorkerTestHelper* helper) - : helper_(helper), binding_(this), weak_factory_(this) {} + : helper_(helper), binding_(this) {} FakeEmbeddedWorkerInstanceClient::~FakeEmbeddedWorkerInstanceClient() = default;
diff --git a/content/browser/service_worker/fake_embedded_worker_instance_client.h b/content/browser/service_worker/fake_embedded_worker_instance_client.h index f0abcad9..bd57d29 100644 --- a/content/browser/service_worker/fake_embedded_worker_instance_client.h +++ b/content/browser/service_worker/fake_embedded_worker_instance_client.h
@@ -74,7 +74,7 @@ mojo::Binding<blink::mojom::EmbeddedWorkerInstanceClient> binding_; base::OnceClosure quit_closure_for_bind_; - base::WeakPtrFactory<FakeEmbeddedWorkerInstanceClient> weak_factory_; + base::WeakPtrFactory<FakeEmbeddedWorkerInstanceClient> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FakeEmbeddedWorkerInstanceClient); };
diff --git a/content/browser/service_worker/service_worker_cache_writer.cc b/content/browser/service_worker/service_worker_cache_writer.cc index 1935f81..6ec47bf 100644 --- a/content/browser/service_worker/service_worker_cache_writer.cc +++ b/content/browser/service_worker/service_worker_cache_writer.cc
@@ -128,8 +128,7 @@ pause_when_not_identical_(pause_when_not_identical), compare_reader_(std::move(compare_reader)), copy_reader_(std::move(copy_reader)), - writer_(std::move(writer)), - weak_factory_(this) {} + writer_(std::move(writer)) {} ServiceWorkerCacheWriter::~ServiceWorkerCacheWriter() {}
diff --git a/content/browser/service_worker/service_worker_cache_writer.h b/content/browser/service_worker/service_worker_cache_writer.h index d0b74fb8..ee94806 100644 --- a/content/browser/service_worker/service_worker_cache_writer.h +++ b/content/browser/service_worker/service_worker_cache_writer.h
@@ -317,7 +317,7 @@ std::unique_ptr<ServiceWorkerResponseReader> compare_reader_; std::unique_ptr<ServiceWorkerResponseReader> copy_reader_; std::unique_ptr<ServiceWorkerResponseWriter> writer_; - base::WeakPtrFactory<ServiceWorkerCacheWriter> weak_factory_; + base::WeakPtrFactory<ServiceWorkerCacheWriter> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/service_worker/service_worker_context_core.cc b/content/browser/service_worker/service_worker_context_core.cc index d63b7e9..46318162 100644 --- a/content/browser/service_worker/service_worker_context_core.cc +++ b/content/browser/service_worker/service_worker_context_core.cc
@@ -258,8 +258,7 @@ loader_factory_getter_(url_loader_factory_getter), force_update_on_page_load_(false), was_service_worker_registered_(false), - observer_list_(observer_list), - weak_factory_(this) { + observer_list_(observer_list) { DCHECK(observer_list_); // These get a WeakPtr from |weak_factory_|, so must be set after // |weak_factory_| is initialized. @@ -279,8 +278,7 @@ was_service_worker_registered_( old_context->was_service_worker_registered_), observer_list_(old_context->observer_list_), - next_embedded_worker_id_(old_context->next_embedded_worker_id_), - weak_factory_(this) { + next_embedded_worker_id_(old_context->next_embedded_worker_id_) { DCHECK(observer_list_); // These get a WeakPtr from |weak_factory_|, so must be set after
diff --git a/content/browser/service_worker/service_worker_context_core.h b/content/browser/service_worker/service_worker_context_core.h index 295dced..51ca4a82 100644 --- a/content/browser/service_worker/service_worker_context_core.h +++ b/content/browser/service_worker/service_worker_context_core.h
@@ -359,7 +359,7 @@ int next_embedded_worker_id_ = 0; - base::WeakPtrFactory<ServiceWorkerContextCore> weak_factory_; + base::WeakPtrFactory<ServiceWorkerContextCore> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerContextCore); };
diff --git a/content/browser/service_worker/service_worker_context_watcher_unittest.cc b/content/browser/service_worker/service_worker_context_watcher_unittest.cc index 4f6ada70..7585751 100644 --- a/content/browser/service_worker/service_worker_context_watcher_unittest.cc +++ b/content/browser/service_worker/service_worker_context_watcher_unittest.cc
@@ -35,7 +35,7 @@ class WatcherCallback { public: - WatcherCallback() : weak_factory_(this) {} + WatcherCallback() {} ~WatcherCallback() {} @@ -114,7 +114,7 @@ int callback_count_ = 0; - base::WeakPtrFactory<WatcherCallback> weak_factory_; + base::WeakPtrFactory<WatcherCallback> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WatcherCallback); };
diff --git a/content/browser/service_worker/service_worker_context_wrapper.h b/content/browser/service_worker/service_worker_context_wrapper.h index e5f6fb2..36d7316a 100644 --- a/content/browser/service_worker/service_worker_context_wrapper.h +++ b/content/browser/service_worker/service_worker_context_wrapper.h
@@ -309,6 +309,11 @@ blink::mojom::ServiceWorkerProviderType provider_type, blink::mojom::ServiceWorkerProviderInfoForWorkerPtr* out_provider_info); + // The core context is only for use on the IO thread. + // Can be null before/during init, during/after shutdown, and after + // DeleteAndStartOver fails. + ServiceWorkerContextCore* context(); + private: friend class BackgroundSyncManagerTest; friend class base::RefCountedThreadSafe<ServiceWorkerContextWrapper>; @@ -414,11 +419,6 @@ blink::ServiceWorkerStatusCode status, scoped_refptr<ServiceWorkerRegistration> registration); - // The core context is only for use on the IO thread. - // Can be null before/during init, during/after shutdown, and after - // DeleteAndStartOver fails. - ServiceWorkerContextCore* context(); - void GetAllServiceWorkerRunningInfosOnIO( GetAllServiceWorkerRunningInfosCallback callback, scoped_refptr<base::SingleThreadTaskRunner> task_runner_for_callback);
diff --git a/content/browser/service_worker/service_worker_controllee_request_handler.cc b/content/browser/service_worker/service_worker_controllee_request_handler.cc index 92d4d956..18bc087b 100644 --- a/content/browser/service_worker/service_worker_controllee_request_handler.cc +++ b/content/browser/service_worker/service_worker_controllee_request_handler.cc
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/trace_event/trace_event.h" #include "components/offline_pages/buildflags/buildflags.h" +#include "content/browser/loader/navigation_url_loader_impl.h" #include "content/browser/navigation_subresource_loader_params.h" #include "content/browser/service_worker/service_worker_context_core.h" #include "content/browser/service_worker/service_worker_metrics.h" @@ -67,8 +68,7 @@ : context_(std::move(context)), provider_host_(std::move(provider_host)), resource_type_(resource_type), - force_update_started_(false), - weak_factory_(this) { + force_update_started_(false) { DCHECK(ServiceWorkerUtils::IsMainResourceType(resource_type)); } @@ -227,15 +227,23 @@ return; } - if (!GetContentClient()->browser()->AllowServiceWorker( - registration->scope(), provider_host_->site_for_cookies(), GURL(), - resource_context_, provider_host_->web_contents_getter())) { - TRACE_EVENT_ASYNC_END1( - "ServiceWorker", - "ServiceWorkerControlleeRequestHandler::MaybeCreateLoader", this, - "Info", "ServiceWorker is blocked"); - CompleteWithoutLoader(); - return; + if (NavigationURLLoaderImpl::IsNavigationLoaderOnUIEnabled()) { + // AllowServiceWorker() expects to be called on the IO thread with a valid + // ResourceContext, and we have a null context here, so skip calling it. + // TODO(crbug.com/926114, crbug.com/908955): Implement + // AllowServiceWorkerUI() with a browser_context instead of + // resource_context? + } else { + if (!GetContentClient()->browser()->AllowServiceWorker( + registration->scope(), provider_host_->site_for_cookies(), GURL(), + resource_context_, provider_host_->web_contents_getter())) { + TRACE_EVENT_ASYNC_END1( + "ServiceWorker", + "ServiceWorkerControlleeRequestHandler::PrepareForMainResource", this, + "Info", "ServiceWorker is blocked"); + CompleteWithoutLoader(); + return; + } } if (!provider_host_->IsContextSecureForServiceWorker()) { @@ -370,7 +378,7 @@ // ServiceWorkerNavigationLoader which does that work. loader_wrapper_ = std::make_unique<ServiceWorkerNavigationLoaderWrapper>( std::make_unique<ServiceWorkerNavigationLoader>( - std::move(fallback_callback_), this, provider_host_, + std::move(fallback_callback_), provider_host_, base::WrapRefCounted(context_->loader_factory_getter()))); TRACE_EVENT_ASYNC_END1( @@ -447,25 +455,6 @@ weak_factory_.GetWeakPtr(), std::move(registration), version)); } -ServiceWorkerVersion* -ServiceWorkerControlleeRequestHandler::GetServiceWorkerVersion() { - if (!provider_host_) - return nullptr; - return provider_host_->controller(); -} - -bool ServiceWorkerControlleeRequestHandler::RequestStillValid() { - // A null |provider_host_| probably means the tab was closed. The null value - // would cause problems down the line, so bail out. - return !!provider_host_; -} - -void ServiceWorkerControlleeRequestHandler::MainResourceLoadFailed() { - DCHECK(provider_host_); - // Detach the controller so subresource requests also skip the worker. - provider_host_->NotifyControllerLost(); -} - void ServiceWorkerControlleeRequestHandler::ClearJob() { // Invalidate weak pointers to cancel RegisterStatusChangeCallback(). // Otherwise we may end up calling ForwardToServiceWorer()
diff --git a/content/browser/service_worker/service_worker_controllee_request_handler.h b/content/browser/service_worker/service_worker_controllee_request_handler.h index 5b53366..5509243 100644 --- a/content/browser/service_worker/service_worker_controllee_request_handler.h +++ b/content/browser/service_worker/service_worker_controllee_request_handler.h
@@ -33,10 +33,8 @@ // Handles main resource requests for service worker clients (documents and // shared workers). -// TODO(falken): Rename to ServiceWorkerNavigationLoaderInterceptor. class CONTENT_EXPORT ServiceWorkerControlleeRequestHandler final - : public NavigationLoaderInterceptor, - public ServiceWorkerNavigationLoader::Delegate { + : public NavigationLoaderInterceptor { public: ServiceWorkerControlleeRequestHandler( base::WeakPtr<ServiceWorkerContextCore> context, @@ -86,11 +84,6 @@ scoped_refptr<ServiceWorkerRegistration> registration, scoped_refptr<ServiceWorkerVersion> version); - // ServiceWorkerNavigationLoader::Delegate implementation: - ServiceWorkerVersion* GetServiceWorkerVersion() override; - bool RequestStillValid() override; - void MainResourceLoadFailed() override; - // Sets |job_| to nullptr, and clears all extra response info associated with // that job, except for timing information. void ClearJob(); @@ -113,7 +106,8 @@ LoaderCallback loader_callback_; FallbackCallback fallback_callback_; - base::WeakPtrFactory<ServiceWorkerControlleeRequestHandler> weak_factory_; + base::WeakPtrFactory<ServiceWorkerControlleeRequestHandler> weak_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerControlleeRequestHandler); };
diff --git a/content/browser/service_worker/service_worker_database.h b/content/browser/service_worker/service_worker_database.h index 9274e7dd..ece2d352 100644 --- a/content/browser/service_worker/service_worker_database.h +++ b/content/browser/service_worker/service_worker_database.h
@@ -24,6 +24,7 @@ #include "content/common/service_worker/service_worker_types.h" #include "third_party/blink/public/common/origin_trials/trial_token_validator.h" #include "third_party/blink/public/common/service_worker/service_worker_status_code.h" +#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h" #include "third_party/blink/public/mojom/web_feature/web_feature.mojom.h" #include "url/gurl.h" #include "url/origin.h"
diff --git a/content/browser/service_worker/service_worker_fetch_dispatcher.cc b/content/browser/service_worker/service_worker_fetch_dispatcher.cc index 148ec3ac..5f7459ef 100644 --- a/content/browser/service_worker/service_worker_fetch_dispatcher.cc +++ b/content/browser/service_worker/service_worker_fetch_dispatcher.cc
@@ -467,8 +467,7 @@ resource_type_(resource_type), prepare_callback_(std::move(prepare_callback)), fetch_callback_(std::move(fetch_callback)), - did_complete_(false), - weak_factory_(this) { + did_complete_(false) { DCHECK(!request_->blob); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( "ServiceWorker", "ServiceWorkerFetchDispatcher::DispatchFetchEvent", this,
diff --git a/content/browser/service_worker/service_worker_fetch_dispatcher.h b/content/browser/service_worker/service_worker_fetch_dispatcher.h index a7940e04..5cebdd7 100644 --- a/content/browser/service_worker/service_worker_fetch_dispatcher.h +++ b/content/browser/service_worker/service_worker_fetch_dispatcher.h
@@ -123,7 +123,7 @@ // service worker along with the fetch event. blink::mojom::FetchEventPreloadHandlePtr preload_handle_; - base::WeakPtrFactory<ServiceWorkerFetchDispatcher> weak_factory_; + base::WeakPtrFactory<ServiceWorkerFetchDispatcher> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerFetchDispatcher); };
diff --git a/content/browser/service_worker/service_worker_installed_script_reader.cc b/content/browser/service_worker/service_worker_installed_script_reader.cc index da9100fa..5b95b7c0 100644 --- a/content/browser/service_worker/service_worker_installed_script_reader.cc +++ b/content/browser/service_worker/service_worker_installed_script_reader.cc
@@ -25,8 +25,7 @@ handle_(std::move(handle)), watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC, - base::SequencedTaskRunnerHandle::Get()), - weak_factory_(this) {} + base::SequencedTaskRunnerHandle::Get()) {} void Start(base::OnceCallback<void(bool /* success */)> callback) { callback_ = std::move(callback); @@ -89,7 +88,7 @@ mojo::ScopedDataPipeProducerHandle handle_; mojo::SimpleWatcher watcher_; - base::WeakPtrFactory<MetaDataSender> weak_factory_; + base::WeakPtrFactory<MetaDataSender> weak_factory_{this}; }; ServiceWorkerInstalledScriptReader::ServiceWorkerInstalledScriptReader( @@ -99,8 +98,7 @@ client_(client), body_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, - base::SequencedTaskRunnerHandle::Get()), - weak_factory_(this) {} + base::SequencedTaskRunnerHandle::Get()) {} ServiceWorkerInstalledScriptReader::~ServiceWorkerInstalledScriptReader() {}
diff --git a/content/browser/service_worker/service_worker_installed_script_reader.h b/content/browser/service_worker/service_worker_installed_script_reader.h index 6db97cc1..f60d869 100644 --- a/content/browser/service_worker/service_worker_installed_script_reader.h +++ b/content/browser/service_worker/service_worker_installed_script_reader.h
@@ -96,7 +96,7 @@ uint64_t body_size_ = std::numeric_limits<uint64_t>::max(); uint64_t body_bytes_sent_ = 0; - base::WeakPtrFactory<ServiceWorkerInstalledScriptReader> weak_factory_; + base::WeakPtrFactory<ServiceWorkerInstalledScriptReader> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/service_worker/service_worker_job_unittest.cc b/content/browser/service_worker/service_worker_job_unittest.cc index e9960c2..b8ba52f7 100644 --- a/content/browser/service_worker/service_worker_job_unittest.cc +++ b/content/browser/service_worker/service_worker_job_unittest.cc
@@ -1170,8 +1170,7 @@ ServiceWorkerVersion::Status status; }; - UpdateJobTestHelper() - : EmbeddedWorkerTestHelper(base::FilePath()), weak_factory_(this) { + UpdateJobTestHelper() : EmbeddedWorkerTestHelper(base::FilePath()) { context_wrapper()->AddObserver(this); if (base::FeatureList::IsEnabled( blink::features::kServiceWorkerImportedScriptUpdateCheck)) { @@ -1344,7 +1343,7 @@ std::unique_ptr<FakeNetworkURLLoaderFactory> loader_factory_for_update_checker_; - base::WeakPtrFactory<UpdateJobTestHelper> weak_factory_; + base::WeakPtrFactory<UpdateJobTestHelper> weak_factory_{this}; }; } // namespace
diff --git a/content/browser/service_worker/service_worker_navigation_handle.cc b/content/browser/service_worker/service_worker_navigation_handle.cc index e86fb6f..0eb63fc0 100644 --- a/content/browser/service_worker/service_worker_navigation_handle.cc +++ b/content/browser/service_worker/service_worker_navigation_handle.cc
@@ -16,8 +16,7 @@ namespace content { ServiceWorkerNavigationHandle::ServiceWorkerNavigationHandle( - ServiceWorkerContextWrapper* context_wrapper) - : weak_factory_(this) { + ServiceWorkerContextWrapper* context_wrapper) { DCHECK_CURRENTLY_ON(BrowserThread::UI); core_ = new ServiceWorkerNavigationHandleCore(weak_factory_.GetWeakPtr(), context_wrapper);
diff --git a/content/browser/service_worker/service_worker_navigation_handle.h b/content/browser/service_worker/service_worker_navigation_handle.h index c11f08f..e4cdc8b 100644 --- a/content/browser/service_worker/service_worker_navigation_handle.h +++ b/content/browser/service_worker/service_worker_navigation_handle.h
@@ -20,7 +20,7 @@ // // The lifetime of the ServiceWorkerNavigationHandle, the // ServiceWorkerNavigationHandleCore and the ServiceWorkerProviderHost are the -// following : +// following: // 1) We create a ServiceWorkerNavigationHandle on the UI thread without // populating the member service worker provider info. This also leads to the // creation of a ServiceWorkerNavigationHandleCore. @@ -74,7 +74,7 @@ // TODO(leonhsl): Use std::unique_ptr<ServiceWorkerNavigationHandleCore, // BrowserThread::DeleteOnIOThread> instead. ServiceWorkerNavigationHandleCore* core_; - base::WeakPtrFactory<ServiceWorkerNavigationHandle> weak_factory_; + base::WeakPtrFactory<ServiceWorkerNavigationHandle> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerNavigationHandle); };
diff --git a/content/browser/service_worker/service_worker_navigation_handle_core.cc b/content/browser/service_worker/service_worker_navigation_handle_core.cc index 26b0570..c627630 100644 --- a/content/browser/service_worker/service_worker_navigation_handle_core.cc +++ b/content/browser/service_worker/service_worker_navigation_handle_core.cc
@@ -4,8 +4,6 @@ #include "content/browser/service_worker/service_worker_navigation_handle_core.h" -#include <utility> - #include "base/bind.h" #include "base/task/post_task.h" #include "content/browser/service_worker/service_worker_context_wrapper.h"
diff --git a/content/browser/service_worker/service_worker_navigation_handle_core.h b/content/browser/service_worker/service_worker_navigation_handle_core.h index 1ee49d1..b1e7d0c 100644 --- a/content/browser/service_worker/service_worker_navigation_handle_core.h +++ b/content/browser/service_worker/service_worker_navigation_handle_core.h
@@ -6,6 +6,7 @@ #define CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_NAVIGATION_HANDLE_CORE_H_ #include <memory> +#include <utility> #include "base/macros.h" #include "base/memory/ref_counted.h" @@ -19,7 +20,6 @@ class ServiceWorkerNavigationHandle; class ServiceWorkerProviderHost; -// PlzNavigate // This class is created on the UI thread, but should only be accessed from the // IO thread afterwards. It is the IO thread pendant of // ServiceWorkerNavigationHandle. See the ServiceWorkerNavigationHandle header @@ -36,6 +36,11 @@ base::WeakPtr<ServiceWorkerProviderHost> provider_host, blink::mojom::ServiceWorkerProviderInfoForWindowPtr provider_info); + void set_provider_host( + base::WeakPtr<ServiceWorkerProviderHost> provider_host) { + provider_host_ = std::move(provider_host); + } + // Called when the navigation is ready to commit, set the 2 IDs for the // pre-created provider host. void OnBeginNavigationCommit(int render_process_id, int render_frame_id);
diff --git a/content/browser/service_worker/service_worker_navigation_loader.cc b/content/browser/service_worker/service_worker_navigation_loader.cc index d74ca80..1b1fa14 100644 --- a/content/browser/service_worker/service_worker_navigation_loader.cc +++ b/content/browser/service_worker/service_worker_navigation_loader.cc
@@ -17,14 +17,13 @@ #include "base/trace_event/trace_event.h" #include "content/browser/service_worker/service_worker_context_core.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" +#include "content/browser/service_worker/service_worker_metrics.h" #include "content/browser/service_worker/service_worker_provider_host.h" #include "content/browser/service_worker/service_worker_version.h" -#include "content/browser/url_loader_factory_getter.h" #include "content/common/fetch/fetch_request_type_converters.h" #include "content/common/service_worker/service_worker_loader_helpers.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/resource_request_info.h" #include "services/network/public/cpp/features.h" #include "services/network/public/mojom/fetch_api.mojom.h" @@ -79,22 +78,17 @@ ServiceWorkerNavigationLoader::ServiceWorkerNavigationLoader( NavigationLoaderInterceptor::FallbackCallback fallback_callback, - Delegate* delegate, base::WeakPtr<ServiceWorkerProviderHost> provider_host, scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter) : fallback_callback_(std::move(fallback_callback)), - delegate_(delegate), provider_host_(std::move(provider_host)), url_loader_factory_getter_(std::move(url_loader_factory_getter)), - binding_(this), - weak_factory_(this) { + binding_(this) { TRACE_EVENT_WITH_FLOW0( "ServiceWorker", "ServiceWorkerNavigationLoader::ServiceWorkerNavigationLoader", this, TRACE_EVENT_FLAG_FLOW_OUT); - DCHECK(delegate_); - response_head_.load_timing.request_start = base::TimeTicks::Now(); response_head_.load_timing.request_start_time = base::Time::Now(); } @@ -107,7 +101,7 @@ } void ServiceWorkerNavigationLoader::DetachedFromRequest() { - delegate_ = nullptr; + is_detached_ = true; DeleteIfNeeded(); } @@ -126,6 +120,7 @@ "url", resource_request.url.spec()); DCHECK(ServiceWorkerUtils::IsMainResourceType( static_cast<ResourceType>(resource_request.resource_type))); + DCHECK_CURRENTLY_ON(BrowserThread::IO); resource_request_ = resource_request; if (provider_host_ && provider_host_->fetch_request_window_id()) { @@ -133,7 +128,6 @@ base::make_optional(provider_host_->fetch_request_window_id()); } - DCHECK(delegate_); DCHECK(!binding_.is_bound()); DCHECK(!url_loader_client_.is_bound()); binding_.Bind(std::move(request)); @@ -144,12 +138,6 @@ TransitionToStatus(Status::kStarted); - ServiceWorkerVersion* active_worker = delegate_->GetServiceWorkerVersion(); - if (!active_worker) { - CommitCompleted(net::ERR_FAILED, "No active worker"); - return; - } - if (!provider_host_) { // We lost |provider_host_| (for the client) somehow before dispatching // FetchEvent. @@ -157,6 +145,13 @@ return; } + scoped_refptr<ServiceWorkerVersion> active_worker = + provider_host_->controller(); + if (!active_worker) { + CommitCompleted(net::ERR_FAILED, "No active worker"); + return; + } + base::WeakPtr<ServiceWorkerContextCore> core = active_worker->context(); if (!core) { CommitCompleted(net::ERR_ABORTED, "No service worker context"); @@ -171,8 +166,7 @@ static_cast<ResourceType>(resource_request_.resource_type), provider_host_->client_uuid(), active_worker, base::BindOnce(&ServiceWorkerNavigationLoader::DidPrepareFetchEvent, - weak_factory_.GetWeakPtr(), - base::WrapRefCounted(active_worker), + weak_factory_.GetWeakPtr(), active_worker, active_worker->running_status()), base::BindOnce(&ServiceWorkerNavigationLoader::DidDispatchFetchEvent, weak_factory_.GetWeakPtr())); @@ -274,9 +268,9 @@ ServiceWorkerMetrics::RecordFetchEventStatus(true /* is_main_resource */, status); - if (!delegate_ || !delegate_->RequestStillValid()) { + if (!provider_host_) { // The navigation or shared worker startup is cancelled. Just abort. - CommitCompleted(net::ERR_ABORTED, "No delegate"); + CommitCompleted(net::ERR_ABORTED, "No provider host"); return; } @@ -288,7 +282,7 @@ // It'd be more correct and simpler to remove this path and show an error // page, but the risk is that the user will be stuck if there's a persistent // failure. - delegate_->MainResourceLoadFailed(); + provider_host_->NotifyControllerLost(); std::move(fallback_callback_) .Run(true /* reset_subresource_loader_params */); return; @@ -466,7 +460,7 @@ } void ServiceWorkerNavigationLoader::DeleteIfNeeded() { - if (!binding_.is_bound() && !delegate_) + if (!binding_.is_bound() && is_detached_) delete this; }
diff --git a/content/browser/service_worker/service_worker_navigation_loader.h b/content/browser/service_worker/service_worker_navigation_loader.h index af871ed..674e6f1 100644 --- a/content/browser/service_worker/service_worker_navigation_loader.h +++ b/content/browser/service_worker/service_worker_navigation_loader.h
@@ -10,11 +10,11 @@ #include <vector> #include "base/macros.h" +#include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "content/browser/loader/navigation_loader_interceptor.h" #include "content/browser/service_worker/embedded_worker_status.h" #include "content/browser/service_worker/service_worker_fetch_dispatcher.h" -#include "content/browser/service_worker/service_worker_metrics.h" #include "content/browser/url_loader_factory_getter.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "mojo/public/cpp/system/data_pipe.h" @@ -30,10 +30,10 @@ class ServiceWorkerProviderHost; // ServiceWorkerNavigationLoader is the URLLoader used for main resource -// requests (i.e., navigation and shared worker requests) that (potentially) go -// through a service worker. This loader is only used for the main resource -// request; once the response is delivered, the resulting client loads -// subresources via ServiceWorkerSubresourceLoader. +// requests (i.e., navigation and shared worker requests) that go through a +// service worker. This loader is only used for the main resource request; once +// the response is delivered, the resulting client loads subresources via +// ServiceWorkerSubresourceLoader. // // This class is owned by ServiceWorkerControlleeRequestHandler until it is // bound to a URLLoader request. After it is bound |this| is kept alive until @@ -41,25 +41,6 @@ class CONTENT_EXPORT ServiceWorkerNavigationLoader : public network::mojom::URLLoader { public: - class CONTENT_EXPORT Delegate { - public: - virtual ~Delegate() {} - - // Returns the ServiceWorkerVersion fetch events for this request job should - // be dispatched to. If no appropriate worker can be determined, returns - // nullptr. - virtual ServiceWorkerVersion* GetServiceWorkerVersion() = 0; - - // Called after dispatching the fetch event to determine if processing of - // the request should still continue, or if processing should be aborted. - // TODO(falken): This can probably be deleted. - virtual bool RequestStillValid() = 0; - - // Called to signal that loading failed, and that the resource being loaded - // was a main resource. - virtual void MainResourceLoadFailed() = 0; - }; - // Created by ServiceWorkerControlleeRequestHandler // after it determines the load should go through a service worker. // @@ -83,7 +64,6 @@ // is used instead of NavigationURLLoaderImpl. ServiceWorkerNavigationLoader( NavigationLoaderInterceptor::FallbackCallback fallback_callback, - Delegate* delegate, base::WeakPtr<ServiceWorkerProviderHost> provider_host, scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter); @@ -174,15 +154,6 @@ NavigationLoaderInterceptor::FallbackCallback fallback_callback_; - // |delegate_| is non-null and owns |this| until DetachedFromRequest() is - // called. Once that is called, |delegate_| is reset to null and |this| owns - // itself, self-destructing when a connection error on |binding_| occurs. - // - // Note: A WeakPtr wouldn't be super safe here because the delegate can - // conceivably still be alive and used for another loader, after calling - // DetachedFromRequest() for this loader. - Delegate* delegate_ = nullptr; - network::ResourceRequest resource_request_; base::WeakPtr<ServiceWorkerProviderHost> provider_host_; scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter_; @@ -205,8 +176,9 @@ mojo::Binding<network::mojom::URLLoader> binding_; Status status_ = Status::kNotStarted; + bool is_detached_ = false; - base::WeakPtrFactory<ServiceWorkerNavigationLoader> weak_factory_; + base::WeakPtrFactory<ServiceWorkerNavigationLoader> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerNavigationLoader); };
diff --git a/content/browser/service_worker/service_worker_navigation_loader_interceptor.cc b/content/browser/service_worker/service_worker_navigation_loader_interceptor.cc new file mode 100644 index 0000000..75b59d94 --- /dev/null +++ b/content/browser/service_worker/service_worker_navigation_loader_interceptor.cc
@@ -0,0 +1,242 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/service_worker/service_worker_navigation_loader_interceptor.h" + +#include <memory> +#include <utility> + +#include "base/bind.h" +#include "base/optional.h" +#include "base/task/post_task.h" +#include "content/browser/frame_host/navigation_request_info.h" +#include "content/browser/loader/navigation_url_loader_impl.h" +#include "content/browser/navigation_subresource_loader_params.h" +#include "content/browser/service_worker/service_worker_context_core.h" +#include "content/browser/service_worker/service_worker_context_wrapper.h" +#include "content/browser/service_worker/service_worker_controllee_request_handler.h" +#include "content/browser/service_worker/service_worker_navigation_handle.h" +#include "content/browser/service_worker/service_worker_navigation_handle_core.h" +#include "content/browser/service_worker/service_worker_provider_host.h" +#include "content/public/browser/browser_task_traits.h" + +namespace content { + +namespace { + +/////////////////////////////////////////////////////////////////////////////// +// IO thread helpers + +using SetupCallback = + base::OnceCallback<void(blink::mojom::ServiceWorkerProviderInfoForWindowPtr, + std::unique_ptr<NavigationLoaderInterceptor, + BrowserThread::DeleteOnIOThread>)>; + +// Does setup on the IO thread and calls |callback| on the UI thread. +void InitOnIO(ServiceWorkerNavigationHandleCore* handle_core, + bool are_ancestors_secure, + int frame_tree_node_id, + ResourceType resource_type, + bool skip_service_worker, + SetupCallback callback) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + + ServiceWorkerContextCore* context_core = + handle_core->context_wrapper()->context(); + if (!context_core) { + PostTaskWithTraits( + FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), /*provider_info=*/nullptr, + /*interceptor=*/nullptr)); + return; + } + + // Make the provider host. + auto provider_info = blink::mojom::ServiceWorkerProviderInfoForWindow::New(); + base::WeakPtr<ServiceWorkerProviderHost> provider_host = + ServiceWorkerProviderHost::PreCreateNavigationHost( + context_core->AsWeakPtr(), are_ancestors_secure, frame_tree_node_id, + &provider_info); + handle_core->set_provider_host(provider_host); + + // TODO(crbug.com/926114): Respect |skip_service_worker|. + + // Make the inner interceptor. + std::unique_ptr<ServiceWorkerControlleeRequestHandler, + BrowserThread::DeleteOnIOThread> + interceptor(new ServiceWorkerControlleeRequestHandler( + context_core->AsWeakPtr(), provider_host, resource_type)); + + PostTaskWithTraits( + FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), std::move(provider_info), + std::move(interceptor))); +} + +void LoaderCallbackWrapperOnIO( + base::WeakPtr<ServiceWorkerNavigationLoaderInterceptor> interceptor_on_ui, + SingleRequestURLLoaderFactory::RequestHandler handler) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + PostTaskWithTraits( + FROM_HERE, {BrowserThread::UI}, + base::BindOnce( + &ServiceWorkerNavigationLoaderInterceptor::LoaderCallbackWrapper, + interceptor_on_ui, std::move(handler))); +} + +void FallbackCallbackWrapperOnIO( + base::WeakPtr<ServiceWorkerNavigationLoaderInterceptor> interceptor_on_ui, + bool reset_subresource_loader_params) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + PostTaskWithTraits( + FROM_HERE, {BrowserThread::UI}, + base::BindOnce( + &ServiceWorkerNavigationLoaderInterceptor::FallbackCallbackWrapper, + interceptor_on_ui, reset_subresource_loader_params)); +} + +void InvokeRequestHandlerOnIO( + SingleRequestURLLoaderFactory::RequestHandler handler, + const network::ResourceRequest& resource_request, + network::mojom::URLLoaderRequest request, + network::mojom::URLLoaderClientPtrInfo client_info) { + network::mojom::URLLoaderClientPtr client(std::move(client_info)); + std::move(handler).Run(resource_request, std::move(request), + std::move(client)); +} +/////////////////////////////////////////////////////////////////////////////// + +} // namespace + +ServiceWorkerNavigationLoaderInterceptor:: + ServiceWorkerNavigationLoaderInterceptor( + const NavigationRequestInfo& request_info, + ServiceWorkerNavigationHandle* handle) + : handle_(handle), + are_ancestors_secure_(request_info.are_ancestors_secure), + frame_tree_node_id_(request_info.frame_tree_node_id), + resource_type_(request_info.is_main_frame ? ResourceType::kMainFrame + : ResourceType::kSubFrame), + skip_service_worker_(request_info.begin_params->skip_service_worker) { + DCHECK(NavigationURLLoaderImpl::IsNavigationLoaderOnUIEnabled()); + DCHECK_CURRENTLY_ON(BrowserThread::UI); +} + +ServiceWorkerNavigationLoaderInterceptor:: + ~ServiceWorkerNavigationLoaderInterceptor() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); +} + +void ServiceWorkerNavigationLoaderInterceptor::MaybeCreateLoader( + const network::ResourceRequest& tentative_resource_request, + BrowserContext* browser_context, + ResourceContext* resource_context, + LoaderCallback loader_callback, + FallbackCallback fallback_callback) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + // First make the inner interceptor if it hasn't been done yet. We'll + // come back here after. + if (!interceptor_on_io_) { + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce( + &InitOnIO, handle_->core(), are_ancestors_secure_, + frame_tree_node_id_, resource_type_, skip_service_worker_, + base::BindOnce( + &ServiceWorkerNavigationLoaderInterceptor::OnInitComplete, + GetWeakPtr(), tentative_resource_request, browser_context, + resource_context, std::move(loader_callback), + std::move(fallback_callback)))); + return; + } + + // Start the inner interceptor on the IO thread. It will call back to + // functions on the IO thread which hop back to LoaderCallbackWrapper() or + // FallbackCallbackWrapper() on the UI thread. + loader_callback_ = std::move(loader_callback); + fallback_callback_ = std::move(fallback_callback); + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce( + &NavigationLoaderInterceptor::MaybeCreateLoader, + base::Unretained(interceptor_on_io_.get()), + tentative_resource_request, browser_context, resource_context, + base::BindOnce(&LoaderCallbackWrapperOnIO, GetWeakPtr()), + base::BindOnce(&FallbackCallbackWrapperOnIO, GetWeakPtr()))); +} + +base::Optional<SubresourceLoaderParams> +ServiceWorkerNavigationLoaderInterceptor::MaybeCreateSubresourceLoaderParams() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + // TODO(crbug.com/926114): Implement this. The params have to be received from + // the IO thread inner interceptor before MaybeCreateLoader() is completed, so + // this function can synchronously return them. + return base::nullopt; +} + +void ServiceWorkerNavigationLoaderInterceptor::OnInitComplete( + const network::ResourceRequest& tentative_resource_request, + BrowserContext* browser_context, + ResourceContext* resource_context, + LoaderCallback callback, + FallbackCallback fallback_callback, + blink::mojom::ServiceWorkerProviderInfoForWindowPtr provider_info, + std::unique_ptr<NavigationLoaderInterceptor, + BrowserThread::DeleteOnIOThread> interceptor) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + DCHECK(!interceptor_on_io_); + interceptor_on_io_ = std::move(interceptor); + + handle_->OnCreatedProviderHost(std::move(provider_info)); + MaybeCreateLoader(tentative_resource_request, browser_context, + resource_context, std::move(callback), + std::move(fallback_callback)); +} + +void ServiceWorkerNavigationLoaderInterceptor::LoaderCallbackWrapper( + SingleRequestURLLoaderFactory::RequestHandler handler_on_io) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + if (!handler_on_io) { + std::move(loader_callback_).Run({}); + return; + } + + // The inner IO thread interceptor wants to handle the request. However, + // |handler_on_io| expects to run on the IO thread. Give our own wrapper to + // the loader callback. + std::move(loader_callback_) + .Run(base::BindOnce( + &ServiceWorkerNavigationLoaderInterceptor::RequestHandlerWrapper, + GetWeakPtr(), std::move(handler_on_io))); +} + +void ServiceWorkerNavigationLoaderInterceptor::FallbackCallbackWrapper( + bool reset_subresource_loader_params) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + std::move(fallback_callback_).Run(reset_subresource_loader_params); +} + +base::WeakPtr<ServiceWorkerNavigationLoaderInterceptor> +ServiceWorkerNavigationLoaderInterceptor::GetWeakPtr() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + return weak_factory_.GetWeakPtr(); +} + +void ServiceWorkerNavigationLoaderInterceptor::RequestHandlerWrapper( + SingleRequestURLLoaderFactory::RequestHandler handler_on_io, + const network::ResourceRequest& resource_request, + network::mojom::URLLoaderRequest request, + network::mojom::URLLoaderClientPtr client) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce(InvokeRequestHandlerOnIO, std::move(handler_on_io), + resource_request, std::move(request), + client.PassInterface())); +} + +} // namespace content
diff --git a/content/browser/service_worker/service_worker_navigation_loader_interceptor.h b/content/browser/service_worker/service_worker_navigation_loader_interceptor.h new file mode 100644 index 0000000..faab431 --- /dev/null +++ b/content/browser/service_worker/service_worker_navigation_loader_interceptor.h
@@ -0,0 +1,107 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_NAVIGATION_LOADER_INTERCEPTOR_H_ +#define CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_NAVIGATION_LOADER_INTERCEPTOR_H_ + +#include <memory> + +#include "base/memory/weak_ptr.h" +#include "content/browser/loader/navigation_loader_interceptor.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/common/resource_type.h" +#include "third_party/blink/public/mojom/service_worker/service_worker_provider.mojom.h" + +namespace content { + +struct NavigationRequestInfo; +class ServiceWorkerNavigationHandle; + +// This class is a work in progress for https://crbug.com/824858. It is used +// only when NavigationLoaderOnUI is enabled. +// +// Handles navigations for service worker clients (for now just documents, not +// web workers). Lives on the UI thread. +// +// The corresponding legacy class is ServiceWorkerControlleeRequestHandler which +// lives on the IO thread. Currently, this class just delegates to the +// legacy class by posting tasks to it on the IO thread. +class ServiceWorkerNavigationLoaderInterceptor final + : public NavigationLoaderInterceptor { + public: + ServiceWorkerNavigationLoaderInterceptor( + const NavigationRequestInfo& request_info, + ServiceWorkerNavigationHandle* handle); + ~ServiceWorkerNavigationLoaderInterceptor() override; + + // NavigationLoaderInterceptor overrides: + + // This could get called multiple times during the lifetime in redirect + // cases. (In fallback-to-network cases we basically forward the request + // to the request to the next request handler) + void MaybeCreateLoader(const network::ResourceRequest& tentative_request, + BrowserContext* browser_context, + ResourceContext* resource_context, + LoaderCallback callback, + FallbackCallback fallback_callback) override; + // Returns params with the ControllerServiceWorkerPtr if we have found + // a matching controller service worker for the |request| that is given + // to MaybeCreateLoader(). Otherwise this returns base::nullopt. + base::Optional<SubresourceLoaderParams> MaybeCreateSubresourceLoaderParams() + override; + + // These are called back from the IO thread helper functions: + void OnInitComplete( + const network::ResourceRequest& tentative_resource_request, + BrowserContext* browser_context, + ResourceContext* resource_context, + LoaderCallback callback, + FallbackCallback fallback_callback, + blink::mojom::ServiceWorkerProviderInfoForWindowPtr provider_info, + std::unique_ptr<NavigationLoaderInterceptor, + BrowserThread::DeleteOnIOThread> interceptor); + void LoaderCallbackWrapper( + SingleRequestURLLoaderFactory::RequestHandler handler); + void FallbackCallbackWrapper(bool reset_subresource_loader_params); + + base::WeakPtr<ServiceWorkerNavigationLoaderInterceptor> GetWeakPtr(); + + private: + // Given as a callback to NavigationURLLoaderImpl. + void RequestHandlerWrapper( + SingleRequestURLLoaderFactory::RequestHandler handler_on_io, + const network::ResourceRequest& resource_request, + network::mojom::URLLoaderRequest request, + network::mojom::URLLoaderClientPtr client); + + // |handle_| owns |this|. + ServiceWorkerNavigationHandle* const handle_; + + const bool are_ancestors_secure_; + const int frame_tree_node_id_; + const ResourceType resource_type_; + const bool skip_service_worker_; + + LoaderCallback loader_callback_; + FallbackCallback fallback_callback_; + + // The inner interceptor. This actually does the work and its methods must be + // called only on the IO thread. The goal is to move everything it does to the + // UI thread so everything can be done directly there instead. + // + // Although methods must only be called on the IO thread, this is set exactly + // once and on the UI thread, so it's OK to get the pointer on the UI thread, + // e.g., to check for nullness or to pass the pointer to the IO thread. + std::unique_ptr<NavigationLoaderInterceptor, BrowserThread::DeleteOnIOThread> + interceptor_on_io_; + + base::WeakPtrFactory<ServiceWorkerNavigationLoaderInterceptor> weak_factory_{ + this}; + + DISALLOW_COPY_AND_ASSIGN(ServiceWorkerNavigationLoaderInterceptor); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_NAVIGATION_LOADER_INTERCEPTOR_H_
diff --git a/content/browser/service_worker/service_worker_navigation_loader_unittest.cc b/content/browser/service_worker/service_worker_navigation_loader_unittest.cc index 72e82bc5..5c7b330 100644 --- a/content/browser/service_worker/service_worker_navigation_loader_unittest.cc +++ b/content/browser/service_worker/service_worker_navigation_loader_unittest.cc
@@ -326,14 +326,7 @@ // Of course, no actual service worker runs in the unit test, it is simulated // via EmbeddedWorkerTestHelper receiving IPC messages from the browser and // responding as if a service worker is running in the renderer. -// -// ServiceWorkerNavigationLoaderTest is also a -// ServiceWorkerNavigationLoader::Delegate. In production code, -// ServiceWorkerControlleeRequestHandler is the Delegate. So this class also -// basically mocks that part of ServiceWorkerControlleeRequestHandler. -class ServiceWorkerNavigationLoaderTest - : public testing::Test, - public ServiceWorkerNavigationLoader::Delegate { +class ServiceWorkerNavigationLoaderTest : public testing::Test { public: ServiceWorkerNavigationLoaderTest() : thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP) {} @@ -391,14 +384,23 @@ // caller can use functions like client_.RunUntilComplete() to wait for // completion. void StartRequest(std::unique_ptr<network::ResourceRequest> request) { - provider_host_ = CreateProviderHostForWindow( - helper_->mock_render_process_id(), true /* is_parent_frame_secure */, - helper_->context()->AsWeakPtr(), &provider_endpoints_); + // Create a ServiceWorkerProviderHost and simulate what + // ServiceWorkerControlleeRequestHandler does to assign it a controller. + if (!provider_host_) { + provider_host_ = CreateProviderHostForWindow( + helper_->mock_render_process_id(), /*is_parent_frame_secure=*/true, + helper_->context()->AsWeakPtr(), &provider_endpoints_); + provider_host_->UpdateUrls(request->url, request->url); + provider_host_->AddMatchingRegistration(registration_.get()); + provider_host_->SetControllerRegistration( + registration_, /*notify_controllerchange=*/false); + } + // Create a ServiceWorkerNavigationLoader. loader_ = std::make_unique<ServiceWorkerNavigationLoader>( base::BindOnce(&ServiceWorkerNavigationLoaderTest::Fallback, base::Unretained(this)), - this, provider_host_, + provider_host_, base::WrapRefCounted<URLLoaderFactoryGetter>( helper_->context()->loader_factory_getter())); @@ -449,7 +451,7 @@ std::unique_ptr<network::ResourceRequest> CreateRequest() { std::unique_ptr<network::ResourceRequest> request = std::make_unique<network::ResourceRequest>(); - request->url = GURL("https://www.example.com/"); + request->url = GURL("https://example.com/"); request->method = "GET"; request->mode = network::mojom::RequestMode::kNavigate; request->credentials_mode = network::mojom::CredentialsMode::kInclude; @@ -457,23 +459,11 @@ return request; } - protected: - // ServiceWorkerNavigationLoader::Delegate ----------------------------------- - ServiceWorkerVersion* GetServiceWorkerVersion() override { - return version_.get(); - } - - bool RequestStillValid() override { return true; } - - void MainResourceLoadFailed() override { - was_main_resource_load_failed_called_ = true; - } - bool HasWorkInBrowser(ServiceWorkerVersion* version) const { return version->HasWorkInBrowser(); } - // -------------------------------------------------------------------------- + protected: TestBrowserThreadBundle thread_bundle_; std::unique_ptr<EmbeddedWorkerTestHelper> helper_; scoped_refptr<ServiceWorkerRegistration> registration_; @@ -481,7 +471,6 @@ FetchEventServiceWorker* service_worker_; storage::BlobStorageContext blob_context_; network::TestURLLoaderClient client_; - bool was_main_resource_load_failed_called_ = false; std::unique_ptr<ServiceWorkerNavigationLoader> loader_; network::mojom::URLLoaderPtr loader_ptr_; base::WeakPtr<ServiceWorkerProviderHost> provider_host_; @@ -521,8 +510,12 @@ TEST_F(ServiceWorkerNavigationLoaderTest, NoActiveWorker) { base::HistogramTester histogram_tester; - // Clear |version_| to make GetServiceWorkerVersion() return null. - version_ = nullptr; + // Make a provider host without a controller. + provider_host_ = CreateProviderHostForWindow( + helper_->mock_render_process_id(), /*is_parent_frame_secure=*/true, + helper_->context()->AsWeakPtr(), &provider_endpoints_); + provider_host_->UpdateUrls(GURL("https://example.com/"), + GURL("https://example.com/")); // Perform the request. StartRequest(CreateRequest()); @@ -802,11 +795,10 @@ // The fallback callback should be called. RunUntilFallbackCallback(); EXPECT_FALSE(reset_subresource_loader_params_); - EXPECT_FALSE(was_main_resource_load_failed_called_); // The request should not be handled by the loader, but it shouldn't be a // failure. - EXPECT_FALSE(was_main_resource_load_failed_called_); + EXPECT_TRUE(provider_host_->controller()); histogram_tester.ExpectUniqueSample(kHistogramMainResourceFetchEvent, blink::ServiceWorkerStatusCode::kOk, 1); @@ -848,7 +840,7 @@ // The fallback callback should be called. RunUntilFallbackCallback(); EXPECT_TRUE(reset_subresource_loader_params_); - EXPECT_TRUE(was_main_resource_load_failed_called_); + EXPECT_FALSE(provider_host_->controller()); histogram_tester.ExpectUniqueSample( kHistogramMainResourceFetchEvent, @@ -946,12 +938,15 @@ base::RunLoop().RunUntilIdle(); } -TEST_F(ServiceWorkerNavigationLoaderTest, DetachedDuringFetchEvent) { +TEST_F(ServiceWorkerNavigationLoaderTest, CancelNavigationDuringFetchEvent) { StartRequest(CreateRequest()); - // Detach the loader immediately after it started. This results in - // DidDispatchFetchEvent() being invoked later with null |delegate_|. - loader_.release()->DetachedFromRequest(); + // Delete the provider host during the request. The load should abort without + // crashing. + *provider_endpoints_.host_ptr() = nullptr; + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(provider_host_); + client_.RunUntilComplete(); EXPECT_EQ(net::ERR_ABORTED, client_.completion_status().error_code); }
diff --git a/content/browser/service_worker/service_worker_new_script_loader.cc b/content/browser/service_worker/service_worker_new_script_loader.cc index d5783b9..a8f05f9 100644 --- a/content/browser/service_worker/service_worker_new_script_loader.cc +++ b/content/browser/service_worker/service_worker_new_script_loader.cc
@@ -94,8 +94,7 @@ type_(Type::kNetworkOnly), client_producer_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, - base::SequencedTaskRunnerHandle::Get()), - weak_factory_(this) { + base::SequencedTaskRunnerHandle::Get()) { network::ResourceRequest resource_request(original_request); #if DCHECK_IS_ON() CheckVersionStatusBeforeLoad(); @@ -190,8 +189,7 @@ client_producer_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, base::SequencedTaskRunnerHandle::Get()), - request_start_(base::TimeTicks::Now()), - weak_factory_(this) { + request_start_(base::TimeTicks::Now()) { #if DCHECK_IS_ON() CheckVersionStatusBeforeLoad(); #endif // DCHECK_IS_ON()
diff --git a/content/browser/service_worker/service_worker_new_script_loader.h b/content/browser/service_worker/service_worker_new_script_loader.h index 36cff0d..79f7a180 100644 --- a/content/browser/service_worker/service_worker_new_script_loader.h +++ b/content/browser/service_worker/service_worker_new_script_loader.h
@@ -312,7 +312,7 @@ base::OnceCallback<void(net::Error)> write_observer_complete_callback_; // ---------- End of Type::kResume loader members ---------- - base::WeakPtrFactory<ServiceWorkerNewScriptLoader> weak_factory_; + base::WeakPtrFactory<ServiceWorkerNewScriptLoader> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerNewScriptLoader); };
diff --git a/content/browser/service_worker/service_worker_object_host.cc b/content/browser/service_worker/service_worker_object_host.cc index d6a44485..8d978a6 100644 --- a/content/browser/service_worker/service_worker_object_host.cc +++ b/content/browser/service_worker/service_worker_object_host.cc
@@ -199,8 +199,7 @@ : context_(context), provider_host_(provider_host), provider_origin_(url::Origin::Create(provider_host->url())), - version_(std::move(version)), - weak_ptr_factory_(this) { + version_(std::move(version)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(context_ && provider_host_ && version_); DCHECK(context_->GetLiveRegistration(version_->registration_id()));
diff --git a/content/browser/service_worker/service_worker_object_host.h b/content/browser/service_worker/service_worker_object_host.h index 0c43f3a..75be5dc 100644 --- a/content/browser/service_worker/service_worker_object_host.h +++ b/content/browser/service_worker/service_worker_object_host.h
@@ -120,7 +120,7 @@ mojo::AssociatedInterfacePtrSet<blink::mojom::ServiceWorkerObject> remote_objects_; - base::WeakPtrFactory<ServiceWorkerObjectHost> weak_ptr_factory_; + base::WeakPtrFactory<ServiceWorkerObjectHost> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerObjectHost); };
diff --git a/content/browser/service_worker/service_worker_process_manager.cc b/content/browser/service_worker/service_worker_process_manager.cc index 8f5225e5..6b1ecc2 100644 --- a/content/browser/service_worker/service_worker_process_manager.cc +++ b/content/browser/service_worker/service_worker_process_manager.cc
@@ -25,8 +25,7 @@ : browser_context_(browser_context), storage_partition_(nullptr), process_id_for_test_(ChildProcessHost::kInvalidUniqueID), - new_process_id_for_test_(ChildProcessHost::kInvalidUniqueID), - weak_this_factory_(this) { + new_process_id_for_test_(ChildProcessHost::kInvalidUniqueID) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(browser_context); weak_this_ = weak_this_factory_.GetWeakPtr();
diff --git a/content/browser/service_worker/service_worker_process_manager.h b/content/browser/service_worker/service_worker_process_manager.h index 7eada9bf..377cf7e6 100644 --- a/content/browser/service_worker/service_worker_process_manager.h +++ b/content/browser/service_worker/service_worker_process_manager.h
@@ -137,7 +137,7 @@ // Used to double-check that we don't access *this after it's destroyed. base::WeakPtr<ServiceWorkerProcessManager> weak_this_; - base::WeakPtrFactory<ServiceWorkerProcessManager> weak_this_factory_; + base::WeakPtrFactory<ServiceWorkerProcessManager> weak_this_factory_{this}; }; } // namespace content
diff --git a/content/browser/service_worker/service_worker_register_job.cc b/content/browser/service_worker/service_worker_register_job.cc index b24403e..a131ff6f 100644 --- a/content/browser/service_worker/service_worker_register_job.cc +++ b/content/browser/service_worker/service_worker_register_job.cc
@@ -52,8 +52,7 @@ should_uninstall_on_failure_(false), force_bypass_cache_(false), skip_script_comparison_(false), - promise_resolved_status_(blink::ServiceWorkerStatusCode::kOk), - weak_factory_(this) {} + promise_resolved_status_(blink::ServiceWorkerStatusCode::kOk) {} ServiceWorkerRegisterJob::ServiceWorkerRegisterJob( base::WeakPtr<ServiceWorkerContextCore> context, @@ -70,8 +69,7 @@ should_uninstall_on_failure_(false), force_bypass_cache_(force_bypass_cache), skip_script_comparison_(skip_script_comparison), - promise_resolved_status_(blink::ServiceWorkerStatusCode::kOk), - weak_factory_(this) { + promise_resolved_status_(blink::ServiceWorkerStatusCode::kOk) { internal_.registration = registration; }
diff --git a/content/browser/service_worker/service_worker_register_job.h b/content/browser/service_worker/service_worker_register_job.h index 4eda2cfe..bfa91dae 100644 --- a/content/browser/service_worker/service_worker_register_job.h +++ b/content/browser/service_worker/service_worker_register_job.h
@@ -198,7 +198,7 @@ std::string promise_resolved_status_message_; scoped_refptr<ServiceWorkerRegistration> promise_resolved_registration_; - base::WeakPtrFactory<ServiceWorkerRegisterJob> weak_factory_; + base::WeakPtrFactory<ServiceWorkerRegisterJob> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerRegisterJob); };
diff --git a/content/browser/service_worker/service_worker_registration_object_host.cc b/content/browser/service_worker/service_worker_registration_object_host.cc index 4a1f47f..422b38e 100644 --- a/content/browser/service_worker/service_worker_registration_object_host.cc +++ b/content/browser/service_worker/service_worker_registration_object_host.cc
@@ -83,8 +83,7 @@ scoped_refptr<ServiceWorkerRegistration> registration) : provider_host_(provider_host), context_(context), - registration_(registration), - weak_ptr_factory_(this) { + registration_(registration) { DCHECK(registration_.get()); DCHECK(provider_host_); registration_->AddListener(this);
diff --git a/content/browser/service_worker/service_worker_registration_object_host.h b/content/browser/service_worker/service_worker_registration_object_host.h index db6c5f8..4f69054 100644 --- a/content/browser/service_worker/service_worker_registration_object_host.h +++ b/content/browser/service_worker/service_worker_registration_object_host.h
@@ -146,7 +146,8 @@ blink::mojom::ServiceWorkerRegistrationObjectAssociatedPtr remote_registration_; - base::WeakPtrFactory<ServiceWorkerRegistrationObjectHost> weak_ptr_factory_; + base::WeakPtrFactory<ServiceWorkerRegistrationObjectHost> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerRegistrationObjectHost); };
diff --git a/content/browser/service_worker/service_worker_request_handler.cc b/content/browser/service_worker/service_worker_request_handler.cc index 3660410e..802250f 100644 --- a/content/browser/service_worker/service_worker_request_handler.cc +++ b/content/browser/service_worker/service_worker_request_handler.cc
@@ -13,7 +13,9 @@ #include "content/browser/service_worker/service_worker_context_core.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/service_worker/service_worker_controllee_request_handler.h" +#include "content/browser/service_worker/service_worker_navigation_handle.h" #include "content/browser/service_worker/service_worker_navigation_handle_core.h" +#include "content/browser/service_worker/service_worker_navigation_loader_interceptor.h" #include "content/browser/service_worker/service_worker_provider_host.h" #include "content/public/common/origin_util.h" #include "content/public/common/url_constants.h" @@ -37,11 +39,31 @@ // static std::unique_ptr<NavigationLoaderInterceptor> -ServiceWorkerRequestHandler::CreateForNavigation( +ServiceWorkerRequestHandler::CreateForNavigationUI( + const GURL& url, + ServiceWorkerNavigationHandle* navigation_handle, + const NavigationRequestInfo& request_info) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + // Create the handler even for insecure HTTP since it's used in the + // case of redirect to HTTPS. + if (!url.SchemeIsHTTPOrHTTPS() && !OriginCanAccessServiceWorkers(url) && + !SchemeMaySupportRedirectingToHTTPS(url)) { + return nullptr; + } + + return std::make_unique<ServiceWorkerNavigationLoaderInterceptor>( + request_info, navigation_handle); +} + +// static +std::unique_ptr<NavigationLoaderInterceptor> +ServiceWorkerRequestHandler::CreateForNavigationIO( const GURL& url, ServiceWorkerNavigationHandleCore* navigation_handle_core, const NavigationRequestInfo& request_info, base::WeakPtr<ServiceWorkerProviderHost>* out_provider_host) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(navigation_handle_core); // Create the handler even for insecure HTTP since it's used in the
diff --git a/content/browser/service_worker/service_worker_request_handler.h b/content/browser/service_worker/service_worker_request_handler.h index 9327173..25b886eb 100644 --- a/content/browser/service_worker/service_worker_request_handler.h +++ b/content/browser/service_worker/service_worker_request_handler.h
@@ -20,6 +20,7 @@ namespace content { +class ServiceWorkerNavigationHandle; class ServiceWorkerNavigationHandleCore; class ServiceWorkerProviderHost; struct NavigationRequestInfo; @@ -30,15 +31,23 @@ // non-member functions? class CONTENT_EXPORT ServiceWorkerRequestHandler { public: - // Returns a loader interceptor for a navigation. May return nullptr - // if the navigation cannot use service workers. - static std::unique_ptr<NavigationLoaderInterceptor> CreateForNavigation( + // Returns a loader interceptor for a navigation. May return nullptr if the + // navigation cannot use service workers. Called on the UI thread. + static std::unique_ptr<NavigationLoaderInterceptor> CreateForNavigationUI( + const GURL& url, + ServiceWorkerNavigationHandle* navigation_handle, + const NavigationRequestInfo& request_info); + + // Returns a loader interceptor for a navigation. May return nullptr if the + // navigation cannot use service workers. Called on the IO thread. + static std::unique_ptr<NavigationLoaderInterceptor> CreateForNavigationIO( const GURL& url, ServiceWorkerNavigationHandleCore* navigation_handle_core, const NavigationRequestInfo& request_info, base::WeakPtr<ServiceWorkerProviderHost>* out_provider_host); - // Same as above but for a dedicated worker or shared worker. + // Same as above but for a dedicated worker or shared worker. Called on the IO + // thread. static std::unique_ptr<NavigationLoaderInterceptor> CreateForWorker( const network::ResourceRequest& resource_request, ServiceWorkerProviderHost* host);
diff --git a/content/browser/service_worker/service_worker_request_handler_unittest.cc b/content/browser/service_worker/service_worker_request_handler_unittest.cc index 0884efc..386bfc54 100644 --- a/content/browser/service_worker/service_worker_request_handler_unittest.cc +++ b/content/browser/service_worker/service_worker_request_handler_unittest.cc
@@ -93,7 +93,7 @@ base::UnguessableToken::Create() /* devtools_navigation_token */, base::UnguessableToken::Create() /* devtools_frame_token */); std::unique_ptr<NavigationLoaderInterceptor> interceptor = - ServiceWorkerRequestHandler::CreateForNavigation( + ServiceWorkerRequestHandler::CreateForNavigationIO( GURL(url), navigation_handle_core.get(), request_info, &service_worker_provider_host); EXPECT_EQ(expected_handler_created, !!interceptor.get());
diff --git a/content/browser/service_worker/service_worker_script_cache_map.cc b/content/browser/service_worker/service_worker_script_cache_map.cc index 39bd78a6..2ba6bb5 100644 --- a/content/browser/service_worker/service_worker_script_cache_map.cc +++ b/content/browser/service_worker/service_worker_script_cache_map.cc
@@ -21,8 +21,7 @@ ServiceWorkerScriptCacheMap::ServiceWorkerScriptCacheMap( ServiceWorkerVersion* owner, base::WeakPtr<ServiceWorkerContextCore> context) - : owner_(owner), context_(context), weak_factory_(this) { -} + : owner_(owner), context_(context) {} ServiceWorkerScriptCacheMap::~ServiceWorkerScriptCacheMap() { }
diff --git a/content/browser/service_worker/service_worker_script_cache_map.h b/content/browser/service_worker/service_worker_script_cache_map.h index 23c9ee3c..9c6f68c 100644 --- a/content/browser/service_worker/service_worker_script_cache_map.h +++ b/content/browser/service_worker/service_worker_script_cache_map.h
@@ -89,7 +89,7 @@ net::URLRequestStatus main_script_status_; std::string main_script_status_message_; - base::WeakPtrFactory<ServiceWorkerScriptCacheMap> weak_factory_; + base::WeakPtrFactory<ServiceWorkerScriptCacheMap> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerScriptCacheMap); };
diff --git a/content/browser/service_worker/service_worker_script_loader_factory.cc b/content/browser/service_worker/service_worker_script_loader_factory.cc index 9cc8519..06167da8 100644 --- a/content/browser/service_worker/service_worker_script_loader_factory.cc +++ b/content/browser/service_worker/service_worker_script_loader_factory.cc
@@ -30,8 +30,7 @@ : context_(context), provider_host_(provider_host), loader_factory_for_new_scripts_( - std::move(loader_factory_for_new_scripts)), - weak_factory_(this) { + std::move(loader_factory_for_new_scripts)) { DCHECK(provider_host_->IsProviderForServiceWorker()); DCHECK(loader_factory_for_new_scripts_ || ServiceWorkerVersion::IsInstalled(
diff --git a/content/browser/service_worker/service_worker_script_loader_factory.h b/content/browser/service_worker/service_worker_script_loader_factory.h index adb571a..928e4b8 100644 --- a/content/browser/service_worker/service_worker_script_loader_factory.h +++ b/content/browser/service_worker/service_worker_script_loader_factory.h
@@ -104,7 +104,7 @@ // Used to copy script started at CopyScript(). std::unique_ptr<ServiceWorkerCacheWriter> cache_writer_; - base::WeakPtrFactory<ServiceWorkerScriptLoaderFactory> weak_factory_; + base::WeakPtrFactory<ServiceWorkerScriptLoaderFactory> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerScriptLoaderFactory); };
diff --git a/content/browser/service_worker/service_worker_single_script_update_checker.cc b/content/browser/service_worker/service_worker_single_script_update_checker.cc index 0844809..88bbd3e 100644 --- a/content/browser/service_worker/service_worker_single_script_update_checker.cc +++ b/content/browser/service_worker/service_worker_single_script_update_checker.cc
@@ -103,8 +103,7 @@ network_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, base::SequencedTaskRunnerHandle::Get()), - callback_(std::move(callback)), - weak_factory_(this) { + callback_(std::move(callback)) { network::ResourceRequest resource_request; resource_request.url = url; resource_request.resource_type = static_cast<int>(
diff --git a/content/browser/service_worker/service_worker_single_script_update_checker.h b/content/browser/service_worker/service_worker_single_script_update_checker.h index cacf99a..8e30733 100644 --- a/content/browser/service_worker/service_worker_single_script_update_checker.h +++ b/content/browser/service_worker/service_worker_single_script_update_checker.h
@@ -202,7 +202,8 @@ ServiceWorkerNewScriptLoader::WriterState body_writer_state_ = ServiceWorkerNewScriptLoader::WriterState::kNotStarted; - base::WeakPtrFactory<ServiceWorkerSingleScriptUpdateChecker> weak_factory_; + base::WeakPtrFactory<ServiceWorkerSingleScriptUpdateChecker> weak_factory_{ + this}; DISALLOW_IMPLICIT_CONSTRUCTORS(ServiceWorkerSingleScriptUpdateChecker); };
diff --git a/content/browser/service_worker/service_worker_storage.cc b/content/browser/service_worker/service_worker_storage.cc index de65b73e..d368dce 100644 --- a/content/browser/service_worker/service_worker_storage.cc +++ b/content/browser/service_worker/service_worker_storage.cc
@@ -1155,8 +1155,7 @@ quota_manager_proxy_(quota_manager_proxy), special_storage_policy_(special_storage_policy), is_purge_pending_(false), - has_checked_for_stale_resources_(false), - weak_factory_(this) { + has_checked_for_stale_resources_(false) { DCHECK(context_); database_.reset(new ServiceWorkerDatabase(GetDatabasePath())); }
diff --git a/content/browser/service_worker/service_worker_storage.h b/content/browser/service_worker/service_worker_storage.h index 02177be3..20ed83f 100644 --- a/content/browser/service_worker/service_worker_storage.h +++ b/content/browser/service_worker/service_worker_storage.h
@@ -614,7 +614,7 @@ bool is_purge_pending_; bool has_checked_for_stale_resources_; - base::WeakPtrFactory<ServiceWorkerStorage> weak_factory_; + base::WeakPtrFactory<ServiceWorkerStorage> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerStorage); };
diff --git a/content/browser/service_worker/service_worker_unregister_job.cc b/content/browser/service_worker/service_worker_unregister_job.cc index c457b7c5..3b1894d 100644 --- a/content/browser/service_worker/service_worker_unregister_job.cc +++ b/content/browser/service_worker/service_worker_unregister_job.cc
@@ -21,10 +21,7 @@ ServiceWorkerUnregisterJob::ServiceWorkerUnregisterJob( base::WeakPtr<ServiceWorkerContextCore> context, const GURL& scope) - : context_(context), - scope_(scope), - is_promise_resolved_(false), - weak_factory_(this) {} + : context_(context), scope_(scope), is_promise_resolved_(false) {} ServiceWorkerUnregisterJob::~ServiceWorkerUnregisterJob() {}
diff --git a/content/browser/service_worker/service_worker_unregister_job.h b/content/browser/service_worker/service_worker_unregister_job.h index f2eade8..96702691 100644 --- a/content/browser/service_worker/service_worker_unregister_job.h +++ b/content/browser/service_worker/service_worker_unregister_job.h
@@ -60,7 +60,7 @@ const GURL scope_; std::vector<UnregistrationCallback> callbacks_; bool is_promise_resolved_; - base::WeakPtrFactory<ServiceWorkerUnregisterJob> weak_factory_; + base::WeakPtrFactory<ServiceWorkerUnregisterJob> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerUnregisterJob); };
diff --git a/content/browser/service_worker/service_worker_update_checker.cc b/content/browser/service_worker/service_worker_update_checker.cc index 536c44e..2286ae8e7 100644 --- a/content/browser/service_worker/service_worker_update_checker.cc +++ b/content/browser/service_worker/service_worker_update_checker.cc
@@ -27,8 +27,7 @@ loader_factory_(std::move(loader_factory)), force_bypass_cache_(force_bypass_cache), update_via_cache_(update_via_cache), - time_since_last_check_(time_since_last_check), - weak_factory_(this) {} + time_since_last_check_(time_since_last_check) {} ServiceWorkerUpdateChecker::~ServiceWorkerUpdateChecker() = default;
diff --git a/content/browser/service_worker/service_worker_update_checker.h b/content/browser/service_worker/service_worker_update_checker.h index 6dba085e..a314128 100644 --- a/content/browser/service_worker/service_worker_update_checker.h +++ b/content/browser/service_worker/service_worker_update_checker.h
@@ -111,7 +111,7 @@ // True if any at least one of the scripts is fetched by network. bool network_accessed_ = false; - base::WeakPtrFactory<ServiceWorkerUpdateChecker> weak_factory_; + base::WeakPtrFactory<ServiceWorkerUpdateChecker> weak_factory_{this}; DISALLOW_IMPLICIT_CONSTRUCTORS(ServiceWorkerUpdateChecker); };
diff --git a/content/browser/service_worker/service_worker_version.cc b/content/browser/service_worker/service_worker_version.cc index c187418a..7ebd70d 100644 --- a/content/browser/service_worker/service_worker_version.cc +++ b/content/browser/service_worker/service_worker_version.cc
@@ -245,8 +245,7 @@ tick_clock_(base::DefaultTickClock::GetInstance()), clock_(base::DefaultClock::GetInstance()), ping_controller_(this), - validator_(std::make_unique<blink::TrialTokenValidator>()), - weak_factory_(this) { + validator_(std::make_unique<blink::TrialTokenValidator>()) { DCHECK_NE(blink::mojom::kInvalidServiceWorkerVersionId, version_id); DCHECK(context_); DCHECK(registration);
diff --git a/content/browser/service_worker/service_worker_version.h b/content/browser/service_worker/service_worker_version.h index 32e3064..5b64374e 100644 --- a/content/browser/service_worker/service_worker_version.h +++ b/content/browser/service_worker/service_worker_version.h
@@ -960,7 +960,7 @@ // This is set when this service worker becomes redundant. base::debug::StackTrace redundant_state_callstack_; - base::WeakPtrFactory<ServiceWorkerVersion> weak_factory_; + base::WeakPtrFactory<ServiceWorkerVersion> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion); };
diff --git a/content/browser/speech/speech_recognition_dispatcher_host.cc b/content/browser/speech/speech_recognition_dispatcher_host.cc index e898a43..9e2e1014 100644 --- a/content/browser/speech/speech_recognition_dispatcher_host.cc +++ b/content/browser/speech/speech_recognition_dispatcher_host.cc
@@ -34,9 +34,7 @@ SpeechRecognitionDispatcherHost::SpeechRecognitionDispatcherHost( int render_process_id, int render_frame_id) - : render_process_id_(render_process_id), - render_frame_id_(render_frame_id), - weak_factory_(this) { + : render_process_id_(render_process_id), render_frame_id_(render_frame_id) { // Do not add any non-trivial initialization here, instead do it lazily when // required (e.g. see the method |SpeechRecognitionManager::GetInstance()|) or // add an Init() method. @@ -204,8 +202,7 @@ blink::mojom::SpeechRecognitionSessionClientPtrInfo client_ptr_info) : session_id_(SpeechRecognitionManager::kSessionIDInvalid), client_(std::move(client_ptr_info)), - stopped_(false), - weak_factory_(this) { + stopped_(false) { client_.set_connection_error_handler( base::BindOnce(&SpeechRecognitionSession::ConnectionErrorHandler, base::Unretained(this)));
diff --git a/content/browser/speech/speech_recognition_dispatcher_host.h b/content/browser/speech/speech_recognition_dispatcher_host.h index 2ae1596..2137385c 100644 --- a/content/browser/speech/speech_recognition_dispatcher_host.h +++ b/content/browser/speech/speech_recognition_dispatcher_host.h
@@ -65,7 +65,7 @@ // Used for posting asynchronous tasks (on the IO thread) without worrying // about this class being destroyed in the meanwhile (due to browser shutdown) // since tasks pending on a destroyed WeakPtr are automatically discarded. - base::WeakPtrFactory<SpeechRecognitionDispatcherHost> weak_factory_; + base::WeakPtrFactory<SpeechRecognitionDispatcherHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SpeechRecognitionDispatcherHost); }; @@ -115,7 +115,7 @@ blink::mojom::SpeechRecognitionSessionClientPtr client_; bool stopped_; - base::WeakPtrFactory<SpeechRecognitionSession> weak_factory_; + base::WeakPtrFactory<SpeechRecognitionSession> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/speech/speech_recognition_manager_impl.cc b/content/browser/speech/speech_recognition_manager_impl.cc index ef826ac..6c093d7 100644 --- a/content/browser/speech/speech_recognition_manager_impl.cc +++ b/content/browser/speech/speech_recognition_manager_impl.cc
@@ -234,8 +234,7 @@ delegate_(GetContentClient() ->browser() ->CreateSpeechRecognitionManagerDelegate()), - requester_id_(next_requester_id_++), - weak_factory_(this) { + requester_id_(next_requester_id_++) { DCHECK(!g_speech_recognition_manager_impl); g_speech_recognition_manager_impl = this;
diff --git a/content/browser/speech/speech_recognition_manager_impl.h b/content/browser/speech/speech_recognition_manager_impl.h index 64bc307..7f67f59b 100644 --- a/content/browser/speech/speech_recognition_manager_impl.h +++ b/content/browser/speech/speech_recognition_manager_impl.h
@@ -193,7 +193,7 @@ // Used for posting asynchronous tasks (on the IO thread) without worrying // about this class being destroyed in the meanwhile (due to browser shutdown) // since tasks pending on a destroyed WeakPtr are automatically discarded. - base::WeakPtrFactory<SpeechRecognitionManagerImpl> weak_factory_; + base::WeakPtrFactory<SpeechRecognitionManagerImpl> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/speech/speech_recognizer_impl.cc b/content/browser/speech/speech_recognizer_impl.cc index 35ed5f7..8b28929 100644 --- a/content/browser/speech/speech_recognizer_impl.cc +++ b/content/browser/speech/speech_recognizer_impl.cc
@@ -187,8 +187,7 @@ is_dispatching_event_(false), provisional_results_(provisional_results), end_of_utterance_(false), - state_(STATE_IDLE), - weak_ptr_factory_(this) { + state_(STATE_IDLE) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(recognition_engine_ != nullptr); DCHECK(audio_system_ != nullptr);
diff --git a/content/browser/speech/speech_recognizer_impl.h b/content/browser/speech/speech_recognizer_impl.h index b802895..8b966d992 100644 --- a/content/browser/speech/speech_recognizer_impl.h +++ b/content/browser/speech/speech_recognizer_impl.h
@@ -184,7 +184,7 @@ // output format. std::unique_ptr<SpeechRecognizerImpl::OnDataConverter> audio_converter_; - base::WeakPtrFactory<SpeechRecognizerImpl> weak_ptr_factory_; + base::WeakPtrFactory<SpeechRecognizerImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SpeechRecognizerImpl); };
diff --git a/content/browser/speech/tts_linux.cc b/content/browser/speech/tts_linux.cc index 6f1b783..4a158e8 100644 --- a/content/browser/speech/tts_linux.cc +++ b/content/browser/speech/tts_linux.cc
@@ -97,7 +97,7 @@ friend struct base::DefaultSingletonTraits<TtsPlatformImplLinux>; - base::WeakPtrFactory<TtsPlatformImplLinux> weak_factory_; + base::WeakPtrFactory<TtsPlatformImplLinux> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TtsPlatformImplLinux); }; @@ -105,8 +105,7 @@ // static SPDNotificationType TtsPlatformImplLinux::current_notification_ = SPD_EVENT_END; -TtsPlatformImplLinux::TtsPlatformImplLinux() - : utterance_id_(0), weak_factory_(this) { +TtsPlatformImplLinux::TtsPlatformImplLinux() : utterance_id_(0) { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (!command_line.HasSwitch(switches::kEnableSpeechDispatcher))
diff --git a/content/browser/ssl/ssl_client_auth_handler.cc b/content/browser/ssl/ssl_client_auth_handler.cc index b8e6b02..54e5d60 100644 --- a/content/browser/ssl/ssl_client_auth_handler.cc +++ b/content/browser/ssl/ssl_client_auth_handler.cc
@@ -153,8 +153,7 @@ Delegate* delegate) : web_contents_getter_(web_contents_getter), cert_request_info_(cert_request_info), - delegate_(delegate), - weak_factory_(this) { + delegate_(delegate) { DCHECK_CURRENTLY_ON(BrowserThread::IO); core_ = new Core(weak_factory_.GetWeakPtr(), std::move(client_cert_store),
diff --git a/content/browser/ssl/ssl_client_auth_handler.h b/content/browser/ssl/ssl_client_auth_handler.h index 937e2067..541ae67 100644 --- a/content/browser/ssl/ssl_client_auth_handler.h +++ b/content/browser/ssl/ssl_client_auth_handler.h
@@ -104,7 +104,7 @@ // The delegate to call back with the result. Delegate* delegate_; - base::WeakPtrFactory<SSLClientAuthHandler> weak_factory_; + base::WeakPtrFactory<SSLClientAuthHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SSLClientAuthHandler); };
diff --git a/content/browser/storage_partition_impl.cc b/content/browser/storage_partition_impl.cc index 4254980..186174c5 100644 --- a/content/browser/storage_partition_impl.cc +++ b/content/browser/storage_partition_impl.cc
@@ -752,8 +752,7 @@ special_storage_policy_(special_storage_policy), network_context_client_binding_(this), browser_context_(browser_context), - deletion_helpers_running_(0), - weak_factory_(this) {} + deletion_helpers_running_(0) {} StoragePartitionImpl::~StoragePartitionImpl() { browser_context_ = nullptr;
diff --git a/content/browser/storage_partition_impl.h b/content/browser/storage_partition_impl.h index 1ed9443..10a6041e 100644 --- a/content/browser/storage_partition_impl.h +++ b/content/browser/storage_partition_impl.h
@@ -426,7 +426,7 @@ // Called when all deletions are done. For test use only. base::OnceClosure on_deletion_helpers_done_callback_; - base::WeakPtrFactory<StoragePartitionImpl> weak_factory_; + base::WeakPtrFactory<StoragePartitionImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(StoragePartitionImpl); };
diff --git a/content/browser/tracing/background_tracing_active_scenario.cc b/content/browser/tracing/background_tracing_active_scenario.cc index f51917ee..764b2e6 100644 --- a/content/browser/tracing/background_tracing_active_scenario.cc +++ b/content/browser/tracing/background_tracing_active_scenario.cc
@@ -270,8 +270,7 @@ : config_(std::move(config)), requires_anonymized_data_(requires_anonymized_data), receive_callback_(std::move(receive_callback)), - on_aborted_callback_(std::move(on_aborted_callback)), - weak_ptr_factory_(this) { + on_aborted_callback_(std::move(on_aborted_callback)) { DCHECK(config_ && !config_->rules().empty()); for (const auto& rule : config_->rules()) { rule->Install();
diff --git a/content/browser/tracing/background_tracing_active_scenario.h b/content/browser/tracing/background_tracing_active_scenario.h index 3e539ee..ea45fc02 100644 --- a/content/browser/tracing/background_tracing_active_scenario.h +++ b/content/browser/tracing/background_tracing_active_scenario.h
@@ -96,7 +96,7 @@ std::unique_ptr<TracingTimer> tracing_timer_; // NOTE: Weak pointers must be invalidated before all other member variables. - base::WeakPtrFactory<BackgroundTracingActiveScenario> weak_ptr_factory_; + base::WeakPtrFactory<BackgroundTracingActiveScenario> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundTracingActiveScenario); };
diff --git a/content/browser/tracing/tracing_ui.cc b/content/browser/tracing/tracing_ui.cc index 4d305f5..3ed091d 100644 --- a/content/browser/tracing/tracing_ui.cc +++ b/content/browser/tracing/tracing_ui.cc
@@ -163,8 +163,7 @@ TracingUI::TracingUI(WebUI* web_ui) : WebUIController(web_ui), - delegate_(GetContentClient()->browser()->GetTracingDelegate()), - weak_factory_(this) { + delegate_(GetContentClient()->browser()->GetTracingDelegate()) { web_ui->RegisterMessageCallback( "doUpload", base::BindRepeating(&TracingUI::DoUpload, base::Unretained(this)));
diff --git a/content/browser/tracing/tracing_ui.h b/content/browser/tracing/tracing_ui.h index 0565a02..6f0d9c8f 100644 --- a/content/browser/tracing/tracing_ui.h +++ b/content/browser/tracing/tracing_ui.h
@@ -46,7 +46,7 @@ std::unique_ptr<TracingDelegate> delegate_; std::unique_ptr<TraceUploader> trace_uploader_; - base::WeakPtrFactory<TracingUI> weak_factory_; + base::WeakPtrFactory<TracingUI> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TracingUI); };
diff --git a/content/browser/utility_process_host.cc b/content/browser/utility_process_host.cc index cbc9d54d..957059c 100644 --- a/content/browser/utility_process_host.cc +++ b/content/browser/utility_process_host.cc
@@ -214,8 +214,7 @@ child_flags_(ChildProcessHost::CHILD_NORMAL), #endif started_(false), - name_(base::ASCIIToUTF16("utility process")), - weak_ptr_factory_(this) { + name_(base::ASCIIToUTF16("utility process")) { process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_UTILITY, this, mojom::kUtilityServiceName)); }
diff --git a/content/browser/utility_process_host.h b/content/browser/utility_process_host.h index 43ef74ce..6c5c47f 100644 --- a/content/browser/utility_process_host.h +++ b/content/browser/utility_process_host.h
@@ -160,7 +160,7 @@ pending_run_service_callbacks_; // Used to vend weak pointers, and should always be declared last. - base::WeakPtrFactory<UtilityProcessHost> weak_ptr_factory_; + base::WeakPtrFactory<UtilityProcessHost> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(UtilityProcessHost); };
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 3cc697a..702a9c4c 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -610,9 +610,7 @@ showing_context_menu_(false), text_autosizer_page_info_({0, 0, 1.f}), native_theme_observer_(this), - had_inner_webcontents_(false), - loading_weak_factory_(this), - weak_factory_(this) { + had_inner_webcontents_(false) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); @@ -6725,6 +6723,10 @@ return GetAudioStreamFactory()->group_id(); } +ukm::SourceId WebContentsImpl::GetLastCommittedSourceId() { + return last_committed_source_id_; +} + BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const { return browser_plugin_embedder_.get(); }
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index 2fde40c..327184c1 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -468,6 +468,7 @@ void SetShowingContextMenu(bool showing) override; base::UnguessableToken GetAudioGroupId() override; bool CompletedFirstVisuallyNonEmptyPaint() override; + ukm::SourceId GetLastCommittedSourceId() override; #if defined(OS_ANDROID) base::android::ScopedJavaLocalRef<jobject> GetJavaWebContents() override; @@ -1923,8 +1924,8 @@ std::unique_ptr<JavaScriptDialogNavigationDeferrer> javascript_dialog_navigation_deferrer_; - base::WeakPtrFactory<WebContentsImpl> loading_weak_factory_; - base::WeakPtrFactory<WebContentsImpl> weak_factory_; + base::WeakPtrFactory<WebContentsImpl> loading_weak_factory_{this}; + base::WeakPtrFactory<WebContentsImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WebContentsImpl); };
diff --git a/content/browser/web_contents/web_contents_impl_browsertest.cc b/content/browser/web_contents/web_contents_impl_browsertest.cc index 02a99c8..6a6b508 100644 --- a/content/browser/web_contents/web_contents_impl_browsertest.cc +++ b/content/browser/web_contents/web_contents_impl_browsertest.cc
@@ -2993,8 +2993,7 @@ SetBrowserClientForTesting(old_client); } -// DISABLED: frquent timeout crbug.com/978028 -IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, DISABLED_SetPageFrozen) { +IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, SetPageFrozen) { EXPECT_TRUE(embedded_test_server()->Start()); GURL test_url = embedded_test_server()->GetURL("/pause_schedule_task.html");
diff --git a/content/browser/web_package/prefetched_signed_exchange_cache.cc b/content/browser/web_package/prefetched_signed_exchange_cache.cc index 8c61557..2058a40 100644 --- a/content/browser/web_package/prefetched_signed_exchange_cache.cc +++ b/content/browser/web_package/prefetched_signed_exchange_cache.cc
@@ -85,6 +85,7 @@ network::ResourceResponseHead response_head = signed_exchange_utils::CreateRedirectResponseHead( outer_response, false /* is_fallback_redirect */); + response_head.was_fetched_via_cache = true; response_head.was_in_prefetch_cache = true; UpdateRequestResponseStartTime(&response_head); client_->OnReceiveRedirect(signed_exchange_utils::CreateRedirectInfo( @@ -134,8 +135,7 @@ : response_(inner_response), blob_data_handle_(std::move(blob_data_handle)), completion_status_(completion_status), - client_(std::move(client)), - weak_factory_(this) { + client_(std::move(client)) { DCHECK(response_.headers); DCHECK(request.request_initiator); @@ -307,7 +307,7 @@ network::mojom::URLLoaderClientPtr client_; std::unique_ptr<CrossOriginReadBlockingChecker> corb_checker_; - base::WeakPtrFactory<InnerResponseURLLoader> weak_factory_; + base::WeakPtrFactory<InnerResponseURLLoader> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(InnerResponseURLLoader); }; @@ -376,9 +376,7 @@ PrefetchedNavigationLoaderInterceptor( std::unique_ptr<const PrefetchedSignedExchangeCache::Entry> exchange, std::vector<PrefetchedSignedExchangeInfo> info_list) - : exchange_(std::move(exchange)), - info_list_(std::move(info_list)), - weak_factory_(this) {} + : exchange_(std::move(exchange)), info_list_(std::move(info_list)) {} ~PrefetchedNavigationLoaderInterceptor() override {} @@ -452,7 +450,8 @@ std::unique_ptr<const PrefetchedSignedExchangeCache::Entry> exchange_; std::vector<PrefetchedSignedExchangeInfo> info_list_; - base::WeakPtrFactory<PrefetchedNavigationLoaderInterceptor> weak_factory_; + base::WeakPtrFactory<PrefetchedNavigationLoaderInterceptor> weak_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(PrefetchedNavigationLoaderInterceptor); };
diff --git a/content/browser/web_package/prefetched_signed_exchange_cache_adapter.cc b/content/browser/web_package/prefetched_signed_exchange_cache_adapter.cc index d64bb19..49628333 100644 --- a/content/browser/web_package/prefetched_signed_exchange_cache_adapter.cc +++ b/content/browser/web_package/prefetched_signed_exchange_cache_adapter.cc
@@ -52,6 +52,7 @@ const network::ResourceResponseHead& response) { std::unique_ptr<network::ResourceResponseHead> inner_response = std::make_unique<network::ResourceResponseHead>(response); + inner_response->was_fetched_via_cache = true; inner_response->was_in_prefetch_cache = true; cached_exchange_->SetInnerResponse(std::move(inner_response)); }
diff --git a/content/browser/web_package/signed_exchange_handler.cc b/content/browser/web_package/signed_exchange_handler.cc index 88a4de4..c44b72a 100644 --- a/content/browser/web_package/signed_exchange_handler.cc +++ b/content/browser/web_package/signed_exchange_handler.cc
@@ -201,8 +201,7 @@ request_matcher_(std::move(request_matcher)), devtools_proxy_(std::move(devtools_proxy)), reporter_(reporter), - frame_tree_node_id_getter_(frame_tree_node_id_getter), - weak_factory_(this) { + frame_tree_node_id_getter_(frame_tree_node_id_getter) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("loading"), "SignedExchangeHandler::SignedExchangeHandler"); @@ -253,8 +252,7 @@ SignedExchangeHandler::SignedExchangeHandler() : is_secure_transport_(true), has_nosniff_(true), - load_flags_(net::LOAD_NORMAL), - weak_factory_(this) {} + load_flags_(net::LOAD_NORMAL) {} const GURL& SignedExchangeHandler::GetFallbackUrl() const { return prologue_fallback_url_and_after_.fallback_url().url;
diff --git a/content/browser/web_package/signed_exchange_handler.h b/content/browser/web_package/signed_exchange_handler.h index 0fc5029..91dec83 100644 --- a/content/browser/web_package/signed_exchange_handler.h +++ b/content/browser/web_package/signed_exchange_handler.h
@@ -183,7 +183,7 @@ base::TimeTicks cert_fetch_start_time_; - base::WeakPtrFactory<SignedExchangeHandler> weak_factory_; + base::WeakPtrFactory<SignedExchangeHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SignedExchangeHandler); };
diff --git a/content/browser/web_package/signed_exchange_loader.cc b/content/browser/web_package/signed_exchange_loader.cc index 4cec257..af7d7a9 100644 --- a/content/browser/web_package/signed_exchange_loader.cc +++ b/content/browser/web_package/signed_exchange_loader.cc
@@ -83,8 +83,7 @@ url_loader_throttles_getter_(std::move(url_loader_throttles_getter)), frame_tree_node_id_getter_(frame_tree_node_id_getter), metric_recorder_(std::move(metric_recorder)), - accept_langs_(accept_langs), - weak_factory_(this) { + accept_langs_(accept_langs) { DCHECK(outer_request_.url.is_valid()); // |metric_recorder_| could be null in some tests.
diff --git a/content/browser/web_package/signed_exchange_loader.h b/content/browser/web_package/signed_exchange_loader.h index c558a55f..7122382 100644 --- a/content/browser/web_package/signed_exchange_loader.h +++ b/content/browser/web_package/signed_exchange_loader.h
@@ -192,7 +192,7 @@ std::unique_ptr<SignedExchangeValidityPinger> validity_pinger_; - base::WeakPtrFactory<SignedExchangeLoader> weak_factory_; + base::WeakPtrFactory<SignedExchangeLoader> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SignedExchangeLoader); };
diff --git a/content/browser/web_package/signed_exchange_request_handler.cc b/content/browser/web_package/signed_exchange_request_handler.cc index d597873..9a29e53 100644 --- a/content/browser/web_package/signed_exchange_request_handler.cc +++ b/content/browser/web_package/signed_exchange_request_handler.cc
@@ -44,9 +44,7 @@ url_loader_factory_(url_loader_factory), url_loader_throttles_getter_(std::move(url_loader_throttles_getter)), metric_recorder_(std::move(metric_recorder)), - accept_langs_(std::move(accept_langs)), - weak_factory_(this) { -} + accept_langs_(std::move(accept_langs)) {} SignedExchangeRequestHandler::~SignedExchangeRequestHandler() = default;
diff --git a/content/browser/web_package/signed_exchange_request_handler.h b/content/browser/web_package/signed_exchange_request_handler.h index 1b0b593..09b1012 100644 --- a/content/browser/web_package/signed_exchange_request_handler.h +++ b/content/browser/web_package/signed_exchange_request_handler.h
@@ -76,7 +76,7 @@ scoped_refptr<SignedExchangePrefetchMetricRecorder> metric_recorder_; const std::string accept_langs_; - base::WeakPtrFactory<SignedExchangeRequestHandler> weak_factory_; + base::WeakPtrFactory<SignedExchangeRequestHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SignedExchangeRequestHandler); };
diff --git a/content/browser/webauth/authenticator_common.cc b/content/browser/webauth/authenticator_common.cc index 20308717..1a45dcc 100644 --- a/content/browser/webauth/authenticator_common.cc +++ b/content/browser/webauth/authenticator_common.cc
@@ -545,8 +545,7 @@ : render_frame_host_(render_frame_host), connector_(connector), transports_(GetTransportsEnabledByFlags()), - timer_(std::move(timer)), - weak_factory_(this) { + timer_(std::move(timer)) { DCHECK(render_frame_host_); DCHECK(timer_); }
diff --git a/content/browser/webauth/authenticator_common.h b/content/browser/webauth/authenticator_common.h index d2b7ef5..08d8bd6 100644 --- a/content/browser/webauth/authenticator_common.h +++ b/content/browser/webauth/authenticator_common.h
@@ -222,7 +222,7 @@ blink::mojom::AuthenticatorStatus error_awaiting_user_acknowledgement_ = blink::mojom::AuthenticatorStatus::NOT_ALLOWED_ERROR; - base::WeakPtrFactory<AuthenticatorCommon> weak_factory_; + base::WeakPtrFactory<AuthenticatorCommon> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AuthenticatorCommon); };
diff --git a/content/browser/webauth/authenticator_impl.cc b/content/browser/webauth/authenticator_impl.cc index 14213f0..a3bdbdb 100644 --- a/content/browser/webauth/authenticator_impl.cc +++ b/content/browser/webauth/authenticator_impl.cc
@@ -28,8 +28,7 @@ std::unique_ptr<AuthenticatorCommon> authenticator_common) : WebContentsObserver(WebContents::FromRenderFrameHost(render_frame_host)), render_frame_host_(render_frame_host), - authenticator_common_(std::move(authenticator_common)), - weak_factory_(this) { + authenticator_common_(std::move(authenticator_common)) { DCHECK(render_frame_host_); DCHECK(authenticator_common_); }
diff --git a/content/browser/webauth/authenticator_impl.h b/content/browser/webauth/authenticator_impl.h index 9819af8..90b881d 100644 --- a/content/browser/webauth/authenticator_impl.h +++ b/content/browser/webauth/authenticator_impl.h
@@ -91,7 +91,7 @@ // Owns pipes to this Authenticator from |render_frame_host_|. mojo::Receiver<blink::mojom::Authenticator> receiver_{this}; - base::WeakPtrFactory<AuthenticatorImpl> weak_factory_; + base::WeakPtrFactory<AuthenticatorImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AuthenticatorImpl); };
diff --git a/content/browser/webrtc/webrtc_internals.cc b/content/browser/webrtc/webrtc_internals.cc index eae73aa7..c943ada 100644 --- a/content/browser/webrtc/webrtc_internals.cc +++ b/content/browser/webrtc/webrtc_internals.cc
@@ -102,8 +102,7 @@ event_log_recordings_(false), num_connected_connections_(0), should_block_power_saving_(should_block_power_saving), - aggregate_updates_ms_(aggregate_updates_ms), - weak_factory_(this) { + aggregate_updates_ms_(aggregate_updates_ms) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!g_webrtc_internals);
diff --git a/content/browser/webrtc/webrtc_internals.h b/content/browser/webrtc/webrtc_internals.h index 3070996..b10e8a9 100644 --- a/content/browser/webrtc/webrtc_internals.h +++ b/content/browser/webrtc/webrtc_internals.h
@@ -291,7 +291,7 @@ const int aggregate_updates_ms_; // Weak factory for this object that we use for bulking up updates. - base::WeakPtrFactory<WebRTCInternals> weak_factory_; + base::WeakPtrFactory<WebRTCInternals> weak_factory_{this}; }; } // namespace content
diff --git a/content/browser/webrtc/webrtc_video_capture_service_browsertest.cc b/content/browser/webrtc/webrtc_video_capture_service_browsertest.cc index 9619ff9..2dee5d94 100644 --- a/content/browser/webrtc/webrtc_video_capture_service_browsertest.cc +++ b/content/browser/webrtc/webrtc_video_capture_service_browsertest.cc
@@ -95,9 +95,7 @@ // RGB dummy frames, one dark one and one light one. class TextureDeviceExerciser : public VirtualDeviceExerciser { public: - TextureDeviceExerciser() : weak_factory_(this) { - DETACH_FROM_SEQUENCE(sequence_checker_); - } + TextureDeviceExerciser() { DETACH_FROM_SEQUENCE(sequence_checker_); } void Initialize() override { ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); @@ -230,7 +228,7 @@ std::vector<gpu::MailboxHolder> dummy_frame_0_mailbox_holder_; std::vector<gpu::MailboxHolder> dummy_frame_1_mailbox_holder_; std::array<bool, 2> frame_being_consumed_; - base::WeakPtrFactory<TextureDeviceExerciser> weak_factory_; + base::WeakPtrFactory<TextureDeviceExerciser> weak_factory_{this}; }; // A VirtualDeviceExerciser for exercising @@ -242,9 +240,7 @@ public: explicit SharedMemoryDeviceExerciser( media::mojom::PlaneStridesPtr strides = nullptr) - : strides_(std::move(strides)), - producer_binding_(this), - weak_factory_(this) {} + : strides_(std::move(strides)), producer_binding_(this) {} // VirtualDeviceExerciser implementation. void Initialize() override {} @@ -396,7 +392,7 @@ std::map<int32_t /*buffer_id*/, std::unique_ptr<media::SharedMemoryHandleProvider>> outgoing_buffer_id_to_buffer_map_; - base::WeakPtrFactory<SharedMemoryDeviceExerciser> weak_factory_; + base::WeakPtrFactory<SharedMemoryDeviceExerciser> weak_factory_{this}; }; // Integration test that obtains a connection to the video capture service via @@ -407,7 +403,7 @@ class WebRtcVideoCaptureServiceBrowserTest : public ContentBrowserTest { public: WebRtcVideoCaptureServiceBrowserTest() - : virtual_device_thread_("Virtual Device Thread"), weak_factory_(this) { + : virtual_device_thread_("Virtual Device Thread") { scoped_feature_list_.InitAndEnableFeature(features::kMojoVideoCapture); virtual_device_thread_.Start(); } @@ -524,7 +520,8 @@ video_capture::mojom::DeviceFactoryPtr factory_; gfx::Size video_size_; base::TimeTicks first_frame_time_; - base::WeakPtrFactory<WebRtcVideoCaptureServiceBrowserTest> weak_factory_; + base::WeakPtrFactory<WebRtcVideoCaptureServiceBrowserTest> weak_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(WebRtcVideoCaptureServiceBrowserTest); };
diff --git a/content/browser/webrtc/webrtc_video_capture_shared_device_browsertest.cc b/content/browser/webrtc/webrtc_video_capture_shared_device_browsertest.cc index f056db96..1079f1dd 100644 --- a/content/browser/webrtc/webrtc_video_capture_shared_device_browsertest.cc +++ b/content/browser/webrtc/webrtc_video_capture_shared_device_browsertest.cc
@@ -69,7 +69,7 @@ : public ContentBrowserTest, public testing::WithParamInterface<TestParams> { public: - WebRtcVideoCaptureSharedDeviceBrowserTest() : weak_factory_(this) { + WebRtcVideoCaptureSharedDeviceBrowserTest() { scoped_feature_list_.InitAndEnableFeature(features::kMojoVideoCapture); } @@ -212,7 +212,8 @@ video_capture::mojom::PushVideoStreamSubscriptionPtr subscription_; video_capture::mojom::ReceiverPtr receiver_proxy_; - base::WeakPtrFactory<WebRtcVideoCaptureSharedDeviceBrowserTest> weak_factory_; + base::WeakPtrFactory<WebRtcVideoCaptureSharedDeviceBrowserTest> weak_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(WebRtcVideoCaptureSharedDeviceBrowserTest); };
diff --git a/content/browser/websockets/websocket_manager.cc b/content/browser/websockets/websocket_manager.cc index 3a2d411..ced3c13 100644 --- a/content/browser/websockets/websocket_manager.cc +++ b/content/browser/websockets/websocket_manager.cc
@@ -103,7 +103,7 @@ explicit SSLErrorHandlerDelegate( std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks> callbacks) - : callbacks_(std::move(callbacks)), weak_ptr_factory_(this) {} + : callbacks_(std::move(callbacks)) {} ~SSLErrorHandlerDelegate() override {} base::WeakPtr<SSLErrorHandler::Delegate> GetWeakPtr() { @@ -127,7 +127,7 @@ private: std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks> callbacks_; - base::WeakPtrFactory<SSLErrorHandlerDelegate> weak_ptr_factory_; + base::WeakPtrFactory<SSLErrorHandlerDelegate> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SSLErrorHandlerDelegate); };
diff --git a/content/browser/webui/url_data_manager_backend.cc b/content/browser/webui/url_data_manager_backend.cc index 8facf181..9004a16a 100644 --- a/content/browser/webui/url_data_manager_backend.cc +++ b/content/browser/webui/url_data_manager_backend.cc
@@ -159,7 +159,7 @@ // The backend is owned by net::URLRequestContext and always outlives us. URLDataManagerBackend* const backend_; - base::WeakPtrFactory<URLRequestChromeJob> weak_factory_; + base::WeakPtrFactory<URLRequestChromeJob> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(URLRequestChromeJob); }; @@ -172,8 +172,7 @@ data_available_status_(net::OK), pending_buf_size_(0), is_gzipped_(false), - backend_(backend), - weak_factory_(this) { + backend_(backend) { DCHECK(backend); } @@ -402,8 +401,7 @@ } // namespace -URLDataManagerBackend::URLDataManagerBackend() - : next_request_id_(0), weak_factory_(this) { +URLDataManagerBackend::URLDataManagerBackend() : next_request_id_(0) { URLDataSource* shared_source = new SharedResourcesDataSource(); AddDataSource(new URLDataSourceImpl(shared_source->GetSource(), base::WrapUnique(shared_source)));
diff --git a/content/browser/webui/url_data_manager_backend.h b/content/browser/webui/url_data_manager_backend.h index d5009883..463bc9a 100644 --- a/content/browser/webui/url_data_manager_backend.h +++ b/content/browser/webui/url_data_manager_backend.h
@@ -128,7 +128,7 @@ // to the backend that originally owned them, even if they've been replaced // and detached from the backend. This allows outstanding asynchronous queries // to be served and routed to the backend to which they were original issued. - base::WeakPtrFactory<URLDataManagerBackend> weak_factory_; + base::WeakPtrFactory<URLDataManagerBackend> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(URLDataManagerBackend); };
diff --git a/content/browser/worker_host/dedicated_worker_host.cc b/content/browser/worker_host/dedicated_worker_host.cc index 6617b00..9ea55f1 100644 --- a/content/browser/worker_host/dedicated_worker_host.cc +++ b/content/browser/worker_host/dedicated_worker_host.cc
@@ -44,8 +44,7 @@ const url::Origin& origin) : process_id_(process_id), ancestor_render_frame_id_(ancestor_render_frame_id), - origin_(origin), - weak_factory_(this) { + origin_(origin) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RegisterMojoInterfaces(); } @@ -305,7 +304,7 @@ service_manager::BinderRegistry registry_; - base::WeakPtrFactory<DedicatedWorkerHost> weak_factory_; + base::WeakPtrFactory<DedicatedWorkerHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DedicatedWorkerHost); };
diff --git a/content/browser/worker_host/shared_worker_host.cc b/content/browser/worker_host/shared_worker_host.cc index 9d408ab..ba3d3ff 100644 --- a/content/browser/worker_host/shared_worker_host.cc +++ b/content/browser/worker_host/shared_worker_host.cc
@@ -116,8 +116,7 @@ instance_(std::move(instance)), process_id_(process_id), next_connection_request_id_(1), - interface_provider_binding_(this), - weak_factory_(this) { + interface_provider_binding_(this) { DCHECK(instance_); // Set up the worker interface request. This is needed first in either // AddClient() or Start(). AddClient() can sometimes be called before Start()
diff --git a/content/browser/worker_host/shared_worker_host.h b/content/browser/worker_host/shared_worker_host.h index 66869a6..b7578e3 100644 --- a/content/browser/worker_host/shared_worker_host.h +++ b/content/browser/worker_host/shared_worker_host.h
@@ -218,7 +218,7 @@ Phase phase_ = Phase::kInitial; - base::WeakPtrFactory<SharedWorkerHost> weak_factory_; + base::WeakPtrFactory<SharedWorkerHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SharedWorkerHost); };
diff --git a/content/browser/worker_host/shared_worker_service_impl.cc b/content/browser/worker_host/shared_worker_service_impl.cc index 213e7758..58663f6e 100644 --- a/content/browser/worker_host/shared_worker_service_impl.cc +++ b/content/browser/worker_host/shared_worker_service_impl.cc
@@ -56,8 +56,7 @@ scoped_refptr<ChromeAppCacheService> appcache_service) : storage_partition_(storage_partition), service_worker_context_(std::move(service_worker_context)), - appcache_service_(std::move(appcache_service)), - weak_factory_(this) { + appcache_service_(std::move(appcache_service)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); }
diff --git a/content/browser/worker_host/shared_worker_service_impl.h b/content/browser/worker_host/shared_worker_service_impl.h index 572e71a..2324598 100644 --- a/content/browser/worker_host/shared_worker_service_impl.h +++ b/content/browser/worker_host/shared_worker_service_impl.h
@@ -138,7 +138,7 @@ scoped_refptr<ChromeAppCacheService> appcache_service_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_override_; - base::WeakPtrFactory<SharedWorkerServiceImpl> weak_factory_; + base::WeakPtrFactory<SharedWorkerServiceImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SharedWorkerServiceImpl); };
diff --git a/content/browser/worker_host/worker_script_loader.cc b/content/browser/worker_host/worker_script_loader.cc index cc7a04d..29e875c 100644 --- a/content/browser/worker_host/worker_script_loader.cc +++ b/content/browser/worker_host/worker_script_loader.cc
@@ -38,8 +38,7 @@ resource_context_getter_(resource_context_getter), default_loader_factory_(std::move(default_loader_factory)), traffic_annotation_(traffic_annotation), - url_loader_client_binding_(this), - weak_factory_(this) { + url_loader_client_binding_(this) { if (service_worker_provider_host_) { std::unique_ptr<NavigationLoaderInterceptor> service_worker_interceptor = ServiceWorkerRequestHandler::CreateForWorker(
diff --git a/content/browser/worker_host/worker_script_loader.h b/content/browser/worker_host/worker_script_loader.h index 5c1847d6..6d0edd2 100644 --- a/content/browser/worker_host/worker_script_loader.h +++ b/content/browser/worker_host/worker_script_loader.h
@@ -151,7 +151,7 @@ bool completed_ = false; - base::WeakPtrFactory<WorkerScriptLoader> weak_factory_; + base::WeakPtrFactory<WorkerScriptLoader> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WorkerScriptLoader); };
diff --git a/content/child/blink_platform_impl.cc b/content/child/blink_platform_impl.cc index 2d4ed5a6..bc030935 100644 --- a/content/child/blink_platform_impl.cc +++ b/content/child/blink_platform_impl.cc
@@ -446,6 +446,8 @@ {"win.css", IDR_UASTYLE_THEME_WIN_CSS, ui::SCALE_FACTOR_NONE, true}, {"win_quirks.css", IDR_UASTYLE_THEME_WIN_QUIRKS_CSS, ui::SCALE_FACTOR_NONE, true}, + {"controls_refresh.css", IDR_UASTYLE_THEME_CONTROLS_REFRESH_CSS, + ui::SCALE_FACTOR_NONE, true}, {"svg.css", IDR_UASTYLE_SVG_CSS, ui::SCALE_FACTOR_NONE, true}, {"mathml.css", IDR_UASTYLE_MATHML_CSS, ui::SCALE_FACTOR_NONE, true}, {"fullscreen.css", IDR_UASTYLE_FULLSCREEN_CSS, ui::SCALE_FACTOR_NONE, true},
diff --git a/content/child/child_thread_impl.cc b/content/child/child_thread_impl.cc index 31ee3932..4cf94cf3 100644 --- a/content/child/child_thread_impl.cc +++ b/content/child/child_thread_impl.cc
@@ -353,8 +353,7 @@ browser_process_io_runner_(options.browser_process_io_runner), channel_connected_factory_( new base::WeakPtrFactory<ChildThreadImpl>(this)), - ipc_task_runner_(options.ipc_task_runner), - weak_factory_(this) { + ipc_task_runner_(options.ipc_task_runner) { Init(options); }
diff --git a/content/child/child_thread_impl.h b/content/child/child_thread_impl.h index 157b604..6c9c9df 100644 --- a/content/child/child_thread_impl.h +++ b/content/child/child_thread_impl.h
@@ -252,7 +252,7 @@ scoped_refptr<base::SingleThreadTaskRunner> ipc_task_runner_; - base::WeakPtrFactory<ChildThreadImpl> weak_factory_; + base::WeakPtrFactory<ChildThreadImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ChildThreadImpl); };
diff --git a/content/common/mime_sniffing_throttle.cc b/content/common/mime_sniffing_throttle.cc index e0653fb..62d72fe 100644 --- a/content/common/mime_sniffing_throttle.cc +++ b/content/common/mime_sniffing_throttle.cc
@@ -11,7 +11,7 @@ MimeSniffingThrottle::MimeSniffingThrottle( scoped_refptr<base::SingleThreadTaskRunner> task_runner) - : task_runner_(std::move(task_runner)), weak_factory_(this) {} + : task_runner_(std::move(task_runner)) {} MimeSniffingThrottle::~MimeSniffingThrottle() = default;
diff --git a/content/common/mime_sniffing_throttle.h b/content/common/mime_sniffing_throttle.h index 15fd17b..539fecb 100644 --- a/content/common/mime_sniffing_throttle.h +++ b/content/common/mime_sniffing_throttle.h
@@ -33,7 +33,7 @@ private: scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - base::WeakPtrFactory<MimeSniffingThrottle> weak_factory_; + base::WeakPtrFactory<MimeSniffingThrottle> weak_factory_{this}; }; } // namespace content
diff --git a/content/common/service_manager/child_connection.cc b/content/common/service_manager/child_connection.cc index b359c59..5613a98a 100644 --- a/content/common/service_manager/child_connection.cc +++ b/content/common/service_manager/child_connection.cc
@@ -132,9 +132,7 @@ mojo::OutgoingInvitation* invitation, service_manager::Connector* connector, scoped_refptr<base::SequencedTaskRunner> io_task_runner) - : context_(new IOThreadContext), - child_identity_(child_identity), - weak_factory_(this) { + : context_(new IOThreadContext), child_identity_(child_identity) { service_token_ = base::NumberToString(base::RandUint64()); context_->Initialize(child_identity_, connector, invitation->AttachMessagePipe(service_token_),
diff --git a/content/common/service_manager/child_connection.h b/content/common/service_manager/child_connection.h index ff66ac6a..e14b29fc 100644 --- a/content/common/service_manager/child_connection.h +++ b/content/common/service_manager/child_connection.h
@@ -69,7 +69,7 @@ service_manager::Identity child_identity_; std::string service_token_; - base::WeakPtrFactory<ChildConnection> weak_factory_; + base::WeakPtrFactory<ChildConnection> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ChildConnection); };
diff --git a/content/common/service_manager/service_manager_connection_impl.cc b/content/common/service_manager/service_manager_connection_impl.cc index 7f4de78c..7e635c4d 100644 --- a/content/common/service_manager/service_manager_connection_impl.cc +++ b/content/common/service_manager/service_manager_connection_impl.cc
@@ -52,15 +52,13 @@ public service_manager::Service, public mojom::Child { public: - IOThreadContext( - service_manager::mojom::ServiceRequest service_request, - scoped_refptr<base::SequencedTaskRunner> io_task_runner, - service_manager::mojom::ConnectorRequest connector_request) + IOThreadContext(service_manager::mojom::ServiceRequest service_request, + scoped_refptr<base::SequencedTaskRunner> io_task_runner, + service_manager::mojom::ConnectorRequest connector_request) : pending_service_request_(std::move(service_request)), io_task_runner_(io_task_runner), pending_connector_request_(std::move(connector_request)), - child_binding_(this), - weak_factory_(this) { + child_binding_(this) { // This will be reattached by any of the IO thread functions on first call. io_thread_checker_.DetachFromThread(); } @@ -338,7 +336,7 @@ mojo::Binding<mojom::Child> child_binding_; - base::WeakPtrFactory<IOThreadContext> weak_factory_; + base::WeakPtrFactory<IOThreadContext> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(IOThreadContext); }; @@ -403,8 +401,7 @@ ServiceManagerConnectionImpl::ServiceManagerConnectionImpl( service_manager::mojom::ServiceRequest request, - scoped_refptr<base::SequencedTaskRunner> io_task_runner) - : weak_factory_(this) { + scoped_refptr<base::SequencedTaskRunner> io_task_runner) { service_manager::mojom::ConnectorRequest connector_request; connector_ = service_manager::Connector::Create(&connector_request); context_ = new IOThreadContext(std::move(request), io_task_runner,
diff --git a/content/common/service_manager/service_manager_connection_impl.h b/content/common/service_manager/service_manager_connection_impl.h index 5f989c7..6f572250 100644 --- a/content/common/service_manager/service_manager_connection_impl.h +++ b/content/common/service_manager/service_manager_connection_impl.h
@@ -59,7 +59,7 @@ base::Closure connection_lost_handler_; - base::WeakPtrFactory<ServiceManagerConnectionImpl> weak_factory_; + base::WeakPtrFactory<ServiceManagerConnectionImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceManagerConnectionImpl); };
diff --git a/content/common/service_worker/service_worker_types.cc b/content/common/service_worker/service_worker_types.cc index f85c1aa4..4a5f27e 100644 --- a/content/common/service_worker/service_worker_types.cc +++ b/content/common/service_worker/service_worker_types.cc
@@ -4,8 +4,6 @@ #include "content/common/service_worker/service_worker_types.h" -#include "net/base/load_flags.h" - namespace content { const char kServiceWorkerRegisterErrorPrefix[] =
diff --git a/content/common/service_worker/service_worker_types.h b/content/common/service_worker/service_worker_types.h index 4ea6959e..5be3ae660 100644 --- a/content/common/service_worker/service_worker_types.h +++ b/content/common/service_worker/service_worker_types.h
@@ -5,32 +5,11 @@ #ifndef CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_TYPES_H_ #define CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_TYPES_H_ -#include <stdint.h> - -#include <map> -#include <memory> -#include <string> -#include <vector> - -#include "base/strings/string_util.h" #include "base/time/time.h" -#include "content/common/content_export.h" -#include "content/public/common/referrer.h" -#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h" -#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom.h" -#include "third_party/blink/public/mojom/service_worker/service_worker_client.mojom.h" -#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h" -#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h" -#include "third_party/blink/public/mojom/service_worker/service_worker_state.mojom.h" -#include "url/gurl.h" // This file is to have common definitions that are to be shared by // browser and child process. -namespace storage { -class BlobHandle; -} - namespace content { // Indicates the document main thread ID in the child process. This is used for @@ -61,8 +40,6 @@ static constexpr base::TimeDelta kServiceWorkerScriptMaxCacheAge = base::TimeDelta::FromHours(24); -using ServiceWorkerHeaderList = std::vector<std::string>; - } // namespace content #endif // CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_TYPES_H_
diff --git a/content/common/service_worker/service_worker_utils.h b/content/common/service_worker/service_worker_utils.h index cb103548..c1977bc 100644 --- a/content/common/service_worker/service_worker_utils.h +++ b/content/common/service_worker/service_worker_utils.h
@@ -19,6 +19,8 @@ #include "net/http/http_request_headers.h" #include "third_party/blink/public/common/fetch/fetch_api_request_headers_map.h" #include "third_party/blink/public/common/service_worker/service_worker_status_code.h" +#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h" +#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h" #include "url/gurl.h" namespace content {
diff --git a/content/common/tab_switch_time_recorder.cc b/content/common/tab_switch_time_recorder.cc index 4360e1b..1d051ca 100644 --- a/content/common/tab_switch_time_recorder.cc +++ b/content/common/tab_switch_time_recorder.cc
@@ -48,7 +48,7 @@ destination_is_loaded(destination_is_loaded), destination_is_frozen(destination_is_frozen) {} -TabSwitchTimeRecorder::TabSwitchTimeRecorder() : weak_ptr_factory_(this) {} +TabSwitchTimeRecorder::TabSwitchTimeRecorder() {} TabSwitchTimeRecorder::~TabSwitchTimeRecorder() {}
diff --git a/content/common/tab_switch_time_recorder.h b/content/common/tab_switch_time_recorder.h index f8dc11e..9a93347613 100644 --- a/content/common/tab_switch_time_recorder.h +++ b/content/common/tab_switch_time_recorder.h
@@ -80,7 +80,7 @@ // null if there is no incomplete tab switch. base::TimeTicks render_widget_visibility_request_timestamp_; - base::WeakPtrFactory<TabSwitchTimeRecorder> weak_ptr_factory_; + base::WeakPtrFactory<TabSwitchTimeRecorder> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TabSwitchTimeRecorder); };
diff --git a/content/common/throttling_url_loader.cc b/content/common/throttling_url_loader.cc index 5c22dc5..3ed9f863 100644 --- a/content/common/throttling_url_loader.cc +++ b/content/common/throttling_url_loader.cc
@@ -303,8 +303,7 @@ const net::NetworkTrafficAnnotationTag& traffic_annotation) : forwarding_client_(client), client_binding_(this), - traffic_annotation_(traffic_annotation), - weak_factory_(this) { + traffic_annotation_(traffic_annotation) { throttles_.reserve(throttles.size()); for (auto& throttle : throttles) throttles_.emplace_back(this, std::move(throttle));
diff --git a/content/common/throttling_url_loader.h b/content/common/throttling_url_loader.h index 3e4e330..188f6ed 100644 --- a/content/common/throttling_url_loader.h +++ b/content/common/throttling_url_loader.h
@@ -264,7 +264,7 @@ int pending_restart_flags_ = 0; bool has_pending_restart_ = false; - base::WeakPtrFactory<ThrottlingURLLoader> weak_factory_; + base::WeakPtrFactory<ThrottlingURLLoader> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ThrottlingURLLoader); };
diff --git a/content/common/throttling_url_loader_unittest.cc b/content/common/throttling_url_loader_unittest.cc index 1d4834c..47574a0 100644 --- a/content/common/throttling_url_loader_unittest.cc +++ b/content/common/throttling_url_loader_unittest.cc
@@ -341,7 +341,7 @@ class ThrottlingURLLoaderTest : public testing::Test { public: - ThrottlingURLLoaderTest() : weak_factory_(this) {} + ThrottlingURLLoaderTest() {} std::unique_ptr<ThrottlingURLLoader>& loader() { return loader_; } TestURLLoaderThrottle* throttle() const { return throttle_; } @@ -385,7 +385,7 @@ // Owned by |throttles_| or |loader_|. TestURLLoaderThrottle* throttle_ = nullptr; - base::WeakPtrFactory<ThrottlingURLLoaderTest> weak_factory_; + base::WeakPtrFactory<ThrottlingURLLoaderTest> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ThrottlingURLLoaderTest); };
diff --git a/content/gpu/gpu_child_thread.cc b/content/gpu/gpu_child_thread.cc index 1cde925a3..8688f3c9 100644 --- a/content/gpu/gpu_child_thread.cc +++ b/content/gpu/gpu_child_thread.cc
@@ -72,9 +72,7 @@ QueueingConnectionFilter( scoped_refptr<base::SequencedTaskRunner> io_task_runner, std::unique_ptr<service_manager::BinderRegistry> registry) - : io_task_runner_(io_task_runner), - registry_(std::move(registry)), - weak_factory_(this) { + : io_task_runner_(io_task_runner), registry_(std::move(registry)) { // This will be reattached by any of the IO thread functions on first call. io_thread_checker_.DetachFromThread(); } @@ -159,7 +157,7 @@ viz::VizMainImpl* viz_main_ = nullptr; #endif - base::WeakPtrFactory<QueueingConnectionFilter> weak_factory_; + base::WeakPtrFactory<QueueingConnectionFilter> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(QueueingConnectionFilter); }; @@ -208,8 +206,7 @@ viz_main_(this, CreateVizMainDependencies(GetConnector()), std::move(gpu_init)), - quit_closure_(std::move(quit_closure)), - weak_factory_(this) { + quit_closure_(std::move(quit_closure)) { if (in_process_gpu()) { DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSingleProcess) ||
diff --git a/content/gpu/gpu_child_thread.h b/content/gpu/gpu_child_thread.h index 6e584b0..b37dd3d 100644 --- a/content/gpu/gpu_child_thread.h +++ b/content/gpu/gpu_child_thread.h
@@ -131,7 +131,7 @@ }; std::vector<PendingServiceRequest> pending_service_requests_; - base::WeakPtrFactory<GpuChildThread> weak_factory_; + base::WeakPtrFactory<GpuChildThread> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(GpuChildThread); };
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index 37d805b..acc91aa7d 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -415,6 +415,7 @@ "//net", "//ppapi/c", "//services/device/public/cpp/geolocation", + "//services/metrics/public/cpp:metrics_cpp", "//services/service_manager/embedder:embedder_result_codes", "//ui/accessibility", "//ui/base",
diff --git a/content/public/browser/DEPS b/content/public/browser/DEPS index 08ef71e..39f1a4a 100644 --- a/content/public/browser/DEPS +++ b/content/public/browser/DEPS
@@ -7,6 +7,7 @@ "+device/fido", "+services/device/public", "+services/media_session/public", + "+services/metrics/public/cpp", "+services/network/public/cpp", "+services/service_manager/sandbox", "+services/video_capture/public/mojom",
diff --git a/content/public/browser/accessibility_tree_formatter.h b/content/public/browser/accessibility_tree_formatter.h index 0a94707..f3796b3a 100644 --- a/content/public/browser/accessibility_tree_formatter.h +++ b/content/public/browser/accessibility_tree_formatter.h
@@ -76,6 +76,9 @@ }; static std::vector<TestPass> GetTestPasses(); + // Gets the test pass at the given index. + static TestPass GetTestPass(size_t index); + virtual void AddDefaultFilters( std::vector<PropertyFilter>* property_filters) = 0;
diff --git a/content/public/browser/content_browser_client.cc b/content/public/browser/content_browser_client.cc index 35a5aa5d..114e421 100644 --- a/content/public/browser/content_browser_client.cc +++ b/content/public/browser/content_browser_client.cc
@@ -750,6 +750,12 @@ return false; } +#if defined(OS_ANDROID) +void ContentBrowserClient::WillCreateURLLoaderFactoryForAppCacheSubresource( + int render_process_id, + network::mojom::URLLoaderFactoryPtrInfo* factory_ptr_info) {} +#endif + bool ContentBrowserClient::WillInterceptWebSocket(RenderFrameHost*) { return false; }
diff --git a/content/public/browser/content_browser_client.h b/content/public/browser/content_browser_client.h index 9a228064..82b0be67 100644 --- a/content/public/browser/content_browser_client.h +++ b/content/public/browser/content_browser_client.h
@@ -1247,6 +1247,19 @@ network::mojom::TrustedURLLoaderHeaderClientPtrInfo* header_client, bool* bypass_redirect_checks); +#if defined(OS_ANDROID) + // Similar to WillCreateURLLoaderFactory but for appcache subresources. + // WillCreateURLLoaderFactory couldn't be used because when the appcache + // URLLoaderFactory is sent on the UI thread, the URLLoaderFactoryRequest is + // already consumed. And on the IO thread when it's created but before it's + // consumed, we don't have the process ID. + // This is behind an OS_ANDROID ifdef because we don't need this on desktop. + // Only WebView should implement this, see https://crbug.com/977873. + virtual void WillCreateURLLoaderFactoryForAppCacheSubresource( + int render_process_id, + network::mojom::URLLoaderFactoryPtrInfo* factory_ptr_info); +#endif + // Returns true when the embedder wants to intercept a websocket connection. virtual bool WillInterceptWebSocket(RenderFrameHost* frame);
diff --git a/content/public/browser/content_index_provider.h b/content/public/browser/content_index_provider.h index 425cef9..424c4774 100644 --- a/content/public/browser/content_index_provider.h +++ b/content/public/browser/content_index_provider.h
@@ -40,11 +40,13 @@ class CONTENT_EXPORT ContentIndexProvider { public: // Interface for the client that updates the provider with entries. - class Client { + class CONTENT_EXPORT Client { public: virtual ~Client(); // The client will need to provide an icon for the entry when requested. + // Must be called on the UI thread. |icon_callback| must be invoked on the + // UI thread. virtual void GetIcon(int64_t service_worker_registration_id, const std::string& description_id, base::OnceCallback<void(SkBitmap)> icon_callback) = 0; @@ -55,11 +57,12 @@ // Called when a new entry is registered. |client| is passed for when the // provider will require additional information relating to the entry. + // Must be called on the UI thread. virtual void OnContentAdded( ContentIndexEntry entry, base::WeakPtr<ContentIndexProvider::Client> client) = 0; - // Called when an entry is unregistered. + // Called when an entry is unregistered. Must be called on the UI thread. virtual void OnContentDeleted(int64_t service_worker_registration_id, const std::string& description_id) = 0;
diff --git a/content/public/browser/provision_fetcher_impl.cc b/content/public/browser/provision_fetcher_impl.cc index 9100523..6d763c66 100644 --- a/content/public/browser/provision_fetcher_impl.cc +++ b/content/public/browser/provision_fetcher_impl.cc
@@ -24,7 +24,7 @@ ProvisionFetcherImpl::ProvisionFetcherImpl( std::unique_ptr<media::ProvisionFetcher> provision_fetcher) - : provision_fetcher_(std::move(provision_fetcher)), weak_factory_(this) { + : provision_fetcher_(std::move(provision_fetcher)) { DVLOG(1) << __FUNCTION__; }
diff --git a/content/public/browser/provision_fetcher_impl.h b/content/public/browser/provision_fetcher_impl.h index 6b3106f9..7e6973fe 100644 --- a/content/public/browser/provision_fetcher_impl.h +++ b/content/public/browser/provision_fetcher_impl.h
@@ -46,7 +46,7 @@ std::unique_ptr<media::ProvisionFetcher> provision_fetcher_; - base::WeakPtrFactory<ProvisionFetcherImpl> weak_factory_; + base::WeakPtrFactory<ProvisionFetcherImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ProvisionFetcherImpl); };
diff --git a/content/public/browser/web_contents.h b/content/public/browser/web_contents.h index 06536cf6..b0f5041 100644 --- a/content/public/browser/web_contents.h +++ b/content/public/browser/web_contents.h
@@ -29,6 +29,7 @@ #include "content/public/browser/visibility.h" #include "content/public/browser/web_ui.h" #include "content/public/common/stop_find_action.h" +#include "services/metrics/public/cpp/ukm_source_id.h" #include "third_party/blink/public/common/frame/sandbox_flags.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom-forward.h" #include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom-forward.h" @@ -943,6 +944,9 @@ // created from a renderer that originated from this WebContents. virtual base::UnguessableToken GetAudioGroupId() = 0; + // The source ID of the last committed navigation. + virtual ukm::SourceId GetLastCommittedSourceId() = 0; + private: // This interface should only be implemented inside content. friend class WebContentsImpl;
diff --git a/content/public/common/content_switches.cc b/content/public/common/content_switches.cc index cf9ce9e..c117782 100644 --- a/content/public/common/content_switches.cc +++ b/content/public/common/content_switches.cc
@@ -962,6 +962,14 @@ const char kEnableSpeechDispatcher[] = "enable-speech-dispatcher"; #endif +#if defined(OS_CHROMEOS) +// A time_t. Passed by session_manager into the Chrome user session, indicating +// that if Chrome crashes before the indicated time, session_manager will +// consider this to be a crash-loop situation and log the user out. Chrome +// mostly just passes this to crash_reporter if it crashes. +const char kCrashLoopBefore[] = "crash-loop-before"; +#endif + #if defined(OS_WIN) // /prefetch:# arguments to use when launching various process types. It has // been observed that when file reads are consistent for 3 process launches with
diff --git a/content/public/common/content_switches.h b/content/public/common/content_switches.h index e6954ad..af70652 100644 --- a/content/public/common/content_switches.h +++ b/content/public/common/content_switches.h
@@ -271,6 +271,10 @@ CONTENT_EXPORT extern const char kEnableSpeechDispatcher[]; #endif +#if defined(OS_CHROMEOS) +CONTENT_EXPORT extern const char kCrashLoopBefore[]; +#endif + #if defined(OS_WIN) CONTENT_EXPORT extern const char kPrefetchArgumentRenderer[]; CONTENT_EXPORT extern const char kPrefetchArgumentGpu[];
diff --git a/content/public/renderer/render_frame_observer.h b/content/public/renderer/render_frame_observer.h index 29405a94..7acbfe9 100644 --- a/content/public/renderer/render_frame_observer.h +++ b/content/public/renderer/render_frame_observer.h
@@ -166,13 +166,13 @@ bool is_animated) {} // Reports that visible elements in the frame shifted (bit.ly/lsm-explainer). - // This is called once for each janking animation frame, with the jank - // fraction for that frame. The cumulative jank score can be inferred by - // summing the jank fractions. |after_input_or_scroll| indicates whether the - // given |jank_fraction| was observed after an input or scroll occurred in the - // associated document. - virtual void DidObserveLayoutJank(double jank_fraction, - bool after_input_or_scroll) {} + // This is called once for each animation frame containing any layout shift, + // and receives the layout shift (LS) score for that frame. The cumulative + // layout shift (CLS) score can be inferred by summing the LS scores. + // |after_input_or_scroll| indicates whether the given |score| was observed + // after an input or scroll occurred in the associated document. + virtual void DidObserveLayoutShift(double score, bool after_input_or_scroll) { + } // Reports lazy loaded behavior when the frame or image is fully deferred or // if the frame or image is loaded after being deferred by lazy load.
diff --git a/content/public/test/browser_test_utils.cc b/content/public/test/browser_test_utils.cc index 2947bc8e..24cb050 100644 --- a/content/public/test/browser_test_utils.cc +++ b/content/public/test/browser_test_utils.cc
@@ -1964,6 +1964,45 @@ return manager->SnapshotAXTreeForTesting(); } +BrowserAccessibility* GetRootAccessibilityNode(WebContents* web_contents) { + WebContentsImpl* web_contents_impl = + static_cast<WebContentsImpl*>(web_contents); + BrowserAccessibilityManager* manager = + web_contents_impl->GetRootBrowserAccessibilityManager(); + return manager ? manager->GetRoot() : nullptr; +} + +FindAccessibilityNodeCriteria::FindAccessibilityNodeCriteria() = default; + +FindAccessibilityNodeCriteria::~FindAccessibilityNodeCriteria() = default; + +BrowserAccessibility* FindAccessibilityNode( + WebContents* web_contents, + const FindAccessibilityNodeCriteria& criteria) { + BrowserAccessibility* root = GetRootAccessibilityNode(web_contents); + CHECK(root); + return FindAccessibilityNodeInSubtree(root, criteria); +} + +BrowserAccessibility* FindAccessibilityNodeInSubtree( + BrowserAccessibility* node, + const FindAccessibilityNodeCriteria& criteria) { + if ((!criteria.name || + node->GetStringAttribute(ax::mojom::StringAttribute::kName) == + criteria.name.value()) && + (!criteria.role || node->GetRole() == criteria.role.value())) { + return node; + } + + for (unsigned int i = 0; i < node->PlatformChildCount(); ++i) { + BrowserAccessibility* result = + FindAccessibilityNodeInSubtree(node->PlatformGetChild(i), criteria); + if (result) + return result; + } + return nullptr; +} + bool IsWebContentsBrowserPluginFocused(content::WebContents* web_contents) { WebContentsImpl* web_contents_impl = static_cast<WebContentsImpl*>(web_contents); @@ -2675,8 +2714,7 @@ handle_(nullptr), navigation_paused_(false), current_state_(NavigationState::INITIAL), - desired_state_(NavigationState::STARTED), - weak_factory_(this) {} + desired_state_(NavigationState::STARTED) {} TestNavigationManager::~TestNavigationManager() { if (navigation_paused_)
diff --git a/content/public/test/browser_test_utils.h b/content/public/test/browser_test_utils.h index 8456549..ab10488 100644 --- a/content/public/test/browser_test_utils.h +++ b/content/public/test/browser_test_utils.h
@@ -78,6 +78,7 @@ namespace content { +class BrowserAccessibility; class BrowserContext; struct FrameVisualProperties; class FrameTreeNode; @@ -868,6 +869,23 @@ // Get a snapshot of a web page's accessibility tree. ui::AXTreeUpdate GetAccessibilityTreeSnapshot(WebContents* web_contents); +// Returns the root accessibility node for the given WebContents. +BrowserAccessibility* GetRootAccessibilityNode(WebContents* web_contents); + +// Finds an accessibility node matching the given criteria. +struct FindAccessibilityNodeCriteria { + FindAccessibilityNodeCriteria(); + ~FindAccessibilityNodeCriteria(); + base::Optional<ax::mojom::Role> role; + base::Optional<std::string> name; +}; +BrowserAccessibility* FindAccessibilityNode( + WebContents* web_contents, + const FindAccessibilityNodeCriteria& criteria); +BrowserAccessibility* FindAccessibilityNodeInSubtree( + BrowserAccessibility* node, + const FindAccessibilityNodeCriteria& criteria); + // Find out if the BrowserPlugin for a guest WebContents is focused. Returns // false if the WebContents isn't a guest with a BrowserPlugin. bool IsWebContentsBrowserPluginFocused(content::WebContents* web_contents); @@ -1427,7 +1445,7 @@ base::OnceClosure quit_closure_; base::RunLoop::Type message_loop_type_ = base::RunLoop::Type::kDefault; - base::WeakPtrFactory<TestNavigationManager> weak_factory_; + base::WeakPtrFactory<TestNavigationManager> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TestNavigationManager); };
diff --git a/content/public/test/download_test_observer.cc b/content/public/test/download_test_observer.cc index 6194485..8dd20f3 100644 --- a/content/public/test/download_test_observer.cc +++ b/content/public/test/download_test_observer.cc
@@ -69,9 +69,7 @@ wait_count_(wait_count), finished_downloads_at_construction_(0), waiting_(false), - dangerous_download_action_(dangerous_download_action), - weak_factory_(this) { -} + dangerous_download_action_(dangerous_download_action) {} DownloadTestObserver::~DownloadTestObserver() { for (DownloadSet::iterator it = downloads_observed_.begin();
diff --git a/content/public/test/download_test_observer.h b/content/public/test/download_test_observer.h index a9986ba..c62c164 100644 --- a/content/public/test/download_test_observer.h +++ b/content/public/test/download_test_observer.h
@@ -167,7 +167,7 @@ // Holds the download ids which were dangerous. std::set<uint32_t> dangerous_downloads_seen_; - base::WeakPtrFactory<DownloadTestObserver> weak_factory_; + base::WeakPtrFactory<DownloadTestObserver> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DownloadTestObserver); };
diff --git a/content/browser/accessibility/dump_accessibility_test_helper.cc b/content/public/test/dump_accessibility_test_helper.cc similarity index 98% rename from content/browser/accessibility/dump_accessibility_test_helper.cc rename to content/public/test/dump_accessibility_test_helper.cc index c6eed89..20154c9 100644 --- a/content/browser/accessibility/dump_accessibility_test_helper.cc +++ b/content/public/test/dump_accessibility_test_helper.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/browser/accessibility/dump_accessibility_test_helper.h" +#include "content/public/test/dump_accessibility_test_helper.h" #include "base/command_line.h" #include "base/files/file_util.h"
diff --git a/content/browser/accessibility/dump_accessibility_test_helper.h b/content/public/test/dump_accessibility_test_helper.h similarity index 88% rename from content/browser/accessibility/dump_accessibility_test_helper.h rename to content/public/test/dump_accessibility_test_helper.h index 71cdf98..4db5710c 100644 --- a/content/browser/accessibility/dump_accessibility_test_helper.h +++ b/content/public/test/dump_accessibility_test_helper.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 CONTENT_BROWSER_ACCESSIBILITY_DUMP_ACCESSIBILITY_TEST_HELPER_H_ -#define CONTENT_BROWSER_ACCESSIBILITY_DUMP_ACCESSIBILITY_TEST_HELPER_H_ +#ifndef CONTENT_PUBLIC_TEST_DUMP_ACCESSIBILITY_TEST_HELPER_H_ +#define CONTENT_PUBLIC_TEST_DUMP_ACCESSIBILITY_TEST_HELPER_H_ #include "base/optional.h" @@ -53,4 +53,4 @@ } // namespace content -#endif // CONTENT_BROWSER_ACCESSIBILITY_DUMP_ACCESSIBILITY_TEST_HELPER_H_ +#endif // CONTENT_PUBLIC_TEST_DUMP_ACCESSIBILITY_TEST_HELPER_H_
diff --git a/content/public/test/mock_render_process_host.cc b/content/public/test/mock_render_process_host.cc index 459d855..7f5c70f 100644 --- a/content/public/test/mock_render_process_host.cc +++ b/content/public/test/mock_render_process_host.cc
@@ -63,8 +63,7 @@ BrowserContext::GetServiceInstanceGroupFor(browser_context), base::Token::CreateRandom(), base::Token::CreateRandom()), - url_loader_factory_(nullptr), - weak_ptr_factory_(this) { + url_loader_factory_(nullptr) { // Child process security operations can't be unit tested unless we add // ourselves as an existing child process. ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID(), browser_context);
diff --git a/content/public/test/mock_render_process_host.h b/content/public/test/mock_render_process_host.h index 71120b2..db3f500 100644 --- a/content/public/test/mock_render_process_host.h +++ b/content/public/test/mock_render_process_host.h
@@ -236,7 +236,7 @@ network::mojom::URLLoaderFactory* url_loader_factory_; blink::mojom::CacheStorageRequest cache_storage_request_; blink::mojom::IDBFactoryRequest idb_factory_request_; - base::WeakPtrFactory<MockRenderProcessHost> weak_ptr_factory_; + base::WeakPtrFactory<MockRenderProcessHost> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MockRenderProcessHost); };
diff --git a/content/public/test/simple_url_loader_test_helper.cc b/content/public/test/simple_url_loader_test_helper.cc index bfe331226..d7c2b9a 100644 --- a/content/public/test/simple_url_loader_test_helper.cc +++ b/content/public/test/simple_url_loader_test_helper.cc
@@ -10,8 +10,7 @@ namespace content { -SimpleURLLoaderTestHelper::SimpleURLLoaderTestHelper() - : weak_ptr_factory_(this) {} +SimpleURLLoaderTestHelper::SimpleURLLoaderTestHelper() {} SimpleURLLoaderTestHelper::~SimpleURLLoaderTestHelper() {}
diff --git a/content/public/test/simple_url_loader_test_helper.h b/content/public/test/simple_url_loader_test_helper.h index 35f93bf..acb687c 100644 --- a/content/public/test/simple_url_loader_test_helper.h +++ b/content/public/test/simple_url_loader_test_helper.h
@@ -48,7 +48,7 @@ std::unique_ptr<std::string> response_body_; - base::WeakPtrFactory<SimpleURLLoaderTestHelper> weak_ptr_factory_; + base::WeakPtrFactory<SimpleURLLoaderTestHelper> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SimpleURLLoaderTestHelper); };
diff --git a/content/public/test/test_download_http_response.cc b/content/public/test/test_download_http_response.cc index 2ef6a31..e922ac82 100644 --- a/content/public/test/test_download_http_response.cc +++ b/content/public/test/test_download_http_response.cc
@@ -240,8 +240,7 @@ parameters_(std::move(parameters)), request_(request), transferred_bytes_(0u), - on_response_sent_callback_(on_response_sent_callback), - weak_ptr_factory_(this) { + on_response_sent_callback_(on_response_sent_callback) { DCHECK_GT(parameters.size, 0) << "File size need to be greater than 0."; ParseRequestHeader(); }
diff --git a/content/public/test/test_download_http_response.h b/content/public/test/test_download_http_response.h index 0ab178d..762245e0f 100644 --- a/content/public/test/test_download_http_response.h +++ b/content/public/test/test_download_http_response.h
@@ -324,7 +324,7 @@ // Callback to run when the response is sent. OnResponseSentCallback on_response_sent_callback_; - base::WeakPtrFactory<TestDownloadHttpResponse> weak_ptr_factory_; + base::WeakPtrFactory<TestDownloadHttpResponse> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TestDownloadHttpResponse); };
diff --git a/content/public/test/test_navigation_throttle.cc b/content/public/test/test_navigation_throttle.cc index 7840237..9277210 100644 --- a/content/public/test/test_navigation_throttle.cc +++ b/content/public/test/test_navigation_throttle.cc
@@ -14,7 +14,7 @@ namespace content { TestNavigationThrottle::TestNavigationThrottle(NavigationHandle* handle) - : NavigationThrottle(handle), weak_ptr_factory_(this) {} + : NavigationThrottle(handle) {} TestNavigationThrottle::~TestNavigationThrottle() {}
diff --git a/content/public/test/test_navigation_throttle.h b/content/public/test/test_navigation_throttle.h index d5115248..a3387307 100644 --- a/content/public/test/test_navigation_throttle.h +++ b/content/public/test/test_navigation_throttle.h
@@ -100,7 +100,7 @@ }; MethodProperties method_properties_[NUM_THROTTLE_METHODS]; - base::WeakPtrFactory<TestNavigationThrottle> weak_ptr_factory_; + base::WeakPtrFactory<TestNavigationThrottle> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TestNavigationThrottle); };
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index 654b9fe..f93096e 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -232,8 +232,6 @@ "media/video_capture/video_capture_impl.h", "media/video_capture/video_capture_impl_manager.cc", "media/video_capture/video_capture_impl_manager.h", - "media/web_media_element_source_utils.cc", - "media/web_media_element_source_utils.h", "media/webrtc/audio_codec_factory.cc", "media/webrtc/audio_codec_factory.h", "media/webrtc/media_stream_track_metrics.cc",
diff --git a/content/renderer/accessibility/ax_image_annotator.cc b/content/renderer/accessibility/ax_image_annotator.cc index 7c40469..2f68cce 100644 --- a/content/renderer/accessibility/ax_image_annotator.cc +++ b/content/renderer/accessibility/ax_image_annotator.cc
@@ -32,8 +32,7 @@ image_annotation::mojom::AnnotatorPtr annotator_ptr) : render_accessibility_(render_accessibility), preferred_language_(preferred_language), - annotator_ptr_(std::move(annotator_ptr)), - weak_factory_(this) { + annotator_ptr_(std::move(annotator_ptr)) { DCHECK(render_accessibility_); }
diff --git a/content/renderer/accessibility/ax_image_annotator.h b/content/renderer/accessibility/ax_image_annotator.h index 9626e267..6b1165e 100644 --- a/content/renderer/accessibility/ax_image_annotator.h +++ b/content/renderer/accessibility/ax_image_annotator.h
@@ -130,7 +130,7 @@ std::unordered_map<int, ImageInfo> image_annotations_; // This member needs to be last because it should destructed first. - base::WeakPtrFactory<AXImageAnnotator> weak_factory_; + base::WeakPtrFactory<AXImageAnnotator> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AXImageAnnotator); };
diff --git a/content/renderer/accessibility/render_accessibility_impl.cc b/content/renderer/accessibility/render_accessibility_impl.cc index e5df765e..d91afb65 100644 --- a/content/renderer/accessibility/render_accessibility_impl.cc +++ b/content/renderer/accessibility/render_accessibility_impl.cc
@@ -139,8 +139,7 @@ plugin_tree_source_(nullptr), last_scroll_offset_(gfx::Size()), ack_pending_(false), - reset_token_(0), - weak_factory_(this) { + reset_token_(0) { ack_token_ = g_next_ack_token++; WebView* web_view = render_frame_->GetRenderView()->GetWebView(); WebSettings* settings = web_view->GetSettings();
diff --git a/content/renderer/accessibility/render_accessibility_impl.h b/content/renderer/accessibility/render_accessibility_impl.h index 1056577..2f423252 100644 --- a/content/renderer/accessibility/render_accessibility_impl.h +++ b/content/renderer/accessibility/render_accessibility_impl.h
@@ -240,7 +240,7 @@ bool is_initial_load_processed_ = false; // So we can queue up tasks to be executed later. - base::WeakPtrFactory<RenderAccessibilityImpl> weak_factory_; + base::WeakPtrFactory<RenderAccessibilityImpl> weak_factory_{this}; friend class AXImageAnnotatorTest; DISALLOW_COPY_AND_ASSIGN(RenderAccessibilityImpl);
diff --git a/content/renderer/browser_plugin/browser_plugin.cc b/content/renderer/browser_plugin/browser_plugin.cc index 34769f4..6f66951b 100644 --- a/content/renderer/browser_plugin/browser_plugin.cc +++ b/content/renderer/browser_plugin/browser_plugin.cc
@@ -91,8 +91,7 @@ browser_plugin_instance_id_(browser_plugin::kInstanceIDNone), delegate_(delegate), task_runner_( - render_frame->GetTaskRunner(blink::TaskType::kInternalDefault)), - weak_ptr_factory_(this) { + render_frame->GetTaskRunner(blink::TaskType::kInternalDefault)) { browser_plugin_instance_id_ = BrowserPluginManager::Get()->GetNextInstanceID();
diff --git a/content/renderer/browser_plugin/browser_plugin.h b/content/renderer/browser_plugin/browser_plugin.h index a81d50fb..1f3e2ac 100644 --- a/content/renderer/browser_plugin/browser_plugin.h +++ b/content/renderer/browser_plugin/browser_plugin.h
@@ -246,7 +246,7 @@ // Weak factory used in v8 |MakeWeak| callback, since the v8 callback might // get called after BrowserPlugin has been destroyed. - base::WeakPtrFactory<BrowserPlugin> weak_ptr_factory_; + base::WeakPtrFactory<BrowserPlugin> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BrowserPlugin); };
diff --git a/content/renderer/compositor/layer_tree_view.cc b/content/renderer/compositor/layer_tree_view.cc index 53a515848..27e0040 100644 --- a/content/renderer/compositor/layer_tree_view.cc +++ b/content/renderer/compositor/layer_tree_view.cc
@@ -64,8 +64,7 @@ compositor_thread_(std::move(compositor_thread)), task_graph_runner_(task_graph_runner), web_main_thread_scheduler_(scheduler), - animation_host_(cc::AnimationHost::CreateMainInstance()), - weak_factory_(this) {} + animation_host_(cc::AnimationHost::CreateMainInstance()) {} LayerTreeView::~LayerTreeView() = default;
diff --git a/content/renderer/compositor/layer_tree_view.h b/content/renderer/compositor/layer_tree_view.h index c9d5168..d07faa6f 100644 --- a/content/renderer/compositor/layer_tree_view.h +++ b/content/renderer/compositor/layer_tree_view.h
@@ -219,7 +219,7 @@ std::vector<base::OnceCallback<void(base::TimeTicks)>>>> presentation_callbacks_; - base::WeakPtrFactory<LayerTreeView> weak_factory_; + base::WeakPtrFactory<LayerTreeView> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LayerTreeView); };
diff --git a/content/renderer/history_entry.cc b/content/renderer/history_entry.cc index 7d32118..e4891ab 100644 --- a/content/renderer/history_entry.cc +++ b/content/renderer/history_entry.cc
@@ -84,7 +84,7 @@ children_.clear(); } -HistoryEntry::HistoryEntry() : weak_ptr_factory_(this) { +HistoryEntry::HistoryEntry() { root_.reset( new HistoryNode(weak_ptr_factory_.GetWeakPtr(), WebHistoryItem())); } @@ -92,8 +92,7 @@ HistoryEntry::~HistoryEntry() { } -HistoryEntry::HistoryEntry(const WebHistoryItem& root) - : weak_ptr_factory_(this) { +HistoryEntry::HistoryEntry(const WebHistoryItem& root) { root_.reset(new HistoryNode(weak_ptr_factory_.GetWeakPtr(), root)); }
diff --git a/content/renderer/history_entry.h b/content/renderer/history_entry.h index 1e0678c..9dbfa4cb 100644 --- a/content/renderer/history_entry.h +++ b/content/renderer/history_entry.h
@@ -83,7 +83,7 @@ private: std::unique_ptr<HistoryNode> root_; - base::WeakPtrFactory<HistoryEntry> weak_ptr_factory_; + base::WeakPtrFactory<HistoryEntry> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(HistoryEntry); };
diff --git a/content/renderer/input/frame_input_handler_impl.cc b/content/renderer/input/frame_input_handler_impl.cc index 03e935b..d9d42986 100644 --- a/content/renderer/input/frame_input_handler_impl.cc +++ b/content/renderer/input/frame_input_handler_impl.cc
@@ -27,8 +27,7 @@ render_frame_(render_frame), input_event_queue_( render_frame->GetLocalRootRenderWidget()->GetInputEventQueue()), - main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()), - weak_ptr_factory_(this) { + main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()) { weak_this_ = weak_ptr_factory_.GetWeakPtr(); // If we have created an input event queue move the mojo request over to the // compositor thread.
diff --git a/content/renderer/input/frame_input_handler_impl.h b/content/renderer/input/frame_input_handler_impl.h index 6c91a84..29e4a17 100644 --- a/content/renderer/input/frame_input_handler_impl.h +++ b/content/renderer/input/frame_input_handler_impl.h
@@ -116,7 +116,7 @@ scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; base::WeakPtr<FrameInputHandlerImpl> weak_this_; - base::WeakPtrFactory<FrameInputHandlerImpl> weak_ptr_factory_; + base::WeakPtrFactory<FrameInputHandlerImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FrameInputHandlerImpl); };
diff --git a/content/renderer/input/main_thread_event_queue_unittest.cc b/content/renderer/input/main_thread_event_queue_unittest.cc index ab4b59f5..98077a42 100644 --- a/content/renderer/input/main_thread_event_queue_unittest.cc +++ b/content/renderer/input/main_thread_event_queue_unittest.cc
@@ -111,8 +111,7 @@ class HandledEventCallbackTracker { public: - HandledEventCallbackTracker() - : handling_event_(false), weak_ptr_factory_(this) { + HandledEventCallbackTracker() : handling_event_(false) { weak_this_ = weak_ptr_factory_.GetWeakPtr(); } @@ -144,7 +143,7 @@ private: std::vector<ReceivedCallback> callbacks_received_; base::WeakPtr<HandledEventCallbackTracker> weak_this_; - base::WeakPtrFactory<HandledEventCallbackTracker> weak_ptr_factory_; + base::WeakPtrFactory<HandledEventCallbackTracker> weak_ptr_factory_{this}; }; class MainThreadEventQueueTest : public testing::Test,
diff --git a/content/renderer/loader/code_cache_loader_impl.cc b/content/renderer/loader/code_cache_loader_impl.cc index 2a79d65a..9c639fd 100644 --- a/content/renderer/loader/code_cache_loader_impl.cc +++ b/content/renderer/loader/code_cache_loader_impl.cc
@@ -13,8 +13,7 @@ CodeCacheLoaderImpl::CodeCacheLoaderImpl( base::WaitableEvent* terminate_sync_load_event) - : terminate_sync_load_event_(terminate_sync_load_event), - weak_ptr_factory_(this) {} + : terminate_sync_load_event_(terminate_sync_load_event) {} CodeCacheLoaderImpl::~CodeCacheLoaderImpl() = default;
diff --git a/content/renderer/loader/code_cache_loader_impl.h b/content/renderer/loader/code_cache_loader_impl.h index 7fd7946..99b89f8 100644 --- a/content/renderer/loader/code_cache_loader_impl.h +++ b/content/renderer/loader/code_cache_loader_impl.h
@@ -57,7 +57,7 @@ bool terminated_ = false; base::WaitableEventWatcher terminate_watcher_; base::WaitableEvent* terminate_sync_load_event_ = nullptr; - base::WeakPtrFactory<CodeCacheLoaderImpl> weak_ptr_factory_; + base::WeakPtrFactory<CodeCacheLoaderImpl> weak_ptr_factory_{this}; }; } // namespace content
diff --git a/content/renderer/loader/navigation_body_loader.cc b/content/renderer/loader/navigation_body_loader.cc index 5cbaa35..ee04788 100644 --- a/content/renderer/loader/navigation_body_loader.cc +++ b/content/renderer/loader/navigation_body_loader.cc
@@ -97,8 +97,7 @@ url_loader_client_binding_(this), handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, - task_runner_), - weak_factory_(this) {} + task_runner_) {} NavigationBodyLoader::~NavigationBodyLoader() { if (!has_received_completion_ || !has_seen_end_of_data_) {
diff --git a/content/renderer/loader/navigation_body_loader.h b/content/renderer/loader/navigation_body_loader.h index 4b17121..b313efb 100644 --- a/content/renderer/loader/navigation_body_loader.h +++ b/content/renderer/loader/navigation_body_loader.h
@@ -171,7 +171,7 @@ // from iniside BodyDataReceived client notification. bool is_in_on_readable_ = false; - base::WeakPtrFactory<NavigationBodyLoader> weak_factory_; + base::WeakPtrFactory<NavigationBodyLoader> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(NavigationBodyLoader); };
diff --git a/content/renderer/loader/resource_dispatcher.cc b/content/renderer/loader/resource_dispatcher.cc index a4f6432..03bf4a8b 100644 --- a/content/renderer/loader/resource_dispatcher.cc +++ b/content/renderer/loader/resource_dispatcher.cc
@@ -116,8 +116,7 @@ return kInitialRequestID + sequence.GetNext(); } -ResourceDispatcher::ResourceDispatcher() - : delegate_(nullptr), weak_factory_(this) {} +ResourceDispatcher::ResourceDispatcher() : delegate_(nullptr) {} ResourceDispatcher::~ResourceDispatcher() { }
diff --git a/content/renderer/loader/resource_dispatcher.h b/content/renderer/loader/resource_dispatcher.h index f700271..9b75fa1 100644 --- a/content/renderer/loader/resource_dispatcher.h +++ b/content/renderer/loader/resource_dispatcher.h
@@ -247,7 +247,7 @@ base::WaitableEvent* terminate_sync_load_event_ = nullptr; - base::WeakPtrFactory<ResourceDispatcher> weak_factory_; + base::WeakPtrFactory<ResourceDispatcher> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ResourceDispatcher); };
diff --git a/content/renderer/loader/url_loader_client_impl.cc b/content/renderer/loader/url_loader_client_impl.cc index 9efa4a31..c50c929 100644 --- a/content/renderer/loader/url_loader_client_impl.cc +++ b/content/renderer/loader/url_loader_client_impl.cc
@@ -152,8 +152,7 @@ task_runner_(std::move(task_runner)), bypass_redirect_checks_(bypass_redirect_checks), last_loaded_url_(request_url), - url_loader_client_binding_(this), - weak_factory_(this) {} + url_loader_client_binding_(this) {} URLLoaderClientImpl::~URLLoaderClientImpl() = default;
diff --git a/content/renderer/loader/url_loader_client_impl.h b/content/renderer/loader/url_loader_client_impl.h index 7580849..d6113cbc 100644 --- a/content/renderer/loader/url_loader_client_impl.h +++ b/content/renderer/loader/url_loader_client_impl.h
@@ -102,7 +102,7 @@ network::mojom::URLLoaderPtr url_loader_; mojo::Binding<network::mojom::URLLoaderClient> url_loader_client_binding_; - base::WeakPtrFactory<URLLoaderClientImpl> weak_factory_; + base::WeakPtrFactory<URLLoaderClientImpl> weak_factory_{this}; }; } // namespace content
diff --git a/content/renderer/loader/web_url_loader_impl_unittest.cc b/content/renderer/loader/web_url_loader_impl_unittest.cc index 566d454..fcf909f 100644 --- a/content/renderer/loader/web_url_loader_impl_unittest.cc +++ b/content/renderer/loader/web_url_loader_impl_unittest.cc
@@ -305,10 +305,7 @@ ~WebURLLoaderImplTest() override {} void DoStartAsyncRequest() { - blink::WebURLRequest request{GURL(kTestURL)}; - request.SetRequestContext(blink::mojom::RequestContextType::INTERNAL); - client()->loader()->LoadAsynchronously(request, client()); - ASSERT_TRUE(peer()); + DoStartAsyncRequestWithPriority(blink::WebURLRequest::Priority::kVeryLow); } void DoStartAsyncRequestWithPriority( @@ -468,6 +465,7 @@ const std::string kMimeType = "application/javascript"; blink::WebURLRequest request(kRequestURL); request.SetRequestContext(blink::mojom::RequestContextType::SCRIPT); + request.SetPriority(blink::WebURLRequest::Priority::kVeryLow); std::unique_ptr<NavigationResponseOverrideParameters> response_override( new NavigationResponseOverrideParameters()); response_override->response_head.mime_type = kMimeType; @@ -610,6 +608,7 @@ const GURL url(kTestURL); blink::WebURLRequest request(url); request.SetRequestContext(blink::mojom::RequestContextType::INTERNAL); + request.SetPriority(blink::WebURLRequest::Priority::kHighest); // Prepare a mock response SyncLoadResponse sync_load_response;
diff --git a/content/renderer/loader/web_worker_fetch_context_impl.cc b/content/renderer/loader/web_worker_fetch_context_impl.cc index 2da6fee..cf853c7 100644 --- a/content/renderer/loader/web_worker_fetch_context_impl.cc +++ b/content/renderer/loader/web_worker_fetch_context_impl.cc
@@ -78,8 +78,7 @@ Factory(base::WeakPtr<ResourceDispatcher> resource_dispatcher, scoped_refptr<network::SharedURLLoaderFactory> loader_factory) : resource_dispatcher_(std::move(resource_dispatcher)), - loader_factory_(std::move(loader_factory)), - weak_ptr_factory_(this) {} + loader_factory_(std::move(loader_factory)) {} ~Factory() override = default; std::unique_ptr<blink::WebURLLoader> CreateURLLoader( @@ -146,7 +145,7 @@ base::WeakPtr<ResourceDispatcher> resource_dispatcher_; scoped_refptr<network::SharedURLLoaderFactory> loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> service_worker_loader_factory_; - base::WeakPtrFactory<Factory> weak_ptr_factory_; + base::WeakPtrFactory<Factory> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(Factory); };
diff --git a/content/renderer/loader/web_worker_fetch_context_impl.h b/content/renderer/loader/web_worker_fetch_context_impl.h index a502db03..fd2a90cf 100644 --- a/content/renderer/loader/web_worker_fetch_context_impl.h +++ b/content/renderer/loader/web_worker_fetch_context_impl.h
@@ -9,6 +9,7 @@ #include <string> #include "base/synchronization/waitable_event.h" +#include "content/common/content_export.h" #include "content/common/service_worker/service_worker_types.h" #include "ipc/ipc_message.h" #include "mojo/public/cpp/bindings/binding.h"
diff --git a/content/renderer/media/audio/mojo_audio_input_ipc.cc b/content/renderer/media/audio/mojo_audio_input_ipc.cc index 87a4892..c616d11 100644 --- a/content/renderer/media/audio/mojo_audio_input_ipc.cc +++ b/content/renderer/media/audio/mojo_audio_input_ipc.cc
@@ -23,8 +23,7 @@ stream_creator_(std::move(stream_creator)), stream_associator_(std::move(stream_associator)), stream_client_binding_(this), - factory_client_binding_(this), - weak_factory_(this) { + factory_client_binding_(this) { DETACH_FROM_SEQUENCE(sequence_checker_); DCHECK(stream_creator_); DCHECK(stream_associator_);
diff --git a/content/renderer/media/audio/mojo_audio_input_ipc.h b/content/renderer/media/audio/mojo_audio_input_ipc.h index 8a3bc33..360f1a0 100644 --- a/content/renderer/media/audio/mojo_audio_input_ipc.h +++ b/content/renderer/media/audio/mojo_audio_input_ipc.h
@@ -96,7 +96,7 @@ base::TimeTicks stream_creation_start_time_; - base::WeakPtrFactory<MojoAudioInputIPC> weak_factory_; + base::WeakPtrFactory<MojoAudioInputIPC> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MojoAudioInputIPC); };
diff --git a/content/renderer/media/audio/mojo_audio_output_ipc.cc b/content/renderer/media/audio/mojo_audio_output_ipc.cc index 03666b9..6a3fa012 100644 --- a/content/renderer/media/audio/mojo_audio_output_ipc.cc +++ b/content/renderer/media/audio/mojo_audio_output_ipc.cc
@@ -28,8 +28,7 @@ scoped_refptr<base::SingleThreadTaskRunner> io_task_runner) : factory_accessor_(std::move(factory_accessor)), binding_(this), - io_task_runner_(std::move(io_task_runner)), - weak_factory_(this) {} + io_task_runner_(std::move(io_task_runner)) {} MojoAudioOutputIPC::~MojoAudioOutputIPC() { DCHECK(!AuthorizationRequested() && !StreamCreationRequested())
diff --git a/content/renderer/media/audio/mojo_audio_output_ipc.h b/content/renderer/media/audio/mojo_audio_output_ipc.h index eaabab4..b4ea74d 100644 --- a/content/renderer/media/audio/mojo_audio_output_ipc.h +++ b/content/renderer/media/audio/mojo_audio_output_ipc.h
@@ -101,7 +101,7 @@ // To make sure we don't send an "authorization completed" callback for a // stream after it's closed, we use this weak factory. - base::WeakPtrFactory<MojoAudioOutputIPC> weak_factory_; + base::WeakPtrFactory<MojoAudioOutputIPC> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MojoAudioOutputIPC); };
diff --git a/content/renderer/media/media_factory.cc b/content/renderer/media/media_factory.cc index 4059a7c..e1af2918 100644 --- a/content/renderer/media/media_factory.cc +++ b/content/renderer/media/media_factory.cc
@@ -23,7 +23,6 @@ #include "content/renderer/media/renderer_webmediaplayer_delegate.h" #include "content/renderer/media/stream/media_stream_renderer_factory_impl.h" #include "content/renderer/media/stream/webmediaplayer_ms.h" -#include "content/renderer/media/web_media_element_source_utils.h" #include "content/renderer/render_frame_impl.h" #include "content/renderer/render_thread_impl.h" #include "content/renderer/render_view_impl.h" @@ -45,6 +44,7 @@ #include "services/service_manager/public/cpp/connect.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "services/viz/public/cpp/gpu/context_provider_command_buffer.h" +#include "third_party/blink/public/platform/modules/mediastream/web_media_element_source_utils.h" #include "third_party/blink/public/platform/web_surface_layer_bridge.h" #include "third_party/blink/public/platform/web_video_frame_submitter.h" #include "third_party/blink/public/web/blink.h" @@ -270,7 +270,7 @@ blink::WebSecurityOrigin security_origin = render_frame_->GetWebFrame()->GetSecurityOrigin(); blink::WebMediaStream web_stream = - GetWebMediaStreamFromWebMediaPlayerSource(source); + blink::GetWebMediaStreamFromWebMediaPlayerSource(source); if (!web_stream.IsNull()) return CreateWebMediaPlayerForMediaStream( client, sink_id, security_origin, web_frame, layer_tree_view, settings);
diff --git a/content/renderer/media/media_interface_factory.cc b/content/renderer/media/media_interface_factory.cc index 50b4c96..f99a4c4 100644 --- a/content/renderer/media/media_interface_factory.cc +++ b/content/renderer/media/media_interface_factory.cc
@@ -17,7 +17,7 @@ MediaInterfaceFactory::MediaInterfaceFactory( service_manager::InterfaceProvider* remote_interfaces) - : remote_interfaces_(remote_interfaces), weak_factory_(this) { + : remote_interfaces_(remote_interfaces) { task_runner_ = base::ThreadTaskRunnerHandle::Get(); weak_this_ = weak_factory_.GetWeakPtr(); }
diff --git a/content/renderer/media/media_interface_factory.h b/content/renderer/media/media_interface_factory.h index b22aad68..d0b1136 100644 --- a/content/renderer/media/media_interface_factory.h +++ b/content/renderer/media/media_interface_factory.h
@@ -69,7 +69,7 @@ scoped_refptr<base::SingleThreadTaskRunner> task_runner_; base::WeakPtr<MediaInterfaceFactory> weak_this_; - base::WeakPtrFactory<MediaInterfaceFactory> weak_factory_; + base::WeakPtrFactory<MediaInterfaceFactory> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MediaInterfaceFactory); };
diff --git a/content/renderer/media/media_permission_dispatcher.cc b/content/renderer/media/media_permission_dispatcher.cc index d971db6a..73bcdb5 100644 --- a/content/renderer/media/media_permission_dispatcher.cc +++ b/content/renderer/media/media_permission_dispatcher.cc
@@ -46,8 +46,7 @@ RenderFrameImpl* render_frame) : task_runner_(base::ThreadTaskRunnerHandle::Get()), next_request_id_(0), - render_frame_(render_frame), - weak_factory_(this) { + render_frame_(render_frame) { DCHECK(render_frame_); weak_ptr_ = weak_factory_.GetWeakPtr(); }
diff --git a/content/renderer/media/media_permission_dispatcher.h b/content/renderer/media/media_permission_dispatcher.h index a06b6c5..ed1a490 100644 --- a/content/renderer/media/media_permission_dispatcher.h +++ b/content/renderer/media/media_permission_dispatcher.h
@@ -73,7 +73,7 @@ // Used to safely post MediaPermission calls for execution on |task_runner_|. base::WeakPtr<MediaPermissionDispatcher> weak_ptr_; - base::WeakPtrFactory<MediaPermissionDispatcher> weak_factory_; + base::WeakPtrFactory<MediaPermissionDispatcher> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MediaPermissionDispatcher); };
diff --git a/content/renderer/media/render_media_log.cc b/content/renderer/media/render_media_log.cc index 51f4f58a..a47d0f1 100644 --- a/content/renderer/media/render_media_log.cc +++ b/content/renderer/media/render_media_log.cc
@@ -43,8 +43,7 @@ task_runner_(std::move(task_runner)), tick_clock_(base::DefaultTickClock::GetInstance()), last_ipc_send_time_(tick_clock_->NowTicks()), - ipc_send_pending_(false), - weak_factory_(this) { + ipc_send_pending_(false) { DCHECK(RenderThread::Get()) << "RenderMediaLog must be constructed on the render thread"; // Pre-bind the WeakPtr on the right thread since we'll receive calls from
diff --git a/content/renderer/media/render_media_log.h b/content/renderer/media/render_media_log.h index e65d6fe..87d24161 100644 --- a/content/renderer/media/render_media_log.h +++ b/content/renderer/media/render_media_log.h
@@ -87,7 +87,7 @@ std::unique_ptr<media::MediaLogEvent> last_pipeline_error_; base::WeakPtr<RenderMediaLog> weak_this_; - base::WeakPtrFactory<RenderMediaLog> weak_factory_; + base::WeakPtrFactory<RenderMediaLog> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderMediaLog); };
diff --git a/content/renderer/media/renderer_webmediaplayer_delegate.h b/content/renderer/media/renderer_webmediaplayer_delegate.h index cc51e85..0084ef2 100644 --- a/content/renderer/media/renderer_webmediaplayer_delegate.h +++ b/content/renderer/media/renderer_webmediaplayer_delegate.h
@@ -18,7 +18,7 @@ #include "base/timer/timer.h" #include "content/common/content_export.h" #include "content/public/renderer/render_frame_observer.h" -#include "media/blink/webmediaplayer_delegate.h" +#include "third_party/blink/public/platform/media/webmediaplayer_delegate.h" #if defined(OS_ANDROID) #include "base/time/time.h" @@ -36,7 +36,7 @@ // the MediaPlayerDelegateHost. class CONTENT_EXPORT RendererWebMediaPlayerDelegate : public content::RenderFrameObserver, - public WebMediaPlayerDelegate, + public blink::WebMediaPlayerDelegate, public base::SupportsWeakPtr<RendererWebMediaPlayerDelegate> { public: explicit RendererWebMediaPlayerDelegate(content::RenderFrame* render_frame); @@ -45,7 +45,7 @@ // Returns true if this RenderFrame has ever seen media playback before. bool has_played_media() const { return has_played_media_; } - // WebMediaPlayerDelegate implementation. + // blink::WebMediaPlayerDelegate implementation. bool IsFrameHidden() override; bool IsFrameClosed() override; int AddObserver(Observer* observer) override;
diff --git a/content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc b/content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc index 64a7efd..3edef35 100644 --- a/content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc +++ b/content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc
@@ -32,7 +32,7 @@ } class MockWebMediaPlayerDelegateObserver - : public WebMediaPlayerDelegate::Observer { + : public blink::WebMediaPlayerDelegate::Observer { public: MockWebMediaPlayerDelegateObserver() {} ~MockWebMediaPlayerDelegateObserver() {}
diff --git a/content/renderer/media/stream/apply_constraints_processor.cc b/content/renderer/media/stream/apply_constraints_processor.cc index 2692c91..3083c6b 100644 --- a/content/renderer/media/stream/apply_constraints_processor.cc +++ b/content/renderer/media/stream/apply_constraints_processor.cc
@@ -41,8 +41,7 @@ MediaDevicesDispatcherCallback media_devices_dispatcher_cb, scoped_refptr<base::SingleThreadTaskRunner> task_runner) : media_devices_dispatcher_cb_(std::move(media_devices_dispatcher_cb)), - task_runner_(std::move(task_runner)), - weak_factory_(this) {} + task_runner_(std::move(task_runner)) {} ApplyConstraintsProcessor::~ApplyConstraintsProcessor() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/content/renderer/media/stream/apply_constraints_processor.h b/content/renderer/media/stream/apply_constraints_processor.h index ce34c656..dd86d05 100644 --- a/content/renderer/media/stream/apply_constraints_processor.h +++ b/content/renderer/media/stream/apply_constraints_processor.h
@@ -89,7 +89,7 @@ const scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - base::WeakPtrFactory<ApplyConstraintsProcessor> weak_factory_; + base::WeakPtrFactory<ApplyConstraintsProcessor> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ApplyConstraintsProcessor); };
diff --git a/content/renderer/media/stream/audio_service_audio_processor_proxy.cc b/content/renderer/media/stream/audio_service_audio_processor_proxy.cc index a17ed83..3c69030a 100644 --- a/content/renderer/media/stream/audio_service_audio_processor_proxy.cc +++ b/content/renderer/media/stream/audio_service_audio_processor_proxy.cc
@@ -30,8 +30,7 @@ AudioServiceAudioProcessorProxy::AudioServiceAudioProcessorProxy( scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner) : main_thread_runner_(std::move(main_thread_task_runner)), - target_stats_interval_(kMaxStatsInterval), - weak_ptr_factory_(this) { + target_stats_interval_(kMaxStatsInterval) { DCHECK(main_thread_runner_->BelongsToCurrentThread()); }
diff --git a/content/renderer/media/stream/audio_service_audio_processor_proxy.h b/content/renderer/media/stream/audio_service_audio_processor_proxy.h index 2e2b5ac..9798385 100644 --- a/content/renderer/media/stream/audio_service_audio_processor_proxy.h +++ b/content/renderer/media/stream/audio_service_audio_processor_proxy.h
@@ -79,7 +79,7 @@ // Communication with browser for AEC dump. std::unique_ptr<AecDumpAgentImpl> aec_dump_agent_impl_; - base::WeakPtrFactory<AudioServiceAudioProcessorProxy> weak_ptr_factory_; + base::WeakPtrFactory<AudioServiceAudioProcessorProxy> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AudioServiceAudioProcessorProxy); };
diff --git a/content/renderer/media/stream/media_stream_audio_processor.cc b/content/renderer/media/stream/media_stream_audio_processor.cc index 57d4738..437d207 100644 --- a/content/renderer/media/stream/media_stream_audio_processor.cc +++ b/content/renderer/media/stream/media_stream_audio_processor.cc
@@ -457,7 +457,6 @@ int audio_delay_milliseconds) { DCHECK_CALLED_ON_VALID_THREAD(render_thread_checker_); DCHECK_GE(audio_bus->channels(), 1); - DCHECK_LE(audio_bus->channels(), 2); int frames_per_10_ms = sample_rate / 100; if (audio_bus->frames() != frames_per_10_ms) { if (unsupported_buffer_size_log_count_ < 10) { @@ -474,15 +473,22 @@ std::numeric_limits<base::subtle::Atomic32>::max()); base::subtle::Release_Store(&render_delay_ms_, audio_delay_milliseconds); - std::vector<const float*> channel_ptrs(audio_bus->channels()); - for (int i = 0; i < audio_bus->channels(); ++i) + // Limit the number of channels to two (stereo) now when multi-channel audio + // sources are supported. We still want to prevent the AEC from "seeing" the + // full signal. + // TODO(crbug.com/982276): process all channels when multi-channel AEC is + // supported. + int channels = std::min(2, audio_bus->channels()); + + std::vector<const float*> channel_ptrs(channels); + for (int i = 0; i < channels; ++i) channel_ptrs[i] = audio_bus->channel(i); // TODO(ajm): Should AnalyzeReverseStream() account for the // |audio_delay_milliseconds|? const int apm_error = audio_processing_->AnalyzeReverseStream( channel_ptrs.data(), audio_bus->frames(), sample_rate, - ChannelsToLayout(audio_bus->channels())); + ChannelsToLayout(channels)); if (apm_error != webrtc::AudioProcessing::kNoError && apm_playout_error_code_log_count_ < 10) { LOG(ERROR) << "MSAP::OnPlayoutData: AnalyzeReverseStream error="
diff --git a/content/renderer/media/stream/processed_local_audio_source.cc b/content/renderer/media/stream/processed_local_audio_source.cc index cddb873..56a74de 100644 --- a/content/renderer/media/stream/processed_local_audio_source.cc +++ b/content/renderer/media/stream/processed_local_audio_source.cc
@@ -104,8 +104,7 @@ audio_processing_properties_(audio_processing_properties), started_callback_(std::move(started_callback)), volume_(0), - allow_invalid_render_frame_id_for_testing_(false), - weak_factory_(this) { + allow_invalid_render_frame_id_for_testing_(false) { DCHECK(pc_factory_); DVLOG(1) << "ProcessedLocalAudioSource::ProcessedLocalAudioSource()"; SetDevice(device);
diff --git a/content/renderer/media/stream/processed_local_audio_source.h b/content/renderer/media/stream/processed_local_audio_source.h index 8757b7a..09ba7de1 100644 --- a/content/renderer/media/stream/processed_local_audio_source.h +++ b/content/renderer/media/stream/processed_local_audio_source.h
@@ -157,7 +157,7 @@ bool allow_invalid_render_frame_id_for_testing_; // Provides weak pointers for tasks posted by this instance. - base::WeakPtrFactory<ProcessedLocalAudioSource> weak_factory_; + base::WeakPtrFactory<ProcessedLocalAudioSource> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ProcessedLocalAudioSource); };
diff --git a/content/renderer/media/stream/user_media_client_impl.cc b/content/renderer/media/stream/user_media_client_impl.cc index 8a5b28a..699d197 100644 --- a/content/renderer/media/stream/user_media_client_impl.cc +++ b/content/renderer/media/stream/user_media_client_impl.cc
@@ -109,8 +109,7 @@ apply_constraints_processor_(new ApplyConstraintsProcessor( base::BindRepeating(&UserMediaClientImpl::GetMediaDevicesDispatcher, base::Unretained(this)), - std::move(task_runner))), - weak_factory_(this) {} + std::move(task_runner))) {} // base::Unretained(this) is safe here because |this| owns // |user_media_processor_|.
diff --git a/content/renderer/media/stream/user_media_client_impl.h b/content/renderer/media/stream/user_media_client_impl.h index 7c170a2..fb2be4cd 100644 --- a/content/renderer/media/stream/user_media_client_impl.h +++ b/content/renderer/media/stream/user_media_client_impl.h
@@ -131,7 +131,7 @@ // Note: This member must be the last to ensure all outstanding weak pointers // are invalidated first. - base::WeakPtrFactory<UserMediaClientImpl> weak_factory_; + base::WeakPtrFactory<UserMediaClientImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(UserMediaClientImpl); };
diff --git a/content/renderer/media/stream/user_media_processor.cc b/content/renderer/media/stream/user_media_processor.cc index ff76e6f..aa2a173 100644 --- a/content/renderer/media/stream/user_media_processor.cc +++ b/content/renderer/media/stream/user_media_processor.cc
@@ -454,8 +454,7 @@ media_stream_device_observer_(std::move(media_stream_device_observer)), media_devices_dispatcher_cb_(std::move(media_devices_dispatcher_cb)), render_frame_(render_frame), - task_runner_(std::move(task_runner)), - weak_factory_(this) { + task_runner_(std::move(task_runner)) { DCHECK(dependency_factory_); DCHECK(media_stream_device_observer_.get()); }
diff --git a/content/renderer/media/stream/user_media_processor.h b/content/renderer/media/stream/user_media_processor.h index 1eeb2f8..50687f8 100644 --- a/content/renderer/media/stream/user_media_processor.h +++ b/content/renderer/media/stream/user_media_processor.h
@@ -311,7 +311,7 @@ // Note: This member must be the last to ensure all outstanding weak pointers // are invalidated first. - base::WeakPtrFactory<UserMediaProcessor> weak_factory_; + base::WeakPtrFactory<UserMediaProcessor> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(UserMediaProcessor); };
diff --git a/content/renderer/media/stream/webmediaplayer_ms.cc b/content/renderer/media/stream/webmediaplayer_ms.cc index a148b70..0f8128c9 100644 --- a/content/renderer/media/stream/webmediaplayer_ms.cc +++ b/content/renderer/media/stream/webmediaplayer_ms.cc
@@ -16,7 +16,6 @@ #include "cc/layers/video_layer.h" #include "content/child/child_process.h" #include "content/renderer/media/stream/webmediaplayer_ms_compositor.h" -#include "content/renderer/media/web_media_element_source_utils.h" #include "content/renderer/render_frame_impl.h" #include "content/renderer/render_thread_impl.h" #include "media/base/bind_to_current_loop.h" @@ -29,6 +28,7 @@ #include "media/video/gpu_memory_buffer_video_frame_pool.h" #include "services/viz/public/cpp/gpu/context_provider_command_buffer.h" #include "third_party/blink/public/platform/modules/mediastream/media_stream_audio_track.h" +#include "third_party/blink/public/platform/modules/mediastream/web_media_element_source_utils.h" #include "third_party/blink/public/platform/modules/mediastream/web_media_stream_audio_renderer.h" #include "third_party/blink/public/platform/modules/mediastream/web_media_stream_renderer_factory.h" #include "third_party/blink/public/platform/modules/mediastream/web_media_stream_video_renderer.h" @@ -85,9 +85,7 @@ : main_task_runner_(base::ThreadTaskRunnerHandle::Get()), player_(player), enqueue_frame_cb_(enqueue_frame_cb), - media_task_runner_(media_task_runner), - weak_factory_for_pool_(this), - weak_factory_(this) { + media_task_runner_(media_task_runner) { DETACH_FROM_THREAD(io_thread_checker_); if (gpu_factories && gpu_factories->ShouldUseGpuMemoryBuffersForVideoFrames( @@ -220,8 +218,8 @@ // Used for DCHECKs to ensure method calls are executed on the correct thread. THREAD_CHECKER(io_thread_checker_); - base::WeakPtrFactory<FrameDeliverer> weak_factory_for_pool_; - base::WeakPtrFactory<FrameDeliverer> weak_factory_; + base::WeakPtrFactory<FrameDeliverer> weak_factory_for_pool_{this}; + base::WeakPtrFactory<FrameDeliverer> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FrameDeliverer); }; @@ -229,7 +227,7 @@ WebMediaPlayerMS::WebMediaPlayerMS( blink::WebLocalFrame* frame, blink::WebMediaPlayerClient* client, - media::WebMediaPlayerDelegate* delegate, + blink::WebMediaPlayerDelegate* delegate, std::unique_ptr<media::MediaLog> media_log, std::unique_ptr<blink::WebMediaStreamRendererFactory> factory, scoped_refptr<base::SingleThreadTaskRunner> main_render_task_runner, @@ -265,8 +263,7 @@ should_play_upon_shown_(false), create_bridge_callback_(std::move(create_bridge_callback)), submitter_(std::move(submitter)), - surface_layer_mode_(surface_layer_mode), - weak_factory_(this) { + surface_layer_mode_(surface_layer_mode) { DVLOG(1) << __func__; DCHECK(client); DCHECK(delegate_); @@ -321,7 +318,7 @@ // TODO(acolwell): Change this to DCHECK_EQ(load_type, LoadTypeMediaStream) // once Blink-side changes land. DCHECK_NE(load_type, kLoadTypeMediaSource); - web_stream_ = GetWebMediaStreamFromWebMediaPlayerSource(source); + web_stream_ = blink::GetWebMediaStreamFromWebMediaPlayerSource(source); if (!web_stream_.IsNull()) web_stream_.AddObserver(this); @@ -739,7 +736,7 @@ } blink::WebMediaPlayer::NetworkState WebMediaPlayerMS::GetNetworkState() const { - DVLOG(1) << __func__ << ", state:" << network_state_; + DVLOG(2) << __func__ << ", state:" << network_state_; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return network_state_; }
diff --git a/content/renderer/media/stream/webmediaplayer_ms.h b/content/renderer/media/stream/webmediaplayer_ms.h index d46ad60e..0c7c7e2 100644 --- a/content/renderer/media/stream/webmediaplayer_ms.h +++ b/content/renderer/media/stream/webmediaplayer_ms.h
@@ -15,9 +15,9 @@ #include "base/threading/thread_checker.h" #include "build/build_config.h" #include "content/common/content_export.h" -#include "media/blink/webmediaplayer_delegate.h" #include "media/renderers/paint_canvas_video_renderer.h" #include "media/video/gpu_video_accelerator_factories.h" +#include "third_party/blink/public/platform/media/webmediaplayer_delegate.h" #include "third_party/blink/public/platform/web_media_player.h" #include "third_party/blink/public/platform/web_media_stream.h" #include "third_party/blink/public/platform/web_surface_layer_bridge.h" @@ -71,7 +71,7 @@ class CONTENT_EXPORT WebMediaPlayerMS : public blink::WebMediaStreamObserver, public blink::WebMediaPlayer, - public media::WebMediaPlayerDelegate::Observer, + public blink::WebMediaPlayerDelegate::Observer, public blink::WebSurfaceLayerBridgeObserver { public: // Construct a WebMediaPlayerMS with reference to the client, and @@ -80,7 +80,7 @@ WebMediaPlayerMS( blink::WebLocalFrame* frame, blink::WebMediaPlayerClient* client, - media::WebMediaPlayerDelegate* delegate, + blink::WebMediaPlayerDelegate* delegate, std::unique_ptr<media::MediaLog> media_log, std::unique_ptr<blink::WebMediaStreamRendererFactory> factory, scoped_refptr<base::SingleThreadTaskRunner> main_render_task_runner, @@ -169,7 +169,7 @@ bool HasAvailableVideoFrame() const override; - // WebMediaPlayerDelegate::Observer implementation. + // blink::WebMediaPlayerDelegate::Observer implementation. void OnFrameHidden() override; void OnFrameClosed() override; void OnFrameShown() override; @@ -282,14 +282,15 @@ // WebMediaPlayer notifies the |delegate_| of playback state changes using // |delegate_id_|; an id provided after registering with the delegate. The // WebMediaPlayer may also receive directives (play, pause) from the delegate - // via the WebMediaPlayerDelegate::Observer interface after registration. + // via the blink::WebMediaPlayerDelegate::Observer interface after + // registration. // // NOTE: HTMLMediaElement is a Blink::PausableObject, and will receive a // call to contextDestroyed() when Blink::Document::shutdown() is called. // Document::shutdown() is called before the frame detaches (and before the // frame is destroyed). RenderFrameImpl owns of |delegate_|, and is guaranteed // to outlive |this|. It is therefore safe use a raw pointer directly. - media::WebMediaPlayerDelegate* delegate_; + blink::WebMediaPlayerDelegate* delegate_; int delegate_id_; // Inner class used for transfering frames on compositor thread to @@ -329,8 +330,9 @@ // The last volume received by setVolume() and the last volume multiplier from // OnVolumeMultiplierUpdate(). The multiplier is typical 1.0, but may be less - // if the WebMediaPlayerDelegate has requested a volume reduction (ducking) - // for a transient sound. Playout volume is derived by volume * multiplier. + // if the blink::WebMediaPlayerDelegate has requested a volume reduction + // (ducking) for a transient sound. Playout volume is derived by volume * + // multiplier. double volume_; double volume_multiplier_; @@ -360,7 +362,7 @@ bool has_first_frame_ = false; base::WeakPtr<WebMediaPlayerMS> weak_this_; - base::WeakPtrFactory<WebMediaPlayerMS> weak_factory_; + base::WeakPtrFactory<WebMediaPlayerMS> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerMS); };
diff --git a/content/renderer/media/stream/webmediaplayer_ms_compositor.cc b/content/renderer/media/stream/webmediaplayer_ms_compositor.cc index aa9b457f..dc1781b 100644 --- a/content/renderer/media/stream/webmediaplayer_ms_compositor.cc +++ b/content/renderer/media/stream/webmediaplayer_ms_compositor.cc
@@ -148,8 +148,7 @@ total_frame_count_(0), dropped_frame_count_(0), stopped_(true), - render_started_(!stopped_), - weak_ptr_factory_(this) { + render_started_(!stopped_) { if (surface_layer_mode != blink::WebMediaPlayer::SurfaceLayerMode::kNever) { submitter_ = std::move(submitter);
diff --git a/content/renderer/media/stream/webmediaplayer_ms_compositor.h b/content/renderer/media/stream/webmediaplayer_ms_compositor.h index 46bb5a0..f4bdacf8 100644 --- a/content/renderer/media/stream/webmediaplayer_ms_compositor.h +++ b/content/renderer/media/stream/webmediaplayer_ms_compositor.h
@@ -224,7 +224,7 @@ // |dropped_frame_count_|, and |render_started_|. base::Lock current_frame_lock_; - base::WeakPtrFactory<WebMediaPlayerMSCompositor> weak_ptr_factory_; + base::WeakPtrFactory<WebMediaPlayerMSCompositor> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WebMediaPlayerMSCompositor); };
diff --git a/content/renderer/media/stream/webmediaplayer_ms_unittest.cc b/content/renderer/media/stream/webmediaplayer_ms_unittest.cc index e64120a7..221dae2 100644 --- a/content/renderer/media/stream/webmediaplayer_ms_unittest.cc +++ b/content/renderer/media/stream/webmediaplayer_ms_unittest.cc
@@ -79,7 +79,7 @@ static const int kStandardHeight = 240; class FakeWebMediaPlayerDelegate - : public media::WebMediaPlayerDelegate, + : public blink::WebMediaPlayerDelegate, public base::SupportsWeakPtr<FakeWebMediaPlayerDelegate> { public: FakeWebMediaPlayerDelegate() {}
diff --git a/content/renderer/media/video_capture/local_video_capturer_source.cc b/content/renderer/media/video_capture/local_video_capturer_source.cc index 103a4202..154e3ab 100644 --- a/content/renderer/media/video_capture/local_video_capturer_source.cc +++ b/content/renderer/media/video_capture/local_video_capturer_source.cc
@@ -19,8 +19,7 @@ : session_id_(session_id), manager_(RenderThreadImpl::current()->video_capture_impl_manager()), release_device_cb_(manager_->UseDevice(session_id_)), - task_runner_(std::move(task_runner)), - weak_factory_(this) { + task_runner_(std::move(task_runner)) { DCHECK(RenderThreadImpl::current()); }
diff --git a/content/renderer/media/video_capture/local_video_capturer_source.h b/content/renderer/media/video_capture/local_video_capturer_source.h index 9076ce3..bc96c68 100644 --- a/content/renderer/media/video_capture/local_video_capturer_source.h +++ b/content/renderer/media/video_capture/local_video_capturer_source.h
@@ -71,7 +71,7 @@ // Bound to the main render thread. THREAD_CHECKER(thread_checker_); - base::WeakPtrFactory<LocalVideoCapturerSource> weak_factory_; + base::WeakPtrFactory<LocalVideoCapturerSource> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LocalVideoCapturerSource); };
diff --git a/content/renderer/media/video_capture/video_capture_impl.cc b/content/renderer/media/video_capture/video_capture_impl.cc index 24cb7b2..daba83c 100644 --- a/content/renderer/media/video_capture/video_capture_impl.cc +++ b/content/renderer/media/video_capture/video_capture_impl.cc
@@ -141,8 +141,7 @@ session_id_(session_id), video_capture_host_for_testing_(nullptr), observer_binding_(this), - state_(blink::VIDEO_CAPTURE_STATE_STOPPED), - weak_factory_(this) { + state_(blink::VIDEO_CAPTURE_STATE_STOPPED) { io_thread_checker_.DetachFromThread(); if (ChildThread::Get()) { // This will be null in unit tests.
diff --git a/content/renderer/media/video_capture/video_capture_impl.h b/content/renderer/media/video_capture/video_capture_impl.h index 63afdcea..0f0dbed1 100644 --- a/content/renderer/media/video_capture/video_capture_impl.h +++ b/content/renderer/media/video_capture/video_capture_impl.h
@@ -155,7 +155,7 @@ // WeakPtrFactory pointing back to |this| object, for use with // media::VideoFrames constructed in OnBufferReceived() from buffers cached // in |client_buffers_|. - base::WeakPtrFactory<VideoCaptureImpl> weak_factory_; + base::WeakPtrFactory<VideoCaptureImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VideoCaptureImpl); };
diff --git a/content/renderer/media/video_capture/video_capture_impl_manager.cc b/content/renderer/media/video_capture/video_capture_impl_manager.cc index bc42c23..9a58e61 100644 --- a/content/renderer/media/video_capture/video_capture_impl_manager.cc +++ b/content/renderer/media/video_capture/video_capture_impl_manager.cc
@@ -60,8 +60,7 @@ VideoCaptureImplManager::VideoCaptureImplManager() : next_client_id_(0), render_main_task_runner_(base::ThreadTaskRunnerHandle::Get()), - is_suspending_all_(false), - weak_factory_(this) {} + is_suspending_all_(false) {} VideoCaptureImplManager::~VideoCaptureImplManager() { DCHECK(render_main_task_runner_->BelongsToCurrentThread());
diff --git a/content/renderer/media/video_capture/video_capture_impl_manager.h b/content/renderer/media/video_capture/video_capture_impl_manager.h index 76be1e4..00852e8 100644 --- a/content/renderer/media/video_capture/video_capture_impl_manager.h +++ b/content/renderer/media/video_capture/video_capture_impl_manager.h
@@ -132,7 +132,7 @@ // Bound to the render thread. // NOTE: Weak pointers must be invalidated before all other member variables. - base::WeakPtrFactory<VideoCaptureImplManager> weak_factory_; + base::WeakPtrFactory<VideoCaptureImplManager> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VideoCaptureImplManager); };
diff --git a/content/renderer/media/web_media_element_source_utils.cc b/content/renderer/media/web_media_element_source_utils.cc deleted file mode 100644 index 9fc4893..0000000 --- a/content/renderer/media/web_media_element_source_utils.cc +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/media/web_media_element_source_utils.h" - -#include "third_party/blink/public/platform/web_media_player_source.h" -#include "third_party/blink/public/platform/web_media_stream.h" - -namespace content { - -blink::WebMediaStream GetWebMediaStreamFromWebMediaPlayerSource( - const blink::WebMediaPlayerSource& source) { - if (source.IsMediaStream()) - return source.GetAsMediaStream(); - - return blink::WebMediaStream(); -} - -} // namespace content
diff --git a/content/renderer/media/web_media_element_source_utils.h b/content/renderer/media/web_media_element_source_utils.h deleted file mode 100644 index 86ca8ce4..0000000 --- a/content/renderer/media/web_media_element_source_utils.h +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_MEDIA_WEB_MEDIA_ELEMENT_SOURCE_UTILS_H_ -#define CONTENT_RENDERER_MEDIA_WEB_MEDIA_ELEMENT_SOURCE_UTILS_H_ - -namespace blink { -class WebMediaPlayerSource; -class WebMediaStream; -} - -namespace content { - -// Obtains a WebMediaStream from a WebMediaPlayerSource. If the -// WebMediaPlayerSource does not contain a WebMediaStream, a null -// WebMediaStream is returned. -blink::WebMediaStream GetWebMediaStreamFromWebMediaPlayerSource( - const blink::WebMediaPlayerSource& source); - -} // namespace content - -#endif // CONTENT_RENDERER_MEDIA_WEB_MEDIA_ELEMENT_SOURCE_UTILS_H_
diff --git a/content/renderer/media/webrtc/media_stream_video_webrtc_sink.cc b/content/renderer/media/webrtc/media_stream_video_webrtc_sink.cc index 09c5bc1..ccf1508 100644 --- a/content/renderer/media/webrtc/media_stream_video_webrtc_sink.cc +++ b/content/renderer/media/webrtc/media_stream_video_webrtc_sink.cc
@@ -211,8 +211,7 @@ MediaStreamVideoWebRtcSink::MediaStreamVideoWebRtcSink( const blink::WebMediaStreamTrack& track, PeerConnectionDependencyFactory* factory, - scoped_refptr<base::SingleThreadTaskRunner> task_runner) - : weak_factory_(this) { + scoped_refptr<base::SingleThreadTaskRunner> task_runner) { blink::MediaStreamVideoTrack* video_track = blink::MediaStreamVideoTrack::GetVideoTrack(track); DCHECK(video_track);
diff --git a/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h b/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h index fdceb2d..642d885 100644 --- a/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h +++ b/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h
@@ -77,7 +77,7 @@ // Provides WebRtcVideoSourceAdapter a weak reference to // MediaStreamVideoWebRtcSink in order to allow it to request refresh frames. // See comments in media_stream_video_webrtc_sink.cc. - base::WeakPtrFactory<MediaStreamVideoWebRtcSink> weak_factory_; + base::WeakPtrFactory<MediaStreamVideoWebRtcSink> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MediaStreamVideoWebRtcSink); };
diff --git a/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h b/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h index 74a5333..1a9c6445 100644 --- a/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h +++ b/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h
@@ -30,6 +30,11 @@ MOCK_METHOD0(NegotiationNeeded, void()); MOCK_METHOD1(DidGenerateICECandidate, void(scoped_refptr<blink::WebRTCICECandidate> candidate)); + MOCK_METHOD4(DidFailICECandidate, + void(const blink::WebString& host_candidate, + const blink::WebString& url, + int error_code, + const blink::WebString& error_text)); MOCK_METHOD1(DidChangeSignalingState, void(webrtc::PeerConnectionInterface::SignalingState state)); MOCK_METHOD1(DidChangeIceGatheringState,
diff --git a/content/renderer/media/webrtc/rtc_dtmf_sender_handler.cc b/content/renderer/media/webrtc/rtc_dtmf_sender_handler.cc index 68a9a7cb..4e1f3f4 100644 --- a/content/renderer/media/webrtc/rtc_dtmf_sender_handler.cc +++ b/content/renderer/media/webrtc/rtc_dtmf_sender_handler.cc
@@ -53,7 +53,7 @@ RtcDtmfSenderHandler::RtcDtmfSenderHandler( scoped_refptr<base::SingleThreadTaskRunner> main_thread, DtmfSenderInterface* dtmf_sender) - : dtmf_sender_(dtmf_sender), webkit_client_(nullptr), weak_factory_(this) { + : dtmf_sender_(dtmf_sender), webkit_client_(nullptr) { DVLOG(1) << "::ctor"; observer_ = new Observer(std::move(main_thread), weak_factory_.GetWeakPtr()); dtmf_sender_->RegisterObserver(observer_.get());
diff --git a/content/renderer/media/webrtc/rtc_dtmf_sender_handler.h b/content/renderer/media/webrtc/rtc_dtmf_sender_handler.h index 66dc328..7b0b635 100644 --- a/content/renderer/media/webrtc/rtc_dtmf_sender_handler.h +++ b/content/renderer/media/webrtc/rtc_dtmf_sender_handler.h
@@ -54,7 +54,7 @@ SEQUENCE_CHECKER(sequence_checker_); // |weak_factory_| must be the last member. - base::WeakPtrFactory<RtcDtmfSenderHandler> weak_factory_; + base::WeakPtrFactory<RtcDtmfSenderHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RtcDtmfSenderHandler); };
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc index 28cf525..5425f4a 100644 --- a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc +++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
@@ -53,6 +53,7 @@ #include "third_party/blink/public/platform/web_rtc_session_description_request.h" #include "third_party/blink/public/platform/web_rtc_stats.h" #include "third_party/blink/public/platform/web_rtc_void_request.h" +#include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_url.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_constraints_util.h" #include "third_party/webrtc/api/rtc_event_log_output.h" @@ -915,6 +916,17 @@ candidate->candidate().address().family())); } + void OnIceCandidateError(const std::string& host_candidate, + const std::string& url, + int error_code, + const std::string& error_text) override { + main_thread_->PostTask( + FROM_HERE, + base::BindOnce( + &RTCPeerConnectionHandler::Observer::OnIceCandidateErrorImpl, this, + host_candidate, url, error_code, error_text)); + } + void OnDataChannelImpl(scoped_refptr<DataChannelInterface> channel) { DCHECK(main_thread_->BelongsToCurrentThread()); if (handler_) @@ -930,6 +942,17 @@ } } + void OnIceCandidateErrorImpl(const std::string& host_candidate, + const std::string& url, + int error_code, + const std::string& error_text) { + DCHECK(main_thread_->BelongsToCurrentThread()); + if (handler_) { + handler_->OnIceCandidateError(host_candidate, url, error_code, + error_text); + } + } + void OnInterestingUsage(int usage_pattern) override { main_thread_->PostTask( FROM_HERE, @@ -961,8 +984,7 @@ track_adapter_map_( new WebRtcMediaStreamTrackAdapterMap(dependency_factory_, task_runner)), - task_runner_(std::move(task_runner)), - weak_factory_(this) { + task_runner_(std::move(task_runner)) { CHECK(client_); GetPeerConnectionHandlers()->insert(this); @@ -2298,6 +2320,21 @@ client_->DidGenerateICECandidate(std::move(web_candidate)); } +void RTCPeerConnectionHandler::OnIceCandidateError( + const std::string& host_candidate, + const std::string& url, + int error_code, + const std::string& error_text) { + DCHECK(task_runner_->RunsTasksInCurrentSequence()); + TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceCandidateError"); + + if (!is_closed_) { + client_->DidFailICECandidate(blink::WebString::FromUTF8(host_candidate), + blink::WebString::FromUTF8(url), error_code, + blink::WebString::FromUTF8(error_text)); + } +} + void RTCPeerConnectionHandler::OnInterestingUsage(int usage_pattern) { client_->DidNoteInterestingUsage(usage_pattern); }
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.h b/content/renderer/media/webrtc/rtc_peer_connection_handler.h index 633d68df..5110fc0 100644 --- a/content/renderer/media/webrtc/rtc_peer_connection_handler.h +++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.h
@@ -242,6 +242,10 @@ int sdp_mline_index, int component, int address_family); + void OnIceCandidateError(const std::string& host_candidate, + const std::string& url, + int error_code, + const std::string& error_text); void OnInterestingUsage(int usage_pattern); private: @@ -407,7 +411,7 @@ scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - base::WeakPtrFactory<RTCPeerConnectionHandler> weak_factory_; + base::WeakPtrFactory<RTCPeerConnectionHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RTCPeerConnectionHandler); };
diff --git a/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc b/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc index 6192208..8c25a0d8 100644 --- a/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc +++ b/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc
@@ -184,8 +184,7 @@ : media_task_runner_(gpu_factories->GetTaskRunner()), gpu_factories_(gpu_factories), format_(format), - config_(config), - weak_this_factory_(this) { + config_(config) { DVLOG(1) << __func__; DETACH_FROM_SEQUENCE(decoding_sequence_checker_); weak_this_ = weak_this_factory_.GetWeakPtr();
diff --git a/content/renderer/media/webrtc/rtc_video_decoder_adapter.h b/content/renderer/media/webrtc/rtc_video_decoder_adapter.h index e81e2447..3bba1d9 100644 --- a/content/renderer/media/webrtc/rtc_video_decoder_adapter.h +++ b/content/renderer/media/webrtc/rtc_video_decoder_adapter.h
@@ -132,7 +132,7 @@ SEQUENCE_CHECKER(decoding_sequence_checker_); base::WeakPtr<RTCVideoDecoderAdapter> weak_this_; - base::WeakPtrFactory<RTCVideoDecoderAdapter> weak_this_factory_; + base::WeakPtrFactory<RTCVideoDecoderAdapter> weak_this_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RTCVideoDecoderAdapter); };
diff --git a/content/renderer/media/webrtc/webrtc_audio_device_impl.cc b/content/renderer/media/webrtc/webrtc_audio_device_impl.cc index 16a6e84..37c5ddef 100644 --- a/content/renderer/media/webrtc/webrtc_audio_device_impl.cc +++ b/content/renderer/media/webrtc/webrtc_audio_device_impl.cc
@@ -71,7 +71,7 @@ const int frames_per_10_ms = sample_rate / 100; DCHECK_EQ(audio_bus->frames(), frames_per_10_ms); DCHECK_GE(audio_bus->channels(), 1); - DCHECK_LE(audio_bus->channels(), 2); + DCHECK_LE(audio_bus->channels(), 8); // Get 10ms audio and copy result to temporary byte buffer. render_buffer_.resize(audio_bus->frames() * audio_bus->channels()); @@ -398,6 +398,7 @@ void WebRtcAudioDeviceImpl::AddPlayoutSink( blink::WebRtcPlayoutDataSource::Sink* sink) { DCHECK_CALLED_ON_VALID_THREAD(main_thread_checker_); + DVLOG(1) << "WebRtcAudioDeviceImpl::AddPlayoutSink()"; DCHECK(sink); base::AutoLock auto_lock(lock_); DCHECK(!base::Contains(playout_sinks_, sink)); @@ -407,6 +408,7 @@ void WebRtcAudioDeviceImpl::RemovePlayoutSink( blink::WebRtcPlayoutDataSource::Sink* sink) { DCHECK_CALLED_ON_VALID_THREAD(main_thread_checker_); + DVLOG(1) << "WebRtcAudioDeviceImpl::RemovePlayoutSink()"; DCHECK(sink); base::AutoLock auto_lock(lock_); playout_sinks_.remove(sink);
diff --git a/content/renderer/p2p/empty_network_manager.cc b/content/renderer/p2p/empty_network_manager.cc index 100b6fff..76165e2 100644 --- a/content/renderer/p2p/empty_network_manager.cc +++ b/content/renderer/p2p/empty_network_manager.cc
@@ -13,7 +13,7 @@ namespace content { EmptyNetworkManager::EmptyNetworkManager(rtc::NetworkManager* network_manager) - : network_manager_(network_manager), weak_ptr_factory_(this) { + : network_manager_(network_manager) { DCHECK(network_manager); thread_checker_.DetachFromThread(); set_enumeration_permission(ENUMERATION_BLOCKED);
diff --git a/content/renderer/p2p/empty_network_manager.h b/content/renderer/p2p/empty_network_manager.h index 35df4d1..65220f46 100644 --- a/content/renderer/p2p/empty_network_manager.h +++ b/content/renderer/p2p/empty_network_manager.h
@@ -59,7 +59,7 @@ // PeerConnectionDependencyFactory. rtc::NetworkManager* network_manager_; - base::WeakPtrFactory<EmptyNetworkManager> weak_ptr_factory_; + base::WeakPtrFactory<EmptyNetworkManager> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(EmptyNetworkManager); };
diff --git a/content/renderer/p2p/filtering_network_manager.cc b/content/renderer/p2p/filtering_network_manager.cc index 0596ce9e..93d42f7 100644 --- a/content/renderer/p2p/filtering_network_manager.cc +++ b/content/renderer/p2p/filtering_network_manager.cc
@@ -20,8 +20,7 @@ media::MediaPermission* media_permission) : network_manager_(network_manager), media_permission_(media_permission), - requesting_origin_(requesting_origin), - weak_ptr_factory_(this) { + requesting_origin_(requesting_origin) { thread_checker_.DetachFromThread(); set_enumeration_permission(ENUMERATION_BLOCKED);
diff --git a/content/renderer/p2p/filtering_network_manager.h b/content/renderer/p2p/filtering_network_manager.h index 95fe433..f15f7623 100644 --- a/content/renderer/p2p/filtering_network_manager.h +++ b/content/renderer/p2p/filtering_network_manager.h
@@ -115,7 +115,7 @@ GURL requesting_origin_; - base::WeakPtrFactory<FilteringNetworkManager> weak_ptr_factory_; + base::WeakPtrFactory<FilteringNetworkManager> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FilteringNetworkManager); };
diff --git a/content/renderer/p2p/ipc_network_manager.cc b/content/renderer/p2p/ipc_network_manager.cc index e2401e4..9d3b263c 100644 --- a/content/renderer/p2p/ipc_network_manager.cc +++ b/content/renderer/p2p/ipc_network_manager.cc
@@ -49,8 +49,7 @@ NetworkListManager* network_list_manager, std::unique_ptr<webrtc::MdnsResponderInterface> mdns_responder) : network_list_manager_(network_list_manager), - mdns_responder_(std::move(mdns_responder)), - weak_factory_(this) { + mdns_responder_(std::move(mdns_responder)) { network_list_manager_->AddNetworkListObserver(this); }
diff --git a/content/renderer/p2p/ipc_network_manager.h b/content/renderer/p2p/ipc_network_manager.h index 3c39178..d0d3b0b 100644 --- a/content/renderer/p2p/ipc_network_manager.h +++ b/content/renderer/p2p/ipc_network_manager.h
@@ -52,7 +52,7 @@ int start_count_ = 0; bool network_list_received_ = false; - base::WeakPtrFactory<IpcNetworkManager> weak_factory_; + base::WeakPtrFactory<IpcNetworkManager> weak_factory_{this}; }; } // namespace content
diff --git a/content/renderer/pepper/message_channel.cc b/content/renderer/pepper/message_channel.cc index 76c0a99..483cb035 100644 --- a/content/renderer/pepper/message_channel.cc +++ b/content/renderer/pepper/message_channel.cc
@@ -183,9 +183,7 @@ plugin_message_queue_state_(WAITING_TO_START), var_converter_(instance->pp_instance(), V8VarConverter::kDisallowObjectVars), - template_cache_(instance->GetIsolate()), - weak_ptr_factory_(this) { -} + template_cache_(instance->GetIsolate()) {} gin::ObjectTemplateBuilder MessageChannel::GetObjectTemplateBuilder( v8::Isolate* isolate) {
diff --git a/content/renderer/pepper/message_channel.h b/content/renderer/pepper/message_channel.h index 93169b2..28d0f98 100644 --- a/content/renderer/pepper/message_channel.h +++ b/content/renderer/pepper/message_channel.h
@@ -200,7 +200,7 @@ // This is used to ensure pending tasks will not fire after this object is // destroyed. - base::WeakPtrFactory<MessageChannel> weak_ptr_factory_; + base::WeakPtrFactory<MessageChannel> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MessageChannel); };
diff --git a/content/renderer/pepper/pepper_audio_encoder_host.cc b/content/renderer/pepper/pepper_audio_encoder_host.cc index bede139..48b2c41 100644 --- a/content/renderer/pepper/pepper_audio_encoder_host.cc +++ b/content/renderer/pepper/pepper_audio_encoder_host.cc
@@ -170,9 +170,8 @@ renderer_ppapi_host_(host), initialized_(false), encoder_last_error_(PP_ERROR_FAILED), - media_task_runner_(RenderThreadImpl::current() - ->GetMediaThreadTaskRunner()), - weak_ptr_factory_(this) {} + media_task_runner_( + RenderThreadImpl::current()->GetMediaThreadTaskRunner()) {} PepperAudioEncoderHost::~PepperAudioEncoderHost() { Close();
diff --git a/content/renderer/pepper/pepper_audio_encoder_host.h b/content/renderer/pepper/pepper_audio_encoder_host.h index 1ed3678c..d180bd3 100644 --- a/content/renderer/pepper/pepper_audio_encoder_host.h +++ b/content/renderer/pepper/pepper_audio_encoder_host.h
@@ -103,7 +103,7 @@ // The encoder actually doing the work. std::unique_ptr<AudioEncoderImpl> encoder_; - base::WeakPtrFactory<PepperAudioEncoderHost> weak_ptr_factory_; + base::WeakPtrFactory<PepperAudioEncoderHost> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperAudioEncoderHost); };
diff --git a/content/renderer/pepper/pepper_file_chooser_host.cc b/content/renderer/pepper/pepper_file_chooser_host.cc index d666743..d0eaf74 100644 --- a/content/renderer/pepper/pepper_file_chooser_host.cc +++ b/content/renderer/pepper/pepper_file_chooser_host.cc
@@ -96,8 +96,7 @@ PP_Resource resource) : ResourceHost(host->GetPpapiHost(), instance, resource), renderer_ppapi_host_(host), - handler_(nullptr), - weak_factory_(this) {} + handler_(nullptr) {} PepperFileChooserHost::~PepperFileChooserHost() {}
diff --git a/content/renderer/pepper/pepper_file_chooser_host.h b/content/renderer/pepper/pepper_file_chooser_host.h index c37930e..a4162596 100644 --- a/content/renderer/pepper/pepper_file_chooser_host.h +++ b/content/renderer/pepper/pepper_file_chooser_host.h
@@ -63,7 +63,7 @@ ppapi::host::ReplyMessageContext reply_context_; CompletionHandler* handler_; - base::WeakPtrFactory<PepperFileChooserHost> weak_factory_; + base::WeakPtrFactory<PepperFileChooserHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperFileChooserHost); };
diff --git a/content/renderer/pepper/pepper_in_process_router.cc b/content/renderer/pepper/pepper_in_process_router.cc index ce05b4a..1c761ac1f 100644 --- a/content/renderer/pepper/pepper_in_process_router.cc +++ b/content/renderer/pepper/pepper_in_process_router.cc
@@ -35,10 +35,7 @@ }; PepperInProcessRouter::PepperInProcessRouter(RendererPpapiHostImpl* host_impl) - : host_impl_(host_impl), - pending_message_id_(0), - reply_result_(false), - weak_factory_(this) { + : host_impl_(host_impl), pending_message_id_(0), reply_result_(false) { browser_channel_.reset(new Channel(base::BindRepeating( &PepperInProcessRouter::SendToBrowser, base::Unretained(this)))); host_to_plugin_router_.reset(new Channel(base::BindRepeating(
diff --git a/content/renderer/pepper/pepper_in_process_router.h b/content/renderer/pepper/pepper_in_process_router.h index b2c99b1a..de27322 100644 --- a/content/renderer/pepper/pepper_in_process_router.h +++ b/content/renderer/pepper/pepper_in_process_router.h
@@ -99,7 +99,7 @@ // Reply result of the pending sync message. bool reply_result_; - base::WeakPtrFactory<PepperInProcessRouter> weak_factory_; + base::WeakPtrFactory<PepperInProcessRouter> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperInProcessRouter); };
diff --git a/content/renderer/pepper/pepper_media_stream_audio_track_host.cc b/content/renderer/pepper/pepper_media_stream_audio_track_host.cc index 132147c..af26f98 100644 --- a/content/renderer/pepper/pepper_media_stream_audio_track_host.cc +++ b/content/renderer/pepper/pepper_media_stream_audio_track_host.cc
@@ -77,8 +77,7 @@ number_of_buffers_(kDefaultNumberOfAudioBuffers), bytes_per_second_(0), bytes_per_frame_(0), - user_buffer_duration_(kDefaultDuration), - weak_factory_(this) {} + user_buffer_duration_(kDefaultDuration) {} PepperMediaStreamAudioTrackHost::AudioSink::~AudioSink() { DCHECK_EQ(main_task_runner_, base::ThreadTaskRunnerHandle::Get());
diff --git a/content/renderer/pepper/pepper_media_stream_audio_track_host.h b/content/renderer/pepper/pepper_media_stream_audio_track_host.h index c838b47..539a30c 100644 --- a/content/renderer/pepper/pepper_media_stream_audio_track_host.h +++ b/content/renderer/pepper/pepper_media_stream_audio_track_host.h
@@ -136,7 +136,7 @@ // Pending |Configure()| reply context. ppapi::host::ReplyMessageContext pending_configure_reply_; - base::WeakPtrFactory<AudioSink> weak_factory_; + base::WeakPtrFactory<AudioSink> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AudioSink); };
diff --git a/content/renderer/pepper/pepper_media_stream_video_track_host.cc b/content/renderer/pepper/pepper_media_stream_video_track_host.cc index a3cc483..53a820bd 100644 --- a/content/renderer/pepper/pepper_media_stream_video_track_host.cc +++ b/content/renderer/pepper/pepper_media_stream_video_track_host.cc
@@ -216,8 +216,7 @@ source_frame_format_(PP_VIDEOFRAME_FORMAT_UNKNOWN), plugin_frame_format_(PP_VIDEOFRAME_FORMAT_UNKNOWN), frame_data_size_(0), - type_(kRead), - weak_factory_(this) { + type_(kRead) { DCHECK(!track_.IsNull()); } @@ -230,8 +229,7 @@ source_frame_format_(PP_VIDEOFRAME_FORMAT_UNKNOWN), plugin_frame_format_(PP_VIDEOFRAME_FORMAT_UNKNOWN), frame_data_size_(0), - type_(kWrite), - weak_factory_(this) { + type_(kWrite) { InitBlinkTrack(); DCHECK(!track_.IsNull()); }
diff --git a/content/renderer/pepper/pepper_media_stream_video_track_host.h b/content/renderer/pepper/pepper_media_stream_video_track_host.h index 1b61aaa8..fe4c1e8 100644 --- a/content/renderer/pepper/pepper_media_stream_video_track_host.h +++ b/content/renderer/pepper/pepper_media_stream_video_track_host.h
@@ -116,7 +116,7 @@ class FrameDeliverer; scoped_refptr<FrameDeliverer> frame_deliverer_; - base::WeakPtrFactory<PepperMediaStreamVideoTrackHost> weak_factory_; + base::WeakPtrFactory<PepperMediaStreamVideoTrackHost> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperMediaStreamVideoTrackHost); };
diff --git a/content/renderer/pepper/pepper_platform_camera_device.cc b/content/renderer/pepper/pepper_platform_camera_device.cc index f066404..878005e64 100644 --- a/content/renderer/pepper/pepper_platform_camera_device.cc +++ b/content/renderer/pepper/pepper_platform_camera_device.cc
@@ -27,8 +27,7 @@ session_id_(0), handler_(handler), pending_open_device_(false), - pending_open_device_id_(-1), - weak_factory_(this) { + pending_open_device_id_(-1) { // We need to open the device and obtain the label and session ID before // initializing. PepperMediaDeviceManager* const device_manager = GetMediaDeviceManager();
diff --git a/content/renderer/pepper/pepper_platform_camera_device.h b/content/renderer/pepper/pepper_platform_camera_device.h index 938f5f52..56fa4bd 100644 --- a/content/renderer/pepper/pepper_platform_camera_device.h +++ b/content/renderer/pepper/pepper_platform_camera_device.h
@@ -60,7 +60,7 @@ base::ThreadChecker thread_checker_; - base::WeakPtrFactory<PepperPlatformCameraDevice> weak_factory_; + base::WeakPtrFactory<PepperPlatformCameraDevice> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperPlatformCameraDevice); };
diff --git a/content/renderer/pepper/pepper_platform_video_capture.cc b/content/renderer/pepper/pepper_platform_video_capture.cc index f0bd250..01f3ac1 100644 --- a/content/renderer/pepper/pepper_platform_video_capture.cc +++ b/content/renderer/pepper/pepper_platform_video_capture.cc
@@ -26,8 +26,7 @@ session_id_(0), handler_(handler), pending_open_device_(false), - pending_open_device_id_(-1), - weak_factory_(this) { + pending_open_device_id_(-1) { // We need to open the device and obtain the label and session ID before // initializing. PepperMediaDeviceManager* const device_manager = GetMediaDeviceManager();
diff --git a/content/renderer/pepper/pepper_platform_video_capture.h b/content/renderer/pepper/pepper_platform_video_capture.h index 46ac124..5bd8e33 100644 --- a/content/renderer/pepper/pepper_platform_video_capture.h +++ b/content/renderer/pepper/pepper_platform_video_capture.h
@@ -66,7 +66,7 @@ base::ThreadChecker thread_checker_; - base::WeakPtrFactory<PepperPlatformVideoCapture> weak_factory_; + base::WeakPtrFactory<PepperPlatformVideoCapture> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperPlatformVideoCapture); };
diff --git a/content/renderer/pepper/pepper_plugin_instance_impl.cc b/content/renderer/pepper/pepper_plugin_instance_impl.cc index 78efcf4..663ba6c 100644 --- a/content/renderer/pepper/pepper_plugin_instance_impl.cc +++ b/content/renderer/pepper/pepper_plugin_instance_impl.cc
@@ -540,9 +540,7 @@ isolate_(v8::Isolate::GetCurrent()), is_deleted_(false), initialized_(false), - audio_controller_(std::make_unique<PepperAudioController>(this)), - view_change_weak_ptr_factory_(this), - weak_factory_(this) { + audio_controller_(std::make_unique<PepperAudioController>(this)) { pp_instance_ = HostGlobals::Get()->AddInstance(this); memset(¤t_print_settings_, 0, sizeof(current_print_settings_));
diff --git a/content/renderer/pepper/pepper_plugin_instance_impl.h b/content/renderer/pepper/pepper_plugin_instance_impl.h index a7d2742..00fe1e5c 100644 --- a/content/renderer/pepper/pepper_plugin_instance_impl.h +++ b/content/renderer/pepper/pepper_plugin_instance_impl.h
@@ -917,8 +917,9 @@ // already a weak ptr pending (HasWeakPtrs is true), code should update the // view_data_ but not send updates. This also allows us to cancel scheduled // view change events. - base::WeakPtrFactory<PepperPluginInstanceImpl> view_change_weak_ptr_factory_; - base::WeakPtrFactory<PepperPluginInstanceImpl> weak_factory_; + base::WeakPtrFactory<PepperPluginInstanceImpl> view_change_weak_ptr_factory_{ + this}; + base::WeakPtrFactory<PepperPluginInstanceImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperPluginInstanceImpl); };
diff --git a/content/renderer/pepper/pepper_video_encoder_host.cc b/content/renderer/pepper/pepper_video_encoder_host.cc index 350dcf45..6814d51 100644 --- a/content/renderer/pepper/pepper_video_encoder_host.cc +++ b/content/renderer/pepper/pepper_video_encoder_host.cc
@@ -182,8 +182,7 @@ initialized_(false), encoder_last_error_(PP_ERROR_FAILED), frame_count_(0), - media_input_format_(media::PIXEL_FORMAT_UNKNOWN), - weak_ptr_factory_(this) {} + media_input_format_(media::PIXEL_FORMAT_UNKNOWN) {} PepperVideoEncoderHost::~PepperVideoEncoderHost() { Close();
diff --git a/content/renderer/pepper/pepper_video_encoder_host.h b/content/renderer/pepper/pepper_video_encoder_host.h index 028da68..b198c7ab6 100644 --- a/content/renderer/pepper/pepper_video_encoder_host.h +++ b/content/renderer/pepper/pepper_video_encoder_host.h
@@ -175,7 +175,7 @@ bool lost_context_ = false; #endif - base::WeakPtrFactory<PepperVideoEncoderHost> weak_ptr_factory_; + base::WeakPtrFactory<PepperVideoEncoderHost> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PepperVideoEncoderHost); };
diff --git a/content/renderer/pepper/plugin_instance_throttler_impl.cc b/content/renderer/pepper/plugin_instance_throttler_impl.cc index 1720f22b..f51570b 100644 --- a/content/renderer/pepper/plugin_instance_throttler_impl.cc +++ b/content/renderer/pepper/plugin_instance_throttler_impl.cc
@@ -68,8 +68,7 @@ base::TimeDelta::FromMilliseconds( kAudioThrottledFrameTimeoutMilliseconds), this, - &PluginInstanceThrottlerImpl::EngageThrottle), - weak_factory_(this) {} + &PluginInstanceThrottlerImpl::EngageThrottle) {} PluginInstanceThrottlerImpl::~PluginInstanceThrottlerImpl() { for (auto& observer : observer_list_)
diff --git a/content/renderer/pepper/plugin_instance_throttler_impl.h b/content/renderer/pepper/plugin_instance_throttler_impl.h index 80b4d04..df0394ae6 100644 --- a/content/renderer/pepper/plugin_instance_throttler_impl.h +++ b/content/renderer/pepper/plugin_instance_throttler_impl.h
@@ -115,7 +115,7 @@ base::ObserverList<Observer>::Unchecked observer_list_; - base::WeakPtrFactory<PluginInstanceThrottlerImpl> weak_factory_; + base::WeakPtrFactory<PluginInstanceThrottlerImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PluginInstanceThrottlerImpl); };
diff --git a/content/renderer/pepper/plugin_object.cc b/content/renderer/pepper/plugin_object.cc index 35001d16..7c36cd0 100644 --- a/content/renderer/pepper/plugin_object.cc +++ b/content/renderer/pepper/plugin_object.cc
@@ -193,8 +193,7 @@ instance_(instance), ppp_class_(ppp_class), ppp_class_data_(ppp_class_data), - template_cache_(instance->GetIsolate()), - weak_factory_(this) { + template_cache_(instance->GetIsolate()) { instance_->AddPluginObject(this); }
diff --git a/content/renderer/pepper/plugin_object.h b/content/renderer/pepper/plugin_object.h index 118e1cbe..e170f828 100644 --- a/content/renderer/pepper/plugin_object.h +++ b/content/renderer/pepper/plugin_object.h
@@ -86,7 +86,7 @@ v8::StdGlobalValueMap<std::string, v8::FunctionTemplate> template_cache_; - base::WeakPtrFactory<PluginObject> weak_factory_; + base::WeakPtrFactory<PluginObject> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PluginObject); };
diff --git a/content/renderer/pepper/ppb_graphics_3d_impl.cc b/content/renderer/pepper/ppb_graphics_3d_impl.cc index ef2861a..7c032187 100644 --- a/content/renderer/pepper/ppb_graphics_3d_impl.cc +++ b/content/renderer/pepper/ppb_graphics_3d_impl.cc
@@ -52,8 +52,7 @@ use_image_chromium_( !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisablePepper3DImageChromium) && - base::FeatureList::IsEnabled(features::kPepper3DImageChromium)), - weak_ptr_factory_(this) {} + base::FeatureList::IsEnabled(features::kPepper3DImageChromium)) {} PPB_Graphics3D_Impl::~PPB_Graphics3D_Impl() { // Unset the client before the command_buffer_ is destroyed, similar to how
diff --git a/content/renderer/pepper/ppb_graphics_3d_impl.h b/content/renderer/pepper/ppb_graphics_3d_impl.h index c71abdf..8d94eeb 100644 --- a/content/renderer/pepper/ppb_graphics_3d_impl.h +++ b/content/renderer/pepper/ppb_graphics_3d_impl.h
@@ -124,7 +124,7 @@ const bool use_image_chromium_; std::unique_ptr<gpu::CommandBufferProxyImpl> command_buffer_; - base::WeakPtrFactory<PPB_Graphics3D_Impl> weak_ptr_factory_; + base::WeakPtrFactory<PPB_Graphics3D_Impl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PPB_Graphics3D_Impl); };
diff --git a/content/renderer/pepper/video_decoder_shim.cc b/content/renderer/pepper/video_decoder_shim.cc index 22e4ce3..55886b2 100644 --- a/content/renderer/pepper/video_decoder_shim.cc +++ b/content/renderer/pepper/video_decoder_shim.cc
@@ -670,14 +670,12 @@ // store id of the current buffer while Decode() call is pending. uint32_t decode_id_ = 0; - base::WeakPtrFactory<DecoderImpl> weak_ptr_factory_; + base::WeakPtrFactory<DecoderImpl> weak_ptr_factory_{this}; }; VideoDecoderShim::DecoderImpl::DecoderImpl( const base::WeakPtr<VideoDecoderShim>& proxy) - : shim_(proxy), - main_task_runner_(base::ThreadTaskRunnerHandle::Get()), - weak_ptr_factory_(this) {} + : shim_(proxy), main_task_runner_(base::ThreadTaskRunnerHandle::Get()) {} VideoDecoderShim::DecoderImpl::~DecoderImpl() { DCHECK(pending_decodes_.empty()); @@ -828,8 +826,8 @@ FROM_HERE, base::BindOnce(&VideoDecoderShim::OnResetComplete, shim_)); } -VideoDecoderShim::VideoDecoderShim( - PepperVideoDecoderHost* host, uint32_t texture_pool_size) +VideoDecoderShim::VideoDecoderShim(PepperVideoDecoderHost* host, + uint32_t texture_pool_size) : state_(UNINITIALIZED), host_(host), media_task_runner_( @@ -838,8 +836,7 @@ RenderThreadImpl::current()->SharedMainThreadContextProvider()), texture_pool_size_(texture_pool_size), num_pending_decodes_(0), - yuv_converter_(new YUVConverter(context_provider_)), - weak_ptr_factory_(this) { + yuv_converter_(new YUVConverter(context_provider_)) { DCHECK(host_); DCHECK(media_task_runner_.get()); DCHECK(context_provider_.get());
diff --git a/content/renderer/pepper/video_decoder_shim.h b/content/renderer/pepper/video_decoder_shim.h index 0136910..bca94b9 100644 --- a/content/renderer/pepper/video_decoder_shim.h +++ b/content/renderer/pepper/video_decoder_shim.h
@@ -108,7 +108,7 @@ std::unique_ptr<YUVConverter> yuv_converter_; - base::WeakPtrFactory<VideoDecoderShim> weak_ptr_factory_; + base::WeakPtrFactory<VideoDecoderShim> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VideoDecoderShim); };
diff --git a/content/renderer/pepper/video_encoder_shim.cc b/content/renderer/pepper/video_encoder_shim.cc index 7474e00..e9180e77 100644 --- a/content/renderer/pepper/video_encoder_shim.cc +++ b/content/renderer/pepper/video_encoder_shim.cc
@@ -350,8 +350,7 @@ VideoEncoderShim::VideoEncoderShim(PepperVideoEncoderHost* host) : host_(host), media_task_runner_( - RenderThreadImpl::current()->GetMediaThreadTaskRunner()), - weak_ptr_factory_(this) { + RenderThreadImpl::current()->GetMediaThreadTaskRunner()) { encoder_impl_.reset(new EncoderImpl(weak_ptr_factory_.GetWeakPtr())); }
diff --git a/content/renderer/pepper/video_encoder_shim.h b/content/renderer/pepper/video_encoder_shim.h index 6f717796..f8021095 100644 --- a/content/renderer/pepper/video_encoder_shim.h +++ b/content/renderer/pepper/video_encoder_shim.h
@@ -67,7 +67,7 @@ // Task doing the encoding. scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_; - base::WeakPtrFactory<VideoEncoderShim> weak_ptr_factory_; + base::WeakPtrFactory<VideoEncoderShim> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VideoEncoderShim); };
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 3967382..f1f17f8 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -1850,8 +1850,7 @@ base::BindRepeating(&RenderFrameImpl::RequestOverlayRoutingToken, base::Unretained(this))), input_target_client_impl_(this), - devtools_frame_token_(params.devtools_frame_token), - weak_factory_(this) { + devtools_frame_token_(params.devtools_frame_token) { DCHECK(RenderThread::IsMainThread()); // The InterfaceProvider to access Mojo services exposed by the RFHI must be // provided at construction time. See: https://crbug.com/729021/. @@ -5581,10 +5580,10 @@ observer.DidObserveNewCssPropertyUsage(css_property, is_animated); } -void RenderFrameImpl::DidObserveLayoutJank(double jank_fraction, - bool after_input_or_scroll) { +void RenderFrameImpl::DidObserveLayoutShift(double score, + bool after_input_or_scroll) { for (auto& observer : observers_) - observer.DidObserveLayoutJank(jank_fraction, after_input_or_scroll); + observer.DidObserveLayoutShift(score, after_input_or_scroll); } void RenderFrameImpl::DidObserveLazyLoadBehavior(
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index df49b0d..c183e7c 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -816,8 +816,7 @@ void DidObserveNewFeatureUsage(blink::mojom::WebFeature feature) override; void DidObserveNewCssPropertyUsage(int css_property, bool is_animated) override; - void DidObserveLayoutJank(double jank_fraction, - bool after_input_or_scroll) override; + void DidObserveLayoutShift(double score, bool after_input_or_scroll) override; void DidObserveLazyLoadBehavior( blink::WebLocalFrameClient::LazyLoadBehavior lazy_load_behavior) override; bool ShouldTrackUseCounter(const blink::WebURL& url) override; @@ -1767,7 +1766,7 @@ class MHTMLBodyLoaderClient; std::unique_ptr<MHTMLBodyLoaderClient> mhtml_body_loader_client_; - base::WeakPtrFactory<RenderFrameImpl> weak_factory_; + base::WeakPtrFactory<RenderFrameImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderFrameImpl); };
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index 821ffd9..f04773f 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -416,7 +416,7 @@ class ResourceUsageReporterImpl : public content::mojom::ResourceUsageReporter { public: explicit ResourceUsageReporterImpl(base::WeakPtr<RenderThread> thread) - : workers_to_go_(0), thread_(thread), weak_factory_(this) {} + : workers_to_go_(0), thread_(thread) {} ~ResourceUsageReporterImpl() override {} private: @@ -503,7 +503,7 @@ int workers_to_go_; base::WeakPtr<RenderThread> thread_; - base::WeakPtrFactory<ResourceUsageReporterImpl> weak_factory_; + base::WeakPtrFactory<ResourceUsageReporterImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ResourceUsageReporterImpl); }; @@ -675,8 +675,7 @@ categorized_worker_pool_(new CategorizedWorkerPool()), renderer_binding_(this), client_id_(1), - compositing_mode_watcher_binding_(this), - weak_factory_(this) { + compositing_mode_watcher_binding_(this) { TRACE_EVENT0("startup", "RenderThreadImpl::Create"); Init(); } @@ -695,8 +694,7 @@ categorized_worker_pool_(new CategorizedWorkerPool()), is_scroll_animator_enabled_(false), renderer_binding_(this), - compositing_mode_watcher_binding_(this), - weak_factory_(this) { + compositing_mode_watcher_binding_(this) { TRACE_EVENT0("startup", "RenderThreadImpl::Create"); DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kRendererClientId)); @@ -2428,14 +2426,16 @@ // Called on the I/O thread. bool RenderThreadImpl::UnfreezableMessageFilter::OnMessageReceived( const IPC::Message& message) { - if ((IPC_MESSAGE_CLASS(message) == UnfreezableFrameMsgStart)) { + if ((IPC_MESSAGE_CLASS(message) == UnfreezableFrameMsgStart) || + (IPC_MESSAGE_CLASS(message) == PageMsgStart)) { auto task_runner = GetUnfreezableTaskRunner(message.routing_id()); - if (task_runner) + if (task_runner) { return task_runner->PostTask( FROM_HERE, base::BindOnce( base::IgnoreResult(&RenderThreadImpl::OnMessageReceived), base::Unretained(render_thread_impl_), message)); + } } // If unfreezable task runner is not found or the message class is not // UnfreezableFrameMsgStart, return false so that this filter is skipped and
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index f4e04fa..c02382e1 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -738,7 +738,7 @@ base::TimeTicks init_start_; base::TimeTicks init_end_; - base::WeakPtrFactory<RenderThreadImpl> weak_factory_; + base::WeakPtrFactory<RenderThreadImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl); };
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index e136b0a..9e03aaf40 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -464,8 +464,7 @@ renderer_wide_named_frame_lookup_( params.renderer_wide_named_frame_lookup), webkit_preferences_(params.web_preferences), - session_storage_namespace_id_(params.session_storage_namespace_id), - weak_ptr_factory_(this) { + session_storage_namespace_id_(params.session_storage_namespace_id) { DCHECK(!session_storage_namespace_id_.empty()) << "Session storage namespace must be populated."; // Please put all logic in RenderViewImpl::Initialize().
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index 62c511d..b5cd0378 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -666,7 +666,7 @@ // notifications. // --------------------------------------------------------------------------- - base::WeakPtrFactory<RenderViewImpl> weak_ptr_factory_; + base::WeakPtrFactory<RenderViewImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderViewImpl); };
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 461008f4..9c1272d6 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -541,6 +541,11 @@ RenderFrame::GetRoutingIdForWebFrame(web_frame), params); } +viz::ContextProvider* +RendererBlinkPlatformImpl::SharedMainThreadContextProvider() { + return RenderThreadImpl::current()->SharedMainThreadContextProvider().get(); +} + //------------------------------------------------------------------------------ std::unique_ptr<WebRTCPeerConnectionHandler>
diff --git a/content/renderer/renderer_blink_platform_impl.h b/content/renderer/renderer_blink_platform_impl.h index 0fbb6ee6..88ea9bc 100644 --- a/content/renderer/renderer_blink_platform_impl.h +++ b/content/renderer/renderer_blink_platform_impl.h
@@ -127,6 +127,7 @@ scoped_refptr<media::AudioCapturerSource> NewAudioCapturerSource( blink::WebLocalFrame* web_frame, const media::AudioSourceParameters& params) override; + viz::ContextProvider* SharedMainThreadContextProvider() override; std::unique_ptr<blink::WebRTCPeerConnectionHandler> CreateRTCPeerConnectionHandler( blink::WebRTCPeerConnectionHandlerClient* client,
diff --git a/content/renderer/service_worker/service_worker_context_client.h b/content/renderer/service_worker/service_worker_context_client.h index df5ebdf..abe9152 100644 --- a/content/renderer/service_worker/service_worker_context_client.h +++ b/content/renderer/service_worker/service_worker_context_client.h
@@ -18,7 +18,7 @@ #include "base/memory/scoped_refptr.h" #include "base/strings/string16.h" #include "base/time/time.h" -#include "content/common/service_worker/service_worker_types.h" +#include "content/common/content_export.h" #include "ipc/ipc_listener.h" #include "mojo/public/cpp/bindings/binding.h" #include "third_party/blink/public/common/service_worker/service_worker_status_code.h"
diff --git a/content/renderer/service_worker/service_worker_network_provider_for_frame.cc b/content/renderer/service_worker/service_worker_network_provider_for_frame.cc index d2abdc3..dd19798 100644 --- a/content/renderer/service_worker/service_worker_network_provider_for_frame.cc +++ b/content/renderer/service_worker/service_worker_network_provider_for_frame.cc
@@ -14,7 +14,6 @@ #include "content/renderer/render_thread_impl.h" #include "content/renderer/service_worker/service_worker_provider_context.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" -#include "third_party/blink/public/common/service_worker/service_worker_types.h" #include "third_party/blink/public/web/web_local_frame.h" namespace content {
diff --git a/content/renderer/service_worker/service_worker_provider_context.cc b/content/renderer/service_worker/service_worker_provider_context.cc index fb70248..9d0ae40 100644 --- a/content/renderer/service_worker/service_worker_provider_context.cc +++ b/content/renderer/service_worker/service_worker_provider_context.cc
@@ -63,8 +63,7 @@ scoped_refptr<network::SharedURLLoaderFactory> fallback_loader_factory) : provider_type_(provider_type), main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()), - binding_(this, std::move(request)), - weak_factory_(this) { + binding_(this, std::move(request)) { container_host_.Bind(std::move(host_ptr_info)); state_for_client_ = std::make_unique<ServiceWorkerProviderStateForClient>( std::move(fallback_loader_factory));
diff --git a/content/renderer/service_worker/service_worker_provider_context.h b/content/renderer/service_worker/service_worker_provider_context.h index e00bd7b..64f8a75 100644 --- a/content/renderer/service_worker/service_worker_provider_context.h +++ b/content/renderer/service_worker/service_worker_provider_context.h
@@ -222,7 +222,7 @@ // NOTE: Add new members to |state_for_client_| if they are relevant only for // service worker clients. Not here! - base::WeakPtrFactory<ServiceWorkerProviderContext> weak_factory_; + base::WeakPtrFactory<ServiceWorkerProviderContext> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerProviderContext); };
diff --git a/content/renderer/service_worker/service_worker_provider_context_unittest.cc b/content/renderer/service_worker/service_worker_provider_context_unittest.cc index a4103d8..90763c6 100644 --- a/content/renderer/service_worker/service_worker_provider_context_unittest.cc +++ b/content/renderer/service_worker/service_worker_provider_context_unittest.cc
@@ -18,7 +18,6 @@ #include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" #include "content/child/thread_safe_sender.h" -#include "content/common/service_worker/service_worker_types.h" #include "content/public/common/content_features.h" #include "content/public/common/resource_type.h" #include "content/renderer/service_worker/controller_service_worker_connector.h"
diff --git a/content/renderer/service_worker/service_worker_subresource_loader.cc b/content/renderer/service_worker/service_worker_subresource_loader.cc index 730194e..67d2645 100644 --- a/content/renderer/service_worker/service_worker_subresource_loader.cc +++ b/content/renderer/service_worker/service_worker_subresource_loader.cc
@@ -15,7 +15,6 @@ #include "base/trace_event/trace_event.h" #include "content/common/fetch/fetch_request_type_converters.h" #include "content/common/service_worker/service_worker_loader_helpers.h" -#include "content/common/service_worker/service_worker_types.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/common/content_features.h" #include "content/renderer/loader/web_url_request_util.h" @@ -178,8 +177,7 @@ resource_request_(resource_request), fallback_factory_(std::move(fallback_factory)), task_runner_(std::move(task_runner)), - response_source_(network::mojom::FetchResponseSource::kUnspecified), - weak_factory_(this) { + response_source_(network::mojom::FetchResponseSource::kUnspecified) { DCHECK(controller_connector_); response_head_.request_start = base::TimeTicks::Now(); response_head_.load_timing.request_start = base::TimeTicks::Now();
diff --git a/content/renderer/service_worker/service_worker_subresource_loader.h b/content/renderer/service_worker/service_worker_subresource_loader.h index 08f3daa..52474e0e 100644 --- a/content/renderer/service_worker/service_worker_subresource_loader.h +++ b/content/renderer/service_worker/service_worker_subresource_loader.h
@@ -192,7 +192,7 @@ blink::mojom::ServiceWorkerFetchEventTimingPtr fetch_event_timing_; network::mojom::FetchResponseSource response_source_; - base::WeakPtrFactory<ServiceWorkerSubresourceLoader> weak_factory_; + base::WeakPtrFactory<ServiceWorkerSubresourceLoader> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerSubresourceLoader); };
diff --git a/content/renderer/service_worker/web_service_worker_provider_impl.cc b/content/renderer/service_worker/web_service_worker_provider_impl.cc index 673242a6..a06865e 100644 --- a/content/renderer/service_worker/web_service_worker_provider_impl.cc +++ b/content/renderer/service_worker/web_service_worker_provider_impl.cc
@@ -33,7 +33,7 @@ WebServiceWorkerProviderImpl::WebServiceWorkerProviderImpl( ServiceWorkerProviderContext* context) - : context_(context), provider_client_(nullptr), weak_factory_(this) { + : context_(context), provider_client_(nullptr) { DCHECK(context_); DCHECK_EQ(context_->provider_type(), blink::mojom::ServiceWorkerProviderType::kForWindow); @@ -68,22 +68,21 @@ GURL pattern(web_pattern); GURL script_url(web_script_url); + const std::string error_prefix("Failed to register a ServiceWorker: "); if (pattern.possibly_invalid_spec().size() > url::kMaxURLChars || script_url.possibly_invalid_spec().size() > url::kMaxURLChars) { - std::string error_message(kServiceWorkerRegisterErrorPrefix); - error_message += "The provided scriptURL or scope is too long."; callbacks->OnError(blink::WebServiceWorkerError( blink::mojom::ServiceWorkerErrorType::kSecurity, - blink::WebString::FromASCII(error_message))); + blink::WebString::FromASCII( + error_prefix + "The provided scriptURL or scope is too long."))); return; } if (!context_->container_host()) { - std::string error_message(kServiceWorkerRegisterErrorPrefix); - error_message += kLostConnectionErrorMessage; callbacks->OnError(blink::WebServiceWorkerError( blink::mojom::ServiceWorkerErrorType::kAbort, - blink::WebString::FromASCII(error_message))); + blink::WebString::FromASCII(error_prefix + + kLostConnectionErrorMessage))); return; } @@ -108,21 +107,20 @@ std::unique_ptr<WebServiceWorkerGetRegistrationCallbacks> callbacks) { DCHECK(callbacks); GURL document_url(web_document_url); + const std::string error_prefix("Failed to get a ServiceWorkerRegistration: "); if (document_url.possibly_invalid_spec().size() > url::kMaxURLChars) { - std::string error_message(kServiceWorkerGetRegistrationErrorPrefix); - error_message += "The provided documentURL is too long."; callbacks->OnError(blink::WebServiceWorkerError( blink::mojom::ServiceWorkerErrorType::kSecurity, - blink::WebString::FromASCII(error_message))); + blink::WebString::FromASCII(error_prefix + + "The provided documentURL is too long."))); return; } if (!context_->container_host()) { - std::string error_message(kServiceWorkerGetRegistrationErrorPrefix); - error_message += kLostConnectionErrorMessage; callbacks->OnError(blink::WebServiceWorkerError( blink::mojom::ServiceWorkerErrorType::kAbort, - blink::WebString::FromASCII(error_message))); + blink::WebString::FromASCII(error_prefix + + kLostConnectionErrorMessage))); return; } @@ -139,11 +137,12 @@ std::unique_ptr<WebServiceWorkerGetRegistrationsCallbacks> callbacks) { DCHECK(callbacks); if (!context_->container_host()) { - std::string error_message(kServiceWorkerGetRegistrationsErrorPrefix); - error_message += kLostConnectionErrorMessage; + const std::string error_prefix( + "Failed to get ServiceWorkerRegistration objects: "); callbacks->OnError(blink::WebServiceWorkerError( blink::mojom::ServiceWorkerErrorType::kAbort, - blink::WebString::FromASCII(error_message))); + blink::WebString::FromASCII(error_prefix + + kLostConnectionErrorMessage))); return; }
diff --git a/content/renderer/service_worker/web_service_worker_provider_impl.h b/content/renderer/service_worker/web_service_worker_provider_impl.h index 0a7dcc8d..2a8572b5 100644 --- a/content/renderer/service_worker/web_service_worker_provider_impl.h +++ b/content/renderer/service_worker/web_service_worker_provider_impl.h
@@ -11,7 +11,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" -#include "content/common/service_worker/service_worker_types.h" +#include "content/common/content_export.h" #include "third_party/blink/public/common/messaging/transferable_message.h" #include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h" #include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h" @@ -97,7 +97,7 @@ // the same context, but could live longer until the context is GC'ed) blink::WebServiceWorkerProviderClient* provider_client_; - base::WeakPtrFactory<WebServiceWorkerProviderImpl> weak_factory_; + base::WeakPtrFactory<WebServiceWorkerProviderImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WebServiceWorkerProviderImpl); };
diff --git a/content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.cc b/content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.cc index 4bae8bc..8ae3a9e 100644 --- a/content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.cc +++ b/content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.cc
@@ -29,7 +29,7 @@ using base::debug::MappedMemoryRegion; -jboolean RunChecks(bool in_browser_process, bool need_relros) { +jboolean RunChecks(bool in_browser_process) { // IMPORTANT NOTE: The Python test control script reads the logcat for // lines like: // BROWSER_LINKER_TEST: <status> @@ -151,18 +151,10 @@ return false; } - if (need_relros) { - if (num_shared_relros == 0) { - LOG(ERROR) << prefix - << "FAIL Missing shared RELRO sections in this process!"; - return false; - } - } else { - if (num_shared_relros > 0) { - LOG(ERROR) << prefix << "FAIL Unexpected " << num_shared_relros - << " shared RELRO sections in this process!"; - return false; - } + if (num_shared_relros == 0) { + LOG(ERROR) << prefix + << "FAIL Missing shared RELRO sections in this process!"; + return false; } VLOG(0) << prefix << "SUCCESS"; @@ -173,13 +165,7 @@ jboolean JNI_LinkerTests_CheckForSharedRelros(JNIEnv* env, jboolean in_browser_process) { - return RunChecks(in_browser_process, true); -} - -jboolean JNI_LinkerTests_CheckForNoSharedRelros( - JNIEnv* env, - jboolean in_browser_process) { - return RunChecks(in_browser_process, false); + return RunChecks(in_browser_process); } } // namespace content
diff --git a/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/ChromiumLinkerTestActivity.java b/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/ChromiumLinkerTestActivity.java index 76bd136..8209c8cb 100644 --- a/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/ChromiumLinkerTestActivity.java +++ b/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/ChromiumLinkerTestActivity.java
@@ -11,7 +11,6 @@ import android.view.LayoutInflater; import android.view.View; -import org.chromium.base.CommandLine; import org.chromium.base.Log; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; @@ -29,16 +28,6 @@ public class ChromiumLinkerTestActivity extends Activity { private static final String TAG = "LinkerTest"; - public static final String COMMAND_LINE_FILE = - "/data/local/tmp/chromium-linker-test-command-line"; - - public static final String COMMAND_LINE_ARGS_KEY = "commandLineArgs"; - - // Use this on the command-line to simulate a low-memory device, otherwise - // a regular device is simulated by this test, independently from what the - // target device running the test really is. - private static final String LOW_MEMORY_DEVICE = "--low-memory-device"; - private ShellManager mShellManager; private ActivityWindowAndroid mWindowAndroid; @@ -46,40 +35,6 @@ public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); - // Initializing the command line must occur before loading the library. - if (!CommandLine.isInitialized()) { - CommandLine.initFromFile(COMMAND_LINE_FILE); - String[] commandLineParams = getCommandLineParamsFromIntent(getIntent()); - if (commandLineParams != null) { - CommandLine.getInstance().appendSwitchesAndArguments(commandLineParams); - } - } - - // CommandLine.getInstance().hasSwitch() doesn't work here for some funky - // reason, so parse the command-line differently here: - boolean hasLowMemoryDeviceSwitch = false; - String[] commandLine = CommandLine.getJavaSwitchesOrNull(); - if (commandLine == null) { - Log.i(TAG, "Command line is null"); - } else { - Log.i(TAG, "Command line is:"); - for (int n = 0; n < commandLine.length; ++n) { - String option = commandLine[n]; - Log.i(TAG, " '" + option + "'"); - if (option.equals(LOW_MEMORY_DEVICE)) { - hasLowMemoryDeviceSwitch = true; - } - } - } - - // Determine which kind of device to simulate from the command-line. - int memoryDeviceConfig = Linker.MEMORY_DEVICE_CONFIG_NORMAL; - if (hasLowMemoryDeviceSwitch) { - memoryDeviceConfig = Linker.MEMORY_DEVICE_CONFIG_LOW; - } - Linker linker = Linker.getInstance(); - linker.setMemoryDeviceConfigForTesting(memoryDeviceConfig); - // Setup the TestRunner class name. Linker.setupForTesting("org.chromium.chromium_linker_test_apk.LinkerTests"); @@ -164,10 +119,6 @@ mWindowAndroid.onActivityResult(requestCode, resultCode, data); } - private static String[] getCommandLineParamsFromIntent(Intent intent) { - return intent != null ? intent.getStringArrayExtra(COMMAND_LINE_ARGS_KEY) : null; - } - /** * @return The {@link WebContents} owned by the currently visible {@link Shell} or null if * one is not showing.
diff --git a/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/LinkerTests.java b/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/LinkerTests.java index f41e44dab..e4f67e6 100644 --- a/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/LinkerTests.java +++ b/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/LinkerTests.java
@@ -4,7 +4,6 @@ package org.chromium.chromium_linker_test_apk; -import org.chromium.base.Log; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.library_loader.Linker; @@ -19,46 +18,11 @@ public LinkerTests() {} @Override - public boolean runChecks(int memoryDeviceConfig, - boolean isBrowserProcess) { - boolean checkSharedRelro; - if (isBrowserProcess) { - // LegacyLinker may share RELROs in the browser. - switch (Linker.BROWSER_SHARED_RELRO_CONFIG) { - case Linker.BROWSER_SHARED_RELRO_CONFIG_NEVER: - checkSharedRelro = false; - break; - case Linker.BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY: - // A shared RELRO should only be used on low-end devices. - checkSharedRelro = (memoryDeviceConfig == Linker.MEMORY_DEVICE_CONFIG_LOW); - break; - case Linker.BROWSER_SHARED_RELRO_CONFIG_ALWAYS: - // Always check for a shared RELRO. - checkSharedRelro = true; - break; - default: - Log.e(TAG, - "Invalid shared RELRO linker configuration: " - + Linker.BROWSER_SHARED_RELRO_CONFIG); - return false; - } - } else { - // Service processes should always use a shared RELRO section. - checkSharedRelro = true; - } - - if (checkSharedRelro) { - return nativeCheckForSharedRelros(isBrowserProcess); - } else { - return nativeCheckForNoSharedRelros(isBrowserProcess); - } + public boolean runChecks(boolean isBrowserProcess) { + return nativeCheckForSharedRelros(isBrowserProcess); } // Check that there are shared RELRO sections in the current process, // and that they are properly mapped read-only. Returns true on success. private static native boolean nativeCheckForSharedRelros(boolean isBrowserProcess); - - // Check that there are no shared RELRO sections in the current process, - // return true on success. - private static native boolean nativeCheckForNoSharedRelros(boolean isBrowserProcess); }
diff --git a/content/shell/browser/shell_devtools_bindings.cc b/content/shell/browser/shell_devtools_bindings.cc index a35734fc..6551538 100644 --- a/content/shell/browser/shell_devtools_bindings.cc +++ b/content/shell/browser/shell_devtools_bindings.cc
@@ -149,8 +149,7 @@ inspected_contents_(inspected_contents), delegate_(delegate), inspect_element_at_x_(-1), - inspect_element_at_y_(-1), - weak_factory_(this) {} + inspect_element_at_y_(-1) {} ShellDevToolsBindings::~ShellDevToolsBindings() { if (agent_host_)
diff --git a/content/shell/browser/shell_devtools_bindings.h b/content/shell/browser/shell_devtools_bindings.h index a346a3f..927d8c3 100644 --- a/content/shell/browser/shell_devtools_bindings.h +++ b/content/shell/browser/shell_devtools_bindings.h
@@ -87,7 +87,7 @@ using ExtensionsAPIs = std::map<std::string, std::string>; ExtensionsAPIs extensions_api_; - base::WeakPtrFactory<ShellDevToolsBindings> weak_factory_; + base::WeakPtrFactory<ShellDevToolsBindings> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ShellDevToolsBindings); };
diff --git a/content/shell/browser/shell_download_manager_delegate.cc b/content/shell/browser/shell_download_manager_delegate.cc index af9b2f3..a181f0e 100644 --- a/content/shell/browser/shell_download_manager_delegate.cc +++ b/content/shell/browser/shell_download_manager_delegate.cc
@@ -37,9 +37,7 @@ namespace content { ShellDownloadManagerDelegate::ShellDownloadManagerDelegate() - : download_manager_(nullptr), - suppress_prompting_(false), - weak_ptr_factory_(this) {} + : download_manager_(nullptr), suppress_prompting_(false) {} ShellDownloadManagerDelegate::~ShellDownloadManagerDelegate() { if (download_manager_) {
diff --git a/content/shell/browser/shell_download_manager_delegate.h b/content/shell/browser/shell_download_manager_delegate.h index 3e4922d..00da47fe 100644 --- a/content/shell/browser/shell_download_manager_delegate.h +++ b/content/shell/browser/shell_download_manager_delegate.h
@@ -57,7 +57,7 @@ DownloadManager* download_manager_; base::FilePath default_download_path_; bool suppress_prompting_; - base::WeakPtrFactory<ShellDownloadManagerDelegate> weak_ptr_factory_; + base::WeakPtrFactory<ShellDownloadManagerDelegate> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ShellDownloadManagerDelegate); };
diff --git a/content/shell/browser/web_test/blink_test_controller.cc b/content/shell/browser/web_test/blink_test_controller.cc index 7943a8a..75e70f2 100644 --- a/content/shell/browser/web_test/blink_test_controller.cc +++ b/content/shell/browser/web_test/blink_test_controller.cc
@@ -326,8 +326,7 @@ test_phase_(BETWEEN_TESTS), crash_when_leak_found_(false), pending_layout_dumps_(0), - render_process_host_observer_(this), - weak_factory_(this) { + render_process_host_observer_(this) { CHECK(!instance_); instance_ = this;
diff --git a/content/shell/browser/web_test/blink_test_controller.h b/content/shell/browser/web_test/blink_test_controller.h index 2a6ef05b..3def7c3 100644 --- a/content/shell/browser/web_test/blink_test_controller.h +++ b/content/shell/browser/web_test/blink_test_controller.h
@@ -329,7 +329,7 @@ SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<BlinkTestController> weak_factory_; + base::WeakPtrFactory<BlinkTestController> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BlinkTestController); };
diff --git a/content/shell/browser/web_test/leak_detector.cc b/content/shell/browser/web_test/leak_detector.cc index b2b9814..3bfeec8a 100644 --- a/content/shell/browser/web_test/leak_detector.cc +++ b/content/shell/browser/web_test/leak_detector.cc
@@ -40,7 +40,7 @@ // objects. const int kInitialNumberOfV8PerContextData = 2; -LeakDetector::LeakDetector() : weak_factory_(this) { +LeakDetector::LeakDetector() { previous_result_ = blink::mojom::LeakDetectionResult::New(); previous_result_->number_of_live_audio_nodes = kInitialNumberOfLiveAudioNodes; previous_result_->number_of_live_documents = kInitialNumberOfLiveDocuments;
diff --git a/content/shell/browser/web_test/leak_detector.h b/content/shell/browser/web_test/leak_detector.h index cb71572..ad7901ff 100644 --- a/content/shell/browser/web_test/leak_detector.h +++ b/content/shell/browser/web_test/leak_detector.h
@@ -41,7 +41,7 @@ blink::mojom::LeakDetectorPtr leak_detector_; blink::mojom::LeakDetectionResultPtr previous_result_; ReportCallback callback_; - base::WeakPtrFactory<LeakDetector> weak_factory_; + base::WeakPtrFactory<LeakDetector> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LeakDetector); };
diff --git a/content/shell/browser/web_test/web_test_background_fetch_delegate.cc b/content/shell/browser/web_test/web_test_background_fetch_delegate.cc index f3a857f..69ed38f16 100644 --- a/content/shell/browser/web_test/web_test_background_fetch_delegate.cc +++ b/content/shell/browser/web_test/web_test_background_fetch_delegate.cc
@@ -63,7 +63,7 @@ public: explicit WebTestBackgroundFetchDownloadClient( base::WeakPtr<content::BackgroundFetchDelegate::Client> client) - : client_(std::move(client)), weak_ptr_factory_(this) {} + : client_(std::move(client)) {} ~WebTestBackgroundFetchDownloadClient() override = default; @@ -221,7 +221,8 @@ base::flat_map<std::string, std::unique_ptr<content::BackgroundFetchResponse>> guid_to_response_; - base::WeakPtrFactory<WebTestBackgroundFetchDownloadClient> weak_ptr_factory_; + base::WeakPtrFactory<WebTestBackgroundFetchDownloadClient> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(WebTestBackgroundFetchDownloadClient); };
diff --git a/content/shell/browser/web_test/web_test_bluetooth_chooser_factory.cc b/content/shell/browser/web_test/web_test_bluetooth_chooser_factory.cc index c28074c..5e8123f2 100644 --- a/content/shell/browser/web_test/web_test_bluetooth_chooser_factory.cc +++ b/content/shell/browser/web_test/web_test_bluetooth_chooser_factory.cc
@@ -88,8 +88,7 @@ DISALLOW_COPY_AND_ASSIGN(Chooser); }; -WebTestBluetoothChooserFactory::WebTestBluetoothChooserFactory() - : weak_this_(this) {} +WebTestBluetoothChooserFactory::WebTestBluetoothChooserFactory() {} WebTestBluetoothChooserFactory::~WebTestBluetoothChooserFactory() { SendEvent(BluetoothChooser::Event::CANCELLED, "");
diff --git a/content/shell/browser/web_test/web_test_bluetooth_chooser_factory.h b/content/shell/browser/web_test/web_test_bluetooth_chooser_factory.h index 0914519f..9b95d32f 100644 --- a/content/shell/browser/web_test/web_test_bluetooth_chooser_factory.h +++ b/content/shell/browser/web_test/web_test_bluetooth_chooser_factory.h
@@ -37,7 +37,7 @@ // Contains the set of live choosers, in order to send them events. std::set<Chooser*> choosers_; - base::WeakPtrFactory<WebTestBluetoothChooserFactory> weak_this_; + base::WeakPtrFactory<WebTestBluetoothChooserFactory> weak_this_{this}; }; } // namespace content
diff --git a/content/shell/test_runner/accessibility_controller.cc b/content/shell/test_runner/accessibility_controller.cc index 268ea1e..0c56252 100644 --- a/content/shell/test_runner/accessibility_controller.cc +++ b/content/shell/test_runner/accessibility_controller.cc
@@ -147,8 +147,7 @@ AccessibilityController::AccessibilityController( WebViewTestProxy* web_view_test_proxy) : log_accessibility_events_(false), - web_view_test_proxy_(web_view_test_proxy), - weak_factory_(this) {} + web_view_test_proxy_(web_view_test_proxy) {} AccessibilityController::~AccessibilityController() {}
diff --git a/content/shell/test_runner/accessibility_controller.h b/content/shell/test_runner/accessibility_controller.h index 14a26b7..45a8a80 100644 --- a/content/shell/test_runner/accessibility_controller.h +++ b/content/shell/test_runner/accessibility_controller.h
@@ -67,7 +67,7 @@ std::unique_ptr<blink::WebAXContext> ax_context_; - base::WeakPtrFactory<AccessibilityController> weak_factory_; + base::WeakPtrFactory<AccessibilityController> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AccessibilityController); };
diff --git a/content/shell/test_runner/event_sender.cc b/content/shell/test_runner/event_sender.cc index 73ed1ad..cbf96e0 100644 --- a/content/shell/test_runner/event_sender.cc +++ b/content/shell/test_runner/event_sender.cc
@@ -1317,8 +1317,7 @@ EventSender::EventSender(WebWidgetTestProxy* web_widget_test_proxy) : web_widget_test_proxy_(web_widget_test_proxy), - replaying_saved_events_(false), - weak_factory_(this) { + replaying_saved_events_(false) { Reset(); }
diff --git a/content/shell/test_runner/event_sender.h b/content/shell/test_runner/event_sender.h index 21c4160..8e9d780 100644 --- a/content/shell/test_runner/event_sender.h +++ b/content/shell/test_runner/event_sender.h
@@ -331,7 +331,7 @@ // Timestamp of the last event that was dispatched base::TimeTicks last_event_timestamp_; - base::WeakPtrFactory<EventSender> weak_factory_; + base::WeakPtrFactory<EventSender> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(EventSender); };
diff --git a/content/shell/test_runner/spell_check_client.cc b/content/shell/test_runner/spell_check_client.cc index 5b6f0cbc..5b8611b 100644 --- a/content/shell/test_runner/spell_check_client.cc +++ b/content/shell/test_runner/spell_check_client.cc
@@ -22,8 +22,7 @@ SpellCheckClient::SpellCheckClient(TestRunner* test_runner) : last_requested_text_checking_completion_(nullptr), - test_runner_(test_runner), - weak_factory_(this) { + test_runner_(test_runner) { DCHECK(test_runner); }
diff --git a/content/shell/test_runner/spell_check_client.h b/content/shell/test_runner/spell_check_client.h index ff85b98..b513caa 100644 --- a/content/shell/test_runner/spell_check_client.h +++ b/content/shell/test_runner/spell_check_client.h
@@ -72,7 +72,7 @@ TestRunner* test_runner_; WebTestDelegate* delegate_; - base::WeakPtrFactory<SpellCheckClient> weak_factory_; + base::WeakPtrFactory<SpellCheckClient> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SpellCheckClient); };
diff --git a/content/shell/test_runner/test_runner.cc b/content/shell/test_runner/test_runner.cc index de91134f..43343fc 100644 --- a/content/shell/test_runner/test_runner.cc +++ b/content/shell/test_runner/test_runner.cc
@@ -1425,7 +1425,7 @@ void TestRunnerBindings::NotImplemented(const gin::Arguments& args) {} TestRunner::WorkQueue::WorkQueue(TestRunner* controller) - : frozen_(false), controller_(controller), weak_factory_(this) {} + : frozen_(false), controller_(controller) {} TestRunner::WorkQueue::~WorkQueue() { Reset(); @@ -1496,8 +1496,7 @@ is_web_platform_tests_mode_(false), animation_requires_raster_(false), effective_connection_type_( - blink::WebEffectiveConnectionType::kTypeUnknown), - weak_factory_(this) {} + blink::WebEffectiveConnectionType::kTypeUnknown) {} TestRunner::~TestRunner() {}
diff --git a/content/shell/test_runner/test_runner.h b/content/shell/test_runner/test_runner.h index e788180..fb76256e 100644 --- a/content/shell/test_runner/test_runner.h +++ b/content/shell/test_runner/test_runner.h
@@ -204,7 +204,7 @@ bool frozen_; TestRunner* controller_; - base::WeakPtrFactory<WorkQueue> weak_factory_; + base::WeakPtrFactory<WorkQueue> weak_factory_{this}; }; /////////////////////////////////////////////////////////////////////////// @@ -591,7 +591,7 @@ // Forces v8 compilation cache to be disabled (used for inspector tests). bool disable_v8_cache_ = false; - base::WeakPtrFactory<TestRunner> weak_factory_; + base::WeakPtrFactory<TestRunner> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TestRunner); };
diff --git a/content/shell/test_runner/test_runner_for_specific_view.cc b/content/shell/test_runner/test_runner_for_specific_view.cc index 6fd628d7..62e606f 100644 --- a/content/shell/test_runner/test_runner_for_specific_view.cc +++ b/content/shell/test_runner/test_runner_for_specific_view.cc
@@ -69,7 +69,7 @@ TestRunnerForSpecificView::TestRunnerForSpecificView( WebViewTestProxy* web_view_test_proxy) - : web_view_test_proxy_(web_view_test_proxy), weak_factory_(this) { + : web_view_test_proxy_(web_view_test_proxy) { Reset(); } @@ -627,7 +627,7 @@ int world_id, v8::Local<v8::Value> security_origin, v8::Local<v8::Value> content_security_policy) { - if (world_id <= content::ISOLATED_WORLD_ID_GLOBAL && + if (world_id <= content::ISOLATED_WORLD_ID_GLOBAL || world_id >= blink::IsolatedWorldId::kEmbedderWorldIdLimit) { return; }
diff --git a/content/shell/test_runner/test_runner_for_specific_view.h b/content/shell/test_runner/test_runner_for_specific_view.h index dbc5ec2..07a3383 100644 --- a/content/shell/test_runner/test_runner_for_specific_view.h +++ b/content/shell/test_runner/test_runner_for_specific_view.h
@@ -233,7 +233,7 @@ WebViewTestProxy* web_view_test_proxy_; - base::WeakPtrFactory<TestRunnerForSpecificView> weak_factory_; + base::WeakPtrFactory<TestRunnerForSpecificView> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TestRunnerForSpecificView); };
diff --git a/content/shell/test_runner/text_input_controller.cc b/content/shell/test_runner/text_input_controller.cc index a2681bc5..f22bd85 100644 --- a/content/shell/test_runner/text_input_controller.cc +++ b/content/shell/test_runner/text_input_controller.cc
@@ -197,7 +197,7 @@ // TextInputController --------------------------------------------------------- TextInputController::TextInputController(WebViewTestProxy* web_view_test_proxy) - : web_view_test_proxy_(web_view_test_proxy), weak_factory_(this) {} + : web_view_test_proxy_(web_view_test_proxy) {} TextInputController::~TextInputController() {}
diff --git a/content/shell/test_runner/text_input_controller.h b/content/shell/test_runner/text_input_controller.h index a1ee9263..47adca1 100644 --- a/content/shell/test_runner/text_input_controller.h +++ b/content/shell/test_runner/text_input_controller.h
@@ -58,7 +58,7 @@ WebViewTestProxy* web_view_test_proxy_; - base::WeakPtrFactory<TextInputController> weak_factory_; + base::WeakPtrFactory<TextInputController> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TextInputController); };
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index b01f6fc..88ed64c 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -38,8 +38,6 @@ "../browser/accessibility/accessibility_event_recorder_uia_win.cc", "../browser/accessibility/accessibility_event_recorder_uia_win.h", "../browser/accessibility/accessibility_event_recorder_win.cc", - "../browser/accessibility/dump_accessibility_test_helper.cc", - "../browser/accessibility/dump_accessibility_test_helper.h", "../browser/background_fetch/background_fetch_test_base.cc", "../browser/background_fetch/background_fetch_test_base.h", "../browser/background_fetch/background_fetch_test_browser_context.cc", @@ -98,6 +96,8 @@ "../public/test/content_test_suite_base.h", "../public/test/download_test_observer.cc", "../public/test/download_test_observer.h", + "../public/test/dump_accessibility_test_helper.cc", + "../public/test/dump_accessibility_test_helper.h", "../public/test/fake_download_item.cc", "../public/test/fake_download_item.h", "../public/test/fake_service_worker_context.cc",
diff --git a/content/test/accessibility_browser_test_utils.cc b/content/test/accessibility_browser_test_utils.cc index 27963d3..1a0f0bc5 100644 --- a/content/test/accessibility_browser_test_utils.cc +++ b/content/test/accessibility_browser_test_utils.cc
@@ -10,6 +10,7 @@ #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "content/browser/accessibility/browser_accessibility.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" @@ -28,8 +29,7 @@ : WebContentsObserver(web_contents), event_to_wait_for_(ax::mojom::Event::kNone), generated_event_to_wait_for_(base::nullopt), - loop_runner_(std::make_unique<base::RunLoop>()), - weak_factory_(this) { + loop_runner_(std::make_unique<base::RunLoop>()) { ListenToAllFrames(web_contents); } @@ -40,8 +40,7 @@ : WebContentsObserver(web_contents), event_to_wait_for_(event_type), generated_event_to_wait_for_(base::nullopt), - loop_runner_(std::make_unique<base::RunLoop>()), - weak_factory_(this) { + loop_runner_(std::make_unique<base::RunLoop>()) { ListenToAllFrames(web_contents); static_cast<WebContentsImpl*>(web_contents) ->AddAccessibilityMode(accessibility_mode); @@ -54,8 +53,7 @@ : WebContentsObserver(web_contents), event_to_wait_for_(base::nullopt), generated_event_to_wait_for_(event_type), - loop_runner_(std::make_unique<base::RunLoop>()), - weak_factory_(this) { + loop_runner_(std::make_unique<base::RunLoop>()) { ListenToAllFrames(web_contents); static_cast<WebContentsImpl*>(web_contents) ->AddAccessibilityMode(accessibility_mode); @@ -151,6 +149,9 @@ manager->SetGeneratedEventCallbackForTesting( base::BindRepeating(&AccessibilityNotificationWaiter::OnGeneratedEvent, weak_factory_.GetWeakPtr())); + manager->SetFocusChangeCallbackForTesting( + base::BindRepeating(&AccessibilityNotificationWaiter::OnFocusChanged, + weak_factory_.GetWeakPtr())); } } @@ -168,6 +169,20 @@ } } +// TODO(982776): Remove this method once we migrate to using AXEventGenerator +// for focus changed events. +void AccessibilityNotificationWaiter::OnFocusChanged() { + WebContentsImpl* web_contents_impl = + static_cast<WebContentsImpl*>(web_contents()); + const BrowserAccessibilityManager* manager = + web_contents_impl->GetRootBrowserAccessibilityManager(); + if (manager && manager->delegate() && manager->GetFocus()) { + OnGeneratedEvent(manager->delegate(), + ui::AXEventGenerator::Event::FOCUS_CHANGED, + manager->GetFocus()->GetId()); + } +} + bool AccessibilityNotificationWaiter::IsAboutBlank() { // Skip any accessibility notifications related to "about:blank", // to avoid a possible race condition between the test beginning
diff --git a/content/test/accessibility_browser_test_utils.h b/content/test/accessibility_browser_test_utils.h index 27870b4..f97d70de 100644 --- a/content/test/accessibility_browser_test_utils.h +++ b/content/test/accessibility_browser_test_utils.h
@@ -82,19 +82,25 @@ // Helper to bind the OnAccessibilityEvent callback void BindOnAccessibilityEvent(RenderFrameHostImpl* frame_host); + // Helper to bind the OnGeneratedEvent callback + void BindOnGeneratedEvent(RenderFrameHostImpl* frame_host); + // Callback from RenderViewHostImpl. void OnAccessibilityEvent(RenderFrameHostImpl* rfhi, ax::mojom::Event event, int event_target_id); - // Helper to bind the OnGeneratedEvent callback - void BindOnGeneratedEvent(RenderFrameHostImpl* frame_host); - - // Callback from BrowserAccessibilityManager + // Callback from BrowserAccessibilityManager for all generated events. void OnGeneratedEvent(BrowserAccessibilityDelegate* delegate, ui::AXEventGenerator::Event event, int event_target_id); + // Callback from BrowserAccessibilityManager for the focus changed event. + // + // TODO(982776): Remove this method once we migrate to using AXEventGenerator + // for focus changed events. + void OnFocusChanged(); + // Helper function to determine if the accessibility tree in // GetAXTree() is about the page with the url "about:blank". bool IsAboutBlank(); @@ -105,7 +111,7 @@ int event_target_id_ = 0; RenderFrameHostImpl* event_render_frame_host_ = nullptr; - base::WeakPtrFactory<AccessibilityNotificationWaiter> weak_factory_; + base::WeakPtrFactory<AccessibilityNotificationWaiter> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AccessibilityNotificationWaiter); };
diff --git a/content/test/data/accessibility/event/aria-combo-box-delay-show-list-expected-win.txt b/content/test/data/accessibility/event/aria-combo-box-delay-show-list-expected-win.txt index c00b1f6..55aef2f 100644 --- a/content/test/data/accessibility/event/aria-combo-box-delay-show-list-expected-win.txt +++ b/content/test/data/accessibility/event/aria-combo-box-delay-show-list-expected-win.txt
@@ -1,5 +1,5 @@ EVENT_OBJECT_FOCUS on <li#op1> role=ROLE_SYSTEM_LISTITEM name="Apple" SELECTED,FOCUSED,FOCUSABLE,SELECTABLE PosInSet=1 SetSize=1 -EVENT_OBJECT_HIDE on <body> role=BODY INVISIBLE +EVENT_OBJECT_HIDE on <body> role=BODY IA2_EVENT_ACTIVE_DESCENDANT_CHANGED on <input> role=ROLE_SYSTEM_COMBOBOX EXPANDED,FOCUSABLE,HASPOPUP IA2_STATE_EDITABLE,IA2_STATE_SELECTABLE_TEXT,IA2_STATE_SINGLE_LINE,IA2_STATE_SUPPORTS_AUTOCOMPLETION IA2_EVENT_TEXT_INSERTED on <#document> role=ROLE_SYSTEM_DOCUMENT value~=[doc-url] FOCUSABLE new_text={'<obj><obj>' start=0 end=2} IA2_EVENT_TEXT_REMOVED on <#document> role=ROLE_SYSTEM_DOCUMENT value~=[doc-url] FOCUSABLE old_text={'<obj>' start=0 end=1}
diff --git a/content/test/data/accessibility/event/aria-hidden-changed-expected-uia-win.txt b/content/test/data/accessibility/event/aria-hidden-changed-expected-uia-win.txt deleted file mode 100644 index 073c1f8..0000000 --- a/content/test/data/accessibility/event/aria-hidden-changed-expected-uia-win.txt +++ /dev/null
@@ -1,3 +0,0 @@ -AriaProperties changed on role=heading, name=Item2 -AriaProperties changed on role=heading, name=Item3 -AriaProperties changed on role=heading, name=Item4
diff --git a/content/test/data/accessibility/event/aria-hidden-changed.html b/content/test/data/accessibility/event/aria-hidden-changed.html deleted file mode 100644 index dd97f6c..0000000 --- a/content/test/data/accessibility/event/aria-hidden-changed.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!-- -@UIA-WIN-DENY:* -@UIA-WIN-ALLOW:AriaProperties* ---> -<!DOCTYPE html> -<html> -<body> - <h4 id="d1">Item1</h4> - <h4 id="d2" aria-hidden="true">Item2</h4> - <h4 id="d3" aria-hidden="false">Item3</h4> - <h4 id="d4" aria-hidden="true">Item4</h4> - <script> - function go() { - // Set aria-hidden from [removed]->false; should not fire an event. - document.getElementById('d1').setAttribute('aria-hidden', 'false'); - - // Set aria-hidden from true->false; should fire an event. - document.getElementById('d2').setAttribute('aria-hidden', 'false'); - - // Set aria-hidden from false->true; should fire an event. - document.getElementById('d3').setAttribute('aria-hidden', 'true'); - - // Set aria-hidden from true->[removed]; should fire an event. - document.getElementById('d4').removeAttribute('aria-hidden'); - } - </script> -</body> -</html>
diff --git a/content/test/data/accessibility/event/css-visibility-expected-win.txt b/content/test/data/accessibility/event/css-visibility-expected-win.txt index d522a9a..a267f80 100644 --- a/content/test/data/accessibility/event/css-visibility-expected-win.txt +++ b/content/test/data/accessibility/event/css-visibility-expected-win.txt
@@ -1,4 +1,4 @@ -EVENT_OBJECT_HIDE on <div.a> role=DIV INVISIBLE level=2 +EVENT_OBJECT_HIDE on <div.a> role=DIV level=2 EVENT_OBJECT_REORDER on <div> role=ROLE_SYSTEM_TOOLBAR IA2_STATE_HORIZONTAL EVENT_OBJECT_SHOW on <div.b> role=ROLE_SYSTEM_GROUPING name="Banner" IA2_EVENT_TEXT_INSERTED on <div> role=ROLE_SYSTEM_TOOLBAR IA2_STATE_HORIZONTAL new_text={'<obj>' start=0 end=1}
diff --git a/content/test/data/accessibility/event/expanded-change-expected-uia-win.txt b/content/test/data/accessibility/event/expanded-change-expected-uia-win.txt index 2bfcb1d..be21082 100644 --- a/content/test/data/accessibility/event/expanded-change-expected-uia-win.txt +++ b/content/test/data/accessibility/event/expanded-change-expected-uia-win.txt
@@ -1,7 +1,2 @@ AriaProperties changed on role=link, name=Toggle -AriaProperties changed on role=list -AriaProperties changed on role=listitem -AriaProperties changed on role=listitem -AriaProperties changed on role=listitem -AriaProperties changed on role=listitem ExpandCollapseExpandCollapseState changed on role=link, name=Toggle
diff --git a/content/test/data/accessibility/event/visibility-hidden-changed-expected-uia-win.txt b/content/test/data/accessibility/event/visibility-hidden-changed-expected-uia-win.txt deleted file mode 100644 index b9eeffe..0000000 --- a/content/test/data/accessibility/event/visibility-hidden-changed-expected-uia-win.txt +++ /dev/null
@@ -1,4 +0,0 @@ -AriaProperties changed on role=heading -AriaProperties changed on role=heading -AriaProperties changed on role=heading, name=Item2 -AriaProperties changed on role=heading, name=Item4
diff --git a/content/test/data/accessibility/event/visibility-hidden-changed.html b/content/test/data/accessibility/event/visibility-hidden-changed.html deleted file mode 100644 index 5084bb5..0000000 --- a/content/test/data/accessibility/event/visibility-hidden-changed.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!-- -@UIA-WIN-DENY:* -@UIA-WIN-ALLOW:AriaProperties* ---> -<!DOCTYPE html> -<html> -<body> - <h4 id="d1">Item1</h4> - <h4 id="d2" style="visibility: hidden">Item2</h4> - <h4 id="d3" style="visibility: visible">Item3</h4> - <h4 id="d4" style="visibility: hidden">Item4</h4> - <script> - function go() { - // Set style from [none]->visibility: hidden; should fire an event. - document.getElementById('d1').setAttribute('style', 'visibility: hidden'); - - // Set style from visibility: hidden->visibility: visible; should fire an event. - document.getElementById('d2').setAttribute('style', 'visibility: visible'); - - // Set style from visibility: visible->visibility: hidden; should fire an event. - document.getElementById('d3').setAttribute('style', 'visibility: hidden'); - - // Remove style visibility; should fire an event. - document.getElementById('d4').removeAttribute('style'); - } - </script> -</body> -</html>
diff --git a/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt b/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt index 80a8ef4..76fc0968 100644 --- a/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt +++ b/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt
@@ -456,7 +456,7 @@ crbug.com/733599 [ android ] conformance/textures/video/tex-2d-alpha-alpha-unsigned_byte.html [ RetryOnFailure ] crbug.com/733599 [ android no-angle ] conformance/textures/video/tex-2d-luminance_alpha-luminance_alpha-unsigned_byte.html [ RetryOnFailure ] crbug.com/733599 [ android no-angle ] conformance/textures/video/tex-2d-luminance-luminance-unsigned_byte.html [ RetryOnFailure ] -crbug.com/834933 [ android android-chromium ] conformance/textures/video/tex-2d-rgb-rgb-unsigned_byte.html [ RetryOnFailure ] +crbug.com/834933 [ android no-angle ] conformance/textures/video/tex-2d-rgb-rgb-unsigned_byte.html [ RetryOnFailure ] crbug.com/834933 [ android android-chromium ] conformance/textures/video/tex-2d-rgba-rgba-unsigned_byte.html [ RetryOnFailure ] # This crashes in Android WebView on the Nexus 6, preventing the @@ -577,6 +577,7 @@ crbug.com/845438 [ android ] conformance/glsl/bugs/sketchfab-lighting-shader-crash.html [ RetryOnFailure ] # Android ANGLE GLES +crbug.com/981579 [ android opengles ] conformance/textures/video/tex-2d-rgb-rgb-unsigned_byte.html [ Failure ] crbug.com/906724 [ android opengles ] conformance/textures/video/tex-2d-luminance_alpha-luminance_alpha-unsigned_byte.html [ Failure ] crbug.com/906724 [ android opengles ] conformance/textures/video/tex-2d-luminance-luminance-unsigned_byte.html [ Failure ]
diff --git a/content/test/navigation_simulator_impl.cc b/content/test/navigation_simulator_impl.cc index c9c1eda..320fd6c2 100644 --- a/content/test/navigation_simulator_impl.cc +++ b/content/test/navigation_simulator_impl.cc
@@ -321,8 +321,7 @@ transition_(browser_initiated ? ui::PAGE_TRANSITION_TYPED : ui::PAGE_TRANSITION_LINK), contents_mime_type_("text/html"), - load_url_params_(nullptr), - weak_factory_(this) { + load_url_params_(nullptr) { net::IPAddress address; CHECK(address.AssignFromIPLiteral("2001:db8::1")); remote_endpoint_ = net::IPEndPoint(address, 80);
diff --git a/content/test/navigation_simulator_impl.h b/content/test/navigation_simulator_impl.h index e38f9fb..6802ed4 100644 --- a/content/test/navigation_simulator_impl.h +++ b/content/test/navigation_simulator_impl.h
@@ -337,7 +337,7 @@ mojo::AssociatedInterfaceRequest<mojom::NavigationClient> navigation_client_request_; - base::WeakPtrFactory<NavigationSimulatorImpl> weak_factory_; + base::WeakPtrFactory<NavigationSimulatorImpl> weak_factory_{this}; }; } // namespace content
diff --git a/content/test/navigation_simulator_unittest.cc b/content/test/navigation_simulator_unittest.cc index fdd5c75c..a5d624e6 100644 --- a/content/test/navigation_simulator_unittest.cc +++ b/content/test/navigation_simulator_unittest.cc
@@ -38,9 +38,7 @@ public: TaskRunnerDeferringThrottle(scoped_refptr<base::TaskRunner> task_runner, NavigationHandle* handle) - : NavigationThrottle(handle), - task_runner_(std::move(task_runner)), - weak_factory_(this) {} + : NavigationThrottle(handle), task_runner_(std::move(task_runner)) {} ~TaskRunnerDeferringThrottle() override {} static std::unique_ptr<NavigationThrottle> Create( @@ -72,7 +70,7 @@ return NavigationThrottle::DEFER; } scoped_refptr<base::TaskRunner> task_runner_; - base::WeakPtrFactory<TaskRunnerDeferringThrottle> weak_factory_; + base::WeakPtrFactory<TaskRunnerDeferringThrottle> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TaskRunnerDeferringThrottle); }; @@ -85,7 +83,7 @@ std::tuple<base::Optional<TestNavigationThrottle::ThrottleMethod>, TestNavigationThrottle::ResultSynchrony>> { public: - CancellingNavigationSimulatorTest() : weak_ptr_factory_(this) {} + CancellingNavigationSimulatorTest() {} ~CancellingNavigationSimulatorTest() override {} void SetUp() override { @@ -132,7 +130,8 @@ bool did_finish_navigation_ = false; bool will_fail_request_called_ = false; std::string response_headers_; - base::WeakPtrFactory<CancellingNavigationSimulatorTest> weak_ptr_factory_; + base::WeakPtrFactory<CancellingNavigationSimulatorTest> weak_ptr_factory_{ + this}; private: DISALLOW_COPY_AND_ASSIGN(CancellingNavigationSimulatorTest);
diff --git a/content/test/test_blink_web_unit_test_support.cc b/content/test/test_blink_web_unit_test_support.cc index c449ad4..39d31411 100644 --- a/content/test/test_blink_web_unit_test_support.cc +++ b/content/test/test_blink_web_unit_test_support.cc
@@ -131,8 +131,7 @@ namespace content { TestBlinkWebUnitTestSupport::TestBlinkWebUnitTestSupport( - TestBlinkWebUnitTestSupport::SchedulerType scheduler_type) - : weak_factory_(this) { + TestBlinkWebUnitTestSupport::SchedulerType scheduler_type) { #if defined(OS_MACOSX) base::mac::ScopedNSAutoreleasePool autorelease_pool; #endif
diff --git a/content/test/test_blink_web_unit_test_support.h b/content/test/test_blink_web_unit_test_support.h index 6028bd4..009b610 100644 --- a/content/test/test_blink_web_unit_test_support.h +++ b/content/test/test_blink_web_unit_test_support.h
@@ -92,7 +92,7 @@ std::unique_ptr<blink::scheduler::WebThreadScheduler> main_thread_scheduler_; bool threaded_animation_ = true; - base::WeakPtrFactory<TestBlinkWebUnitTestSupport> weak_factory_; + base::WeakPtrFactory<TestBlinkWebUnitTestSupport> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TestBlinkWebUnitTestSupport); };
diff --git a/docs/media/gpu/video_decoder_test_usage.md b/docs/media/gpu/video_decoder_test_usage.md index bfaba76..f09c117 100644 --- a/docs/media/gpu/video_decoder_test_usage.md +++ b/docs/media/gpu/video_decoder_test_usage.md
@@ -63,8 +63,7 @@ -v enable verbose mode, e.g. -v=2. --vmodule enable verbose mode for the specified module, e.g. --vmodule=*media/gpu*=2. - --disable_validator disable frame validation, useful on old - platforms that don't support import mode. + --disable_validator disable frame validation. --output_frames write all decoded video frames to the "<testname>" folder. --output_folder overwrite the default output folder used when
diff --git a/docs/testing/web_test_expectations.md b/docs/testing/web_test_expectations.md index 41f3dee..d101278 100644 --- a/docs/testing/web_test_expectations.md +++ b/docs/testing/web_test_expectations.md
@@ -266,7 +266,7 @@ * `fast/html/article-element.html` to fail with a text diff (since it is in the fast/html directory). * `fast/html/keygen.html` to pass (since the exact match on the test name). -* `fast/html/submit.html` to pass (since the configuration parameters don't +* `fast/forms/submit.html` to pass (since the configuration parameters don't match). * `fast/html/section-element.html` to either crash or produce a text (or image and text) failure, but not time out or pass.
diff --git a/extensions/browser/api/web_request/web_request_proxying_websocket.cc b/extensions/browser/api/web_request/web_request_proxying_websocket.cc index 7df5ec0c..d6acb13 100644 --- a/extensions/browser/api/web_request/web_request_proxying_websocket.cc +++ b/extensions/browser/api/web_request/web_request_proxying_websocket.cc
@@ -343,24 +343,20 @@ } } + // Here we detect mojo connection errors on |handshake_client|. See also + // CreateWebSocket in //network/services/public/mojom/network_context.mojom. + // Here we don't have |connection_client| so using |handshake_client| is the + // best. network::mojom::WebSocketHandshakeClientPtr handshake_client; binding_as_handshake_client_.Bind(mojo::MakeRequest(&handshake_client)); binding_as_handshake_client_.set_connection_error_handler( base::BindOnce(&WebRequestProxyingWebSocket::OnError, base::Unretained(this), net::ERR_FAILED)); - network::mojom::AuthenticationHandlerPtr auth_handler; binding_as_auth_handler_.Bind(mojo::MakeRequest(&auth_handler)); - binding_as_auth_handler_.set_connection_error_handler( - base::BindOnce(&WebRequestProxyingWebSocket::OnError, - base::Unretained(this), net::ERR_FAILED)); - network::mojom::TrustedHeaderClientPtr trusted_header_client; if (binding_as_header_client_.impl()) { binding_as_header_client_.Bind(mojo::MakeRequest(&trusted_header_client)); - binding_as_header_client_.set_connection_error_handler( - base::BindOnce(&WebRequestProxyingWebSocket::OnError, - base::Unretained(this), net::ERR_FAILED)); } std::move(factory_).Run(info_.url, std::move(additional_headers),
diff --git a/extensions/renderer/api/automation/automation_ax_tree_wrapper.cc b/extensions/renderer/api/automation/automation_ax_tree_wrapper.cc index 5d9b581..af188b4 100644 --- a/extensions/renderer/api/automation/automation_ax_tree_wrapper.cc +++ b/extensions/renderer/api/automation/automation_ax_tree_wrapper.cc
@@ -198,6 +198,7 @@ case ui::AXEventGenerator::Event::DESCRIPTION_CHANGED: case ui::AXEventGenerator::Event::DROPEFFECT_CHANGED: case ui::AXEventGenerator::Event::ENABLED_CHANGED: + case ui::AXEventGenerator::Event::FOCUS_CHANGED: case ui::AXEventGenerator::Event::FLOW_FROM_CHANGED: case ui::AXEventGenerator::Event::FLOW_TO_CHANGED: case ui::AXEventGenerator::Event::GRABBED_CHANGED:
diff --git a/fuchsia/engine/BUILD.gn b/fuchsia/engine/BUILD.gn index 816722a..6877312 100644 --- a/fuchsia/engine/BUILD.gn +++ b/fuchsia/engine/BUILD.gn
@@ -117,12 +117,12 @@ "browser/web_engine_content_browser_client.h", "browser/web_engine_devtools_manager_delegate.cc", "browser/web_engine_devtools_manager_delegate.h", - "browser/web_engine_devtools_socket_factory.cc", - "browser/web_engine_devtools_socket_factory.h", "browser/web_engine_net_log.cc", "browser/web_engine_net_log.h", "browser/web_engine_permission_manager.cc", "browser/web_engine_permission_manager.h", + "browser/web_engine_remote_debugging.cc", + "browser/web_engine_remote_debugging.h", "browser/web_engine_screen.cc", "browser/web_engine_screen.h", "browser/web_engine_url_request_context_getter.cc", @@ -245,6 +245,8 @@ sources = [ "test_debug_listener.cc", "test_debug_listener.h", + "test_devtools_list_fetcher.cc", + "test_devtools_list_fetcher.h", "web_engine_debug_integration_test.cc", "web_engine_integration_test.cc", ]
diff --git a/fuchsia/engine/browser/context_impl.cc b/fuchsia/engine/browser/context_impl.cc index 2c0ae51..b87a3964 100644 --- a/fuchsia/engine/browser/context_impl.cc +++ b/fuchsia/engine/browser/context_impl.cc
@@ -9,32 +9,13 @@ #include <utility> #include "base/fuchsia/fuchsia_logging.h" -#include "base/strings/string_tokenizer.h" #include "content/public/browser/web_contents.h" #include "fuchsia/engine/browser/frame_impl.h" #include "fuchsia/engine/browser/web_engine_browser_context.h" #include "fuchsia/engine/common.h" ContextImpl::ContextImpl(content::BrowserContext* browser_context) - : browser_context_(browser_context) { - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - kRemoteDebuggerHandles)) { - std::string handle_ids_str = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - kRemoteDebuggerHandles); - - // Extract individual handle IDs from the comma-separated list. - base::StringTokenizer tokenizer(handle_ids_str, ","); - while (tokenizer.GetNext()) { - uint32_t handle_id = 0; - if (!base::StringToUint(tokenizer.token(), &handle_id)) - continue; - fidl::InterfacePtr<fuchsia::web::DevToolsPerContextListener> listener; - listener.Bind(zx::channel(zx_take_startup_handle(handle_id))); - devtools_listeners_.AddInterfacePtr(std::move(listener)); - } - } -} + : browser_context_(browser_context) {} ContextImpl::~ContextImpl() = default; @@ -47,17 +28,8 @@ return allow_javascript_injection_; } -void ContextImpl::OnDevToolsPortReady() { - if (devtools_port_ == 0 || devtools_listeners_notified_) - return; - for (auto& listener : devtools_listeners_.ptrs()) { - listener->get()->OnHttpPortOpen(devtools_port_); - } - devtools_listeners_notified_ = true; -} - -void ContextImpl::OnDevToolsPortOpened(uint16_t port) { - devtools_port_ = port; +void ContextImpl::OnDebugDevToolsPortReady() { + web_engine_remote_debugging_.OnDebugDevToolsPortReady(); } void ContextImpl::CreateFrame( @@ -70,6 +42,11 @@ std::move(frame))); } +void ContextImpl::GetRemoteDebuggingPort( + GetRemoteDebuggingPortCallback callback) { + web_engine_remote_debugging_.GetRemoteDebuggingPort(std::move(callback)); +} + FrameImpl* ContextImpl::GetFrameImplForTest(fuchsia::web::FramePtr* frame_ptr) { DCHECK(frame_ptr);
diff --git a/fuchsia/engine/browser/context_impl.h b/fuchsia/engine/browser/context_impl.h index 96ef6a9..cd40610 100644 --- a/fuchsia/engine/browser/context_impl.h +++ b/fuchsia/engine/browser/context_impl.h
@@ -6,12 +6,12 @@ #define FUCHSIA_ENGINE_BROWSER_CONTEXT_IMPL_H_ #include <fuchsia/web/cpp/fidl.h> -#include <lib/fidl/cpp/interface_ptr_set.h> #include <memory> #include <set> #include "base/containers/unique_ptr_adapters.h" #include "base/macros.h" +#include "fuchsia/engine/browser/web_engine_remote_debugging.h" #include "fuchsia/engine/web_engine_export.h" namespace content { @@ -42,15 +42,13 @@ bool IsJavaScriptInjectionAllowed(); // Called by Frames to signal a document has been loaded and signal to the - // |devtools_listeners_| that they can now successfully connect ChromeDriver - // on |devtools_port_|. - void OnDevToolsPortReady(); - - // Signals the DevTools debugging port has been opened. - void OnDevToolsPortOpened(uint16_t port); + // debug listeners in |web_engine_remote_debugging_| that they can now + // successfully connect ChromeDriver. + void OnDebugDevToolsPortReady(); // fuchsia::web::Context implementation. void CreateFrame(fidl::InterfaceRequest<fuchsia::web::Frame> frame) override; + void GetRemoteDebuggingPort(GetRemoteDebuggingPortCallback callback) override; // Gets the underlying FrameImpl service object associated with a connected // |frame_ptr| client. @@ -67,10 +65,7 @@ // destruction when this ContextImpl is destroyed. std::set<std::unique_ptr<FrameImpl>, base::UniquePtrComparator> frames_; - fidl::InterfacePtrSet<fuchsia::web::DevToolsPerContextListener> - devtools_listeners_; - bool devtools_listeners_notified_ = false; - uint16_t devtools_port_ = 0; + WebEngineRemoteDebugging web_engine_remote_debugging_; DISALLOW_COPY_AND_ASSIGN(ContextImpl); };
diff --git a/fuchsia/engine/browser/frame_impl.cc b/fuchsia/engine/browser/frame_impl.cc index 1782787..0793e4d 100644 --- a/fuchsia/engine/browser/frame_impl.cc +++ b/fuchsia/engine/browser/frame_impl.cc
@@ -580,5 +580,5 @@ void FrameImpl::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { - context_->OnDevToolsPortReady(); + context_->OnDebugDevToolsPortReady(); }
diff --git a/fuchsia/engine/browser/web_engine_browser_main_parts.cc b/fuchsia/engine/browser/web_engine_browser_main_parts.cc index fafc7ea..ae98822 100644 --- a/fuchsia/engine/browser/web_engine_browser_main_parts.cc +++ b/fuchsia/engine/browser/web_engine_browser_main_parts.cc
@@ -8,15 +8,12 @@ #include "base/bind_helpers.h" #include "base/command_line.h" -#include "base/files/file_util.h" #include "base/fuchsia/fuchsia_logging.h" #include "base/logging.h" -#include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/render_frame_host.h" #include "content/public/common/main_function_params.h" #include "fuchsia/engine/browser/context_impl.h" #include "fuchsia/engine/browser/web_engine_browser_context.h" -#include "fuchsia/engine/browser/web_engine_devtools_socket_factory.h" #include "fuchsia/engine/browser/web_engine_screen.h" #include "fuchsia/engine/common.h" #include "ui/aura/screen_ozone.h" @@ -54,16 +51,6 @@ context_binding_ = std::make_unique<fidl::Binding<fuchsia::web::Context>>( context_service_.get(), std::move(request_)); - // Start the remote debugging server. - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - kRemoteDebuggerHandles)) { - content::DevToolsAgentHost::StartRemoteDebuggingServer( - std::make_unique<WebEngineDevToolsSocketFactory>( - base::BindRepeating(&ContextImpl::OnDevToolsPortOpened, - base::Unretained(context_service_.get()))), - browser_context_->GetPath(), base::FilePath()); - } - // Quit the browser main loop when the Context connection is dropped. context_binding_->set_error_handler([this](zx_status_t status) { ZX_LOG_IF(ERROR, status != ZX_ERR_PEER_CLOSED, status) @@ -103,11 +90,6 @@ DCHECK(!context_service_); DCHECK(!context_binding_->is_bound()); - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - kRemoteDebuggerHandles)) { - content::DevToolsAgentHost::StopRemoteDebuggingServer(); - } - // These resources must be freed while a MessageLoop is still available, so // that they may post cleanup tasks during teardown. // NOTE: Please destroy objects in the reverse order of their creation.
diff --git a/fuchsia/engine/browser/web_engine_devtools_socket_factory.cc b/fuchsia/engine/browser/web_engine_devtools_socket_factory.cc deleted file mode 100644 index a80d661..0000000 --- a/fuchsia/engine/browser/web_engine_devtools_socket_factory.cc +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "fuchsia/engine/browser/web_engine_devtools_socket_factory.h" -#include "fuchsia/engine/browser/web_engine_browser_context.h" -#include "net/base/net_errors.h" -#include "net/socket/tcp_server_socket.h" - -namespace { - -const int kTcpListenBackLog = 5; - -} // namespace - -WebEngineDevToolsSocketFactory::WebEngineDevToolsSocketFactory( - OnPortOpenedCallback callback) - : callback_(std::move(callback)) {} - -WebEngineDevToolsSocketFactory::~WebEngineDevToolsSocketFactory() = default; - -std::unique_ptr<net::ServerSocket> -WebEngineDevToolsSocketFactory::CreateForHttpServer() { - std::unique_ptr<net::ServerSocket> socket( - new net::TCPServerSocket(nullptr, net::NetLogSource())); - if (socket->Listen(net::IPEndPoint(net::IPAddress::IPv4Localhost(), 0), - kTcpListenBackLog) == net::OK) { - net::IPEndPoint end_point; - socket->GetLocalAddress(&end_point); - callback_.Run(end_point.port()); - return socket; - } - int error = socket->Listen( - net::IPEndPoint(net::IPAddress::IPv6Localhost(), 0), kTcpListenBackLog); - if (error == net::OK) { - net::IPEndPoint end_point; - socket->GetLocalAddress(&end_point); - callback_.Run(end_point.port()); - return socket; - } - LOG(WARNING) << "Failed to start the HTTP debugger service. " - << net::ErrorToString(error); - return nullptr; -} - -std::unique_ptr<net::ServerSocket> -WebEngineDevToolsSocketFactory::CreateForTethering(std::string* out_name) { - return nullptr; -}
diff --git a/fuchsia/engine/browser/web_engine_devtools_socket_factory.h b/fuchsia/engine/browser/web_engine_devtools_socket_factory.h deleted file mode 100644 index e35d933..0000000 --- a/fuchsia/engine/browser/web_engine_devtools_socket_factory.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_DEVTOOLS_SOCKET_FACTORY_H_ -#define FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_DEVTOOLS_SOCKET_FACTORY_H_ - -#include "base/callback.h" -#include "content/public/browser/devtools_socket_factory.h" - -class WebEngineDevToolsSocketFactory : public content::DevToolsSocketFactory { - public: - using OnPortOpenedCallback = base::RepeatingCallback<void(uint16_t)>; - - explicit WebEngineDevToolsSocketFactory(OnPortOpenedCallback callback); - ~WebEngineDevToolsSocketFactory() override; - - // content::DevToolsSocketFactory implementation. - std::unique_ptr<net::ServerSocket> CreateForHttpServer() override; - std::unique_ptr<net::ServerSocket> CreateForTethering( - std::string* out_name) override; - - private: - OnPortOpenedCallback callback_; - - DISALLOW_COPY_AND_ASSIGN(WebEngineDevToolsSocketFactory); -}; - -#endif // FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_DEVTOOLS_SOCKET_FACTORY_H_
diff --git a/fuchsia/engine/browser/web_engine_net_log.cc b/fuchsia/engine/browser/web_engine_net_log.cc index 25b696f6..1de0b49 100644 --- a/fuchsia/engine/browser/web_engine_net_log.cc +++ b/fuchsia/engine/browser/web_engine_net_log.cc
@@ -37,7 +37,7 @@ WebEngineNetLog::WebEngineNetLog(const base::FilePath& log_path) { if (!log_path.empty()) { - net::NetLogCaptureMode capture_mode = net::NetLogCaptureMode::Default(); + net::NetLogCaptureMode capture_mode = net::NetLogCaptureMode::kDefault; file_net_log_observer_ = net::FileNetLogObserver::CreateUnbounded( log_path, GetWebEngineConstants()); file_net_log_observer_->StartObserving(this, capture_mode);
diff --git a/fuchsia/engine/browser/web_engine_remote_debugging.cc b/fuchsia/engine/browser/web_engine_remote_debugging.cc new file mode 100644 index 0000000..b58ff23 --- /dev/null +++ b/fuchsia/engine/browser/web_engine_remote_debugging.cc
@@ -0,0 +1,204 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "fuchsia/engine/browser/web_engine_remote_debugging.h" + +#include "base/bind_helpers.h" +#include "base/command_line.h" +#include "base/files/file_util.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_tokenizer.h" +#include "content/public/browser/devtools_agent_host.h" +#include "content/public/browser/devtools_socket_factory.h" +#include "content/public/common/content_switches.h" +#include "fuchsia/engine/browser/web_engine_browser_context.h" +#include "fuchsia/engine/common.h" +#include "net/base/net_errors.h" +#include "net/base/port_util.h" +#include "net/socket/tcp_server_socket.h" + +namespace { + +class WebEngineDevToolsSocketFactory : public content::DevToolsSocketFactory { + public: + WebEngineDevToolsSocketFactory( + WebEngineRemoteDebugging::OnListenCallback on_listen_callback, + uint16_t port, + bool for_fidl_debug_api) + : on_listen_callback_(std::move(on_listen_callback)), + port_(port), + for_fidl_debug_api_(for_fidl_debug_api) {} + ~WebEngineDevToolsSocketFactory() override = default; + + // content::DevToolsSocketFactory implementation. + std::unique_ptr<net::ServerSocket> CreateForHttpServer() override { + const int kTcpListenBackLog = 5; + std::unique_ptr<net::ServerSocket> socket( + new net::TCPServerSocket(nullptr, net::NetLogSource())); + // When set from the fuchsia.web.Debug API, remote debugging only listens on + // IPv4 localhost, not IPv6. + net::IPEndPoint ip_end_point(for_fidl_debug_api_ + ? net::IPAddress::IPv4Localhost() + : net::IPAddress::IPv6AllZeros(), + port_); + int error = socket->Listen(ip_end_point, kTcpListenBackLog); + if (error != net::OK) { + LOG(WARNING) << "Failed to start the HTTP debugger service. " + << net::ErrorToString(error); + std::move(on_listen_callback_).Run(0); + return nullptr; + } + + net::IPEndPoint end_point; + socket->GetLocalAddress(&end_point); + std::move(on_listen_callback_).Run(end_point.port()); + return socket; + } + + std::unique_ptr<net::ServerSocket> CreateForTethering( + std::string* out_name) override { + return nullptr; + } + + private: + WebEngineRemoteDebugging::OnListenCallback on_listen_callback_; + const uint16_t port_; + const bool for_fidl_debug_api_; + + DISALLOW_COPY_AND_ASSIGN(WebEngineDevToolsSocketFactory); +}; + +} // namespace + +WebEngineRemoteDebugging::WebEngineRemoteDebugging() { + const base::FilePath kDisableActivePortOutputDirectory; + const base::FilePath kDisableDebugOutput; + + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kRemoteDebuggingPort)) { + // Set up DevTools to listen on all network routes on the command-line + // provided port. + base::StringPiece command_line_port_value = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kRemoteDebuggingPort); + int parsed_port = 0; + + // The command-line option can only be provided by the ContextProvider + // process, it should not fail to parse to an int. + DCHECK(base::StringToInt(command_line_port_value, &parsed_port)); + if (parsed_port != 0 && + (!net::IsPortValid(parsed_port) || net::IsWellKnownPort(parsed_port))) { + LOG(WARNING) << "Invalid HTTP debugger service port number " + << command_line_port_value; + OnRemoteDebuggingServiceStatusChanged(0); + return; + } + + content::DevToolsAgentHost::StartRemoteDebuggingServer( + std::make_unique<WebEngineDevToolsSocketFactory>( + base::BindOnce(&WebEngineRemoteDebugging:: + OnRemoteDebuggingServiceStatusChanged, + base::Unretained(this)), + parsed_port, false), + kDisableActivePortOutputDirectory, kDisableDebugOutput); + remote_debugging_enabled_ = true; + } else if (base::CommandLine::ForCurrentProcess()->HasSwitch( + kRemoteDebuggerHandles)) { + // Set up DevTools to listen on localhost on an ephemeral port when + // enabled from the fuchsia.web.Debug API. + content::DevToolsAgentHost::StartRemoteDebuggingServer( + std::make_unique<WebEngineDevToolsSocketFactory>( + base::BindOnce(&WebEngineRemoteDebugging:: + OnRemoteDebuggingServiceStatusChanged, + base::Unretained(this)), + 0, true), + kDisableActivePortOutputDirectory, kDisableDebugOutput); + remote_debugging_enabled_ = true; + + // Initialize the Debug devtools listeners. + debug_devtools_listeners_.emplace(); + std::string handle_ids_str = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + kRemoteDebuggerHandles); + + // Extract individual handle IDs from the comma-separated list. + base::StringTokenizer tokenizer(handle_ids_str, ","); + while (tokenizer.GetNext()) { + uint32_t handle_id = 0; + if (!base::StringToUint(tokenizer.token(), &handle_id)) + continue; + fidl::InterfacePtr<fuchsia::web::DevToolsPerContextListener> listener; + listener.Bind(zx::channel(zx_take_startup_handle(handle_id))); + debug_devtools_listeners_->AddInterfacePtr(std::move(listener)); + } + } else { + OnRemoteDebuggingServiceStatusChanged(0); + } +} + +void WebEngineRemoteDebugging::OnDebugDevToolsPortReady() { + // The DevTools service should have been opened before a Frame navigated. + DCHECK(devtools_port_received_); + + if (debug_devtools_listeners_notified_) + return; + debug_devtools_listeners_notified_ = true; + if (!debug_devtools_listeners_) + return; + + if (devtools_port_ == 0) { + // The DevTools service failed to open. Close the listeners. + debug_devtools_listeners_->CloseAll(); + } else { + for (auto& listener : debug_devtools_listeners_->ptrs()) { + listener->get()->OnHttpPortOpen(devtools_port_); + } + } +} + +void WebEngineRemoteDebugging::GetRemoteDebuggingPort( + GetRemoteDebuggingPortCallback callback) { + pending_callbacks_.push_back(std::move(callback)); + MaybeSendRemoteDebuggingCallbacks(); +} + +WebEngineRemoteDebugging::~WebEngineRemoteDebugging() { + if (remote_debugging_enabled_) + content::DevToolsAgentHost::StopRemoteDebuggingServer(); +} + +void WebEngineRemoteDebugging::OnRemoteDebuggingServiceStatusChanged( + uint16_t port) { + DCHECK(!devtools_port_received_); + devtools_port_ = port; + devtools_port_received_ = true; + MaybeSendRemoteDebuggingCallbacks(); +} + +void WebEngineRemoteDebugging::MaybeSendRemoteDebuggingCallbacks() { + if (!devtools_port_received_) + return; + + std::vector<GetRemoteDebuggingPortCallback> pending_callbacks = + std::move(pending_callbacks_); + + // Signal the pending callbacks and clear the vector. + std::for_each( + pending_callbacks.begin(), pending_callbacks.end(), + [this](GetRemoteDebuggingPortCallback& callback) { + fuchsia::web::Context_GetRemoteDebuggingPort_Result result; + // Do not send the port in case the service was opened for debugging + // and not via CreateContextParams argument. + if (debug_devtools_listeners_ || devtools_port_ == 0) { + result.set_err( + fuchsia::web::ContextError::REMOTE_DEBUGGING_PORT_NOT_OPENED); + } else { + fuchsia::web::Context_GetRemoteDebuggingPort_Response response; + response.port = devtools_port_; + result.set_response(std::move(response)); + } + callback(std::move(result)); + }); + pending_callbacks.clear(); +}
diff --git a/fuchsia/engine/browser/web_engine_remote_debugging.h b/fuchsia/engine/browser/web_engine_remote_debugging.h new file mode 100644 index 0000000..0ac107b --- /dev/null +++ b/fuchsia/engine/browser/web_engine_remote_debugging.h
@@ -0,0 +1,65 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_REMOTE_DEBUGGING_H_ +#define FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_REMOTE_DEBUGGING_H_ + +#include <fuchsia/web/cpp/fidl.h> +#include <lib/fidl/cpp/interface_ptr_set.h> + +#include "base/callback.h" +#include "base/optional.h" + +// Initializes the DevTools service with the information provided on the +// command line. +class WebEngineRemoteDebugging { + public: + using OnListenCallback = base::OnceCallback<void(uint16_t port)>; + using GetRemoteDebuggingPortCallback = + fuchsia::web::Context::GetRemoteDebuggingPortCallback; + + WebEngineRemoteDebugging(); + ~WebEngineRemoteDebugging(); + + // Called by the Context to signal a document has been loaded and signal to + // the |debug_devtools_listeners_| that they can now successfully connect + // ChromeDriver on |devtools_port_|. + void OnDebugDevToolsPortReady(); + + // Actual implementation of the Context.GetRemoteDebuggingPort() FIDL API. + void GetRemoteDebuggingPort(GetRemoteDebuggingPortCallback callback); + + private: + // Signals the remote debugging service status changed. |port| will be set to + // 0 if the service was not open or failed to open. + void OnRemoteDebuggingServiceStatusChanged(uint16_t port); + + void MaybeSendRemoteDebuggingCallbacks(); + + // Set to true if remote debugging was enabled. + bool remote_debugging_enabled_ = false; + + // The remote debugging port, 0 if not set or the service failed to open. + uint16_t devtools_port_ = 0; + + // Set to true once OnRemoteDebuggingServiceStatusChanged() has been called. + // Must only be set once. + bool devtools_port_received_ = false; + + // Pending callbacks for the GetRemoteDebuggingPort() API. + std::vector<GetRemoteDebuggingPortCallback> pending_callbacks_; + + // If remote debugging is enabled via the fuchsia.web.Debug API, holds the + // Debug listeners. + base::Optional< + fidl::InterfacePtrSet<fuchsia::web::DevToolsPerContextListener>> + debug_devtools_listeners_; + + // Set to true once the |debug_devtools_listeners_| have been notified. + bool debug_devtools_listeners_notified_ = false; + + DISALLOW_COPY_AND_ASSIGN(WebEngineRemoteDebugging); +}; + +#endif // FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_REMOTE_DEBUGGING_H_
diff --git a/fuchsia/engine/context_provider_impl.cc b/fuchsia/engine/context_provider_impl.cc index 5d50626..c550ec76 100644 --- a/fuchsia/engine/context_provider_impl.cc +++ b/fuchsia/engine/context_provider_impl.cc
@@ -30,6 +30,7 @@ #include "base/process/launch.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" +#include "content/public/common/content_switches.h" #include "fuchsia/engine/common.h" #include "net/http/http_util.h" #include "services/service_manager/sandbox/fuchsia/sandbox_policy_fuchsia.h" @@ -153,10 +154,14 @@ launch_options.job_handle = job.get(); base::CommandLine launch_command = *base::CommandLine::ForCurrentProcess(); - - // Connect DevTools listeners to the new Context process. std::vector<zx::channel> devtools_listener_channels; - if (devtools_listeners_.size() != 0) { + + if (params.has_remote_debugging_port()) { + launch_command.AppendSwitchNative( + switches::kRemoteDebuggingPort, + base::NumberToString(params.remote_debugging_port())); + } else if (devtools_listeners_.size() != 0) { + // Connect DevTools listeners to the new Context process. std::vector<std::string> handles_ids; for (auto& devtools_listener : devtools_listeners_.ptrs()) { fidl::InterfaceHandle<fuchsia::web::DevToolsPerContextListener>
diff --git a/fuchsia/engine/test_devtools_list_fetcher.cc b/fuchsia/engine/test_devtools_list_fetcher.cc new file mode 100644 index 0000000..0cca898 --- /dev/null +++ b/fuchsia/engine/test_devtools_list_fetcher.cc
@@ -0,0 +1,74 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "fuchsia/engine/test_devtools_list_fetcher.h" + +#include "base/callback.h" +#include "base/json/json_reader.h" +#include "base/macros.h" +#include "base/memory/scoped_refptr.h" +#include "base/run_loop.h" +#include "base/threading/thread_task_runner_handle.h" +#include "net/http/http_status_code.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_fetcher.h" +#include "net/url_request/url_fetcher_delegate.h" +#include "net/url_request/url_request_test_util.h" + +namespace { + +// Utility class to get the JSON value of the list URL for a DevTools service on +// localhost. +class DevToolsListFetcher : public net::URLFetcherDelegate { + public: + DevToolsListFetcher() { + request_context_getter_ = + base::MakeRefCounted<net::TestURLRequestContextGetter>( + base::ThreadTaskRunnerHandle::Get()); + } + ~DevToolsListFetcher() override = default; + + base::Value GetDevToolsListFromPort(uint16_t port) { + std::string url = base::StringPrintf("http://127.0.0.1:%d/json/list", port); + std::unique_ptr<net::URLFetcher> fetcher = net::URLFetcher::Create( + GURL(url), net::URLFetcher::GET, this, TRAFFIC_ANNOTATION_FOR_TESTS); + fetcher->SetRequestContext(request_context_getter_.get()); + fetcher->Start(); + + base::RunLoop run_loop; + on_url_fetch_complete_ack_ = run_loop.QuitClosure(); + run_loop.Run(); + + if (fetcher->GetStatus().status() != net::URLRequestStatus::SUCCESS) + return base::Value(); + + if (fetcher->GetResponseCode() != net::HTTP_OK) + return base::Value(); + + std::string result; + if (!fetcher->GetResponseAsString(&result)) + return base::Value(); + + return base::JSONReader::Read(result).value_or(base::Value()); + } + + private: + // fuchsia::web::URLFetcherDelegate implementation. + void OnURLFetchComplete(const net::URLFetcher* source) override { + DCHECK(on_url_fetch_complete_ack_); + std::move(on_url_fetch_complete_ack_).Run(); + } + + scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_; + base::OnceClosure on_url_fetch_complete_ack_; + + DISALLOW_COPY_AND_ASSIGN(DevToolsListFetcher); +}; + +} // namespace + +base::Value GetDevToolsListFromPort(uint16_t port) { + DevToolsListFetcher devtools_fetcher; + return devtools_fetcher.GetDevToolsListFromPort(port); +}
diff --git a/fuchsia/engine/test_devtools_list_fetcher.h b/fuchsia/engine/test_devtools_list_fetcher.h new file mode 100644 index 0000000..b133cbf4 --- /dev/null +++ b/fuchsia/engine/test_devtools_list_fetcher.h
@@ -0,0 +1,14 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_ENGINE_TEST_DEVTOOLS_LIST_FETCHER_H_ +#define FUCHSIA_ENGINE_TEST_DEVTOOLS_LIST_FETCHER_H_ + +#include "base/values.h" + +// Returns the JSON value of the list URL for the DevTools service listening +// on port |port| on localhost. Returns an empty value on error. +base::Value GetDevToolsListFromPort(uint16_t port); + +#endif // FUCHSIA_ENGINE_TEST_DEVTOOLS_LIST_FETCHER_H_
diff --git a/fuchsia/engine/web_engine_debug_integration_test.cc b/fuchsia/engine/web_engine_debug_integration_test.cc index e8d8766..e70c05b 100644 --- a/fuchsia/engine/web_engine_debug_integration_test.cc +++ b/fuchsia/engine/web_engine_debug_integration_test.cc
@@ -9,19 +9,14 @@ #include "base/files/file_enumerator.h" #include "base/fuchsia/file_utils.h" #include "base/fuchsia/service_directory_client.h" -#include "base/json/json_reader.h" #include "base/macros.h" #include "fuchsia/base/fit_adapter.h" #include "fuchsia/base/frame_test_util.h" #include "fuchsia/base/result_receiver.h" #include "fuchsia/base/test_navigation_listener.h" #include "fuchsia/engine/test_debug_listener.h" -#include "net/http/http_status_code.h" +#include "fuchsia/engine/test_devtools_list_fetcher.h" #include "net/test/embedded_test_server/embedded_test_server.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_fetcher_delegate.h" -#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -30,8 +25,7 @@ } // namespace -class WebEngineDebugIntegrationTest : public testing::Test, - public net::URLFetcherDelegate { +class WebEngineDebugIntegrationTest : public testing::Test { public: WebEngineDebugIntegrationTest() : dev_tools_listener_binding_(&dev_tools_listener_) {} @@ -64,10 +58,6 @@ // callback so the listener will have been added after this call returns. debug_->EnableDevTools(dev_tools_listener_binding_.NewBinding()); - request_context_getter_ = - base::MakeRefCounted<net::TestURLRequestContextGetter>( - message_loop_.task_runner()); - test_server_.ServeFilesFromSourceDirectory(kTestServerRoot); ASSERT_TRUE(test_server_.Start()); } @@ -89,53 +79,18 @@ web_context.NewRequest()); web_context.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); - fuchsia::web::FramePtr web_frame; - web_context->CreateFrame(web_frame.NewRequest()); - web_frame.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); - - fuchsia::web::NavigationControllerPtr nav_controller; - web_frame->GetNavigationController(nav_controller.NewRequest()); - nav_controller.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); - base::RunLoop run_loop; - cr_fuchsia::ResultReceiver<fuchsia::web::NavigationState> result( - run_loop.QuitClosure()); - nav_controller->GetVisibleEntry( - cr_fuchsia::CallbackToFitFunction(result.GetReceiveCallback())); + cr_fuchsia::ResultReceiver< + fuchsia::web::Context_GetRemoteDebuggingPort_Result> + port_receiver(run_loop.QuitClosure()); + web_context->GetRemoteDebuggingPort( + cr_fuchsia::CallbackToFitFunction(port_receiver.GetReceiveCallback())); run_loop.Run(); - // Sanity check, the NavigationState should be empty at this point. - ASSERT_TRUE(result->IsEmpty()); - } - - base::Value GetDevToolsListFromPort(uint16_t port) { - std::string url = base::StringPrintf("http://127.0.0.1:%d/json/list", port); - std::unique_ptr<net::URLFetcher> fetcher = net::URLFetcher::Create( - GURL(url), net::URLFetcher::GET, this, TRAFFIC_ANNOTATION_FOR_TESTS); - fetcher->SetRequestContext(request_context_getter_.get()); - fetcher->Start(); - - base::RunLoop run_loop; - on_url_fetch_complete_ack_ = run_loop.QuitClosure(); - run_loop.Run(); - - if (fetcher->GetStatus().status() != net::URLRequestStatus::SUCCESS) - return base::Value(); - - if (fetcher->GetResponseCode() != net::HTTP_OK) - return base::Value(); - - std::string result; - if (!fetcher->GetResponseAsString(&result)) - return base::Value(); - - return base::JSONReader::Read(result).value_or(base::Value()); - } - - // fuchsia::web::URLFetcherDelegate implementation. - void OnURLFetchComplete(const net::URLFetcher* source) override { - if (on_url_fetch_complete_ack_) - std::move(on_url_fetch_complete_ack_).Run(); + // Sanity check. + ASSERT_TRUE(port_receiver->is_err()); + ASSERT_EQ(port_receiver->err(), + fuchsia::web::ContextError::REMOTE_DEBUGGING_PORT_NOT_OPENED); } base::MessageLoopForIO message_loop_; @@ -146,7 +101,6 @@ fuchsia::web::ContextProviderPtr web_context_provider_; fuchsia::web::DebugSyncPtr debug_; - scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_; base::OnceClosure on_url_fetch_complete_ack_; net::EmbeddedTestServer test_server_; @@ -280,4 +234,4 @@ frame_data2.context.Unbind(); dev_tools_listener_.RunUntilNumberOfPortsIs(0); dev_tools_listener2.RunUntilNumberOfPortsIs(0); -} \ No newline at end of file +}
diff --git a/fuchsia/engine/web_engine_integration_test.cc b/fuchsia/engine/web_engine_integration_test.cc index 08b302d..d2aa6b1 100644 --- a/fuchsia/engine/web_engine_integration_test.cc +++ b/fuchsia/engine/web_engine_integration_test.cc
@@ -6,11 +6,15 @@ #include <lib/fidl/cpp/binding.h> #include "base/fuchsia/file_utils.h" +#include "base/fuchsia/fuchsia_logging.h" #include "base/fuchsia/service_directory_client.h" #include "base/macros.h" #include "base/test/scoped_task_environment.h" +#include "fuchsia/base/fit_adapter.h" #include "fuchsia/base/frame_test_util.h" +#include "fuchsia/base/result_receiver.h" #include "fuchsia/base/test_navigation_listener.h" +#include "fuchsia/engine/test_devtools_list_fetcher.h" #include "net/http/http_request_headers.h" #include "net/test/embedded_test_server/default_handlers.h" #include "net/test/embedded_test_server/embedded_test_server.h" @@ -187,3 +191,60 @@ CreateContextAndExpectError(std::move(create_params), ZX_ERR_INVALID_ARGS); } } + +// Check the remote_debugging_port parameter in CreateContextParams properly +// opens the DevTools service in the created Context. +// Check Context.GetRemoteDebuggingPort() API is not blocking. +TEST_F(WebEngineIntegrationTest, RemoteDebuggingPort) { + fuchsia::web::CreateContextParams create_params; + auto directory = base::fuchsia::OpenDirectory( + base::FilePath(base::fuchsia::kServiceDirectoryPath)); + ASSERT_TRUE(directory.is_valid()); + create_params.set_service_directory(std::move(directory)); + create_params.set_remote_debugging_port(0); + + // Create Context, Frame and NavigationController. + fuchsia::web::ContextPtr web_context; + web_context_provider_->Create(std::move(create_params), + web_context.NewRequest()); + web_context.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); + + // Get the remote debugging port early, to ensure this is not blocking. + base::RunLoop run_loop; + cr_fuchsia::ResultReceiver< + fuchsia::web::Context_GetRemoteDebuggingPort_Result> + port_receiver(run_loop.QuitClosure()); + web_context->GetRemoteDebuggingPort( + cr_fuchsia::CallbackToFitFunction(port_receiver.GetReceiveCallback())); + run_loop.Run(); + + ASSERT_TRUE(port_receiver->is_response()); + uint16_t remote_debugging_port = port_receiver->response().port; + ASSERT_TRUE(remote_debugging_port != 0); + + fuchsia::web::FramePtr web_frame; + web_context->CreateFrame(web_frame.NewRequest()); + web_frame.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); + + fuchsia::web::NavigationControllerPtr nav_controller; + web_frame->GetNavigationController(nav_controller.NewRequest()); + nav_controller.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); + + cr_fuchsia::TestNavigationListener navigation_listener; + fidl::Binding<fuchsia::web::NavigationEventListener> listener_binding( + &navigation_listener); + web_frame->SetNavigationEventListener(listener_binding.NewBinding()); + + GURL url = embedded_test_server_.GetURL("/defaultresponse"); + ASSERT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( + nav_controller.get(), fuchsia::web::LoadUrlParams(), url.spec())); + navigation_listener.RunUntilUrlEquals(url); + + base::Value devtools_list = GetDevToolsListFromPort(remote_debugging_port); + ASSERT_TRUE(devtools_list.is_list()); + EXPECT_EQ(devtools_list.GetList().size(), 1u); + + base::Value* devtools_url = devtools_list.GetList()[0].FindPath("url"); + ASSERT_TRUE(devtools_url->is_string()); + EXPECT_EQ(devtools_url->GetString(), url); +}
diff --git a/google_apis/gcm/tools/mcs_probe.cc b/google_apis/gcm/tools/mcs_probe.cc index c566116..8585317 100644 --- a/google_apis/gcm/tools/mcs_probe.cc +++ b/google_apis/gcm/tools/mcs_probe.cc
@@ -335,7 +335,7 @@ base::FilePath log_path = command_line_.GetSwitchValuePath(kLogFileSwitch); logger_ = net::FileNetLogObserver::CreateUnbounded(log_path, nullptr); net::NetLogCaptureMode capture_mode = - net::NetLogCaptureMode::IncludeCookiesAndCredentials(); + net::NetLogCaptureMode::kIncludeSensitive; logger_->StartObserving(&net_log_, capture_mode); }
diff --git a/gpu/ipc/common/android/surface_owner_android.cc b/gpu/ipc/common/android/surface_owner_android.cc index 7a77b45..9faa7a4 100644 --- a/gpu/ipc/common/android/surface_owner_android.cc +++ b/gpu/ipc/common/android/surface_owner_android.cc
@@ -102,7 +102,12 @@ // Set the width, height and format to some default value. This parameters // are/maybe overriden by the producer sending buffers to this imageReader's // Surface. - int32_t width = 1, height = 1, max_images = 3; + // Note that max_images should be as small as possible to limit the memory + // usage. ImageReader needs 2 images to mimic the behavior of SurfaceTexture. + // Also note that we always acquire an image before deleting the + // previous acquired image. This causes 2 acquired images to be in flight at + // the image acquisition point until the previous image is deleted. + int32_t width = 1, height = 1, max_images = 2; AIMAGE_FORMATS format = AIMAGE_FORMAT_YUV_420_888; AImageReader* reader = nullptr; // The usage flag below should be used when the buffer will be read from by @@ -194,7 +199,12 @@ // This method duplicates the fence file descriptor and the caller is // responsible for closing the returend file descriptor. - return_code = loader_.AImageReader_acquireLatestImageAsync( + // We now use AcquireNextImageAsync() instead of AcquireLatestImageAsync() + // because AcquireLatestImageAsync() only works when + // max_images-number_of_acquired_images >= 2. This is now not true for our + // AImageReader use case with max_images=2 since we always have one previously + // acquired image when we try to acquire a new image. + return_code = loader_.AImageReader_acquireNextImageAsync( image_reader_, &image, &acquire_fence_fd); // Log the error return code.
diff --git a/infra/config/cr-buildbucket.cfg b/infra/config/cr-buildbucket.cfg index 4fe6927..87e1800 100644 --- a/infra/config/cr-buildbucket.cfg +++ b/infra/config/cr-buildbucket.cfg
@@ -4079,6 +4079,8 @@ mixins: "builderless" mixins: "linux-try" name: "linux-ozone-rel" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "linux-try" @@ -4117,6 +4119,8 @@ builders { mixins: "linux-try" mixins: "goma-rbe-prod" + mixins: "linux-xenial" + mixins: "builderless" name: "linux_chromium_cfi_rel_ng" dimensions: "cores:32" }
diff --git a/ios/chrome/browser/BUILD.gn b/ios/chrome/browser/BUILD.gn index 4bd9d92..b5981b3 100644 --- a/ios/chrome/browser/BUILD.gn +++ b/ios/chrome/browser/BUILD.gn
@@ -55,8 +55,6 @@ "installation_notifier.mm", "ios_chrome_field_trials.cc", "ios_chrome_field_trials.h", - "ios_chrome_flag_descriptions.cc", - "ios_chrome_flag_descriptions.h", "ios_chrome_io_thread.h", "ios_chrome_io_thread.mm", "ios_first_run_field_trials.cc",
diff --git a/ios/chrome/browser/OWNERS b/ios/chrome/browser/OWNERS index 9244a78..5f6cbd92 100644 --- a/ios/chrome/browser/OWNERS +++ b/ios/chrome/browser/OWNERS
@@ -2,8 +2,5 @@ per-file ios_chrome_io_thread*=rch@chromium.org per-file ios_chrome_io_thread*=rsleevi@chromium.org -# Only for adding and removing flags. -per-file ios_chrome_flag_descriptions.*=* - # TEAM: ios-directory-owners@chromium.org # OS: iOS
diff --git a/ios/chrome/browser/browser_state/chrome_browser_state_io_data.mm b/ios/chrome/browser/browser_state/chrome_browser_state_io_data.mm index 2dc3350..5d5b586 100644 --- a/ios/chrome/browser/browser_state/chrome_browser_state_io_data.mm +++ b/ios/chrome/browser/browser_state/chrome_browser_state_io_data.mm
@@ -32,7 +32,7 @@ #include "components/net_log/chrome_net_log.h" #include "components/prefs/pref_service.h" #include "components/proxy_config/ios/proxy_service_factory.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/chrome_url_constants.h"
diff --git a/ios/chrome/browser/browser_state_metrics/browser_state_metrics.cc b/ios/chrome/browser/browser_state_metrics/browser_state_metrics.cc index dbb1f4e..583fd1e 100644 --- a/ios/chrome/browser/browser_state_metrics/browser_state_metrics.cc +++ b/ios/chrome/browser/browser_state_metrics/browser_state_metrics.cc
@@ -6,9 +6,11 @@ #include <stddef.h> +#include "components/profile_metrics/browser_profile_type.h" #include "components/profile_metrics/counts.h" #include "ios/chrome/browser/browser_state/browser_state_info_cache.h" #include "ios/chrome/browser/browser_state/chrome_browser_state_manager.h" +#include "ios/web/public/browser_state.h" bool CountBrowserStateInformation(ios::ChromeBrowserStateManager* manager, profile_metrics::Counts* counts) { @@ -35,3 +37,10 @@ CountBrowserStateInformation(manager, &counts); profile_metrics::LogProfileMetricsCounts(counts); } + +profile_metrics::BrowserProfileType GetBrowserStateType( + web::BrowserState* browser_state) { + return browser_state->IsOffTheRecord() + ? profile_metrics::BrowserProfileType::kIncognito + : profile_metrics::BrowserProfileType::kRegular; +} \ No newline at end of file
diff --git a/ios/chrome/browser/browser_state_metrics/browser_state_metrics.h b/ios/chrome/browser/browser_state_metrics/browser_state_metrics.h index 397c93c..95d36b5 100644 --- a/ios/chrome/browser/browser_state_metrics/browser_state_metrics.h +++ b/ios/chrome/browser/browser_state_metrics/browser_state_metrics.h
@@ -11,6 +11,11 @@ namespace profile_metrics { struct Counts; +enum class BrowserProfileType; +} // namespace profile_metrics + +namespace web { +class BrowserState; } // Counts and returns summary information about the browser states currently in @@ -21,4 +26,7 @@ void LogNumberOfBrowserStates(ios::ChromeBrowserStateManager* manager); +profile_metrics::BrowserProfileType GetBrowserStateType( + web::BrowserState* browser_state); + #endif // IOS_CHROME_BROWSER_BROWSER_STATE_METRICS_BROWSER_STATE_METRICS_H_
diff --git a/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm b/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm index 2ae8a28..7cf81c08 100644 --- a/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm +++ b/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm
@@ -35,8 +35,8 @@ #include "components/prefs/pref_service.h" #include "components/search_engines/template_url_service.h" #include "components/sessions/core/tab_restore_service.h" -#include "components/signin/core/browser/signin_pref_names.h" #include "components/signin/ios/browser/account_consistency_service.h" +#include "components/signin/public/base/signin_pref_names.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/autofill/personal_data_manager_factory.h" #include "ios/chrome/browser/autofill/strike_database_factory.h"
diff --git a/ios/chrome/browser/flags/BUILD.gn b/ios/chrome/browser/flags/BUILD.gn index 576cbab..e0f76b6 100644 --- a/ios/chrome/browser/flags/BUILD.gn +++ b/ios/chrome/browser/flags/BUILD.gn
@@ -7,6 +7,8 @@ sources = [ "about_flags.h", "about_flags.mm", + "ios_chrome_flag_descriptions.cc", + "ios_chrome_flag_descriptions.h", ] deps = [ @@ -27,7 +29,7 @@ "//components/security_state/core", "//components/send_tab_to_self", "//components/signin/core/browser", - "//components/signin/core/browser:shared", + "//components/signin/public/base", "//components/strings:components_strings", "//components/sync/driver", "//components/translate/core/browser",
diff --git a/ios/chrome/browser/flags/OWNERS b/ios/chrome/browser/flags/OWNERS index 7352d8d..87d44989 100644 --- a/ios/chrome/browser/flags/OWNERS +++ b/ios/chrome/browser/flags/OWNERS
@@ -1,4 +1,6 @@ +# Only for adding and removing flags. per-file about_flags.*=* +per-file ios_chrome_flag_descriptions.*=* # TEAM: ios-directory-owners@chromium.org # OS: iOS
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index b5d214c2a..b60d318f 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -41,7 +41,7 @@ #include "components/security_state/core/features.h" #include "components/send_tab_to_self/features.h" #include "components/signin/core/browser/account_reconcilor.h" -#include "components/signin/core/browser/signin_switches.h" +#include "components/signin/public/base/signin_switches.h" #include "components/strings/grit/components_strings.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/translate/core/browser/translate_prefs.h" @@ -53,7 +53,7 @@ #include "ios/chrome/browser/crash_report/crash_report_flags.h" #include "ios/chrome/browser/drag_and_drop/drag_and_drop_flag.h" #include "ios/chrome/browser/find_in_page/features.h" -#include "ios/chrome/browser/ios_chrome_flag_descriptions.h" +#include "ios/chrome/browser/flags/ios_chrome_flag_descriptions.h" #include "ios/chrome/browser/passwords/password_manager_features.h" #include "ios/chrome/browser/reading_list/features.h" #include "ios/chrome/browser/signin/feature_flags.h"
diff --git a/ios/chrome/browser/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc similarity index 99% rename from ios/chrome/browser/ios_chrome_flag_descriptions.cc rename to ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc index b130756b..f6bb7c8 100644 --- a/ios/chrome/browser/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ios/chrome/browser/ios_chrome_flag_descriptions.h" +#include "ios/chrome/browser/flags/ios_chrome_flag_descriptions.h" // This file declares strings used in chrome://flags. These messages are not // translated, because instead of end-users they target Chromium developers and
diff --git a/ios/chrome/browser/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h similarity index 98% rename from ios/chrome/browser/ios_chrome_flag_descriptions.h rename to ios/chrome/browser/flags/ios_chrome_flag_descriptions.h index 9a61e50..1d84891 100644 --- a/ios/chrome/browser/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.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 IOS_CHROME_BROWSER_IOS_CHROME_FLAG_DESCRIPTIONS_H_ -#define IOS_CHROME_BROWSER_IOS_CHROME_FLAG_DESCRIPTIONS_H_ +#ifndef IOS_CHROME_BROWSER_FLAGS_IOS_CHROME_FLAG_DESCRIPTIONS_H_ +#define IOS_CHROME_BROWSER_FLAGS_IOS_CHROME_FLAG_DESCRIPTIONS_H_ // Please add names and descriptions in alphabetical order. @@ -407,4 +407,4 @@ } // namespace flag_descriptions -#endif // IOS_CHROME_BROWSER_IOS_CHROME_FLAG_DESCRIPTIONS_H_ +#endif // IOS_CHROME_BROWSER_FLAGS_IOS_CHROME_FLAG_DESCRIPTIONS_H_
diff --git a/ios/chrome/browser/prefs/browser_prefs.mm b/ios/chrome/browser/prefs/browser_prefs.mm index 1152433..7dd017b 100644 --- a/ios/chrome/browser/prefs/browser_prefs.mm +++ b/ios/chrome/browser/prefs/browser_prefs.mm
@@ -35,7 +35,7 @@ #include "components/rappor/rappor_service_impl.h" #include "components/search_engines/template_url_prepopulate_data.h" #include "components/sessions/core/session_id_generator.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/strings/grit/components_locale_settings.h" #include "components/sync/base/sync_prefs.h"
diff --git a/ios/chrome/browser/signin/BUILD.gn b/ios/chrome/browser/signin/BUILD.gn index 5149c316..1819e4f 100644 --- a/ios/chrome/browser/signin/BUILD.gn +++ b/ios/chrome/browser/signin/BUILD.gn
@@ -119,8 +119,8 @@ "//components/image_fetcher/core:test_support", "//components/keyed_service/core", "//components/signin/core/browser", - "//components/signin/core/browser:internals_test_support", "//components/signin/ios/browser", + "//components/signin/public/base:test_support", "//components/signin/public/identity_manager:test_support", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/browser_state:test_support", @@ -148,9 +148,9 @@ "//components/pref_registry", "//components/prefs", "//components/signin/core/browser", - "//components/signin/core/browser:internals_test_support", "//components/signin/ios/browser", "//components/signin/ios/browser:test_support", + "//components/signin/public/base:test_support", "//components/signin/public/identity_manager", "//components/signin/public/identity_manager:test_support", "//components/sync:test_support",
diff --git a/ios/chrome/browser/signin/authentication_service.h b/ios/chrome/browser/signin/authentication_service.h index d7d8b410..695d3b774 100644 --- a/ios/chrome/browser/signin/authentication_service.h +++ b/ios/chrome/browser/signin/authentication_service.h
@@ -13,7 +13,7 @@ #include "base/scoped_observer.h" #include "components/keyed_service/core/keyed_service.h" #include "components/pref_registry/pref_registry_syncable.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "ios/public/provider/chrome/browser/signin/chrome_identity_service.h"
diff --git a/ios/chrome/browser/signin/authentication_service.mm b/ios/chrome/browser/signin/authentication_service.mm index 5bd7b1d..3a7a83f 100644 --- a/ios/chrome/browser/signin/authentication_service.mm +++ b/ios/chrome/browser/signin/authentication_service.mm
@@ -13,7 +13,8 @@ #include "base/threading/thread_task_runner_handle.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" +#include "components/signin/public/identity_manager/device_accounts_synchronizer.h" #import "components/signin/public/identity_manager/primary_account_mutator.h" #include "components/sync/driver/sync_service.h" #include "components/sync/driver/sync_user_settings.h" @@ -160,11 +161,17 @@ // Clear signin errors on the accounts that had a specific MDM device status. // This will trigger services to fetch data for these accounts again. - std::map<std::string, NSDictionary*> cached_mdm_infos(cached_mdm_infos_); - cached_mdm_infos_.clear(); - for (const auto& cached_mdm_info : cached_mdm_infos) { - // TODO(crbug.com/930094): Eliminate this. - identity_manager_->LegacyAddAccountFromSystem(cached_mdm_info.first); + using std::swap; + std::map<std::string, NSDictionary*> cached_mdm_infos; + swap(cached_mdm_infos_, cached_mdm_infos); + + if (!cached_mdm_infos.empty()) { + identity::DeviceAccountsSynchronizer* device_accounts_synchronizer = + identity_manager_->GetDeviceAccountsSynchronizer(); + for (const auto& cached_mdm_info : cached_mdm_infos) { + device_accounts_synchronizer->ReloadAccountFromSystem( + cached_mdm_info.first); + } } } @@ -301,7 +308,8 @@ // Load all credentials from SSO library. This must load the credentials // for the primary account too. - identity_manager_->LegacyReloadAccountsFromSystem(); + identity_manager_->GetDeviceAccountsSynchronizer() + ->ReloadAllAccountsFromSystem(); // Ensure that the account the user is trying to sign into has been loaded // from the SSO library and that hosted_domain is set to the provided value. @@ -531,8 +539,8 @@ HandleForgottenIdentity(nil, should_prompt); if (IsAuthenticated()) { - // TODO(crbug.com/930094): Eliminate this. - identity_manager_->LegacyReloadAccountsFromSystem(); + identity_manager_->GetDeviceAccountsSynchronizer() + ->ReloadAllAccountsFromSystem(); } }
diff --git a/ios/chrome/browser/signin/authentication_service_factory.h b/ios/chrome/browser/signin/authentication_service_factory.h index 32331534..67fda04 100644 --- a/ios/chrome/browser/signin/authentication_service_factory.h +++ b/ios/chrome/browser/signin/authentication_service_factory.h
@@ -38,6 +38,10 @@ ios::ChromeBrowserState* browser_state, std::unique_ptr<AuthenticationServiceDelegate> delegate); + // Returns the default factory used to build AuthenticationServices. Can be + // registered with SetTestingFactory to use real instances during testing. + static TestingFactory GetDefaultFactory(); + private: friend class base::NoDestructor<AuthenticationServiceFactory>;
diff --git a/ios/chrome/browser/signin/authentication_service_factory.mm b/ios/chrome/browser/signin/authentication_service_factory.mm index a436d2b..059a178e 100644 --- a/ios/chrome/browser/signin/authentication_service_factory.mm +++ b/ios/chrome/browser/signin/authentication_service_factory.mm
@@ -20,6 +20,21 @@ #error "This file requires ARC support." #endif +namespace { + +std::unique_ptr<KeyedService> BuildAuthenticationService( + web::BrowserState* context) { + ios::ChromeBrowserState* browser_state = + ios::ChromeBrowserState::FromBrowserState(context); + return std::make_unique<AuthenticationService>( + browser_state->GetPrefs(), + SyncSetupServiceFactory::GetForBrowserState(browser_state), + IdentityManagerFactory::GetForBrowserState(browser_state), + ProfileSyncServiceFactory::GetForBrowserState(browser_state)); +} + +} // namespace + // static AuthenticationService* AuthenticationServiceFactory::GetForBrowserState( ios::ChromeBrowserState* browser_state) { @@ -45,6 +60,12 @@ service->Initialize(std::move(delegate)); } +// static +AuthenticationServiceFactory::TestingFactory +AuthenticationServiceFactory::GetDefaultFactory() { + return base::BindRepeating(&BuildAuthenticationService); +} + AuthenticationServiceFactory::AuthenticationServiceFactory() : BrowserStateKeyedServiceFactory( "AuthenticationService", @@ -59,13 +80,7 @@ std::unique_ptr<KeyedService> AuthenticationServiceFactory::BuildServiceInstanceFor( web::BrowserState* context) const { - ios::ChromeBrowserState* browser_state = - ios::ChromeBrowserState::FromBrowserState(context); - return std::make_unique<AuthenticationService>( - browser_state->GetPrefs(), - SyncSetupServiceFactory::GetForBrowserState(browser_state), - IdentityManagerFactory::GetForBrowserState(browser_state), - ProfileSyncServiceFactory::GetForBrowserState(browser_state)); + return BuildAuthenticationService(context); } void AuthenticationServiceFactory::RegisterBrowserStatePrefs(
diff --git a/ios/chrome/browser/signin/authentication_service_unittest.mm b/ios/chrome/browser/signin/authentication_service_unittest.mm index 42711f4..066b7956 100644 --- a/ios/chrome/browser/signin/authentication_service_unittest.mm +++ b/ios/chrome/browser/signin/authentication_service_unittest.mm
@@ -6,13 +6,15 @@ #include "base/bind.h" #include "base/run_loop.h" +#include "base/scoped_observer.h" #include "base/strings/sys_string_conversions.h" #include "components/keyed_service/core/service_access_type.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_registry_simple.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" +#include "components/signin/public/identity_manager/device_accounts_synchronizer.h" #include "components/signin/public/identity_manager/identity_manager.h" -#import "components/signin/public/identity_manager/identity_test_environment.h" +#include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/sync/driver/mock_sync_service.h" #include "components/sync_preferences/pref_service_mock_factory.h" #include "components/sync_preferences/pref_service_syncable.h" @@ -27,14 +29,12 @@ #import "ios/chrome/browser/signin/authentication_service_delegate_fake.h" #import "ios/chrome/browser/signin/authentication_service_factory.h" #import "ios/chrome/browser/signin/identity_manager_factory.h" -#import "ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.h" #include "ios/chrome/browser/signin/ios_chrome_signin_client.h" #include "ios/chrome/browser/signin/signin_client_factory.h" #include "ios/chrome/browser/sync/profile_sync_service_factory.h" #include "ios/chrome/browser/sync/sync_setup_service_factory.h" #include "ios/chrome/browser/sync/sync_setup_service_mock.h" #include "ios/chrome/browser/system_flags.h" -#include "ios/chrome/test/ios_chrome_scoped_testing_chrome_browser_state_manager.h" #include "ios/public/provider/chrome/browser/chrome_browser_provider.h" #import "ios/public/provider/chrome/browser/signin/chrome_identity.h" #import "ios/public/provider/chrome/browser/signin/fake_chrome_identity_service.h" @@ -63,7 +63,6 @@ : IOSChromeSigninClient(browser_state, cookie_settings, host_content_settings_map) {} - ~FakeSigninClient() override {} }; std::unique_ptr<KeyedService> BuildFakeTestSigninClient( @@ -89,26 +88,40 @@ ProfileSyncServiceFactory::GetForBrowserState(browser_state)); } +class TestIdentityManagerObserver : public identity::IdentityManager::Observer { + public: + TestIdentityManagerObserver(identity::IdentityManager* identity_manager) + : scoped_observer_(this) { + DCHECK(identity_manager); + scoped_observer_.Add(identity_manager); + } + + TestIdentityManagerObserver(const TestIdentityManagerObserver&) = delete; + TestIdentityManagerObserver& operator=(const TestIdentityManagerObserver&) = + delete; + + int refresh_token_available_count() const { + return refresh_token_available_count_; + } + + // IdentityManager::Observer + void OnRefreshTokenUpdatedForAccount( + const CoreAccountInfo& account_info) override { + refresh_token_available_count_++; + } + + private: + int refresh_token_available_count_ = 0; + ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + scoped_observer_; +}; + } // namespace -class AuthenticationServiceTest : public PlatformTest, - public identity::IdentityManager::Observer { +class AuthenticationServiceTest : public PlatformTest { protected: - AuthenticationServiceTest() - : scoped_browser_state_manager_( - std::make_unique<TestChromeBrowserStateManager>(base::FilePath())), - refresh_token_available_count_(0) {} - - void SetUp() override { - PlatformTest::SetUp(); - - identity_service_ = - ios::FakeChromeIdentityService::GetInstanceFromChromeProvider(); - identity_service_->AddIdentities(@[ @"foo", @"foo2" ]); - identity_ = - [identity_service_->GetAllIdentitiesSortedForDisplay() objectAtIndex:0]; - identity2_ = - [identity_service_->GetAllIdentitiesSortedForDisplay() objectAtIndex:1]; + AuthenticationServiceTest() { + identity_service()->AddIdentities(@[ @"foo", @"foo2" ]); TestChromeBrowserState::Builder builder; builder.SetPrefService(CreatePrefService()); @@ -118,25 +131,15 @@ base::BindRepeating(&BuildMockSyncService)); builder.AddTestingFactory(SyncSetupServiceFactory::GetInstance(), base::BindRepeating(&BuildMockSyncSetupService)); - builder.SetPrefService(CreatePrefService()); + builder.AddTestingFactory( + AuthenticationServiceFactory::GetInstance(), + AuthenticationServiceFactory::GetDefaultFactory()); - // This test requires usage of the production iOS TokenService delegate, - // as the production AuthenticationService class assumes the presence of - // this delegate. - browser_state_ = IdentityTestEnvironmentChromeBrowserStateAdaptor:: - CreateChromeBrowserStateForIdentityTestEnvironment( - builder, /*use_ios_token_service_delegate=*/true); + browser_state_ = builder.Build(); - identity_test_environment_adaptor_ = - std::make_unique<IdentityTestEnvironmentChromeBrowserStateAdaptor>( - browser_state_.get()); - - mock_sync_service_ = static_cast<syncer::MockSyncService*>( - ProfileSyncServiceFactory::GetForBrowserState(browser_state_.get())); - sync_setup_service_mock_ = static_cast<SyncSetupServiceMock*>( - SyncSetupServiceFactory::GetForBrowserState(browser_state_.get())); - CreateAuthenticationService(); - identity_manager()->AddObserver(this); + AuthenticationServiceFactory::CreateAndInitializeForBrowserState( + browser_state_.get(), + std::make_unique<AuthenticationServiceDelegateFake>()); } std::unique_ptr<sync_preferences::PrefServiceSyncable> CreatePrefService() { @@ -149,132 +152,115 @@ return prefs; } - void TearDown() override { - identity_manager()->RemoveObserver(this); - identity_test_environment_adaptor_.reset(); - authentication_service_->Shutdown(); - authentication_service_.reset(); - browser_state_.reset(); - PlatformTest::TearDown(); - } - void SetExpectationsForSignIn() { - EXPECT_CALL(*mock_sync_service_->GetMockUserSettings(), + EXPECT_CALL(*mock_sync_service()->GetMockUserSettings(), SetSyncRequested(true)); - EXPECT_CALL(*sync_setup_service_mock_, PrepareForFirstSyncSetup()); - } - - void CreateAuthenticationService() { - if (authentication_service_.get()) { - authentication_service_->Shutdown(); - } - authentication_service_ = std::make_unique<AuthenticationService>( - browser_state_->GetPrefs(), - SyncSetupServiceFactory::GetForBrowserState(browser_state_.get()), - IdentityManagerFactory::GetForBrowserState(browser_state_.get()), - ProfileSyncServiceFactory::GetForBrowserState(browser_state_.get())); - authentication_service_->Initialize( - std::make_unique<AuthenticationServiceDelegateFake>()); + EXPECT_CALL(*sync_setup_service_mock(), PrepareForFirstSyncSetup()); } void StoreAccountsInPrefs() { - authentication_service_->StoreAccountsInPrefs(); + authentication_service()->StoreAccountsInPrefs(); } void MigrateAccountsStoredInPrefsIfNeeded() { - authentication_service_->MigrateAccountsStoredInPrefsIfNeeded(); + authentication_service()->MigrateAccountsStoredInPrefsIfNeeded(); } std::vector<std::string> GetAccountsInPrefs() { - return authentication_service_->GetAccountsInPrefs(); + return authentication_service()->GetAccountsInPrefs(); } void FireApplicationWillEnterForeground() { - authentication_service_->OnApplicationWillEnterForeground(); + authentication_service()->OnApplicationWillEnterForeground(); } void FireApplicationDidEnterBackground() { - authentication_service_->OnApplicationDidEnterBackground(); + authentication_service()->OnApplicationDidEnterBackground(); } void FireAccessTokenRefreshFailed(ChromeIdentity* identity, NSDictionary* user_info) { - authentication_service_->OnAccessTokenRefreshFailed(identity, user_info); + authentication_service()->OnAccessTokenRefreshFailed(identity, user_info); } void FireIdentityListChanged() { - authentication_service_->OnIdentityListChanged(); + authentication_service()->OnIdentityListChanged(); } void SetCachedMDMInfo(ChromeIdentity* identity, NSDictionary* user_info) { - authentication_service_ + authentication_service() ->cached_mdm_infos_[base::SysNSStringToUTF8([identity gaiaID])] = user_info; } bool HasCachedMDMInfo(ChromeIdentity* identity) { - return authentication_service_->cached_mdm_infos_.count( + return authentication_service()->cached_mdm_infos_.count( base::SysNSStringToUTF8([identity gaiaID])) > 0; } - // IdentityManager::Observer - void OnRefreshTokenUpdatedForAccount( - const CoreAccountInfo& account_info) override { - refresh_token_available_count_++; + AuthenticationService* authentication_service() { + return AuthenticationServiceFactory::GetForBrowserState( + browser_state_.get()); } identity::IdentityManager* identity_manager() { - return identity_test_env()->identity_manager(); + return IdentityManagerFactory::GetForBrowserState(browser_state_.get()); } - identity::IdentityTestEnvironment* identity_test_env() { - return identity_test_environment_adaptor_->identity_test_env(); + ios::FakeChromeIdentityService* identity_service() { + return ios::FakeChromeIdentityService::GetInstanceFromChromeProvider(); + } + + syncer::MockSyncService* mock_sync_service() { + return static_cast<syncer::MockSyncService*>( + ProfileSyncServiceFactory::GetForBrowserState(browser_state_.get())); + } + + SyncSetupServiceMock* sync_setup_service_mock() { + return static_cast<SyncSetupServiceMock*>( + SyncSetupServiceFactory::GetForBrowserState(browser_state_.get())); + } + + ChromeIdentity* identity(NSUInteger index) { + return [identity_service()->GetAllIdentitiesSortedForDisplay() + objectAtIndex:index]; } web::TestWebThreadBundle thread_bundle_; - IOSChromeScopedTestingChromeBrowserStateManager scoped_browser_state_manager_; std::unique_ptr<TestChromeBrowserState> browser_state_; - ios::FakeChromeIdentityService* identity_service_; - syncer::MockSyncService* mock_sync_service_; - SyncSetupServiceMock* sync_setup_service_mock_; - std::unique_ptr<AuthenticationService> authentication_service_; - std::unique_ptr<IdentityTestEnvironmentChromeBrowserStateAdaptor> - identity_test_environment_adaptor_; - ChromeIdentity* identity_; - ChromeIdentity* identity2_; - int refresh_token_available_count_; }; TEST_F(AuthenticationServiceTest, TestDefaultGetAuthenticatedIdentity) { - EXPECT_FALSE(authentication_service_->GetAuthenticatedIdentity()); + EXPECT_FALSE(authentication_service()->GetAuthenticatedIdentity()); } TEST_F(AuthenticationServiceTest, TestSignInAndGetAuthenticatedIdentity) { // Sign in. SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); - EXPECT_NSEQ(identity_, authentication_service_->GetAuthenticatedIdentity()); + EXPECT_NSEQ(identity(0), + authentication_service()->GetAuthenticatedIdentity()); - std::string user_email = base::SysNSStringToUTF8([identity_ userEmail]); + std::string user_email = base::SysNSStringToUTF8([identity(0) userEmail]); AccountInfo account_info = identity_manager() ->FindAccountInfoForAccountWithRefreshTokenByEmailAddress(user_email) .value(); EXPECT_EQ(user_email, account_info.email); - EXPECT_EQ(base::SysNSStringToUTF8([identity_ gaiaID]), account_info.gaia); + EXPECT_EQ(base::SysNSStringToUTF8([identity(0) gaiaID]), account_info.gaia); EXPECT_TRUE( identity_manager()->HasAccountWithRefreshToken(account_info.account_id)); } TEST_F(AuthenticationServiceTest, TestSetPromptForSignIn) { // Verify that the default value of this flag is off. - EXPECT_FALSE(authentication_service_->ShouldPromptForSignIn()); + EXPECT_FALSE(authentication_service()->ShouldPromptForSignIn()); // Verify that prompt-flag setter and getter functions are working correctly. - authentication_service_->SetPromptForSignIn(); - EXPECT_TRUE(authentication_service_->ShouldPromptForSignIn()); - authentication_service_->ResetPromptForSignIn(); - EXPECT_FALSE(authentication_service_->ShouldPromptForSignIn()); + authentication_service()->SetPromptForSignIn(); + EXPECT_TRUE(authentication_service()->ShouldPromptForSignIn()); + authentication_service()->ResetPromptForSignIn(); + EXPECT_FALSE(authentication_service()->ShouldPromptForSignIn()); } TEST_F(AuthenticationServiceTest, OnAppEnterForegroundWithSyncSetupCompleted) { @@ -287,16 +273,14 @@ // Sign in. SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); - EXPECT_CALL(*sync_setup_service_mock_, HasFinishedInitialSetup()) + EXPECT_CALL(*sync_setup_service_mock(), HasFinishedInitialSetup()) .WillOnce(Return(true)); - CreateAuthenticationService(); - - EXPECT_EQ(base::SysNSStringToUTF8([identity_ userEmail]), + EXPECT_EQ(base::SysNSStringToUTF8([identity(0) userEmail]), identity_manager()->GetPrimaryAccountInfo().email); - EXPECT_EQ(identity_, authentication_service_->GetAuthenticatedIdentity()); + EXPECT_EQ(identity(0), authentication_service()->GetAuthenticatedIdentity()); } TEST_F(AuthenticationServiceTest, OnAppEnterForegroundWithSyncDisabled) { @@ -309,20 +293,18 @@ // Sign in. SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); - EXPECT_CALL(*sync_setup_service_mock_, HasFinishedInitialSetup()) + EXPECT_CALL(*sync_setup_service_mock(), HasFinishedInitialSetup()) .WillOnce(Invoke( - sync_setup_service_mock_, + sync_setup_service_mock(), &SyncSetupServiceMock::SyncSetupServiceHasFinishedInitialSetup)); - EXPECT_CALL(*mock_sync_service_, GetDisableReasons()) + EXPECT_CALL(*mock_sync_service(), GetDisableReasons()) .WillOnce(Return(syncer::SyncService::DISABLE_REASON_USER_CHOICE)); - CreateAuthenticationService(); - - EXPECT_EQ(base::SysNSStringToUTF8([identity_ userEmail]), + EXPECT_EQ(base::SysNSStringToUTF8([identity(0) userEmail]), identity_manager()->GetPrimaryAccountInfo().email); - EXPECT_EQ(identity_, authentication_service_->GetAuthenticatedIdentity()); + EXPECT_EQ(identity(0), authentication_service()->GetAuthenticatedIdentity()); } TEST_F(AuthenticationServiceTest, OnAppEnterForegroundWithSyncNotConfigured) { @@ -335,55 +317,53 @@ // Sign in. SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); - EXPECT_CALL(*sync_setup_service_mock_, HasFinishedInitialSetup()) + EXPECT_CALL(*sync_setup_service_mock(), HasFinishedInitialSetup()) .WillOnce(Return(false)); // Expect a call to disable sync as part of the sign out process. - EXPECT_CALL(*mock_sync_service_, StopAndClear()); - - CreateAuthenticationService(); + EXPECT_CALL(*mock_sync_service(), StopAndClear()); // User is signed out if sync initial setup isn't completed. - EXPECT_EQ("", identity_manager()->GetPrimaryAccountInfo().email); - EXPECT_FALSE(authentication_service_->GetAuthenticatedIdentity()); + EXPECT_TRUE(identity_manager()->GetPrimaryAccountInfo().email.empty()); + EXPECT_FALSE(authentication_service()->GetAuthenticatedIdentity()); } TEST_F(AuthenticationServiceTest, TestHandleForgottenIdentityNoPromptSignIn) { // Sign in. SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); // Set the authentication service as "In Foreground", remove identity and run // the loop. FireApplicationDidEnterBackground(); FireApplicationWillEnterForeground(); - identity_service_->ForgetIdentity(identity_, nil); + identity_service()->ForgetIdentity(identity(0), nil); base::RunLoop().RunUntilIdle(); // User is signed out (no corresponding identity), but not prompted for sign // in (as the action was user initiated). - EXPECT_EQ("", identity_manager()->GetPrimaryAccountInfo().email); - EXPECT_FALSE(authentication_service_->GetAuthenticatedIdentity()); - EXPECT_FALSE(authentication_service_->ShouldPromptForSignIn()); + EXPECT_TRUE(identity_manager()->GetPrimaryAccountInfo().email.empty()); + EXPECT_FALSE(authentication_service()->GetAuthenticatedIdentity()); + EXPECT_FALSE(authentication_service()->ShouldPromptForSignIn()); } TEST_F(AuthenticationServiceTest, TestHandleForgottenIdentityPromptSignIn) { // Sign in. SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); // Set the authentication service as "In Background", remove identity and run // the loop. FireApplicationDidEnterBackground(); - identity_service_->ForgetIdentity(identity_, nil); + identity_service()->ForgetIdentity(identity(0), nil); base::RunLoop().RunUntilIdle(); // User is signed out (no corresponding identity), but not prompted for sign // in (as the action was user initiated). - EXPECT_EQ("", identity_manager()->GetPrimaryAccountInfo().email); - EXPECT_FALSE(authentication_service_->GetAuthenticatedIdentity()); - EXPECT_TRUE(authentication_service_->ShouldPromptForSignIn()); + EXPECT_TRUE(identity_manager()->GetPrimaryAccountInfo().email.empty()); + EXPECT_FALSE(authentication_service()->GetAuthenticatedIdentity()); + EXPECT_TRUE(authentication_service()->ShouldPromptForSignIn()); } TEST_F(AuthenticationServiceTest, StoreAndGetAccountsInPrefs) { @@ -393,7 +373,7 @@ // Sign in. SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); // Store the accounts and get them back from the prefs. They should be the // same as the token service accounts. @@ -421,9 +401,9 @@ OnApplicationEnterForegroundReloadCredentials) { // Sign in. SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); - identity_service_->AddIdentities(@[ @"foo3" ]); + identity_service()->AddIdentities(@[ @"foo3" ]); auto account_compare_func = [](const CoreAccountInfo& first, const CoreAccountInfo& second) { @@ -478,14 +458,14 @@ } TEST_F(AuthenticationServiceTest, HaveAccountsNotChangedDefault) { - EXPECT_FALSE(authentication_service_->HaveAccountsChanged()); + EXPECT_FALSE(authentication_service()->HaveAccountsChanged()); } TEST_F(AuthenticationServiceTest, HaveAccountsNotChanged) { SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); - identity_service_->AddIdentities(@[ @"foo3" ]); + identity_service()->AddIdentities(@[ @"foo3" ]); FireIdentityListChanged(); base::RunLoop().RunUntilIdle(); @@ -493,56 +473,56 @@ FireApplicationDidEnterBackground(); FireApplicationWillEnterForeground(); - EXPECT_FALSE(authentication_service_->HaveAccountsChanged()); + EXPECT_FALSE(authentication_service()->HaveAccountsChanged()); } TEST_F(AuthenticationServiceTest, HaveAccountsChanged) { SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); - identity_service_->AddIdentities(@[ @"foo3" ]); + identity_service()->AddIdentities(@[ @"foo3" ]); FireIdentityListChanged(); base::RunLoop().RunUntilIdle(); // Simulate a switching to background and back to foreground, changing the // accounts while in background. FireApplicationDidEnterBackground(); - identity_service_->AddIdentities(@[ @"foo4" ]); + identity_service()->AddIdentities(@[ @"foo4" ]); FireApplicationWillEnterForeground(); - EXPECT_TRUE(authentication_service_->HaveAccountsChanged()); + EXPECT_TRUE(authentication_service()->HaveAccountsChanged()); } TEST_F(AuthenticationServiceTest, HaveAccountsChangedBackground) { SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); - identity_service_->AddIdentities(@[ @"foo3" ]); + identity_service()->AddIdentities(@[ @"foo3" ]); FireIdentityListChanged(); base::RunLoop().RunUntilIdle(); // Simulate a switching to background, changing the accounts while in // background. FireApplicationDidEnterBackground(); - identity_service_->AddIdentities(@[ @"foo4" ]); + identity_service()->AddIdentities(@[ @"foo4" ]); base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(authentication_service_->HaveAccountsChanged()); + EXPECT_TRUE(authentication_service()->HaveAccountsChanged()); } TEST_F(AuthenticationServiceTest, IsAuthenticatedBackground) { // Sign in. SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); - EXPECT_TRUE(authentication_service_->IsAuthenticated()); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); + EXPECT_TRUE(authentication_service()->IsAuthenticated()); // Remove the signed in identity while in background, and check that // IsAuthenticated is up-to-date. FireApplicationDidEnterBackground(); - identity_service_->ForgetIdentity(identity_, nil); + identity_service()->ForgetIdentity(identity(0), nil); base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(authentication_service_->IsAuthenticated()); + EXPECT_FALSE(authentication_service()->IsAuthenticated()); } TEST_F(AuthenticationServiceTest, MigrateAccountsStoredInPref) { @@ -562,7 +542,7 @@ // Sign in user emails as account ids. SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); std::vector<std::string> accounts_in_prefs = GetAccountsInPrefs(); ASSERT_EQ(2U, accounts_in_prefs.size()); EXPECT_EQ("foo2@foo.com", accounts_in_prefs[0]); @@ -578,8 +558,9 @@ // AccountTrackerService::Initialize(), it fails because account ids are // updated with gaia ID from email at MigrateToGaiaId. As IdentityManager // needs refresh token to find account info, it reloads all credentials. - // TODO(crbug.com/930094): Eliminate this. - identity_manager()->LegacyReloadAccountsFromSystem(); + identity_manager() + ->GetDeviceAccountsSynchronizer() + ->ReloadAllAccountsFromSystem(); // Actually migrate the accounts in prefs. MigrateAccountsStoredInPrefsIfNeeded(); @@ -598,95 +579,99 @@ // Tests that MDM errors are correctly cleared on foregrounding, sending // refresh token available notifications. TEST_F(AuthenticationServiceTest, MDMErrorsClearedOnForeground) { + TestIdentityManagerObserver observer(identity_manager()); + SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); - EXPECT_EQ(2, refresh_token_available_count_); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); + EXPECT_EQ(2, observer.refresh_token_available_count()); NSDictionary* user_info = [NSDictionary dictionary]; - SetCachedMDMInfo(identity_, user_info); + SetCachedMDMInfo(identity(0), user_info); GoogleServiceAuthError error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); - identity_test_env()->UpdatePersistentErrorOfRefreshTokenForAccount( - base::SysNSStringToUTF8([identity_ gaiaID]), error); - EXPECT_EQ(2, refresh_token_available_count_); + identity::UpdatePersistentErrorOfRefreshTokenForAccount( + identity_manager(), base::SysNSStringToUTF8([identity(0) gaiaID]), error); + EXPECT_EQ(2, observer.refresh_token_available_count()); // MDM error for |identity_| is being cleared, refresh token available // notification will be sent. FireApplicationDidEnterBackground(); FireApplicationWillEnterForeground(); - EXPECT_EQ(3, refresh_token_available_count_); + EXPECT_EQ(3, observer.refresh_token_available_count()); // MDM error has already been cleared, no notification will be sent. FireApplicationDidEnterBackground(); FireApplicationWillEnterForeground(); - EXPECT_EQ(3, refresh_token_available_count_); + EXPECT_EQ(3, observer.refresh_token_available_count()); } // Tests that MDM errors are correctly cleared when signing out, without sending // refresh token available notifications. TEST_F(AuthenticationServiceTest, MDMErrorsClearedOnSignout) { + TestIdentityManagerObserver observer(identity_manager()); + SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); NSDictionary* user_info = [NSDictionary dictionary]; - SetCachedMDMInfo(identity_, user_info); + SetCachedMDMInfo(identity(0), user_info); int refresh_token_available_count_before_signout = - refresh_token_available_count_; + observer.refresh_token_available_count(); - authentication_service_->SignOut(signin_metrics::ABORT_SIGNIN, nil); - EXPECT_FALSE(HasCachedMDMInfo(identity_)); + authentication_service()->SignOut(signin_metrics::ABORT_SIGNIN, nil); + EXPECT_FALSE(HasCachedMDMInfo(identity(0))); EXPECT_EQ(refresh_token_available_count_before_signout, - refresh_token_available_count_); + observer.refresh_token_available_count()); } // Tests that potential MDM notifications are correctly handled and dispatched // to MDM service when necessary. TEST_F(AuthenticationServiceTest, HandleMDMNotification) { SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); GoogleServiceAuthError error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); - identity_test_env()->UpdatePersistentErrorOfRefreshTokenForAccount( - base::SysNSStringToUTF8([identity_ gaiaID]), error); + identity::UpdatePersistentErrorOfRefreshTokenForAccount( + identity_manager(), base::SysNSStringToUTF8([identity(0) gaiaID]), error); NSDictionary* user_info1 = @{ @"foo" : @1 }; - ON_CALL(*identity_service_, GetMDMDeviceStatus(user_info1)) + ON_CALL(*identity_service(), GetMDMDeviceStatus(user_info1)) .WillByDefault(Return(1)); NSDictionary* user_info2 = @{ @"foo" : @2 }; - ON_CALL(*identity_service_, GetMDMDeviceStatus(user_info2)) + ON_CALL(*identity_service(), GetMDMDeviceStatus(user_info2)) .WillByDefault(Return(2)); // Notification will show the MDM dialog the first time. - EXPECT_CALL(*identity_service_, - HandleMDMNotification(identity_, user_info1, _)) + EXPECT_CALL(*identity_service(), + HandleMDMNotification(identity(0), user_info1, _)) .WillOnce(Return(true)); - FireAccessTokenRefreshFailed(identity_, user_info1); + FireAccessTokenRefreshFailed(identity(0), user_info1); // Same notification won't show the MDM dialog the second time. - EXPECT_CALL(*identity_service_, - HandleMDMNotification(identity_, user_info1, _)) + EXPECT_CALL(*identity_service(), + HandleMDMNotification(identity(0), user_info1, _)) .Times(0); - FireAccessTokenRefreshFailed(identity_, user_info1); + FireAccessTokenRefreshFailed(identity(0), user_info1); // New notification will show the MDM dialog on the same identity. - EXPECT_CALL(*identity_service_, - HandleMDMNotification(identity_, user_info2, _)) + EXPECT_CALL(*identity_service(), + HandleMDMNotification(identity(0), user_info2, _)) .WillOnce(Return(true)); - FireAccessTokenRefreshFailed(identity_, user_info2); + FireAccessTokenRefreshFailed(identity(0), user_info2); } // Tests that MDM blocked notifications are correctly signing out the user if // the primary account is blocked. TEST_F(AuthenticationServiceTest, HandleMDMBlockedNotification) { SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); GoogleServiceAuthError error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); - identity_test_env()->UpdatePersistentErrorOfRefreshTokenForAccount( - base::SysNSStringToUTF8([identity_ gaiaID]), error); + identity::UpdatePersistentErrorOfRefreshTokenForAccount( + identity_manager(), base::SysNSStringToUTF8([identity(0) gaiaID]), error); NSDictionary* user_info1 = @{ @"foo" : @1 }; - ON_CALL(*identity_service_, GetMDMDeviceStatus(user_info1)) + ON_CALL(*identity_service(), GetMDMDeviceStatus(user_info1)) .WillByDefault(Return(1)); auto handle_mdm_notification_callback = [](ChromeIdentity*, NSDictionary*, @@ -695,61 +680,61 @@ return true; }; - // User not signed out as |identity2_| isn't the primary account. - EXPECT_CALL(*identity_service_, - HandleMDMNotification(identity2_, user_info1, _)) + // User not signed out as |identity(1)| isn't the primary account. + EXPECT_CALL(*identity_service(), + HandleMDMNotification(identity(1), user_info1, _)) .WillOnce(Invoke(handle_mdm_notification_callback)); - FireAccessTokenRefreshFailed(identity2_, user_info1); - EXPECT_TRUE(authentication_service_->IsAuthenticated()); + FireAccessTokenRefreshFailed(identity(1), user_info1); + EXPECT_TRUE(authentication_service()->IsAuthenticated()); // User signed out as |identity_| is the primary account. - EXPECT_CALL(*identity_service_, - HandleMDMNotification(identity_, user_info1, _)) + EXPECT_CALL(*identity_service(), + HandleMDMNotification(identity(0), user_info1, _)) .WillOnce(Invoke(handle_mdm_notification_callback)); - FireAccessTokenRefreshFailed(identity_, user_info1); - EXPECT_FALSE(authentication_service_->IsAuthenticated()); + FireAccessTokenRefreshFailed(identity(0), user_info1); + EXPECT_FALSE(authentication_service()->IsAuthenticated()); } // Tests that MDM dialog isn't shown when there is no cached MDM error. TEST_F(AuthenticationServiceTest, ShowMDMErrorDialogNoCachedError) { - EXPECT_CALL(*identity_service_, HandleMDMNotification(identity_, _, _)) + EXPECT_CALL(*identity_service(), HandleMDMNotification(identity(0), _, _)) .Times(0); EXPECT_FALSE( - authentication_service_->ShowMDMErrorDialogForIdentity(identity_)); + authentication_service()->ShowMDMErrorDialogForIdentity(identity(0))); } // Tests that MDM dialog isn't shown when there is a cached MDM error but no // corresponding error for the account. TEST_F(AuthenticationServiceTest, ShowMDMErrorDialogInvalidCachedError) { NSDictionary* user_info = [NSDictionary dictionary]; - SetCachedMDMInfo(identity_, user_info); + SetCachedMDMInfo(identity(0), user_info); - EXPECT_CALL(*identity_service_, - HandleMDMNotification(identity_, user_info, _)) + EXPECT_CALL(*identity_service(), + HandleMDMNotification(identity(0), user_info, _)) .Times(0); EXPECT_FALSE( - authentication_service_->ShowMDMErrorDialogForIdentity(identity_)); + authentication_service()->ShowMDMErrorDialogForIdentity(identity(0))); } // Tests that MDM dialog is shown when there is a cached error and a // corresponding error for the account. TEST_F(AuthenticationServiceTest, ShowMDMErrorDialog) { SetExpectationsForSignIn(); - authentication_service_->SignIn(identity_, kNoHostedDomainFound); + authentication_service()->SignIn(identity(0), kNoHostedDomainFound); GoogleServiceAuthError error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); - identity_test_env()->UpdatePersistentErrorOfRefreshTokenForAccount( - base::SysNSStringToUTF8([identity_ gaiaID]), error); + identity::UpdatePersistentErrorOfRefreshTokenForAccount( + identity_manager(), base::SysNSStringToUTF8([identity(0) gaiaID]), error); NSDictionary* user_info = [NSDictionary dictionary]; - SetCachedMDMInfo(identity_, user_info); + SetCachedMDMInfo(identity(0), user_info); - EXPECT_CALL(*identity_service_, - HandleMDMNotification(identity_, user_info, _)) + EXPECT_CALL(*identity_service(), + HandleMDMNotification(identity(0), user_info, _)) .WillOnce(Return(true)); EXPECT_TRUE( - authentication_service_->ShowMDMErrorDialogForIdentity(identity_)); + authentication_service()->ShowMDMErrorDialogForIdentity(identity(0))); }
diff --git a/ios/chrome/browser/signin/device_accounts_provider_impl.mm b/ios/chrome/browser/signin/device_accounts_provider_impl.mm index f88583c4..fbd72e4 100644 --- a/ios/chrome/browser/signin/device_accounts_provider_impl.mm +++ b/ios/chrome/browser/signin/device_accounts_provider_impl.mm
@@ -6,7 +6,7 @@ #include "base/logging.h" #include "base/strings/sys_string_conversions.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "ios/chrome/browser/signin/constants.h" #include "ios/chrome/browser/signin/signin_util.h" #import "ios/public/provider/chrome/browser/chrome_browser_provider.h"
diff --git a/ios/chrome/browser/signin/identity_manager_factory.cc b/ios/chrome/browser/signin/identity_manager_factory.cc index 86329440..fb7976a 100644 --- a/ios/chrome/browser/signin/identity_manager_factory.cc +++ b/ios/chrome/browser/signin/identity_manager_factory.cc
@@ -11,18 +11,19 @@ #include "components/keyed_service/core/keyed_service.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" #include "components/pref_registry/pref_registry_syncable.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_fetcher_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/gaia_cookie_manager_service.h" #include "components/signin/core/browser/primary_account_manager.h" #include "components/signin/core/browser/primary_account_policy_manager_impl.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_client.h" #include "components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h" +#include "components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h" #include "components/signin/internal/identity_manager/diagnostics_provider_impl.h" #include "components/signin/internal/identity_manager/primary_account_mutator_impl.h" #include "components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_client.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "ios/chrome/browser/application_context.h" @@ -167,13 +168,17 @@ SigninClientFactory::GetForBrowserState(browser_state), token_service.get(), account_tracker_service.get()); + auto device_accounts_synchronizer = + std::make_unique<identity::DeviceAccountsSynchronizerImpl>( + token_service->GetDelegate()); + auto identity_manager = std::make_unique<identity::IdentityManager>( std::move(account_tracker_service), std::move(token_service), std::move(gaia_cookie_manager_service), std::move(primary_account_manager), std::move(account_fetcher_service), std::move(primary_account_mutator), /*accounts_mutator=*/nullptr, std::move(accounts_cookie_mutator), - std::move(diagnostics_provider)); + std::move(diagnostics_provider), std::move(device_accounts_synchronizer)); for (auto& observer : observer_list_) observer.IdentityManagerCreated(identity_manager.get());
diff --git a/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc b/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc index c4324bc..c8f688f 100644 --- a/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc +++ b/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc
@@ -7,8 +7,8 @@ #include <utility> #include "base/bind.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/test_signin_client.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/test_signin_client.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/signin/device_accounts_provider_impl.h" #include "ios/chrome/browser/signin/identity_manager_factory.h"
diff --git a/ios/chrome/browser/signin/ios_chrome_signin_client.h b/ios/chrome/browser/signin/ios_chrome_signin_client.h index fda0d650..bbe8cae 100644 --- a/ios/chrome/browser/signin/ios_chrome_signin_client.h +++ b/ios/chrome/browser/signin/ios_chrome_signin_client.h
@@ -10,8 +10,8 @@ #include "base/macros.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "components/content_settings/core/browser/host_content_settings_map.h" -#include "components/signin/core/browser/signin_client.h" #include "components/signin/ios/browser/wait_for_network_callback_helper.h" +#include "components/signin/public/base/signin_client.h" #include "net/cookies/cookie_change_dispatcher.h" namespace ios {
diff --git a/ios/chrome/browser/signin/signin_browser_state_info_updater.mm b/ios/chrome/browser/signin/signin_browser_state_info_updater.mm index d9fc2c7..1935bbd 100644 --- a/ios/chrome/browser/signin/signin_browser_state_info_updater.mm +++ b/ios/chrome/browser/signin/signin_browser_state_info_updater.mm
@@ -12,7 +12,7 @@ #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/browser_state_info_cache.h" #include "ios/chrome/browser/browser_state/chrome_browser_state_manager.h"
diff --git a/ios/chrome/browser/signin/signin_browser_state_info_updater_unittest.mm b/ios/chrome/browser/signin/signin_browser_state_info_updater_unittest.mm index 57db6a4..a1e8a27 100644 --- a/ios/chrome/browser/signin/signin_browser_state_info_updater_unittest.mm +++ b/ios/chrome/browser/signin/signin_browser_state_info_updater_unittest.mm
@@ -15,7 +15,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "google_apis/gaia/google_service_auth_error.h" #include "ios/chrome/browser/application_context.h"
diff --git a/ios/chrome/browser/sync/device_info_sync_service_factory.mm b/ios/chrome/browser/sync/device_info_sync_service_factory.mm index 8a72c1a..a254733 100644 --- a/ios/chrome/browser/sync/device_info_sync_service_factory.mm +++ b/ios/chrome/browser/sync/device_info_sync_service_factory.mm
@@ -11,7 +11,7 @@ #include "components/keyed_service/core/service_access_type.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" #include "components/send_tab_to_self/features.h" -#include "components/signin/core/browser/device_id_helper.h" +#include "components/signin/public/base/device_id_helper.h" #include "components/sync/model/model_type_store_service.h" #include "components/sync_device_info/device_info_sync_service_impl.h" #include "components/sync_device_info/local_device_info_provider_impl.h"
diff --git a/ios/chrome/browser/sync/profile_sync_service_factory_unittest.cc b/ios/chrome/browser/sync/profile_sync_service_factory_unittest.cc index 74c734de..a4bd2a3 100644 --- a/ios/chrome/browser/sync/profile_sync_service_factory_unittest.cc +++ b/ios/chrome/browser/sync/profile_sync_service_factory_unittest.cc
@@ -59,7 +59,12 @@ datatypes.push_back(syncer::FAVICON_TRACKING); datatypes.push_back(syncer::FAVICON_IMAGES); datatypes.push_back(syncer::HISTORY_DELETE_DIRECTIVES); - datatypes.push_back(syncer::PASSWORDS); + if (!base::FeatureList::IsEnabled(switches::kSyncUSSPasswords)) { + // Password store factory is null for testing. For directory + // implementation, a controller was added anyway. For USS, no controller + // gets added, and hence the type isn't available. + datatypes.push_back(syncer::PASSWORDS); + } datatypes.push_back(syncer::PREFERENCES); datatypes.push_back(syncer::PRIORITY_PREFERENCES); datatypes.push_back(syncer::READING_LIST);
diff --git a/ios/chrome/browser/system_flags.mm b/ios/chrome/browser/system_flags.mm index b19372a..bc56171 100644 --- a/ios/chrome/browser/system_flags.mm +++ b/ios/chrome/browser/system_flags.mm
@@ -20,7 +20,7 @@ #include "base/strings/sys_string_conversions.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/password_manager/core/common/password_manager_features.h" -#include "components/signin/core/browser/signin_switches.h" +#include "components/signin/public/base/signin_switches.h" #include "components/variations/variations_associated_data.h" #include "ios/chrome/browser/browsing_data/browsing_data_features.h" #include "ios/chrome/browser/chrome_switches.h"
diff --git a/ios/chrome/browser/tabs/BUILD.gn b/ios/chrome/browser/tabs/BUILD.gn index 36979f39..3b5d7f5 100644 --- a/ios/chrome/browser/tabs/BUILD.gn +++ b/ios/chrome/browser/tabs/BUILD.gn
@@ -67,6 +67,7 @@ "//ios/chrome/browser/autofill", "//ios/chrome/browser/autofill:autofill_internal", "//ios/chrome/browser/browser_state", + "//ios/chrome/browser/browser_state_metrics", "//ios/chrome/browser/download", "//ios/chrome/browser/download:features", "//ios/chrome/browser/favicon",
diff --git a/ios/chrome/browser/tabs/tab_model.mm b/ios/chrome/browser/tabs/tab_model.mm index 37ed359..030ba1a 100644 --- a/ios/chrome/browser/tabs/tab_model.mm +++ b/ios/chrome/browser/tabs/tab_model.mm
@@ -26,6 +26,7 @@ #include "components/sessions/core/tab_restore_service.h" #include "components/sessions/ios/ios_live_tab.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" +#include "ios/chrome/browser/browser_state_metrics/browser_state_metrics.h" #include "ios/chrome/browser/chrome_url_constants.h" #import "ios/chrome/browser/chrome_url_util.h" #include "ios/chrome/browser/crash_loop_detection_util.h" @@ -207,15 +208,10 @@ DCHECK(web_state->GetNavigationManager()); web::NavigationItem* item = web_state->GetNavigationManager()->GetLastCommittedItem(); - // TODO(crbug.com/966747): Add a function in browser_state_metrics.h to return - // profile type. - profile_metrics::BrowserProfileType profile_type = - web_state->GetBrowserState()->IsOffTheRecord() - ? profile_metrics::BrowserProfileType::kIncognito - : profile_metrics::BrowserProfileType::kRegular; navigation_metrics::RecordMainFrameNavigation( item ? item->GetVirtualURL() : GURL::EmptyGURL(), true, - web_state->GetBrowserState()->IsOffTheRecord(), profile_type); + web_state->GetBrowserState()->IsOffTheRecord(), + GetBrowserStateType(web_state->GetBrowserState())); } } // anonymous namespace
diff --git a/ios/chrome/browser/ui/authentication/BUILD.gn b/ios/chrome/browser/ui/authentication/BUILD.gn index 6da87518..2b86394 100644 --- a/ios/chrome/browser/ui/authentication/BUILD.gn +++ b/ios/chrome/browser/ui/authentication/BUILD.gn
@@ -162,7 +162,7 @@ ":authentication", "unified_consent", "//components/signin/core/browser", - "//components/signin/core/browser:shared", + "//components/signin/public/base", "//components/signin/public/identity_manager", "//components/unified_consent", "//ios/chrome/app/strings:ios_strings_grit",
diff --git a/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm b/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm index 05b571c..961e944 100644 --- a/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm +++ b/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm
@@ -14,7 +14,7 @@ #include "base/time/time.h" #include "base/timer/timer.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/strings/grit/components_strings.h" #include "components/unified_consent/feature.h"
diff --git a/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h b/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h index 69d55ab..8ddd260 100644 --- a/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h +++ b/ios/chrome/browser/ui/authentication/cells/signin_promo_view.h
@@ -7,7 +7,7 @@ #import <UIKit/UIKit.h> -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" @protocol SigninPromoViewDelegate;
diff --git a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.h b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.h index 51cee1a..18a38849 100644 --- a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.h +++ b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.h
@@ -11,7 +11,7 @@ #include "base/auto_reset.h" #include "base/timer/timer.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #import "ios/chrome/browser/signin/constants.h" #include "ios/chrome/browser/ui/authentication/signin_confirmation_view_controller.h"
diff --git a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm index 8bb1a12..7f745f3 100644 --- a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm +++ b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm
@@ -18,8 +18,8 @@ #import "base/strings/sys_string_conversions.h" #include "base/timer/elapsed_timer.h" #include "components/consent_auditor/consent_auditor.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/strings/grit/components_strings.h" #include "components/unified_consent/feature.h" #include "components/unified_consent/unified_consent_service.h"
diff --git a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller_unittest.mm b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller_unittest.mm index 85f5f218..511709b 100644 --- a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller_unittest.mm
@@ -13,7 +13,7 @@ #include "base/timer/mock_timer.h" #include "components/consent_auditor/consent_auditor.h" #include "components/consent_auditor/fake_consent_auditor.h" -#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/public/base/account_consistency_method.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/unified_consent/feature.h" #include "components/unified_consent/scoped_unified_consent.h"
diff --git a/ios/chrome/browser/ui/authentication/re_signin_infobar_delegate.mm b/ios/chrome/browser/ui/authentication/re_signin_infobar_delegate.mm index e0b9896..19c6d9f 100644 --- a/ios/chrome/browser/ui/authentication/re_signin_infobar_delegate.mm +++ b/ios/chrome/browser/ui/authentication/re_signin_infobar_delegate.mm
@@ -11,7 +11,7 @@ #include "base/logging.h" #include "components/infobars/core/infobar_manager.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/strings/grit/components_strings.h" #import "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/infobars/infobar.h"
diff --git a/ios/chrome/browser/ui/authentication/signin_earlgrey_utils_app_interface.mm b/ios/chrome/browser/ui/authentication/signin_earlgrey_utils_app_interface.mm index f4b92a41..411817e 100644 --- a/ios/chrome/browser/ui/authentication/signin_earlgrey_utils_app_interface.mm +++ b/ios/chrome/browser/ui/authentication/signin_earlgrey_utils_app_interface.mm
@@ -5,7 +5,7 @@ #import "ios/chrome/browser/ui/authentication/signin_earlgrey_utils_app_interface.h" #include "base/strings/sys_string_conversions.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/signin/identity_manager_factory.h"
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm index 161a86d..543f5a2 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm
@@ -11,7 +11,7 @@ #include "base/metrics/user_metrics_action.h" #include "base/strings/sys_string_conversions.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/chrome_browser_provider_observer_bridge.h" #include "ios/chrome/browser/pref_names.h"
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm b/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm index 553fbb9..7d97b784 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm
@@ -6,7 +6,7 @@ #include <memory> -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/objc/identity_manager_observer_bridge.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h"
diff --git a/ios/chrome/browser/ui/commands/show_signin_command.h b/ios/chrome/browser/ui/commands/show_signin_command.h index d512a9a..820c095 100644 --- a/ios/chrome/browser/ui/commands/show_signin_command.h +++ b/ios/chrome/browser/ui/commands/show_signin_command.h
@@ -7,7 +7,7 @@ #import <Foundation/Foundation.h> -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" @class ChromeIdentity;
diff --git a/ios/chrome/browser/ui/first_run/first_run_chrome_signin_view_controller.mm b/ios/chrome/browser/ui/first_run/first_run_chrome_signin_view_controller.mm index 87f0f6b..8b1c8e5 100644 --- a/ios/chrome/browser/ui/first_run/first_run_chrome_signin_view_controller.mm +++ b/ios/chrome/browser/ui/first_run/first_run_chrome_signin_view_controller.mm
@@ -6,7 +6,7 @@ #import "base/ios/block_types.h" #include "base/metrics/user_metrics.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/unified_consent/feature.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #import "ios/chrome/browser/first_run/first_run_configuration.h"
diff --git a/ios/chrome/browser/ui/open_in/open_in_controller_egtest.mm b/ios/chrome/browser/ui/open_in/open_in_controller_egtest.mm index 3862a08..69b83fbb 100644 --- a/ios/chrome/browser/ui/open_in/open_in_controller_egtest.mm +++ b/ios/chrome/browser/ui/open_in/open_in_controller_egtest.mm
@@ -4,6 +4,7 @@ #import <UIKit/UIKit.h> +#include "base/ios/ios_util.h" #include "base/strings/sys_string_conversions.h" #include "ios/chrome/grit/ios_strings.h" #import "ios/chrome/test/earl_grey/chrome_actions.h" @@ -23,6 +24,14 @@ // Path which leads to a PDF file. const char kPDFPath[] = "/testpage.pdf"; +id<GREYMatcher> ShareMenuDismissButton() { + if (@available(iOS 13, *)) { + return chrome_test_util::CloseButton(); + } else { + return chrome_test_util::CancelButton(); + } +} + } // namespace // Tests Open in Feature for PDF files. @@ -39,12 +48,23 @@ // Tests that open in button appears when opening a PDF, and that tapping on it // will open the activity view. - (void)testOpenIn { + // TODO(crbug.com/982845): A bug is causing the "Open in" toolbar to disappear + // after any VC is presented fullscreen over the BVC. The iOS 13 share menu + // is presented fullscreen, but only when compiling with the iOS 12 SDK. + // Disable this test in this configuration until the underlying bug is fixed. +#if !defined(__IPHONE_13_0) || (__IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_13_0) + if (base::ios::IsRunningOnIOS13OrLater()) { + EARL_GREY_TEST_DISABLED( + @"Disabled on iOS 13 when compiled with the iOS 12 SDK."); + } +#endif + [ChromeEarlGrey loadURL:self.testServer->GetURL(kPDFPath)]; [[EarlGrey selectElementWithMatcher:chrome_test_util::OpenInButton()] performAction:grey_tap()]; // Check and tap on the Cancel button that appears below the activity menu. // Other actions buttons can't be checked from EarlGrey. - [[[EarlGrey selectElementWithMatcher:chrome_test_util::CancelButton()] + [[[EarlGrey selectElementWithMatcher:ShareMenuDismissButton()] assertWithMatcher:grey_interactable()] performAction:grey_tap()]; // Check that after dismissing the activity view, tapping on the web view will
diff --git a/ios/chrome/browser/ui/popup_menu/BUILD.gn b/ios/chrome/browser/ui/popup_menu/BUILD.gn index d3710774..17a0156d 100644 --- a/ios/chrome/browser/ui/popup_menu/BUILD.gn +++ b/ios/chrome/browser/ui/popup_menu/BUILD.gn
@@ -100,6 +100,7 @@ "//components/feature_engagement/test:test_support", "//components/language/ios/browser", "//components/reading_list/core", + "//components/translate/core/browser", "//ios/chrome/browser/browser_state:test_support", "//ios/chrome/browser/ui/popup_menu/cells", "//ios/chrome/browser/ui/popup_menu/public:popup_menu_ui",
diff --git a/ios/chrome/browser/ui/popup_menu/popup_menu_mediator_unittest.mm b/ios/chrome/browser/ui/popup_menu/popup_menu_mediator_unittest.mm index d4ec032..6c33cd8 100644 --- a/ios/chrome/browser/ui/popup_menu/popup_menu_mediator_unittest.mm +++ b/ios/chrome/browser/ui/popup_menu/popup_menu_mediator_unittest.mm
@@ -7,6 +7,7 @@ #include "components/feature_engagement/test/mock_tracker.h" #include "components/language/ios/browser/ios_language_detection_tab_helper.h" #include "components/reading_list/core/reading_list_model_impl.h" +#include "components/translate/core/browser/translate_prefs.h" #import "ios/chrome/browser/ui/popup_menu/cells/popup_menu_tools_item.h" #import "ios/chrome/browser/ui/popup_menu/popup_menu_constants.h" #import "ios/chrome/browser/ui/popup_menu/public/popup_menu_table_view_controller.h" @@ -190,35 +191,57 @@ mediator_.popupMenu = popup_menu_; mediator_.engagementTracker = &tracker; - EXPECT_CALL(tracker, Dismissed(testing::_)); + // There may be one or more Tools Menu items that use engagement trackers. + EXPECT_CALL(tracker, Dismissed(testing::_)).Times(testing::AtLeast(1)); [mediator_ disconnect]; } // Tests that the mediator is returning the right number of items and sections // for the Tools Menu type. -TEST_F(PopupMenuMediatorTest, TestElementsToolsMenu) { +TEST_F(PopupMenuMediatorTest, TestToolsMenuItemsCount) { CreateMediator(PopupMenuTypeToolsMenu, NO, NO); NSUInteger number_of_action_items = 6; + if (base::FeatureList::IsEnabled(translate::kTranslateMobileManualTrigger)) { + number_of_action_items++; + } if (ios::GetChromeBrowserProvider() ->GetUserFeedbackProvider() ->IsUserFeedbackEnabled()) { number_of_action_items++; } - CheckMediatorSetItems(@[ @(3), @(5), @(number_of_action_items) ]); + // Checks that Tools Menu has the right number of items in each section. + CheckMediatorSetItems(@[ + // Stop/Reload, New Tab, New Incognito Tab + @(3), + // 4 collections + Settings + @(5), + // Other actions, depending on configuration + @(number_of_action_items) + ]); } // Tests that the mediator is returning the right number of items and sections // for the Tab Grid type, in non-incognito. -TEST_F(PopupMenuMediatorTest, TestElementsTabGridNonIncognito) { +TEST_F(PopupMenuMediatorTest, TestTabGridMenuNonIncognito) { CreateMediator(PopupMenuTypeTabGrid, NO, NO); - CheckMediatorSetItems(@[ @(2), @(1) ]); + CheckMediatorSetItems(@[ + // New Tab, New Incognito Tab + @(2), + // Close Tab + @(1) + ]); } // Tests that the mediator is returning the right number of items and sections // for the Tab Grid type, in incognito. -TEST_F(PopupMenuMediatorTest, TestElementsTabGridIncognito) { +TEST_F(PopupMenuMediatorTest, TestTabGridMenuIncognito) { CreateMediator(PopupMenuTypeTabGrid, YES, NO); - CheckMediatorSetItems(@[ @(2), @(1) ]); + CheckMediatorSetItems(@[ + // New Tab, New Incognito Tab + @(2), + // Close Tab + @(1) + ]); } // Tests that the mediator is asking for an item to be highlighted when asked.
diff --git a/ios/chrome/browser/ui/promos/signin_promo_view_controller.mm b/ios/chrome/browser/ui/promos/signin_promo_view_controller.mm index 15e9a4e..d57517cf 100644 --- a/ios/chrome/browser/ui/promos/signin_promo_view_controller.mm +++ b/ios/chrome/browser/ui/promos/signin_promo_view_controller.mm
@@ -8,7 +8,7 @@ #include "base/metrics/user_metrics.h" #include "base/strings/sys_string_conversions.h" #include "base/version.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/unified_consent/feature.h" #include "components/version_info/version_info.h" #include "ios/chrome/app/tests_hook.h"
diff --git a/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.mm b/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.mm index 9d0ff22..b727c1bf 100644 --- a/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.mm +++ b/ios/chrome/browser/ui/settings/google_services/advanced_signin_settings_coordinator.mm
@@ -8,7 +8,7 @@ #include "base/logging.h" #include "base/metrics/user_metrics.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/strings/grit/components_strings.h" #include "components/sync/driver/sync_service.h" #include "components/unified_consent/unified_consent_metrics.h"
diff --git a/ios/chrome/browser/ui/settings/settings_table_view_controller.mm b/ios/chrome/browser/ui/settings/settings_table_view_controller.mm index 1bbdb22d..a5a7699 100644 --- a/ios/chrome/browser/ui/settings/settings_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_table_view_controller.mm
@@ -16,7 +16,7 @@ #import "components/prefs/ios/pref_observer_bridge.h" #include "components/prefs/pref_service.h" #include "components/search_engines/util.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/identity_manager.h" #import "components/signin/public/identity_manager/objc/identity_manager_observer_bridge.h" #include "components/strings/grit/components_strings.h" @@ -24,7 +24,6 @@ #include "components/unified_consent/feature.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/ios_chrome_flag_descriptions.h" #include "ios/chrome/browser/passwords/ios_chrome_password_store_factory.h" #include "ios/chrome/browser/pref_names.h" #include "ios/chrome/browser/search_engines/search_engine_observer_bridge.h"
diff --git a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.h b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.h index 5802fe0..365a059e 100644 --- a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.h +++ b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.h
@@ -8,7 +8,7 @@ #import <Foundation/Foundation.h> #import "base/ios/block_types.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" @protocol ApplicationCommands; namespace ios {
diff --git a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.mm b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.mm index 6105784..3753820a 100644 --- a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.mm +++ b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.mm
@@ -8,8 +8,8 @@ #include "base/logging.h" #include "base/strings/sys_string_conversions.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/unified_consent/feature.h" #import "ios/chrome/browser/browser_state/chrome_browser_state.h"
diff --git a/ios/chrome/browser/ui/signin_interaction/signin_interaction_coordinator.h b/ios/chrome/browser/ui/signin_interaction/signin_interaction_coordinator.h index 9c2bf77..404edf82 100644 --- a/ios/chrome/browser/ui/signin_interaction/signin_interaction_coordinator.h +++ b/ios/chrome/browser/ui/signin_interaction/signin_interaction_coordinator.h
@@ -8,7 +8,7 @@ #import <UIKit/UIKit.h> #import "base/ios/block_types.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "ios/chrome/browser/signin/constants.h" @protocol ApplicationCommands;
diff --git a/ios/chrome/browser/ui/ui_feature_flags.cc b/ios/chrome/browser/ui/ui_feature_flags.cc index 80bf763a..2d5eb4a 100644 --- a/ios/chrome/browser/ui/ui_feature_flags.cc +++ b/ios/chrome/browser/ui/ui_feature_flags.cc
@@ -21,7 +21,7 @@ base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kCopiedContentBehavior{"CopiedContentBehavior", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kSettingsRefresh{"SettingsRefresh", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/ios/chrome/browser/ui/webui/net_export/net_export_ui.mm b/ios/chrome/browser/ui/webui/net_export/net_export_ui.mm index 3ba0844..c4b69f35 100644 --- a/ios/chrome/browser/ui/webui/net_export/net_export_ui.mm +++ b/ios/chrome/browser/ui/webui/net_export/net_export_ui.mm
@@ -137,7 +137,7 @@ const base::Value::ListStorage& params = list->GetList(); // Determine the capture mode. - net::NetLogCaptureMode capture_mode = net::NetLogCaptureMode::Default(); + net::NetLogCaptureMode capture_mode = net::NetLogCaptureMode::kDefault; if (params.size() > 0 && params[0].is_string()) { capture_mode = net_log::NetExportFileWriter::CaptureModeFromString( params[0].GetString());
diff --git a/ios/chrome/test/DEPS b/ios/chrome/test/DEPS index b41d64c..cb31aee5 100644 --- a/ios/chrome/test/DEPS +++ b/ios/chrome/test/DEPS
@@ -11,6 +11,7 @@ "+components/network_time", "+components/prefs", "+components/signin/core/browser", + "+components/signin/public/base", # Use identity_manager.h instead of the below files; # see https://groups.google.com/a/chromium.org/d/msg/chromium-dev/dgFLuxqZt1o/iEqkyoQQBwAJ for help and info. "-components/signin/core/browser/account_fetcher_service.h",
diff --git a/ios/chrome/test/app/signin_test_util.mm b/ios/chrome/test/app/signin_test_util.mm index 19c5c4d9..ab932a7e 100644 --- a/ios/chrome/test/app/signin_test_util.mm +++ b/ios/chrome/test/app/signin_test_util.mm
@@ -8,7 +8,7 @@ #include "base/strings/stringprintf.h" #import "base/test/ios/wait_util.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_pref_names.h" +#include "components/signin/public/base/signin_pref_names.h" #include "google_apis/gaia/gaia_constants.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/pref_names.h"
diff --git a/ios/public/provider/chrome/browser/signin/BUILD.gn b/ios/public/provider/chrome/browser/signin/BUILD.gn index 1d076df..848e31b 100644 --- a/ios/public/provider/chrome/browser/signin/BUILD.gn +++ b/ios/public/provider/chrome/browser/signin/BUILD.gn
@@ -38,7 +38,7 @@ deps = [ ":signin", "//base", - "//components/signin/core/browser:shared", + "//components/signin/public/identity_manager", "//google_apis", "//ios/public/provider/chrome/browser", "//ui/base:test_support",
diff --git a/ios/public/provider/chrome/browser/signin/DEPS b/ios/public/provider/chrome/browser/signin/DEPS index a285d454..a812063 100644 --- a/ios/public/provider/chrome/browser/signin/DEPS +++ b/ios/public/provider/chrome/browser/signin/DEPS
@@ -3,6 +3,6 @@ "+ui/base/test/ios/ui_image_test_utils.h", ], "fake_chrome_identity\.mm": [ - "+components/signin/core/browser/account_info.h" + "+components/signin/public/identity_manager/account_info.h" ] }
diff --git a/ios/public/provider/chrome/browser/signin/fake_chrome_identity.mm b/ios/public/provider/chrome/browser/signin/fake_chrome_identity.mm index 262c981..a35e766 100644 --- a/ios/public/provider/chrome/browser/signin/fake_chrome_identity.mm +++ b/ios/public/provider/chrome/browser/signin/fake_chrome_identity.mm
@@ -8,7 +8,7 @@ #error "This file requires ARC support." #endif -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" @implementation FakeChromeIdentity { NSString* _userEmail;
diff --git a/ios/web_view/BUILD.gn b/ios/web_view/BUILD.gn index d6d28c4..9ef6dcd70 100644 --- a/ios/web_view/BUILD.gn +++ b/ios/web_view/BUILD.gn
@@ -430,8 +430,8 @@ "//components/autofill/ios/form_util:test_support", "//components/browser_sync:test_support", "//components/prefs:test_support", - "//components/signin/core/browser:internals_test_support", "//components/signin/ios/browser:test_support", + "//components/signin/public/base:test_support", "//components/signin/public/identity_manager:test_support", "//components/sync:test_support", "//ios/web/public/deprecated:test_doubles",
diff --git a/ios/web_view/internal/signin/ios_web_view_signin_client.h b/ios/web_view/internal/signin/ios_web_view_signin_client.h index d7db8fc3..ecb6d1ea 100644 --- a/ios/web_view/internal/signin/ios_web_view_signin_client.h +++ b/ios/web_view/internal/signin/ios_web_view_signin_client.h
@@ -10,8 +10,8 @@ #include "base/macros.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "components/content_settings/core/browser/host_content_settings_map.h" -#include "components/signin/core/browser/signin_client.h" #include "components/signin/ios/browser/wait_for_network_callback_helper.h" +#include "components/signin/public/base/signin_client.h" #include "net/cookies/cookie_change_dispatcher.h" #include "services/network/public/cpp/shared_url_loader_factory.h"
diff --git a/ios/web_view/internal/signin/web_view_identity_manager_factory.mm b/ios/web_view/internal/signin/web_view_identity_manager_factory.mm index 02e1af21d..15fc065 100644 --- a/ios/web_view/internal/signin/web_view_identity_manager_factory.mm +++ b/ios/web_view/internal/signin/web_view_identity_manager_factory.mm
@@ -11,19 +11,20 @@ #include "components/keyed_service/ios/browser_state_dependency_manager.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_fetcher_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/gaia_cookie_manager_service.h" #include "components/signin/core/browser/primary_account_manager.h" #include "components/signin/core/browser/primary_account_policy_manager_impl.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_client.h" -#include "components/signin/core/browser/signin_pref_names.h" #include "components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h" +#include "components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h" #include "components/signin/internal/identity_manager/diagnostics_provider_impl.h" #include "components/signin/internal/identity_manager/primary_account_mutator_impl.h" #include "components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.h" +#include "components/signin/public/base/account_consistency_method.h" +#include "components/signin/public/base/signin_client.h" +#include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "ios/web_view/internal/app/application_context.h" @@ -168,13 +169,17 @@ WebViewSigninClientFactory::GetForBrowserState(browser_state), token_service.get(), account_tracker_service.get()); + auto device_accounts_synchronizer = + std::make_unique<identity::DeviceAccountsSynchronizerImpl>( + token_service->GetDelegate()); + return std::make_unique<identity::IdentityManager>( std::move(account_tracker_service), std::move(token_service), std::move(gaia_cookie_manager_service), std::move(primary_account_manager), std::move(account_fetcher_service), std::move(primary_account_mutator), /*accounts_mutator=*/nullptr, std::move(accounts_cookie_mutator), - std::move(diagnostics_provider)); + std::move(diagnostics_provider), std::move(device_accounts_synchronizer)); } } // namespace ios_web_view
diff --git a/ios/web_view/internal/signin/web_view_signin_client_factory.mm b/ios/web_view/internal/signin/web_view_signin_client_factory.mm index 13c8f7a..4fe6df19 100644 --- a/ios/web_view/internal/signin/web_view_signin_client_factory.mm +++ b/ios/web_view/internal/signin/web_view_signin_client_factory.mm
@@ -7,7 +7,7 @@ #include "base/no_destructor.h" #include "components/keyed_service/core/service_access_type.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" -#include "components/signin/core/browser/signin_client.h" +#include "components/signin/public/base/signin_client.h" #include "ios/web_view/internal/content_settings/web_view_cookie_settings_factory.h" #include "ios/web_view/internal/content_settings/web_view_host_content_settings_map_factory.h" #include "ios/web_view/internal/signin/ios_web_view_signin_client.h"
diff --git a/ios/web_view/internal/sync/cwv_sync_controller.mm b/ios/web_view/internal/sync/cwv_sync_controller.mm index 76e60e0..f6db59c 100644 --- a/ios/web_view/internal/sync/cwv_sync_controller.mm +++ b/ios/web_view/internal/sync/cwv_sync_controller.mm
@@ -8,8 +8,9 @@ #include <memory> #include "base/strings/sys_string_conversions.h" -#include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/signin_error_controller.h" +#include "components/signin/public/identity_manager/account_info.h" +#include "components/signin/public/identity_manager/device_accounts_synchronizer.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" #include "components/sync/driver/sync_service.h" @@ -165,7 +166,8 @@ base::SysNSStringToUTF8(identity.gaiaID), base::SysNSStringToUTF8(identity.email)); - _identityManager->LegacyReloadAccountsFromSystem(); + _identityManager->GetDeviceAccountsSynchronizer() + ->ReloadAllAccountsFromSystem(); CHECK(_identityManager->HasAccountWithRefreshToken(accountId)); _identityManager->GetPrimaryAccountMutator()->SetPrimaryAccount(accountId); @@ -202,7 +204,8 @@ - (void)reloadCredentials { if (_currentIdentity != nil) { - _identityManager->LegacyReloadAccountsFromSystem(); + _identityManager->GetDeviceAccountsSynchronizer() + ->ReloadAllAccountsFromSystem(); } }
diff --git a/ios/web_view/internal/sync/cwv_sync_controller_internal.h b/ios/web_view/internal/sync/cwv_sync_controller_internal.h index e865deb..a93a54d 100644 --- a/ios/web_view/internal/sync/cwv_sync_controller_internal.h +++ b/ios/web_view/internal/sync/cwv_sync_controller_internal.h
@@ -7,7 +7,7 @@ #include <set> -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/public/base/signin_metrics.h" #include "google_apis/gaia/google_service_auth_error.h" #include "ios/web_view/internal/signin/web_view_device_accounts_provider_impl.h" #import "ios/web_view/public/cwv_sync_controller.h"
diff --git a/ios/web_view/internal/sync/web_view_device_info_sync_service_factory.mm b/ios/web_view/internal/sync/web_view_device_info_sync_service_factory.mm index a6f4bf9..5b5f7b41 100644 --- a/ios/web_view/internal/sync/web_view_device_info_sync_service_factory.mm +++ b/ios/web_view/internal/sync/web_view_device_info_sync_service_factory.mm
@@ -9,7 +9,7 @@ #include "base/bind.h" #include "base/memory/singleton.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" -#include "components/signin/core/browser/device_id_helper.h" +#include "components/signin/public/base/device_id_helper.h" #include "components/sync/model/model_type_store_service.h" #include "components/sync_device_info/device_info_sync_service_impl.h" #include "components/sync_device_info/local_device_info_provider_impl.h"
diff --git a/ipc/ipc_channel_proxy.cc b/ipc/ipc_channel_proxy.cc index 3a183ea..54179c0 100644 --- a/ipc/ipc_channel_proxy.cc +++ b/ipc/ipc_channel_proxy.cc
@@ -345,23 +345,22 @@ void ChannelProxy::Context::RemoveListenerTaskRunner(int32_t routing_id) { DCHECK(default_listener_task_runner_->BelongsToCurrentThread()); base::AutoLock lock(listener_thread_task_runners_lock_); - if (base::Contains(listener_thread_task_runners_, routing_id)) - listener_thread_task_runners_.erase(routing_id); + listener_thread_task_runners_.erase(routing_id); } // Called on the IPC::Channel thread. -base::SingleThreadTaskRunner* ChannelProxy::Context::GetTaskRunner( - int32_t routing_id) { +scoped_refptr<base::SingleThreadTaskRunner> +ChannelProxy::Context::GetTaskRunner(int32_t routing_id) { DCHECK(ipc_task_runner_->BelongsToCurrentThread()); if (routing_id == MSG_ROUTING_NONE) - return default_listener_task_runner_.get(); + return default_listener_task_runner_; base::AutoLock lock(listener_thread_task_runners_lock_); - base::SingleThreadTaskRunner* task_runner = - listener_thread_task_runners_[routing_id].get(); - if (task_runner) - return task_runner; - return default_listener_task_runner_.get(); + auto task_runner = listener_thread_task_runners_.find(routing_id); + if (task_runner == listener_thread_task_runners_.end()) + return default_listener_task_runner_; + DCHECK(task_runner->second); + return task_runner->second; } // Called on the listener's thread
diff --git a/ipc/ipc_channel_proxy.h b/ipc/ipc_channel_proxy.h index 8352a93..ae4e0d5 100644 --- a/ipc/ipc_channel_proxy.h +++ b/ipc/ipc_channel_proxy.h
@@ -282,7 +282,8 @@ // Called on the IPC::Channel thread. // Returns the task runner associated with |routing_id|. - base::SingleThreadTaskRunner* GetTaskRunner(int32_t routing_id); + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner( + int32_t routing_id); protected: friend class base::RefCountedThreadSafe<Context>;
diff --git a/media/audio/audio_output_device.cc b/media/audio/audio_output_device.cc index 0b4eda8f6..8d48e9c 100644 --- a/media/audio/audio_output_device.cc +++ b/media/audio/audio_output_device.cc
@@ -61,6 +61,7 @@ RenderCallback* callback) { DCHECK(!callback_) << "Calling Initialize() twice?"; DCHECK(params.IsValid()); + DVLOG(1) << __func__ << ": " << params.AsHumanReadableString(); audio_parameters_ = params; callback_ = callback; }
diff --git a/media/audio/win/audio_low_latency_output_win.cc b/media/audio/win/audio_low_latency_output_win.cc index 225682e..c128513 100644 --- a/media/audio/win/audio_low_latency_output_win.cc +++ b/media/audio/win/audio_low_latency_output_win.cc
@@ -68,6 +68,7 @@ DVLOG(1) << "WASAPIAudioOutputStream::WASAPIAudioOutputStream()"; DVLOG_IF(1, share_mode_ == AUDCLNT_SHAREMODE_EXCLUSIVE) << "Core Audio (WASAPI) EXCLUSIVE MODE is enabled."; + DVLOG(1) << params.AsHumanReadableString(); // Load the Avrt DLL if not already loaded. Required to support MMCSS. bool avrt_init = avrt::Initialize(); @@ -93,6 +94,7 @@ format_.Samples.wValidBitsPerSample = format->wBitsPerSample; format_.dwChannelMask = CoreAudioUtil::GetChannelConfig(device_id, eRender); format_.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; + DVLOG(1) << "Format: " << CoreAudioUtil::WaveFormatToString(&format_); // Store size (in different units) of audio packets which we expect to // get from the audio endpoint device in each render event.
diff --git a/media/base/byte_queue.cc b/media/base/byte_queue.cc index 08ac9a2..245fafa6 100644 --- a/media/base/byte_queue.cc +++ b/media/base/byte_queue.cc
@@ -5,17 +5,11 @@ #include "media/base/byte_queue.h" #include "base/logging.h" +#include "base/numerics/checked_math.h" namespace media { -// Default starting size for the queue. -enum { kDefaultQueueSize = 1024 }; - -ByteQueue::ByteQueue() - : buffer_(new uint8_t[kDefaultQueueSize]), - size_(kDefaultQueueSize), - offset_(0), - used_(0) {} +ByteQueue::ByteQueue() : buffer_(new uint8_t[size_]) {} ByteQueue::~ByteQueue() = default; @@ -28,40 +22,50 @@ DCHECK(data); DCHECK_GT(size, 0); - size_t size_needed = used_ + size; + // This can never overflow since used and size are both ints. + const size_t size_needed = static_cast<size_t>(used_) + size; // Check to see if we need a bigger buffer. if (size_needed > size_) { - size_t new_size = 2 * size_; - while (size_needed > new_size && new_size > size_) - new_size *= 2; - - // Sanity check to make sure we didn't overflow. - CHECK_GT(new_size, size_); - - std::unique_ptr<uint8_t[]> new_buffer(new uint8_t[new_size]); + // Growth is based on base::circular_deque which grows at 25%. + const size_t safe_size = + (base::CheckedNumeric<size_t>(size_) + size_ / 4).ValueOrDie(); + const size_t new_size = std::max(size_needed, safe_size); // Copy the data from the old buffer to the start of the new one. - if (used_ > 0) - memcpy(new_buffer.get(), front(), used_); + if (used_ > 0) { + // Note: We could use realloc() here, but would need an additional move to + // pack data at offset_ = 0 after a potential internal new allocation + + // copy by realloc(). + // + // In local tests on a few top video sites that ends up being the common + // case, so just prefer to copy and pack ourselves. + std::unique_ptr<uint8_t[]> new_buffer(new uint8_t[new_size]); + memcpy(new_buffer.get(), Front(), used_); + buffer_ = std::move(new_buffer); + } else { + // Free the existing |data| first so that the memory can be reused, if + // possible. Note that the new array is purposely not initialized. + buffer_.reset(); + buffer_.reset(new uint8_t[new_size]); + } - buffer_ = std::move(new_buffer); size_ = new_size; offset_ = 0; } else if ((offset_ + used_ + size) > size_) { // The buffer is big enough, but we need to move the data in the queue. - memmove(buffer_.get(), front(), used_); + memmove(buffer_.get(), Front(), used_); offset_ = 0; } - memcpy(front() + used_, data, size); + memcpy(Front() + used_, data, size); used_ += size; } void ByteQueue::Peek(const uint8_t** data, int* size) const { DCHECK(data); DCHECK(size); - *data = front(); + *data = Front(); *size = used_; } @@ -78,7 +82,7 @@ } } -uint8_t* ByteQueue::front() const { +uint8_t* ByteQueue::Front() const { return buffer_.get() + offset_; }
diff --git a/media/base/byte_queue.h b/media/base/byte_queue.h index d034da4..23270ac7 100644 --- a/media/base/byte_queue.h +++ b/media/base/byte_queue.h
@@ -15,9 +15,10 @@ namespace media { -// Represents a queue of bytes. -// Data is added to the end of the queue via an Push() call and removed via -// Pop(). The contents of the queue can be observed via the Peek() method. +// Represents a queue of bytes. Data is added to the end of the queue via an +// Push() call and removed via Pop(). The contents of the queue can be observed +// via the Peek() method. +// // This class manages the underlying storage of the queue and tries to minimize // the number of buffer copies when data is appended and removed. class MEDIA_EXPORT ByteQueue { @@ -31,28 +32,30 @@ // Appends new bytes onto the end of the queue. void Push(const uint8_t* data, int size); - // Get a pointer to the front of the queue and the queue size. - // These values are only valid until the next Push() or - // Pop() call. + // Get a pointer to the front of the queue and the queue size. These values + // are only valid until the next Push() or Pop() call. void Peek(const uint8_t** data, int* size) const; // Remove |count| bytes from the front of the queue. void Pop(int count); private: - // Returns a pointer to the front of the queue. - uint8_t* front() const; + // Default starting size for the queue. + enum { kDefaultQueueSize = 1024 }; - std::unique_ptr<uint8_t[]> buffer_; + // Returns a pointer to the front of the queue. + uint8_t* Front() const; // Size of |buffer_|. - size_t size_; + size_t size_ = kDefaultQueueSize; // Offset from the start of |buffer_| that marks the front of the queue. - size_t offset_; + size_t offset_ = 0u; - // Number of bytes stored in the queue. - int used_; + // Number of bytes stored in |buffer_|. + int used_ = 0; + + std::unique_ptr<uint8_t[]> buffer_; DISALLOW_COPY_AND_ASSIGN(ByteQueue); };
diff --git a/media/blink/BUILD.gn b/media/blink/BUILD.gn index 356c890..75fe7576a 100644 --- a/media/blink/BUILD.gn +++ b/media/blink/BUILD.gn
@@ -59,7 +59,6 @@ "webencryptedmediaclient_impl.h", "webinbandtexttrack_impl.cc", "webinbandtexttrack_impl.h", - "webmediaplayer_delegate.h", "webmediaplayer_params.cc", "webmediaplayer_params.h", "webmediaplayer_util.cc",
diff --git a/media/blink/webmediaplayer_impl.cc b/media/blink/webmediaplayer_impl.cc index 6c2ab21..3034da0e 100644 --- a/media/blink/webmediaplayer_impl.cc +++ b/media/blink/webmediaplayer_impl.cc
@@ -48,7 +48,6 @@ #include "media/blink/watch_time_reporter.h" #include "media/blink/webcontentdecryptionmodule_impl.h" #include "media/blink/webinbandtexttrack_impl.h" -#include "media/blink/webmediaplayer_delegate.h" #include "media/blink/webmediaplayer_util.h" #include "media/blink/webmediasource_impl.h" #include "media/filters/chunk_demuxer.h" @@ -279,7 +278,7 @@ blink::WebLocalFrame* frame, blink::WebMediaPlayerClient* client, blink::WebMediaPlayerEncryptedMediaClient* encrypted_client, - WebMediaPlayerDelegate* delegate, + blink::WebMediaPlayerDelegate* delegate, std::unique_ptr<RendererFactorySelector> renderer_factory_selector, UrlIndex* url_index, std::unique_ptr<VideoFrameCompositor> compositor, @@ -3484,7 +3483,7 @@ RecordTimingUMA("Media.TimeToFirstFrame", elapsed); // Needed to signal HTMLVideoElement that it should remove the poster image. - if (client_ && did_lazy_load_ && has_poster_) + if (client_ && has_poster_) client_->Repaint(); }
diff --git a/media/blink/webmediaplayer_impl.h b/media/blink/webmediaplayer_impl.h index ad191cbe..1356cda 100644 --- a/media/blink/webmediaplayer_impl.h +++ b/media/blink/webmediaplayer_impl.h
@@ -37,11 +37,11 @@ #include "media/blink/media_blink_export.h" #include "media/blink/multibuffer_data_source.h" #include "media/blink/video_frame_compositor.h" -#include "media/blink/webmediaplayer_delegate.h" #include "media/blink/webmediaplayer_params.h" #include "media/blink/webmediaplayer_util.h" #include "media/filters/pipeline_controller.h" #include "media/renderers/paint_canvas_video_renderer.h" +#include "third_party/blink/public/platform/media/webmediaplayer_delegate.h" #include "third_party/blink/public/platform/web_audio_source_provider.h" #include "third_party/blink/public/platform/web_content_decryption_module_result.h" #include "third_party/blink/public/platform/web_media_player.h" @@ -49,10 +49,10 @@ #include "url/gurl.h" namespace blink { +class WebAudioSourceProviderImpl; class WebLocalFrame; class WebMediaPlayerClient; class WebMediaPlayerEncryptedMediaClient; -class WebAudioSourceProviderImpl; } namespace base { @@ -79,14 +79,13 @@ class UrlIndex; class VideoFrameCompositor; class WatchTimeReporter; -class WebMediaPlayerDelegate; // The canonical implementation of blink::WebMediaPlayer that's backed by // Pipeline. Handles normal resource loading, Media Source, and // Encrypted Media. class MEDIA_BLINK_EXPORT WebMediaPlayerImpl : public blink::WebMediaPlayer, - public WebMediaPlayerDelegate::Observer, + public blink::WebMediaPlayerDelegate::Observer, public Pipeline::Client, public MediaObserverClient, public blink::WebSurfaceLayerBridgeObserver { @@ -97,7 +96,7 @@ blink::WebLocalFrame* frame, blink::WebMediaPlayerClient* client, blink::WebMediaPlayerEncryptedMediaClient* encrypted_client, - WebMediaPlayerDelegate* delegate, + blink::WebMediaPlayerDelegate* delegate, std::unique_ptr<RendererFactorySelector> renderer_factory_selector, UrlIndex* url_index, std::unique_ptr<VideoFrameCompositor> compositor, @@ -225,7 +224,7 @@ void OnHasNativeControlsChanged(bool) override; void OnDisplayTypeChanged(WebMediaPlayer::DisplayType) override; - // WebMediaPlayerDelegate::Observer implementation. + // blink::WebMediaPlayerDelegate::Observer implementation. void OnFrameHidden() override; void OnFrameClosed() override; void OnFrameShown() override; @@ -698,7 +697,7 @@ // Document::shutdown() is called before the frame detaches (and before the // frame is destroyed). RenderFrameImpl owns |delegate_| and is guaranteed // to outlive |this|; thus it is safe to store |delegate_| as a raw pointer. - media::WebMediaPlayerDelegate* const delegate_; + blink::WebMediaPlayerDelegate* const delegate_; int delegate_id_ = 0; WebMediaPlayerParams::DeferLoadCB defer_load_cb_;
diff --git a/media/blink/webmediaplayer_impl_unittest.cc b/media/blink/webmediaplayer_impl_unittest.cc index 355a4cfe..862f550 100644 --- a/media/blink/webmediaplayer_impl_unittest.cc +++ b/media/blink/webmediaplayer_impl_unittest.cc
@@ -37,7 +37,6 @@ #include "media/blink/mock_webassociatedurlloader.h" #include "media/blink/resource_multibuffer_data_provider.h" #include "media/blink/video_decode_stats_reporter.h" -#include "media/blink/webmediaplayer_delegate.h" #include "media/blink/webmediaplayer_params.h" #include "media/mojo/services/media_metrics_provider.h" #include "media/mojo/services/video_decode_stats_recorder.h" @@ -48,6 +47,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/mojom/frame/document_interface_broker.mojom.h" +#include "third_party/blink/public/platform/media/webmediaplayer_delegate.h" #include "third_party/blink/public/platform/web_fullscreen_video_status.h" #include "third_party/blink/public/platform/web_media_player.h" #include "third_party/blink/public/platform/web_media_player_client.h" @@ -175,12 +175,12 @@ DISALLOW_COPY_AND_ASSIGN(MockWebMediaPlayerEncryptedMediaClient); }; -class MockWebMediaPlayerDelegate : public WebMediaPlayerDelegate { +class MockWebMediaPlayerDelegate : public blink::WebMediaPlayerDelegate { public: MockWebMediaPlayerDelegate() = default; ~MockWebMediaPlayerDelegate() override = default; - // WebMediaPlayerDelegate implementation. + // blink::WebMediaPlayerDelegate implementation. int AddObserver(Observer* observer) override { DCHECK_EQ(nullptr, observer_); observer_ = observer;
diff --git a/media/capture/video/chromeos/mojo/cros_image_capture.mojom b/media/capture/video/chromeos/mojo/cros_image_capture.mojom index 215f191..dcdb702 100644 --- a/media/capture/video/chromeos/mojo/cros_image_capture.mojom +++ b/media/capture/video/chromeos/mojo/cros_image_capture.mojom
@@ -33,14 +33,15 @@ SetReprocessOption(string source_id, Effect effect) => (int32 status, media.mojom.Blob blob); - // Sets the frame rate range for upcoming configured camera stream. + // Sets the fps range for upcoming configured camera stream. // The |source_id| might need translation to be actual video device id. // The |stream_width| and |stream_height| are the target stream resolution - // that the caller sets the frame rate range for. - // The |min_frame_rate| and |max_frame_rate| represent the frame rate range. - // If the given frame rate is valid and set successfully, |is_success| returns - // true. False otherwise. + // that the caller sets the fps range for. + // The |min_fps| and |max_fps| represent the target fps range. + // If the given fps range is valid and set successfully, |is_success| returns + // true. If the given fps range is invalid, the fps range which is cached + // previously will be cleared and |is_success| will return false. SetFpsRange(string source_id, uint32 stream_width, uint32 stream_height, - int32 min_frame_rate, int32 max_frame_rate) + int32 min_fps, int32 max_fps) => (bool is_success); }; \ No newline at end of file
diff --git a/media/capture/video/chromeos/reprocess_manager.cc b/media/capture/video/chromeos/reprocess_manager.cc index 3c0776c..d2c9798 100644 --- a/media/capture/video/chromeos/reprocess_manager.cc +++ b/media/capture/video/chromeos/reprocess_manager.cc
@@ -211,14 +211,21 @@ } } + auto resolution = gfx::Size(stream_width, stream_height); + auto& fps_map = resolution_fps_range_map_[device_id]; if (!is_valid) { + // If the input range is invalid, we should still clear the cache range so + // that it will fallback to use default fps range rather than the cache one. + auto it = fps_map.find(resolution); + if (it != fps_map.end()) { + fps_map.erase(it); + } std::move(callback).Run(false); return; } - auto resolution = gfx::Size(stream_width, stream_height); auto fps_range = gfx::Range(min_fps, max_fps); - resolution_fps_range_map_[device_id][resolution] = fps_range; + fps_map[resolution] = fps_range; std::move(callback).Run(true); }
diff --git a/media/gpu/BUILD.gn b/media/gpu/BUILD.gn index c500e5c9..f7387029 100644 --- a/media/gpu/BUILD.gn +++ b/media/gpu/BUILD.gn
@@ -193,6 +193,8 @@ "windows/init_guid.cc", "windows/media_foundation_video_encode_accelerator_win.cc", "windows/media_foundation_video_encode_accelerator_win.h", + "windows/supported_profile_helpers.cc", + "windows/supported_profile_helpers.h", ] configs += [ # TODO(https://crbug.com/167187): Fix size_t to int truncations.
diff --git a/media/gpu/test/video_player/frame_renderer_dummy.cc b/media/gpu/test/video_player/frame_renderer_dummy.cc index aecafcaf..1b99099 100644 --- a/media/gpu/test/video_player/frame_renderer_dummy.cc +++ b/media/gpu/test/video_player/frame_renderer_dummy.cc
@@ -10,6 +10,7 @@ #include "base/memory/ptr_util.h" #include "media/gpu/macros.h" +#include "media/gpu/test/video_frame_helpers.h" namespace media { namespace test { @@ -130,7 +131,16 @@ const gfx::Size& size, uint32_t texture_target, uint32_t* texture_id) { - return nullptr; + *texture_id = 0; + + // Create a dummy video frame. No actual rendering will be done but the video + // frame's properties such as timestamp will be used. + // TODO(dstaessens): Remove this function when allocate mode is deprecated. + base::Optional<VideoFrameLayout> layout = + CreateVideoFrameLayout(pixel_format, size); + DCHECK(layout); + return VideoFrame::WrapExternalDataWithLayout(*layout, gfx::Rect(size), size, + nullptr, 0, base::TimeDelta()); } uint64_t FrameRendererDummy::FramesDropped() const {
diff --git a/media/gpu/test/video_player/test_vda_video_decoder.cc b/media/gpu/test/video_player/test_vda_video_decoder.cc index a9a53b63..63dd2ce4 100644 --- a/media/gpu/test/video_player/test_vda_video_decoder.cc +++ b/media/gpu/test/video_player/test_vda_video_decoder.cc
@@ -192,12 +192,16 @@ const gfx::Rect& visible_rect, uint32_t texture_target) { DCHECK_CALLED_ON_VALID_SEQUENCE(vda_wrapper_sequence_checker_); - ASSERT_NE(format, PIXEL_FORMAT_UNKNOWN); ASSERT_EQ(textures_per_buffer, 1u); DVLOGF(4) << "Requested " << requested_num_of_buffers << " picture buffers with size " << dimensions.height() << "x" << dimensions.height(); + // If using allocate mode the format requested here might be + // PIXEL_FORMAT_UNKNOWN. + if (format == PIXEL_FORMAT_UNKNOWN) + format = PIXEL_FORMAT_ARGB; + std::vector<PictureBuffer> picture_buffers; switch (output_mode_) { @@ -276,33 +280,33 @@ ASSERT_NE(timestamp_it, decode_start_timestamps_.end()); video_frame->set_timestamp(timestamp_it->second); - // When using import mode, we wrap the video frame in another video frame that - // calls ReusePictureBufferTask() upon destruction. When the renderer and - // video frame processors are done using the video frame, the associated - // picture buffer will automatically be flagged for reuse. - if (output_mode_ == VideoDecodeAccelerator::Config::OutputMode::IMPORT) { - base::OnceClosure reuse_cb = BindToCurrentLoop( - base::BindOnce(&TestVDAVideoDecoder::ReusePictureBufferTask, weak_this_, - picture.picture_buffer_id())); + scoped_refptr<VideoFrame> wrapped_video_frame = nullptr; - scoped_refptr<VideoFrame> wrapped_video_frame = VideoFrame::WrapVideoFrame( + // Wrap the video frame in another frame that calls ReusePictureBufferTask() + // upon destruction. When the renderer and video frame processors are done + // using the video frame, the associated picture buffer will automatically be + // flagged for reuse. WrapVideoFrame() is not supported for texture-based + // video frames (see http://crbug/362521) so we work around this by creating a + // new video frame using the same mailbox. + if (!video_frame->HasTextures()) { + wrapped_video_frame = VideoFrame::WrapVideoFrame( *video_frame, video_frame->format(), picture.visible_rect(), picture.visible_rect().size()); - wrapped_video_frame->AddDestructionObserver(std::move(reuse_cb)); - - output_cb_.Run(wrapped_video_frame); + } else { + gpu::MailboxHolder mailbox_holders[media::VideoFrame::kMaxPlanes]; + mailbox_holders[0] = video_frame->mailbox_holder(0); + wrapped_video_frame = VideoFrame::WrapNativeTextures( + video_frame->format(), mailbox_holders, VideoFrame::ReleaseMailboxCB(), + video_frame->coded_size(), video_frame->visible_rect(), + video_frame->natural_size(), video_frame->timestamp()); } - // Wrapping a video frame inside another video frame is not supported in - // allocate mode, so we have to render the frame and return the picture buffer - // synchronously here. See http://crbug/362521. - if (output_mode_ == VideoDecodeAccelerator::Config::OutputMode::ALLOCATE) { - PostTaskAndReply( - FROM_HERE, base::BindOnce(output_cb_, video_frame), - base::BindOnce(&TestVDAVideoDecoder::ReusePictureBufferTask, weak_this_, - picture.picture_buffer_id())); - return; - } + DCHECK(wrapped_video_frame); + base::OnceClosure reuse_cb = BindToCurrentLoop( + base::BindOnce(&TestVDAVideoDecoder::ReusePictureBufferTask, weak_this_, + picture.picture_buffer_id())); + wrapped_video_frame->AddDestructionObserver(std::move(reuse_cb)); + output_cb_.Run(std::move(wrapped_video_frame)); } // Called when a picture buffer is ready to be re-used.
diff --git a/media/gpu/test/video_player/video_decoder_client.cc b/media/gpu/test/video_player/video_decoder_client.cc index 3bb4702..f7d4c87 100644 --- a/media/gpu/test/video_player/video_decoder_client.cc +++ b/media/gpu/test/video_player/video_decoder_client.cc
@@ -43,13 +43,6 @@ video_(video) { DETACH_FROM_SEQUENCE(decoder_client_sequence_checker_); - // Video frame processors are currently only supported in import mode, as - // wrapping texture-backed video frames is not supported (See - // http://crbug/362521). - LOG_ASSERT(config.allocation_mode == AllocationMode::kImport || - frame_processors.size() == 0) - << "Video frame processors are only supported when using import mode"; - weak_this_ = weak_this_factory_.GetWeakPtr(); } @@ -337,16 +330,10 @@ void VideoDecoderClient::FrameReadyTask(scoped_refptr<VideoFrame> video_frame) { DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_client_sequence_checker_); - // When using allocate mode the frame will be reused after this function, so - // the frame should be rendered synchronously in this case. frame_renderer_->RenderFrame(video_frame); - // When using allocate mode, direct texture memory access is not supported. - // Since this is required by the video frame processors we can't use these. - if (decoder_client_config_.allocation_mode == AllocationMode::kImport) { - for (auto& frame_processor : frame_processors_) - frame_processor->ProcessVideoFrame(video_frame, current_frame_index_); - } + for (auto& frame_processor : frame_processors_) + frame_processor->ProcessVideoFrame(video_frame, current_frame_index_); // Notify the test a frame has been decoded. We should only do this after // scheduling the frame to be processed, so calling WaitForFrameProcessors()
diff --git a/media/gpu/v4l2/v4l2_slice_video_decoder.cc b/media/gpu/v4l2/v4l2_slice_video_decoder.cc index b984c70..ba40afef 100644 --- a/media/gpu/v4l2/v4l2_slice_video_decoder.cc +++ b/media/gpu/v4l2/v4l2_slice_video_decoder.cc
@@ -82,9 +82,14 @@ const OutputRequestType type; // The surface to be outputted. scoped_refptr<V4L2DecodeSurface> surface; + // The timestamp of the output frame. Because a surface might be outputted + // multiple times with different timestamp, we need to store timestamp out of + // surface. + base::TimeDelta timestamp; - static OutputRequest Surface(scoped_refptr<V4L2DecodeSurface> s) { - return OutputRequest(std::move(s)); + static OutputRequest Surface(scoped_refptr<V4L2DecodeSurface> s, + base::TimeDelta t) { + return OutputRequest(std::move(s), t); } static OutputRequest FlushFence() { return OutputRequest(kFlushFence); } @@ -101,8 +106,8 @@ OutputRequest(OutputRequest&&) = default; private: - explicit OutputRequest(scoped_refptr<V4L2DecodeSurface> s) - : type(kSurface), surface(std::move(s)) {} + OutputRequest(scoped_refptr<V4L2DecodeSurface> s, base::TimeDelta t) + : type(kSurface), surface(std::move(s)), timestamp(t) {} explicit OutputRequest(OutputRequestType t) : type(t) {} DISALLOW_COPY_AND_ASSIGN(OutputRequest); @@ -545,8 +550,12 @@ void V4L2SliceVideoDecoder::EnqueueDecodeTask(DecodeRequest request) { DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_); - DCHECK(state_ == State::kDecoding || state_ == State::kPause); + DCHECK(state_ == State::kDecoding || state_ == State::kFlushing); + if (!request.buffer->end_of_stream()) { + bitstream_id_to_timestamp_.emplace(request.bitstream_id, + request.buffer->timestamp()); + } decode_request_queue_.push(std::move(request)); // If we are already decoding, then we don't need to pump again. if (!current_decode_request_) @@ -555,18 +564,19 @@ void V4L2SliceVideoDecoder::PumpDecodeTask() { DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_); - DCHECK(state_ == State::kDecoding || state_ == State::kPause); + DCHECK(state_ == State::kDecoding || state_ == State::kFlushing); DVLOGF(3) << "state_:" << static_cast<int>(state_) << " Number of Decode requests: " << decode_request_queue_.size(); - if (state_ == State::kPause) + if (state_ == State::kFlushing) return; + pause_reason_ = PauseReason::kNone; while (true) { switch (avd_->Decode()) { case AcceleratedVideoDecoder::kAllocateNewSurfaces: DVLOGF(3) << "Need to change resolution. Pause decoding."; - SetState(State::kPause); + SetState(State::kFlushing); output_request_queue_.push(OutputRequest::ChangeResolutionFence()); PumpOutputSurfaces(); @@ -596,7 +606,7 @@ // Put the decoder in an idle state, ready to resume. avd_->Reset(); - SetState(State::kPause); + SetState(State::kFlushing); DCHECK(!flush_cb_); flush_cb_ = std::move(current_decode_request_->decode_cb); @@ -612,10 +622,12 @@ case AcceleratedVideoDecoder::kRanOutOfSurfaces: DVLOGF(3) << "Ran out of surfaces. Resume when buffer is returned."; + pause_reason_ = PauseReason::kRanOutOfSurfaces; return; case AcceleratedVideoDecoder::kNeedContextUpdate: DVLOGF(3) << "Awaiting context update"; + pause_reason_ = PauseReason::kWaitSubFrameDecoded; return; case AcceleratedVideoDecoder::kDecodeError: @@ -668,7 +680,7 @@ scoped_refptr<V4L2DecodeSurface> surface = std::move(request.surface); DCHECK(surface->video_frame()); - RunOutputCB(surface->video_frame()); + RunOutputCB(surface->video_frame(), request.timestamp); break; } } @@ -683,7 +695,7 @@ bool V4L2SliceVideoDecoder::ChangeResolution() { DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_); - DCHECK_EQ(state_, State::kPause); + DCHECK_EQ(state_, State::kFlushing); // We change resolution after outputting all pending surfaces, there should // be no V4L2DecodeSurface left. DCHECK(surfaces_at_device_.empty()); @@ -784,7 +796,7 @@ DVLOGF(3) << "Reuse output surface #" << buffer->BufferId(); // Resume decoding in case of ran out of surface. - if (state_ == State::kDecoding) { + if (pause_reason_ == PauseReason::kRanOutOfSurfaces) { decoder_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecoder::PumpDecodeTask, weak_this_)); @@ -856,10 +868,16 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_); DVLOGF(3); + auto it = bitstream_id_to_timestamp_.find(bitstream_id); + DCHECK(it != bitstream_id_to_timestamp_.end()); + base::TimeDelta timestamp = it->second; + bitstream_id_to_timestamp_.erase(it); + // TODO(akahuang): Update visible_rect at the output frame. dec_surface->SetVisibleRect(visible_rect); - output_request_queue_.push(OutputRequest::Surface(std::move(dec_surface))); + output_request_queue_.push( + OutputRequest::Surface(std::move(dec_surface), timestamp)); PumpOutputSurfaces(); } @@ -966,6 +984,7 @@ << ", Number of queued output buffers: " << output_queue_->QueuedBuffersCount(); + bool resume_decode = false; // Dequeue V4L2 output buffer first to reduce output latency. bool success; V4L2ReadableBufferRef dequeued_buffer; @@ -986,6 +1005,9 @@ surfaces_at_device_.pop(); surface->SetDecoded(); + // VP9Decoder update context after surface is decoded. Resume decoding for + // previous pause of AVD::kWaitSubFrameDecoded. + resume_decode = true; // Keep a reference to the V4L2 buffer until the buffer is reused. The // reason for this is that the config store uses V4L2 buffer IDs to @@ -1012,6 +1034,12 @@ } SchedulePollTaskIfNeeded(); + + if (resume_decode && pause_reason_ == PauseReason::kWaitSubFrameDecoded) { + decoder_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&V4L2SliceVideoDecoder::PumpDecodeTask, weak_this_)); + } } int32_t V4L2SliceVideoDecoder::GetNextBitstreamId() { @@ -1028,10 +1056,23 @@ base::BindOnce(std::move(cb), status)); } -void V4L2SliceVideoDecoder::RunOutputCB(scoped_refptr<VideoFrame> frame) { +void V4L2SliceVideoDecoder::RunOutputCB(scoped_refptr<VideoFrame> frame, + base::TimeDelta timestamp) { DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_); + DVLOGF(4) << "timestamp: " << timestamp; + // The attribute of the frame is needed to update. Wrap the frame again. + if (frame->timestamp() != timestamp) { + scoped_refptr<VideoFrame> wrapped_frame = VideoFrame::WrapVideoFrame( + *frame, frame->format(), frame->visible_rect(), frame->natural_size()); + wrapped_frame->set_timestamp(timestamp); + wrapped_frame->AddDestructionObserver(base::BindOnce( + base::DoNothing::Once<scoped_refptr<VideoFrame>>(), std::move(frame))); + + frame = std::move(wrapped_frame); + } frame->metadata()->SetBoolean(VideoFrameMetadata::POWER_EFFICIENT, true); + scoped_refptr<VideoFrame> converted_frame = frame_converter_->ConvertFrame(std::move(frame)); if (!converted_frame) { @@ -1039,6 +1080,7 @@ SetState(State::kError); return; } + // Although the document of VideoDecoder says "should run |output_cb| as soon // as possible (without thread trampolining)", MojoVideoDecoderService still // assumes the callback is called at original thread. @@ -1071,9 +1113,9 @@ case State::kDecoding: break; - case State::kPause: + case State::kFlushing: if (state_ != State::kDecoding) { - VLOGF(1) << "kPause should only be set when kDecoding."; + VLOGF(1) << "kFlushing should only be set when kDecoding."; new_state = State::kError; } break;
diff --git a/media/gpu/v4l2/v4l2_slice_video_decoder.h b/media/gpu/v4l2/v4l2_slice_video_decoder.h index 64eab649..acb2d062 100644 --- a/media/gpu/v4l2/v4l2_slice_video_decoder.h +++ b/media/gpu/v4l2/v4l2_slice_video_decoder.h
@@ -110,16 +110,28 @@ // Initial state. Transitions to |kDecoding| if Initialize() is successful, // |kError| otherwise. kUninitialized, - // Transitions to |kPause| when flushing or changing resolution, + // Transitions to |kFlushing| when flushing or changing resolution, // |kError| if any unexpected error occurs. kDecoding, // Transitions to |kDecoding| when flushing or changing resolution is - // finished. - kPause, + // finished. Do not process new input buffer in this state. + kFlushing, // Error state. Cannot transition to other state anymore. kError, }; + // The reason the decoding is paused. + enum class PauseReason { + // Not stopped, decoding normally. + kNone, + // Cannot create a new V4L2 surface. Waiting for surfaces to be released. + kRanOutOfSurfaces, + // A VP9 superframe contains multiple subframes. Before decoding the next + // subframe, we need to wait for previous subframes decoded and update the + // context. + kWaitSubFrameDecoded, + }; + // Initialize on decoder thread. void InitializeTask(const VideoDecoderConfig& config, InitCB init_cb, @@ -176,7 +188,7 @@ // Get the next bitsream ID. int32_t GetNextBitstreamId(); // Convert the frame and call the output callback. - void RunOutputCB(scoped_refptr<VideoFrame> frame); + void RunOutputCB(scoped_refptr<VideoFrame> frame, base::TimeDelta timestamp); // Call the decode callback and count the number of pending callbacks. void RunDecodeCB(DecodeCB cb, DecodeStatus status); // Change the state and check the state transition is valid. @@ -202,6 +214,8 @@ // State of the instance. State state_; + // Indicates why decoding is currently paused. + PauseReason pause_reason_ = PauseReason::kNone; // Parameters for generating output VideoFrame. base::Optional<VideoFrameLayout> frame_layout_; @@ -216,6 +230,9 @@ scoped_refptr<V4L2Queue> input_queue_; scoped_refptr<V4L2Queue> output_queue_; + // The mapping between bitstream id and the timestamp. + std::map<int32_t, base::TimeDelta> bitstream_id_to_timestamp_; + // Queue of pending decode request. base::queue<DecodeRequest> decode_request_queue_; // Surfaces enqueued to V4L2 device. Since we are stateless, they are
diff --git a/media/gpu/video_decode_accelerator_perf_tests.cc b/media/gpu/video_decode_accelerator_perf_tests.cc index 8cd9b39..12c424c7 100644 --- a/media/gpu/video_decode_accelerator_perf_tests.cc +++ b/media/gpu/video_decode_accelerator_perf_tests.cc
@@ -317,6 +317,10 @@ VideoDecoderClientConfig config; config.use_vd = g_env->UseVD(); + // Force allocate mode if import mode is not supported. + if (!g_env->ImportSupported()) + config.allocation_mode = AllocationMode::kAllocate; + return VideoPlayer::Create(video, std::move(frame_renderer), std::move(frame_processors), config); }
diff --git a/media/gpu/video_decode_accelerator_tests.cc b/media/gpu/video_decode_accelerator_tests.cc index a4dda81..20ec349 100644 --- a/media/gpu/video_decode_accelerator_tests.cc +++ b/media/gpu/video_decode_accelerator_tests.cc
@@ -39,8 +39,7 @@ " -v enable verbose mode, e.g. -v=2.\n" " --vmodule enable verbose mode for the specified module,\n" " e.g. --vmodule=*media/gpu*=2.\n" - " --disable_validator disable frame validation, useful on old\n" - " platforms that don't support import mode.\n" + " --disable_validator disable frame validation.\n" " --output_frames write all decoded video frames to the\n" " \"<testname>\" folder.\n" " --output_folder overwrite the default output folder used when\n" @@ -63,8 +62,9 @@ LOG_ASSERT(video); std::vector<std::unique_ptr<VideoFrameProcessor>> frame_processors; - // Validate decoded video frames. - if (g_env->IsValidatorEnabled()) { + // Use the video frame validator to validate decoded video frames if import + // mode is supported. + if (g_env->IsValidatorEnabled() && g_env->ImportSupported()) { frame_processors.push_back( media::test::VideoFrameValidator::Create(video->FrameChecksums())); } @@ -257,12 +257,11 @@ // Play a video from start to finish. Thumbnails of the decoded frames will be // rendered into a image, whose checksum is compared to a golden value. This -// test is only needed on older platforms that don't support the video frame -// validator, which requires direct access to the video frame's memory. This -// test is only ran when --disable_validator is specified, and will be -// deprecated in the future. +// test is only run on older platforms that don't support the video frame +// validator, which requires import mode. This test will be deprecated once all +// devices support import mode. TEST_F(VideoDecoderTest, FlushAtEndOfStream_RenderThumbnails) { - if (g_env->IsValidatorEnabled()) + if (!g_env->IsValidatorEnabled() || g_env->ImportSupported()) GTEST_SKIP(); base::FilePath output_folder = @@ -286,6 +285,27 @@ ->ValidateThumbnail()); } +// Play a video from start to finish, using allocate mode. This test is only run +// on platforms that support import mode, as on allocate-mode only platforms all +// tests are run in allocate mode. The test will be skipped when --use_vd is +// specified as the new video decoders only support import mode. +// TODO(dstaessens): Deprecate after switching to new VD-based video decoders. +TEST_F(VideoDecoderTest, FlushAtEndOfStream_Allocate) { + if (!g_env->ImportSupported() || g_env->UseVD()) + GTEST_SKIP(); + + VideoDecoderClientConfig config; + config.allocation_mode = AllocationMode::kAllocate; + auto tvp = CreateVideoPlayer(g_env->Video(), config); + + tvp->Play(); + EXPECT_TRUE(tvp->WaitForFlushDone()); + + EXPECT_EQ(tvp->GetFlushDoneCount(), 1u); + EXPECT_EQ(tvp->GetFrameDecodedCount(), g_env->Video()->NumFrames()); + EXPECT_TRUE(tvp->WaitForFrameProcessors()); +} + } // namespace test } // namespace media
diff --git a/media/gpu/windows/dxva_video_decode_accelerator_win.cc b/media/gpu/windows/dxva_video_decode_accelerator_win.cc index 93d7452..77c8c84 100644 --- a/media/gpu/windows/dxva_video_decode_accelerator_win.cc +++ b/media/gpu/windows/dxva_video_decode_accelerator_win.cc
@@ -51,6 +51,7 @@ #include "media/base/win/mf_initializer.h" #include "media/filters/vp9_parser.h" #include "media/gpu/windows/dxva_picture_buffer_win.h" +#include "media/gpu/windows/supported_profile_helpers.h" #include "media/video/h264_parser.h" #include "media/video/video_decode_accelerator.h" #include "third_party/angle/include/EGL/egl.h" @@ -118,56 +119,6 @@ 0x4c54, {0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6}}; -// R600, R700, Evergreen and Cayman AMD cards. These support DXVA via UVD3 -// or earlier, and don't handle resolutions higher than 1920 x 1088 well. -// -// NOTE: This list must be kept in sorted order. -static const uint16_t kLegacyAmdGpuList[] = { - 0x130f, 0x6700, 0x6701, 0x6702, 0x6703, 0x6704, 0x6705, 0x6706, 0x6707, - 0x6708, 0x6709, 0x6718, 0x6719, 0x671c, 0x671d, 0x671f, 0x6720, 0x6721, - 0x6722, 0x6723, 0x6724, 0x6725, 0x6726, 0x6727, 0x6728, 0x6729, 0x6738, - 0x6739, 0x673e, 0x6740, 0x6741, 0x6742, 0x6743, 0x6744, 0x6745, 0x6746, - 0x6747, 0x6748, 0x6749, 0x674a, 0x6750, 0x6751, 0x6758, 0x6759, 0x675b, - 0x675d, 0x675f, 0x6760, 0x6761, 0x6762, 0x6763, 0x6764, 0x6765, 0x6766, - 0x6767, 0x6768, 0x6770, 0x6771, 0x6772, 0x6778, 0x6779, 0x677b, 0x6798, - 0x67b1, 0x6821, 0x683d, 0x6840, 0x6841, 0x6842, 0x6843, 0x6849, 0x6850, - 0x6858, 0x6859, 0x6880, 0x6888, 0x6889, 0x688a, 0x688c, 0x688d, 0x6898, - 0x6899, 0x689b, 0x689c, 0x689d, 0x689e, 0x68a0, 0x68a1, 0x68a8, 0x68a9, - 0x68b0, 0x68b8, 0x68b9, 0x68ba, 0x68be, 0x68bf, 0x68c0, 0x68c1, 0x68c7, - 0x68c8, 0x68c9, 0x68d8, 0x68d9, 0x68da, 0x68de, 0x68e0, 0x68e1, 0x68e4, - 0x68e5, 0x68e8, 0x68e9, 0x68f1, 0x68f2, 0x68f8, 0x68f9, 0x68fa, 0x68fe, - 0x9400, 0x9401, 0x9402, 0x9403, 0x9405, 0x940a, 0x940b, 0x940f, 0x9440, - 0x9441, 0x9442, 0x9443, 0x9444, 0x9446, 0x944a, 0x944b, 0x944c, 0x944e, - 0x9450, 0x9452, 0x9456, 0x945a, 0x945b, 0x945e, 0x9460, 0x9462, 0x946a, - 0x946b, 0x947a, 0x947b, 0x9480, 0x9487, 0x9488, 0x9489, 0x948a, 0x948f, - 0x9490, 0x9491, 0x9495, 0x9498, 0x949c, 0x949e, 0x949f, 0x94a0, 0x94a1, - 0x94a3, 0x94b1, 0x94b3, 0x94b4, 0x94b5, 0x94b9, 0x94c0, 0x94c1, 0x94c3, - 0x94c4, 0x94c5, 0x94c6, 0x94c7, 0x94c8, 0x94c9, 0x94cb, 0x94cc, 0x94cd, - 0x9500, 0x9501, 0x9504, 0x9505, 0x9506, 0x9507, 0x9508, 0x9509, 0x950f, - 0x9511, 0x9515, 0x9517, 0x9519, 0x9540, 0x9541, 0x9542, 0x954e, 0x954f, - 0x9552, 0x9553, 0x9555, 0x9557, 0x955f, 0x9580, 0x9581, 0x9583, 0x9586, - 0x9587, 0x9588, 0x9589, 0x958a, 0x958b, 0x958c, 0x958d, 0x958e, 0x958f, - 0x9590, 0x9591, 0x9593, 0x9595, 0x9596, 0x9597, 0x9598, 0x9599, 0x959b, - 0x95c0, 0x95c2, 0x95c4, 0x95c5, 0x95c6, 0x95c7, 0x95c9, 0x95cc, 0x95cd, - 0x95ce, 0x95cf, 0x9610, 0x9611, 0x9612, 0x9613, 0x9614, 0x9615, 0x9616, - 0x9640, 0x9641, 0x9642, 0x9643, 0x9644, 0x9645, 0x9647, 0x9648, 0x9649, - 0x964a, 0x964b, 0x964c, 0x964e, 0x964f, 0x9710, 0x9711, 0x9712, 0x9713, - 0x9714, 0x9715, 0x9802, 0x9803, 0x9804, 0x9805, 0x9806, 0x9807, 0x9808, - 0x9809, 0x980a, 0x9830, 0x983d, 0x9850, 0x9851, 0x9874, 0x9900, 0x9901, - 0x9903, 0x9904, 0x9905, 0x9906, 0x9907, 0x9908, 0x9909, 0x990a, 0x990b, - 0x990c, 0x990d, 0x990e, 0x990f, 0x9910, 0x9913, 0x9917, 0x9918, 0x9919, - 0x9990, 0x9991, 0x9992, 0x9993, 0x9994, 0x9995, 0x9996, 0x9997, 0x9998, - 0x9999, 0x999a, 0x999b, 0x999c, 0x999d, 0x99a0, 0x99a2, 0x99a4}; - -// Legacy Intel GPUs which have trouble even querying if resolutions higher than -// 1920 x 1088 are supported. Updated based on crash reports. -// -// NOTE: This list must be kept in sorted order. -static const uint16_t kLegacyIntelGpuList[] = { - 0x102, 0x106, 0x116, 0x126, 0x152, 0x156, 0x166, - 0x402, 0x406, 0x416, 0x41e, 0xa06, 0xa16, 0xf31, -}; - constexpr const wchar_t* const kMediaFoundationVideoDecoderDLLs[] = { L"mf.dll", L"mfplat.dll", L"msmpeg2vdec.dll", }; @@ -183,143 +134,6 @@ uint64_t g_last_process_output_time; HRESULT g_last_device_removed_reason; -// Certain AMD GPU drivers like R600, R700, Evergreen and Cayman and some second -// generation Intel GPU drivers crash if we create a video device with a -// resolution higher then 1920 x 1088. This function checks if the GPU is in -// this list and if yes returns true. -bool IsLegacyGPU(ID3D11Device* device) { - DCHECK(std::is_sorted(std::begin(kLegacyAmdGpuList), - std::end(kLegacyAmdGpuList))); - DCHECK(std::is_sorted(std::begin(kLegacyIntelGpuList), - std::end(kLegacyIntelGpuList))); - - constexpr int kAMDGPUId1 = 0x1002; - constexpr int kAMDGPUId2 = 0x1022; - constexpr int kIntelGPU = 0x8086; - - Microsoft::WRL::ComPtr<IDXGIDevice> dxgi_device; - HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&dxgi_device)); - if (FAILED(hr)) - return true; - - Microsoft::WRL::ComPtr<IDXGIAdapter> adapter; - hr = dxgi_device->GetAdapter(&adapter); - if (FAILED(hr)) - return true; - - DXGI_ADAPTER_DESC adapter_desc = {}; - hr = adapter->GetDesc(&adapter_desc); - if (FAILED(hr)) - return true; - - // All the values in the legacy gpu list are uint16_t. - if (adapter_desc.DeviceId > std::numeric_limits<uint16_t>::max()) - return false; - - const uint16_t device_id = adapter_desc.DeviceId; - - // We check if the device is an Intel or an AMD device and whether it is in - // the global list defined by the kLegacyAmdGpuList and kLegacyIntelGpuList - // arrays above. If yes then the device is treated as a legacy device. - if (adapter_desc.VendorId == kAMDGPUId1 || - adapter_desc.VendorId == kAMDGPUId2) { - if (std::binary_search(std::begin(kLegacyAmdGpuList), - std::end(kLegacyAmdGpuList), device_id)) { - return true; - } - } else if (adapter_desc.VendorId == kIntelGPU) { - if (std::binary_search(std::begin(kLegacyIntelGpuList), - std::end(kLegacyIntelGpuList), device_id)) { - return true; - } - } - - return false; -} - -// Returns true if a ID3D11VideoDecoder can be created for |resolution_to_test| -// on the given |video_device|. -bool IsResolutionSupportedForDevice(const gfx::Size& resolution_to_test, - const GUID& decoder_guid, - ID3D11VideoDevice* video_device, - DXGI_FORMAT format) { - D3D11_VIDEO_DECODER_DESC desc = { - decoder_guid, // Guid - resolution_to_test.width(), // SampleWidth - resolution_to_test.height(), // SampleHeight - format // OutputFormat - }; - - // We've chosen the least expensive test for identifying if a given resolution - // is supported. Actually creating the VideoDecoder instance only fails ~0.4% - // of the time and the outcome is that we will offer support and then - // immediately fall back to software; e.g., playback still works. Since these - // calls can take hundreds of milliseconds to complete and are often executed - // during startup, this seems a reasonably trade off. - // - // See the deprecated histograms Media.DXVAVDA.GetDecoderConfigStatus which - // succeeds 100% of the time and Media.DXVAVDA.CreateDecoderStatus which - // only succeeds 99.6% of the time (in a 28 day aggregation). - UINT config_count; - return SUCCEEDED( - video_device->GetVideoDecoderConfigCount(&desc, &config_count)) && - config_count > 0; -} - -// Returns a tuple of (LandscapeMax, PortraitMax). If landscape maximum can not -// be computed, the value of |default_max| is returned for the landscape maximum -// and a zero size value is returned for portrait max (erring conservatively). -using ResolutionPair = std::pair<gfx::Size, gfx::Size>; -ResolutionPair GetMaxResolutionsForGUIDs( - const gfx::Size& default_max, - ID3D11VideoDevice* video_device, - const std::vector<GUID>& valid_guids, - const std::vector<gfx::Size>& resolutions_to_test, - DXGI_FORMAT format = DXGI_FORMAT_NV12) { - TRACE_EVENT0("gpu,startup", "GetMaxResolutionsForGUIDs"); - ResolutionPair result(default_max, gfx::Size()); - - // Enumerate supported video profiles and look for the profile. - GUID decoder_guid = GUID_NULL; - UINT profile_count = video_device->GetVideoDecoderProfileCount(); - for (UINT profile_idx = 0; profile_idx < profile_count; profile_idx++) { - GUID profile_id = {}; - if (SUCCEEDED( - video_device->GetVideoDecoderProfile(profile_idx, &profile_id)) && - std::find(valid_guids.begin(), valid_guids.end(), profile_id) != - valid_guids.end()) { - decoder_guid = profile_id; - break; - } - } - if (decoder_guid == GUID_NULL) - return result; - - // Verify input is in ascending order by height. - DCHECK(std::is_sorted(resolutions_to_test.begin(), resolutions_to_test.end(), - [](const gfx::Size& a, const gfx::Size& b) { - return a.height() < b.height(); - })); - - for (const auto& res : resolutions_to_test) { - if (!IsResolutionSupportedForDevice(res, decoder_guid, video_device, - format)) { - break; - } - result.first = res; - } - - // The max supported portrait resolution should be just be a w/h flip of the - // max supported landscape resolution. - gfx::Size flipped(result.first.height(), result.first.width()); - if (IsResolutionSupportedForDevice(flipped, decoder_guid, video_device, - format)) { - result.second = flipped; - } - - return result; -} - } // namespace namespace media { @@ -1422,45 +1236,10 @@ ResolutionPair max_vp9_profile0_resolutions; ResolutionPair max_vp9_profile2_resolutions; - if (base::win::GetVersion() > base::win::Version::WIN7) { - // To detect if a driver supports the desired resolutions, we try and create - // a DXVA decoder instance for that resolution and profile. If that succeeds - // we assume that the driver supports decoding for that resolution. - ComD3D11Device device = gl::QueryD3D11DeviceObjectFromANGLE(); - - // Legacy AMD drivers with UVD3 or earlier and some Intel GPU's crash while - // creating surfaces larger than 1920 x 1088. - if (device && !IsLegacyGPU(device.Get())) { - ComD3D11VideoDevice video_device; - if (SUCCEEDED(device.As(&video_device))) { - max_h264_resolutions = GetMaxResolutionsForGUIDs( - max_h264_resolutions.first, video_device.Get(), - {DXVA2_ModeH264_E, DXVA2_Intel_ModeH264_E}, - {gfx::Size(2560, 1440), gfx::Size(3840, 2160), - gfx::Size(4096, 2160), gfx::Size(4096, 2304)}); - - if (!workarounds.disable_accelerated_vpx_decode) { - max_vp9_profile0_resolutions = GetMaxResolutionsForGUIDs( - max_vp9_profile0_resolutions.first, video_device.Get(), - {D3D11_DECODER_PROFILE_VP9_VLD_PROFILE0}, - {gfx::Size(4096, 2160), gfx::Size(4096, 2304), - gfx::Size(7680, 4320), gfx::Size(8192, 4320), - gfx::Size(8192, 8192)}); - - // RS3 has issues with VP9.2 decoding. See https://crbug.com/937108. - if (base::win::GetVersion() != base::win::Version::WIN10_RS3) { - max_vp9_profile2_resolutions = GetMaxResolutionsForGUIDs( - max_vp9_profile2_resolutions.first, video_device.Get(), - {D3D11_DECODER_PROFILE_VP9_VLD_10BIT_PROFILE2}, - {gfx::Size(4096, 2160), gfx::Size(4096, 2304), - gfx::Size(7680, 4320), gfx::Size(8192, 4320), - gfx::Size(8192, 8192)}, - DXGI_FORMAT_P010); - } - } - } - } - } + GetResolutionsForDecoders( + {DXVA2_ModeH264_E, DXVA2_Intel_ModeH264_E}, + gl::QueryD3D11DeviceObjectFromANGLE(), workarounds, &max_h264_resolutions, + &max_vp9_profile0_resolutions, &max_vp9_profile2_resolutions); for (const auto& supported_profile : kSupportedProfiles) { const bool is_h264 = supported_profile >= H264PROFILE_MIN &&
diff --git a/media/gpu/windows/supported_profile_helpers.cc b/media/gpu/windows/supported_profile_helpers.cc new file mode 100644 index 0000000..b7b24694 --- /dev/null +++ b/media/gpu/windows/supported_profile_helpers.cc
@@ -0,0 +1,255 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "media/gpu/windows/supported_profile_helpers.h" + +#include <algorithm> +#include <limits> +#include <memory> +#include <utility> + +#include "base/trace_event/trace_event.h" +#include "base/win/windows_version.h" +#include "build/build_config.h" +#include "gpu/config/gpu_driver_bug_workarounds.h" + +#if !defined(OS_WIN) +#error This file should only be built on Windows. +#endif // !defined(OS_WIN) + +namespace { + +// R600, R700, Evergreen and Cayman AMD cards. These support DXVA via UVD3 +// or earlier, and don't handle resolutions higher than 1920 x 1088 well. +// +// NOTE: This list must be kept in sorted order. +static const uint16_t kLegacyAmdGpuList[] = { + 0x130f, 0x6700, 0x6701, 0x6702, 0x6703, 0x6704, 0x6705, 0x6706, 0x6707, + 0x6708, 0x6709, 0x6718, 0x6719, 0x671c, 0x671d, 0x671f, 0x6720, 0x6721, + 0x6722, 0x6723, 0x6724, 0x6725, 0x6726, 0x6727, 0x6728, 0x6729, 0x6738, + 0x6739, 0x673e, 0x6740, 0x6741, 0x6742, 0x6743, 0x6744, 0x6745, 0x6746, + 0x6747, 0x6748, 0x6749, 0x674a, 0x6750, 0x6751, 0x6758, 0x6759, 0x675b, + 0x675d, 0x675f, 0x6760, 0x6761, 0x6762, 0x6763, 0x6764, 0x6765, 0x6766, + 0x6767, 0x6768, 0x6770, 0x6771, 0x6772, 0x6778, 0x6779, 0x677b, 0x6798, + 0x67b1, 0x6821, 0x683d, 0x6840, 0x6841, 0x6842, 0x6843, 0x6849, 0x6850, + 0x6858, 0x6859, 0x6880, 0x6888, 0x6889, 0x688a, 0x688c, 0x688d, 0x6898, + 0x6899, 0x689b, 0x689c, 0x689d, 0x689e, 0x68a0, 0x68a1, 0x68a8, 0x68a9, + 0x68b0, 0x68b8, 0x68b9, 0x68ba, 0x68be, 0x68bf, 0x68c0, 0x68c1, 0x68c7, + 0x68c8, 0x68c9, 0x68d8, 0x68d9, 0x68da, 0x68de, 0x68e0, 0x68e1, 0x68e4, + 0x68e5, 0x68e8, 0x68e9, 0x68f1, 0x68f2, 0x68f8, 0x68f9, 0x68fa, 0x68fe, + 0x9400, 0x9401, 0x9402, 0x9403, 0x9405, 0x940a, 0x940b, 0x940f, 0x9440, + 0x9441, 0x9442, 0x9443, 0x9444, 0x9446, 0x944a, 0x944b, 0x944c, 0x944e, + 0x9450, 0x9452, 0x9456, 0x945a, 0x945b, 0x945e, 0x9460, 0x9462, 0x946a, + 0x946b, 0x947a, 0x947b, 0x9480, 0x9487, 0x9488, 0x9489, 0x948a, 0x948f, + 0x9490, 0x9491, 0x9495, 0x9498, 0x949c, 0x949e, 0x949f, 0x94a0, 0x94a1, + 0x94a3, 0x94b1, 0x94b3, 0x94b4, 0x94b5, 0x94b9, 0x94c0, 0x94c1, 0x94c3, + 0x94c4, 0x94c5, 0x94c6, 0x94c7, 0x94c8, 0x94c9, 0x94cb, 0x94cc, 0x94cd, + 0x9500, 0x9501, 0x9504, 0x9505, 0x9506, 0x9507, 0x9508, 0x9509, 0x950f, + 0x9511, 0x9515, 0x9517, 0x9519, 0x9540, 0x9541, 0x9542, 0x954e, 0x954f, + 0x9552, 0x9553, 0x9555, 0x9557, 0x955f, 0x9580, 0x9581, 0x9583, 0x9586, + 0x9587, 0x9588, 0x9589, 0x958a, 0x958b, 0x958c, 0x958d, 0x958e, 0x958f, + 0x9590, 0x9591, 0x9593, 0x9595, 0x9596, 0x9597, 0x9598, 0x9599, 0x959b, + 0x95c0, 0x95c2, 0x95c4, 0x95c5, 0x95c6, 0x95c7, 0x95c9, 0x95cc, 0x95cd, + 0x95ce, 0x95cf, 0x9610, 0x9611, 0x9612, 0x9613, 0x9614, 0x9615, 0x9616, + 0x9640, 0x9641, 0x9642, 0x9643, 0x9644, 0x9645, 0x9647, 0x9648, 0x9649, + 0x964a, 0x964b, 0x964c, 0x964e, 0x964f, 0x9710, 0x9711, 0x9712, 0x9713, + 0x9714, 0x9715, 0x9802, 0x9803, 0x9804, 0x9805, 0x9806, 0x9807, 0x9808, + 0x9809, 0x980a, 0x9830, 0x983d, 0x9850, 0x9851, 0x9874, 0x9900, 0x9901, + 0x9903, 0x9904, 0x9905, 0x9906, 0x9907, 0x9908, 0x9909, 0x990a, 0x990b, + 0x990c, 0x990d, 0x990e, 0x990f, 0x9910, 0x9913, 0x9917, 0x9918, 0x9919, + 0x9990, 0x9991, 0x9992, 0x9993, 0x9994, 0x9995, 0x9996, 0x9997, 0x9998, + 0x9999, 0x999a, 0x999b, 0x999c, 0x999d, 0x99a0, 0x99a2, 0x99a4}; + +// Legacy Intel GPUs which have trouble even querying if resolutions higher than +// 1920 x 1088 are supported. Updated based on crash reports. +// +// NOTE: This list must be kept in sorted order. +static const uint16_t kLegacyIntelGpuList[] = { + 0x102, 0x106, 0x116, 0x126, 0x152, 0x156, 0x166, + 0x402, 0x406, 0x416, 0x41e, 0xa06, 0xa16, 0xf31, +}; + +} // namespace + +namespace media { + +// Certain AMD GPU drivers like R600, R700, Evergreen and Cayman and some second +// generation Intel GPU drivers crash if we create a video device with a +// resolution higher then 1920 x 1088. This function checks if the GPU is in +// this list and if yes returns true. +bool IsLegacyGPU(ID3D11Device* device) { + DCHECK(std::is_sorted(std::begin(kLegacyAmdGpuList), + std::end(kLegacyAmdGpuList))); + DCHECK(std::is_sorted(std::begin(kLegacyIntelGpuList), + std::end(kLegacyIntelGpuList))); + + constexpr int kAMDGPUId1 = 0x1002; + constexpr int kAMDGPUId2 = 0x1022; + constexpr int kIntelGPU = 0x8086; + + Microsoft::WRL::ComPtr<IDXGIDevice> dxgi_device; + HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&dxgi_device)); + if (FAILED(hr)) + return true; + + Microsoft::WRL::ComPtr<IDXGIAdapter> adapter; + hr = dxgi_device->GetAdapter(&adapter); + if (FAILED(hr)) + return true; + + DXGI_ADAPTER_DESC adapter_desc = {}; + hr = adapter->GetDesc(&adapter_desc); + if (FAILED(hr)) + return true; + + // All the values in the legacy gpu list are uint16_t. + if (adapter_desc.DeviceId > std::numeric_limits<uint16_t>::max()) + return false; + + const uint16_t device_id = adapter_desc.DeviceId; + + // We check if the device is an Intel or an AMD device and whether it is in + // the global list defined by the kLegacyAmdGpuList and kLegacyIntelGpuList + // arrays above. If yes then the device is treated as a legacy device. + if (adapter_desc.VendorId == kAMDGPUId1 || + adapter_desc.VendorId == kAMDGPUId2) { + if (std::binary_search(std::begin(kLegacyAmdGpuList), + std::end(kLegacyAmdGpuList), device_id)) { + return true; + } + } else if (adapter_desc.VendorId == kIntelGPU) { + if (std::binary_search(std::begin(kLegacyIntelGpuList), + std::end(kLegacyIntelGpuList), device_id)) { + return true; + } + } + + return false; +} + +bool IsResolutionSupportedForDevice(const gfx::Size& resolution_to_test, + const GUID& decoder_guid, + ID3D11VideoDevice* video_device, + DXGI_FORMAT format) { + D3D11_VIDEO_DECODER_DESC desc = { + decoder_guid, // Guid + resolution_to_test.width(), // SampleWidth + resolution_to_test.height(), // SampleHeight + format // OutputFormat + }; + + // We've chosen the least expensive test for identifying if a given resolution + // is supported. Actually creating the VideoDecoder instance only fails ~0.4% + // of the time and the outcome is that we will offer support and then + // immediately fall back to software; e.g., playback still works. Since these + // calls can take hundreds of milliseconds to complete and are often executed + // during startup, this seems a reasonably trade off. + // + // See the deprecated histograms Media.DXVAVDA.GetDecoderConfigStatus which + // succeeds 100% of the time and Media.DXVAVDA.CreateDecoderStatus which + // only succeeds 99.6% of the time (in a 28 day aggregation). + UINT config_count; + return SUCCEEDED( + video_device->GetVideoDecoderConfigCount(&desc, &config_count)) && + config_count > 0; +} + +// Returns a tuple of (LandscapeMax, PortraitMax). If landscape maximum can not +// be computed, the value of |default_max| is returned for the landscape maximum +// and a zero size value is returned for portrait max (erring conservatively). +ResolutionPair GetMaxResolutionsForGUIDs( + const gfx::Size& default_max, + ID3D11VideoDevice* video_device, + const std::vector<GUID>& valid_guids, + const std::vector<gfx::Size>& resolutions_to_test, + DXGI_FORMAT format) { + TRACE_EVENT0("gpu,startup", "GetMaxResolutionsForGUIDs"); + ResolutionPair result(default_max, gfx::Size()); + + // Enumerate supported video profiles and look for the profile. + GUID decoder_guid = GUID_NULL; + UINT profile_count = video_device->GetVideoDecoderProfileCount(); + for (UINT profile_idx = 0; profile_idx < profile_count; profile_idx++) { + GUID profile_id = {}; + if (SUCCEEDED( + video_device->GetVideoDecoderProfile(profile_idx, &profile_id)) && + std::find(valid_guids.begin(), valid_guids.end(), profile_id) != + valid_guids.end()) { + decoder_guid = profile_id; + break; + } + } + if (decoder_guid == GUID_NULL) + return result; + + // Verify input is in ascending order by height. + DCHECK(std::is_sorted(resolutions_to_test.begin(), resolutions_to_test.end(), + [](const gfx::Size& a, const gfx::Size& b) { + return a.height() < b.height(); + })); + + for (const auto& res : resolutions_to_test) { + if (!media::IsResolutionSupportedForDevice(res, decoder_guid, video_device, + format)) { + break; + } + result.first = res; + } + + // The max supported portrait resolution should be just be a w/h flip of the + // max supported landscape resolution. + gfx::Size flipped(result.first.height(), result.first.width()); + if (media::IsResolutionSupportedForDevice(flipped, decoder_guid, video_device, + format)) { + result.second = flipped; + } + + return result; +} + +void GetResolutionsForDecoders(std::vector<GUID> h264_guids, + ComD3D11Device device, + const gpu::GpuDriverBugWorkarounds& workarounds, + ResolutionPair* h264_resolutions, + ResolutionPair* vp9_0_resolutions, + ResolutionPair* vp9_2_resolutions) { + if (base::win::GetVersion() > base::win::Version::WIN7) { + // To detect if a driver supports the desired resolutions, we try and create + // a DXVA decoder instance for that resolution and profile. If that succeeds + // we assume that the driver supports decoding for that resolution. + // Legacy AMD drivers with UVD3 or earlier and some Intel GPU's crash while + // creating surfaces larger than 1920 x 1088. + if (device && !IsLegacyGPU(device.Get())) { + ComD3D11VideoDevice video_device; + if (SUCCEEDED(device.As(&video_device))) { + *h264_resolutions = GetMaxResolutionsForGUIDs( + h264_resolutions->first, video_device.Get(), h264_guids, + {gfx::Size(2560, 1440), gfx::Size(3840, 2160), + gfx::Size(4096, 2160), gfx::Size(4096, 2304)}); + + if (!workarounds.disable_accelerated_vpx_decode) { + *vp9_0_resolutions = GetMaxResolutionsForGUIDs( + vp9_0_resolutions->first, video_device.Get(), + {D3D11_DECODER_PROFILE_VP9_VLD_PROFILE0}, + {gfx::Size(4096, 2160), gfx::Size(4096, 2304), + gfx::Size(7680, 4320), gfx::Size(8192, 4320), + gfx::Size(8192, 8192)}); + + // RS3 has issues with VP9.2 decoding. See https://crbug.com/937108. + if (base::win::GetVersion() != base::win::Version::WIN10_RS3) { + *vp9_2_resolutions = GetMaxResolutionsForGUIDs( + vp9_2_resolutions->first, video_device.Get(), + {D3D11_DECODER_PROFILE_VP9_VLD_10BIT_PROFILE2}, + {gfx::Size(4096, 2160), gfx::Size(4096, 2304), + gfx::Size(7680, 4320), gfx::Size(8192, 4320), + gfx::Size(8192, 8192)}, + DXGI_FORMAT_P010); + } + } + } + } + } +} + +} // namespace media
diff --git a/media/gpu/windows/supported_profile_helpers.h b/media/gpu/windows/supported_profile_helpers.h new file mode 100644 index 0000000..62d77480 --- /dev/null +++ b/media/gpu/windows/supported_profile_helpers.h
@@ -0,0 +1,47 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef MEDIA_GPU_WINDOWS_SUPPORTED_PROFILE_HELPERS_H_ +#define MEDIA_GPU_WINDOWS_SUPPORTED_PROFILE_HELPERS_H_ + +#include <d3d11_1.h> +#include <wrl/client.h> +#include <memory> +#include <utility> +#include <vector> + +#include "gpu/config/gpu_driver_bug_workarounds.h" +#include "media/gpu/windows/d3d11_com_defs.h" +#include "ui/gfx/geometry/rect.h" + +namespace media { + +using ResolutionPair = std::pair<gfx::Size, gfx::Size>; + +bool IsLegacyGPU(ID3D11Device* device); + +// Returns true if a ID3D11VideoDecoder can be created for |resolution_to_test| +// on the given |video_device|. +bool IsResolutionSupportedForDevice(const gfx::Size& resolution_to_test, + const GUID& decoder_guid, + ID3D11VideoDevice* video_device, + DXGI_FORMAT format); + +ResolutionPair GetMaxResolutionsForGUIDs( + const gfx::Size& default_max, + ID3D11VideoDevice* video_device, + const std::vector<GUID>& valid_guids, + const std::vector<gfx::Size>& resolutions_to_test, + DXGI_FORMAT format = DXGI_FORMAT_NV12); + +void GetResolutionsForDecoders(std::vector<GUID> h264_guids, + ComD3D11Device device, + const gpu::GpuDriverBugWorkarounds& workarounds, + ResolutionPair* h264_resolutions, + ResolutionPair* vp9_0_resolutions, + ResolutionPair* vp9_2_resolutions); + +} // namespace media + +#endif // MEDIA_GPU_WINDOWS_SUPPORTED_PROFILE_HELPERS_H_
diff --git a/net/cert/ct_signed_certificate_timestamp_log_param.h b/net/cert/ct_signed_certificate_timestamp_log_param.h index 89eb38ce..644f96e 100644 --- a/net/cert/ct_signed_certificate_timestamp_log_param.h +++ b/net/cert/ct_signed_certificate_timestamp_log_param.h
@@ -9,6 +9,7 @@ #include "base/strings/string_piece.h" #include "net/cert/signed_certificate_timestamp_and_status.h" +#include "net/log/net_log_capture_mode.h" namespace base { class Value; @@ -16,8 +17,6 @@ namespace net { -class NetLogCaptureMode; - // Creates a dictionary of processed Signed Certificate Timestamps to be // logged in the NetLog. // See the documentation for SIGNED_CERTIFICATE_TIMESTAMPS_CHECKED
diff --git a/net/cert/multi_threaded_cert_verifier.cc b/net/cert/multi_threaded_cert_verifier.cc index e2c6013..4489af1 100644 --- a/net/cert/multi_threaded_cert_verifier.cc +++ b/net/cert/multi_threaded_cert_verifier.cc
@@ -35,8 +35,6 @@ namespace net { -class NetLogCaptureMode; - // Allows DoVerifyOnWorkerThread to wait on a base::WaitableEvent. // DoVerifyOnWorkerThread may wait on network operations done on a separate // sequence. For instance when using the NSS-based implementation of certificate
diff --git a/net/cert/x509_certificate_net_log_param.h b/net/cert/x509_certificate_net_log_param.h index c328189..a84bdc4 100644 --- a/net/cert/x509_certificate_net_log_param.h +++ b/net/cert/x509_certificate_net_log_param.h
@@ -8,6 +8,7 @@ #include <memory> #include "net/base/net_export.h" +#include "net/log/net_log_capture_mode.h" namespace base { class Value; @@ -15,7 +16,6 @@ namespace net { -class NetLogCaptureMode; class X509Certificate; // Creates NetLog parameter to describe an X509Certificate.
diff --git a/net/cookies/cookie_monster_netlog_params.cc b/net/cookies/cookie_monster_netlog_params.cc index f7a58843..9b8f4811 100644 --- a/net/cookies/cookie_monster_netlog_params.cc +++ b/net/cookies/cookie_monster_netlog_params.cc
@@ -20,7 +20,7 @@ base::Value NetLogCookieMonsterCookieAdded(const CanonicalCookie* cookie, bool sync_requested, NetLogCaptureMode capture_mode) { - if (!capture_mode.include_cookies_and_credentials()) + if (!NetLogCaptureIncludesSensitive(capture_mode)) return base::Value(); base::Value dict(base::Value::Type::DICTIONARY); @@ -41,7 +41,7 @@ CookieChangeCause cause, bool sync_requested, NetLogCaptureMode capture_mode) { - if (!capture_mode.include_cookies_and_credentials()) + if (!NetLogCaptureIncludesSensitive(capture_mode)) return base::Value(); base::Value dict(base::Value::Type::DICTIONARY); @@ -59,7 +59,7 @@ const CanonicalCookie* old_cookie, const CanonicalCookie* new_cookie, NetLogCaptureMode capture_mode) { - if (!capture_mode.include_cookies_and_credentials()) + if (!NetLogCaptureIncludesSensitive(capture_mode)) return base::Value(); base::Value dict(base::Value::Type::DICTIONARY); dict.SetStringKey("name", old_cookie->Name()); @@ -75,7 +75,7 @@ const CanonicalCookie* old_cookie, const CanonicalCookie* new_cookie, NetLogCaptureMode capture_mode) { - if (!capture_mode.include_cookies_and_credentials()) + if (!NetLogCaptureIncludesSensitive(capture_mode)) return base::Value(); base::Value dict(base::Value::Type::DICTIONARY); dict.SetStringKey("name", old_cookie->Name()); @@ -91,7 +91,7 @@ const CanonicalCookie* preserved, const CanonicalCookie* new_cookie, NetLogCaptureMode capture_mode) { - if (!capture_mode.include_cookies_and_credentials()) + if (!NetLogCaptureIncludesSensitive(capture_mode)) return base::Value(); base::Value dict(base::Value::Type::DICTIONARY); dict.SetStringKey("name", preserved->Name());
diff --git a/net/dns/dns_transaction_unittest.cc b/net/dns/dns_transaction_unittest.cc index ec5f56e..42bd4ae 100644 --- a/net/dns/dns_transaction_unittest.cc +++ b/net/dns/dns_transaction_unittest.cc
@@ -1946,8 +1946,7 @@ TransactionHelper helper0(kT0HostName, kT0Qtype, true /* secure */, kT0RecordCount); CountingObserver observer; - helper0.net_log()->AddObserver(&observer, - NetLogCaptureMode::IncludeSocketBytes()); + helper0.net_log()->AddObserver(&observer, NetLogCaptureMode::kEverything); EXPECT_TRUE(helper0.RunUntilDone(transaction_factory_.get())); base::RunLoop().RunUntilIdle(); EXPECT_EQ(observer.count(), 5);
diff --git a/net/extras/sqlite/sqlite_persistent_cookie_store.cc b/net/extras/sqlite/sqlite_persistent_cookie_store.cc index 6b86778..9f3e319 100644 --- a/net/extras/sqlite/sqlite_persistent_cookie_store.cc +++ b/net/extras/sqlite/sqlite_persistent_cookie_store.cc
@@ -47,7 +47,7 @@ base::Value CookieKeyedLoadNetLogCallback(const std::string& key, net::NetLogCaptureMode capture_mode) { - if (!capture_mode.include_cookies_and_credentials()) + if (!net::NetLogCaptureIncludesSensitive(capture_mode)) return base::Value(); base::DictionaryValue dict; dict.SetString("key", key);
diff --git a/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc b/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc index dc3612a..6c76aff 100644 --- a/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc +++ b/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc
@@ -392,7 +392,7 @@ base::Unretained(this)), net_log.bound()); base::RunLoop run_loop; - net_log.SetCaptureMode(NetLogCaptureMode::Default()); + net_log.SetCaptureMode(NetLogCaptureMode::kDefault); store_->LoadCookiesForKey( "aaa.com", base::Bind(&SQLitePersistentCookieStoreTest::OnKeyLoaded, base::Unretained(this), run_loop.QuitClosure()));
diff --git a/net/http/bidirectional_stream_unittest.cc b/net/http/bidirectional_stream_unittest.cc index 319e455c4..76cb401 100644 --- a/net/http/bidirectional_stream_unittest.cc +++ b/net/http/bidirectional_stream_unittest.cc
@@ -408,7 +408,7 @@ ssl_data_.next_proto = kProtoHTTP2; ssl_data_.ssl_info.cert = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); - net_log_.SetCaptureMode(NetLogCaptureMode::IncludeSocketBytes()); + net_log_.SetCaptureMode(NetLogCaptureMode::kEverything); socket_factory_ = new MockTaggingClientSocketFactory(); session_deps_.socket_factory.reset(socket_factory_); }
diff --git a/net/http/http_auth_handler_negotiate.cc b/net/http/http_auth_handler_negotiate.cc index 612e52e..8ff3f96c 100644 --- a/net/http/http_auth_handler_negotiate.cc +++ b/net/http/http_auth_handler_negotiate.cc
@@ -36,7 +36,7 @@ const std::string& channel_binding_token, NetLogCaptureMode capture_mode) { base::DictionaryValue dict; - if (!capture_mode.include_socket_bytes()) + if (!NetLogCaptureIncludesSocketBytes(capture_mode)) return std::move(dict); dict.Clear();
diff --git a/net/http/http_log_util.cc b/net/http/http_log_util.cc index 699dd80..4ef9b4b 100644 --- a/net/http/http_log_util.cc +++ b/net/http/http_log_util.cc
@@ -41,7 +41,7 @@ std::string::const_iterator redact_end = value.begin(); if (redact_begin == redact_end && - !capture_mode.include_cookies_and_credentials()) { + !NetLogCaptureIncludesSensitive(capture_mode)) { if (base::EqualsCaseInsensitiveASCII(header, "set-cookie") || base::EqualsCaseInsensitiveASCII(header, "set-cookie2") || base::EqualsCaseInsensitiveASCII(header, "cookie") ||
diff --git a/net/http/http_log_util_unittest.cc b/net/http/http_log_util_unittest.cc index 9b6ec8f8..c4406c8 100644 --- a/net/http/http_log_util_unittest.cc +++ b/net/http/http_log_util_unittest.cc
@@ -11,61 +11,61 @@ TEST(HttpLogUtilTest, ElideHeaderValueForNetLog) { // Only elide for appropriate log level. EXPECT_EQ("[10 bytes were stripped]", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), "Cookie", + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "Cookie", "name=value")); - EXPECT_EQ("name=value", ElideHeaderValueForNetLog( - NetLogCaptureMode::IncludeCookiesAndCredentials(), - "Cookie", "name=value")); + EXPECT_EQ("name=value", + ElideHeaderValueForNetLog(NetLogCaptureMode::kIncludeSensitive, + "Cookie", "name=value")); // Headers are compared case insensitively. EXPECT_EQ("[10 bytes were stripped]", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), "cOoKiE", + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "cOoKiE", "name=value")); // These headers should be completely elided. EXPECT_EQ("[10 bytes were stripped]", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), - "Set-Cookie", "name=value")); + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "Set-Cookie", + "name=value")); EXPECT_EQ("[10 bytes were stripped]", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "Set-Cookie2", "name=value")); EXPECT_EQ("[10 bytes were stripped]", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "Authorization", "Basic 1234")); EXPECT_EQ("[10 bytes were stripped]", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "Proxy-Authorization", "Basic 1234")); // Unknown headers should pass through. - EXPECT_EQ("value", ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), + EXPECT_EQ("value", ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "Boring", "value")); // Basic and Digest auth challenges are public. EXPECT_EQ("Basic realm=test", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "WWW-Authenticate", "Basic realm=test")); EXPECT_EQ("Digest realm=test", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "WWW-Authenticate", "Digest realm=test")); EXPECT_EQ("Basic realm=test", ElideHeaderValueForNetLog( - NetLogCaptureMode::Default(), + NetLogCaptureMode::kDefault, "Proxy-Authenticate", "Basic realm=test")); EXPECT_EQ( "Digest realm=test", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "Proxy-Authenticate", "Digest realm=test")); // Multi-round mechanisms partially elided. EXPECT_EQ("NTLM [4 bytes were stripped]", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "WWW-Authenticate", "NTLM 1234")); EXPECT_EQ("NTLM [4 bytes were stripped]", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "Proxy-Authenticate", "NTLM 1234")); // Leave whitespace intact. EXPECT_EQ("NTLM [4 bytes were stripped] ", - ElideHeaderValueForNetLog(NetLogCaptureMode::Default(), + ElideHeaderValueForNetLog(NetLogCaptureMode::kDefault, "WWW-Authenticate", "NTLM 1234 ")); }
diff --git a/net/http/http_network_transaction.cc b/net/http/http_network_transaction.cc index 4e86490..0c0ab0f 100644 --- a/net/http/http_network_transaction.cc +++ b/net/http/http_network_transaction.cc
@@ -399,9 +399,6 @@ DCHECK(proxy_info_.is_http() || proxy_info_.is_https() || proxy_info_.is_quic()); DCHECK_EQ(headers->response_code(), HTTP_PROXY_AUTHENTICATION_REQUIRED); - LOG(WARNING) << "Blocked proxy response with status " - << headers->response_code() << " to CONNECT request for " - << GetHostAndPort(url_) << "."; return ERR_TUNNEL_CONNECTION_FAILED; }
diff --git a/net/http/http_request_headers.h b/net/http/http_request_headers.h index 2ec412731..55d8e179 100644 --- a/net/http/http_request_headers.h +++ b/net/http/http_request_headers.h
@@ -17,6 +17,7 @@ #include "base/macros.h" #include "base/strings/string_piece.h" #include "net/base/net_export.h" +#include "net/log/net_log_capture_mode.h" namespace base { class Value; @@ -24,8 +25,6 @@ namespace net { -class NetLogCaptureMode; - class NET_EXPORT HttpRequestHeaders { public: struct NET_EXPORT HeaderKeyValuePair {
diff --git a/net/http/http_response_headers.h b/net/http/http_response_headers.h index be21635..c3b42e2 100644 --- a/net/http/http_response_headers.h +++ b/net/http/http_response_headers.h
@@ -18,6 +18,7 @@ #include "base/time/time.h" #include "net/base/net_export.h" #include "net/http/http_version.h" +#include "net/log/net_log_capture_mode.h" namespace base { class Pickle; @@ -30,7 +31,6 @@ namespace net { class HttpByteRange; -class NetLogCaptureMode; enum ValidationType { VALIDATION_NONE, // The resource is fresh.
diff --git a/net/log/file_net_log_observer.h b/net/log/file_net_log_observer.h index 02d9a78..66c80ca 100644 --- a/net/log/file_net_log_observer.h +++ b/net/log/file_net_log_observer.h
@@ -23,8 +23,6 @@ namespace net { -class NetLogCaptureMode; - // FileNetLogObserver watches the NetLog event stream and sends all entries to // a file. //
diff --git a/net/log/file_net_log_observer_unittest.cc b/net/log/file_net_log_observer_unittest.cc index b5ec383..fc0a00e 100644 --- a/net/log/file_net_log_observer_unittest.cc +++ b/net/log/file_net_log_observer_unittest.cc
@@ -62,8 +62,7 @@ NetLogEntryData base_entry_data(NetLogEventType::PAC_JAVASCRIPT_ERROR, source, NetLogEventPhase::BEGIN, base::TimeTicks::Now(), &callback); - NetLogEntry base_entry(&base_entry_data, - NetLogCaptureMode::IncludeSocketBytes()); + NetLogEntry base_entry(&base_entry_data, NetLogCaptureMode::kEverything); base::Value value = base_entry.ToValue(); std::string json; base::JSONWriter::Write(value, &json); @@ -93,7 +92,7 @@ NetLogEntryData entry_data(NetLogEventType::PAC_JAVASCRIPT_ERROR, source, NetLogEventPhase::BEGIN, base::TimeTicks::Now(), &callback); - NetLogEntry entry(&entry_data, NetLogCaptureMode::IncludeSocketBytes()); + NetLogEntry entry(&entry_data, NetLogCaptureMode::kEverything); logger->OnAddEntry(entry); } } @@ -253,7 +252,7 @@ FileNetLogObserver::CreateUnbounded(log_path_, std::move(constants)); } - logger_->StartObserving(&net_log_, NetLogCaptureMode::Default()); + logger_->StartObserving(&net_log_, NetLogCaptureMode::kDefault); } void CreateAndStartObservingPreExisting( @@ -275,7 +274,7 @@ std::move(file), std::move(constants)); } - logger_->StartObserving(&net_log_, NetLogCaptureMode::Default()); + logger_->StartObserving(&net_log_, NetLogCaptureMode::kDefault); } bool LogFileExists() { @@ -314,7 +313,7 @@ int num_files) { logger_ = FileNetLogObserver::CreateBoundedForTests( log_path_, total_file_size, num_files, std::move(constants)); - logger_->StartObserving(&net_log_, NetLogCaptureMode::Default()); + logger_->StartObserving(&net_log_, NetLogCaptureMode::kDefault); } // Returns the path for an internally directory created for bounded logs (this @@ -500,7 +499,7 @@ else logger_ = FileNetLogObserver::CreateUnboundedPreExisting(std::move(file), nullptr); - logger_->StartObserving(&net_log_, NetLogCaptureMode::Default()); + logger_->StartObserving(&net_log_, NetLogCaptureMode::kDefault); // Send dummy event. AddEntries(logger_.get(), 1, kDummyEventSize); @@ -954,7 +953,7 @@ logger_ = FileNetLogObserver::CreateBoundedPreExisting( scratch_dir.GetPath(), std::move(file), kLargeFileSize, nullptr); - logger_->StartObserving(&net_log_, NetLogCaptureMode::Default()); + logger_->StartObserving(&net_log_, NetLogCaptureMode::kDefault); base::ThreadPoolInstance::Get()->FlushForTesting(); EXPECT_TRUE(base::PathExists(log_path_));
diff --git a/net/log/net_log.cc b/net/log/net_log.cc index d0074d7d..bcd714f 100644 --- a/net/log/net_log.cc +++ b/net/log/net_log.cc
@@ -98,7 +98,8 @@ } // namespace -NetLog::ThreadSafeObserver::ThreadSafeObserver() : net_log_(nullptr) {} +NetLog::ThreadSafeObserver::ThreadSafeObserver() + : capture_mode_(NetLogCaptureMode::kDefault), net_log_(nullptr) {} NetLog::ThreadSafeObserver::~ThreadSafeObserver() { // Make sure we aren't watching a NetLog on destruction. Because the NetLog @@ -180,7 +181,7 @@ observers_.erase(it); observer->net_log_ = nullptr; - observer->capture_mode_ = NetLogCaptureMode(); + observer->capture_mode_ = NetLogCaptureMode::kDefault; UpdateIsCapturing(); }
diff --git a/net/log/net_log_capture_mode.cc b/net/log/net_log_capture_mode.cc index 9b00247e..40b072a 100644 --- a/net/log/net_log_capture_mode.cc +++ b/net/log/net_log_capture_mode.cc
@@ -6,60 +6,12 @@ namespace net { -namespace { - -// Integer representation for the capture mode. The numeric value is depended on -// for methods of NetLogCaptureMode, which expect that higher values represent a -// strict superset of the capabilities of lower values. -enum InternalValue { - // Log all events, but do not include the actual transferred bytes, and - // remove cookies and HTTP credentials and HTTP/2 GOAWAY frame debug data. - DEFAULT, - - // Log all events, but do not include the actual transferred bytes as - // parameters for bytes sent/received events. - // TODO(bnc): Consider renaming to INCLUDE_PRIVACY_INFO. - INCLUDE_COOKIES_AND_CREDENTIALS, - - // Log everything possible, even if it is slow and memory expensive. - // Includes logging of transferred bytes. - INCLUDE_SOCKET_BYTES, -}; - -} // namespace - -NetLogCaptureMode::NetLogCaptureMode() : NetLogCaptureMode(DEFAULT) { +bool NetLogCaptureIncludesSensitive(NetLogCaptureMode capture_mode) { + return capture_mode >= NetLogCaptureMode::kIncludeSensitive; } -NetLogCaptureMode NetLogCaptureMode::Default() { - return NetLogCaptureMode(DEFAULT); -} - -NetLogCaptureMode NetLogCaptureMode::IncludeCookiesAndCredentials() { - return NetLogCaptureMode(INCLUDE_COOKIES_AND_CREDENTIALS); -} - -NetLogCaptureMode NetLogCaptureMode::IncludeSocketBytes() { - return NetLogCaptureMode(INCLUDE_SOCKET_BYTES); -} - -bool NetLogCaptureMode::include_cookies_and_credentials() const { - return value_ >= INCLUDE_COOKIES_AND_CREDENTIALS; -} - -bool NetLogCaptureMode::include_socket_bytes() const { - return value_ >= INCLUDE_SOCKET_BYTES; -} - -bool NetLogCaptureMode::operator==(NetLogCaptureMode mode) const { - return value_ == mode.value_; -} - -bool NetLogCaptureMode::operator!=(NetLogCaptureMode mode) const { - return !(*this == mode); -} - -NetLogCaptureMode::NetLogCaptureMode(uint32_t value) : value_(value) { +bool NetLogCaptureIncludesSocketBytes(NetLogCaptureMode capture_mode) { + return capture_mode == NetLogCaptureMode::kEverything; } } // namespace net
diff --git a/net/log/net_log_capture_mode.h b/net/log/net_log_capture_mode.h index b688c57e..96d6268 100644 --- a/net/log/net_log_capture_mode.h +++ b/net/log/net_log_capture_mode.h
@@ -11,52 +11,45 @@ namespace net { -// NetLogCaptureMode specifies the granularity of events that should be emitted -// to the log. It is a simple wrapper around an integer, so it should be passed -// to functions by value rather than by reference. -class NET_EXPORT NetLogCaptureMode { - public: - // NOTE: Default assignment and copy constructor are OK. +// NetLogCaptureMode specifies the logging level. +// +// It is used to control which events are emitted to the log, and what level of +// detail is included in their parameters. +// +// The capture mode is expressed as a number, where higher values imply more +// information. The exact numeric values should not be depended on. +enum class NetLogCaptureMode : uint32_t { + // Default logging level, which is expected to be light-weight and + // does best-effort stripping of privacy/security sensitive data. + // + // * Includes most HTTP request/response headers, but strips cookies and + // auth. + // * Does not include the full bytes read/written to sockets. + kDefault, - // The default constructor creates a capture mode equivalent to - // Default(). - NetLogCaptureMode(); + // Logging level that includes everything from kDefault, plus sensitive data + // that it may have strippped. + // + // * Includes cookies and authentication headers. + // * Does not include the full bytes read/written to sockets. + kIncludeSensitive, - // Constructs a capture mode which logs basic events and event parameters. - // include_cookies_and_credentials() --> false - // include_socket_bytes() --> false - static NetLogCaptureMode Default(); - - // Constructs a capture mode which logs basic events, and additionally makes - // no effort to strip cookies and credentials. - // include_cookies_and_credentials() --> true - // include_socket_bytes() --> false - // TODO(bnc): Consider renaming to IncludePrivacyInfo(). - static NetLogCaptureMode IncludeCookiesAndCredentials(); - - // Constructs a capture mode which logs the data sent/received from sockets. - // include_cookies_and_credentials() --> true - // include_socket_bytes() --> true - static NetLogCaptureMode IncludeSocketBytes(); - - // If include_cookies_and_credentials() is true , then it is OK to log - // events which contain cookies, credentials or other privacy sensitive data. - // TODO(bnc): Consider renaming to include_privacy_info(). - bool include_cookies_and_credentials() const; - - // If include_socket_bytes() is true, then it is OK to output the actual - // bytes read/written from the network, even if it contains private data. - bool include_socket_bytes() const; - - bool operator==(NetLogCaptureMode mode) const; - bool operator!=(NetLogCaptureMode mode) const; - - private: - explicit NetLogCaptureMode(uint32_t value); - - int32_t value_; + // Logging level that includes everything that is possible to be logged. + // + // * Includes the actual bytes read/written to sockets + // * Will result in large log files. + kEverything, }; +// Returns true if |capture_mode| permits logging sensitive values such as +// cookies and credentials. +NET_EXPORT bool NetLogCaptureIncludesSensitive(NetLogCaptureMode capture_mode); + +// Returns true if |capture_mode| permits logging the full request/response +// bytes from sockets. +NET_EXPORT bool NetLogCaptureIncludesSocketBytes( + NetLogCaptureMode capture_mode); + } // namespace net #endif // NET_LOG_NET_LOG_CAPTURE_MODE_H_
diff --git a/net/log/net_log_capture_mode_unittest.cc b/net/log/net_log_capture_mode_unittest.cc index a249bf1..ea4fa30c 100644 --- a/net/log/net_log_capture_mode_unittest.cc +++ b/net/log/net_log_capture_mode_unittest.cc
@@ -10,41 +10,25 @@ namespace { -TEST(NetLogCaptureMode, DefaultConstructor) { - EXPECT_EQ(NetLogCaptureMode(), NetLogCaptureMode::Default()); -} - TEST(NetLogCaptureMode, Default) { - NetLogCaptureMode mode = NetLogCaptureMode::Default(); + NetLogCaptureMode mode = NetLogCaptureMode::kDefault; - EXPECT_FALSE(mode.include_cookies_and_credentials()); - EXPECT_FALSE(mode.include_socket_bytes()); - - EXPECT_EQ(mode, NetLogCaptureMode::Default()); - EXPECT_NE(mode, NetLogCaptureMode::IncludeCookiesAndCredentials()); - EXPECT_NE(mode, NetLogCaptureMode::IncludeSocketBytes()); + EXPECT_FALSE(NetLogCaptureIncludesSensitive(mode)); + EXPECT_FALSE(NetLogCaptureIncludesSocketBytes(mode)); } -TEST(NetLogCaptureMode, IncludeCookiesAndCredentials) { - NetLogCaptureMode mode = NetLogCaptureMode::IncludeCookiesAndCredentials(); +TEST(NetLogCaptureMode, IncludeSensitive) { + NetLogCaptureMode mode = NetLogCaptureMode::kIncludeSensitive; - EXPECT_TRUE(mode.include_cookies_and_credentials()); - EXPECT_FALSE(mode.include_socket_bytes()); - - EXPECT_NE(mode, NetLogCaptureMode::Default()); - EXPECT_EQ(mode, NetLogCaptureMode::IncludeCookiesAndCredentials()); - EXPECT_NE(mode, NetLogCaptureMode::IncludeSocketBytes()); + EXPECT_TRUE(NetLogCaptureIncludesSensitive(mode)); + EXPECT_FALSE(NetLogCaptureIncludesSocketBytes(mode)); } -TEST(NetLogCaptureMode, IncludeSocketBytes) { - NetLogCaptureMode mode = NetLogCaptureMode::IncludeSocketBytes(); +TEST(NetLogCaptureMode, Everything) { + NetLogCaptureMode mode = NetLogCaptureMode::kEverything; - EXPECT_TRUE(mode.include_cookies_and_credentials()); - EXPECT_TRUE(mode.include_socket_bytes()); - - EXPECT_NE(mode, NetLogCaptureMode::Default()); - EXPECT_NE(mode, NetLogCaptureMode::IncludeCookiesAndCredentials()); - EXPECT_EQ(mode, NetLogCaptureMode::IncludeSocketBytes()); + EXPECT_TRUE(NetLogCaptureIncludesSensitive(mode)); + EXPECT_TRUE(NetLogCaptureIncludesSocketBytes(mode)); } } // namespace
diff --git a/net/log/net_log_unittest.cc b/net/log/net_log_unittest.cc index 0169afb..8cf4d0c 100644 --- a/net/log/net_log_unittest.cc +++ b/net/log/net_log_unittest.cc
@@ -33,11 +33,11 @@ // this internal value is not exposed. These tests need to serialize a // NetLogCaptureMode to a base::Value, so create our own private mapping. int CaptureModeToInt(NetLogCaptureMode capture_mode) { - if (capture_mode == NetLogCaptureMode::Default()) + if (capture_mode == NetLogCaptureMode::kDefault) return 0; - if (capture_mode == NetLogCaptureMode::IncludeCookiesAndCredentials()) + if (capture_mode == NetLogCaptureMode::kIncludeSensitive) return 1; - if (capture_mode == NetLogCaptureMode::IncludeSocketBytes()) + if (capture_mode == NetLogCaptureMode::kEverything) return 2; ADD_FAILURE() << "Unknown capture mode"; @@ -75,9 +75,9 @@ // Check that the correct CaptureMode is sent to NetLog Value callbacks. TEST(NetLogTest, CaptureModes) { NetLogCaptureMode kModes[] = { - NetLogCaptureMode::Default(), - NetLogCaptureMode::IncludeCookiesAndCredentials(), - NetLogCaptureMode::IncludeSocketBytes(), + NetLogCaptureMode::kDefault, + NetLogCaptureMode::kIncludeSensitive, + NetLogCaptureMode::kEverything, }; TestNetLog net_log; @@ -218,17 +218,14 @@ for (int i = 0; i < kEvents; ++i) { ASSERT_FALSE(observer_.net_log()); - net_log_->AddObserver(&observer_, - NetLogCaptureMode::IncludeCookiesAndCredentials()); + net_log_->AddObserver(&observer_, NetLogCaptureMode::kIncludeSensitive); ASSERT_EQ(net_log_, observer_.net_log()); - ASSERT_EQ(NetLogCaptureMode::IncludeCookiesAndCredentials(), - observer_.capture_mode()); + ASSERT_EQ(NetLogCaptureMode::kIncludeSensitive, observer_.capture_mode()); net_log_->SetObserverCaptureMode(&observer_, - NetLogCaptureMode::IncludeSocketBytes()); + NetLogCaptureMode::kEverything); ASSERT_EQ(net_log_, observer_.net_log()); - ASSERT_EQ(NetLogCaptureMode::IncludeSocketBytes(), - observer_.capture_mode()); + ASSERT_EQ(NetLogCaptureMode::kEverything, observer_.capture_mode()); net_log_->RemoveObserver(&observer_); ASSERT_TRUE(!observer_.net_log()); @@ -268,7 +265,7 @@ // safely detach themselves on destruction. CountingObserver observers[3]; for (size_t i = 0; i < base::size(observers); ++i) { - net_log.AddObserver(&observers[i], NetLogCaptureMode::IncludeSocketBytes()); + net_log.AddObserver(&observers[i], NetLogCaptureMode::kEverything); } // Run a bunch of threads to completion, each of which will emit events to @@ -292,22 +289,19 @@ EXPECT_FALSE(net_log.IsCapturing()); // Add the observer and add an event. - net_log.AddObserver(&observer, - NetLogCaptureMode::IncludeCookiesAndCredentials()); + net_log.AddObserver(&observer, NetLogCaptureMode::kIncludeSensitive); EXPECT_TRUE(net_log.IsCapturing()); EXPECT_EQ(&net_log, observer.net_log()); - EXPECT_EQ(NetLogCaptureMode::IncludeCookiesAndCredentials(), - observer.capture_mode()); + EXPECT_EQ(NetLogCaptureMode::kIncludeSensitive, observer.capture_mode()); EXPECT_TRUE(net_log.IsCapturing()); AddEvent(&net_log); EXPECT_EQ(1, observer.count()); // Change the observer's logging level and add an event. - net_log.SetObserverCaptureMode(&observer, - NetLogCaptureMode::IncludeSocketBytes()); + net_log.SetObserverCaptureMode(&observer, NetLogCaptureMode::kEverything); EXPECT_EQ(&net_log, observer.net_log()); - EXPECT_EQ(NetLogCaptureMode::IncludeSocketBytes(), observer.capture_mode()); + EXPECT_EQ(NetLogCaptureMode::kEverything, observer.capture_mode()); EXPECT_TRUE(net_log.IsCapturing()); AddEvent(&net_log); @@ -322,9 +316,9 @@ EXPECT_EQ(2, observer.count()); // Add the observer a final time, and add an event. - net_log.AddObserver(&observer, NetLogCaptureMode::IncludeSocketBytes()); + net_log.AddObserver(&observer, NetLogCaptureMode::kEverything); EXPECT_EQ(&net_log, observer.net_log()); - EXPECT_EQ(NetLogCaptureMode::IncludeSocketBytes(), observer.capture_mode()); + EXPECT_EQ(NetLogCaptureMode::kEverything, observer.capture_mode()); EXPECT_TRUE(net_log.IsCapturing()); AddEvent(&net_log); @@ -337,22 +331,18 @@ LoggingObserver observer[2]; // Add first observer. - net_log.AddObserver(&observer[0], - NetLogCaptureMode::IncludeCookiesAndCredentials()); + net_log.AddObserver(&observer[0], NetLogCaptureMode::kIncludeSensitive); EXPECT_EQ(&net_log, observer[0].net_log()); EXPECT_EQ(NULL, observer[1].net_log()); - EXPECT_EQ(NetLogCaptureMode::IncludeCookiesAndCredentials(), - observer[0].capture_mode()); + EXPECT_EQ(NetLogCaptureMode::kIncludeSensitive, observer[0].capture_mode()); EXPECT_TRUE(net_log.IsCapturing()); // Add second observer observer. - net_log.AddObserver(&observer[1], NetLogCaptureMode::IncludeSocketBytes()); + net_log.AddObserver(&observer[1], NetLogCaptureMode::kEverything); EXPECT_EQ(&net_log, observer[0].net_log()); EXPECT_EQ(&net_log, observer[1].net_log()); - EXPECT_EQ(NetLogCaptureMode::IncludeCookiesAndCredentials(), - observer[0].capture_mode()); - EXPECT_EQ(NetLogCaptureMode::IncludeSocketBytes(), - observer[1].capture_mode()); + EXPECT_EQ(NetLogCaptureMode::kIncludeSensitive, observer[0].capture_mode()); + EXPECT_EQ(NetLogCaptureMode::kEverything, observer[1].capture_mode()); EXPECT_TRUE(net_log.IsCapturing()); // Add event and make sure both observers receive it at their respective log @@ -370,8 +360,7 @@ net_log.RemoveObserver(&observer[1]); EXPECT_EQ(&net_log, observer[0].net_log()); EXPECT_EQ(NULL, observer[1].net_log()); - EXPECT_EQ(NetLogCaptureMode::IncludeCookiesAndCredentials(), - observer[0].capture_mode()); + EXPECT_EQ(NetLogCaptureMode::kIncludeSensitive, observer[0].capture_mode()); EXPECT_TRUE(net_log.IsCapturing()); // Add event and make sure only second observer gets it. @@ -516,7 +505,7 @@ NetLogEntryData entry_data1(NetLogEventType::REQUEST_ALIVE, NetLogSource(), NetLogEventPhase::BEGIN, base::TimeTicks(), nullptr); - NetLogEntry entry1(&entry_data1, NetLogCaptureMode::Default()); + NetLogEntry entry1(&entry_data1, NetLogCaptureMode::kDefault); // NetLogEntry with a parameters callback that returns a NONE value. NetLogParametersCallback callback2 = @@ -524,7 +513,7 @@ NetLogEntryData entry_data2(NetLogEventType::REQUEST_ALIVE, NetLogSource(), NetLogEventPhase::BEGIN, base::TimeTicks(), &callback2); - NetLogEntry entry2(&entry_data2, NetLogCaptureMode::Default()); + NetLogEntry entry2(&entry_data2, NetLogCaptureMode::kDefault); ASSERT_FALSE(entry_data1.parameters_callback); ASSERT_TRUE(entry_data2.parameters_callback);
diff --git a/net/log/net_log_util.cc b/net/log/net_log_util.cc index dcf2fb5..6c4172a 100644 --- a/net/log/net_log_util.cc +++ b/net/log/net_log_util.cc
@@ -507,12 +507,12 @@ NetLogParametersCallback callback = base::Bind(&GetRequestStateAsValue, base::Unretained(request)); - // Note that passing the hardcoded NetLogCaptureMode::Default() below is + // Note that passing the hardcoded NetLogCaptureMode::kDefault below is // fine, since GetRequestStateAsValue() ignores the capture mode. NetLogEntryData entry_data( NetLogEventType::REQUEST_ALIVE, request->net_log().source(), NetLogEventPhase::BEGIN, request->creation_time(), &callback); - NetLogEntry entry(&entry_data, NetLogCaptureMode::Default()); + NetLogEntry entry(&entry_data, NetLogCaptureMode::kDefault); observer->OnAddEntry(entry); } }
diff --git a/net/log/net_log_with_source.cc b/net/log/net_log_with_source.cc index 020c340..6159331ad 100644 --- a/net/log/net_log_with_source.cc +++ b/net/log/net_log_with_source.cc
@@ -28,7 +28,7 @@ NetLogCaptureMode capture_mode) { base::DictionaryValue dict; dict.SetInteger("byte_count", byte_count); - if (capture_mode.include_socket_bytes() && byte_count > 0) + if (NetLogCaptureIncludesSocketBytes(capture_mode) && byte_count > 0) dict.SetKey("bytes", NetLogBinaryValue(bytes, byte_count)); return std::move(dict); }
diff --git a/net/log/test_net_log.cc b/net/log/test_net_log.cc index 6814f15..8ebb945 100644 --- a/net/log/test_net_log.cc +++ b/net/log/test_net_log.cc
@@ -74,8 +74,7 @@ }; TestNetLog::TestNetLog() : observer_(new Observer()) { - AddObserver(observer_.get(), - NetLogCaptureMode::IncludeCookiesAndCredentials()); + AddObserver(observer_.get(), NetLogCaptureMode::kIncludeSensitive); } TestNetLog::~TestNetLog() {
diff --git a/net/log/test_net_log.h b/net/log/test_net_log.h index f7aff17..d13c34dc0 100644 --- a/net/log/test_net_log.h +++ b/net/log/test_net_log.h
@@ -18,7 +18,6 @@ namespace net { -class NetLogCaptureMode; struct NetLogSource; // TestNetLog is NetLog subclass which records all NetLog events that occur and
diff --git a/net/log/trace_net_log_observer.cc b/net/log/trace_net_log_observer.cc index 7b572840..1c42ceae 100644 --- a/net/log/trace_net_log_observer.cc +++ b/net/log/trace_net_log_observer.cc
@@ -116,7 +116,7 @@ if (!enabled) return; - net_log_to_watch_->AddObserver(this, NetLogCaptureMode::Default()); + net_log_to_watch_->AddObserver(this, NetLogCaptureMode::kDefault); } void TraceNetLogObserver::OnTraceLogDisabled() {
diff --git a/net/proxy_resolution/pac_file_decider.h b/net/proxy_resolution/pac_file_decider.h index 101a032..1144e46 100644 --- a/net/proxy_resolution/pac_file_decider.h +++ b/net/proxy_resolution/pac_file_decider.h
@@ -32,7 +32,6 @@ class DhcpPacFileFetcher; class NetLog; -class NetLogCaptureMode; class ProxyResolver; class PacFileFetcher;
diff --git a/net/socket/ssl_client_socket_impl.cc b/net/socket/ssl_client_socket_impl.cc index 292c138..e940add 100644 --- a/net/socket/ssl_client_socket_impl.cc +++ b/net/socket/ssl_client_socket_impl.cc
@@ -140,7 +140,7 @@ // (that's the private key which isn't sent over the wire), but it may contain // information on the user's identity. if (!is_write || type != SSL3_MT_CERTIFICATE || - capture_mode.include_socket_bytes()) { + NetLogCaptureIncludesSocketBytes(capture_mode)) { dict.SetKey("bytes", NetLogBinaryValue(bytes, len)); }
diff --git a/net/socket/ssl_client_socket_unittest.cc b/net/socket/ssl_client_socket_unittest.cc index 97d62b52..84a3bcb9 100644 --- a/net/socket/ssl_client_socket_unittest.cc +++ b/net/socket/ssl_client_socket_unittest.cc
@@ -2387,7 +2387,7 @@ TestCompletionCallback callback; TestNetLog log; - log.SetCaptureMode(NetLogCaptureMode::IncludeSocketBytes()); + log.SetCaptureMode(NetLogCaptureMode::kEverything); std::unique_ptr<StreamSocket> transport( new TCPClientSocket(addr(), nullptr, &log, NetLogSource())); int rv = callback.GetResult(transport->Connect(callback.callback()));
diff --git a/net/socket/udp_net_log_parameters.cc b/net/socket/udp_net_log_parameters.cc index d6b6fad3..a62dfa3f 100644 --- a/net/socket/udp_net_log_parameters.cc +++ b/net/socket/udp_net_log_parameters.cc
@@ -21,7 +21,7 @@ NetLogCaptureMode capture_mode) { base::DictionaryValue dict; dict.SetInteger("byte_count", byte_count); - if (capture_mode.include_socket_bytes()) + if (NetLogCaptureIncludesSocketBytes(capture_mode)) dict.SetKey("bytes", NetLogBinaryValue(bytes, byte_count)); if (address) dict.SetString("address", address->ToString());
diff --git a/net/spdy/spdy_log_util.cc b/net/spdy/spdy_log_util.cc index bb44301d..01291a9 100644 --- a/net/spdy/spdy_log_util.cc +++ b/net/spdy/spdy_log_util.cc
@@ -15,7 +15,7 @@ base::Value ElideGoAwayDebugDataForNetLog(NetLogCaptureMode capture_mode, base::StringPiece debug_data) { - if (capture_mode.include_cookies_and_credentials()) + if (NetLogCaptureIncludesSensitive(capture_mode)) return NetLogStringValue(debug_data); return NetLogStringValue(base::StrCat(
diff --git a/net/spdy/spdy_log_util_unittest.cc b/net/spdy/spdy_log_util_unittest.cc index 53f788a..2a9dbf4 100644 --- a/net/spdy/spdy_log_util_unittest.cc +++ b/net/spdy/spdy_log_util_unittest.cc
@@ -21,15 +21,13 @@ TEST(SpdyLogUtilTest, ElideGoAwayDebugDataForNetLog) { // Only elide for appropriate log level. EXPECT_EQ("[6 bytes were stripped]", - ElideGoAwayDebugDataForNetLogAsString(NetLogCaptureMode::Default(), + ElideGoAwayDebugDataForNetLogAsString(NetLogCaptureMode::kDefault, "foobar")); - EXPECT_EQ("foobar", + EXPECT_EQ("foobar", ElideGoAwayDebugDataForNetLogAsString( + NetLogCaptureMode::kIncludeSensitive, "foobar")); + EXPECT_EQ("%ESCAPED:\xE2\x80\x8B %FE%FF", ElideGoAwayDebugDataForNetLogAsString( - NetLogCaptureMode::IncludeCookiesAndCredentials(), "foobar")); - EXPECT_EQ( - "%ESCAPED:\xE2\x80\x8B %FE%FF", - ElideGoAwayDebugDataForNetLogAsString( - NetLogCaptureMode::IncludeCookiesAndCredentials(), "\xfe\xff\x00")); + NetLogCaptureMode::kIncludeSensitive, "\xfe\xff\x00")); } TEST(SpdyLogUtilTest, ElideSpdyHeaderBlockForNetLog) { @@ -38,7 +36,7 @@ headers["cookie"] = "name=value"; base::ListValue list = - ElideSpdyHeaderBlockForNetLog(headers, NetLogCaptureMode::Default()); + ElideSpdyHeaderBlockForNetLog(headers, NetLogCaptureMode::kDefault); ASSERT_FALSE(list.is_none()); ASSERT_EQ(2u, list.GetList().size()); @@ -49,8 +47,8 @@ ASSERT_TRUE(list.GetList()[1].is_string()); EXPECT_EQ("cookie: [10 bytes were stripped]", list.GetList()[1].GetString()); - list = ElideSpdyHeaderBlockForNetLog( - headers, NetLogCaptureMode::IncludeCookiesAndCredentials()); + list = ElideSpdyHeaderBlockForNetLog(headers, + NetLogCaptureMode::kIncludeSensitive); ASSERT_FALSE(list.is_none()); ASSERT_EQ(2u, list.GetList().size()); @@ -68,7 +66,7 @@ headers["cookie"] = "name=value"; std::unique_ptr<base::Value> dict = base::Value::ToUniquePtrValue( - SpdyHeaderBlockNetLogCallback(&headers, NetLogCaptureMode::Default())); + SpdyHeaderBlockNetLogCallback(&headers, NetLogCaptureMode::kDefault)); ASSERT_TRUE(dict); ASSERT_TRUE(dict->is_dict()); @@ -87,7 +85,7 @@ header_list->GetList()[1].GetString()); dict = base::Value::ToUniquePtrValue(SpdyHeaderBlockNetLogCallback( - &headers, NetLogCaptureMode::IncludeCookiesAndCredentials())); + &headers, NetLogCaptureMode::kIncludeSensitive)); ASSERT_TRUE(dict); ASSERT_TRUE(dict->is_dict()); @@ -113,7 +111,7 @@ headers["\xde\xad"] = "\xbe\xef"; base::ListValue list = - ElideSpdyHeaderBlockForNetLog(headers, NetLogCaptureMode::Default()); + ElideSpdyHeaderBlockForNetLog(headers, NetLogCaptureMode::kDefault); ASSERT_EQ(3u, list.GetSize()); std::string field;
diff --git a/net/url_request/url_request_netlog_params.h b/net/url_request/url_request_netlog_params.h index 6fd10177..eaa8c64 100644 --- a/net/url_request/url_request_netlog_params.h +++ b/net/url_request/url_request_netlog_params.h
@@ -13,6 +13,7 @@ #include "net/base/net_export.h" #include "net/base/privacy_mode.h" #include "net/base/request_priority.h" +#include "net/log/net_log_capture_mode.h" #include "net/traffic_annotation/network_traffic_annotation.h" class GURL; @@ -23,8 +24,6 @@ namespace net { -class NetLogCaptureMode; - // Returns a Value containing NetLog parameters for constructing a URLRequest. NET_EXPORT base::Value NetLogURLRequestConstructorCallback( const GURL* url,
diff --git a/remoting/base/vlog_net_log.cc b/remoting/base/vlog_net_log.cc index 75a6eace..7e2f9c8 100644 --- a/remoting/base/vlog_net_log.cc +++ b/remoting/base/vlog_net_log.cc
@@ -43,8 +43,7 @@ VlogNetLog::VlogNetLog() : observer_(new Observer()) { - AddObserver(observer_.get(), - net::NetLogCaptureMode::IncludeCookiesAndCredentials()); + AddObserver(observer_.get(), net::NetLogCaptureMode::kIncludeSensitive); } VlogNetLog::~VlogNetLog() {
diff --git a/services/device/public/mojom/usb_device.mojom b/services/device/public/mojom/usb_device.mojom index 595a77d3..fcc22dd 100644 --- a/services/device/public/mojom/usb_device.mojom +++ b/services/device/public/mojom/usb_device.mojom
@@ -88,6 +88,8 @@ struct UsbInterfaceInfo { uint8 interface_number; + // First interface of the function to which this interface belongs. + uint8 first_interface; array<UsbAlternateInterfaceInfo> alternates; };
diff --git a/services/device/usb/fake_usb_device_handle.cc b/services/device/usb/fake_usb_device_handle.cc index 6b92fde1..cf03e1b 100644 --- a/services/device/usb/fake_usb_device_handle.cc +++ b/services/device/usb/fake_usb_device_handle.cc
@@ -4,6 +4,9 @@ #include "services/device/usb/fake_usb_device_handle.h" +#include <algorithm> +#include <utility> + #include "base/callback.h" #include "base/logging.h" #include "base/memory/ref_counted_memory.h" @@ -115,7 +118,7 @@ NOTIMPLEMENTED(); } -const UsbInterfaceDescriptor* FakeUsbDeviceHandle::FindInterfaceByEndpoint( +const mojom::UsbInterfaceInfo* FakeUsbDeviceHandle::FindInterfaceByEndpoint( uint8_t endpoint_address) { NOTIMPLEMENTED(); return nullptr;
diff --git a/services/device/usb/fake_usb_device_handle.h b/services/device/usb/fake_usb_device_handle.h index 86578d3..b9390ccb 100644 --- a/services/device/usb/fake_usb_device_handle.h +++ b/services/device/usb/fake_usb_device_handle.h
@@ -5,6 +5,8 @@ #ifndef SERVICES_DEVICE_USB_FAKE_USB_DEVICE_HANDLE_H_ #define SERVICES_DEVICE_USB_FAKE_USB_DEVICE_HANDLE_H_ +#include <vector> + #include "services/device/usb/usb_device_handle.h" namespace device { @@ -64,7 +66,7 @@ scoped_refptr<base::RefCountedBytes> buffer, unsigned int timeout, TransferCallback callback) override; - const UsbInterfaceDescriptor* FindInterfaceByEndpoint( + const mojom::UsbInterfaceInfo* FindInterfaceByEndpoint( uint8_t endpoint_address) override; private:
diff --git a/services/device/usb/mock_usb_device_handle.h b/services/device/usb/mock_usb_device_handle.h index 25a2c61..ba19ffa 100644 --- a/services/device/usb/mock_usb_device_handle.h +++ b/services/device/usb/mock_usb_device_handle.h
@@ -132,7 +132,7 @@ TransferCallback& callback)); MOCK_METHOD1(FindInterfaceByEndpoint, - const UsbInterfaceDescriptor*(uint8_t endpoint_address)); + const mojom::UsbInterfaceInfo*(uint8_t endpoint_address)); protected: ~MockUsbDeviceHandle() override;
diff --git a/services/device/usb/mojo/device_impl.cc b/services/device/usb/mojo/device_impl.cc index 0320df3..13afedb 100644 --- a/services/device/usb/mojo/device_impl.cc +++ b/services/device/usb/mojo/device_impl.cc
@@ -136,17 +136,17 @@ if (!config) return false; - const UsbInterfaceDescriptor* interface = nullptr; + const mojom::UsbInterfaceInfo* interface = nullptr; if (recipient == UsbControlTransferRecipient::ENDPOINT) { interface = device_handle_->FindInterfaceByEndpoint(index & 0xff); } else { auto interface_it = std::find_if(config->interfaces.begin(), config->interfaces.end(), - [index](const UsbInterfaceDescriptor& this_iface) { - return this_iface.interface_number == (index & 0xff); + [index](const mojom::UsbInterfaceInfoPtr& this_iface) { + return this_iface->interface_number == (index & 0xff); }); if (interface_it != config->interfaces.end()) - interface = &*interface_it; + interface = interface_it->get(); } return interface != nullptr; @@ -226,11 +226,11 @@ return; } - auto interface_it = - std::find_if(config->interfaces.begin(), config->interfaces.end(), - [interface_number](const UsbInterfaceDescriptor& interface) { - return interface.interface_number == interface_number; - }); + auto interface_it = std::find_if( + config->interfaces.begin(), config->interfaces.end(), + [interface_number](const mojom::UsbInterfaceInfoPtr& interface) { + return interface->interface_number == interface_number; + }); if (interface_it == config->interfaces.end()) { std::move(callback).Run(false); return;
diff --git a/services/device/usb/mojo/device_impl_unittest.cc b/services/device/usb/mojo/device_impl_unittest.cc index e23728e..d65869a 100644 --- a/services/device/usb/mojo/device_impl_unittest.cc +++ b/services/device/usb/mojo/device_impl_unittest.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include <stdint.h> +#include <algorithm> #include <map> #include <memory> #include <numeric> @@ -27,6 +28,7 @@ #include "services/device/usb/mock_usb_device.h" #include "services/device/usb/mock_usb_device_handle.h" #include "services/device/usb/mojo/type_converters.h" +#include "services/device/usb/usb_descriptors.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; @@ -56,8 +58,9 @@ uint8_t class_code, uint8_t subclass_code, uint8_t protocol_code) { - config_.interfaces.emplace_back(interface_number, alternate_setting, - class_code, subclass_code, protocol_code); + config_.interfaces.push_back( + BuildUsbInterfaceInfoPtr(interface_number, alternate_setting, + class_code, subclass_code, protocol_code)); return *this; } @@ -281,7 +284,7 @@ UsbDeviceHandle::ResultCallback& callback) { for (const auto& config : mock_configs_) { for (const auto& interface : config.second.interfaces) { - if (interface.interface_number == interface_number) { + if (interface->interface_number == interface_number) { claimed_interfaces_.insert(interface_number); std::move(callback).Run(true); return; @@ -305,12 +308,11 @@ uint8_t alternate_setting, UsbDeviceHandle::ResultCallback& callback) { for (const auto& config : mock_configs_) { - for (const auto& interface : config.second.interfaces) { - if (interface.interface_number == interface_number && - interface.alternate_setting == alternate_setting) { - std::move(callback).Run(true); - return; - } + CombinedInterfaceInfo interface = FindInterfaceInfoFromConfig( + &config.second, interface_number, alternate_setting); + if (interface.IsValid()) { + std::move(callback).Run(true); + return; } } std::move(callback).Run(false);
diff --git a/services/device/usb/mojo/type_converters.cc b/services/device/usb/mojo/type_converters.cc index e8680e5..c7cda11 100644 --- a/services/device/usb/mojo/type_converters.cc +++ b/services/device/usb/mojo/type_converters.cc
@@ -17,60 +17,6 @@ namespace mojo { // static -device::mojom::UsbAlternateInterfaceInfoPtr -TypeConverter<device::mojom::UsbAlternateInterfaceInfoPtr, - device::UsbInterfaceDescriptor>:: - Convert(const device::UsbInterfaceDescriptor& interface) { - auto info = device::mojom::UsbAlternateInterfaceInfo::New(); - info->alternate_setting = interface.alternate_setting; - info->class_code = interface.interface_class; - info->subclass_code = interface.interface_subclass; - info->protocol_code = interface.interface_protocol; - info->extra_data.assign(interface.extra_data.begin(), - interface.extra_data.end()); - - // Filter out control endpoints for the public interface. - info->endpoints.reserve(interface.endpoints.size()); - for (const auto& endpoint : interface.endpoints) { - if (endpoint->type != device::UsbTransferType::CONTROL) - info->endpoints.push_back(endpoint->Clone()); - } - - return info; -} - -// static -std::vector<device::mojom::UsbInterfaceInfoPtr> -TypeConverter<std::vector<device::mojom::UsbInterfaceInfoPtr>, - std::vector<device::UsbInterfaceDescriptor>>:: - Convert(const std::vector<device::UsbInterfaceDescriptor>& interfaces) { - std::vector<device::mojom::UsbInterfaceInfoPtr> infos; - - // Aggregate each alternate setting into an InterfaceInfo corresponding to its - // interface number. - std::map<uint8_t, device::mojom::UsbInterfaceInfo*> interface_map; - for (size_t i = 0; i < interfaces.size(); ++i) { - auto alternate = - device::mojom::UsbAlternateInterfaceInfo::From(interfaces[i]); - auto iter = interface_map.find(interfaces[i].interface_number); - if (iter == interface_map.end()) { - // This is the first time we're seeing an alternate with this interface - // number, so add a new InterfaceInfo to the array and map the number. - auto info = device::mojom::UsbInterfaceInfo::New(); - info->interface_number = interfaces[i].interface_number; - iter = interface_map - .insert( - std::make_pair(interfaces[i].interface_number, info.get())) - .first; - infos.push_back(std::move(info)); - } - iter->second->alternates.push_back(std::move(alternate)); - } - - return infos; -} - -// static device::mojom::UsbConfigurationInfoPtr TypeConverter< device::mojom::UsbConfigurationInfoPtr, device::UsbConfigDescriptor>::Convert(const device::UsbConfigDescriptor& @@ -80,10 +26,13 @@ info->self_powered = config.self_powered; info->remote_wakeup = config.remote_wakeup; info->maximum_power = config.maximum_power; - info->interfaces = - mojo::ConvertTo<std::vector<device::mojom::UsbInterfaceInfoPtr>>( - config.interfaces); info->extra_data.assign(config.extra_data.begin(), config.extra_data.end()); + + info->interfaces.reserve(config.interfaces.size()); + for (const auto& interface : config.interfaces) { + info->interfaces.push_back(interface->Clone()); + } + return info; }
diff --git a/services/device/usb/mojo/type_converters.h b/services/device/usb/mojo/type_converters.h index 0e32854..70b84c74 100644 --- a/services/device/usb/mojo/type_converters.h +++ b/services/device/usb/mojo/type_converters.h
@@ -19,30 +19,11 @@ namespace device { struct UsbConfigDescriptor; class UsbDevice; -struct UsbInterfaceDescriptor; } // namespace device namespace mojo { template <> -struct TypeConverter<device::mojom::UsbAlternateInterfaceInfoPtr, - device::UsbInterfaceDescriptor> { - static device::mojom::UsbAlternateInterfaceInfoPtr Convert( - const device::UsbInterfaceDescriptor& iface); -}; - -// Note that this is an explicit vector-to-array conversion, as -// UsbInterfaceDescriptor collections are flattened to contain all alternate -// settings, whereas InterfaceInfos contain their own sets of alternates with -// a different structure type. -template <> -struct TypeConverter<std::vector<device::mojom::UsbInterfaceInfoPtr>, - std::vector<device::UsbInterfaceDescriptor>> { - static std::vector<device::mojom::UsbInterfaceInfoPtr> Convert( - const std::vector<device::UsbInterfaceDescriptor>& interfaces); -}; - -template <> struct TypeConverter<device::mojom::UsbConfigurationInfoPtr, device::UsbConfigDescriptor> { static device::mojom::UsbConfigurationInfoPtr Convert(
diff --git a/services/device/usb/usb_configuration_android.cc b/services/device/usb/usb_configuration_android.cc index a22babe0..3facdae7 100644 --- a/services/device/usb/usb_configuration_android.cc +++ b/services/device/usb/usb_configuration_android.cc
@@ -30,6 +30,7 @@ for (auto interface : interfaces) { config.interfaces.push_back(UsbInterfaceAndroid::Convert(env, interface)); } + AggregateInterfacesForConfig(&config); return config; }
diff --git a/services/device/usb/usb_descriptors.cc b/services/device/usb/usb_descriptors.cc index 891c4695..677ac6ec 100644 --- a/services/device/usb/usb_descriptors.cc +++ b/services/device/usb/usb_descriptors.cc
@@ -235,48 +235,15 @@ } // namespace -UsbInterfaceDescriptor::UsbInterfaceDescriptor(const uint8_t* data) - : UsbInterfaceDescriptor(data[2] /* bInterfaceNumber */, - data[3] /* bAlternateSetting */, - data[5] /* bInterfaceClass */, - data[6] /* bInterfaceSubClass */, - data[7] /* bInterfaceProtocol */) { - DCHECK_GE(data[0], kInterfaceDescriptorLength); - DCHECK_EQ(data[1], kInterfaceDescriptorType); +CombinedInterfaceInfo::CombinedInterfaceInfo( + const mojom::UsbInterfaceInfo* interface, + const mojom::UsbAlternateInterfaceInfo* alternate) + : interface(interface), alternate(alternate) {} + +bool CombinedInterfaceInfo::IsValid() const { + return interface && alternate; } -UsbInterfaceDescriptor::UsbInterfaceDescriptor(uint8_t interface_number, - uint8_t alternate_setting, - uint8_t interface_class, - uint8_t interface_subclass, - uint8_t interface_protocol) - : interface_number(interface_number), - alternate_setting(alternate_setting), - interface_class(interface_class), - interface_subclass(interface_subclass), - interface_protocol(interface_protocol), - first_interface(interface_number) {} - -// Do a deep copy especially needed by |endpoints|. -UsbInterfaceDescriptor::UsbInterfaceDescriptor( - const UsbInterfaceDescriptor& other) - : interface_number(other.interface_number), - alternate_setting(other.alternate_setting), - interface_class(other.interface_class), - interface_subclass(other.interface_subclass), - interface_protocol(other.interface_protocol), - extra_data(other.extra_data), - first_interface(other.first_interface) { - for (auto& endpoint : other.endpoints) { - endpoints.push_back(endpoint.Clone()); - } -} - -UsbInterfaceDescriptor::UsbInterfaceDescriptor(UsbInterfaceDescriptor&& other) = - default; - -UsbInterfaceDescriptor::~UsbInterfaceDescriptor() = default; - UsbConfigDescriptor::UsbConfigDescriptor(const uint8_t* data) : UsbConfigDescriptor(data[5] /* bConfigurationValue */, (data[7] & 0x02) != 0 /* bmAttributes */, @@ -295,8 +262,17 @@ remote_wakeup(remote_wakeup), maximum_power(maximum_power) {} -UsbConfigDescriptor::UsbConfigDescriptor(const UsbConfigDescriptor& other) = - default; +// Make a deep copy because |interfaces| are move-only. +UsbConfigDescriptor::UsbConfigDescriptor(const UsbConfigDescriptor& other) { + configuration_value = other.configuration_value; + self_powered = other.self_powered; + remote_wakeup = other.remote_wakeup; + maximum_power = other.maximum_power; + extra_data = other.extra_data; + for (const auto& interface : other.interfaces) { + interfaces.push_back(interface->Clone()); + } +} UsbConfigDescriptor::UsbConfigDescriptor(UsbConfigDescriptor&& other) = default; @@ -306,8 +282,10 @@ std::vector<UsbInterfaceAssociationDescriptor> functions; ParseInterfaceAssociationDescriptors(extra_data, &functions); for (const auto& interface : interfaces) { - ParseInterfaceAssociationDescriptors(interface.extra_data, &functions); - for (auto& endpoint : interface.endpoints) + DCHECK_EQ(1u, interface->alternates.size()); + ParseInterfaceAssociationDescriptors(interface->alternates[0]->extra_data, + &functions); + for (auto& endpoint : interface->alternates[0]->endpoints) ParseInterfaceAssociationDescriptors(endpoint->extra_data, &functions); } @@ -323,18 +301,19 @@ if (remaining_interfaces > 0) { // Continuation of a previous function. Tag all alternate interfaces // (which are guaranteed to be contiguous). - for (uint8_t interface_number = interface_it->interface_number; + for (uint8_t interface_number = (*interface_it)->interface_number; interface_it != interfaces.end() && - interface_it->interface_number == interface_number; + (*interface_it)->interface_number == interface_number; ++interface_it) { - interface_it->first_interface = function_it->first_interface; + (*interface_it)->first_interface = function_it->first_interface; } if (--remaining_interfaces == 0) ++function_it; } else if (function_it != functions.end() && - interface_it->interface_number == function_it->first_interface) { + (*interface_it)->interface_number == + function_it->first_interface) { // Start of a new function. - interface_it->first_interface = function_it->first_interface; + (*interface_it)->first_interface = function_it->first_interface; if (function_it->interface_count > 1) remaining_interfaces = function_it->interface_count - 1; else @@ -377,7 +356,7 @@ bool UsbDeviceDescriptor::Parse(const std::vector<uint8_t>& buffer) { UsbConfigDescriptor* last_config = nullptr; - UsbInterfaceDescriptor* last_interface = nullptr; + mojom::UsbInterfaceInfo* last_interface = nullptr; mojom::UsbEndpointInfo* last_endpoint = nullptr; for (auto it = buffer.begin(); it != buffer.end(); @@ -407,8 +386,10 @@ case kConfigurationDescriptorType: if (length < kConfigurationDescriptorLength) return false; - if (last_config) + if (last_config) { last_config->AssignFirstInterfaceNumbers(); + AggregateInterfacesForConfig(last_config); + } configurations.emplace_back(data); last_config = &configurations.back(); last_interface = nullptr; @@ -417,15 +398,16 @@ case kInterfaceDescriptorType: if (!last_config || length < kInterfaceDescriptorLength) return false; - last_config->interfaces.emplace_back(data); - last_interface = &last_config->interfaces.back(); + last_config->interfaces.push_back(BuildUsbInterfaceInfoPtr(data)); + last_interface = last_config->interfaces.back().get(); last_endpoint = nullptr; break; case kEndpointDescriptorType: if (!last_interface || length < kEndpointDescriptorLength) return false; - last_interface->endpoints.push_back(BuildUsbEndpointInfoPtr(data)); - last_endpoint = last_interface->endpoints.back().get(); + last_interface->alternates[0]->endpoints.push_back( + BuildUsbEndpointInfoPtr(data)); + last_endpoint = last_interface->alternates[0]->endpoints.back().get(); break; default: // Append unknown descriptor types to the |extra_data| field of the last @@ -434,8 +416,10 @@ last_endpoint->extra_data.insert(last_endpoint->extra_data.end(), data, data + length); } else if (last_interface) { - last_interface->extra_data.insert(last_interface->extra_data.end(), - data, data + length); + DCHECK_EQ(1u, last_interface->alternates.size()); + last_interface->alternates[0]->extra_data.insert( + last_interface->alternates[0]->extra_data.end(), data, + data + length); } else if (last_config) { last_config->extra_data.insert(last_config->extra_data.end(), data, data + length); @@ -443,8 +427,10 @@ } } - if (last_config) + if (last_config) { last_config->AssignFirstInterfaceNumbers(); + AggregateInterfacesForConfig(last_config); + } return true; } @@ -581,4 +567,85 @@ return endpoint; } +UsbInterfaceInfoPtr BuildUsbInterfaceInfoPtr(const uint8_t* data) { + DCHECK_GE(data[0], kInterfaceDescriptorLength); + DCHECK_EQ(data[1], kInterfaceDescriptorType); + return BuildUsbInterfaceInfoPtr( + data[2] /* bInterfaceNumber */, data[3] /* bAlternateSetting */, + data[5] /* bInterfaceClass */, data[6] /* bInterfaceSubClass */, + data[7] /* bInterfaceProtocol */); +} + +UsbInterfaceInfoPtr BuildUsbInterfaceInfoPtr(uint8_t interface_number, + uint8_t alternate_setting, + uint8_t interface_class, + uint8_t interface_subclass, + uint8_t interface_protocol) { + UsbInterfaceInfoPtr interface_info = mojom::UsbInterfaceInfo::New(); + interface_info->interface_number = interface_number; + interface_info->first_interface = interface_number; + + UsbAlternateInterfaceInfoPtr alternate = + mojom::UsbAlternateInterfaceInfo::New(); + alternate->alternate_setting = alternate_setting; + alternate->class_code = interface_class; + alternate->subclass_code = interface_subclass; + alternate->protocol_code = interface_protocol; + + interface_info->alternates.push_back(std::move(alternate)); + + return interface_info; +} + +// Aggregate each alternate setting into an InterfaceInfo corresponding to its +// interface number. +void AggregateInterfacesForConfig(UsbConfigDescriptor* config) { + std::map<uint8_t, device::mojom::UsbInterfaceInfo*> interface_map; + std::vector<device::mojom::UsbInterfaceInfoPtr> interfaces = + std::move(config->interfaces); + config->interfaces.clear(); + + for (size_t i = 0; i < interfaces.size(); ++i) { + // As interfaces should appear in order, this map could be unnecessary, + // but this errs on the side of caution. + auto iter = interface_map.find(interfaces[i]->interface_number); + if (iter == interface_map.end()) { + // This is the first time we're seeing an alternate with this interface + // number, so add a new InterfaceInfo to the array and map the number. + config->interfaces.push_back(std::move(interfaces[i])); + interface_map.insert( + std::make_pair(config->interfaces.back()->interface_number, + config->interfaces.back().get())); + } else { + DCHECK_EQ(1u, interfaces[i]->alternates.size()); + iter->second->alternates.push_back( + std::move(interfaces[i]->alternates[0])); + } + } +} + +CombinedInterfaceInfo FindInterfaceInfoFromConfig( + const UsbConfigDescriptor* config, + uint8_t interface_number, + uint8_t alternate_setting) { + CombinedInterfaceInfo interface_info; + if (!config) { + return interface_info; + } + + for (const auto& iface : config->interfaces) { + if (iface->interface_number == interface_number) { + interface_info.interface = iface.get(); + + for (const auto& alternate : iface->alternates) { + if (alternate->alternate_setting == alternate_setting) { + interface_info.alternate = alternate.get(); + break; + } + } + } + } + return interface_info; +} + } // namespace device
diff --git a/services/device/usb/usb_descriptors.h b/services/device/usb/usb_descriptors.h index ebe6b958..dad28829 100644 --- a/services/device/usb/usb_descriptors.h +++ b/services/device/usb/usb_descriptors.h
@@ -25,28 +25,18 @@ using UsbSynchronizationType = mojom::UsbSynchronizationType; using UsbUsageType = mojom::UsbUsageType; using UsbEndpointInfoPtr = mojom::UsbEndpointInfoPtr; +using UsbAlternateInterfaceInfoPtr = mojom::UsbAlternateInterfaceInfoPtr; +using UsbInterfaceInfoPtr = mojom::UsbInterfaceInfoPtr; -struct UsbInterfaceDescriptor { - explicit UsbInterfaceDescriptor(const uint8_t* data); - UsbInterfaceDescriptor(uint8_t interface_number, - uint8_t alternate_setting, - uint8_t interface_class, - uint8_t interface_subclass, - uint8_t interface_protocol); - UsbInterfaceDescriptor() = delete; - UsbInterfaceDescriptor(const UsbInterfaceDescriptor& other); - UsbInterfaceDescriptor(UsbInterfaceDescriptor&& other); - ~UsbInterfaceDescriptor(); +struct CombinedInterfaceInfo { + CombinedInterfaceInfo() = default; + CombinedInterfaceInfo(const mojom::UsbInterfaceInfo* interface, + const mojom::UsbAlternateInterfaceInfo* alternate); - uint8_t interface_number; - uint8_t alternate_setting; - uint8_t interface_class; - uint8_t interface_subclass; - uint8_t interface_protocol; - std::vector<UsbEndpointInfoPtr> endpoints; - std::vector<uint8_t> extra_data; - // First interface of the function to which this interface belongs. - uint8_t first_interface; + bool IsValid() const; + + const mojom::UsbInterfaceInfo* interface = nullptr; + const mojom::UsbAlternateInterfaceInfo* alternate = nullptr; }; struct UsbConfigDescriptor { @@ -68,7 +58,7 @@ bool self_powered; bool remote_wakeup; uint8_t maximum_power; - std::vector<UsbInterfaceDescriptor> interfaces; + std::vector<UsbInterfaceInfoPtr> interfaces; std::vector<uint8_t> extra_data; }; @@ -121,6 +111,21 @@ uint16_t maximum_packet_size, uint8_t polling_interval); +UsbInterfaceInfoPtr BuildUsbInterfaceInfoPtr(const uint8_t* data); + +UsbInterfaceInfoPtr BuildUsbInterfaceInfoPtr(uint8_t interface_number, + uint8_t alternate_setting, + uint8_t interface_class, + uint8_t interface_subclass, + uint8_t interface_protocol); + +void AggregateInterfacesForConfig(UsbConfigDescriptor* config); + +CombinedInterfaceInfo FindInterfaceInfoFromConfig( + const UsbConfigDescriptor* config, + uint8_t interface_number, + uint8_t alternate_setting); + } // namespace device #endif // SERVICES_DEVICE_USB_USB_DESCRIPTORS_H_
diff --git a/services/device/usb/usb_descriptors_unittest.cc b/services/device/usb/usb_descriptors_unittest.cc index 4ce9744..4755076 100644 --- a/services/device/usb/usb_descriptors_unittest.cc +++ b/services/device/usb/usb_descriptors_unittest.cc
@@ -61,7 +61,7 @@ const uint8_t kConfig2Descriptor[] = { // Config 2 0x09, 0x02, 0x29, 0x00, 0x01, 0x02, 0x04, 0x03, 0x20, - // Interface 0 + // Interface 0 (alternate 0) 0x09, 0x04, 0x00, 0x00, 0x00, 0xCD, 0xEF, 0x01, 0x04, // Interface 0 (alternate 1) 0x09, 0x04, 0x00, 0x01, 0x02, 0xCD, 0xEF, 0x01, 0x05, @@ -81,61 +81,56 @@ ASSERT_EQ(2u, config.interfaces.size()); EXPECT_EQ(8u, config.extra_data.size()); // Interface 0 - EXPECT_EQ(0, config.interfaces[0].interface_number); - EXPECT_EQ(0, config.interfaces[0].alternate_setting); - EXPECT_EQ(0x12, config.interfaces[0].interface_class); - EXPECT_EQ(0x34, config.interfaces[0].interface_subclass); - EXPECT_EQ(0x56, config.interfaces[0].interface_protocol); - ASSERT_EQ(3u, config.interfaces[0].endpoints.size()); - EXPECT_EQ(0u, config.interfaces[0].extra_data.size()); - EXPECT_EQ(0, config.interfaces[0].first_interface); + EXPECT_EQ(0, config.interfaces[0]->interface_number); + EXPECT_EQ(0, config.interfaces[0]->first_interface); + const auto& alternate = config.interfaces[0]->alternates[0]; + EXPECT_EQ(0, alternate->alternate_setting); + EXPECT_EQ(0x12, alternate->class_code); + EXPECT_EQ(0x34, alternate->subclass_code); + EXPECT_EQ(0x56, alternate->protocol_code); + ASSERT_EQ(3u, alternate->endpoints.size()); + EXPECT_EQ(0u, alternate->extra_data.size()); + // Endpoint 1 IN - EXPECT_EQ(0x01, config.interfaces[0].endpoints[0]->endpoint_number); - EXPECT_EQ(UsbTransferDirection::INBOUND, - config.interfaces[0].endpoints[0]->direction); - EXPECT_EQ(512u, config.interfaces[0].endpoints[0]->packet_size); + EXPECT_EQ(0x01, alternate->endpoints[0]->endpoint_number); + EXPECT_EQ(UsbTransferDirection::INBOUND, alternate->endpoints[0]->direction); + EXPECT_EQ(512u, alternate->endpoints[0]->packet_size); EXPECT_EQ(UsbSynchronizationType::NONE, - config.interfaces[0].endpoints[0]->synchronization_type); - EXPECT_EQ(UsbTransferType::BULK, config.interfaces[0].endpoints[0]->type); - EXPECT_EQ(UsbUsageType::RESERVED, - config.interfaces[0].endpoints[0]->usage_type); - EXPECT_EQ(0, config.interfaces[0].endpoints[0]->polling_interval); - EXPECT_EQ(0u, config.interfaces[0].endpoints[0]->extra_data.size()); + alternate->endpoints[0]->synchronization_type); + EXPECT_EQ(UsbTransferType::BULK, alternate->endpoints[0]->type); + EXPECT_EQ(UsbUsageType::RESERVED, alternate->endpoints[0]->usage_type); + EXPECT_EQ(0, alternate->endpoints[0]->polling_interval); + EXPECT_EQ(0u, alternate->endpoints[0]->extra_data.size()); // Endpoint 2 IN - EXPECT_EQ(0x02, config.interfaces[0].endpoints[1]->endpoint_number); - EXPECT_EQ(UsbTransferDirection::INBOUND, - config.interfaces[0].endpoints[1]->direction); - EXPECT_EQ(512u, config.interfaces[0].endpoints[1]->packet_size); + EXPECT_EQ(0x02, alternate->endpoints[1]->endpoint_number); + EXPECT_EQ(UsbTransferDirection::INBOUND, alternate->endpoints[1]->direction); + EXPECT_EQ(512u, alternate->endpoints[1]->packet_size); EXPECT_EQ(UsbSynchronizationType::NONE, - config.interfaces[0].endpoints[1]->synchronization_type); - EXPECT_EQ(UsbTransferType::INTERRUPT, - config.interfaces[0].endpoints[1]->type); - EXPECT_EQ(UsbUsageType::PERIODIC, - config.interfaces[0].endpoints[1]->usage_type); - EXPECT_EQ(4, config.interfaces[0].endpoints[1]->polling_interval); - EXPECT_EQ(0u, config.interfaces[0].endpoints[1]->extra_data.size()); + alternate->endpoints[1]->synchronization_type); + EXPECT_EQ(UsbTransferType::INTERRUPT, alternate->endpoints[1]->type); + EXPECT_EQ(UsbUsageType::PERIODIC, alternate->endpoints[1]->usage_type); + EXPECT_EQ(4, alternate->endpoints[1]->polling_interval); + EXPECT_EQ(0u, alternate->endpoints[1]->extra_data.size()); // Endpoint 3 OUT - EXPECT_EQ(0x03, config.interfaces[0].endpoints[2]->endpoint_number); - EXPECT_EQ(UsbTransferDirection::OUTBOUND, - config.interfaces[0].endpoints[2]->direction); - EXPECT_EQ(512u, config.interfaces[0].endpoints[2]->packet_size); + EXPECT_EQ(0x03, alternate->endpoints[2]->endpoint_number); + EXPECT_EQ(UsbTransferDirection::OUTBOUND, alternate->endpoints[2]->direction); + EXPECT_EQ(512u, + config.interfaces[0]->alternates[0]->endpoints[2]->packet_size); EXPECT_EQ(UsbSynchronizationType::NONE, - config.interfaces[0].endpoints[2]->synchronization_type); - EXPECT_EQ(UsbTransferType::INTERRUPT, - config.interfaces[0].endpoints[2]->type); - EXPECT_EQ(UsbUsageType::NOTIFICATION, - config.interfaces[0].endpoints[2]->usage_type); - EXPECT_EQ(4, config.interfaces[0].endpoints[2]->polling_interval); - EXPECT_EQ(0u, config.interfaces[0].endpoints[2]->extra_data.size()); + alternate->endpoints[2]->synchronization_type); + EXPECT_EQ(UsbTransferType::INTERRUPT, alternate->endpoints[2]->type); + EXPECT_EQ(UsbUsageType::NOTIFICATION, alternate->endpoints[2]->usage_type); + EXPECT_EQ(4, alternate->endpoints[2]->polling_interval); + EXPECT_EQ(0u, alternate->endpoints[2]->extra_data.size()); // Interface 1 - EXPECT_EQ(1, config.interfaces[1].interface_number); - EXPECT_EQ(0, config.interfaces[1].alternate_setting); - EXPECT_EQ(0x78, config.interfaces[1].interface_class); - EXPECT_EQ(0x9A, config.interfaces[1].interface_subclass); - EXPECT_EQ(0xAB, config.interfaces[1].interface_protocol); - ASSERT_EQ(0u, config.interfaces[1].endpoints.size()); - EXPECT_EQ(0u, config.interfaces[1].extra_data.size()); - EXPECT_EQ(0, config.interfaces[1].first_interface); + EXPECT_EQ(1, config.interfaces[1]->interface_number); + EXPECT_EQ(0, config.interfaces[1]->first_interface); + EXPECT_EQ(0, config.interfaces[1]->alternates[0]->alternate_setting); + EXPECT_EQ(0x78, config.interfaces[1]->alternates[0]->class_code); + EXPECT_EQ(0x9A, config.interfaces[1]->alternates[0]->subclass_code); + EXPECT_EQ(0xAB, config.interfaces[1]->alternates[0]->protocol_code); + ASSERT_EQ(0u, config.interfaces[1]->alternates[0]->endpoints.size()); + EXPECT_EQ(0u, config.interfaces[1]->alternates[0]->extra_data.size()); } void ExpectConfig2Descriptor(const UsbConfigDescriptor& config) { @@ -144,51 +139,46 @@ EXPECT_TRUE(config.self_powered); EXPECT_FALSE(config.remote_wakeup); EXPECT_EQ(32, config.maximum_power); - ASSERT_EQ(2u, config.interfaces.size()); + ASSERT_EQ(1u, config.interfaces.size()); + ASSERT_EQ(2u, config.interfaces[0]->alternates.size()); EXPECT_EQ(0u, config.extra_data.size()); // Interface 0 - EXPECT_EQ(0, config.interfaces[0].interface_number); - EXPECT_EQ(0, config.interfaces[0].alternate_setting); - EXPECT_EQ(0xCD, config.interfaces[0].interface_class); - EXPECT_EQ(0xEF, config.interfaces[0].interface_subclass); - EXPECT_EQ(0x01, config.interfaces[0].interface_protocol); - ASSERT_EQ(0u, config.interfaces[0].endpoints.size()); - EXPECT_EQ(0u, config.interfaces[0].extra_data.size()); - EXPECT_EQ(0, config.interfaces[0].first_interface); + EXPECT_EQ(0, config.interfaces[0]->interface_number); + EXPECT_EQ(0, config.interfaces[0]->alternates[0]->alternate_setting); + EXPECT_EQ(0xCD, config.interfaces[0]->alternates[0]->class_code); + EXPECT_EQ(0xEF, config.interfaces[0]->alternates[0]->subclass_code); + EXPECT_EQ(0x01, config.interfaces[0]->alternates[0]->protocol_code); + ASSERT_EQ(0u, config.interfaces[0]->alternates[0]->endpoints.size()); + EXPECT_EQ(0u, config.interfaces[0]->alternates[0]->extra_data.size()); + EXPECT_EQ(0, config.interfaces[0]->first_interface); // Interface 0 (alternate 1) - EXPECT_EQ(0, config.interfaces[1].interface_number); - EXPECT_EQ(1, config.interfaces[1].alternate_setting); - EXPECT_EQ(0xCD, config.interfaces[1].interface_class); - EXPECT_EQ(0xEF, config.interfaces[1].interface_subclass); - EXPECT_EQ(0x01, config.interfaces[1].interface_protocol); - ASSERT_EQ(2u, config.interfaces[1].endpoints.size()); - EXPECT_EQ(0u, config.interfaces[1].extra_data.size()); - EXPECT_EQ(0, config.interfaces[1].first_interface); + const auto& alternate = config.interfaces[0]->alternates[1]; + EXPECT_EQ(1, alternate->alternate_setting); + EXPECT_EQ(0xCD, alternate->class_code); + EXPECT_EQ(0xEF, alternate->subclass_code); + EXPECT_EQ(0x01, alternate->protocol_code); + ASSERT_EQ(2u, alternate->endpoints.size()); + EXPECT_EQ(0u, alternate->extra_data.size()); // Endpoint 1 IN - EXPECT_EQ(0x01, config.interfaces[1].endpoints[0]->endpoint_number); - EXPECT_EQ(UsbTransferDirection::INBOUND, - config.interfaces[1].endpoints[0]->direction); - EXPECT_EQ(1024u, config.interfaces[1].endpoints[0]->packet_size); + EXPECT_EQ(0x01, alternate->endpoints[0]->endpoint_number); + EXPECT_EQ(UsbTransferDirection::INBOUND, alternate->endpoints[0]->direction); + EXPECT_EQ(1024u, alternate->endpoints[0]->packet_size); EXPECT_EQ(UsbSynchronizationType::NONE, - config.interfaces[1].endpoints[0]->synchronization_type); - EXPECT_EQ(UsbTransferType::ISOCHRONOUS, - config.interfaces[1].endpoints[0]->type); - EXPECT_EQ(UsbUsageType::DATA, config.interfaces[1].endpoints[0]->usage_type); - EXPECT_EQ(8, config.interfaces[1].endpoints[0]->polling_interval); - EXPECT_EQ(0u, config.interfaces[1].endpoints[0]->extra_data.size()); + alternate->endpoints[0]->synchronization_type); + EXPECT_EQ(UsbTransferType::ISOCHRONOUS, alternate->endpoints[0]->type); + EXPECT_EQ(UsbUsageType::DATA, alternate->endpoints[0]->usage_type); + EXPECT_EQ(8, alternate->endpoints[0]->polling_interval); + EXPECT_EQ(0u, alternate->endpoints[0]->extra_data.size()); // Endpoint 2 OUT - EXPECT_EQ(0x02, config.interfaces[1].endpoints[1]->endpoint_number); - EXPECT_EQ(UsbTransferDirection::OUTBOUND, - config.interfaces[1].endpoints[1]->direction); - EXPECT_EQ(1024u, config.interfaces[1].endpoints[1]->packet_size); + EXPECT_EQ(0x02, alternate->endpoints[1]->endpoint_number); + EXPECT_EQ(UsbTransferDirection::OUTBOUND, alternate->endpoints[1]->direction); + EXPECT_EQ(1024u, alternate->endpoints[1]->packet_size); EXPECT_EQ(UsbSynchronizationType::NONE, - config.interfaces[1].endpoints[1]->synchronization_type); - EXPECT_EQ(UsbTransferType::ISOCHRONOUS, - config.interfaces[1].endpoints[1]->type); - EXPECT_EQ(UsbUsageType::FEEDBACK, - config.interfaces[1].endpoints[1]->usage_type); - EXPECT_EQ(8, config.interfaces[1].endpoints[1]->polling_interval); - EXPECT_EQ(0u, config.interfaces[1].endpoints[1]->extra_data.size()); + alternate->endpoints[1]->synchronization_type); + EXPECT_EQ(UsbTransferType::ISOCHRONOUS, alternate->endpoints[1]->type); + EXPECT_EQ(UsbUsageType::FEEDBACK, alternate->endpoints[1]->usage_type); + EXPECT_EQ(8, alternate->endpoints[1]->polling_interval); + EXPECT_EQ(0u, alternate->endpoints[1]->extra_data.size()); } void ExpectDeviceDescriptor(const UsbDeviceDescriptor& descriptor) { @@ -257,14 +247,14 @@ TEST_F(UsbDescriptorsTest, NoInterfaceAssociations) { UsbConfigDescriptor config(1, false, false, 0); - config.interfaces.emplace_back(0, 0, 255, 255, 255); - config.interfaces.emplace_back(0, 1, 255, 255, 255); - config.interfaces.emplace_back(1, 0, 255, 255, 255); + config.interfaces.push_back(BuildUsbInterfaceInfoPtr(0, 0, 255, 255, 255)); + config.interfaces.push_back(BuildUsbInterfaceInfoPtr(0, 1, 255, 255, 255)); + config.interfaces.push_back(BuildUsbInterfaceInfoPtr(1, 0, 255, 255, 255)); config.AssignFirstInterfaceNumbers(); - EXPECT_EQ(0, config.interfaces[0].first_interface); - EXPECT_EQ(0, config.interfaces[1].first_interface); - EXPECT_EQ(1, config.interfaces[2].first_interface); + EXPECT_EQ(0, config.interfaces[0]->first_interface); + EXPECT_EQ(0, config.interfaces[1]->first_interface); + EXPECT_EQ(1, config.interfaces[2]->first_interface); } TEST_F(UsbDescriptorsTest, InterfaceAssociations) { @@ -285,38 +275,40 @@ config.extra_data.assign(kIAD1, kIAD1 + sizeof(kIAD1)); config.extra_data.insert(config.extra_data.end(), kIAD2, kIAD2 + sizeof(kIAD2)); - config.interfaces.emplace_back(0, 0, 255, 255, 255); - config.interfaces.emplace_back(1, 0, 255, 255, 255); - UsbInterfaceDescriptor iface1a(1, 1, 255, 255, 255); - iface1a.extra_data.assign(kIAD3, kIAD3 + sizeof(kIAD3)); + config.interfaces.push_back(BuildUsbInterfaceInfoPtr(0, 0, 255, 255, 255)); + config.interfaces.push_back(BuildUsbInterfaceInfoPtr(1, 0, 255, 255, 255)); + mojom::UsbInterfaceInfoPtr iface1a = + BuildUsbInterfaceInfoPtr(1, 1, 255, 255, 255); + iface1a->alternates[0]->extra_data.assign(kIAD3, kIAD3 + sizeof(kIAD3)); config.interfaces.push_back(std::move(iface1a)); - config.interfaces.emplace_back(2, 0, 255, 255, 255); - config.interfaces.emplace_back(3, 0, 255, 255, 255); - UsbInterfaceDescriptor iface4(4, 0, 255, 255, 255); - iface4.extra_data.assign(kIAD4, kIAD4 + sizeof(kIAD4)); + config.interfaces.push_back(BuildUsbInterfaceInfoPtr(2, 0, 255, 255, 255)); + config.interfaces.push_back(BuildUsbInterfaceInfoPtr(3, 0, 255, 255, 255)); + mojom::UsbInterfaceInfoPtr iface4 = + BuildUsbInterfaceInfoPtr(4, 0, 255, 255, 255); + iface4->alternates[0]->extra_data.assign(kIAD4, kIAD4 + sizeof(kIAD4)); config.interfaces.push_back(std::move(iface4)); - config.interfaces.emplace_back(5, 0, 255, 255, 255); + config.interfaces.push_back(BuildUsbInterfaceInfoPtr(5, 0, 255, 255, 255)); config.AssignFirstInterfaceNumbers(); // Interfaces 0 and 1 (plus 1's alternate) are a single function. - EXPECT_EQ(0, config.interfaces[0].interface_number); - EXPECT_EQ(0, config.interfaces[0].first_interface); - EXPECT_EQ(1, config.interfaces[1].interface_number); - EXPECT_EQ(0, config.interfaces[1].first_interface); - EXPECT_EQ(1, config.interfaces[2].interface_number); - EXPECT_EQ(0, config.interfaces[2].first_interface); + EXPECT_EQ(0, config.interfaces[0]->interface_number); + EXPECT_EQ(0, config.interfaces[0]->first_interface); + EXPECT_EQ(1, config.interfaces[1]->interface_number); + EXPECT_EQ(0, config.interfaces[1]->first_interface); + EXPECT_EQ(1, config.interfaces[2]->interface_number); + EXPECT_EQ(0, config.interfaces[2]->first_interface); // Interfaces 2 and 3 are their own functions. - EXPECT_EQ(2, config.interfaces[3].interface_number); - EXPECT_EQ(2, config.interfaces[3].first_interface); - EXPECT_EQ(3, config.interfaces[4].interface_number); - EXPECT_EQ(3, config.interfaces[4].first_interface); + EXPECT_EQ(2, config.interfaces[3]->interface_number); + EXPECT_EQ(2, config.interfaces[3]->first_interface); + EXPECT_EQ(3, config.interfaces[4]->interface_number); + EXPECT_EQ(3, config.interfaces[4]->first_interface); // Interfaces 4 and 5 are a single function. - EXPECT_EQ(4, config.interfaces[5].interface_number); - EXPECT_EQ(4, config.interfaces[5].first_interface); - EXPECT_EQ(5, config.interfaces[6].interface_number); - EXPECT_EQ(4, config.interfaces[6].first_interface); + EXPECT_EQ(4, config.interfaces[5]->interface_number); + EXPECT_EQ(4, config.interfaces[5]->first_interface); + EXPECT_EQ(5, config.interfaces[6]->interface_number); + EXPECT_EQ(4, config.interfaces[6]->first_interface); } TEST_F(UsbDescriptorsTest, CorruptInterfaceAssociations) { @@ -340,12 +332,12 @@ static const uint8_t kIAD[] = {0x08, 0x0b, 0x07, 0x00, 0xff, 0xff, 0xff, 0x00}; UsbConfigDescriptor config(1, false, false, 0); - config.interfaces.emplace_back(0, 0, 255, 255, 255); + config.interfaces.push_back(BuildUsbInterfaceInfoPtr(0, 0, 255, 255, 255)); config.extra_data.assign(kIAD, kIAD + sizeof(kIAD)); config.AssignFirstInterfaceNumbers(); - EXPECT_EQ(0, config.interfaces[0].interface_number); - EXPECT_EQ(0, config.interfaces[0].first_interface); + EXPECT_EQ(0, config.interfaces[0]->interface_number); + EXPECT_EQ(0, config.interfaces[0]->first_interface); } }
diff --git a/services/device/usb/usb_device_android.cc b/services/device/usb/usb_device_android.cc index 9a857ab..4c439f5 100644 --- a/services/device/usb/usb_device_android.cc +++ b/services/device/usb/usb_device_android.cc
@@ -153,6 +153,7 @@ for (auto interface : interfaces) { config.interfaces.push_back(UsbInterfaceAndroid::Convert(env, interface)); } + AggregateInterfacesForConfig(&config); descriptor_.configurations.push_back(config); }
diff --git a/services/device/usb/usb_device_handle.h b/services/device/usb/usb_device_handle.h index e2f7d781..df5ad67c 100644 --- a/services/device/usb/usb_device_handle.h +++ b/services/device/usb/usb_device_handle.h
@@ -99,7 +99,7 @@ // Gets the interface containing |endpoint_address|. Returns nullptr if no // claimed interface contains that endpoint. - virtual const UsbInterfaceDescriptor* FindInterfaceByEndpoint( + virtual const mojom::UsbInterfaceInfo* FindInterfaceByEndpoint( uint8_t endpoint_address) = 0; protected:
diff --git a/services/device/usb/usb_device_handle_impl.cc b/services/device/usb/usb_device_handle_impl.cc index d2fd569..bd86279e 100644 --- a/services/device/usb/usb_device_handle_impl.cc +++ b/services/device/usb/usb_device_handle_impl.cc
@@ -815,7 +815,7 @@ SubmitTransfer(std::move(transfer)); } -const UsbInterfaceDescriptor* UsbDeviceHandleImpl::FindInterfaceByEndpoint( +const mojom::UsbInterfaceInfo* UsbDeviceHandleImpl::FindInterfaceByEndpoint( uint8_t endpoint_address) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -989,21 +989,19 @@ DCHECK(device_); endpoint_map_.clear(); const UsbConfigDescriptor* config = device_->active_configuration(); - if (config) { - for (const auto& map_entry : claimed_interfaces_) { - int interface_number = map_entry.first; - const scoped_refptr<InterfaceClaimer>& claimed_iface = map_entry.second; + if (!config) + return; - for (const UsbInterfaceDescriptor& iface : config->interfaces) { - if (iface.interface_number == interface_number && - iface.alternate_setting == claimed_iface->alternate_setting()) { - for (const auto& endpoint : iface.endpoints) { - endpoint_map_[ConvertEndpointNumberToAddress(*endpoint)] = { - &iface, endpoint.get()}; - } - break; - } - } + for (const auto& map_entry : claimed_interfaces_) { + CombinedInterfaceInfo interface_info = FindInterfaceInfoFromConfig( + config, map_entry.first, map_entry.second->alternate_setting()); + + if (!interface_info.IsValid()) + return; + + for (const auto& endpoint : interface_info.alternate->endpoints) { + endpoint_map_[ConvertEndpointNumberToAddress(*endpoint)] = { + interface_info.interface, endpoint.get()}; } } }
diff --git a/services/device/usb/usb_device_handle_impl.h b/services/device/usb/usb_device_handle_impl.h index b1d1e64..7cf379a 100644 --- a/services/device/usb/usb_device_handle_impl.h +++ b/services/device/usb/usb_device_handle_impl.h
@@ -30,7 +30,7 @@ namespace device { struct EndpointMapValue { - const UsbInterfaceDescriptor* interface; + const mojom::UsbInterfaceInfo* interface; const mojom::UsbEndpointInfo* endpoint; }; @@ -80,7 +80,7 @@ scoped_refptr<base::RefCountedBytes> buffer, unsigned int timeout, TransferCallback callback) override; - const UsbInterfaceDescriptor* FindInterfaceByEndpoint( + const mojom::UsbInterfaceInfo* FindInterfaceByEndpoint( uint8_t endpoint_address) override; protected:
diff --git a/services/device/usb/usb_device_handle_unittest.cc b/services/device/usb/usb_device_handle_unittest.cc index bfee391..f571258 100644 --- a/services/device/usb/usb_device_handle_unittest.cc +++ b/services/device/usb/usb_device_handle_unittest.cc
@@ -140,7 +140,7 @@ handle->ClaimInterface(0, claim_interface.GetCallback()); ASSERT_TRUE(claim_interface.WaitForResult()); - const UsbInterfaceDescriptor* interface = + const mojom::UsbInterfaceInfo* interface = handle->FindInterfaceByEndpoint(0x81); EXPECT_TRUE(interface); EXPECT_EQ(0, interface->interface_number); @@ -208,7 +208,7 @@ EXPECT_FALSE(handle->FindInterfaceByEndpoint(0x81)); EXPECT_FALSE(handle->FindInterfaceByEndpoint(0x01)); - const UsbInterfaceDescriptor* interface = + const mojom::UsbInterfaceInfo* interface = handle->FindInterfaceByEndpoint(0x82); EXPECT_TRUE(interface); EXPECT_EQ(1, interface->interface_number);
diff --git a/services/device/usb/usb_device_handle_usbfs.cc b/services/device/usb/usb_device_handle_usbfs.cc index 21f4333..40bf6f68 100644 --- a/services/device/usb/usb_device_handle_usbfs.cc +++ b/services/device/usb/usb_device_handle_usbfs.cc
@@ -10,6 +10,7 @@ #include <sys/ioctl.h> #include <numeric> +#include <utility> #include "base/bind.h" #include "base/cancelable_callback.h" @@ -706,7 +707,7 @@ } } -const UsbInterfaceDescriptor* UsbDeviceHandleUsbfs::FindInterfaceByEndpoint( +const mojom::UsbInterfaceInfo* UsbDeviceHandleUsbfs::FindInterfaceByEndpoint( uint8_t endpoint_address) { DCHECK(sequence_checker_.CalledOnValidSequence()); auto it = endpoints_.find(endpoint_address); @@ -867,21 +868,16 @@ return; for (const auto& entry : interfaces_) { - auto interface_it = std::find_if( - config->interfaces.begin(), config->interfaces.end(), - [entry](const UsbInterfaceDescriptor& interface) { - uint8_t interface_number = entry.first; - uint8_t alternate_setting = entry.second.alternate_setting; - return interface.interface_number == interface_number && - interface.alternate_setting == alternate_setting; - }); - DCHECK(interface_it != config->interfaces.end()); + CombinedInterfaceInfo interface = FindInterfaceInfoFromConfig( + config, entry.first, entry.second.alternate_setting); - for (const auto& endpoint : interface_it->endpoints) { + DCHECK(interface.IsValid()); + + for (const auto& endpoint : interface.alternate->endpoints) { EndpointInfo& info = endpoints_[ConvertEndpointNumberToAddress(*endpoint)]; info.type = endpoint->type; - info.interface = &*interface_it; + info.interface = interface.interface; } } }
diff --git a/services/device/usb/usb_device_handle_usbfs.h b/services/device/usb/usb_device_handle_usbfs.h index 2458383..2cbb3af4 100644 --- a/services/device/usb/usb_device_handle_usbfs.h +++ b/services/device/usb/usb_device_handle_usbfs.h
@@ -70,7 +70,7 @@ scoped_refptr<base::RefCountedBytes> buffer, unsigned int timeout, TransferCallback callback) override; - const UsbInterfaceDescriptor* FindInterfaceByEndpoint( + const mojom::UsbInterfaceInfo* FindInterfaceByEndpoint( uint8_t endpoint_address) override; protected: @@ -95,7 +95,7 @@ }; struct EndpointInfo { UsbTransferType type; - const UsbInterfaceDescriptor* interface; + const mojom::UsbInterfaceInfo* interface; }; void SetConfigurationComplete(int configuration_value,
diff --git a/services/device/usb/usb_device_handle_win.cc b/services/device/usb/usb_device_handle_win.cc index 5babe84e..9e83ca0 100644 --- a/services/device/usb/usb_device_handle_win.cc +++ b/services/device/usb/usb_device_handle_win.cc
@@ -469,7 +469,7 @@ std::move(buffer))); } -const UsbInterfaceDescriptor* UsbDeviceHandleWin::FindInterfaceByEndpoint( +const mojom::UsbInterfaceInfo* UsbDeviceHandleWin::FindInterfaceByEndpoint( uint8_t endpoint_address) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -490,13 +490,16 @@ DCHECK(device_->active_configuration()); for (const auto& interface : device_->active_configuration()->interfaces) { - if (interface.alternate_setting != 0) - continue; + for (const auto& alternate : interface->alternates) { + if (alternate->alternate_setting != 0) + continue; - Interface& interface_info = interfaces_[interface.interface_number]; - interface_info.interface_number = interface.interface_number; - interface_info.first_interface = interface.first_interface; - RegisterEndpoints(interface); + Interface& interface_info = interfaces_[interface->interface_number]; + interface_info.interface_number = interface->interface_number; + interface_info.first_interface = interface->first_interface; + RegisterEndpoints( + CombinedInterfaceInfo(interface.get(), alternate.get())); + } } } @@ -556,18 +559,19 @@ } void UsbDeviceHandleWin::RegisterEndpoints( - const UsbInterfaceDescriptor& interface) { - for (const auto& endpoint : interface.endpoints) { + const CombinedInterfaceInfo& interface) { + DCHECK(interface.IsValid()); + for (const auto& endpoint : interface.alternate->endpoints) { Endpoint& endpoint_info = endpoints_[ConvertEndpointNumberToAddress(*endpoint)]; - endpoint_info.interface = &interface; + endpoint_info.interface = interface.interface; endpoint_info.type = endpoint->type; } } void UsbDeviceHandleWin::UnregisterEndpoints( - const UsbInterfaceDescriptor& interface) { - for (const auto& endpoint : interface.endpoints) + const CombinedInterfaceInfo& interface) { + for (const auto& endpoint : interface.alternate->endpoints) endpoints_.erase(ConvertEndpointNumberToAddress(*endpoint)); }
diff --git a/services/device/usb/usb_device_handle_win.h b/services/device/usb/usb_device_handle_win.h index 2bead587..f2695e1cf 100644 --- a/services/device/usb/usb_device_handle_win.h +++ b/services/device/usb/usb_device_handle_win.h
@@ -6,6 +6,7 @@ #define SERVICES_DEVICE_USB_USB_DEVICE_HANDLE_WIN_H_ #include <map> +#include <memory> #include <vector> #include "base/callback.h" @@ -67,7 +68,7 @@ scoped_refptr<base::RefCountedBytes> buffer, unsigned int timeout, TransferCallback callback) override; - const UsbInterfaceDescriptor* FindInterfaceByEndpoint( + const mojom::UsbInterfaceInfo* FindInterfaceByEndpoint( uint8_t endpoint_address) override; protected: @@ -99,13 +100,13 @@ }; struct Endpoint { - const UsbInterfaceDescriptor* interface; + const mojom::UsbInterfaceInfo* interface; UsbTransferType type; }; bool OpenInterfaceHandle(Interface* interface); - void RegisterEndpoints(const UsbInterfaceDescriptor& interface); - void UnregisterEndpoints(const UsbInterfaceDescriptor& interface); + void RegisterEndpoints(const CombinedInterfaceInfo& interface); + void UnregisterEndpoints(const CombinedInterfaceInfo& interface); WINUSB_INTERFACE_HANDLE GetInterfaceForControlTransfer( UsbControlTransferRecipient recipient, uint16_t index);
diff --git a/services/device/usb/usb_interface_android.cc b/services/device/usb/usb_interface_android.cc index e327951..decb143 100644 --- a/services/device/usb/usb_interface_android.cc +++ b/services/device/usb/usb_interface_android.cc
@@ -13,7 +13,7 @@ namespace device { // static -UsbInterfaceDescriptor UsbInterfaceAndroid::Convert( +mojom::UsbInterfaceInfoPtr UsbInterfaceAndroid::Convert( JNIEnv* env, const base::android::JavaRef<jobject>& usb_interface) { ScopedJavaLocalRef<jobject> wrapper = @@ -26,7 +26,7 @@ Java_ChromeUsbInterface_getAlternateSetting(env, wrapper); } - UsbInterfaceDescriptor interface( + auto interface = BuildUsbInterfaceInfoPtr( Java_ChromeUsbInterface_getInterfaceNumber(env, wrapper), alternate_setting, Java_ChromeUsbInterface_getInterfaceClass(env, wrapper), @@ -35,9 +35,10 @@ base::android::JavaObjectArrayReader<jobject> endpoints( Java_ChromeUsbInterface_getEndpoints(env, wrapper)); - interface.endpoints.reserve(endpoints.size()); + interface->alternates[0]->endpoints.reserve(endpoints.size()); for (auto endpoint : endpoints) { - interface.endpoints.push_back(UsbEndpointAndroid::Convert(env, endpoint)); + interface->alternates[0]->endpoints.push_back( + UsbEndpointAndroid::Convert(env, endpoint)); } return interface;
diff --git a/services/device/usb/usb_interface_android.h b/services/device/usb/usb_interface_android.h index 1aa9158c..4ed435c 100644 --- a/services/device/usb/usb_interface_android.h +++ b/services/device/usb/usb_interface_android.h
@@ -12,7 +12,7 @@ class UsbInterfaceAndroid { public: - static UsbInterfaceDescriptor Convert( + static mojom::UsbInterfaceInfoPtr Convert( JNIEnv* env, const base::android::JavaRef<jobject>& usb_interface); };
diff --git a/services/identity/BUILD.gn b/services/identity/BUILD.gn index 8af1424f..b816137 100644 --- a/services/identity/BUILD.gn +++ b/services/identity/BUILD.gn
@@ -19,7 +19,7 @@ deps = [ "//base", "//components/signin/core/browser:internals", - "//components/signin/core/browser:shared", + "//components/signin/public/base", "//components/signin/public/identity_manager", "//google_apis", "//services/identity/public/cpp:cpp_types", @@ -40,7 +40,7 @@ ":lib", "//base", "//base/test:test_support", - "//components/signin/core/browser:shared", + "//components/signin/public/base", "//components/signin/public/identity_manager:test_support", "//services/identity/public/cpp:cpp_types", "//services/identity/public/mojom",
diff --git a/services/identity/DEPS b/services/identity/DEPS index 92de58db..6056656c 100644 --- a/services/identity/DEPS +++ b/services/identity/DEPS
@@ -1,5 +1,5 @@ include_rules = [ - "+components/signin/core/browser/account_info.h", + "+components/signin/public/identity_manager/account_info.h", "+components/signin/core/browser/profile_oauth2_token_service.h", "+components/signin/public/identity_manager/access_token_info.h", "+components/signin/public/identity_manager/identity_manager.h",
diff --git a/services/identity/identity_accessor_impl.h b/services/identity/identity_accessor_impl.h index 8ced9d3..8b0c516b 100644 --- a/services/identity/identity_accessor_impl.h +++ b/services/identity/identity_accessor_impl.h
@@ -9,8 +9,8 @@ #include <memory> #include "base/callback_list.h" -#include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "google_apis/gaia/core_account_id.h" #include "services/identity/public/cpp/account_state.h"
diff --git a/services/identity/identity_accessor_impl_unittest.cc b/services/identity/identity_accessor_impl_unittest.cc index a672b68e7..90488ae 100644 --- a/services/identity/identity_accessor_impl_unittest.cc +++ b/services/identity/identity_accessor_impl_unittest.cc
@@ -6,7 +6,7 @@ #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "build/build_config.h" -#include "components/signin/core/browser/account_info.h" +#include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "services/identity/identity_service.h" #include "services/identity/public/cpp/account_state.h"
diff --git a/services/network/BUILD.gn b/services/network/BUILD.gn index d01715a..8fbd123 100644 --- a/services/network/BUILD.gn +++ b/services/network/BUILD.gn
@@ -208,6 +208,8 @@ "cert_verify_proc_chromeos.h", "nss_temp_certs_cache_chromeos.cc", "nss_temp_certs_cache_chromeos.h", + "system_trust_store_provider_chromeos.cc", + "system_trust_store_provider_chromeos.h", ] }
diff --git a/services/network/network_context.cc b/services/network/network_context.cc index d61991d8..0bc1dff 100644 --- a/services/network/network_context.cc +++ b/services/network/network_context.cc
@@ -107,10 +107,13 @@ #if defined(OS_CHROMEOS) #include "crypto/nss_util_internal.h" #include "net/cert/caching_cert_verifier.h" +#include "net/cert/cert_verify_proc_builtin.h" +#include "net/cert/internal/system_trust_store.h" #include "net/cert/multi_threaded_cert_verifier.h" #include "services/network/cert_verifier_with_trust_anchors.h" #include "services/network/cert_verify_proc_chromeos.h" #include "services/network/nss_temp_certs_cache_chromeos.h" +#include "services/network/system_trust_store_provider_chromeos.h" #endif #if !defined(OS_IOS) @@ -2104,7 +2107,7 @@ if (g_cert_verifier_for_testing) { cert_verifier = std::make_unique<WrappedTestingCertVerifier>(); } else { -#if defined(OS_ANDROID) || defined(OS_FUCHSIA) || \ +#if defined(OS_ANDROID) || defined(OS_FUCHSIA) || defined(OS_CHROMEOS) || \ BUILDFLAG(TRIAL_COMPARISON_CERT_VERIFIER_SUPPORTED) cert_net_fetcher_ = base::MakeRefCounted<net::CertNetFetcherImpl>(); #endif @@ -2112,7 +2115,7 @@ if (params_->username_hash.empty()) { cert_verifier = std::make_unique<net::CachingCertVerifier>( std::make_unique<net::MultiThreadedCertVerifier>( - base::MakeRefCounted<CertVerifyProcChromeOS>())); + CreateCertVerifyProcWithoutUserSlots(cert_net_fetcher_))); } else { // Make sure NSS is initialized for the user. crypto::InitializeNSSForChromeOSUser(params_->username_hash, @@ -2120,8 +2123,9 @@ crypto::ScopedPK11Slot public_slot = crypto::GetPublicSlotForChromeOSUser(params_->username_hash); - scoped_refptr<net::CertVerifyProc> verify_proc( - new CertVerifyProcChromeOS(std::move(public_slot))); + scoped_refptr<net::CertVerifyProc> verify_proc = + CreateCertVerifyProcForUser(cert_net_fetcher_, + std::move(public_slot)); cert_verifier_with_trust_anchors_ = new CertVerifierWithTrustAnchors( base::Bind(&NetworkContext::TrustAnchorUsed, base::Unretained(this))); @@ -2300,6 +2304,30 @@ void NetworkContext::TrustAnchorUsed() { network_service_->client()->OnTrustAnchorUsed(params_->username_hash); } + +scoped_refptr<net::CertVerifyProc> NetworkContext::CreateCertVerifyProcForUser( + scoped_refptr<net::CertNetFetcher> net_fetcher, + crypto::ScopedPK11Slot user_public_slot) { + if (params_->use_builtin_cert_verifier) { + return net::CreateCertVerifyProcBuiltin( + std::move(net_fetcher), + std::make_unique<SystemTrustStoreProviderChromeOS>( + std::move(user_public_slot))); + } + return base::MakeRefCounted<CertVerifyProcChromeOS>( + std::move(user_public_slot)); +} + +scoped_refptr<net::CertVerifyProc> +NetworkContext::CreateCertVerifyProcWithoutUserSlots( + scoped_refptr<net::CertNetFetcher> net_fetcher) { + if (params_->use_builtin_cert_verifier) { + return net::CreateCertVerifyProcBuiltin( + std::move(net_fetcher), + std::make_unique<SystemTrustStoreProviderChromeOS>()); + } + return base::MakeRefCounted<CertVerifyProcChromeOS>(); +} #endif void NetworkContext::InitializeCorsParams() {
diff --git a/services/network/network_context.h b/services/network/network_context.h index 8b45ddce..3f47a762 100644 --- a/services/network/network_context.h +++ b/services/network/network_context.h
@@ -51,13 +51,19 @@ #include "services/network/socket_factory.h" #include "services/network/url_request_context_owner.h" +#if defined(OS_CHROMEOS) +#include "crypto/scoped_nss_types.h" +#endif + namespace base { class UnguessableToken; } // namespace base namespace net { +class CertNetFetcher; class CertNetFetcherImpl; class CertVerifier; +class CertVerifyProc; class HostPortPair; class ReportSender; class StaticHttpUserAgentSettings; @@ -448,6 +454,13 @@ #if defined(OS_CHROMEOS) void TrustAnchorUsed(); + + scoped_refptr<net::CertVerifyProc> CreateCertVerifyProcForUser( + scoped_refptr<net::CertNetFetcher> net_fetcher, + crypto::ScopedPK11Slot user_public_slot); + + scoped_refptr<net::CertVerifyProc> CreateCertVerifyProcWithoutUserSlots( + scoped_refptr<net::CertNetFetcher> net_fetcher); #endif #if BUILDFLAG(IS_CT_SUPPORTED)
diff --git a/services/network/network_context_unittest.cc b/services/network/network_context_unittest.cc index f8cb6e1..c89fdfcf 100644 --- a/services/network/network_context_unittest.cc +++ b/services/network/network_context_unittest.cc
@@ -2479,7 +2479,7 @@ net::TestCompletionCallback start_callback; net_log_exporter->Start(std::move(out_file), std::move(dict_start), - net::NetLogCaptureMode::Default(), 100 * 1024, + net::NetLogCaptureMode::kDefault, 100 * 1024, start_callback.callback()); EXPECT_EQ(net::OK, start_callback.WaitForResult()); @@ -2524,7 +2524,7 @@ net::TestCompletionCallback start_callback; net_log_exporter->Start( std::move(out_file), base::Value(base::Value::Type::DICTIONARY), - net::NetLogCaptureMode::Default(), + net::NetLogCaptureMode::kDefault, mojom::NetLogExporter::kUnlimitedFileSize, start_callback.callback()); EXPECT_EQ(net::OK, start_callback.WaitForResult()); @@ -2566,7 +2566,7 @@ net::TestCompletionCallback start_callback; net_log_exporter->Start( std::move(temp_file), base::Value(base::Value::Type::DICTIONARY), - net::NetLogCaptureMode::Default(), 100 * 1024, start_callback.callback()); + net::NetLogCaptureMode::kDefault, 100 * 1024, start_callback.callback()); EXPECT_EQ(net::OK, start_callback.WaitForResult()); // Can't start twice. @@ -2577,10 +2577,9 @@ ASSERT_TRUE(temp_file2.IsValid()); net::TestCompletionCallback start_callback2; - net_log_exporter->Start(std::move(temp_file2), - base::Value(base::Value::Type::DICTIONARY), - net::NetLogCaptureMode::Default(), 100 * 1024, - start_callback2.callback()); + net_log_exporter->Start( + std::move(temp_file2), base::Value(base::Value::Type::DICTIONARY), + net::NetLogCaptureMode::kDefault, 100 * 1024, start_callback2.callback()); EXPECT_EQ(net::ERR_UNEXPECTED, start_callback2.WaitForResult()); base::DeleteFile(temp_path, false); @@ -2624,7 +2623,7 @@ net_log_exporter->Start( std::move(temp_file), base::Value(base::Value::Type::DICTIONARY), - net::NetLogCaptureMode::Default(), 100, base::BindOnce([](int) {})); + net::NetLogCaptureMode::kDefault, 100, base::BindOnce([](int) {})); net_log_exporter = nullptr; block_mktemp.Signal(); @@ -3992,7 +3991,7 @@ net_log_exporter->Start( std::move(net_log_file), /*extra_constants=*/base::Value(base::Value::Type::DICTIONARY), - net::NetLogCaptureMode::Default(), + net::NetLogCaptureMode::kDefault, network::mojom::NetLogExporter::kUnlimitedFileSize, start_callback); run_loop.Run(); EXPECT_EQ(net::OK, start_param);
diff --git a/services/network/network_service_unittest.cc b/services/network/network_service_unittest.cc index 4554386..ce8f35df 100644 --- a/services/network/network_service_unittest.cc +++ b/services/network/network_service_unittest.cc
@@ -734,7 +734,7 @@ base::File log_file(log_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); network_service_->StartNetLog( - std::move(log_file), net::NetLogCaptureMode::Default(), std::move(dict)); + std::move(log_file), net::NetLogCaptureMode::kDefault, std::move(dict)); CreateNetworkContext(); LoadURL(test_server()->GetURL("/echo")); EXPECT_EQ(net::OK, client()->completion_status().error_code);
diff --git a/services/network/public/cpp/net_log_mojom_traits.cc b/services/network/public/cpp/net_log_mojom_traits.cc index c1648f2b..8e0ff02 100644 --- a/services/network/public/cpp/net_log_mojom_traits.cc +++ b/services/network/public/cpp/net_log_mojom_traits.cc
@@ -12,13 +12,13 @@ net::NetLogCaptureMode* out) { switch (capture_mode) { case network::mojom::NetLogCaptureMode::DEFAULT: - *out = net::NetLogCaptureMode::Default(); + *out = net::NetLogCaptureMode::kDefault; return true; - case network::mojom::NetLogCaptureMode::INCLUDE_COOKIES_AND_CREDENTIALS: - *out = net::NetLogCaptureMode::IncludeCookiesAndCredentials(); + case network::mojom::NetLogCaptureMode::INCLUDE_PRIVACY_INFO: + *out = net::NetLogCaptureMode::kIncludeSensitive; return true; - case network::mojom::NetLogCaptureMode::INCLUDE_SOCKET_BYTES: - *out = net::NetLogCaptureMode::IncludeSocketBytes(); + case network::mojom::NetLogCaptureMode::EVERYTHING: + *out = net::NetLogCaptureMode::kEverything; return true; } return false; @@ -28,12 +28,16 @@ network::mojom::NetLogCaptureMode EnumTraits<network::mojom::NetLogCaptureMode, net::NetLogCaptureMode>::ToMojom( net::NetLogCaptureMode capture_mode) { - if (capture_mode.include_cookies_and_credentials()) - return network::mojom::NetLogCaptureMode::INCLUDE_COOKIES_AND_CREDENTIALS; - if (capture_mode.include_socket_bytes()) - return network::mojom::NetLogCaptureMode::INCLUDE_SOCKET_BYTES; + switch (capture_mode) { + case net::NetLogCaptureMode::kDefault: + return network::mojom::NetLogCaptureMode::DEFAULT; + case net::NetLogCaptureMode::kIncludeSensitive: + return network::mojom::NetLogCaptureMode::INCLUDE_PRIVACY_INFO; + case net::NetLogCaptureMode::kEverything: + return network::mojom::NetLogCaptureMode::EVERYTHING; + } - // TODO(eroman): Should fail if unrecognized mode rather than defaulting. + NOTREACHED(); return network::mojom::NetLogCaptureMode::DEFAULT; }
diff --git a/services/network/public/cpp/network_switches.cc b/services/network/public/cpp/network_switches.cc index 8a52522b7..3b3480a1 100644 --- a/services/network/public/cpp/network_switches.cc +++ b/services/network/public/cpp/network_switches.cc
@@ -43,11 +43,11 @@ // Sets the granularity of events to capture in the network log. The mode can be // set to one of the following values: // "Default" -// "IncludeCookiesAndCredentials" -// "IncludeSocketBytes" +// "IncludeSensitive" +// "Everything" // -// See the functions of the corresponding name in net_log_capture_mode.h for a -// description of their meaning. +// See the enums of the corresponding name in net_log_capture_mode.h for a +// description of their meanings. const char kNetLogCaptureMode[] = "net-log-capture-mode"; // Causes SSL key material to be logged to the specified file for debugging
diff --git a/services/network/public/cpp/url_request_for_blink.typemap b/services/network/public/cpp/url_request_for_blink.typemap index b43cde34..cd39dcc 100644 --- a/services/network/public/cpp/url_request_for_blink.typemap +++ b/services/network/public/cpp/url_request_for_blink.typemap
@@ -4,7 +4,11 @@ # TODO(minggang): Delete this file once all typemappings for network.mojom.URLRequest are done. mojom = "//services/network/public/mojom/url_loader.mojom" -public_headers = [ "//services/network/public/cpp/resource_request_body.h" ] +public_headers = [ + "//net/base/request_priority.h", + "//net/url_request/url_request.h", + "//services/network/public/cpp/resource_request_body.h", +] traits_headers = [ "//services/network/public/cpp/url_request_mojom_traits.h" ] public_deps = [ "//services/network/public/cpp:cpp_base", @@ -12,4 +16,6 @@ type_mappings = [ "network.mojom.DataElement=network::DataElement[move_only]", "network.mojom.URLRequestBody=scoped_refptr<network::ResourceRequestBody>[nullable_is_same_type,copyable_pass_by_value]", + "network.mojom.RequestPriority=net::RequestPriority", + "network.mojom.URLRequestReferrerPolicy=net::URLRequest::ReferrerPolicy", ]
diff --git a/services/network/public/mojom/net_log.mojom b/services/network/public/mojom/net_log.mojom index 8ccafc6..0c8ed4c 100644 --- a/services/network/public/mojom/net_log.mojom +++ b/services/network/public/mojom/net_log.mojom
@@ -14,11 +14,11 @@ // Log all events, but do not include the actual transferred bytes as // parameters for bytes sent/received events. - INCLUDE_COOKIES_AND_CREDENTIALS, + INCLUDE_PRIVACY_INFO, // Log everything possible, even if it is slow and memory expensive. // Includes logging of transferred bytes. - INCLUDE_SOCKET_BYTES + EVERYTHING }; // Manages export of ongoing NetLog events to a file.
diff --git a/services/network/public/mojom/network_context.mojom b/services/network/public/mojom/network_context.mojom index 52ed232f..1635251 100644 --- a/services/network/public/mojom/network_context.mojom +++ b/services/network/public/mojom/network_context.mojom
@@ -325,6 +325,11 @@ [EnableIf=is_chromeos] AdditionalCertificates? initial_additional_certificates; + // If true, the built-in cert verifier will be used. If false, the platform + // cert verifier will be used. + [EnableIf=is_chromeos] + bool use_builtin_cert_verifier = false; + // Parameters for the cert verifier comparison trial. This is a temporary // interface and embedders should not use it. // See https://crbug.com/649026 @@ -836,13 +841,22 @@ // "sec-websocket-protocol" is constructed from |requested_protocols| in // this message). |site_for_cookies| represents the first-party origin for // the request. |options| may be a combination of the kWebSocketOption* flags. - // The connection will be shut down when |handshake_client| gets disconnected - // during the handshake phase, or |connection_client| gets disconnected. + // // If |header_client| is set, requests with the kURLLoadOptionUseHeaderClient // option will callback to the |header_client|, allowing the Cookie/Referrer // request headers and Cookie response headers to be modified. This has a // performance impact because of the extra process hops, so use should be // minimized. + // + // Detect mojo connection errors on |handshake_client| in the caller side. + // Do *NOT* interpret mojo connection errors on |auth_handler| and + // |header_client| as WebSocket connection errors. They are disconnected when + // the connection is established, and due to message ordering uncertainty we + // cannot know what happened. |handshake_client| doesn't have such an issue + // because OnConnectionEstablished will be called when the connection is + // established, but it is still recommended to rely only on + // |connection_client| because |connection_client| can be disconnected with + // custom reasons. CreateWebSocket( url.mojom.Url url, array<string> requested_protocols,
diff --git a/services/network/session_cleanup_cookie_store.cc b/services/network/session_cleanup_cookie_store.cc index 651101c..92b0c42 100644 --- a/services/network/session_cleanup_cookie_store.cc +++ b/services/network/session_cleanup_cookie_store.cc
@@ -29,7 +29,7 @@ base::Value CookieStoreOriginFiltered(const std::string& origin, bool is_https, net::NetLogCaptureMode capture_mode) { - if (!capture_mode.include_cookies_and_credentials()) + if (!net::NetLogCaptureIncludesSensitive(capture_mode)) return base::Value(); base::DictionaryValue dict; dict.SetString("origin", origin);
diff --git a/services/network/session_cleanup_cookie_store_unittest.cc b/services/network/session_cleanup_cookie_store_unittest.cc index 1e9d305..24e3158 100644 --- a/services/network/session_cleanup_cookie_store_unittest.cc +++ b/services/network/session_cleanup_cookie_store_unittest.cc
@@ -167,7 +167,7 @@ base::Time t = base::Time::Now(); AddCookie("A", "B", "nonpersistent.com", "/", t); - net_log_.SetCaptureMode(net::NetLogCaptureMode::Default()); + net_log_.SetCaptureMode(net::NetLogCaptureMode::kDefault); // Cookies from "nonpersistent.com" should be deleted. store_->DeleteSessionCookies( base::BindRepeating([](const std::string& domain, bool is_https) {
diff --git a/services/network/system_trust_store_provider_chromeos.cc b/services/network/system_trust_store_provider_chromeos.cc new file mode 100644 index 0000000..2777918 --- /dev/null +++ b/services/network/system_trust_store_provider_chromeos.cc
@@ -0,0 +1,35 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/network/system_trust_store_provider_chromeos.h" + +#include <pk11pub.h> + +#include <utility> + +#include "net/cert/internal/system_trust_store_nss.h" + +namespace network { + +SystemTrustStoreProviderChromeOS::SystemTrustStoreProviderChromeOS() {} + +SystemTrustStoreProviderChromeOS::SystemTrustStoreProviderChromeOS( + crypto::ScopedPK11Slot user_slot) + : user_slot_(std::move(user_slot)) {} + +SystemTrustStoreProviderChromeOS::~SystemTrustStoreProviderChromeOS() = default; + +std::unique_ptr<net::SystemTrustStore> +SystemTrustStoreProviderChromeOS::CreateSystemTrustStore() { + if (user_slot_) { + auto user_slot_copy = + crypto::ScopedPK11Slot(PK11_ReferenceSlot(user_slot_.get())); + return net::CreateSslSystemTrustStoreNSSWithUserSlotRestriction( + std::move(user_slot_copy)); + } + + return net::CreateSslSystemTrustStoreNSSWithNoUserSlots(); +} + +} // namespace network
diff --git a/services/network/system_trust_store_provider_chromeos.h b/services/network/system_trust_store_provider_chromeos.h new file mode 100644 index 0000000..fd7514c3 --- /dev/null +++ b/services/network/system_trust_store_provider_chromeos.h
@@ -0,0 +1,50 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_NETWORK_SYSTEM_TRUST_STORE_PROVIDER_CHROMEOS_H_ +#define SERVICES_NETWORK_SYSTEM_TRUST_STORE_PROVIDER_CHROMEOS_H_ + +#include <certt.h> +#include <memory> + +#include "base/macros.h" +#include "crypto/scoped_nss_types.h" +#include "net/cert/cert_verify_proc_builtin.h" +#include "net/cert/nss_profile_filter_chromeos.h" + +namespace net { +class SystemTrustStore; +} + +namespace network { + +// A SystemTrustStoreProvider that supports creating SystemTrustStore instances +// which will only consider user-imported certificates trusted if they are on a +// specific NSS slot. +class SystemTrustStoreProviderChromeOS : public net::SystemTrustStoreProvider { + public: + // Creates a SystemTrustStoreProvider that will provide SystemTrustStore + // instances which will not allow trusting user-imported certififcates. + SystemTrustStoreProviderChromeOS(); + + // Creates a SystemTrustStoreProvider that will provide SystemTrustStore + // instances which will only consider user-imported certificates trusted if + // they are on |user_slot|. + explicit SystemTrustStoreProviderChromeOS(crypto::ScopedPK11Slot user_slot); + + ~SystemTrustStoreProviderChromeOS() override; + + // As SystemTrustStoreProvider states, this must be thread-safe and will be + // called concurrently from worker threads. + std::unique_ptr<net::SystemTrustStore> CreateSystemTrustStore() override; + + private: + const crypto::ScopedPK11Slot user_slot_; + + DISALLOW_COPY_AND_ASSIGN(SystemTrustStoreProviderChromeOS); +}; + +} // namespace network + +#endif // SERVICES_NETWORK_SYSTEM_TRUST_STORE_PROVIDER_CHROMEOS_H_
diff --git a/services/network/websocket.cc b/services/network/websocket.cc index 80ef1f1e..8f21251 100644 --- a/services/network/websocket.cc +++ b/services/network/websocket.cc
@@ -385,6 +385,10 @@ header_client_.set_connection_error_handler( base::BindOnce(&WebSocket::OnConnectionError, base::Unretained(this))); } + handshake_client_.set_connection_error_handler( + base::BindOnce(&WebSocket::OnConnectionError, base::Unretained(this))); + client_.set_connection_error_handler( + base::BindOnce(&WebSocket::OnConnectionError, base::Unretained(this))); if (delay_ > base::TimeDelta()) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE,
diff --git a/services/network/websocket_factory.cc b/services/network/websocket_factory.cc index 808a153..715e3b7a 100644 --- a/services/network/websocket_factory.cc +++ b/services/network/websocket_factory.cc
@@ -106,7 +106,7 @@ mojom::TrustedHeaderClientPtr header_client) { if (throttler_.HasTooManyPendingConnections(process_id)) { // Too many websockets! - handshake_client.ResetWithReason( + client.ResetWithReason( mojom::WebSocket::kInsufficientResources, "Error in connection establishment: net::ERR_INSUFFICIENT_RESOURCES"); return;
diff --git a/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc b/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc index dd785091..1776e66 100644 --- a/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc +++ b/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc
@@ -259,11 +259,9 @@ } if (filtering_enabled) { EXPECT_FALSE(packet->thread_descriptor().has_thread_name()); - } else { - EXPECT_EQ(kTestThread, packet->thread_descriptor().thread_name()); + EXPECT_EQ(perfetto::protos::ThreadDescriptor::CHROME_THREAD_MAIN, + packet->thread_descriptor().chrome_thread_type()); } - EXPECT_EQ(perfetto::protos::ThreadDescriptor::CHROME_THREAD_MAIN, - packet->thread_descriptor().chrome_thread_type()); last_timestamp_ = packet->thread_descriptor().reference_timestamp_us(); last_thread_time_ = packet->thread_descriptor().reference_thread_time_us();
diff --git a/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc b/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc index 9f2b7109..1235ae5f 100644 --- a/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc +++ b/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc
@@ -553,10 +553,15 @@ thread_name_ = maybe_new_name; thread_type_ = GetThreadType(maybe_new_name); } - if (!privacy_filtering_enabled_ && !thread_name_.empty()) { - thread_descriptor->set_thread_name(thread_name_.c_str()); + // TODO(ssid): Adding name and type to thread descriptor adds thread names + // from killed processes. The catapult trace importer can't handle different + // processes with same process ids. To workaround this issue, we do not emit + // name and type when filtering is enabled (when metadata is not emitted). + // Thread names will be emitted by trace log at metadata generation step when + // filtering is not enabled. See crbug/978093. + if (privacy_filtering_enabled_) { + thread_descriptor->set_chrome_thread_type(thread_type_); } - thread_descriptor->set_chrome_thread_type(thread_type_); if (explicit_timestamp || !trace_event) { // Don't use a user-provided timestamp as a reference timestamp.
diff --git a/testing/buildbot/README.md b/testing/buildbot/README.md index 516f2260..888eb5f 100644 --- a/testing/buildbot/README.md +++ b/testing/buildbot/README.md
@@ -269,11 +269,23 @@ bot. This can be used to add additional command line arguments, Swarming parameters, etc. -* `key_removals`: a dictionary mapping a bot's name to a list of keys which - should be removed from the test's specification on that bot. Note that by - design, this feature *can not* be used to remove Swarming dictionary entries. - This feature was mainly used to match the previously handwritten JSON files, - should not be used in the future, and should ideally be removed. +* `replacements`: a dictionary mapping bot names to a dictionaries of field + names to dictionaries of key/value pairs to replace. If the given value is + `None`, then the key will simply be removed. For example: + ``` + 'foo_tests': { + 'Foo Tester': { + 'args': { + '--some-flag': None, + '--another-flag': 'some-value', + }, + }, + } + ``` + would remove the `--some-flag` and replace whatever value `--another-flag` was + set to with `some-value`. Note that passing `None` only works if the flag + being removed either has no value or is in the `--key=value` format. It does + not work if the key and value are two separate entries in the args list. ### Order of application of test changes
diff --git a/testing/buildbot/filters/navigation_loader_on_ui_browser_tests.filter b/testing/buildbot/filters/navigation_loader_on_ui_browser_tests.filter index 859646ca..30cc29219 100644 --- a/testing/buildbot/filters/navigation_loader_on_ui_browser_tests.filter +++ b/testing/buildbot/filters/navigation_loader_on_ui_browser_tests.filter
@@ -1,248 +1,21 @@ # These tests currently fail when run with --enable-features=NavigationLoaderOnUI # http://crbug.com/824858 --AppBannerManagerBrowserTest.ListedRelatedChromeAppInstalled --AppBannerManagerBrowserTest.PreferRelatedAppUnknown --AppBannerManagerBrowserTest.PreferRelatedChromeApp --AppBannerManagerBrowserTest.WebAppBannerCancelled --AppBannerManagerBrowserTest.WebAppBannerInsufficientEngagement --AppBannerManagerBrowserTest.WebAppBannerNeedsEngagement --AppBannerManagerBrowserTest.WebAppBannerNoTypeInManifest --AppBannerManagerBrowserTest.WebAppBannerNoTypeInManifestCapsExtension --AppBannerManagerBrowserTest.WebAppBannerNotCreated --AppBannerManagerBrowserTest.WebAppBannerPromptWithGesture --AppBannerManagerBrowserTest.WebAppBannerReprompt --AppBannerManagerDesktopBrowserTest.DestroyWebContents --AppBannerManagerDesktopBrowserTest.InstallPromptAfterUserMenuInstall --AppBannerManagerDesktopBrowserTest.InstallPromptAfterUserOmniboxInstall --AppBannerManagerDesktopBrowserTest.WebAppBannerFiresAppInstalled --AppBannerManagerDesktopBrowserTest.WebAppBannerResolvesUserChoice --BackgroundFetchBrowserTest.AbortFromUI --BackgroundFetchBrowserTest.ClickEventIsDispatched --BackgroundFetchBrowserTest.DownloadService_Acceptance --BackgroundFetchBrowserTest.FetchCanBePausedAndResumed --BackgroundFetchBrowserTest.FetchFromChildFrameWithAsk --BackgroundFetchBrowserTest.FetchFromChildFrameWithMissingPermissions --BackgroundFetchBrowserTest.FetchFromChildFrameWithPermissions --BackgroundFetchBrowserTest.FetchFromServiceWorker --BackgroundFetchBrowserTest.FetchFromServiceWorkerWithAsk --BackgroundFetchBrowserTest.FetchRejectedWithoutPermission --BackgroundFetchBrowserTest.FetchesRunToCompletionAndUpdateTitle_Failed --BackgroundFetchBrowserTest.FetchesRunToCompletionAndUpdateTitle_Fetched --BackgroundFetchBrowserTest.FetchesRunToCompletion_Upload --BackgroundFetchBrowserTest.OfflineItemCollection_IncognitoPropagated --BackgroundFetchBrowserTest.OfflineItemCollection_SingleFileMetadata --BackgroundFetchBrowserTest.OfflineItemCollection_VerifyIconReceived --BackgroundFetchBrowserTest.OfflineItemCollection_VerifyResourceDownloadedWhenCorrectDownloadTotalSpecified --BackgroundFetchBrowserTest.OfflineItemCollection_VerifyResourceDownloadedWhenDownloadTotalLargerThanActualSize --BackgroundFetchBrowserTest.OfflineItemCollection_VerifyResourceDownloadedWhenDownloadTotalSmallerThanActualSize --BackgroundFetchBrowserTest.RecordBackgroundFetchUkmEvent --BackgroundSyncBrowserTest.VerifyShutdownBehavior --BookmarkAppHelperTest.CreateWindowedPWAIntoAppWindow --BookmarkAppTest.EngagementHistogramDefaultApp --BrowsingDataRemoverBrowserTest.SessionOnlyStorageRemoved --BrowsingDataRemoverBrowserTest.StorageRemovedFromDisk --BrowsingDataRemoverBrowserTestP.ServiceWorkerDeletion/0 --BrowsingDataRemoverBrowserTestP.ServiceWorkerDeletion/1 --BrowsingDataRemoverBrowserTestP.ServiceWorkerIncognitoDeletion/0 --BrowsingDataRemoverBrowserTestP.ServiceWorkerIncognitoDeletion/1 --ChromeDoNotTrackTest.FetchFromServiceWorker -ChromeDoNotTrackTest.FetchFromSharedWorker --ChromeServiceWorkerFetchPPAPITest.NotInterceptedByServiceWorker --ChromeServiceWorkerLinkFetchTest.FaviconOtherOrigin --ChromeServiceWorkerLinkFetchTest.FaviconSameOrigin --ChromeServiceWorkerLinkFetchTest.ManifestOtherOrigin --ChromeServiceWorkerLinkFetchTest.ManifestOtherOriginUseCredentials --ChromeServiceWorkerLinkFetchTest.ManifestSameOrigin --ChromeServiceWorkerLinkFetchTest.ManifestSameOriginUseCredentials --ChromeServiceWorkerNavigationHintTest.AlreadyRunning --ChromeServiceWorkerNavigationHintTest.NoFetchHandler --ChromeServiceWorkerNavigationHintTest.Started --ChromeServiceWorkerNavigationPreloadTest.SubFrameWithThirdPartyBlocking --ChromeServiceWorkerNavigationPreloadTest.TopFrameWithThirdPartyBlocking -ChromeServiceWorkerTest.FallbackMainResourceRequestWhenJSDisabled --ChromeServiceWorkerTest.StartServiceWorkerAndDispatchMessage --ChromeServiceWorkerTest.StartServiceWorkerForLongRunningMessage -ChromeWorkerBrowserTest.SharedWorkerScriptFetchWithThirdPartyBlocking -ChromeWorkerBrowserTest.SharedWorkerScriptFetchWithoutThirdPartyBlocking --ContentSettingsWorkerModulesBrowserTest.CookieStore --CrossOriginReadBlockingExtensionTest.FromServiceWorker_NoSniffXml --DataSaverForWorkerBrowserTest.FetchFromServiceWorker/0 --DataSaverForWorkerBrowserTest.FetchFromServiceWorker/1 --DataSaverForWorkerBrowserTest.FetchFromServiceWorkerControlledPage_NoFetchHandler/0 --DataSaverForWorkerBrowserTest.FetchFromServiceWorkerControlledPage_NoFetchHandler/1 --DataSaverForWorkerBrowserTest.FetchFromServiceWorkerControlledPage_PassThrough/0 --DataSaverForWorkerBrowserTest.FetchFromServiceWorkerControlledPage_PassThrough/1 --DataSaverForWorkerBrowserTest.FetchFromServiceWorkerControlledPage_RespondWithFetch/0 --DataSaverForWorkerBrowserTest.FetchFromServiceWorkerControlledPage_RespondWithFetch/1 -DataSaverForWorkerBrowserTest.FetchFromSharedWorker/0 -DataSaverForWorkerBrowserTest.FetchFromSharedWorker/1 --DataSaverForWorkerBrowserTest.ServiceWorker_Register/0 --DataSaverForWorkerBrowserTest.ServiceWorker_Register/1 --DataSaverForWorkerBrowserTest.ServiceWorker_Update/0 --DataSaverForWorkerBrowserTest.ServiceWorker_Update/1 -DataSaverForWorkerBrowserTest.SharedWorker/0 -DataSaverForWorkerBrowserTest.SharedWorker/1 --DataSaverForWorkerBrowserTest.SharedWorker_Off --DataSaverForWorkerBrowserTest.SharedWorker_On -DebuggerExtensionApiTest.Debugger --ErrorCases/PaymentHandlerChangePaymentMethodTest.Test/0 --ErrorCases/PaymentHandlerChangePaymentMethodTest.Test/1 --ErrorCases/PaymentHandlerChangePaymentMethodTest.Test/2 --ErrorCases/PaymentHandlerChangePaymentMethodTest.Test/3 -ExtensionApiTest.SharedWorker -ExtensionApiTest.SharedWorker_ControlledByServiceWorker -ExtensionApiTestWithSwitch.ExtensionDebugger --ExtensionFetchTest.HostCanFetchWebAccessibleExtensionResource_FetchFromServiceWorker --ExtensionWebRequestApiTest.ServiceWorkerFallback --ExtensionWebRequestApiTest.ServiceWorkerFetch --ExtensionWebRequestApiTest.ServiceWorkerNavigationPreload --ExtensionWebRequestApiTest.ServiceWorkerNoFetchHandler --HostedAppPWAOnlyTest.InstallInstallableSite/0 --HostedAppPWAOnlyTest.InstallToShelfContainsAppName/0 --HostedAppPWAOnlyTest.ShortcutMenuOptionsForInstallablePWA/0 -InspectUITest.SharedWorker --InstallManagerBookmarkAppDialogTest.CreateWindowedPWA_FromInstallableSite --InstallReplacementWebAppApiTest.InstallableWebApp --InstallableManagerBrowserTest.CheckChangeInIconDimensions --InstallableManagerBrowserTest.CheckDataUrlIcon --InstallableManagerBrowserTest.CheckLazyServiceWorkerNoFetchHandlerFails --InstallableManagerBrowserTest.CheckLazyServiceWorkerPassesWhenWaiting --InstallableManagerBrowserTest.CheckNavigationWithoutRunning --InstallableManagerBrowserTest.CheckPageWithNestedServiceWorkerCanBeInstalled --InstallableManagerBrowserTest.CheckPageWithNoServiceWorkerFetchHandler --InstallableManagerBrowserTest.CheckServiceWorkerErrorIsNotCached --InstallableManagerBrowserTest.CheckWebapp --InstallableManagerBrowserTest.GetAllErrorsNoErrors --InstallableManagerBrowserTest.ManifestUrlChangeFlushesState --MerchantResponse/PaymentHandlerChangePaymentMethodTest.Test/0 --MerchantResponse/PaymentHandlerChangePaymentMethodTest.Test/1 --NoMerchantResponse/PaymentHandlerChangePaymentMethodTest.Test/0 --NoMerchantResponse/PaymentHandlerChangePaymentMethodTest.Test/1 --NoStatePrefetchBrowserTest.ServiceWorkerIntercept --NotificationPermissionContextApiTest.Denied --NotificationPermissionContextApiTest.Granted --PDFExtensionTest.ServiceWorkerInterception --PDFExtensionTest.ServiceWorkerNetworkFallback --PDFExtensionTest.ServiceWorkerNoFetchHandler --PaymentRequestPaymentAppTest.BlockAlicePay --PaymentRequestPaymentAppTest.CanNotPayWithBobPay --PaymentRequestPaymentAppTest.NotSupportedError --PaymentRequestPaymentAppTest.PayWithAlicePay --PaymentRequestPaymentAppTest.PayWithAlicePayIncognito --PaymentRequestPaymentAppTest.PayWithBasicCard --PaymentRequestPaymentAppTest.SkipUIDisabledWithMultipleAcceptedMethods --PaymentRequestPaymentAppTest.SkipUIDisabledWithRequestedPayerEmail --PaymentRequestPaymentAppTest.SkipUIEnabledWithBobPay --PaymentRequestShowPromiseTest.CannotShipError --PaymentRequestShowPromiseTest.DigitalGoods --PaymentRequestShowPromiseTest.ResolveWithEmptyDictionary --PaymentRequestShowPromiseTest.ResolveWithEmptyListsOfItems --PaymentRequestShowPromiseTest.SingleOptionShipping --PaymentRequestShowPromiseTest.SingleOptionShippingWithUpdate --PaymentRequestShowPromiseTest.SkipUI --PendingBookmarkAppManagerBrowserTest.AlwaysUpdate --PendingBookmarkAppManagerBrowserTest.ForceReinstall --PushMessagingBrowserTest.AppHandlerOnlyIfSubscribed --PushMessagingBrowserTest.AutomaticUnsubscriptionFollowsContentSettingRules --PushMessagingBrowserTest.DenyNotificationsPermissionUnsubscribes --PushMessagingBrowserTest.DenyPushPermissionUnsubscribes --PushMessagingBrowserTest.EncryptionKeyUniqueness --PushMessagingBrowserTest.GlobalResetNotificationsPermissionUnsubscribes --PushMessagingBrowserTest.GlobalResetPushPermissionUnsubscribes --PushMessagingBrowserTest.GrantAlreadyGrantedPermissionDoesNotUnsubscribe --PushMessagingBrowserTest.InvalidGetSubscriptionUnsubscribes --PushMessagingBrowserTest.LegacyPushEvent --PushMessagingBrowserTest.LocalResetNotificationsPermissionUnsubscribes --PushMessagingBrowserTest.LocalResetPushPermissionUnsubscribes --PushMessagingBrowserTest.NoSubscription --PushMessagingBrowserTest.PermissionStateSaysDenied --PushMessagingBrowserTest.PermissionStateSaysGranted --PushMessagingBrowserTest.PermissionStateSaysPrompt --PushMessagingBrowserTest.PushEventAllowSilentPushCommandLineFlag --PushMessagingBrowserTest.PushEventEnforcesUserVisibleNotification --PushMessagingBrowserTest.PushEventEnforcesUserVisibleNotificationAfterQueue --PushMessagingBrowserTest.PushEventIgnoresScheduledNotificationsForEnforcement --PushMessagingBrowserTest.PushEventNotificationWithoutEventWaitUntil --PushMessagingBrowserTest.PushEventOnShutdown --PushMessagingBrowserTest.PushEventSuccess --PushMessagingBrowserTest.PushEventWithoutPayload --PushMessagingBrowserTest.PushEventWithoutPermission --PushMessagingBrowserTest.RegisterFailureEmptyPushSubscriptionOptions --PushMessagingBrowserTest.ResubscribeWithMismatchedKey --PushMessagingBrowserTest.ResubscribeWithoutKeyAfterSubscribingFromDocumentWithNumber --PushMessagingBrowserTest.ResubscribeWithoutKeyAfterSubscribingFromDocumentWithP256Key --PushMessagingBrowserTest.ResubscribeWithoutKeyAfterSubscribingFromWorkerWithNumber --PushMessagingBrowserTest.ResubscribeWithoutKeyAfterSubscribingFromWorkerWithP256Key --PushMessagingBrowserTest.ResubscribeWithoutKeyAfterSubscribingWithKeyInManifest --PushMessagingBrowserTest.ServiceWorkerDatabaseDeletionUnsubscribes --PushMessagingBrowserTest.SubscribeFailureNoManifest --PushMessagingBrowserTest.SubscribeFailureNoSenderId --PushMessagingBrowserTest.SubscribeFailureNotificationsBlocked --PushMessagingBrowserTest.SubscribePersisted --PushMessagingBrowserTest.SubscribeSuccessNotificationsGranted --PushMessagingBrowserTest.SubscribeSuccessNotificationsGrantedWithBase64URLKey --PushMessagingBrowserTest.SubscribeSuccessNotificationsPrompt --PushMessagingBrowserTest.SubscribeWithInvalidation --PushMessagingBrowserTest.SubscribeWithoutKeySuccessNotificationsGranted --PushMessagingBrowserTest.SubscribeWorker --PushMessagingBrowserTest.SubscribeWorkerWithBase64URLEncodedString --PushMessagingBrowserTest.UnregisteringServiceWorkerUnsubscribes --PushMessagingBrowserTest.UnsubscribeOffline --PushMessagingBrowserTest.UnsubscribeSuccess --PushMessagingIncognitoBrowserTest.IncognitoGetSubscriptionDoesNotHang --PwaInstallViewBrowserTest.AnimationSuppression --PwaInstallViewBrowserTest.BouncedInstallIgnored --PwaInstallViewBrowserTest.BouncedInstallMeasured --PwaInstallViewBrowserTest.IconVisibilityAfterInstallabilityCheck --PwaInstallViewBrowserTest.IconVisibilityAfterTabSwitching --PwaInstallViewBrowserTest.LabelAnimation --PwaInstallViewBrowserTest.ListedRelatedChromeAppInstalled --PwaInstallViewBrowserTest.NavigateToDifferentEmptyScope --PwaInstallViewBrowserTest.NavigateToDifferentScope --PwaInstallViewBrowserTest.NavigateToSameScope --PwaInstallViewBrowserTest.NavigateToSameScopeNonInstallable --PwaInstallViewBrowserTest.PreferRelatedAppUnknown --PwaInstallViewBrowserTest.PreferRelatedChromeApp --PwaInstallViewBrowserTest.TextContrast --ServiceWorkerAppTest.RegisterAndPostMessage --ServiceWorkerBackgroundSyncTest.Sync --ServiceWorkerBasedBackgroundTest.WorkerRefCount --ServiceWorkerPaymentAppFactoryBrowserTest.AllOringsSupported --ServiceWorkerPaymentAppFactoryBrowserTest.BasicCard --ServiceWorkerPaymentAppFactoryBrowserTest.NotSupportedOrigin --ServiceWorkerPaymentAppFactoryBrowserTest.OwnOrigin --ServiceWorkerPaymentAppFactoryBrowserTest.SupportedOrigin --ServiceWorkerPaymentAppFactoryBrowserTest.TwoAppsDifferentMethods --ServiceWorkerPaymentAppFactoryBrowserTest.TwoAppsSameMethod --ServiceWorkerPaymentAppFactoryBrowserTest.UnknownMethod --ServiceWorkerPushMessagingTest.OnPush --ServiceWorkerTaskProviderBrowserTest.CreateTasksForMultiProfiles --ServiceWorkerTaskProviderBrowserTest.CreateTasksForOffTheRecordProfile --ServiceWorkerTaskProviderBrowserTest.CreateTasksForSingleProfile --ServiceWorkerTest.BackgroundPageIsWokenIfAsleep --ServiceWorkerTest.BackgroundPagePostsMessageToServiceWorker --ServiceWorkerTest.FetchArbitraryPaths --ServiceWorkerTest.FetchExtensionResourceFromServiceWorker --ServiceWorkerTest.FetchFromContentScriptShouldNotGoToServiceWorkerOfPage --ServiceWorkerTest.GetBackgroundClientFailsWithNoBackgroundPage -ServiceWorkerTest.MimeHandlerView --ServiceWorkerTest.NotificationAPI --ServiceWorkerTest.OnBeforeRequest --ServiceWorkerTest.RegisterSucceeds --ServiceWorkerTest.SWServedBackgroundPage --ServiceWorkerTest.SWServedBackgroundPageReceivesEvent --ServiceWorkerTest.ServiceWorkerPostsMessageToBackgroundClient --ServiceWorkerTest.ServiceWorkerSuspensionOnExtensionUnload --ServiceWorkerTest.UpdateRefreshesServiceWorker --ServiceWorkerTest.VerifyNoApiBindings --ServiceWorkerTest.WebAccessibleResourcesFetch --ServiceWorkerTest.WebAccessibleResourcesIframeSrc -SitePerProcessDebuggerExtensionApiTest.Debugger --VariationsHttpHeadersBrowserTest.ServiceWorkerNavigationPreload --VariationsHttpHeadersBrowserTest.ServiceWorkerNetworkFallback --VariationsHttpHeadersBrowserTest.ServiceWorkerRespondWithFetch --VariationsHttpHeadersBrowserTest.ServiceWorkerScript -VariationsHttpHeadersBrowserTest.SharedWorkerScript -WebViewTest.FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsAllow -WebViewTest.FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsDefaultAllow
diff --git a/testing/buildbot/filters/navigation_loader_on_ui_content_browsertests.filter b/testing/buildbot/filters/navigation_loader_on_ui_content_browsertests.filter index fed92303..7b4dabc8 100644 --- a/testing/buildbot/filters/navigation_loader_on_ui_content_browsertests.filter +++ b/testing/buildbot/filters/navigation_loader_on_ui_content_browsertests.filter
@@ -11,141 +11,7 @@ # http://crbug.com/824858 -AcceptHeaderTest.Check --BackgroundSyncBrowserTest.FiringSyncEventDeletedWhenClearingSiteData --BackgroundSyncBrowserTest.GetRegistrationsFromServiceWorker --BackgroundSyncBrowserTest.GetTags --BackgroundSyncBrowserTest.HasTagFromServiceWorker --BackgroundSyncBrowserTest.Incognito --BackgroundSyncBrowserTest.RegisterFromControlledDocument --BackgroundSyncBrowserTest.RegisterFromIFrameWithMainFrameHost --BackgroundSyncBrowserTest.RegisterFromServiceWorker --BackgroundSyncBrowserTest.RegisterFromServiceWorkerWithoutMainFrameHost --BackgroundSyncBrowserTest.RegisterFromUncontrolledDocument --BackgroundSyncBrowserTest.RegistrationDelaysForNetwork --BackgroundSyncBrowserTest.SyncRegistrationDeletedWhenClearingSiteData --BackgroundSyncBrowserTest.SyncRegistrationFromSWDeletedWhenClearingSiteData --BackgroundSyncBrowserTest.SyncRegistrationsDeletedWhenClearingSiteData --BackgroundSyncBrowserTest.WaitUntil --BackgroundSyncBrowserTest.WaitUntilReject --ClearSiteDataHandlerBrowserTest.ClearSiteDataDuringServiceWorkerInstall --ClearSiteDataHandlerBrowserTest.ClearSiteDataDuringServiceWorkerUpdate --ClearSiteDataHandlerBrowserTest.ServiceWorker --ClearSiteDataHandlerBrowserTest.StorageServiceWorkersIntegrationTest --CrossSiteDocumentBlockingServiceWorkerTest.NetworkToServiceWorkerResponse --DoNotTrackTest.FetchFromServiceWorker --DoNotTrackTest.FetchFromServiceWorkerControlledPage_NoFetchHandler --DoNotTrackTest.FetchFromServiceWorkerControlledPage_PassThrough --DoNotTrackTest.FetchFromServiceWorkerControlledPage_RespondWithFetch --DoNotTrackTest.ServiceWorker_Register --DoNotTrackTest.ServiceWorker_Update --DownloadContentTest.DownloadOctetStream_OctetStreamServiceWorker --DownloadContentTest.DownloadOctetStream_PassThroughServiceWorker --DownloadContentTest.DownloadOctetStream_RespondWithFetchServiceWorker --NetworkServiceRestartBrowserTest.FetchFromServiceWorkerControlledPage_NoFetchHandler --NetworkServiceRestartBrowserTest.FetchFromServiceWorkerControlledPage_PassThrough --NetworkServiceRestartBrowserTest.FetchFromServiceWorkerControlledPage_RespondWithFetch --NetworkServiceRestartBrowserTest.ServiceWorkerFetch --PaymentAppBrowserTest.AbortPayment --PaymentAppBrowserTest.AbortPaymentWithInvalidRegistrationId --PaymentAppBrowserTest.CanMakePayment --PaymentAppBrowserTest.PaymentAppInvocation --PaymentAppBrowserTest.PaymentAppInvocationAndFailed --PaymentAppBrowserTest.PaymentAppOpenWindowFailed -ReloadCacheControlBrowserTest.BypassingReload_ControlledByServiceWorker --ReloadCacheControlBrowserTest.NormalReload_ControlledByServiceWorker --ServiceWorkerBasicAuthTest.BasicAuthPromptFetchMainResourceMainFrame --ServiceWorkerBasicAuthTest.BasicAuthPromptFetchMainResourceSubframe --ServiceWorkerBasicAuthTest.BasicAuthPromptFetchSubResource --ServiceWorkerBrowserTest.FetchPageWithSaveData --ServiceWorkerBrowserTest.GetAllServiceWorkerRunningInfos --ServiceWorkerBrowserTest.GetServiceWorkerRunningInfo --ServiceWorkerBrowserTest.ImportsBustMemcache --ServiceWorkerBrowserTest.Reload --ServiceWorkerBrowserTest.RequestOrigin --ServiceWorkerBrowserTest.ResponseFromHTTPSServiceWorkerIsMarkedAsSecure --ServiceWorkerBrowserTest.ResponseFromHTTPServiceWorkerIsNotMarkedAsSecure --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.FetchPageWithSaveData/0 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.FetchPageWithSaveData/1 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.GetAllServiceWorkerRunningInfos/0 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.GetAllServiceWorkerRunningInfos/1 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.GetServiceWorkerRunningInfo/0 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.GetServiceWorkerRunningInfo/1 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.ImportsBustMemcache/0 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.ImportsBustMemcache/1 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.Reload/0 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.Reload/1 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.RequestOrigin/0 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.RequestOrigin/1 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.ResponseFromHTTPSServiceWorkerIsMarkedAsSecure/0 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.ResponseFromHTTPSServiceWorkerIsMarkedAsSecure/1 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.ResponseFromHTTPServiceWorkerIsNotMarkedAsSecure/0 --ServiceWorkerBrowserTestOnMainThreadFetch/ServiceWorkerBrowserTest.ResponseFromHTTPServiceWorkerIsNotMarkedAsSecure/1 --ServiceWorkerClientsApiBrowserTest.Navigate --ServiceWorkerClientsApiBrowserTest.NavigateDisallowedUrl --ServiceWorkerClientsApiBrowserTest.NavigateDuringBrowserNavigation --ServiceWorkerClientsApiBrowserTest.OpenWindow --ServiceWorkerClientsApiBrowserTest.OpenWindowDisallowedUrl --ServiceWorkerCodeCacheStrategyDontGenerateTest.DontGenerate --ServiceWorkerCodeCacheStrategyDontGenerateTestOnMainThreadFetch/ServiceWorkerCodeCacheStrategyDontGenerateTest.DontGenerate/0 --ServiceWorkerCodeCacheStrategyDontGenerateTestOnMainThreadFetch/ServiceWorkerCodeCacheStrategyDontGenerateTest.DontGenerate/1 --ServiceWorkerCodeCacheStrategyIdleTaskTest.CacheScriptTwice --ServiceWorkerCodeCacheStrategyIdleTaskTest.GenerateInIdleTask --ServiceWorkerCodeCacheStrategyIdleTaskTestOnMainThreadFetch/ServiceWorkerCodeCacheStrategyIdleTaskTest.CacheScriptTwice/0 --ServiceWorkerCodeCacheStrategyIdleTaskTestOnMainThreadFetch/ServiceWorkerCodeCacheStrategyIdleTaskTest.CacheScriptTwice/1 --ServiceWorkerCodeCacheStrategyIdleTaskTestOnMainThreadFetch/ServiceWorkerCodeCacheStrategyIdleTaskTest.GenerateInIdleTask/0 --ServiceWorkerCodeCacheStrategyIdleTaskTestOnMainThreadFetch/ServiceWorkerCodeCacheStrategyIdleTaskTest.GenerateInIdleTask/1 --ServiceWorkerCodeCacheStrategyInstallEventTest.GenerateInInstallEvent --ServiceWorkerCodeCacheStrategyInstallEventTestOnMainThreadFetch/ServiceWorkerCodeCacheStrategyInstallEventTest.GenerateInInstallEvent/0 --ServiceWorkerCodeCacheStrategyInstallEventTestOnMainThreadFetch/ServiceWorkerCodeCacheStrategyInstallEventTest.GenerateInInstallEvent/1 --ServiceWorkerDisableWebSecurityTest.GetRegistrationNoCrash --ServiceWorkerDisableWebSecurityTest.RegisterNoCrash --ServiceWorkerDisableWebSecurityTest.UnregisterNoCrash --ServiceWorkerDisableWebSecurityTest.UpdateNoCrash --ServiceWorkerDisableWebSecurityTestOnMainThreadFetch/ServiceWorkerDisableWebSecurityTest.GetRegistrationNoCrash/0 --ServiceWorkerDisableWebSecurityTestOnMainThreadFetch/ServiceWorkerDisableWebSecurityTest.GetRegistrationNoCrash/1 --ServiceWorkerDisableWebSecurityTestOnMainThreadFetch/ServiceWorkerDisableWebSecurityTest.RegisterNoCrash/0 --ServiceWorkerDisableWebSecurityTestOnMainThreadFetch/ServiceWorkerDisableWebSecurityTest.RegisterNoCrash/1 --ServiceWorkerDisableWebSecurityTestOnMainThreadFetch/ServiceWorkerDisableWebSecurityTest.UnregisterNoCrash/0 --ServiceWorkerDisableWebSecurityTestOnMainThreadFetch/ServiceWorkerDisableWebSecurityTest.UnregisterNoCrash/1 --ServiceWorkerDisableWebSecurityTestOnMainThreadFetch/ServiceWorkerDisableWebSecurityTest.UpdateNoCrash/0 --ServiceWorkerDisableWebSecurityTestOnMainThreadFetch/ServiceWorkerDisableWebSecurityTest.UpdateNoCrash/1 --ServiceWorkerFileUploadTest.AsBlob --ServiceWorkerFileUploadTest.AsFormData --ServiceWorkerFileUploadTest.AsFormData_CrossOrigin --ServiceWorkerFileUploadTest.AsText --ServiceWorkerFileUploadTest.NetworkFallback --ServiceWorkerFileUploadTest.NetworkFallback_CrossOrigin --ServiceWorkerNavigationPreloadTest.InvalidRedirect_InvalidLocation --ServiceWorkerNavigationPreloadTest.InvalidRedirect_MultiLocation --ServiceWorkerNavigationPreloadTest.NetworkError --ServiceWorkerNavigationPreloadTest.NotEnabled --ServiceWorkerNavigationPreloadTest.PreloadHeadersCustom --ServiceWorkerNavigationPreloadTest.PreloadHeadersSimple --ServiceWorkerNavigationPreloadTest.RespondWithNavigationPreload --ServiceWorkerNavigationPreloadTest.SetHeaderValue --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.InvalidRedirect_InvalidLocation/0 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.InvalidRedirect_InvalidLocation/1 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.InvalidRedirect_MultiLocation/0 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.InvalidRedirect_MultiLocation/1 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.NetworkError/0 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.NetworkError/1 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.NotEnabled/0 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.NotEnabled/1 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.PreloadHeadersCustom/0 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.PreloadHeadersCustom/1 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.PreloadHeadersSimple/0 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.PreloadHeadersSimple/1 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.RespondWithNavigationPreload/0 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.RespondWithNavigationPreload/1 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.SetHeaderValue/0 --ServiceWorkerNavigationPreloadTestOnMainThreadFetch/ServiceWorkerNavigationPreloadTest.SetHeaderValue/1 --ServiceWorkerNoBestEffortTasksTest.RegisterServiceWorker --ServiceWorkerTlsTest.ClientAuthFetchMainResource --ServiceWorkerTlsTest.ClientAuthFetchSubResource --ServiceWorkerURLLoaderThrottleTest.FetchEventForNavigationHasThrottledRequest --ServiceWorkerURLLoaderThrottleTest.NavigationHasThrottledRequestHeadersAfterNetworkFallback --ServiceWorkerURLLoaderThrottleTest.NavigationPreloadHasThrottledRequestHeaders --ServiceWorkerURLLoaderThrottleTest.RedirectOccursBeforeFetchEvent -ServiceWorkerURLLoaderThrottleTestOnMainThreadFetch/ServiceWorkerURLLoaderThrottleTest.FetchEventForNavigationHasThrottledRequest/0 -ServiceWorkerURLLoaderThrottleTestOnMainThreadFetch/ServiceWorkerURLLoaderThrottleTest.FetchEventForNavigationHasThrottledRequest/1 -ServiceWorkerURLLoaderThrottleTestOnMainThreadFetch/ServiceWorkerURLLoaderThrottleTest.NavigationHasThrottledRequestHeadersAfterNetworkFallback/0 @@ -154,9 +20,6 @@ -ServiceWorkerURLLoaderThrottleTestOnMainThreadFetch/ServiceWorkerURLLoaderThrottleTest.NavigationPreloadHasThrottledRequestHeaders/1 -ServiceWorkerURLLoaderThrottleTestOnMainThreadFetch/ServiceWorkerURLLoaderThrottleTest.RedirectOccursBeforeFetchEvent/0 -ServiceWorkerURLLoaderThrottleTestOnMainThreadFetch/ServiceWorkerURLLoaderThrottleTest.RedirectOccursBeforeFetchEvent/1 --ServiceWorkerV8CodeCacheForCacheStorageTest.V8CacheOnCacheStorage --ServiceWorkerV8CodeCacheForCacheStorageTestOnMainThreadFetch/ServiceWorkerV8CodeCacheForCacheStorageTest.V8CacheOnCacheStorage/0 --ServiceWorkerV8CodeCacheForCacheStorageTestOnMainThreadFetch/ServiceWorkerV8CodeCacheForCacheStorageTest.V8CacheOnCacheStorage/1 # http://crbug.com/824854 -PrefetchBrowserTest/PrefetchBrowserTest.CrossOriginSignedExchangeWithPreload/3
diff --git a/testing/buildbot/generate_buildbot_json.py b/testing/buildbot/generate_buildbot_json.py index 4b31b82..61efc004 100755 --- a/testing/buildbot/generate_buildbot_json.py +++ b/testing/buildbot/generate_buildbot_json.py
@@ -279,6 +279,12 @@ return None return exception.get('modifications', {}).get(tester_name) + def get_test_replacements(self, test, test_name, tester_name): + exception = self.get_exception_for_test(test_name, test) + if not exception: + return None + return exception.get('replacements', {}).get(tester_name) + def merge_command_line_args(self, arr, prefix, splitter): prefix_len = len(prefix) idx = 0 @@ -447,9 +453,44 @@ for d in test['swarming'].get('dimension_sets', []): if d.get('os') == 'Android' and not d.get('device_os_type'): d['device_os_type'] = 'userdebug' + self.replace_test_args(test, test_name, tester_name) return test + def replace_test_args(self, test, test_name, tester_name): + replacements = self.get_test_replacements( + test, test_name, tester_name) or {} + valid_replacement_keys = ['args', 'non_precommit_args', 'precommit_args'] + for key, replacement_dict in replacements.iteritems(): + if key not in valid_replacement_keys: + raise BBGenErr( + 'Given replacement key %s for %s on %s is not in the list of valid ' + 'keys %s' % (key, test_name, tester_name, valid_replacement_keys)) + for replacement_key, replacement_val in replacement_dict.iteritems(): + found_key = False + for i, test_key in enumerate(test.get(key, [])): + # Handle both the key/value being replaced being defined as two + # separate items or as key=value. + if test_key == replacement_key: + found_key = True + # Handle flags without values. + if replacement_val == None: + del test[key][i] + else: + test[key][i+1] = replacement_val + break + elif test_key.startswith(replacement_key + '='): + found_key = True + if replacement_val == None: + del test[key][i] + else: + test[key][i] = '%s=%s' % (replacement_key, replacement_val) + break + if not found_key: + raise BBGenErr('Could not find %s in existing list of values for key ' + '%s in %s on %s' % (replacement_key, key, test_name, + tester_name)) + def add_common_test_properties(self, test, tester_config): if tester_config.get('use_multi_dimension_trigger_script'): # Assumes update_and_cleanup_test has already been called, so the
diff --git a/testing/buildbot/generate_buildbot_json_unittest.py b/testing/buildbot/generate_buildbot_json_unittest.py index a148b2e..7640bbb 100755 --- a/testing/buildbot/generate_buildbot_json_unittest.py +++ b/testing/buildbot/generate_buildbot_json_unittest.py
@@ -3852,5 +3852,231 @@ self.assertEqual(cm.exception.code, 1) self.assertTrue(fbb.printed_lines) + +FOO_TEST_SUITE_WITH_ENABLE_FEATURES_SEPARATE_ENTRIES = """\ +{ + 'basic_suites': { + 'foo_tests': { + 'foo_test': { + 'args': [ + '--enable-features', + 'Foo,Bar', + ], + }, + }, + }, +} +""" + + +FOO_TEST_REPLACEMENTS_REMOVE_NO_VALUE = """\ +{ + 'foo_test': { + 'replacements': { + 'Fake Tester': { + 'args': { + '--c_arg': None, + }, + }, + }, + }, +} +""" + + +FOO_TEST_REPLACEMENTS_REMOVE_VALUE = """\ +{ + 'foo_test': { + 'replacements': { + 'Fake Tester': { + 'args': { + '--enable-features': None, + }, + }, + }, + }, +} +""" + + +FOO_TEST_REPLACEMENTS_REPLACE_VALUE = """\ +{ + 'foo_test': { + 'replacements': { + 'Fake Tester': { + 'args': { + '--enable-features': 'Bar,Baz', + }, + }, + }, + }, +} +""" + + +FOO_TEST_REPLACEMENTS_INVALID_KEY = """\ +{ + 'foo_test': { + 'replacements': { + 'Fake Tester': { + 'invalid': { + '--enable-features': 'Bar,Baz', + }, + }, + }, + }, +} +""" + + +REPLACEMENTS_REMOVE_OUTPUT = """\ +{ + "AAAAA1 AUTOGENERATED FILE DO NOT EDIT": {}, + "AAAAA2 See generate_buildbot_json.py to make changes": {}, + "Fake Tester": { + "gtest_tests": [ + { + "args": [], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "kvm": "1" + } + ] + }, + "test": "foo_test" + } + ] + } +} +""" + +REPLACEMENTS_VALUE_OUTPUT = """\ +{ + "AAAAA1 AUTOGENERATED FILE DO NOT EDIT": {}, + "AAAAA2 See generate_buildbot_json.py to make changes": {}, + "Fake Tester": { + "gtest_tests": [ + { + "args": [ + "--enable-features=Bar,Baz" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "kvm": "1" + } + ] + }, + "test": "foo_test" + } + ] + } +} +""" + +REPLACEMENTS_VALUE_SEPARATE_ENTRIES_OUTPUT = """\ +{ + "AAAAA1 AUTOGENERATED FILE DO NOT EDIT": {}, + "AAAAA2 See generate_buildbot_json.py to make changes": {}, + "Fake Tester": { + "gtest_tests": [ + { + "args": [ + "--enable-features", + "Bar,Baz" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "kvm": "1" + } + ] + }, + "test": "foo_test" + } + ] + } +} +""" + + +class ReplacementTests(unittest.TestCase): + """Tests for the arg replacement feature.""" + def test_replacement_valid_remove_no_value(self): + fbb = FakeBBGen(FOO_GTESTS_WATERFALL, + FOO_TEST_SUITE_WITH_ARGS, + FOO_TEST_REPLACEMENTS_REMOVE_NO_VALUE, + EMPTY_PYL_FILE, + LUCI_MILO_CFG) + fbb.files['chromium.test.json'] = REPLACEMENTS_REMOVE_OUTPUT + fbb.check_output_file_consistency(verbose=True) + self.assertFalse(fbb.printed_lines) + + def test_replacement_valid_remove_value(self): + fbb = FakeBBGen(FOO_GTESTS_WATERFALL, + FOO_TEST_SUITE_WITH_ENABLE_FEATURES, + FOO_TEST_REPLACEMENTS_REMOVE_VALUE, + EMPTY_PYL_FILE, + LUCI_MILO_CFG) + fbb.files['chromium.test.json'] = REPLACEMENTS_REMOVE_OUTPUT + fbb.check_output_file_consistency(verbose=True) + self.assertFalse(fbb.printed_lines) + + def test_replacement_valid_replace_value(self): + fbb = FakeBBGen(FOO_GTESTS_WATERFALL, + FOO_TEST_SUITE_WITH_ENABLE_FEATURES, + FOO_TEST_REPLACEMENTS_REPLACE_VALUE, + EMPTY_PYL_FILE, + LUCI_MILO_CFG) + fbb.files['chromium.test.json'] = REPLACEMENTS_VALUE_OUTPUT + fbb.check_output_file_consistency(verbose=True) + self.assertFalse(fbb.printed_lines) + + def test_replacement_valid_replace_value_separate_entries(self): + fbb = FakeBBGen(FOO_GTESTS_WATERFALL, + FOO_TEST_SUITE_WITH_ENABLE_FEATURES_SEPARATE_ENTRIES, + FOO_TEST_REPLACEMENTS_REPLACE_VALUE, + EMPTY_PYL_FILE, + LUCI_MILO_CFG) + fbb.files['chromium.test.json'] = REPLACEMENTS_VALUE_SEPARATE_ENTRIES_OUTPUT + fbb.check_output_file_consistency(verbose=True) + self.assertFalse(fbb.printed_lines) + + def test_replacement_invalid_key_not_valid(self): + fbb = FakeBBGen(FOO_GTESTS_WATERFALL, + FOO_TEST_SUITE, + FOO_TEST_REPLACEMENTS_INVALID_KEY, + EMPTY_PYL_FILE, + LUCI_MILO_CFG) + with self.assertRaisesRegexp(generate_buildbot_json.BBGenErr, + 'Given replacement key *'): + fbb.check_output_file_consistency(verbose=True) + + def test_replacement_invalid_key_not_found(self): + fbb = FakeBBGen(FOO_GTESTS_WATERFALL, + FOO_TEST_SUITE_WITH_ARGS, + FOO_TEST_REPLACEMENTS_REPLACE_VALUE, + EMPTY_PYL_FILE, + LUCI_MILO_CFG) + with self.assertRaisesRegexp(generate_buildbot_json.BBGenErr, + 'Could not find *'): + fbb.check_output_file_consistency(verbose=True) + if __name__ == '__main__': unittest.main()
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 7c9dc7e..ed858fa 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -1231,7 +1231,39 @@ }, }, }, - 'pixel_test':{ + 'pixel_skia_gold_test': { + 'replacements': { + # client.v8.fyi + # The V8 builders pass the V8 revision for ${got_revision}, so instead + # use ${got_cr_revision}, which is only set on the V8 bots. + 'Android V8 FYI Release (Nexus 5X)': { + 'args': { + '--build-revision': '${got_cr_revision}', + }, + }, + 'Linux V8 FYI Release (NVIDIA)': { + 'args': { + '--build-revision': '${got_cr_revision}', + }, + }, + 'Linux V8 FYI Release - pointer compression (NVIDIA)': { + 'args': { + '--build-revision': '${got_cr_revision}', + }, + }, + 'Mac V8 FYI Release (Intel)': { + 'args': { + '--build-revision': '${got_cr_revision}', + }, + }, + 'Win V8 FYI Release (NVIDIA)': { + 'args': { + '--build-revision': '${got_cr_revision}', + }, + }, + }, + }, + 'pixel_test':{ 'modifications': { 'Android Release (Nexus 5X)': { 'swarming': {
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index d2ad2615..71684fb 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -3713,49 +3713,6 @@ }, }, - # This is identical to 'gpu_telemetry_tests_for_skia_gold_testing', except - # that the --build-revision arg uses ${got_cr_revision} instead of - # ${got_revision}. This is because got_revision on V8 builders contains - # the V8 revision, not the Chromium revision, which confuses the GPU team's - # Skia Gold instance since it's tracking the Chromium src repo. - 'gpu_telemetry_tests_for_skia_gold_testing_v8': { - 'pixel_skia': { - 'name': 'pixel_skia_gold_test', - 'args': [ - '--dont-restore-color-profile-after-test', - '--refimg-cloud-storage-bucket', - 'chromium-gpu-archive/reference-images', - '--os-type', - '${os_type}', - '--build-revision', - '${got_cr_revision}', - '--test-machine-name', - '${buildername}', - '--use-skia-gold', - ], - 'non_precommit_args': [ - '--upload-refimg-to-cloud-storage', - ], - 'precommit_args': [ - '--download-refimg-from-cloud-storage', - # Gerrit issue ID - '--review-patch-issue', - '${patch_issue}', - # Patch set number - '--review-patch-set', - '${patch_set}', - # Buildbucket ID - '--buildbucket-build-id', - '${buildbucket_build_id}', - ], - 'experiment_percentage': 100, - 'swarming': { - 'service_account': 'chrome-gpu-gold@chops-service-accounts.iam.gserviceaccount.com' - }, - 'telemetry_test_name': 'pixel', - }, - }, - 'gpu_webgl2_conformance_d3d11_validating_telemetry_tests': { 'webgl2_conformance_d3d11_validating_tests': { 'args': [ @@ -5422,7 +5379,7 @@ 'gpu_nexus5x_telemetry_tests_v8': [ 'gpu_common_and_optional_telemetry_tests', 'gpu_telemetry_tests', - 'gpu_telemetry_tests_for_skia_gold_testing_v8', + 'gpu_telemetry_tests_for_skia_gold_testing', 'gpu_webgl_conformance_gles_passthrough_telemetry_tests', 'gpu_webgl_conformance_telemetry_tests', ], @@ -5453,7 +5410,7 @@ 'gpu_v8_desktop_telemetry_tests': [ 'gpu_common_and_optional_telemetry_tests', 'gpu_telemetry_tests', - 'gpu_telemetry_tests_for_skia_gold_testing_v8', + 'gpu_telemetry_tests_for_skia_gold_testing', 'gpu_webgl2_conformance_telemetry_tests', 'gpu_webgl_conformance_telemetry_tests', ],
diff --git a/third_party/android_deps/BUILD.gn b/third_party/android_deps/BUILD.gn index c3768e3..a041137 100644 --- a/third_party/android_deps/BUILD.gn +++ b/third_party/android_deps/BUILD.gn
@@ -88,6 +88,9 @@ ":android_arch_core_common_java", ":android_arch_lifecycle_common_java", ] + + # https://crbug.com/887942#c1 + ignore_proguard_configs = true } # This is generated, do not edit. Update BuildConfigGenerator.groovy instead.
diff --git a/third_party/android_deps/licenses/CDDLv1.0.txt b/third_party/android_deps/licenses/CDDLv1.0.txt new file mode 100644 index 0000000..cead8832 --- /dev/null +++ b/third_party/android_deps/licenses/CDDLv1.0.txt
@@ -0,0 +1,287 @@ +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 + +1. Definitions. + +1.1. Contributor means each individual or entity that creates or contributes to +the creation of Modifications. + +1.2. Contributor Version means the combination of the Original Software, prior +Modifications used by a Contributor (if any), and the Modifications made by +that particular Contributor. + +1.3. Covered Software means (a) the Original Software, or (b) Modifications, or +(c) the combination of files containing Original Software with files containing +Modifications, in each case including portions thereof. + +1.4. Executable means the Covered Software in any form other than Source Code. + +1.5. Initial Developer means the individual or entity that first makes Original +Software available under this License. + +1.6. Larger Work means a work which combines Covered Software or portions +thereof with code not governed by the terms of this License. + +1.7. License means this document. + +1.8. Licensable means having the right to grant, to the maximum extent +possible, whether at the time of the initial grant or subsequently acquired, +any and all of the rights conveyed herein. + +1.9. Modifications means the Source Code and Executable form of any of the +following: A. Any file that results from an addition to, deletion from or +modification of the contents of a file containing Original Software or previous +Modifications; B. Any new file that contains any part of the Original Software +or previous Modification; or C. Any new file that is contributed or otherwise +made available under the terms of this License. + +1.10. Original Software means the Source Code and Executable form of computer +software code that is originally released under this License. + +1.11. Patent Claims means any patent claim(s), now owned or hereafter acquired, +including without limitation, method, process, and apparatus claims, in any +patent Licensable by grantor. + +1.12. Source Code means (a) the common form of computer software code in which +modifications are made and (b) associated documentation included in or with +such code. + +1.13. You (or Your) means an individual or a legal entity exercising rights +under, and complying with all of the terms of, this License. For legal +entities, You includes any entity which controls, is controlled by, or is under +common control with You. For purposes of this definition, control means (a) the +power, direct or indirect, to cause the direction or management of such entity, +whether by contract or otherwise, or (b) ownership of more than fifty percent +(50%) of the outstanding shares or beneficial ownership of such entity. + +2. License Grants. + +2.1. The Initial Developer Grant. Conditioned upon Your compliance with Section +3.1 below and subject to third party intellectual property claims, the Initial +Developer hereby grants You a world-wide, royalty-free, non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) +Licensable by Initial Developer, to use, reproduce, modify, display, perform, +sublicense and distribute the Original Software (or portions thereof), with or +without Modifications, and/or as part of a Larger Work; and + +(b) under Patent Claims infringed by the making, using or selling of Original +Software, to make, have made, use, practice, sell, and offer for sale, and/or +otherwise dispose of the Original Software (or portions thereof); + +(c) The licenses granted in Sections 2.1(a) and (b) are effective on the date +Initial Developer first distributes or otherwise makes the Original Software +available to a third party under the terms of this License; + +(d) Notwithstanding Section 2.1(b) above, no patent license is granted: (1) for +code that You delete from the Original Software, or (2) for infringements +caused by: (i) the modification of the Original Software, or (ii) the +combination of the Original Software with other software or devices. + +2.2. Contributor Grant. Conditioned upon Your compliance with Section 3.1 below +and subject to third party intellectual property claims, each Contributor +hereby grants You a world-wide, royalty-free, non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) +Licensable by Contributor to use, reproduce, modify, display, perform, +sublicense and distribute the Modifications created by such Contributor (or +portions thereof), either on an unmodified basis, with other Modifications, as +Covered Software and/or as part of a Larger Work; and + +(b) under Patent Claims infringed by the making, using, or selling of +Modifications made by that Contributor either alone and/or in combination with +its Contributor Version (or portions of such combination), to make, use, sell, +offer for sale, have made, and/or otherwise dispose of: (1) Modifications made +by that Contributor (or portions thereof); and (2) the combination of +Modifications made by that Contributor with its Contributor Version (or +portions of such combination). + +(c) The licenses granted in Sections 2.2(a) and 2.2(b) are effective on the +date Contributor first distributes or otherwise makes the Modifications +available to a third party. + +(d) Notwithstanding Section 2.2(b) above, no patent license is granted: (1) for +any code that Contributor has deleted from the Contributor Version; (2) for +infringements caused by: (i) third party modifications of Contributor Version, +or (ii) the combination of Modifications made by that Contributor with other +software (except as part of the Contributor Version) or other devices; or (3) +under Patent Claims infringed by Covered Software in the absence of +Modifications made by that Contributor. + +3. Distribution Obligations. + +3.1. Availability of Source Code. Any Covered Software that You distribute or +otherwise make available in Executable form must also be made available in +Source Code form and that Source Code form must be distributed only under the +terms of this License. You must include a copy of this License with every copy +of the Source Code form of the Covered Software You distribute or otherwise +make available. You must inform recipients of any such Covered Software in +Executable form as to how they can obtain such Covered Software in Source Code +form in a reasonable manner on or through a medium customarily used for +software exchange. + +3.2. Modifications. The Modifications that You create or to which You +contribute are governed by the terms of this License. You represent that You +believe Your Modifications are Your original creation(s) and/or You have +sufficient rights to grant the rights conveyed by this License. + +3.3. Required Notices. You must include a notice in each of Your Modifications +that identifies You as the Contributor of the Modification. You may not remove +or alter any copyright, patent or trademark notices contained within the +Covered Software, or any notices of licensing or any descriptive text giving +attribution to any Contributor or the Initial Developer. + +3.4. Application of Additional Terms. You may not offer or impose any terms on +any Covered Software in Source Code form that alters or restricts the +applicable version of this License or the recipients rights hereunder. You may +choose to offer, and to charge a fee for, warranty, support, indemnity or +liability obligations to one or more recipients of Covered Software. However, +you may do so only on Your own behalf, and not on behalf of the Initial +Developer or any Contributor. You must make it absolutely clear that any such +warranty, support, indemnity or liability obligation is offered by You alone, +and You hereby agree to indemnify the Initial Developer and every Contributor +for any liability incurred by the Initial Developer or such Contributor as a +result of warranty, support, indemnity or liability terms You offer. + +3.5. Distribution of Executable Versions. You may distribute the Executable +form of the Covered Software under the terms of this License or under the terms +of a license of Your choice, which may contain terms different from this +License, provided that You are in compliance with the terms of this License and +that the license for the Executable form does not attempt to limit or alter the +recipients rights in the Source Code form from the rights set forth in this +License. If You distribute the Covered Software in Executable form under a +different license, You must make it absolutely clear that any terms which +differ from this License are offered by You alone, not by the Initial Developer +or Contributor. You hereby agree to indemnify the Initial Developer and every +Contributor for any liability incurred by the Initial Developer or such +Contributor as a result of any such terms You offer. + +3.6. Larger Works. You may create a Larger Work by combining Covered Software +with other code not governed by the terms of this License and distribute the +Larger Work as a single product. In such a case, You must make sure the +requirements of this License are fulfilled for the Covered Software. + +4. Versions of the License. + +4.1. New Versions. Sun Microsystems, Inc. is the initial license steward and +may publish revised and/or new versions of this License from time to time. Each +version will be given a distinguishing version number. Except as provided in +Section 4.3, no one other than the license steward has the right to modify this +License. + +4.2. Effect of New Versions. You may always continue to use, distribute or +otherwise make the Covered Software available under the terms of the version of +the License under which You originally received the Covered Software. If the +Initial Developer includes a notice in the Original Software prohibiting it +from being distributed or otherwise made available under any subsequent version +of the License, You must distribute and make the Covered Software available +under the terms of the version of the License under which You originally +received the Covered Software. Otherwise, You may also choose to use, +distribute or otherwise make the Covered Software available under the terms of +any subsequent version of the License published by the license steward. + +4.3. Modified Versions. When You are an Initial Developer and You want to +create a new license for Your Original Software, You may create and use a +modified version of this License if You: (a) rename the license and remove any +references to the name of the license steward (except to note that the license +differs from this License); and (b) otherwise make it clear that the license +contains terms which differ from this License. + +5. DISCLAIMER OF WARRANTY. COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON +AN AS IS BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, +INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF +DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH +YOU. SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE +INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY +SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN +ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED +HEREUNDER EXCEPT UNDER THIS DISCLAIMER. + +6. TERMINATION. + +6.1. This License and the rights granted hereunder will terminate automatically +if You fail to comply with terms herein and fail to cure such breach within 30 +days of becoming aware of the breach. Provisions which, by their nature, must +remain in effect beyond the termination of this License shall survive. + +6.2. If You assert a patent infringement claim (excluding declaratory judgment +actions) against Initial Developer or a Contributor (the Initial Developer or +Contributor against whom You assert such claim is referred to as Participant) +alleging that the Participant Software (meaning the Contributor Version where +the Participant is a Contributor or the Original Software where the Participant +is the Initial Developer) directly or indirectly infringes any patent, then any +and all rights granted directly or indirectly to You by such Participant, the +Initial Developer (if the Initial Developer is not the Participant) and all +Contributors under Sections 2.1 and/or 2.2 of this License shall, upon 60 days +notice from Participant terminate prospectively and automatically at the +expiration of such 60 day notice period, unless if within such 60 day period +You withdraw Your claim with respect to the Participant Software against such +Participant either unilaterally or pursuant to a written agreement with +Participant. + +6.3. In the event of termination under Sections 6.1 or 6.2 above, all end user +licenses that have been validly granted by You or any distributor hereunder +prior to termination (excluding licenses granted to You by any distributor) +shall survive termination. + +7. LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, +WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE +INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED +SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR +ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER +INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK +STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL +DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE +POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO +LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTYS NEGLIGENCE TO +THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT +ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO +THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. + +8. U.S. GOVERNMENT END USERS. The Covered Software is a commercial item, as +that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of commercial +computer software (as that term is defined at 48 C.F.R. 252.227-7014(a)(1)) and +commercial computer software documentation as such terms are used in 48 C.F.R. +12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 +through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered +Software with only those rights set forth herein. This U.S. Government Rights +clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or +provision that addresses Government rights in computer software under this +License. + +9. MISCELLANEOUS. This License represents the complete agreement concerning +subject matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent necessary to +make it enforceable. This License shall be governed by the law of the +jurisdiction specified in a notice contained within the Original Software +(except to the extent applicable law, if any, provides otherwise), excluding +such jurisdictions conflict-of-law provisions. Any litigation relating to this +License shall be subject to the jurisdiction of the courts located in the +jurisdiction and venue specified in a notice contained within the Original +Software, with the losing party responsible for costs, including, without +limitation, court costs and reasonable attorneys fees and expenses. The +application of the United Nations Convention on Contracts for the International +Sale of Goods is expressly excluded. Any law or regulation which provides that +the language of a contract shall be construed against the drafter shall not +apply to this License. You agree that You alone are responsible for compliance +with the United States export administration regulations (and the export +control laws and regulation of any other countries) when You use, distribute or +otherwise make available any Covered Software. + +10. RESPONSIBILITY FOR CLAIMS. As between Initial Developer and the +Contributors, each party is responsible for claims and damages arising, +directly or indirectly, out of its utilization of rights under this License and +You agree to work with Initial Developer and Contributors to distribute such +responsibility on an equitable basis. Nothing herein is intended or shall be +deemed to constitute any admission of liability. + +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION LICENSE +(CDDL) + +For Covered Software in this distribution, this License shall be governed by +the laws of the State of California (excluding conflict-of-law provisions). + +Any litigation relating to this License shall be subject to the jurisdiction of +the Federal Courts of the Northern District of California and the state courts +of the State of California, with venue lying in Santa Clara County, California. +
diff --git a/third_party/blink/common/web_package/signed_exchange_request_matcher.cc b/third_party/blink/common/web_package/signed_exchange_request_matcher.cc index 522d578..d7641a0 100644 --- a/third_party/blink/common/web_package/signed_exchange_request_matcher.cc +++ b/third_party/blink/common/web_package/signed_exchange_request_matcher.cc
@@ -5,10 +5,12 @@ #include "third_party/blink/public/common/web_package/signed_exchange_request_matcher.h" #include <algorithm> +#include <limits> #include <memory> #include <utility> #include "base/containers/span.h" +#include "base/numerics/checked_math.h" #include "base/optional.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -278,6 +280,33 @@ return parsed; } +// Returns the index of matching entry in Possible Keys [1] which is the cross +// product of |sorted_variants|. If there is no matching entry returns nullopt. +// Example: +// sorted_variants: [["image/webp","image/jpg"], ["en", "fr", "ja"]] +// variant_key: ["image/jpg", "fr"] +// Possible Keys list for this sorted_variants: +// [["image/webp", "en"], ["image/webp", "fr"], ["image/webp", "ja"], +// ["image/jpg", "en"], ["image/jpg", "fr"], ["image/jpg", "ja"]] +// Result: 4 +// [1] https://httpwg.org/http-extensions/draft-ietf-httpbis-variants.html#find +base::Optional<size_t> GetPossibleKeysIndex( + const std::vector<std::vector<std::string>>& sorted_variants, + const std::vector<std::string>& variant_key) { + DCHECK_EQ(variant_key.size(), sorted_variants.size()); + size_t index = 0; + for (size_t i = 0; i < sorted_variants.size(); ++i) { + auto found = std::find(sorted_variants[i].begin(), sorted_variants[i].end(), + variant_key[i]); + if (found == sorted_variants[i].end()) + return base::nullopt; + + index = index * sorted_variants[i].size() + + (found - sorted_variants[i].begin()); + } + return index; +} + } // namespace SignedExchangeRequestMatcher::SignedExchangeRequestMatcher( @@ -300,6 +329,14 @@ return MatchRequest(request_headers_, response_headers); } +std::vector<std::string>::const_iterator +SignedExchangeRequestMatcher::FindBestMatchingVariantKey( + const std::string& variants, + const std::vector<std::string>& variant_key_list) const { + return FindBestMatchingVariantKey(request_headers_, variants, + variant_key_list); +} + // Implements "Cache Behaviour" [1] when "stored-responses" is a singleton list // containing a response that has "Variants" header whose value is |variants|. // [1] https://httpwg.org/http-extensions/draft-ietf-httpbis-variants.html#cache @@ -452,4 +489,52 @@ return false; } +// static +std::vector<std::string>::const_iterator +SignedExchangeRequestMatcher::FindBestMatchingVariantKey( + const net::HttpRequestHeaders& request_headers, + const std::string& variants, + const std::vector<std::string>& variant_keys_list) { + auto parsed_variants = http_structured_header::ParseListOfLists(variants); + if (!parsed_variants) + return variant_keys_list.end(); + + std::vector<std::vector<std::string>> sorted_variants = + CacheBehavior(*parsed_variants, request_headers); + // This happens when `Variant` has unknown field names. In such cases, + // this algorithm never returns "match", so we do an early return. + if (sorted_variants.size() != parsed_variants->size()) + return variant_keys_list.end(); + + // Check that the combination count of Possible Keys doesn't overflow. + // Currently we have only three ContentNegotiationAlgorithms, so it is + // impossible to overflow. But we check to protect for future extension. + size_t possible_keys_count = 1; + for (const auto& key : sorted_variants) { + if (!base::CheckMul(possible_keys_count, key.size()) + .AssignIfValid(&possible_keys_count)) { + return variant_keys_list.end(); + } + } + + size_t minimum_index = std::numeric_limits<size_t>::max(); + auto found_variant_key = variant_keys_list.end(); + + for (auto variant_keys_list_it = variant_keys_list.begin(); + variant_keys_list_it < variant_keys_list.end(); ++variant_keys_list_it) { + auto parsed_variant_keys = + ParseVariantKey(*variant_keys_list_it, parsed_variants->size()); + if (!parsed_variant_keys) + continue; + for (const std::vector<std::string>& variant_key : *parsed_variant_keys) { + auto maching_index = GetPossibleKeysIndex(sorted_variants, variant_key); + if (maching_index.has_value() && *maching_index < minimum_index) { + minimum_index = *maching_index; + found_variant_key = variant_keys_list_it; + } + } + } + return found_variant_key; +} + } // namespace blink
diff --git a/third_party/blink/common/web_package/signed_exchange_request_matcher_unittest.cc b/third_party/blink/common/web_package/signed_exchange_request_matcher_unittest.cc index 15e1732..475c630c 100644 --- a/third_party/blink/common/web_package/signed_exchange_request_matcher_unittest.cc +++ b/third_party/blink/common/web_package/signed_exchange_request_matcher_unittest.cc
@@ -218,4 +218,87 @@ } } +TEST(SignedExchangeRequestMatcherTest, FindBestMatchingVariantKey) { + const struct TestCase { + const char* name; + std::map<std::string, std::string> req_headers; + std::string variants; + std::vector<std::string> variant_key_list; + base::Optional<std::string> expected_result; + } cases[] = { + { + "Content type negotiation: default value", + {{"accept", "image/webp,image/jpg"}}, + "Accept;image/xx;image/yy", + {"image/yy", "image/xx"}, + "image/xx" // There is no preferred available, image/xx is the + // default. + }, + { + "Language negotiation: default value", + {{"accept-language", "en,fr"}}, + "accept-language;ja;ch", + {"ja", "ch"}, + "ja" // There is no preferred available, ja is the default. + }, + { + "Language negotiation: no matching language", + {{"accept-language", "en,fr"}}, + "accept-language;ja;ch", + {"ch"}, + base::nullopt // There is no matching language. + }, + { + "Content type negotiation: Q value", + {{"accept", "image/jpg;q=0.8,image/webp,image/apng"}}, + "Accept;image/jpg;image/apng;image/webp", + {"image/jpg", "image/webp", "image/apng"}, + "image/webp" // image/webp is the most preferred content type. + }, + { + "Content type and Language negotiation", + {{"accept", "image/webp,image/jpg,*/*;q=0.3"}, + {"accept-language", "en,fr,ja"}}, + "Accept;image/webp;image/apng,accept-language;ja;en", + {"image/apng;ja", "image/webp;ja", "image/apng;en,image/webp;en"}, + "image/apng;en,image/webp;en" // image/webp;en is the most preferred + // content type. + }, + { + "Variants is invalid", + {{"accept", "image/webp,image/jpg"}}, + " ", + {}, + base::nullopt // Variants is invalid. + }, + { + "Variants size and Variant Key size don't match", + {{"accept", "image/webp,image/jpg"}}, + "Accept;image/webp;image/apng,accept-language;ja;en", + {"image/webp", "image/apng"}, + base::nullopt // There is no matching Variant Key. + }, + { + "Unknown Variant", + {{"accept", "image/webp,image/jpg"}}, + "Accept;image/webp;image/jpg, FooBar;foo;bar", + {"image/webp;foo", "image/webp;bar", "image/webp;jpg", + "image/jpg;bar"}, + base::nullopt // FooBar is unknown. + }, + }; + for (const auto& c : cases) { + net::HttpRequestHeaders request_headers; + for (auto it = c.req_headers.begin(); it != c.req_headers.end(); ++it) + request_headers.SetHeader(it->first, it->second); + auto variant_key_list_it = + SignedExchangeRequestMatcher::FindBestMatchingVariantKey( + request_headers, c.variants, c.variant_key_list); + if (variant_key_list_it == c.variant_key_list.end()) { + EXPECT_EQ(c.expected_result, base::nullopt) << c.name; + } else { + EXPECT_EQ(c.expected_result, *variant_key_list_it) << c.name; + } + } +} } // namespace blink
diff --git a/third_party/blink/public/BUILD.gn b/third_party/blink/public/BUILD.gn index 3188a28..2a23cf3 100644 --- a/third_party/blink/public/BUILD.gn +++ b/third_party/blink/public/BUILD.gn
@@ -131,6 +131,7 @@ "platform/linux/web_sandbox_support.h", "platform/mac/web_sandbox_support.h", "platform/mac/web_scrollbar_theme.h", + "platform/media/webmediaplayer_delegate.h", "platform/modules/indexeddb/web_idb_database_exception.h", "platform/modules/media_capabilities/web_audio_configuration.h", "platform/modules/media_capabilities/web_media_capabilities_decoding_info.h", @@ -147,6 +148,7 @@ "platform/modules/mediastream/media_stream_dispatcher_eventhandler.h", "platform/modules/mediastream/media_stream_types.h", "platform/modules/mediastream/secure_display_link_tracker.h", + "platform/modules/mediastream/web_media_element_source_utils.h", "platform/modules/mediastream/web_media_stream_audio_renderer.h", "platform/modules/mediastream/web_media_stream_audio_sink.h", "platform/modules/mediastream/web_media_stream_renderer_factory.h",
diff --git a/third_party/blink/public/blink_resources.grd b/third_party/blink/public/blink_resources.grd index 375c78cf..b49f146b 100644 --- a/third_party/blink/public/blink_resources.grd +++ b/third_party/blink/public/blink_resources.grd
@@ -24,6 +24,7 @@ <include name="IDR_UASTYLE_THEME_INPUT_MULTIPLE_FIELDS_CSS" file="../renderer/core/html/resources/input_multiple_fields.css" type="BINDATA" compress="gzip"/> <include name="IDR_UASTYLE_THEME_WIN_CSS" file="../renderer/core/html/resources/win.css" type="BINDATA" compress="gzip"/> <include name="IDR_UASTYLE_THEME_WIN_QUIRKS_CSS" file="../renderer/core/html/resources/win_quirks.css" type="BINDATA" compress="gzip"/> + <include name="IDR_UASTYLE_THEME_CONTROLS_REFRESH_CSS" file="../renderer/core/html/resources/controls_refresh.css" type="BINDATA" compress="gzip"/> <include name="IDR_UASTYLE_SVG_CSS" file="../renderer/core/css/svg.css" type="BINDATA" compress="gzip"/> <include name="IDR_UASTYLE_MATHML_CSS" file="../renderer/core/css/mathml.css" type="BINDATA" compress="gzip"/> <include name="IDR_UASTYLE_FULLSCREEN_CSS" file="../renderer/core/css/fullscreen.css" type="BINDATA" compress="gzip"/>
diff --git a/third_party/blink/public/common/web_package/signed_exchange_request_matcher.h b/third_party/blink/public/common/web_package/signed_exchange_request_matcher.h index 234cda8f..d16ac43 100644 --- a/third_party/blink/public/common/web_package/signed_exchange_request_matcher.h +++ b/third_party/blink/public/common/web_package/signed_exchange_request_matcher.h
@@ -31,6 +31,16 @@ const std::string& accept_langs); bool MatchRequest(const HeaderMap& response_headers) const; + // Returns the iterator of |variant_keys_list| which contains the best + // matching variant key. This method use the preference order of the result of + // "Cache Behaviour" [2]. If there is no matching variant key, returns + // |variant_keys_list.end()|. + // [2]: + // https://httpwg.org/http-extensions/draft-ietf-httpbis-variants.html#cache + std::vector<std::string>::const_iterator FindBestMatchingVariantKey( + const std::string& variants, + const std::vector<std::string>& variant_keys_list) const; + private: net::HttpRequestHeaders request_headers_; @@ -39,8 +49,16 @@ static std::vector<std::vector<std::string>> CacheBehavior( const http_structured_header::ListOfLists& variants, const net::HttpRequestHeaders& request_headers); + + static std::vector<std::string>::const_iterator FindBestMatchingVariantKey( + const net::HttpRequestHeaders& request_headers, + const std::string& variants, + const std::vector<std::string>& variant_key_list); + FRIEND_TEST_ALL_PREFIXES(SignedExchangeRequestMatcherTest, MatchRequest); FRIEND_TEST_ALL_PREFIXES(SignedExchangeRequestMatcherTest, CacheBehavior); + FRIEND_TEST_ALL_PREFIXES(SignedExchangeRequestMatcherTest, + FindBestMatchingVariantKey); }; } // namespace blink
diff --git a/third_party/blink/public/mojom/websockets/websocket_connector.mojom b/third_party/blink/public/mojom/websockets/websocket_connector.mojom index 2859229..4e40af5 100644 --- a/third_party/blink/public/mojom/websockets/websocket_connector.mojom +++ b/third_party/blink/public/mojom/websockets/websocket_connector.mojom
@@ -13,6 +13,8 @@ // Starts an opening handshake. // |user_agent| is a "user-agent" request header value. For other params, see // CreateWebSocket in //services/network/public/mojom/network_context.mojom. + // It is recommended to detect mojo connection errors on |connection_client|, + // not on |handshake_client|. See network_context.mojom for details. Connect(url.mojom.Url url, array<string> requested_protocols, url.mojom.Url site_for_cookies,
diff --git a/third_party/blink/public/platform/media/OWNERS b/third_party/blink/public/platform/media/OWNERS new file mode 100644 index 0000000..168af18 --- /dev/null +++ b/third_party/blink/public/platform/media/OWNERS
@@ -0,0 +1 @@ +file://media/OWNERS
diff --git a/media/blink/webmediaplayer_delegate.h b/third_party/blink/public/platform/media/webmediaplayer_delegate.h similarity index 94% rename from media/blink/webmediaplayer_delegate.h rename to third_party/blink/public/platform/media/webmediaplayer_delegate.h index b592b21..7b42144 100644 --- a/media/blink/webmediaplayer_delegate.h +++ b/third_party/blink/public/platform/media/webmediaplayer_delegate.h
@@ -2,27 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef MEDIA_BLINK_WEBMEDIAPLAYER_DELEGATE_H_ -#define MEDIA_BLINK_WEBMEDIAPLAYER_DELEGATE_H_ +#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MEDIA_WEBMEDIAPLAYER_DELEGATE_H_ +#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MEDIA_WEBMEDIAPLAYER_DELEGATE_H_ +#include "third_party/blink/public/platform/web_common.h" #include "third_party/blink/public/platform/web_media_player.h" -namespace blink { -enum class WebFullscreenVideoStatus; -class WebMediaPlayer; -} // namespace blink - namespace gfx { class Size; } // namespace gfx namespace media { - enum class MediaContentType; +} // namespace media + +namespace blink { + +enum class WebFullscreenVideoStatus; +class WebMediaPlayer; // An interface to collect WebMediaPlayer state changes and to fan out commands // from the browser. -class WebMediaPlayerDelegate { +class BLINK_PLATFORM_EXPORT WebMediaPlayerDelegate { public: // Note: WebMediaPlayerDelegate implementations should not call an Observer // method on a stack that includes a call from the player. @@ -146,6 +147,6 @@ virtual ~WebMediaPlayerDelegate() = default; }; -} // namespace media +} // namespace blink -#endif // MEDIA_BLINK_WEBMEDIAPLAYER_DELEGATE_H_ +#endif // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MEDIA_WEBMEDIAPLAYER_DELEGATE_H_
diff --git a/third_party/blink/public/platform/modules/mediastream/web_media_element_source_utils.h b/third_party/blink/public/platform/modules/mediastream/web_media_element_source_utils.h new file mode 100644 index 0000000..67cafb0 --- /dev/null +++ b/third_party/blink/public/platform/modules/mediastream/web_media_element_source_utils.h
@@ -0,0 +1,23 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_MEDIASTREAM_WEB_MEDIA_ELEMENT_SOURCE_UTILS_H_ +#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_MEDIASTREAM_WEB_MEDIA_ELEMENT_SOURCE_UTILS_H_ + +#include "third_party/blink/public/platform/web_common.h" + +namespace blink { + +class WebMediaPlayerSource; +class WebMediaStream; + +// Obtains a WebMediaStream from a WebMediaPlayerSource. If the +// WebMediaPlayerSource does not contain a WebMediaStream, a null +// WebMediaStream is returned. +BLINK_PLATFORM_EXPORT WebMediaStream +GetWebMediaStreamFromWebMediaPlayerSource(const WebMediaPlayerSource& source); + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_MEDIASTREAM_WEB_MEDIA_ELEMENT_SOURCE_UTILS_H_
diff --git a/third_party/blink/public/platform/platform.h b/third_party/blink/public/platform/platform.h index 5b29bbe..342e17a 100644 --- a/third_party/blink/public/platform/platform.h +++ b/third_party/blink/public/platform/platform.h
@@ -100,6 +100,10 @@ class Local; } +namespace viz { +class ContextProvider; +} + namespace webrtc { struct RtpCapabilities; class AsyncResolverFactory; @@ -554,6 +558,10 @@ return nullptr; } + virtual viz::ContextProvider* SharedMainThreadContextProvider() { + return nullptr; + } + // WebRTC ---------------------------------------------------------- // Creates a WebRTCPeerConnectionHandler for RTCPeerConnection.
diff --git a/third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h b/third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h index a789ec3..adf7f5b 100644 --- a/third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h +++ b/third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h
@@ -44,6 +44,7 @@ class WebRTCICECandidate; class WebRTCRtpReceiver; class WebRTCRtpTransceiver; +class WebString; struct BLINK_PLATFORM_EXPORT WebRTCSctpTransportSnapshot { rtc::scoped_refptr<webrtc::SctpTransportInterface> transport; @@ -59,6 +60,10 @@ virtual void NegotiationNeeded() = 0; virtual void DidGenerateICECandidate(scoped_refptr<WebRTCICECandidate>) = 0; + virtual void DidFailICECandidate(const WebString& host_candidate, + const WebString& url, + int error_code, + const WebString& error_text) = 0; virtual void DidChangeSignalingState( webrtc::PeerConnectionInterface::SignalingState) = 0; virtual void DidChangeIceGatheringState(
diff --git a/third_party/blink/public/web/web_local_frame_client.h b/third_party/blink/public/web/web_local_frame_client.h index b4e3faae..30fb02ce 100644 --- a/third_party/blink/public/web/web_local_frame_client.h +++ b/third_party/blink/public/web/web_local_frame_client.h
@@ -669,8 +669,8 @@ bool /*is_animated*/) {} // Reports that visible elements in the frame shifted (bit.ly/lsm-explainer). - virtual void DidObserveLayoutJank(double jank_fraction, - bool after_input_or_scroll) {} + virtual void DidObserveLayoutShift(double score, bool after_input_or_scroll) { + } enum class LazyLoadBehavior { kDeferredImage, // An image is being deferred by the lazy load feature.
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.cc b/third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.cc index 5f5c1cf..37e233d 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.cc
@@ -4,7 +4,6 @@ #include "third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.h" -#include <array> #include <cstring> #include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h" @@ -460,8 +459,8 @@ // Function templates v8::HandleScope handleScope(isolate); - std::array<v8::Local<v8::FunctionTemplate>, kSnapshotInterfaceSize> - interface_templates; + Vector<v8::Local<v8::FunctionTemplate>> interface_templates( + kSnapshotInterfaceSize); v8::Local<v8::FunctionTemplate> window_template; for (size_t i = 0; i < kSnapshotInterfaceSize; ++i) { const WrapperTypeInfo* wrapper_type_info =
diff --git a/third_party/blink/renderer/bindings/modules/BUILD.gn b/third_party/blink/renderer/bindings/modules/BUILD.gn index 97df9fb..e400dc8 100644 --- a/third_party/blink/renderer/bindings/modules/BUILD.gn +++ b/third_party/blink/renderer/bindings/modules/BUILD.gn
@@ -47,6 +47,7 @@ "//third_party/blink/renderer/modules/payments/payment_request_update_event.idl", "//third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.idl", "//third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.idl", + "//third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.idl", "//third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.idl", "//third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.idl", "//third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.idl",
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py b/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py index f7c240d..0840e29 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py
@@ -162,6 +162,9 @@ for k, v in groupby(attributes, key=lambda x: x.key) } + def __bool__(self): + return bool(self._attributes) + def __contains__(self, key): """ Returns True if this has an extended attribute with the |key|. @@ -178,6 +181,9 @@ for attr in attrs: yield attr + def __len__(self): + return len(list(self.__iter__())) + def __str__(self): attrs = [str(attr) for attr in self] return '[{}]'.format(', '.join(attrs)) @@ -185,6 +191,9 @@ def make_copy(self): return ExtendedAttributes(map(ExtendedAttribute.make_copy, self)) + def keys(self): + return self._attributes.keys() + def get(self, key): """ Returns an exnteded attribute whose key is |key|.
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py b/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py index 0a1cff9..c278c11 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py
@@ -27,10 +27,9 @@ # + PromiseType # + UnionType # + NullableType -# + AnnotatedType -class IdlType(WithCodeGeneratorInfo, WithDebugInfo): +class IdlType(WithExtendedAttributes, WithCodeGeneratorInfo, WithDebugInfo): """ Represents a 'type' in Web IDL @@ -43,36 +42,35 @@ language bindings (such as ECMAScript bindings), thus it's out of scope for IdlType to tell whether IDL dictionary type accepts ES null value or not. - *CAUTION*: Predicators are defined based on the exact definition of Web - IDL, and may behave counterintuitively. See examples below. - - clamp_nullable_long = ...an IdlType of '[Clamp] long?' - isisntance(clamp_nullable_long, AnnotatedType) # True - clamp_nullable_long.is_annotated # True - clamp_nullable_long.is_nullable # False, this is not a NullableType - - nullable_long = clamp_nullable_long.inner_type - isinstance(nullable_long, NullableType) # True - nullable_long.is_nullable # True - nullable_long.is_numeric # False, NullableType is not a numeric type - - long_type = nullable_long.inner_type - isinstance(long_type, SimpleType) # True - long_type.is_numeric # True + Nullable type and typedef are implemented as if they're a container type + like record type and promise type. """ - def __init__(self, code_generator_info=None, debug_info=None): + def __init__(self, + extended_attributes=None, + code_generator_info=None, + debug_info=None): + WithExtendedAttributes.__init__(self, extended_attributes) WithCodeGeneratorInfo.__init__(self, code_generator_info) WithDebugInfo.__init__(self, debug_info) def __str__(self): + return self.syntactic_form + + @property + def syntactic_form(self): + """ + Returns a text representation of the type in the form of Web IDL syntax. + @return str + """ raise exceptions.NotImplementedError() @property def type_name(self): """ - Returns type name of this type. + Returns the type name. https://heycam.github.io/webidl/#dfn-type-name + Note that a type name is not necessarily unique. @return str """ raise exceptions.NotImplementedError() @@ -213,10 +211,10 @@ @property def is_annotated(self): """ - Returns True if |self| is an annotated type. + Returns True if |self| is annotated. @return bool """ - return False + return bool(self.extended_attributes) @property def is_promise(self): @@ -258,6 +256,18 @@ """ return False + def _format_syntactic_form(self, syntactic_form_inner): + """Helper function to implement |syntactic_form|.""" + if self.extended_attributes: + return '{} {}'.format(self.extended_attributes, + syntactic_form_inner) + return syntactic_form_inner + + def _format_type_name(self, type_name_inner): + """Helper function to implement |type_name|.""" + return '{}{}'.format(type_name_inner, ''.join( + sorted(self.extended_attributes.keys()))) + class SimpleType(IdlType): """ @@ -274,24 +284,30 @@ _VALID_TYPES = ('any', 'boolean', 'object', 'symbol', 'void') + _NUMERIC_TYPES + _STRING_TYPES - def __init__(self, name, code_generator_info=None, debug_info=None): + def __init__(self, + name, + extended_attributes=None, + code_generator_info=None, + debug_info=None): IdlType.__init__( self, + extended_attributes=extended_attributes, code_generator_info=code_generator_info, debug_info=debug_info) assert name in SimpleType._VALID_TYPES, ( 'Unknown type name: {}'.format(name)) self._name = name - def __str__(self): - return self._name - # IdlType overrides @property + def syntactic_form(self): + return self._format_syntactic_form(self._name) + + @property def type_name(self): - if str(self) == 'DOMString': - return 'String' - return NameStyleConverter(self._name).to_upper_camel_case() + name = 'String' if self._name == 'DOMString' else self._name + return self._format_type_name( + NameStyleConverter(name).to_upper_camel_case()) @property def is_numeric(self): @@ -340,11 +356,13 @@ def __init__(self, ref_to_idl_type, + extended_attributes=None, code_generator_info=None, debug_info=None): assert RefByIdFactory.is_reference(ref_to_idl_type) IdlType.__init__( self, + extended_attributes=extended_attributes, code_generator_info=code_generator_info, debug_info=debug_info) WithIdentifier.__init__(self, ref_to_idl_type.identifier) @@ -377,6 +395,16 @@ # IdlType overrides @property + def syntactic_form(self): + assert not self.extended_attributes + return self.identifier + + @property + def type_name(self): + assert not self.extended_attributes + return self.identifier + + @property def is_interface(self): return self._definition.is_interface @@ -404,7 +432,7 @@ 'typedef' in Web IDL is not a type, however, there are use cases that have interest in typedef names. Thus, the IDL compiler does not resolve typedefs transparently (i.e. does not remove typedefs entirely), and - IdlTypes representing typedefs remain and behave like AnnotatedType. You + IdlTypes representing typedefs remain and behave like NullableType. You can track down the typedef'ed type to |original_type|. """ @@ -426,7 +454,13 @@ # IdlType overrides @property + def syntactic_form(self): + assert not self.extended_attributes + return self.identifier + + @property def type_name(self): + assert not self.extended_attributes return self.original_type.type_name @property @@ -439,10 +473,14 @@ class _ArrayLikeType(IdlType): - def __init__(self, element_type, code_generator_info=None, + def __init__(self, + element_type, + extended_attributes=None, + code_generator_info=None, debug_info=None): IdlType.__init__( self, + extended_attributes=extended_attributes, code_generator_info=code_generator_info, debug_info=debug_info) assert isinstance(element_type, IdlType) @@ -454,17 +492,28 @@ class SequenceType(_ArrayLikeType): - def __init__(self, element_type, code_generator_info=None, + def __init__(self, + element_type, + extended_attributes=None, + code_generator_info=None, debug_info=None): - _ArrayLikeType.__init__(self, element_type) + _ArrayLikeType.__init__( + self, + element_type, + extended_attributes=extended_attributes, + code_generator_info=code_generator_info, + debug_info=debug_info) # IdlType overrides - def __str__(self): - return 'sequence<{}>'.format(self.element_type) + @property + def syntactic_form(self): + return self._format_syntactic_form('sequence<{}>'.format( + self.element_type.syntactic_form)) @property def type_name(self): - return self.element_type.type_name + 'Sequence' + return self._format_type_name('{}Sequence'.format( + self.element_type.type_name)) @property def is_sequence(self): @@ -472,17 +521,28 @@ class FrozenArrayType(_ArrayLikeType): - def __init__(self, element_type, code_generator_info=None, + def __init__(self, + element_type, + extended_attributes=None, + code_generator_info=None, debug_info=None): - _ArrayLikeType.__init__(self, element_type) + _ArrayLikeType.__init__( + self, + element_type, + extended_attributes=extended_attributes, + code_generator_info=code_generator_info, + debug_info=debug_info) # IdlType overrides - def __str__(self): - return 'FrozenArray<{}>'.format(self.element_type) + @property + def syntactic_form(self): + return self._format_syntactic_form('FrozenArray<{}>'.format( + self.element_type.syntactic_form)) @property def type_name(self): - return self.element_type.type_name + 'Array' + return self._format_type_name('{}Array'.format( + self.element_type.type_name)) @property def is_frozen_array(self): @@ -493,10 +553,12 @@ def __init__(self, key_type, value_type, + extended_attributes=None, code_generator_info=None, debug_info=None): IdlType.__init__( self, + extended_attributes=extended_attributes, code_generator_info=code_generator_info, debug_info=debug_info) assert isinstance(key_type, IdlType) @@ -522,12 +584,15 @@ return self._value_type # IdlType overrides - def __str__(self): - return 'record<{}, {}>'.format(self.key_type, self.value_type) + @property + def syntactic_form(self): + return self._format_syntactic_form('record<{}, {}>'.format( + self.key_type.syntactic_form, self.value_type.syntactic_form)) @property def type_name(self): - return self.key_type.type_name + self.value_type.type_name + 'Record' + return self._format_type_name('{}{}Record'.format( + self.key_type.type_name, self.value_type.type_name)) @property def is_record(self): @@ -535,9 +600,14 @@ class PromiseType(IdlType): - def __init__(self, result_type, code_generator_info=None, debug_info=None): + def __init__(self, + result_type, + extended_attributes=None, + code_generator_info=None, + debug_info=None): IdlType.__init__( self, + extended_attributes=extended_attributes, code_generator_info=code_generator_info, debug_info=debug_info) assert isinstance(result_type, IdlType) @@ -552,12 +622,15 @@ return self._result_type # IdlType overrides - def __str__(self): - return 'Promise<{}>'.format(self.result_type) + @property + def syntactic_form(self): + return self._format_syntactic_form('Promise<{}>'.format( + self.result_type.syntactic_form)) @property def type_name(self): - return self.result_type.type_name + 'Promise' + return self._format_type_name('{}Promise'.format( + self.result_type.type_name)) @property def is_promise(self): @@ -566,10 +639,14 @@ # https://heycam.github.io/webidl/#idl-union class UnionType(IdlType): - def __init__(self, member_types, code_generator_info=None, + def __init__(self, + member_types, + extended_attributes=None, + code_generator_info=None, debug_info=None): IdlType.__init__( self, + extended_attributes=extended_attributes, code_generator_info=code_generator_info, debug_info=debug_info) assert isinstance(member_types, (list, tuple)) @@ -591,8 +668,8 @@ def flattened_member_types(self): """ Returns a set of flattened member types. - NOTE: Returned set does not contain nullable types nor annotated types, - even if |self| contains nullable/annotated types in its members. + NOTE: Returned set does not contain nullable types even if |self| + contains nullable types in its members. https://heycam.github.io/webidl/#dfn-flattened-union-member-types @return set(IdlType) """ @@ -600,12 +677,15 @@ assert False, 'Not implemented yet' # IdlType overrides - def __str__(self): - return '({})'.format(' or '.join([str(t) for t in self.member_types])) + @property + def syntactic_form(self): + return self._format_syntactic_form('({})'.format(' or '.join( + [member.syntactic_form for member in self.member_types]))) @property def type_name(self): - return 'Or'.join([member.type_name for member in self.member_types]) + return self._format_type_name('Or'.join( + [member.type_name for member in self.member_types])) @property def does_include_nullable_type(self): @@ -618,21 +698,38 @@ class NullableType(IdlType): - def __init__(self, inner_type, code_generator_info=None, debug_info=None): + def __init__(self, + inner_type, + extended_attributes=None, + code_generator_info=None, + debug_info=None): IdlType.__init__( self, + extended_attributes=extended_attributes, code_generator_info=code_generator_info, debug_info=debug_info) assert isinstance(inner_type, IdlType) self._inner_type = inner_type # IdlType overrides - def __str__(self): - return '{}?'.format(self.inner_type) + @property + def syntactic_form(self): + assert not self.extended_attributes + return '{}?'.format(self.inner_type.syntactic_form) @property def type_name(self): - return self.inner_type.type_name + 'OrNull' + assert not self.extended_attributes + # https://heycam.github.io/webidl/#idl-annotated-types + # Web IDL seems not supposing a case of [X] ([Y] Type)?, i.e. something + # like [X] nullable<[Y] Type>, which should turn into "TypeYOrNullX". + # + # In case of '[Clamp] long?', it's interpreted as '([Clamp] long)?' but + # the type name must be "LongOrNullClamp" instead of "LongClampOrNull". + name = self.inner_type.type_name + ext_attrs = ''.join(sorted(self.inner_type.extended_attributes.keys())) + sep_index = len(name) - len(ext_attrs) + return '{}OrNull{}'.format(name[0:sep_index], name[sep_index:]) @property def does_include_nullable_type(self): @@ -645,39 +742,3 @@ @property def inner_type(self): return self._inner_type - - -class AnnotatedType(IdlType, WithExtendedAttributes): - def __init__(self, - inner_type, - extended_attributes, - code_generator_info=None, - debug_info=None): - IdlType.__init__( - self, - code_generator_info=code_generator_info, - debug_info=debug_info) - WithExtendedAttributes.__init__(self, extended_attributes) - assert isinstance(inner_type, IdlType) - self._inner_type = inner_type - - # IdlType overrides - def __str__(self): - return '{} {}'.format(self.extended_attributes, self.inner_type) - - @property - def type_name(self): - return self.inner_type.type_name + ''.join( - sorted([ext_attr.key for ext_attr in self.extended_attributes])) - - @property - def does_include_nullable_type(self): - return self.inner_type.does_include_nullable_type - - @property - def is_annotated(self): - return True - - @property - def inner_type(self): - return self._inner_type
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/idl_types_test.py b/third_party/blink/renderer/bindings/scripts/web_idl/idl_types_test.py index b40fccd..280212d 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/idl_types_test.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/idl_types_test.py
@@ -6,7 +6,6 @@ from .extended_attribute import ExtendedAttribute from .extended_attribute import ExtendedAttributes -from .idl_types import AnnotatedType from .idl_types import FrozenArrayType from .idl_types import NullableType from .idl_types import PromiseType @@ -44,10 +43,10 @@ self.assertTrue(FrozenArrayType(short_type).is_frozen_array) self.assertTrue(UnionType([short_type, string_type]).is_union) self.assertTrue(NullableType(short_type).is_nullable) - annotated_type = AnnotatedType(short_type, ext_attrs) + self.assertFalse(NullableType(short_type).is_numeric) + annotated_type = SimpleType('short', extended_attributes=ext_attrs) self.assertTrue(annotated_type.is_annotated) - # Predictors are not transparent - self.assertFalse(annotated_type.is_numeric) + self.assertTrue(annotated_type.is_numeric) self.assertFalse(SimpleType('long').is_string) self.assertFalse(SimpleType('DOMString').is_object) @@ -85,15 +84,17 @@ ext_attrs = ExtendedAttributes( [ExtendedAttribute('TreatNullAs', 'EmptyString')]) - self.assertEqual('StringTreatNullAs', - AnnotatedType(string_type, ext_attrs).type_name) + self.assertEqual( + 'StringTreatNullAs', + SimpleType('DOMString', extended_attributes=ext_attrs).type_name) def test_union_types(self): # Test target: ((unrestricted double or object)? or # [TreatNullAs=EmptyString] DOMString) treat_null_as = ExtendedAttribute('TreatNullAs', 'EmptyString') - annotated_string = AnnotatedType( - SimpleType('DOMString'), ExtendedAttributes([treat_null_as])) + annotated_string = SimpleType( + 'DOMString', + extended_attributes=ExtendedAttributes([treat_null_as])) obj = SimpleType('object') unrestricted_double = SimpleType('unrestricted double') union = UnionType(
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/ir_builder.py b/third_party/blink/renderer/bindings/scripts/web_idl/ir_builder.py index c9e9bad..c25eb711 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/ir_builder.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/ir_builder.py
@@ -10,7 +10,6 @@ from .dictionary import DictionaryMember from .enumeration import Enumeration from .extended_attribute import ExtendedAttributes -from .idl_types import AnnotatedType from .idl_types import FrozenArrayType from .idl_types import NullableType from .idl_types import PromiseType @@ -207,83 +206,76 @@ return self._create_ref_to_idl_def(node.GetName()) def _build_type(self, node): - def build_maybe_inner_type(node): - return self._build_type_internal(node.GetChildren()[0]) - - def build_maybe_nullable_type(node): - maybe_inner_type = build_maybe_inner_type(node) - if node.GetProperty('NULLABLE'): - return NullableType(maybe_inner_type) - return maybe_inner_type - - def build_maybe_annotated_type(node): - type_nodes = list(node.GetChildren()) - extended_attributes = self._take_extended_attributes(type_nodes) - assert len(type_nodes) == 1 - maybe_inner_type = build_maybe_nullable_type(node) - if extended_attributes: - return AnnotatedType( - inner_type=maybe_inner_type, - extended_attributes=extended_attributes) - return maybe_inner_type - assert node.GetClass() == 'Type' - return build_maybe_annotated_type(node) + if node.GetProperty('NULLABLE'): + return NullableType(self._build_type_internal(node.GetChildren())) + return self._build_type_internal(node.GetChildren()) - def _build_type_internal(self, node): + def _build_type_internal(self, nodes): """ Args: - node: The body node of the type definition, which is supposed to be - the first child of a 'Type' node. + nodes: The child nodes of a 'Type' node. """ - def build_frozen_array_type(node): + def build_frozen_array_type(node, extended_attributes): assert len(node.GetChildren()) == 1 return FrozenArrayType( element_type=self._build_type(node.GetChildren()[0]), + extended_attributes=extended_attributes, debug_info=self._build_debug_info(node)) - def build_promise_type(node): + def build_promise_type(node, extended_attributes): assert len(node.GetChildren()) == 1 return PromiseType( result_type=self._build_type(node.GetChildren()[0]), + extended_attributes=extended_attributes, debug_info=self._build_debug_info(node)) - def build_union_type(node): - union_type = UnionType( - member_types=map(self._build_type, node.GetChildren())) - return union_type + def build_union_type(node, extended_attributes): + return UnionType( + member_types=map(self._build_type, node.GetChildren()), + extended_attributes=extended_attributes, + debug_info=self._build_debug_info(node)) - def build_record_type(node): + def build_record_type(node, extended_attributes): key_node, value_node = node.GetChildren() return RecordType( # idl_parser doesn't produce a 'Type' node for the key type, # hence we need to skip one level. - key_type=self._build_type_internal(key_node), + key_type=self._build_type_internal([key_node]), value_type=self._build_type(value_node), + extended_attributes=extended_attributes, debug_info=self._build_debug_info(node)) - def build_reference_type(node): + def build_reference_type(node, extended_attributes): identifier = node.GetName() - ref_type = ReferenceType( + return ReferenceType( ref_to_idl_type=self._create_ref_to_idl_type(identifier), + extended_attributes=extended_attributes, debug_info=self._build_debug_info(node)) - return ref_type - def build_sequence_type(node): + def build_sequence_type(node, extended_attributes): return SequenceType( element_type=self._build_type(node.GetChildren()[0]), + extended_attributes=extended_attributes, debug_info=self._build_debug_info(node)) - def build_simple_type(node): - type_name = node.GetName() - if type_name is None: + def build_simple_type(node, extended_attributes): + name = node.GetName() + if name is None: assert node.GetClass() == 'Any' - type_name = node.GetClass().lower() + name = node.GetClass().lower() if node.GetProperty('UNRESTRICTED'): - type_name = 'unrestricted ' + type_name + name = 'unrestricted {}'.format(name) return SimpleType( - name=type_name, debug_info=self._build_debug_info(node)) + name=name, + extended_attributes=extended_attributes, + debug_info=self._build_debug_info(node)) + + type_nodes = list(nodes) + extended_attributes = self._take_extended_attributes(type_nodes) + assert len(type_nodes) == 1 + body_node = type_nodes[0] build_functions = { 'Any': build_simple_type, @@ -296,7 +288,8 @@ 'Typeref': build_reference_type, 'UnionType': build_union_type, } - return build_functions[node.GetClass()](node) + return build_functions[body_node.GetClass()](body_node, + extended_attributes) def _take_and_build(self, node_class, build_func, node_list): """
diff --git a/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.cc b/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.cc index f41117d..2887146 100644 --- a/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.cc +++ b/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.cc
@@ -86,12 +86,14 @@ } CSSNumericValueType::CSSNumericValueType(CSSPrimitiveValue::UnitType unit) { + exponents_.Fill(0, kNumBaseTypes); if (unit != CSSPrimitiveValue::UnitType::kNumber) SetExponent(UnitTypeToBaseType(unit), 1); } CSSNumericValueType::CSSNumericValueType(int exponent, CSSPrimitiveValue::UnitType unit) { + exponents_.Fill(0, kNumBaseTypes); if (unit != CSSPrimitiveValue::UnitType::kNumber) SetExponent(UnitTypeToBaseType(unit), exponent); }
diff --git a/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.h b/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.h index 886f1a9..42c0311 100644 --- a/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.h +++ b/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.h
@@ -7,8 +7,6 @@ #include "third_party/blink/renderer/core/css/css_primitive_value.h" -#include <array> - namespace blink { // Represents the type of a CSSNumericValue, which is a map of base types to @@ -93,7 +91,7 @@ return num_non_zero_entries_ == 1 && Exponent(base_type) == value; } - std::array<int, kNumBaseTypes> exponents_{}; // zero-initialize + Vector<int, kNumBaseTypes> exponents_; BaseType percent_hint_ = BaseType::kPercent; bool has_percent_hint_ = false; unsigned num_non_zero_entries_ = 0;
diff --git a/third_party/blink/renderer/core/dom/events/event_target.h b/third_party/blink/renderer/core/dom/events/event_target.h index 35a4470..6b48c93 100644 --- a/third_party/blink/renderer/core/dom/events/event_target.h +++ b/third_party/blink/renderer/core/dom/events/event_target.h
@@ -114,8 +114,6 @@ // or the document you're in. // - Your trace() method will need to call EventTargetWithInlineData::trace // depending on the base class of your class. -// - EventTargets do not support EAGERLY_FINALIZE. You need to use -// a pre-finalizer instead. class CORE_EXPORT EventTarget : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO();
diff --git a/third_party/blink/renderer/core/events/event_type_names.json5 b/third_party/blink/renderer/core/events/event_type_names.json5 index f115ea22..2ed6257 100644 --- a/third_party/blink/renderer/core/events/event_type_names.json5 +++ b/third_party/blink/renderer/core/events/event_type_names.json5
@@ -145,6 +145,7 @@ "gotpointercapture", "hashchange", "icecandidate", + "icecandidateerror", "iceconnectionstatechange", "icegatheringstatechange", "inactive",
diff --git a/third_party/blink/renderer/core/exported/local_frame_client_impl.cc b/third_party/blink/renderer/core/exported/local_frame_client_impl.cc index 86b5b05..d9d01c6 100644 --- a/third_party/blink/renderer/core/exported/local_frame_client_impl.cc +++ b/third_party/blink/renderer/core/exported/local_frame_client_impl.cc
@@ -759,10 +759,10 @@ } } -void LocalFrameClientImpl::DidObserveLayoutJank(double jank_fraction, - bool after_input_or_scroll) { +void LocalFrameClientImpl::DidObserveLayoutShift(double score, + bool after_input_or_scroll) { if (WebLocalFrameClient* client = web_frame_->Client()) - client->DidObserveLayoutJank(jank_fraction, after_input_or_scroll); + client->DidObserveLayoutShift(score, after_input_or_scroll); } void LocalFrameClientImpl::DidObserveLazyLoadBehavior(
diff --git a/third_party/blink/renderer/core/exported/local_frame_client_impl.h b/third_party/blink/renderer/core/exported/local_frame_client_impl.h index 7cc44113..991a32bf 100644 --- a/third_party/blink/renderer/core/exported/local_frame_client_impl.h +++ b/third_party/blink/renderer/core/exported/local_frame_client_impl.h
@@ -150,8 +150,7 @@ void DidObserveLoadingBehavior(WebLoadingBehaviorFlag) override; void DidObserveNewFeatureUsage(mojom::WebFeature) override; void DidObserveNewCssPropertyUsage(int, bool) override; - void DidObserveLayoutJank(double jank_fraction, - bool after_input_or_scroll) override; + void DidObserveLayoutShift(double score, bool after_input_or_scroll) override; void DidObserveLazyLoadBehavior( WebLocalFrameClient::LazyLoadBehavior lazy_load_behavior) override; bool ShouldTrackUseCounter(const KURL&) override;
diff --git a/third_party/blink/renderer/core/fetch/DEPS b/third_party/blink/renderer/core/fetch/DEPS index 3c497b0..15b3d08 100644 --- a/third_party/blink/renderer/core/fetch/DEPS +++ b/third_party/blink/renderer/core/fetch/DEPS
@@ -4,4 +4,5 @@ "+mojo/public/cpp/bindings/binding_set.h", "+mojo/public/cpp/system/data_pipe.h", "+mojo/public/cpp/system/simple_watcher.h", + "+net/base/request_priority.h", ]
diff --git a/third_party/blink/renderer/core/fetch/fetch_request_data.cc b/third_party/blink/renderer/core/fetch/fetch_request_data.cc index baabcbb..24fa093 100644 --- a/third_party/blink/renderer/core/fetch/fetch_request_data.cc +++ b/third_party/blink/renderer/core/fetch/fetch_request_data.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/fetch/fetch_request_data.h" +#include "net/base/request_priority.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_http_body.h" #include "third_party/blink/public/platform/web_url_request.h" @@ -19,34 +20,30 @@ #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h" #include "third_party/blink/renderer/platform/network/http_names.h" -namespace mojo { +namespace { -template <> -struct TypeConverter<::blink::ResourceLoadPriority, - network::mojom::blink::RequestPriority> { - static ::blink::ResourceLoadPriority Convert( - network::mojom::blink::RequestPriority priority) { - switch (priority) { - case network::mojom::blink::RequestPriority::kThrottled: - break; - case network::mojom::blink::RequestPriority::kIdle: - return ::blink::ResourceLoadPriority::kVeryLow; - case network::mojom::blink::RequestPriority::kLowest: - return ::blink::ResourceLoadPriority::kLow; - case network::mojom::blink::RequestPriority::kLow: - return ::blink::ResourceLoadPriority::kMedium; - case network::mojom::blink::RequestPriority::kMedium: - return ::blink::ResourceLoadPriority::kHigh; - case network::mojom::blink::RequestPriority::kHighest: - return ::blink::ResourceLoadPriority::kVeryHigh; - } - - NOTREACHED() << priority; - return blink::ResourceLoadPriority::kUnresolved; +::blink::ResourceLoadPriority ConvertRequestPriorityToResourceLoadPriority( + net::RequestPriority priority) { + switch (priority) { + case net::RequestPriority::THROTTLED: + break; + case net::RequestPriority::IDLE: + return ::blink::ResourceLoadPriority::kVeryLow; + case net::RequestPriority::LOWEST: + return ::blink::ResourceLoadPriority::kLow; + case net::RequestPriority::LOW: + return ::blink::ResourceLoadPriority::kMedium; + case net::RequestPriority::MEDIUM: + return ::blink::ResourceLoadPriority::kHigh; + case net::RequestPriority::HIGHEST: + return ::blink::ResourceLoadPriority::kVeryHigh; } -}; -} // namespace mojo + NOTREACHED() << priority; + return blink::ResourceLoadPriority::kUnresolved; +} + +} // namespace namespace blink { @@ -123,7 +120,7 @@ request->SetKeepalive(fetch_api_request.keepalive); request->SetIsHistoryNavigation(fetch_api_request.is_history_navigation); request->SetPriority( - mojo::ConvertTo<ResourceLoadPriority>(fetch_api_request.priority)); + ConvertRequestPriorityToResourceLoadPriority(fetch_api_request.priority)); if (fetch_api_request.fetch_window_id) request->SetWindowId(fetch_api_request.fetch_window_id.value()); return request;
diff --git a/third_party/blink/renderer/core/frame/local_frame_client.h b/third_party/blink/renderer/core/frame/local_frame_client.h index cc8c55e..f3845a6 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client.h +++ b/third_party/blink/renderer/core/frame/local_frame_client.h
@@ -245,8 +245,8 @@ bool /*is_animated*/) {} // Reports that visible elements in the frame shifted (bit.ly/lsm-explainer). - virtual void DidObserveLayoutJank(double jank_fraction, - bool after_input_or_scroll) {} + virtual void DidObserveLayoutShift(double score, bool after_input_or_scroll) { + } // Reports lazy loaded behavior when the frame or image is fully deferred or // if the frame or image is loaded after being deferred. Called every time the
diff --git a/third_party/blink/renderer/core/frame/root_frame_viewport.cc b/third_party/blink/renderer/core/frame/root_frame_viewport.cc index 39fd4ba5..03ae36bed 100644 --- a/third_party/blink/renderer/core/frame/root_frame_viewport.cc +++ b/third_party/blink/renderer/core/frame/root_frame_viewport.cc
@@ -291,7 +291,7 @@ PhysicalRect rect_in_document = rect_in_absolute; rect_in_document.Move( - PhysicalOffset::FromFloatSizeRound(LayoutViewport().GetScrollOffset())); + PhysicalOffset::FromFloatSizeFloor(LayoutViewport().GetScrollOffset())); ScrollOffset new_scroll_offset = ClampScrollOffset(ScrollAlignment::GetScrollOffsetToExpose(
diff --git a/third_party/blink/renderer/core/frame/visual_viewport.cc b/third_party/blink/renderer/core/frame/visual_viewport.cc index 6cd0184e..51ca341 100644 --- a/third_party/blink/renderer/core/frame/visual_viewport.cc +++ b/third_party/blink/renderer/core/frame/visual_viewport.cc
@@ -1207,7 +1207,7 @@ return value; } -void VisualViewport::PreFinalize() { +void VisualViewport::DisposeImpl() { root_transform_layer_.reset(); inner_viewport_container_layer_.reset(); overscroll_elasticity_layer_.reset(); @@ -1226,6 +1226,7 @@ scroll_node_.reset(); horizontal_scrollbar_effect_node_.reset(); vertical_scrollbar_effect_node_.reset(); + ScrollableArea::DisposeImpl(); } } // namespace blink
diff --git a/third_party/blink/renderer/core/frame/visual_viewport.h b/third_party/blink/renderer/core/frame/visual_viewport.h index 5c99383..2406019a 100644 --- a/third_party/blink/renderer/core/frame/visual_viewport.h +++ b/third_party/blink/renderer/core/frame/visual_viewport.h
@@ -274,7 +274,7 @@ void SetNeedsPaintPropertyUpdate() { needs_paint_property_update_ = true; } bool NeedsPaintPropertyUpdate() const { return needs_paint_property_update_; } - void PreFinalize() override; + void DisposeImpl() override; private: bool DidSetScaleOrLocation(float scale,
diff --git a/third_party/blink/renderer/core/frame/visual_viewport_test.cc b/third_party/blink/renderer/core/frame/visual_viewport_test.cc index 4a48109..cb0714bf 100644 --- a/third_party/blink/renderer/core/frame/visual_viewport_test.cc +++ b/third_party/blink/renderer/core/frame/visual_viewport_test.cc
@@ -1264,8 +1264,13 @@ kProgrammaticScroll); inputBox->scrollIntoViewIfNeeded(false); - EXPECT_EQ(ScrollOffset(0, 900), - layout_viewport_scrollable_area->GetScrollOffset()); + if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) { + EXPECT_EQ(ScrollOffset(0, 900.75), + layout_viewport_scrollable_area->GetScrollOffset()); + } else { + EXPECT_EQ(ScrollOffset(0, 900), + layout_viewport_scrollable_area->GetScrollOffset()); + } EXPECT_EQ(FloatSize(250.25f, 100.25f), visual_viewport.GetScrollOffset()); // Change the fractional part of the frameview to one that would round down. @@ -1273,8 +1278,13 @@ kProgrammaticScroll); inputBox->scrollIntoViewIfNeeded(false); - EXPECT_EQ(ScrollOffset(0, 900), - layout_viewport_scrollable_area->GetScrollOffset()); + if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) { + EXPECT_EQ(ScrollOffset(0, 900.125), + layout_viewport_scrollable_area->GetScrollOffset()); + } else { + EXPECT_EQ(ScrollOffset(0, 900), + layout_viewport_scrollable_area->GetScrollOffset()); + } EXPECT_EQ(FloatSize(250.25f, 100.25f), visual_viewport.GetScrollOffset()); // Repeat both tests above with the visual viewport at a high fractional. @@ -1283,8 +1293,13 @@ kProgrammaticScroll); inputBox->scrollIntoViewIfNeeded(false); - EXPECT_EQ(ScrollOffset(0, 900), - layout_viewport_scrollable_area->GetScrollOffset()); + if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) { + EXPECT_EQ(ScrollOffset(0, 900.75), + layout_viewport_scrollable_area->GetScrollOffset()); + } else { + EXPECT_EQ(ScrollOffset(0, 900), + layout_viewport_scrollable_area->GetScrollOffset()); + } EXPECT_EQ(FloatSize(250.875f, 100.875f), visual_viewport.GetScrollOffset()); // Change the fractional part of the frameview to one that would round down. @@ -1292,8 +1307,13 @@ kProgrammaticScroll); inputBox->scrollIntoViewIfNeeded(false); - EXPECT_EQ(ScrollOffset(0, 900), - layout_viewport_scrollable_area->GetScrollOffset()); + if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) { + EXPECT_EQ(ScrollOffset(0, 900.125), + layout_viewport_scrollable_area->GetScrollOffset()); + } else { + EXPECT_EQ(ScrollOffset(0, 900), + layout_viewport_scrollable_area->GetScrollOffset()); + } EXPECT_EQ(FloatSize(250.875f, 100.875f), visual_viewport.GetScrollOffset()); // Both viewports with a 0.5 fraction. @@ -1302,8 +1322,13 @@ kProgrammaticScroll); inputBox->scrollIntoViewIfNeeded(false); - EXPECT_EQ(ScrollOffset(0, 900), - layout_viewport_scrollable_area->GetScrollOffset()); + if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) { + EXPECT_EQ(ScrollOffset(0, 900.5), + layout_viewport_scrollable_area->GetScrollOffset()); + } else { + EXPECT_EQ(ScrollOffset(0, 900), + layout_viewport_scrollable_area->GetScrollOffset()); + } EXPECT_EQ(FloatSize(250.5f, 100.5f), visual_viewport.GetScrollOffset()); }
diff --git a/third_party/blink/renderer/core/html/image_document_test.cc b/third_party/blink/renderer/core/html/image_document_test.cc index 62a71b0b..23d0f6a 100644 --- a/third_party/blink/renderer/core/html/image_document_test.cc +++ b/third_party/blink/renderer/core/html/image_document_test.cc
@@ -236,16 +236,26 @@ GetDocument().ImageClicked(15, 27); ScrollOffset offset = GetDocument().GetFrame()->View()->LayoutViewport()->GetScrollOffset(); - EXPECT_EQ(22, offset.Width()); - EXPECT_EQ(42, offset.Height()); + if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) { + EXPECT_EQ(22.5f, offset.Width()); + EXPECT_EQ(42, offset.Height()); + } else { + EXPECT_EQ(22, offset.Width()); + EXPECT_EQ(42, offset.Height()); + } GetDocument().ImageClicked(20, 20); GetDocument().ImageClicked(12, 15); offset = GetDocument().GetFrame()->View()->LayoutViewport()->GetScrollOffset(); - EXPECT_EQ(11, offset.Width()); - EXPECT_EQ(22, offset.Height()); + if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) { + EXPECT_EQ(11.25f, offset.Width()); + EXPECT_EQ(22.5f, offset.Height()); + } else { + EXPECT_EQ(11, offset.Width()); + EXPECT_EQ(22, offset.Height()); + } } class ImageDocumentViewportTest : public SimTest {
diff --git a/third_party/blink/renderer/core/html/resources/controls_refresh.css b/third_party/blink/renderer/core/html/resources/controls_refresh.css new file mode 100644 index 0000000..69b6bb18 --- /dev/null +++ b/third_party/blink/renderer/core/html/resources/controls_refresh.css
@@ -0,0 +1,23 @@ +/* Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +/* These styles adjust the default styling for HTML elements as defined in + * core/html/resources/html.css in order to provide an updated style when + * using the refreshed controls UI. + */ + +input, textarea { + background-color: #ffffff; + border-color: #cecece; +} + +input:hover, textarea:hover { + border-color: #9d9d9d; +} + +input:disabled, textarea:disabled { + background-color: #ffffff; + border-color: #c5c5c5; +}
diff --git a/third_party/blink/renderer/core/input/mouse_event_manager.cc b/third_party/blink/renderer/core/input/mouse_event_manager.cc index 3808111c..6049b4db 100644 --- a/third_party/blink/renderer/core/input/mouse_event_manager.cc +++ b/third_party/blink/renderer/core/input/mouse_event_manager.cc
@@ -393,10 +393,9 @@ } void MouseEventManager::RecomputeMouseHoverStateIfNeeded() { - // |RecomputeMouseHoverState| may set |hover_state_dirty_| to be true. if (HoverStateDirty()) { - hover_state_dirty_ = false; RecomputeMouseHoverState(); + hover_state_dirty_ = false; } }
diff --git a/third_party/blink/renderer/core/inspector/browser_protocol.pdl b/third_party/blink/renderer/core/inspector/browser_protocol.pdl index 03f4a84..d174271a 100644 --- a/third_party/blink/renderer/core/inspector/browser_protocol.pdl +++ b/third_party/blink/renderer/core/inspector/browser_protocol.pdl
@@ -4754,6 +4754,8 @@ DOM.NodeId nodeId # Whether to include distance info. optional boolean includeDistance + # Whether to include style info. + optional boolean includeStyle returns # Highlight data for the node. object highlight
diff --git a/third_party/blink/renderer/core/inspector/inspector_highlight.cc b/third_party/blink/renderer/core/inspector/inspector_highlight.cc index f92775a9..bee7c0b 100644 --- a/third_party/blink/renderer/core/inspector/inspector_highlight.cc +++ b/third_party/blink/renderer/core/inspector/inspector_highlight.cc
@@ -201,9 +201,9 @@ const InspectorHighlightContrastInfo& node_contrast) { std::unique_ptr<protocol::DictionaryValue> computed_style = protocol::DictionaryValue::create(); - CSSStyleDeclaration* style = + CSSComputedStyleDeclaration* style = MakeGarbageCollected<CSSComputedStyleDeclaration>(node, true); - Vector<AtomicString> properties; + Vector<CSSPropertyID> properties; // For text nodes, we can show color & font properties. bool has_text_children = false; @@ -212,25 +212,26 @@ has_text_children = child->IsTextNode(); } if (has_text_children) { - properties.push_back("color"); - properties.push_back("font-family"); - properties.push_back("font-size"); - properties.push_back("line-height"); + properties.push_back(CSSPropertyID::kColor); + properties.push_back(CSSPropertyID::kFontFamily); + properties.push_back(CSSPropertyID::kFontSize); + properties.push_back(CSSPropertyID::kLineHeight); } - properties.push_back("padding"); - properties.push_back("margin"); - properties.push_back("background-color"); + properties.push_back(CSSPropertyID::kPadding); + properties.push_back(CSSPropertyID::kMargin); + properties.push_back(CSSPropertyID::kBackgroundColor); for (size_t i = 0; i < properties.size(); ++i) { - const CSSValue* value = style->GetPropertyCSSValueInternal(properties[i]); + const CSSValue* value = style->GetPropertyCSSValue(properties[i]); if (!value) continue; + AtomicString name = CSSPropertyName(properties[i]).ToAtomicString(); if (value->IsColorValue()) { Color color = static_cast<const cssvalue::CSSColorValue*>(value)->Value(); - computed_style->setString(properties[i], ToHEXA(color)); + computed_style->setString(name, ToHEXA(color)); } else { - computed_style->setString(properties[i], value->CssText()); + computed_style->setString(name, value->CssText()); } } element_info->setValue("style", std::move(computed_style)); @@ -479,11 +480,11 @@ if (!layout_object) return; - CSSStyleDeclaration* style = + CSSComputedStyleDeclaration* style = MakeGarbageCollected<CSSComputedStyleDeclaration>(node, true); for (size_t i = 0; i < style->length(); ++i) { AtomicString name(style->item(i)); - const CSSValue* value = style->GetPropertyCSSValueInternal(name); + const CSSValue* value = style->GetPropertyCSSValue(cssPropertyID(name)); if (!value) continue; if (value->IsColorValue()) {
diff --git a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc index ba4ae345..1913052 100644 --- a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc
@@ -619,6 +619,7 @@ Response InspectorOverlayAgent::getHighlightObjectForTest( int node_id, Maybe<bool> include_distance, + Maybe<bool> include_style, std::unique_ptr<protocol::DictionaryValue>* result) { Node* node = nullptr; Response response = dom_agent_->AssertNode(node_id, node); @@ -634,10 +635,12 @@ is_locked_ancestor = true; } - InspectorHighlight highlight( - node, InspectorHighlight::DefaultConfig(), - InspectorHighlightContrastInfo(), true /* append_element_info */, - include_distance.fromMaybe(false), is_locked_ancestor); + InspectorHighlightConfig config = InspectorHighlight::DefaultConfig(); + config.show_styles = include_style.fromMaybe(false); + InspectorHighlight highlight(node, config, InspectorHighlightContrastInfo(), + true /* append_element_info */, + include_distance.fromMaybe(false), + is_locked_ancestor); *result = highlight.AsProtocolValue(); return Response::OK(); }
diff --git a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h index fb989f3..4abc8d7c 100644 --- a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h +++ b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h
@@ -158,6 +158,7 @@ protocol::Response getHighlightObjectForTest( int node_id, protocol::Maybe<bool> include_distance, + protocol::Maybe<bool> include_style, std::unique_ptr<protocol::DictionaryValue>* highlight) override; // InspectorBaseAgent overrides.
diff --git a/third_party/blink/renderer/core/layout/geometry/physical_offset.h b/third_party/blink/renderer/core/layout/geometry/physical_offset.h index e4fc8c2..f435b7ec 100644 --- a/third_party/blink/renderer/core/layout/geometry/physical_offset.h +++ b/third_party/blink/renderer/core/layout/geometry/physical_offset.h
@@ -105,6 +105,10 @@ return {LayoutUnit::FromFloatRound(point.X()), LayoutUnit::FromFloatRound(point.Y())}; } + static PhysicalOffset FromFloatSizeFloor(const FloatSize& size) { + return {LayoutUnit::FromFloatFloor(size.Width()), + LayoutUnit::FromFloatFloor(size.Height())}; + } static PhysicalOffset FromFloatSizeRound(const FloatSize& size) { return {LayoutUnit::FromFloatRound(size.Width()), LayoutUnit::FromFloatRound(size.Height())};
diff --git a/third_party/blink/renderer/core/layout/layout_shift_tracker.cc b/third_party/blink/renderer/core/layout/layout_shift_tracker.cc index e4eaa6d..bb79f48 100644 --- a/third_party/blink/renderer/core/layout/layout_shift_tracker.cc +++ b/third_party/blink/renderer/core/layout/layout_shift_tracker.cc
@@ -332,8 +332,8 @@ weighted_score_ += weighted_jank_fraction; if (RuntimeEnabledFeatures::LayoutInstabilityMoveDistanceEnabled()) weighted_jank_fraction *= move_distance_factor; - frame.Client()->DidObserveLayoutJank(weighted_jank_fraction, - observed_input_or_scroll_); + frame.Client()->DidObserveLayoutShift(weighted_jank_fraction, + observed_input_or_scroll_); } }
diff --git a/third_party/blink/renderer/core/layout/layout_theme_default.cc b/third_party/blink/renderer/core/layout/layout_theme_default.cc index 327fe540..5baf5bee 100644 --- a/third_party/blink/renderer/core/layout/layout_theme_default.cc +++ b/third_party/blink/renderer/core/layout/layout_theme_default.cc
@@ -94,13 +94,18 @@ ? GetDataResourceAsASCIIString("input_multiple_fields.css") : String(); String windows_style_sheet = GetDataResourceAsASCIIString("win.css"); + String controls_refresh_style_sheet = + RuntimeEnabledFeatures::FormControlsRefreshEnabled() + ? GetDataResourceAsASCIIString("controls_refresh.css") + : String(); StringBuilder builder; - builder.ReserveCapacity(extra_style_sheet.length() + - multiple_fields_style_sheet.length() + - windows_style_sheet.length()); + builder.ReserveCapacity( + extra_style_sheet.length() + multiple_fields_style_sheet.length() + + windows_style_sheet.length() + controls_refresh_style_sheet.length()); builder.Append(extra_style_sheet); builder.Append(multiple_fields_style_sheet); builder.Append(windows_style_sheet); + builder.Append(controls_refresh_style_sheet); return builder.ToString(); }
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc index a499812f..3c104c0c 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc
@@ -503,6 +503,8 @@ DCHECK(line_info.IsEmptyLine() || !line_box_metrics.IsEmpty()) << "Non-empty lines must have a valid set of linebox metrics."; + bool is_empty_inline = Node().IsEmptyInline(); + // All children within the linebox are positioned relative to the baseline, // then shifted later using NGLineBoxFragmentBuilder::MoveInBlockDirection. LayoutUnit baseline_adjustment = @@ -533,10 +535,10 @@ // To correctly determine which "line" block-level out-of-flow positioned // object is placed on, we need to keep track of if there is any inline-level // content preceeding it. - bool has_preceeding_inline_level_content = false; + bool has_preceding_inline_level_content = false; for (NGLineBoxFragmentBuilder::Child& child : line_box_) { - has_preceeding_inline_level_content |= child.HasInFlowFragment(); + has_preceding_inline_level_content |= child.HasInFlowFragment(); LayoutObject* box = child.out_of_flow_positioned_box; if (!box) @@ -547,11 +549,20 @@ // An inline-level OOF element positions itself within the line, at the // position it would have been if it was in-flow. static_offset.inline_offset = child.offset.inline_offset; + + // The static-position of inline-level OOF-positioned nodes depends on + // previous floats (if any). + // + // If we are an empty-inline we may not have the correct BFC block-offset + // yet. Due to this we need to mark this node as having adjoining + // objects, and perform a re-layout if our position shifts. + if (is_empty_inline) + container_builder_.AddAdjoiningFloatTypes(kAdjoiningInlineOutOfFlow); } else { // A block-level OOF element positions itself on the "next" line. However // only shifts down if there is inline-level content. static_offset.inline_offset = block_level_inline_offset; - if (has_preceeding_inline_level_content) + if (has_preceding_inline_level_content) static_offset.block_offset += line_height; } @@ -798,11 +809,16 @@ unsigned handled_leading_floats_index = PositionLeadingFloats(&initial_exclusion_space, &leading_floats); + // Only empty-inlines should have the "forced" BFC block-offset set. + DCHECK(is_empty_inline || !ConstraintSpace().ForcedBfcBlockOffset()); + // We query all the layout opportunities on the initial exclusion space up // front, as if the line breaker may add floats and change the opportunities. const LayoutOpportunityVector opportunities = initial_exclusion_space.AllLayoutOpportunities( - ConstraintSpace().BfcOffset(), + {ConstraintSpace().BfcOffset().line_offset, + ConstraintSpace().ForcedBfcBlockOffset().value_or( + ConstraintSpace().BfcOffset().block_offset)}, ConstraintSpace().AvailableSize().inline_size); NGExclusionSpace exclusion_space; @@ -863,17 +879,19 @@ !opportunity.IsBlockDeltaBelowShapes(block_delta)) { block_delta += LayoutUnit(1); line_block_size = LayoutUnit(); - } else { - // We've either don't have any shapes, or run out of block-delta space - // to test, proceed to the next layout opportunity. + continue; + } + // We've either don't have any shapes, or run out of block-delta space + // to test, proceed to the next layout opportunity. + if (opportunities_it + 1 != opportunities.end()) { block_delta = LayoutUnit(); line_block_size = LayoutUnit(); ++opportunities_it; + continue; } - // There must be at least one more opportunity, or we fail to call - // |CreateLine()|. - DCHECK_NE(opportunities_it, opportunities.end()); - continue; + // Normally the last opportunity should fit the line, but arithmetic + // overflow can lead to failures for all opportunities. Just let the line + // to overflow in that case. } PrepareBoxStates(line_info, break_token); @@ -917,10 +935,6 @@ continue; } - if (opportunity.rect.BlockStartOffset() > - ConstraintSpace().BfcOffset().block_offset) - container_builder_.SetIsPushedByFloats(); - // Success! container_builder_.SetBreakToken(line_breaker.CreateBreakToken(line_info)); @@ -937,6 +951,10 @@ // our adjoining floats, and shouldn't propagate this information // to siblings. container_builder_.ResetAdjoiningFloatTypes(); + + if (opportunity.rect.BlockStartOffset() > + ConstraintSpace().BfcOffset().block_offset) + container_builder_.SetIsPushedByFloats(); } break; }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc index c918813..098d8d43 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc
@@ -803,10 +803,26 @@ static_offset.block_offset += previous_inflow_position.margin_strut.Sum(); if (child.Style().IsOriginalDisplayInlineType()) { + // The static-position of inline-level OOF-positioned nodes depends on + // previous floats (if any). + // + // Due to this we need to mark this node as having adjoining objects, and + // perform a re-layout if our position shifts. + if (!container_builder_.BfcBlockOffset()) { + container_builder_.AddAdjoiningFloatTypes(kAdjoiningInlineOutOfFlow); + abort_when_bfc_block_offset_updated_ = true; + } + + LayoutUnit origin_bfc_block_offset = + container_builder_.BfcBlockOffset().value_or( + ConstraintSpace().ForcedBfcBlockOffset().value_or( + ConstraintSpace().BfcOffset().block_offset)) + + static_offset.block_offset; + NGBfcOffset origin_bfc_offset = { ConstraintSpace().BfcOffset().line_offset + border_scrollbar_padding_.LineLeft(Style().Direction()), - BfcBlockOffset() + static_offset.block_offset}; + origin_bfc_block_offset}; static_offset.inline_offset += CalculateOutOfFlowStaticInlineLevelOffset( Style(), origin_bfc_offset, exclusion_space_,
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc index 4743312..986c3484 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc
@@ -1365,15 +1365,17 @@ offset = To<NGPhysicalLineBoxFragment>(linebox_fragment)->Children()[0].offset; - // inline 10 = left float's margin(10) + // The floats are positioned outside the line-box as the line-box is + // "avoiding" these floats. + // inline -35 = inline-size of left-float (including margins). // block 10 = left float's margin - EXPECT_THAT(offset, PhysicalOffset(10, 10)); + EXPECT_THAT(offset, PhysicalOffset(-35, 10)); offset = To<NGPhysicalLineBoxFragment>(linebox_fragment)->Children()[1].offset; - // inline offset 135 = right float's margin(10) + right float offset(125) + // inline offset 90 = right float's margin(10) + right float offset(80) // block offset 15 = right float's margin - LayoutUnit right_float_offset = LayoutUnit(125); + LayoutUnit right_float_offset = LayoutUnit(80); EXPECT_THAT(offset, PhysicalOffset(LayoutUnit(10) + right_float_offset, LayoutUnit(15)));
diff --git a/third_party/blink/renderer/core/layout/ng/ng_constraint_space.h b/third_party/blink/renderer/core/layout/ng/ng_constraint_space.h index eb15eef..0464c66e 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_constraint_space.h +++ b/third_party/blink/renderer/core/layout/ng/ng_constraint_space.h
@@ -580,7 +580,7 @@ } unsigned has_rare_data : 1; - unsigned adjoining_floats : 2; // NGFloatTypes + unsigned adjoining_floats : 3; // NGFloatTypes unsigned writing_mode : 3; unsigned direction : 1;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_floats_utils.h b/third_party/blink/renderer/core/layout/ng/ng_floats_utils.h index 76d91b1..1b6d9cb 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_floats_utils.h +++ b/third_party/blink/renderer/core/layout/ng/ng_floats_utils.h
@@ -23,11 +23,13 @@ typedef Vector<NGPositionedFloat, 8> NGPositionedFloatVector; +// TODO(ikilpatrick): Rename this to NGAdjoiningObjectTypes. enum NGFloatTypeValue { - kFloatTypeNone = 0b00, - kFloatTypeLeft = 0b01, - kFloatTypeRight = 0b10, - kFloatTypeBoth = 0b11 + kFloatTypeNone = 0b000, + kFloatTypeLeft = 0b001, + kFloatTypeRight = 0b010, + kFloatTypeBoth = 0b011, + kAdjoiningInlineOutOfFlow = 0b100 }; typedef int NGFloatTypes;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_result.h b/third_party/blink/renderer/core/layout/ng/ng_layout_result.h index 9416d55f..6bc0c33 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_result.h +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_result.h
@@ -329,7 +329,7 @@ unsigned is_self_collapsing : 1; unsigned is_pushed_by_floats : 1; - unsigned adjoining_floats : 2; // NGFloatTypes + unsigned adjoining_floats : 3; // NGFloatTypes unsigned is_initial_block_size_indefinite : 1; unsigned has_descendant_that_depends_on_percentage_block_size : 1;
diff --git a/third_party/blink/renderer/core/loader/DEPS b/third_party/blink/renderer/core/loader/DEPS new file mode 100644 index 0000000..0d1f45e --- /dev/null +++ b/third_party/blink/renderer/core/loader/DEPS
@@ -0,0 +1,5 @@ +specific_include_rules = { + "alternate_signed_exchange_resource_info.cc" : [ + "+net/http/http_request_headers.h" + ], +}
diff --git a/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.cc b/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.cc index 5867f426..96ab51b7 100644 --- a/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.cc +++ b/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.cc
@@ -4,8 +4,11 @@ #include "third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h" +#include "net/http/http_request_headers.h" #include "third_party/blink/public/common/web_package/signed_exchange_consts.h" +#include "third_party/blink/public/common/web_package/signed_exchange_request_matcher.h" #include "third_party/blink/public/platform/web_url.h" +#include "third_party/blink/renderer/platform/loader/fetch/resource.h" #include "third_party/blink/renderer/platform/loader/link_header.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/wtf/hash_functions.h" @@ -18,6 +21,12 @@ constexpr char kAlternate[] = "alternate"; constexpr char kAllowedAltSxg[] = "allowed-alt-sxg"; +// These accept header values are also defined in web_url_loader_impl.h and +// loader_util.h. TODO(horo): Move somewhere and use shared constant value. +const char kDefaultAcceptHeader[] = "*/*"; +const char kStylesheetAcceptHeader[] = "text/css,*/*;q=0.1"; +const char kImageAcceptHeader[] = "image/webp,image/apng,image/*,*/*;q=0.8"; + using AlternateSignedExchangeMachingKey = std::pair<String /* anchor */, std::pair<String /* variants */, String /* variant_key */>>; @@ -113,12 +122,67 @@ : alternative_resources_(std::move(alternative_resources)) {} AlternateSignedExchangeResourceInfo::Entry* -AlternateSignedExchangeResourceInfo::FindMatchingEntry(const KURL& url) const { +AlternateSignedExchangeResourceInfo::FindMatchingEntry( + const KURL& url, + base::Optional<ResourceType> resource_type, + const Vector<String>& languages) const { + const char* accept_header = kDefaultAcceptHeader; + if (resource_type == ResourceType::kCSSStyleSheet) { + accept_header = kStylesheetAcceptHeader; + } else if (resource_type == ResourceType::kImage) { + accept_header = kImageAcceptHeader; + } + return FindMatchingEntry(url, accept_header, languages); +} + +AlternateSignedExchangeResourceInfo::Entry* +AlternateSignedExchangeResourceInfo::FindMatchingEntry( + const KURL& url, + mojom::RequestContextType request_context, + const Vector<String>& languages) const { + const char* accept_header = kDefaultAcceptHeader; + if (request_context == mojom::RequestContextType::STYLE) { + accept_header = kStylesheetAcceptHeader; + } else if (request_context == mojom::RequestContextType::IMAGE) { + accept_header = kImageAcceptHeader; + } + return FindMatchingEntry(url, accept_header, languages); +} + +AlternateSignedExchangeResourceInfo::Entry* +AlternateSignedExchangeResourceInfo::FindMatchingEntry( + const KURL& url, + const char* accept_header, + const Vector<String>& languages) const { const auto it = alternative_resources_.find(url); if (it == alternative_resources_.end()) return nullptr; - // TODO(crbug.com/935267): Support variants and variant_key checking. - return it->value.back().get(); + const Vector<std::unique_ptr<Entry>>& entries = it->value; + DCHECK(!entries.IsEmpty()); + if (entries[0]->variants().IsNull()) + return entries[0].get(); + + const std::string variants = entries[0]->variants().Utf8(); + std::vector<std::string> variant_keys_list; + for (const auto& entry : entries) { + variant_keys_list.emplace_back(entry->variant_key().Utf8()); + } + std::string accept_langs; + for (const auto& language : languages) { + if (!accept_langs.empty()) + accept_langs += ","; + accept_langs += language.Utf8(); + } + net::HttpRequestHeaders request_headers; + request_headers.SetHeader("accept", accept_header); + + SignedExchangeRequestMatcher matcher(request_headers, accept_langs); + const auto variant_keys_list_it = + matcher.FindBestMatchingVariantKey(variants, variant_keys_list); + if (variant_keys_list_it == variant_keys_list.end()) + return nullptr; + return (entries.begin() + (variant_keys_list_it - variant_keys_list.begin())) + ->get(); } } // namespace blink
diff --git a/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h b/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h index 15ef7f2..c1fe8c0 100644 --- a/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h +++ b/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h
@@ -6,6 +6,8 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_ALTERNATE_SIGNED_EXCHANGE_RESOURCE_INFO_H_ #include "base/macros.h" +#include "base/optional.h" +#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/weborigin/kurl_hash.h" @@ -16,6 +18,8 @@ namespace blink { +enum class ResourceType : uint8_t; + // AlternateSignedExchangeResourceInfo keeps the alternate signed exchange // resource information which is extracted from "alternate" link headers in the // outer response and "allowed-alt-sxg" link headers in the inner response while @@ -91,14 +95,27 @@ AlternateSignedExchangeResourceInfo(EntryMap alternative_resources); ~AlternateSignedExchangeResourceInfo() = default; - // Returns the best matching alternate resource. Currently this method just - // returns the last one. TODO(crbug.com/935267): Support variants and - // variant_key checking. - Entry* FindMatchingEntry(const KURL& url) const; + // Returns the best matching alternate resource. If the first entry which + // |anchor_url| is |url| has non-null |variants| value, this method use the + // preference order of the result of "Cache Behaviour" [1] to find the best + // matching entry. Otherwise returns the first entry which |anchor_url| is + // |url|. + // [1] + // https://httpwg.org/http-extensions/draft-ietf-httpbis-variants.html#cache + Entry* FindMatchingEntry(const KURL& url, + base::Optional<ResourceType> resource_type, + const Vector<String>& languages) const; + Entry* FindMatchingEntry(const KURL& url, + mojom::RequestContextType request_context, + const Vector<String>& languages) const; private: friend class AlternateSignedExchangeResourceInfoTest; + Entry* FindMatchingEntry(const KURL& url, + const char* accept_header, + const Vector<String>& languages) const; + const EntryMap alternative_resources_; DISALLOW_COPY_AND_ASSIGN(AlternateSignedExchangeResourceInfo);
diff --git a/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info_test.cc b/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info_test.cc index 31ca25451..9ac6dbb 100644 --- a/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info_test.cc +++ b/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info_test.cc
@@ -63,10 +63,12 @@ EXPECT_TRUE(resource->variants().IsEmpty()); EXPECT_TRUE(resource->variant_key().IsEmpty()); - EXPECT_EQ(resource.get(), info->FindMatchingEntry( - KURL("https://publisher.example/script.js"))); + EXPECT_EQ(resource.get(), + info->FindMatchingEntry(KURL("https://publisher.example/script.js"), + base::nullopt, {"en"})); EXPECT_EQ(nullptr, - info->FindMatchingEntry(KURL("https://publisher.example/image"))); + info->FindMatchingEntry(KURL("https://publisher.example/image"), + base::nullopt, {"en"})); } TEST_F(AlternateSignedExchangeResourceInfoTest, MultipleResources) { @@ -110,7 +112,8 @@ EXPECT_TRUE(resource->variants().IsEmpty()); EXPECT_TRUE(resource->variant_key().IsEmpty()); EXPECT_EQ(resource.get(), info->FindMatchingEntry( - KURL("https://publisher.example/script.js"))); + KURL("https://publisher.example/script.js"), + base::nullopt, {"en"})); } { const auto& it = entries.find(KURL("https://publisher.example/image")); @@ -125,7 +128,8 @@ EXPECT_TRUE(resource->variants().IsEmpty()); EXPECT_TRUE(resource->variant_key().IsEmpty()); EXPECT_EQ(resource.get(), - info->FindMatchingEntry(KURL("https://publisher.example/image"))); + info->FindMatchingEntry(KURL("https://publisher.example/image"), + base::nullopt, {"en"})); } } @@ -155,8 +159,9 @@ EXPECT_TRUE(resource->variants().IsEmpty()); EXPECT_TRUE(resource->variant_key().IsEmpty()); - EXPECT_EQ(resource.get(), info->FindMatchingEntry( - KURL("https://publisher.example/script.js"))); + EXPECT_EQ(resource.get(), + info->FindMatchingEntry(KURL("https://publisher.example/script.js"), + base::nullopt, {"en"})); } TEST_F(AlternateSignedExchangeResourceInfoTest, NoType) { @@ -188,10 +193,12 @@ EXPECT_TRUE(resource->variants().IsEmpty()); EXPECT_TRUE(resource->variant_key().IsEmpty()); - EXPECT_EQ(resource.get(), info->FindMatchingEntry( - KURL("https://publisher.example/script.js"))); + EXPECT_EQ(resource.get(), + info->FindMatchingEntry(KURL("https://publisher.example/script.js"), + base::nullopt, {"en"})); EXPECT_EQ(nullptr, - info->FindMatchingEntry(KURL("https://publisher.example/image"))); + info->FindMatchingEntry(KURL("https://publisher.example/image"), + base::nullopt, {"en"})); } TEST_F(AlternateSignedExchangeResourceInfoTest, InvalidOuterURL) { @@ -222,8 +229,9 @@ EXPECT_TRUE(resource->variants().IsEmpty()); EXPECT_TRUE(resource->variant_key().IsEmpty()); - EXPECT_EQ(resource.get(), info->FindMatchingEntry( - KURL("https://publisher.example/script.js"))); + EXPECT_EQ(resource.get(), + info->FindMatchingEntry(KURL("https://publisher.example/script.js"), + base::nullopt, {"en"})); } TEST_F(AlternateSignedExchangeResourceInfoTest, InvalidInnerURL) { @@ -249,27 +257,27 @@ "<https://distributor.example/publisher.example/image_jpeg.sxg>;" "rel=\"alternate\";" "type=\"application/signed-exchange;v=b3\";" - "variants-04=\"accept;image/jpeg,image/webp\";" + "variants-04=\"accept;image/jpeg;image/webp\";" "variant-key-04=\"image/jpeg\";" "anchor=\"https://publisher.example/image\";," // The second outer link header "<https://distributor.example/publisher.example/image_webp.sxg>;" "rel=\"alternate\";" "type=\"application/signed-exchange;v=b3\";" - "variants-04=\"accept;image/jpeg,image/webp\";" + "variants-04=\"accept;image/jpeg;image/webp\";" "variant-key-04=\"image/webp\";" "anchor=\"https://publisher.example/image\"", // The first inner link header "<https://publisher.example/image>;" "rel=\"allowed-alt-sxg\";" - "variants-04=\"accept;image/jpeg,image/webp\";" + "variants-04=\"accept;image/jpeg;image/webp\";" "variant-key-04=\"image/jpeg\";" "header-integrity=" "\"sha256-q1phjFcR+umcl0zBaEz6E5AGVlnc9yF0zOjDYi5c6aM=\"," // The second inner link header "<https://publisher.example/image>;" "rel=\"allowed-alt-sxg\";" - "variants-04=\"accept;image/jpeg,image/webp\";" + "variants-04=\"accept;image/jpeg;image/webp\";" "variant-key-04=\"image/webp\";" "header-integrity=" "\"sha256-KRcYU+BZK8Sb2ccJfDPz+uUKXDdB1PVToPugItdzRXY=\""); @@ -287,7 +295,7 @@ resource->alternative_url()); EXPECT_EQ("sha256-q1phjFcR+umcl0zBaEz6E5AGVlnc9yF0zOjDYi5c6aM=", resource->header_integrity()); - EXPECT_EQ("accept;image/jpeg,image/webp", resource->variants()); + EXPECT_EQ("accept;image/jpeg;image/webp", resource->variants()); EXPECT_EQ("image/jpeg", resource->variant_key()); } { @@ -298,13 +306,12 @@ resource->alternative_url()); EXPECT_EQ("sha256-KRcYU+BZK8Sb2ccJfDPz+uUKXDdB1PVToPugItdzRXY=", resource->header_integrity()); - EXPECT_EQ("accept;image/jpeg,image/webp", resource->variants()); + EXPECT_EQ("accept;image/jpeg;image/webp", resource->variants()); EXPECT_EQ("image/webp", resource->variant_key()); - // Currently FindMatchingEntry() just returns the last - // matching resource without checking variants and variant-key. - EXPECT_EQ(resource.get(), - info->FindMatchingEntry(KURL("https://publisher.example/image"))); + EXPECT_EQ(resource.get(), info->FindMatchingEntry( + KURL("https://publisher.example/image"), + mojom::RequestContextType::IMAGE, {"en"})); } }
diff --git a/third_party/blink/renderer/core/loader/document_loader.h b/third_party/blink/renderer/core/loader/document_loader.h index 772a994..e581fc1 100644 --- a/third_party/blink/renderer/core/loader/document_loader.h +++ b/third_party/blink/renderer/core/loader/document_loader.h
@@ -282,6 +282,10 @@ void SetLoadingJavaScriptUrl() { loading_url_as_javascript_ = true; } + WebURLRequest::PreviewsState previews_state() const { + return previews_state_; + } + protected: bool had_transient_activation() const { return had_transient_activation_; }
diff --git a/third_party/blink/renderer/core/loader/frame_fetch_context.cc b/third_party/blink/renderer/core/loader/frame_fetch_context.cc index 4aff35c..2f50275 100644 --- a/third_party/blink/renderer/core/loader/frame_fetch_context.cc +++ b/third_party/blink/renderer/core/loader/frame_fetch_context.cc
@@ -323,6 +323,10 @@ return document_loader->GetPreviewsResourceLoadingHints(); } +WebURLRequest::PreviewsState FrameFetchContext::previews_state() const { + return GetLocalFrameClient()->GetPreviewsStateForFrame(); +} + LocalFrame* FrameFetchContext::GetFrame() const { return &frame_or_imported_document_->GetFrame(); }
diff --git a/third_party/blink/renderer/core/loader/frame_fetch_context.h b/third_party/blink/renderer/core/loader/frame_fetch_context.h index cabf299..245079b 100644 --- a/third_party/blink/renderer/core/loader/frame_fetch_context.h +++ b/third_party/blink/renderer/core/loader/frame_fetch_context.h
@@ -130,6 +130,7 @@ SubresourceFilter* GetSubresourceFilter() const override; PreviewsResourceLoadingHints* GetPreviewsResourceLoadingHints() const override; + WebURLRequest::PreviewsState previews_state() const override; bool AllowScriptFromSource(const KURL&) const override; bool ShouldBlockRequestByInspector(const KURL&) const override; void DispatchDidBlockRequest(const ResourceRequest&,
diff --git a/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.cc b/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.cc index 8313c44..d65e705 100644 --- a/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.cc +++ b/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.cc
@@ -16,7 +16,9 @@ #include "third_party/blink/public/platform/web_url_loader_factory.h" #include "third_party/blink/public/platform/web_url_response.h" #include "third_party/blink/renderer/core/dom/document.h" +#include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/core/frame/navigator.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h" #include "third_party/blink/renderer/platform/loader/link_header.h" @@ -184,8 +186,9 @@ const WebURLRequest& request) { if (started_) return nullptr; - const auto* matching_resource = - alternative_resources_->FindMatchingEntry(request.Url()); + const auto* matching_resource = alternative_resources_->FindMatchingEntry( + request.Url(), request.GetRequestContext(), + frame_->DomWindow()->navigator()->languages()); if (!matching_resource) return nullptr; @@ -227,8 +230,9 @@ // arbitrary information to the publisher using this resource. continue; } - const auto* matching_resource = - alternative_resources_->FindMatchingEntry(loader->request().Url()); + const auto* matching_resource = alternative_resources_->FindMatchingEntry( + loader->request().Url(), loader->request().GetRequestContext(), + frame_->DomWindow()->navigator()->languages()); const auto alternative_url = matching_resource->alternative_url(); if (!alternative_url.IsValid()) { // There is no matching "alternate" link header in outer response header.
diff --git a/third_party/blink/renderer/core/loader/preload_helper.cc b/third_party/blink/renderer/core/loader/preload_helper.cc index 7c5fe741..984919eb 100644 --- a/third_party/blink/renderer/core/loader/preload_helper.cc +++ b/third_party/blink/renderer/core/loader/preload_helper.cc
@@ -12,7 +12,9 @@ #include "third_party/blink/renderer/core/css/parser/sizes_attribute_parser.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/frame/frame_console.h" +#include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/core/frame/navigator.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/frame/viewport_data.h" #include "third_party/blink/renderer/core/html/parser/html_preload_scanner.h" @@ -527,7 +529,8 @@ params.image_srcset, params.image_sizes); } const auto* alternative_resource = - alternate_resource_info->FindMatchingEntry(url); + alternate_resource_info->FindMatchingEntry( + url, resource_type, frame.DomWindow()->navigator()->languages()); if (alternative_resource && alternative_resource->alternative_url().IsValid()) { UseCounter::Count(document,
diff --git a/third_party/blink/renderer/core/loader/private/prerender_handle.cc b/third_party/blink/renderer/core/loader/private/prerender_handle.cc index 490c0d6..01aaa28 100644 --- a/third_party/blink/renderer/core/loader/private/prerender_handle.cc +++ b/third_party/blink/renderer/core/loader/private/prerender_handle.cc
@@ -69,7 +69,9 @@ PrerenderHandle::PrerenderHandle(Document& document, Prerender* prerender) : ContextLifecycleObserver(&document), prerender_(prerender) {} -PrerenderHandle::~PrerenderHandle() { +PrerenderHandle::~PrerenderHandle() = default; + +void PrerenderHandle::Dispose() { if (prerender_) { prerender_->Abandon(); Detach();
diff --git a/third_party/blink/renderer/core/loader/private/prerender_handle.h b/third_party/blink/renderer/core/loader/private/prerender_handle.h index f380c83..14ad87f 100644 --- a/third_party/blink/renderer/core/loader/private/prerender_handle.h +++ b/third_party/blink/renderer/core/loader/private/prerender_handle.h
@@ -46,6 +46,7 @@ class PrerenderHandle final : public GarbageCollectedFinalized<PrerenderHandle>, public ContextLifecycleObserver { USING_GARBAGE_COLLECTED_MIXIN(PrerenderHandle); + USING_PRE_FINALIZER(PrerenderHandle, Dispose); public: static PrerenderHandle* Create(Document&, @@ -55,6 +56,7 @@ PrerenderHandle(Document&, Prerender*); virtual ~PrerenderHandle(); + void Dispose(); void Cancel(); const KURL& Url() const; @@ -63,7 +65,6 @@ void ContextDestroyed(ExecutionContext*) override; void Trace(blink::Visitor*) override; - EAGERLY_FINALIZE(); private: void Detach();
diff --git a/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc b/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc index 9d3ade3..bdff8d67 100644 --- a/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc +++ b/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc
@@ -158,12 +158,12 @@ body { height: 4000px; } - h2 { + div { position: absolute; top: 3000px; } </style> - <h2 id="target">Target</h2> + <div id="target">Target</h2> )HTML"); main_resource.Finish(); css_resource.Complete(); @@ -174,7 +174,7 @@ test::RunPendingTasks(); ScrollableArea* layout_viewport = GetDocument().View()->LayoutViewport(); - EXPECT_EQ(3001, layout_viewport->GetScrollOffset().Height()); + EXPECT_EQ(3000, layout_viewport->GetScrollOffset().Height()); } } // namespace blink
diff --git a/third_party/blink/renderer/core/page/scrolling/scroll_into_view_test.cc b/third_party/blink/renderer/core/page/scrolling/scroll_into_view_test.cc index e3f98e4..02c528d 100644 --- a/third_party/blink/renderer/core/page/scrolling/scroll_into_view_test.cc +++ b/third_party/blink/renderer/core/page/scrolling/scroll_into_view_test.cc
@@ -171,7 +171,7 @@ Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(Window().scrollY(), 299); + ASSERT_NEAR(Window().scrollY(), 299, 1); // Finish scrolling the container Compositor().BeginFrame(1); @@ -207,7 +207,7 @@ Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(Window().scrollY(), 299); + ASSERT_NEAR(Window().scrollY(), 299, 1); ASSERT_EQ(container->scrollTop(), 0); // Finish scrolling the outer container @@ -218,7 +218,7 @@ // Scrolling the inner container Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(container->scrollTop(), 299); + ASSERT_NEAR(container->scrollTop(), 299, 1); // Finish scrolling the inner container Compositor().BeginFrame(1); @@ -261,14 +261,14 @@ Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(Window().scrollY(), 299); + ASSERT_NEAR(Window().scrollY(), 299, 1); ASSERT_EQ(container1->scrollTop(), 0); content2->scrollIntoView(arg); Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(Window().scrollY(), 61); + ASSERT_NEAR(Window().scrollY(), 61, 1); ASSERT_EQ(container1->scrollTop(), 0); // container1 should not scroll. Compositor().BeginFrame(1); @@ -278,7 +278,7 @@ // Scrolling content2 in container2 Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(container2->scrollTop(), 300); + ASSERT_NEAR(container2->scrollTop(), 300, 1); // Finish all the animation to make sure there is no another animation queued // on container1. @@ -320,7 +320,7 @@ Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(Window().scrollY(), 299); + ASSERT_NEAR(Window().scrollY(), 299, 1); ASSERT_EQ(container->scrollTop(), 0); ScrollToOptions* window_option = ScrollToOptions::Create(); @@ -331,7 +331,7 @@ Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(Window().scrollY(), 58); + ASSERT_NEAR(Window().scrollY(), 58, 1); Compositor().BeginFrame(1); ASSERT_EQ(Window().scrollY(), 0); @@ -435,7 +435,7 @@ Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(container->scrollTop(), 299); + ASSERT_NEAR(container->scrollTop(), 299, 1); // Finish scrolling the container Compositor().BeginFrame(1); @@ -468,7 +468,7 @@ Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(container->scrollTop(), 299); + ASSERT_NEAR(container->scrollTop(), 299, 1); // Finish scrolling the container Compositor().BeginFrame(1); @@ -521,7 +521,7 @@ Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(Window().scrollY(), 299); + ASSERT_NEAR(Window().scrollY(), 299, 1); // Finish scrolling the container Compositor().BeginFrame(1); @@ -687,7 +687,7 @@ Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(Window().scrollY(), 299); + ASSERT_NEAR(Window().scrollY(), 299, 1); // ProgrammaticScroll that could interrupt the current smooth scroll. Window().scrollTo(0, 0); @@ -722,7 +722,7 @@ Compositor().BeginFrame(); // update run_state_. Compositor().BeginFrame(); // Set start_time = now. Compositor().BeginFrame(0.2); - ASSERT_EQ(Window().scrollY(), 864); + ASSERT_NEAR(Window().scrollY(), 864, 1); // Finish scrolling the container Compositor().BeginFrame(2.8);
diff --git a/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc b/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc index 81cb9f09..de8180f 100644 --- a/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc
@@ -153,6 +153,19 @@ RegisterNotifySwapTime(); } +void ImagePaintTimingDetector::LayoutObjectWillBeDestroyed( + const LayoutObject& object) { + if (!is_recording_) + return; + + DOMNodeId node_id = DOMNodeIds::ExistingIdForNode(object.GetNode()); + if (node_id == kInvalidDOMNodeId) + return; + // The visible record removal has been handled by + // |NotifyBackgroundImageRemoved|. + records_manager_.RemoveInvisibleRecordIfNeeded(node_id); +} + void ImagePaintTimingDetector::NotifyBackgroundImageRemoved( DOMNodeId node_id, const ImageResourceContent* cached_image) { @@ -270,15 +283,6 @@ need_update_timing_at_frame_end_ = true; } } - - if (records_manager_.RecordedTooManyNodes()) - HandleTooManyNodes(); -} - -void ImagePaintTimingDetector::HandleTooManyNodes() { - TRACE_EVENT_INSTANT0("loading", "ImagePaintTimingDetector::OverNodeLimit", - TRACE_EVENT_SCOPE_THREAD); - StopRecordEntries(); } ImageRecordsManager::ImageRecordsManager() @@ -311,7 +315,6 @@ const DOMNodeId& node_id, const ImageResourceContent* cached_image, const uint64_t& visual_size) { - DCHECK(!RecordedTooManyNodes()); DCHECK_GT(visual_size, 0u); std::unique_ptr<ImageRecord> record = std::make_unique<ImageRecord>(node_id, cached_image, visual_size);
diff --git a/third_party/blink/renderer/core/paint/image_paint_timing_detector.h b/third_party/blink/renderer/core/paint/image_paint_timing_detector.h index d54612a..526d38b3 100644 --- a/third_party/blink/renderer/core/paint/image_paint_timing_detector.h +++ b/third_party/blink/renderer/core/paint/image_paint_timing_detector.h
@@ -68,16 +68,15 @@ std::set<base::WeakPtr<ImageRecord>, NodesQueueComparator>; public: - // Set a big enough limit for the number of nodes to ensure memory usage is - // capped. Exceeding such limit will make the detactor stops recording - // entries. - static constexpr size_t kImageNodeNumberLimit = 5000; - ImageRecordsManager(); ImageRecord* FindLargestPaintCandidate() const; bool AreAllVisibleNodesDetached() const; + inline void RemoveInvisibleRecordIfNeeded( + const DOMNodeId& invisible_node_id) { + invisible_node_ids_.erase(invisible_node_id); + } inline void RemoveVisibleRecord( const BackgroundImageId& background_image_id) { base::WeakPtr<ImageRecord> record = @@ -90,7 +89,6 @@ } inline void RecordInvisibleNode(const DOMNodeId& node_id) { - DCHECK(!RecordedTooManyNodes()); invisible_node_ids_.insert(node_id); } void RecordVisibleNode(const BackgroundImageId& background_image_id, @@ -104,11 +102,6 @@ return invisible_node_ids_.Contains(node_id); } - inline bool RecordedTooManyNodes() const { - return visible_background_image_map_.size() + invisible_node_ids_.size() > - kImageNodeNumberLimit; - } - inline bool WasVisibleNodeLoaded( const BackgroundImageId& background_image_id) const { DCHECK(visible_background_image_map_.Contains(background_image_id)); @@ -212,7 +205,7 @@ const ImageResourceContent& cached_image, const PropertyTreeState& current_paint_chunk_properties); void OnPaintFinished(); - void LayoutObjectWillBeDestroyed(DOMNodeId); + void LayoutObjectWillBeDestroyed(const LayoutObject&); void NotifyBackgroundImageRemoved(DOMNodeId, const ImageResourceContent*); // After the method being called, the detector stops to record new entries and // node removal. But it still observe the loading status. In other words, if @@ -241,7 +234,6 @@ void ReportCandidateToTrace(ImageRecord&); void ReportNoCandidateToTrace(); void Deactivate(); - void HandleTooManyNodes(); void UpdateCandidate();
diff --git a/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc b/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc index be87f279..440f1ff5 100644 --- a/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc +++ b/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc
@@ -102,9 +102,18 @@ ->records_manager_.visible_background_image_map_.size(); } + size_t CountInvisibleRecords() { + return GetPaintTimingDetector() + .GetImagePaintTimingDetector() + ->records_manager_.invisible_node_ids_.size(); + } + size_t ContainerTotalSize() { return GetPaintTimingDetector() .GetImagePaintTimingDetector() + ->records_manager_.invisible_node_ids_.size() + + GetPaintTimingDetector() + .GetImagePaintTimingDetector() ->records_manager_.visible_background_image_map_.size() + GetPaintTimingDetector() .GetImagePaintTimingDetector() @@ -597,6 +606,35 @@ } TEST_F(ImagePaintTimingDetectorTest, + RemoveRecordFromAllContainersAfterInvisibleImageRemoved) { + SetBodyInnerHTML(R"HTML( + <style> + #target { + position: relative; + left: 100px; + } + #parent { + background-color: yellow; + height: 50px; + width: 50px; + overflow: scroll; + } + </style> + <div id='parent'> + <img id='target'></img> + </div> + )HTML"); + SetImageAndPaint("target", 5, 5); + UpdateAllLifecyclePhasesAndInvokeCallbackIfAny(); + EXPECT_EQ(ContainerTotalSize(), 1u); + EXPECT_EQ(CountInvisibleRecords(), 1u); + + GetDocument().body()->RemoveChild(GetDocument().getElementById("parent")); + EXPECT_EQ(ContainerTotalSize(), 0u); + EXPECT_EQ(CountInvisibleRecords(), 0u); +} + +TEST_F(ImagePaintTimingDetectorTest, RemoveRecordFromAllContainersAfterBackgroundImageRemoval) { SetBodyInnerHTML(R"HTML( <style>
diff --git a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc index 49b1bf0..78371fe 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc +++ b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc
@@ -2036,7 +2036,7 @@ PhysicalOffset border_origin_to_scroll_origin(-GetLayoutBox()->BorderLeft(), -GetLayoutBox()->BorderTop()); border_origin_to_scroll_origin += - PhysicalOffset::FromFloatSizeRound(GetScrollOffset()); + PhysicalOffset::FromFloatSizeFloor(GetScrollOffset()); // Represent the rect in the container's scroll-origin coordinate. local_expose_rect.Move(border_origin_to_scroll_origin); PhysicalRect scroll_snapport_rect = VisibleScrollSnapportRect(); @@ -2928,10 +2928,11 @@ ->PaintedOutputOfObjectHasNoEffectRegardlessOfSize(); } -void PaintLayerScrollableArea::PreFinalize() { +void PaintLayerScrollableArea::DisposeImpl() { if (!HasBeenDisposed()) Dispose(); rare_data_.reset(); + ScrollableArea::DisposeImpl(); } } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h index 6bb84d4c..e5942221 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h +++ b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h
@@ -545,7 +545,7 @@ return scrolling_background_display_item_client_; } - void PreFinalize() override; + void DisposeImpl() override; private: bool NeedsScrollbarReconstruction() const;
diff --git a/third_party/blink/renderer/core/paint/paint_timing_detector.cc b/third_party/blink/renderer/core/paint/paint_timing_detector.cc index 03368e08..d462f117 100644 --- a/third_party/blink/renderer/core/paint/paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/paint_timing_detector.cc
@@ -120,6 +120,9 @@ const LayoutObject& object) { if (text_paint_timing_detector_) text_paint_timing_detector_->LayoutObjectWillBeDestroyed(object); + + if (image_paint_timing_detector_) + image_paint_timing_detector_->LayoutObjectWillBeDestroyed(object); } void PaintTimingDetector::NotifyBackgroundImageRemoved(
diff --git a/third_party/blink/renderer/core/paint/theme_painter.cc b/third_party/blink/renderer/core/paint/theme_painter.cc index 2c83795..fcb48cb 100644 --- a/third_party/blink/renderer/core/paint/theme_painter.cc +++ b/third_party/blink/renderer/core/paint/theme_painter.cc
@@ -96,6 +96,27 @@ #define COUNT_APPEARANCE(doc, feature) \ doc.CountUse(WebFeature::kCSSValueAppearance##feature##Rendered) +void CountAppearanceTextFieldPart(const Node* node) { + if (!node) { + return; + } + UseCounter::Count(node->GetDocument(), + WebFeature::kCSSValueAppearanceTextFieldRendered); + WebFeature feature = + WebFeature::kCSSValueAppearanceTextFieldForOthersRendered; + if (auto* input = ToHTMLInputElementOrNull(node)) { + const AtomicString& type = input->type(); + if (type == input_type_names::kSearch) { + feature = WebFeature::kCSSValueAppearanceTextFieldForSearch; + } else if (input->IsTextField()) { + feature = WebFeature::kCSSValueAppearanceTextFieldForTextField; + } else if (IsMultipleFieldsTemporalInput(type)) { + feature = WebFeature::kCSSValueAppearanceTextFieldForTemporalRendered; + } + } + UseCounter::Count(node->GetDocument(), feature); +} + // Returns true; Needs CSS painting and/or PaintBorderOnly(). bool ThemePainter::Paint(const LayoutObject& o, const PaintInfo& paint_info, @@ -214,9 +235,24 @@ case kMediaVolumeSliderThumbPart: return true; case kMenulistButtonPart: - case kTextFieldPart: - case kTextAreaPart: return true; + case kTextFieldPart: + if (!RuntimeEnabledFeatures::FormControlsRefreshEnabled()) { + return true; + } + CountAppearanceTextFieldPart(node); + return PaintTextField(node, style, paint_info, r); + case kTextAreaPart: + if (!RuntimeEnabledFeatures::FormControlsRefreshEnabled()) { + return true; + } + if (node) { + const auto& doc = node->GetDocument(); + COUNT_APPEARANCE(doc, TextArea); + if (!IsHTMLTextAreaElement(node)) + COUNT_APPEARANCE(doc, TextAreaForOthers); + } + return PaintTextArea(node, style, paint_info, r); case kSearchFieldPart: { COUNT_APPEARANCE(doc, SearchField); auto* input = ToHTMLInputElementOrNull(node); @@ -260,26 +296,15 @@ // Call the appropriate paint method based off the appearance value. switch (style.Appearance()) { case kTextFieldPart: - if (node) { - UseCounter::Count(node->GetDocument(), - WebFeature::kCSSValueAppearanceTextFieldRendered); - WebFeature feature = - WebFeature::kCSSValueAppearanceTextFieldForOthersRendered; - if (auto* input = ToHTMLInputElementOrNull(node)) { - const AtomicString& type = input->type(); - if (type == input_type_names::kSearch) { - feature = WebFeature::kCSSValueAppearanceTextFieldForSearch; - } else if (input->IsTextField()) { - feature = WebFeature::kCSSValueAppearanceTextFieldForTextField; - } else if (IsMultipleFieldsTemporalInput(type)) { - feature = - WebFeature::kCSSValueAppearanceTextFieldForTemporalRendered; - } - } - UseCounter::Count(node->GetDocument(), feature); + if (RuntimeEnabledFeatures::FormControlsRefreshEnabled()) { + return false; } + CountAppearanceTextFieldPart(node); return PaintTextField(node, style, paint_info, r); case kTextAreaPart: + if (RuntimeEnabledFeatures::FormControlsRefreshEnabled()) { + return false; + } if (node) { const auto& doc = node->GetDocument(); COUNT_APPEARANCE(doc, TextArea);
diff --git a/third_party/blink/renderer/core/script/BUILD.gn b/third_party/blink/renderer/core/script/BUILD.gn index 83dd22d7..ac7886e 100644 --- a/third_party/blink/renderer/core/script/BUILD.gn +++ b/third_party/blink/renderer/core/script/BUILD.gn
@@ -75,3 +75,24 @@ jumbo_excluded_sources = [ "modulator.cc" ] # https://crbug.com/716395 } + +copy("layered_apis_elements_virtual_scroller_js") { + testonly = true + + sources = [ + "resources/layered_api/elements/virtual-scroller/find-element.mjs", + "resources/layered_api/elements/virtual-scroller/sets.mjs", + "resources/layered_api/elements/virtual-scroller/visibility-manager.mjs", + ] + + outputs = [ + "{{source_gen_dir}}/{{source_file_part}}", + ] +} + +group("js_files_for_web_tests") { + testonly = true + data_deps = [ + ":layered_apis_elements_virtual_scroller_js", + ] +}
diff --git a/third_party/blink/renderer/core/script/layered_api_module.h b/third_party/blink/renderer/core/script/layered_api_module.h index 7be3348..7dd7d687 100644 --- a/third_party/blink/renderer/core/script/layered_api_module.h +++ b/third_party/blink/renderer/core/script/layered_api_module.h
@@ -18,8 +18,8 @@ kElementsInternal, kElementsSwitch, kElementsToast, + kElementsVirtualScroller, kKvStorage, - kVirtualScroller, }; } // namespace layered_api
diff --git a/third_party/blink/renderer/core/script/layered_api_resources.h b/third_party/blink/renderer/core/script/layered_api_resources.h index dc7e79e..98be4b3 100644 --- a/third_party/blink/renderer/core/script/layered_api_resources.h +++ b/third_party/blink/renderer/core/script/layered_api_resources.h
@@ -45,6 +45,19 @@ {"elements/toast/index.mjs", IDR_LAYERED_API_ELEMENTS_TOAST_INDEX_MJS, Module::kElementsToast}, + {"elements/virtual-scroller/find-element.mjs", + IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_FIND_ELEMENT_MJS, + Module::kElementsVirtualScroller}, + {"elements/virtual-scroller/index.mjs", + IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_INDEX_MJS, + Module::kElementsVirtualScroller}, + {"elements/virtual-scroller/sets.mjs", + IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_SETS_MJS, + Module::kElementsVirtualScroller}, + {"elements/virtual-scroller/visibility-manager.mjs", + IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_VISIBILITY_MANAGER_MJS, + Module::kElementsVirtualScroller}, + {"kv-storage/async_iterator.mjs", IDR_LAYERED_API_KV_STORAGE_ASYNC_ITERATOR_MJS, Module::kKvStorage}, {"kv-storage/idb_utils.mjs", IDR_LAYERED_API_KV_STORAGE_IDB_UTILS_MJS, @@ -52,28 +65,6 @@ {"kv-storage/index.mjs", IDR_LAYERED_API_KV_STORAGE_INDEX_MJS, Module::kKvStorage}, - {"virtual-scroller/index.mjs", IDR_LAYERED_API_VIRTUAL_SCROLLER_INDEX_MJS, - Module::kVirtualScroller}, - {"virtual-scroller/item-source.mjs", - IDR_LAYERED_API_VIRTUAL_SCROLLER_ITEM_SOURCE_MJS, - Module::kVirtualScroller}, - {"virtual-scroller/virtual-repeater.mjs", - IDR_LAYERED_API_VIRTUAL_SCROLLER_VIRTUAL_REPEATER_MJS, - Module::kVirtualScroller}, - {"virtual-scroller/virtual-scroller.mjs", - IDR_LAYERED_API_VIRTUAL_SCROLLER_VIRTUAL_SCROLLER_MJS, - Module::kVirtualScroller}, - - {"virtual-scroller/layouts/layout-1d-base.mjs", - IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_BASE_MJS, - Module::kVirtualScroller}, - {"virtual-scroller/layouts/layout-1d-grid.mjs", - IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_GRID_MJS, - Module::kVirtualScroller}, - {"virtual-scroller/layouts/layout-1d.mjs", - IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_MJS, - Module::kVirtualScroller}, - }; } // namespace
diff --git a/third_party/blink/renderer/core/script/modulator_impl_base.cc b/third_party/blink/renderer/core/script/modulator_impl_base.cc index 8fc9f20..71a69de8 100644 --- a/third_party/blink/renderer/core/script/modulator_impl_base.cc +++ b/third_party/blink/renderer/core/script/modulator_impl_base.cc
@@ -59,8 +59,6 @@ switch (module) { case layered_api::Module::kBlank: return true; - case layered_api::Module::kVirtualScroller: - return false; case layered_api::Module::kKvStorage: return RuntimeEnabledFeatures::BuiltInModuleKvStorageEnabled( GetExecutionContext()); @@ -71,6 +69,8 @@ return RuntimeEnabledFeatures::BuiltInModuleSwitchElementEnabled(); case layered_api::Module::kElementsToast: return RuntimeEnabledFeatures::BuiltInModuleAllEnabled(); + case layered_api::Module::kElementsVirtualScroller: + return false; } } @@ -90,7 +90,7 @@ case layered_api::Module::kElementsToast: UseCounter::Count(GetExecutionContext(), WebFeature::kBuiltInModuleToast); break; - case layered_api::Module::kVirtualScroller: + case layered_api::Module::kElementsVirtualScroller: UseCounter::Count(GetExecutionContext(), WebFeature::kBuiltInModuleVirtualScroller); break;
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py b/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py index cee21a2..4364aaf 100644 --- a/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py +++ b/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py
@@ -8,8 +8,7 @@ def _CommonChecks(input_api, output_api): results = [] - # We don't apply eslint to virtual-scroller/, which is not developed here. - # TODO(tkent): kv-storage/.eslintrc.js and toast/.eslintrc.js specify babel-eslint parser, which + # TODO(tkent): {kv-storage,toast,virtual-scroller}/.eslintrc.js specify babel-eslint parser, which # is not in third_party/node/node_modules/. mjs_files = input_api.AffectedFiles( file_filter=lambda f: (f.LocalPath().endswith('.mjs') and
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/index.mjs b/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/index.mjs index 45c3c72..281dabf 100644 --- a/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/index.mjs +++ b/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/index.mjs
@@ -120,10 +120,23 @@ delete StdToastElement.prototype.observedAttributes; delete StdToastElement.prototype.connectedCallback; -export function showToast(message, options) { +export function showToast(message, options = {}) { const toast = new StdToastElement(message); + + const {action, ...showOptions} = options; + if (action !== undefined) { + const actionButton = document.createElement('button'); + + // Unlike String(), this performs the desired JavaScript ToString operation. + // https://gist.github.com/domenic/82adbe7edc4a33a70f42f255479cec39 + actionButton.textContent = `${action}`; + + actionButton.setAttribute('slot', 'action'); + toast.appendChild(actionButton); + } + document.body.append(toast); - toast.show(options); + toast.show(showOptions); return toast; }
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/.eslintrc.js b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/.eslintrc.js new file mode 100644 index 0000000..90e626a41 --- /dev/null +++ b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/.eslintrc.js
@@ -0,0 +1,337 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module.exports = { + root: true, + env: { + es6: true, + browser: true + }, + 'parser': 'babel-eslint', + parserOptions: { + sourceType: 'module', + ecmaVersion: 2019 + }, + rules: { + 'for-direction': 'error', + 'getter-return': 'error', + 'no-async-promise-executor': 'error', + 'no-await-in-loop': 'error', + 'no-compare-neg-zero': 'error', + 'no-cond-assign': ['error', 'except-parens'], + 'no-console': 'error', + 'no-constant-condition': ['error', {checkLoops: false}], + 'no-control-regex': 'error', + 'no-debugger': 'error', + 'no-dupe-args': 'error', + 'no-dupe-keys': 'error', + 'no-duplicate-case': 'error', + 'no-empty': 'error', + 'no-empty-character-class': 'error', + 'no-ex-assign': 'error', + 'no-extra-boolean-cast': 'error', + 'no-extra-parens': [ + 'error', + 'all', + { + conditionalAssign: false, + nestedBinaryExpressions: false, + returnAssign: false + } + ], + 'no-extra-semi': 'error', + 'no-func-assign': 'error', + 'no-inner-declarations': 'off', + 'no-invalid-regexp': 'error', + 'no-irregular-whitespace': 'error', + 'no-misleading-character-class': 'error', + 'no-obj-calls': 'error', + 'no-prototype-builtins': 'error', + 'no-regex-spaces': 'error', + 'no-sparse-arrays': 'error', + 'no-template-curly-in-string': 'error', + 'no-unexpected-multiline': 'error', + 'no-unreachable': 'error', + 'no-unsafe-finally': 'off', + 'no-unsafe-negation': 'error', + 'use-isnan': 'error', + 'valid-typeof': 'error', + 'accessor-pairs': 'error', + 'array-callback-return': 'error', + 'block-scoped-var': 'off', + 'class-methods-use-this': 'off', + 'complexity': 'off', + 'consistent-return': 'error', + 'curly': ['error', 'all'], + 'default-case': 'off', + 'dot-location': ['error', 'property'], + 'dot-notation': 'error', + 'eqeqeq': 'error', + 'guard-for-in': 'off', + 'no-alert': 'error', + 'no-caller': 'error', + 'no-case-declarations': 'error', + 'no-div-regex': 'off', + 'no-empty-function': 'off', + 'no-empty-pattern': 'error', + 'no-eq-null': 'error', + 'no-eval': 'error', + 'no-extend-native': 'error', + 'no-extra-bind': 'error', + 'no-extra-label': 'error', + 'no-fallthrough': 'error', + 'no-floating-decimal': 'error', + 'no-global-assign': 'error', + 'no-implicit-coercion': 'error', + 'no-implicit-globals': 'error', + 'no-implied-eval': 'error', + 'no-iterator': 'error', + 'no-labels': ['error', {allowLoop: true}], + 'no-lone-blocks': 'error', + 'no-loop-func': 'error', + 'no-magic-numbers': ['error', {ignore: [0, 1, 2]}], + 'no-multi-spaces': ['error', {ignoreEOLComments: true}], + 'no-multi-str': 'error', + 'no-new': 'error', + 'no-new-func': 'error', + 'no-new-wrappers': 'error', + 'no-octal': 'error', + 'no-octal-escape': 'error', + 'no-param-reassign': 'off', + 'no-process-env': 'error', + 'no-proto': 'error', + 'no-redeclare': 'error', + 'no-restricted-properties': 'off', + 'no-return-assign': ['error', 'except-parens'], + 'no-return-await': 'error', + 'no-script-url': 'off', + 'no-self-assign': 'error', + 'no-self-compare': 'error', + 'no-sequences': 'error', + 'no-throw-literal': 'error', + 'no-unmodified-loop-condition': 'error', + 'no-unused-expressions': 'error', + 'no-unused-labels': 'error', + 'no-useless-call': 'error', + 'no-useless-concat': 'error', + 'no-useless-escape': 'error', + 'no-useless-return': 'error', + 'no-void': 'error', + 'no-warning-comments': 'off', + 'no-with': 'error', + 'prefer-promise-reject-errors': 'error', + 'radix': ['error', 'as-needed'], + 'require-await': 'off', + 'vars-on-top': 'off', + 'wrap-iife': ['error', 'outside'], + 'yoda': ['error', 'never'], + 'strict': ['error', 'global'], + 'init-declarations': 'off', + 'no-delete-var': 'error', + 'no-label-var': 'error', + 'no-restricted-globals': 'off', + 'no-shadow': 'error', + 'no-shadow-restricted-names': 'error', + 'no-undef': 'error', + 'no-undef-init': 'error', + 'no-undefined': 'off', + 'no-unused-vars': 'error', + 'no-use-before-define': ['error', 'nofunc'], + 'callback-return': 'off', + 'global-require': 'error', + 'handle-callback-err': 'error', + 'no-buffer-constructor': 'error', + 'no-mixed-requires': ['error', true], + 'no-new-require': 'error', + 'no-path-concat': 'error', + 'no-process-exit': 'error', + 'no-restricted-modules': 'off', + 'no-sync': 'off', + 'array-bracket-newline': ['error', {multiline: true}], + 'array-bracket-spacing': ['error', 'never'], + 'array-element-newline': 'off', + 'block-spacing': ['error', 'always'], + 'brace-style': [ + 'error', + '1tbs', + {allowSingleLine: false} + ], + camelcase: ['error', {properties: 'always'}], + 'capitalized-comments': 'off', + 'comma-dangle': ['error', 'always-multiline'], + 'comma-spacing': [ + 'error', + { + before: false, + after: true + } + ], + 'comma-style': ['error', 'last'], + 'computed-property-spacing': ['error', 'never'], + 'consistent-this': 'off', + 'eol-last': 'error', + 'func-call-spacing': ['error', 'never'], + 'func-name-matching': 'error', + 'func-names': 'off', + 'func-style': ['error', 'declaration'], + 'function-paren-newline': 'off', + 'id-blacklist': 'off', + 'id-length': 'off', + 'id-match': 'off', + indent: 'off', // not really compatible with clang-format + 'jsx-quotes': 'off', + 'key-spacing': [ + 'error', + { + beforeColon: false, + afterColon: true, + mode: 'strict' + } + ], + 'keyword-spacing': [ + 'error', + { + before: true, + after: true + } + ], + 'line-comment-position': 'off', + 'linebreak-style': ['error', 'unix'], + 'lines-around-comment': 'off', + 'max-depth': 'off', + 'max-len': ['error', { + tabWidth: 2, + ignorePattern: "(^import |// eslint-disable-line )"}], + 'max-lines': 'off', + 'max-nested-callbacks': 'off', + 'max-params': 'off', + 'max-statements': 'off', + 'max-statements-per-line': ['error', {max: 1}], + 'multiline-ternary': ['error', 'always-multiline'], + 'new-cap': 'error', + 'new-parens': 'error', + 'newline-per-chained-call': 'off', + 'no-array-constructor': 'error', + 'no-bitwise': 'off', + 'no-continue': 'off', + 'no-inline-comments': 'off', + 'no-mixed-operators': [ + 'error', + { + groups: [ + ['&', '|', '^', '~', '<<', '>>', '>>>'], + ['==', '!=', '===', '!==', '>', '>=', '<', '<='], + ['&&', '||'], + ['in', 'instanceof'] + ] + } + ], + 'no-mixed-spaces-and-tabs': 'error', + 'no-multi-assign': 'off', + 'no-multiple-empty-lines': 'error', + 'no-negated-condition': 'off', + 'no-nested-ternary': 'error', + 'no-new-object': 'error', + 'no-plusplus': 'off', + 'no-restricted-syntax': 'off', + 'no-tabs': 'error', + 'no-ternary': 'off', + 'no-trailing-spaces': 'error', + 'no-underscore-dangle': 'off', + 'no-unneeded-ternary': 'error', + 'no-whitespace-before-property': 'error', + 'nonblock-statement-body-position': 'error', + 'object-curly-newline': ['error', {consistent: true}], + 'object-curly-spacing': ['error', 'never'], + 'object-property-newline': 'off', + 'one-var': ['error', 'never'], + 'one-var-declaration-per-line': ['error', 'initializations'], + 'operator-assignment': ['error', 'always'], + 'operator-linebreak': ['error', 'after'], + 'padded-blocks': ['error', 'never'], + 'padding-line-between-statements': 'off', + 'quote-props': ['error', 'as-needed'], + quotes: [ + 'error', + 'single', + { + avoidEscape: true, + allowTemplateLiterals: true + } + ], + semi: ['error', 'always'], + 'semi-spacing': 'error', + 'semi-style': 'error', + 'sort-keys': 'off', + 'sort-vars': 'off', + 'space-before-blocks': ['error', 'always'], + 'space-before-function-paren': [ + 'error', + { + anonymous: 'always', + named: 'never' + } + ], + 'space-in-parens': ['error', 'never'], + 'space-infix-ops': 'error', + 'space-unary-ops': [ + 'error', + { + words: true, + nonwords: false + } + ], + 'spaced-comment': ['error', 'always'], + 'switch-colon-spacing': 'error', + 'template-tag-spacing': 'error', + 'unicode-bom': 'error', + 'wrap-regex': 'off', + 'arrow-body-style': 'off', + 'arrow-parens': ['error', 'as-needed'], + 'arrow-spacing': 'error', + 'constructor-super': 'error', + 'generator-star-spacing': ['error', 'neither'], + 'no-class-assign': 'error', + 'no-confusing-arrow': 'off', + 'no-const-assign': 'error', + 'no-dupe-class-members': 'error', + 'no-duplicate-imports': 'error', + 'no-new-symbol': 'error', + 'no-restricted-imports': 'off', + 'no-this-before-super': 'error', + 'no-useless-computed-key': 'error', + 'no-useless-constructor': 'error', + 'no-useless-rename': 'error', + 'no-var': 'error', + 'object-shorthand': 'error', + 'prefer-arrow-callback': 'error', + 'prefer-const': ['error', {ignoreReadBeforeAssign: true}], + 'prefer-destructuring': [ + 'error', + { + VariableDeclarator: { + array: false, + object: true + }, + AssignmentExpression: { + array: false, + object: false + } + }, + { + enforceForRenamedProperties: false + } + ], + 'prefer-numeric-literals': 'error', + 'prefer-rest-params': 'error', + 'prefer-spread': 'error', + 'prefer-template': 'off', + 'require-yield': 'error', + 'rest-spread-spacing': 'error', + 'sort-imports': 'off', + 'symbol-description': 'error', + 'template-curly-spacing': ['error', 'never'], + 'yield-star-spacing': ['error', 'after'] + } +};
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs new file mode 100644 index 0000000..c25edc0 --- /dev/null +++ b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs
@@ -0,0 +1,104 @@ +/** + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + * + * @fileoverview Utilities for binary searching by layed-out pixed offset in a + * list of elements. + * @package + */ + +/** Symbols for use with @see findElement */ +export const BIAS_LOW = Symbol('BIAS_LOW'); +export const BIAS_HIGH = Symbol('BIAS_HIGH'); + +function getBound(elements, edgeIndex) { + const element = elements[Math.floor(edgeIndex / 2)]; + const rect = element.getBoundingClientRect(); + return edgeIndex % 2 ? rect.bottom : rect.top; +} + +/** + * Does the actual work of binary searching. This searches amongst the 2*N edges + * of the N elements. Returns the index of an edge found, 2i is the low edge of + * the ith element, 2i+1 is the high edge of the ith element. If |bias| is low + * then we find the index of the lowest edge >= offset. Otherwise we find index + * of the highest edge > offset. + */ +function findEdgeIndex(elements, offset, bias) { + let low = 0; + let high = elements.length * 2 - 1; + while (low < high) { + const i = Math.floor((low + high) / 2); + const bound = getBound(elements, i); + if (bias === BIAS_LOW) { + if (bound < offset) { + low = i + 1; + } else { + high = i; + } + } else { + if (offset < bound) { + high = i; + } else { + low = i + 1; + } + } + } + return low; +} + +/** + * Binary searches inside the array |elements| to find an element containing or + * nearest to |offset| (based on @see Element#getBoundingClientRect()). Assumes + * that the elements are already sorted in increasing pixel order. |bias| + * controls what happens if |offset| is not contained within any element or if + * |offset| is contained with 2 elements (this only happens if there is no + * margin between the elements). If |bias| is BIAS_LOW, then this selects the + * lower element nearest |offset|, otherwise it selects the higher element. + * + * Returns null if |offset| is not within any element. + * + * @param {!Element[]} elements An array of Elements in display order, + * i.e. the pixel offsets of later element are higher than those of earlier + * elements. + * @param {!number} offset The target offset in pixels to search for. + * @param {!Symbol} bias Controls whether we prefer a higher or lower element + * when there is a choice between two elements. + */ +export function findElement(elements, offset, bias) { + if (elements.length === 0) { + return null; + } + // Check if the offset is outside the range entirely. + if (offset < getBound(elements, 0) || + offset > getBound(elements, elements.length * 2 - 1)) { + return null; + } + + let edgeIndex = findEdgeIndex(elements, offset, bias); + + // Fix up edge cases. + if (bias === BIAS_LOW) { + // bound(0)..bound(edgeIndex) < offset <= bound(edgeIndex+1) ... + // If we bias low and we got a low edge and we weren't exactly on the edge + // then we want to select the element that's lower. + if (edgeIndex % 2 === 0) { + const bound = getBound(elements, edgeIndex); + if (offset < bound) { + edgeIndex--; + } + } + } else { + // bound(0)..bound(edgeIndex - 1) <= offset < bound(edgeIndex) ... + // If we bias high and we got a low edge, we need to check if we were + // exactly on the edge of the previous element. + if (edgeIndex % 2 === 0) { + const bound = getBound(elements, edgeIndex - 1); + if (offset === bound) { + edgeIndex--; + } + } + } + return elements[Math.floor(edgeIndex / 2)]; +}
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/index.mjs b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/index.mjs new file mode 100644 index 0000000..daef60f --- /dev/null +++ b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/index.mjs
@@ -0,0 +1,57 @@ +/** + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + * + * @fileoverview This file defines virtual-scroller element. + * EXPLAINER: https://github.com/fergald/virtual-scroller/blob/master/README.md + * TEST PATH: third_party/blink/web_tests/http/tests/virtual-scroller/* + * third_party/blink/web_tests/wpt_internal/virtual-scroller/* + * @package + */ +import {VisibilityManager} from './visibility-manager.mjs'; + +function styleSheetFactory() { + let styleSheet; + return () => { + if (!styleSheet) { + styleSheet = new CSSStyleSheet(); + styleSheet.replaceSync(` +:host { + display: block; +} + +::slotted(*) { + display: block !important; + contain: layout style; +} +`); + } + return styleSheet; + }; +} + +/** + * The class backing the virtual-scroller custom element. + */ +export class VirtualScrollerElement extends HTMLElement { + constructor() { + super(); + + const shadowRoot = this.attachShadow({mode: 'closed'}); + shadowRoot.adoptedStyleSheets = [styleSheetFactory()()]; + shadowRoot.appendChild(document.createElement('slot')); + + const visibilityManager = new VisibilityManager(this.children); + + new ResizeObserver(() => { + visibilityManager.scheduleSync(); + }).observe(this); + + new MutationObserver(records => { + visibilityManager.applyMutationObserverRecords(records); + }).observe(this, {childList: true}); + } +} + +customElements.define('virtual-scroller', VirtualScrollerElement);
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs new file mode 100644 index 0000000..9b1aff8 --- /dev/null +++ b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs
@@ -0,0 +1,24 @@ +/** + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + * + * @fileoverview Utility functions for set operations. + * @package + */ + +/* + * Returns the set of elements in |a| that are not in |b|. + * + * @param {!Set} a A set of elements. + * @param {!Set} b A set of elements. +*/ +export function difference(a, b) { + const result = new Set(); + for (const element of a) { + if (!b.has(element)) { + result.add(element); + } + } + return result; +}
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs new file mode 100644 index 0000000..ecc160f --- /dev/null +++ b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs
@@ -0,0 +1,407 @@ +/** + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + * + * @fileoverview This file provides the class backing the virtual-scroller + * element. + * @package + */ +import * as sets from './sets.mjs'; +import * as findElement from './find-element.mjs'; + + +// This controls how much above and below the current screen we +// reveal, e.g. 1 = 1 screen of content. +const BUFFER = 0.2; +// When we know about the heights of elements we default this height. +const DEFAULT_HEIGHT_ESTIMATE_PX = 100; +// When we lock an element, we use this as the width. We use 1px because locked +// items will not resize when their container changes and so could result in a +// horizontal scroll-bar appearing if it they are wide enough. +const LOCKED_WIDTH_PX = 1; + +/** + * Represents a range of elements from |low| to |high|, inclusive. + * If either |low| or |high| are null then we treat this as an empty range. + */ +class ElementBounds { + /** @const {Element} */ + low; + /** @const {Element} */ + high; + + constructor(low, high) { + this.low = low; + this.high = high; + } + + // Returns a Set containing all of the elements from low to high. + elementSet() { + const result = new Set(); + if (this.low === null || this.high === null) { + return result; + } + let element = this.low; + while (element) { + result.add(element); + if (element === this.high) { + break; + } + element = element.nextElementSibling; + } + return result; + } +} + +const EMPTY_ELEMENT_BOUNDS = new ElementBounds(null, null); + +/** + * Manages measuring and estimating sizes of elements. + * + * This tracks an average measured element size as elements are added + * and removed. +*/ +class SizeManager { + #sizes = new WeakMap(); + + #totalMeasuredSize = 0; + #measuredCount = 0; + + /** + * Measures and stores |element|'s size. If |element| was measured + * previously, this updates everything to use the new current size. + * + * @param {!Element} element The element to measure. + */ + measure(element) { + let oldSize = this.#sizes.get(element); + if (oldSize === undefined) { + oldSize = 0; + this.#measuredCount++; + } + const newSize = element.getBoundingClientRect().height; + this.#totalMeasuredSize += newSize - oldSize; + this.#sizes.set(element, newSize); + } + + /** + * Returns a size for |element|, either the last stored size or an + * estimate based on all other previously measured elements or a + * default. + * + * @param {!Element} element The element to produce a size for. + */ + getHopefulSize(element) { + const size = this.#sizes.get(element); + return size === undefined ? this.#getAverageSize() : size; + } + + #getAverageSize = () => { + return this.#measuredCount > 0 ? + this.#totalMeasuredSize / this.#measuredCount : + DEFAULT_HEIGHT_ESTIMATE_PX; + } + + /** + * Removes all data related to |element| from the manager. + * + * @param {!Element} element The element to remove. + */ + remove(element) { + const oldSize = this.#sizes.get(element); + if (oldSize === undefined) { + return; + } + this.#totalMeasuredSize -= oldSize; + this.#measuredCount--; + this.#sizes.delete(element); + } +} + +/** + * Manages the visibility (locked/unlocked state) of a list of + * elements. This list of elements is assumed to be in vertical + * display order (e.g. from lowest to highest offset). + * + * It uses resize and intersection observers on all of the visible + * elements to ensure that changes that impact visibility cause us to + * recalulate things (e.g. scrolling, restyling). +*/ +export class VisibilityManager { + #sizeManager = new SizeManager(); + #elements; + #syncRAFToken; + + #elementIntersectionObserver; + #elementResizeObserver; + + #revealed = new Set(); + + constructor(elements) { + this.#elements = elements; + + // We want to sync if any element's size changes or if it becomes + // more/less visible. + this.#elementIntersectionObserver = new IntersectionObserver(() => { + this.scheduleSync(); + }); + // TODO(fergal): Remove this? I'm not sure that we need the resize + // observer. Any resize that is important to us seems like it will + // also involve an intersection change. + this.#elementResizeObserver = new ResizeObserver(() => { + this.scheduleSync(); + }); + + for (const element of this.#elements) { + this.#didAdd(element); + } + this.scheduleSync(); + } + + /** + * Attempts to unlock a range of elements suitable for the current + * viewport. This causes one forced layout. + */ + #sync = () => { + if (this.#elements.length === 0) { + return; + } + + // The basic idea is ... + // The forced layout occurs at the start. We then use the laid out + // coordinates (which are based on a mix of real sizes for + // unlocked elements and the estimated sizes at the time of + // locking for locked elements) to calculate a set of elements + // which should be revealed. We use unlock/lock to move to this + // new set of revealed elements. We will check in the next frame + // whether we got it correct. + + // This causes a forced layout and takes measurements of all + // currently revealed elements. + this.#measureRevealed(); + + // Compute the pixel bounds of what we would like to reveal. Then + // find the elements corresponding to these bounds. + // TODO(fergal): Use nearest scrolling ancestor? + const desiredLow = 0 - window.innerHeight * BUFFER; + const desiredHigh = window.innerHeight + window.innerHeight * BUFFER; + const newBounds = this.#findElementBounds(desiredLow, desiredHigh); + const newRevealed = newBounds.elementSet(); + + // TODO(fergal): We need to observe 1 element off the end of the + // list, to cope with e.g. the scrolling region suddenly growing. + + // Lock and unlock the minimal set of elements to get us to the + // new state. + const toHide = sets.difference(this.#revealed, newRevealed); + toHide.forEach(e => this.#hide(e)); + const toReveal = sets.difference(newRevealed, this.#revealed); + toReveal.forEach(e => this.#reveal(e)); + + // Now we have revealed what we hope will fill the screen. It + // could be incorrect. Rather than measuring now and correcting it + // which would involve an unknown number of forced layouts, we + // come back next frame and try to make it better. We know we can + // stop when we didn't hide or reveal any elements. + if (toHide.size > 0 || toReveal.size > 0) { + this.scheduleSync(); + } + } + + /** + * Searches within the managed elements and returns an ElementBounds + * object. This object may represent an empty range or a range whose low + * element contains or is lower than |low| (or the lowest element + * possible). Similarly for |high|. + * + * @param {!number} low The lower bound to locate. + * @param {!number} high The upper bound to locate. + */ + #findElementBounds = (low, high) => { + const lowElement = findElement.findElement( + this.#elements, low, findElement.BIAS_LOW); + const highElement = findElement.findElement( + this.#elements, high, findElement.BIAS_HIGH); + + if (lowElement === null) { + if (highElement === null) { + return EMPTY_ELEMENT_BOUNDS; + } else { + return new ElementBounds(this.#elements[0], highElement); + } + } else if (highElement === null) { + return new ElementBounds( + lowElement, this.#elements[this.#elements.length - 1]); + } + return new ElementBounds(lowElement, highElement); + } + + /** + * Updates the size manager with all of the currently revealed + * elements' sizes. This will cause a forced layout. + */ + #measureRevealed = () => { + for (const element of this.#revealed) { + this.#sizeManager.measure(element); + } + } + + /** + * Reveals |element| so that it can be rendered. This includes + * unlocking and adding to various observers. + * + * @param {!Element} element The element to reveal. + */ + #reveal = element => { + this.#revealed.add(element); + this.#elementIntersectionObserver.observe(element); + this.#elementResizeObserver.observe(element); + this.#unlock(element); + } + + #logLockingError = (operation, reason, element) => { + // TODO: Figure out the LAPIs error/warning logging story. + console.error('Rejected: ', operation, element, reason); // eslint-disable-line no-console + } + + /** + * Unlocks |element|. + * + * @param {!Element} element The element to unlock. + */ + #unlock = element => { + element.displayLock.commit().catch(reason => { + // Only warn if the unlocked failed and we should be revealed. + if (this.#revealed.has(element)) { + this.#logLockingError('Commit', reason, element); + } + }); + } + + /** + * Hides |element| so that it cannot be rendered. This includes + * locking and removing from various observers. + * + * @param {!Element} element The element to hide. + */ + #hide = element => { + this.#revealed.delete(element); + this.#elementIntersectionObserver.unobserve(element); + this.#elementResizeObserver.unobserve(element); + element.displayLock.acquire({ + timeout: Infinity, + activatable: true, + size: [LOCKED_WIDTH_PX, this.#sizeManager.getHopefulSize(element)], + }).catch(reason => { + // Only warn if the lock failed and we should be locked. + if (!this.#revealed.has(element)) { + this.#logLockingError('Acquire', reason, element); + } + }); + } + + /** + * Notify the manager that |element| has been added to the list of + * managed elements. + * + * @param {!Element} element The element that was added. + */ + #didAdd = element => { + // Added children should be invisible initially. We want to make them + // invisible at this MutationObserver timing, so that there is no + // frame where the browser is asked to render all of the children + // (which could be a lot). + this.#hide(element); + } + + /** + * Notify the manager that |element| has been removed from the list + * of managed elements. + * + * @param {!Element} element The element that was removed. + */ + #didRemove = element => { + // Removed children should be made visible again. We should stop + // observing them and discard any size info we have for them as it + // may have become incorrect. + // + // TODO(fergal): Decide whether to also unlock if + // displayLock.locked is true. That would only be necessary if we + // got out of sync between this.#revealed and the locked state. So + // for now, assume are not buggy. + if (this.#revealed.has(element)) { + this.#unlock(element); + } + this.#revealed.delete(element); + this.#elementIntersectionObserver.unobserve(element); + this.#elementResizeObserver.unobserve(element); + this.#sizeManager.remove(element); + } + + /** + * Ensures that @see #sync() will be called at the next animation frame. + */ + scheduleSync() { + if (this.#syncRAFToken !== undefined) { + return; + } + + this.#syncRAFToken = window.requestAnimationFrame(() => { + this.#syncRAFToken = undefined; + this.#sync(); + }); + } + + /** + * Applys |records| generated by a mutation event to the manager. + * This computes the elements that were newly added/removed and + * notifies the managers for each. + * + * @param {!Object} records The mutations records. + */ + applyMutationObserverRecords(records) { + // It's unclear if we can support children which are not + // elements. We cannot control their visibility using display + // locking but we can just leave them alone. + // + // Relevant mutations are any additions or removals, including + // non-elements and also elements that are removed and then + // re-added as this may impact element bounds. + let relevantMutation = false; + const toRemove = new Set(); + for (const record of records) { + relevantMutation = relevantMutation || record.removedNodes.length > 0; + for (const node of record.removedNodes) { + if (node.nodeType === Node.ELEMENT_NODE) { + toRemove.add(node); + } + } + } + + const toAdd = new Set(); + for (const record of records) { + relevantMutation = relevantMutation || record.addedNodes.length > 0; + for (const node of record.addedNodes) { + if (node.nodeType === Node.ELEMENT_NODE) { + if (toRemove.has(node)) { + toRemove.delete(node); + } else { + toAdd.add(node); + } + } + } + } + for (const node of toRemove) { + this.#didRemove(node); + } + for (const node of toAdd) { + this.#didAdd(node); + } + + if (relevantMutation) { + this.scheduleSync(); + } + } +} +
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp b/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp index e883432..255d055 100644 --- a/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp +++ b/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp
@@ -13,14 +13,11 @@ <include name="IDR_LAYERED_API_ELEMENTS_SWITCH_STYLE_MJS" file="../renderer/core/script/resources/layered_api/elements/switch/style.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> <include name="IDR_LAYERED_API_ELEMENTS_SWITCH_TRACK_MJS" file="../renderer/core/script/resources/layered_api/elements/switch/track.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> <include name="IDR_LAYERED_API_ELEMENTS_TOAST_INDEX_MJS" file="../renderer/core/script/resources/layered_api/elements/toast/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> + <include name="IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_FIND_ELEMENT_MJS" file="../renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> + <include name="IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_INDEX_MJS" file="../renderer/core/script/resources/layered_api/elements/virtual-scroller/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> + <include name="IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_SETS_MJS" file="../renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> + <include name="IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_VISIBILITY_MANAGER_MJS" file="../renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> <include name="IDR_LAYERED_API_KV_STORAGE_ASYNC_ITERATOR_MJS" file="../renderer/core/script/resources/layered_api/kv-storage/async_iterator.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> <include name="IDR_LAYERED_API_KV_STORAGE_IDB_UTILS_MJS" file="../renderer/core/script/resources/layered_api/kv-storage/idb_utils.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> <include name="IDR_LAYERED_API_KV_STORAGE_INDEX_MJS" file="../renderer/core/script/resources/layered_api/kv-storage/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> - <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_INDEX_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> - <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_ITEM_SOURCE_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/item-source.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> - <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_VIRTUAL_REPEATER_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/virtual-repeater.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> - <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_VIRTUAL_SCROLLER_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/virtual-scroller.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> - <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_BASE_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-base.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> - <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_GRID_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-grid.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> - <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> </grit-part>
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/README.chromium b/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/README.chromium deleted file mode 100644 index e8b4d5d..0000000 --- a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/README.chromium +++ /dev/null
@@ -1,12 +0,0 @@ -Name: virtual-scroller Layered API -URL: https://github.com/valdrinkoshi/virtual-scroller -Version: 58659cee10c5d9237821d5c475dac89720bd995d -Security Critical: no - -Description: -Temporarily, the files under this directory are authored by Chromium Authors -on a github repository, and then imported to Chromium repository directly here, -until a long-term Layered API development plan is settled. - -Local Modifications: -None (except for renaming virtual-scroller-element.mjs to index.mjs)
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/index.mjs b/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/index.mjs deleted file mode 100644 index 8cdad80..0000000 --- a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/index.mjs +++ /dev/null
@@ -1,213 +0,0 @@ -import {_item, _key, ItemSource} from './item-source.mjs'; -import {default as Layout1dGrid} from './layouts/layout-1d-grid.mjs'; -import {default as Layout1d} from './layouts/layout-1d.mjs'; -import {VirtualScroller} from './virtual-scroller.mjs'; - -export {ItemSource}; - -/** Properties */ -const _scroller = Symbol(); -const _createElement = Symbol(); -const _updateElement = Symbol(); -const _recycleElement = Symbol(); -const _nodePool = Symbol(); -const _rawItemSource = Symbol(); -const _itemSource = Symbol(); -const _elementSource = Symbol(); -const _firstConnected = Symbol(); -/** Functions */ -const _render = Symbol(); - -export class VirtualScrollerElement extends HTMLElement { - constructor() { - super(); - this[_scroller] = null; - // Default create/update/recycleElement. - this[_nodePool] = []; - let childTemplate = null; - this[_createElement] = () => { - if (this[_nodePool] && this[_nodePool].length) { - return this[_nodePool].pop(); - } - if (!childTemplate) { - const template = this.querySelector('template'); - childTemplate = template && template.content.firstElementChild ? - template.content.firstElementChild : - document.createElement('div'); - } - return childTemplate.cloneNode(true); - }; - this[_updateElement] = (element, item) => element.textContent = - item.toString(); - this[_recycleElement] = (element) => this[_nodePool].push(element); - - this[_itemSource] = this[_rawItemSource] = null; - this[_elementSource] = {}; - - this[_firstConnected] = false; - } - - connectedCallback() { - if (!this[_firstConnected]) { - this.attachShadow({mode: 'open'}).innerHTML = ` -<style> - :host { - display: block; - position: relative; - contain: strict; - height: 150px; - overflow: auto; - } - :host([hidden]) { - display: none; - } - ::slotted(*) { - box-sizing: border-box; - } - :host([layout=vertical]) ::slotted(*) { - width: 100%; - } - :host([layout=horizontal]) ::slotted(*) { - height: 100%; - } -</style> -<slot></slot>`; - // Set default values. - if (!this.layout) { - this.layout = 'vertical'; - } - // Enables rendering. - this[_firstConnected] = true; - } - this[_render](); - } - - static get observedAttributes() { - return ['layout']; - } - - attributeChangedCallback(name, oldVal, newVal) { - this[_render](); - } - - get layout() { - return this.getAttribute('layout'); - } - set layout(layout) { - this.setAttribute('layout', layout); - } - - get itemSource() { - return this[_itemSource]; - } - set itemSource(itemSource) { - // No Change. - if (this[_rawItemSource] === itemSource) { - return; - } - this[_rawItemSource] = itemSource; - this[_itemSource] = Array.isArray(itemSource) ? - ItemSource.fromArray(itemSource) : - itemSource; - this[_render](); - } - - get createElement() { - return this[_createElement]; - } - set createElement(fn) { - // Resets default recycling. - if (this[_nodePool]) { - this.recycleElement = null; - } - this[_createElement] = fn; - // Invalidate wrapped function. - this[_elementSource].createElement = null; - this[_render](); - } - - get updateElement() { - return this[_updateElement]; - } - set updateElement(fn) { - this[_updateElement] = fn; - // Invalidate wrapped function. - this[_elementSource].updateElement = null; - this[_render](); - } - - get recycleElement() { - return this[_recycleElement]; - } - set recycleElement(fn) { - // Marks default recycling changed. - this[_nodePool] = null; - this[_recycleElement] = fn; - // Invalidate wrapped function. - this[_elementSource].recycleElement = null; - this[_render](); - } - - itemsChanged() { - if (this[_scroller]) { - // Render because length might have changed. - this[_render](); - // Request reset because items might have changed. - this[_scroller].requestReset(); - } - } - - scrollToIndex(index, { position = 'start' } = {}) { - if (this[_scroller]) { - this[_scroller].layout.scrollToIndex(index, position); - } - } - - [_render]() { - // Wait first connected as scroller needs to measure - // sizes of container and children. - if (!this[_firstConnected] || !this.createElement) { - return; - } - if (!this[_scroller]) { - this[_scroller] = - new VirtualScroller({container: this, scrollTarget: this}); - } - const scroller = this[_scroller]; - - const layoutAttr = this.layout; - const Layout = layoutAttr.endsWith('-grid') ? Layout1dGrid : Layout1d; - const direction = - layoutAttr.startsWith('horizontal') ? 'horizontal' : 'vertical'; - const layout = scroller.layout instanceof Layout && - scroller.layout.direction === direction ? - scroller.layout : - new Layout({direction}); - - let {createElement, updateElement, recycleElement} = this[_elementSource]; - if (!createElement) { - createElement = this[_elementSource].createElement = (index) => - this.createElement(this.itemSource[_item](index), index); - } - if (this.updateElement && !updateElement) { - updateElement = this[_elementSource].updateElement = (element, index) => - this.updateElement(element, this.itemSource[_item](index), index); - } - if (this.recycleElement && !recycleElement) { - recycleElement = this[_elementSource].recycleElement = (element, index) => - this.recycleElement(element, this.itemSource[_item](index), index); - } - - const elementKey = this.itemSource ? this.itemSource[_key] : null; - const totalItems = this.itemSource ? this.itemSource.length : 0; - Object.assign(scroller, { - layout, - createElement, - updateElement, - recycleElement, - elementKey, - totalItems - }); - } -} -customElements.define('virtual-scroller', VirtualScrollerElement);
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/item-source.mjs b/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/item-source.mjs deleted file mode 100644 index 255e97b2..0000000 --- a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/item-source.mjs +++ /dev/null
@@ -1,47 +0,0 @@ -export const _getLength = Symbol(); -export const _item = Symbol(); -export const _key = Symbol(); - -export class ItemSource { - constructor({getLength, item, key}) { - if (typeof getLength !== 'function') { - throw new TypeError('getLength option must be a function'); - } - if (typeof item !== 'function') { - throw new TypeError('item option must be a function'); - } - if (typeof key !== 'function') { - throw new TypeError('key option must be a function'); - } - - this[_getLength] = getLength; - this[_item] = item; - this[_key] = key; - } - - static fromArray(array, key) { - if (!Array.isArray(array)) { - throw new TypeError('First argument to fromArray() must be an array'); - } - if (typeof key !== 'function' && key !== undefined) { - throw new TypeError( - 'Second argument to fromArray() must be a function or undefined'); - } - - return new this({ - getLength() { - return array.length; - }, - item(index) { - return array[index]; - }, - key(index) { - return key ? key(array[index], index) : array[index]; - } - }); - } - - get length() { - return this[_getLength](); - } -}
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-base.mjs b/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-base.mjs deleted file mode 100644 index 89a9a9e..0000000 --- a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-base.mjs +++ /dev/null
@@ -1,320 +0,0 @@ -export default class Layout extends EventTarget { - constructor(config) { - super(); - - this._physicalMin = 0; - this._physicalMax = 0; - - this._first = -1; - this._last = -1; - - this._latestCoords = {left: 0, top: 0}; - - this._itemSize = {width: 100, height: 100}; - this._spacing = 0; - - this._sizeDim = 'height'; - this._secondarySizeDim = 'width'; - this._positionDim = 'top'; - this._secondaryPositionDim = 'left'; - this._direction = 'vertical'; - - this._scrollPosition = 0; - this._scrollError = 0; - this._viewportSize = {width: 0, height: 0}; - this._totalItems = 0; - - this._scrollSize = 1; - - this._overhang = 150; - - this._pendingReflow = false; - - this._scrollToIndex = -1; - this._scrollToAnchor = 0; - - Object.assign(this, config); - } - - // public properties - - get totalItems() { - return this._totalItems; - } - set totalItems(num) { - if (num !== this._totalItems) { - this._totalItems = num; - this._maxIdx = num - 1; - this._scheduleReflow(); - } - } - - get direction() { - return this._direction; - } - set direction(dir) { - // Force it to be either horizontal or vertical. - dir = (dir === 'horizontal') ? dir : 'vertical'; - if (dir !== this._direction) { - this._direction = dir; - this._sizeDim = (dir === 'horizontal') ? 'width' : 'height'; - this._secondarySizeDim = (dir === 'horizontal') ? 'height' : 'width'; - this._positionDim = (dir === 'horizontal') ? 'left' : 'top'; - this._secondaryPositionDim = (dir === 'horizontal') ? 'top' : 'left'; - this._scheduleReflow(); - } - } - - get itemSize() { - return this._itemSize; - } - set itemSize(dims) { - const {_itemDim1, _itemDim2} = this; - Object.assign(this._itemSize, dims); - if (_itemDim1 !== this._itemDim1 || _itemDim2 !== this._itemDim2) { - if (_itemDim2 !== this._itemDim2) { - this._itemDim2Changed(); - } else { - this._scheduleReflow(); - } - } - } - - get spacing() { - return this._spacing; - } - set spacing(px) { - if (px !== this._spacing) { - this._spacing = px; - this._scheduleReflow(); - } - } - - get viewportSize() { - return this._viewportSize; - } - set viewportSize(dims) { - const {_viewDim1, _viewDim2} = this; - Object.assign(this._viewportSize, dims); - if (_viewDim2 !== this._viewDim2) { - this._viewDim2Changed(); - } else if (_viewDim1 !== this._viewDim1) { - this._checkThresholds(); - } - } - - get viewportScroll() { - return this._latestCoords; - } - set viewportScroll(coords) { - Object.assign(this._latestCoords, coords); - const oldPos = this._scrollPosition; - this._scrollPosition = this._latestCoords[this._positionDim]; - if (oldPos !== this._scrollPosition) { - this._scrollPositionChanged(oldPos, this._scrollPosition); - } - this._checkThresholds(); - } - - // private properties - - get _delta() { - return this._itemDim1 + this._spacing; - } - - get _itemDim1() { - return this._itemSize[this._sizeDim]; - } - - get _itemDim2() { - return this._itemSize[this._secondarySizeDim]; - } - - get _viewDim1() { - return this._viewportSize[this._sizeDim]; - } - - get _viewDim2() { - return this._viewportSize[this._secondarySizeDim]; - } - - get _num() { - if (this._first === -1 || this._last === -1) { - return 0; - } - return this._last - this._first + 1; - } - - // public methods - - reflowIfNeeded() { - if (this._pendingReflow) { - this._pendingReflow = false; - this._reflow(); - } - } - - scrollToIndex(index, position = 'start') { - if (!Number.isFinite(index)) - return; - index = Math.min(this.totalItems, Math.max(0, index)); - this._scrollToIndex = index; - if (position === 'nearest') { - position = index > this._first + this._num / 2 ? 'end' : 'start'; - } - switch (position) { - case 'start': - this._scrollToAnchor = 0; - break; - case 'center': - this._scrollToAnchor = 0.5; - break; - case 'end': - this._scrollToAnchor = 1; - break; - default: - throw new TypeError( - 'position must be one of: start, center, end, nearest'); - } - this._scheduleReflow(); - this.reflowIfNeeded(); - } - - /// - - _scheduleReflow() { - this._pendingReflow = true; - } - - _reflow() { - const {_first, _last, _scrollSize} = this; - - this._updateScrollSize(); - this._getActiveItems(); - this._scrollIfNeeded(); - - if (this._scrollSize !== _scrollSize) { - this._emitScrollSize(); - } - - if (this._first === -1 && this._last === -1) { - this._emitRange(); - } else if ( - this._first !== _first || this._last !== _last || - this._spacingChanged) { - this._emitRange(); - this._emitChildPositions(); - } - this._emitScrollError(); - } - - _updateScrollSize() { - // Ensure we have at least 1px - this allows getting at least 1 item to be - // rendered. - this._scrollSize = Math.max(1, this._totalItems * this._delta); - } - - _checkThresholds() { - if (this._viewDim1 === 0 && this._num > 0) { - this._scheduleReflow(); - } else { - const min = Math.max(0, this._scrollPosition - this._overhang); - const max = Math.min( - this._scrollSize, - this._scrollPosition + this._viewDim1 + this._overhang); - if (this._physicalMin > min || this._physicalMax < max) { - this._scheduleReflow(); - } - } - } - - _scrollIfNeeded() { - if (this._scrollToIndex === -1) { - return; - } - const index = this._scrollToIndex; - const anchor = this._scrollToAnchor; - const pos = this._getItemPosition(index)[this._positionDim]; - const size = this._getItemSize(index)[this._sizeDim]; - - const curAnchorPos = this._scrollPosition + this._viewDim1 * anchor; - const newAnchorPos = pos + size * anchor; - // Ensure scroll position is an integer within scroll bounds. - const scrollPosition = Math.floor(Math.min( - this._scrollSize - this._viewDim1, - Math.max(0, this._scrollPosition - curAnchorPos + newAnchorPos))); - this._scrollError += this._scrollPosition - scrollPosition; - this._scrollPosition = scrollPosition; - } - - _emitRange(inProps) { - const detail = Object.assign( - { - first: this._first, - last: this._last, - num: this._num, - stable: true, - }, - inProps); - this.dispatchEvent(new CustomEvent('rangechange', {detail})); - } - - _emitScrollSize() { - const detail = { - [this._sizeDim]: this._scrollSize, - }; - this.dispatchEvent(new CustomEvent('scrollsizechange', {detail})); - } - - _emitScrollError() { - if (this._scrollError) { - const detail = { - [this._positionDim]: this._scrollError, - [this._secondaryPositionDim]: 0, - }; - this.dispatchEvent(new CustomEvent('scrollerrorchange', {detail})); - this._scrollError = 0; - } - } - - _emitChildPositions() { - const detail = {}; - for (let idx = this._first; idx <= this._last; idx++) { - detail[idx] = this._getItemPosition(idx); - } - this.dispatchEvent(new CustomEvent('itempositionchange', {detail})); - } - - _itemDim2Changed() { - // Override - } - - _viewDim2Changed() { - // Override - } - - _scrollPositionChanged(oldPos, newPos) { - // When both values are bigger than the max scroll position, keep the - // current _scrollToIndexx, otherwise invalidate it. - const maxPos = this._scrollSize - this._viewDim1; - if (oldPos < maxPos || newPos < maxPos) { - this._scrollToIndex = -1; - } - } - - _getActiveItems() { - // Override - } - - _getItemPosition(idx) { - // Override. - } - - _getItemSize(idx) { - // Override. - return { - [this._sizeDim]: this._itemDim1, - [this._secondarySizeDim]: this._itemDim2, - }; - } -} \ No newline at end of file
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-grid.mjs b/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-grid.mjs deleted file mode 100644 index c9c00d0..0000000 --- a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-grid.mjs +++ /dev/null
@@ -1,64 +0,0 @@ -import Layout1dBase from './layout-1d-base.mjs'; - -export default class Layout extends Layout1dBase { - constructor(config) { - super(config); - this._rolumns = 1; - } - - updateItemSizes(sizes) { - // Assume all items have the same size. - const size = Object.values(sizes)[0]; - if (size) { - this.itemSize = size; - } - } - - _viewDim2Changed() { - this._defineGrid(); - } - - _itemDim2Changed() { - this._defineGrid(); - } - - _getActiveItems() { - const min = Math.max(0, this._scrollPosition - this._overhang); - const max = Math.min( - this._scrollSize, - this._scrollPosition + this._viewDim1 + this._overhang); - const firstCow = Math.floor(min / this._delta); - const lastCow = Math.ceil(max / this._delta) - 1; - - this._first = firstCow * this._rolumns; - this._last = - Math.min(((lastCow + 1) * this._rolumns) - 1, this._totalItems); - this._physicalMin = this._delta * firstCow; - this._physicalMax = this._delta * (lastCow + 1); - } - - _getItemPosition(idx) { - return { - [this._positionDim]: Math.floor(idx / this._rolumns) * this._delta, - [this._secondaryPositionDim]: this._spacing + - ((idx % this._rolumns) * (this._spacing + this._itemDim2)) - } - } - - - _defineGrid() { - const {_spacing} = this; - this._rolumns = Math.max(1, Math.floor(this._viewDim2 / this._itemDim2)); - if (this._rolumns > 1) { - this._spacing = (this._viewDim2 % (this._rolumns * this._itemDim2)) / - (this._rolumns + 1); - } - this._spacingChanged = !(_spacing === this._spacing); - this._scheduleReflow(); - } - - _updateScrollSize() { - this._scrollSize = - Math.max(1, Math.ceil(this._totalItems / this._rolumns) * this._delta); - } -} \ No newline at end of file
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d.mjs b/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d.mjs deleted file mode 100644 index 6f5d181..0000000 --- a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d.mjs +++ /dev/null
@@ -1,349 +0,0 @@ -import Layout1dBase from './layout-1d-base.mjs'; - -export default class Layout extends Layout1dBase { - constructor(config) { - super(config); - this._physicalItems = new Map(); - this._newPhysicalItems = new Map(); - - this._metrics = new Map(); - - this._anchorIdx = null; - this._anchorPos = null; - this._stable = true; - - this._needsRemeasure = false; - - this._nMeasured = 0; - this._tMeasured = 0; - - this._estimate = true; - } - - updateItemSizes(sizes) { - Object.keys(sizes).forEach((key) => { - const metrics = sizes[key], mi = this._getMetrics(key), - prevSize = mi[this._sizeDim]; - - // TODO(valdrin) Handle margin collapsing. - // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing - mi.width = metrics.width + (metrics.marginLeft || 0) + - (metrics.marginRight || 0); - mi.height = metrics.height + (metrics.marginTop || 0) + - (metrics.marginBottom || 0); - - const size = mi[this._sizeDim]; - const item = this._getPhysicalItem(Number(key)); - if (item) { - let delta; - - if (size !== undefined) { - item.size = size; - if (prevSize === undefined) { - delta = size; - this._nMeasured++; - } else { - delta = size - prevSize; - } - } - this._tMeasured = this._tMeasured + delta; - } else { - // console.debug(`Could not find physical item for key ${key}`); - } - }); - if (!this._nMeasured) { - console.warn(`No items measured yet.`); - } else { - this._updateItemSize(); - this._scheduleReflow(); - } - } - - _updateItemSize() { - // Keep integer values. - this._itemSize[this._sizeDim] = - Math.round(this._tMeasured / this._nMeasured); - } - - // - - _getMetrics(idx) { - return (this._metrics[idx] = this._metrics[idx] || {}); - } - - _getPhysicalItem(idx) { - return this._newPhysicalItems.get(idx) || this._physicalItems.get(idx); - } - - _getSize(idx) { - const item = this._getPhysicalItem(idx); - return item && item.size; - } - - _getPosition(idx) { - const item = this._physicalItems.get(idx); - return item ? item.pos : (idx * (this._delta)) + this._spacing; - } - - _calculateAnchor(lower, upper) { - if (lower === 0) { - return 0; - } - if (upper > this._scrollSize - this._viewDim1) { - return this._maxIdx; - } - return Math.max( - 0, - Math.min( - this._maxIdx, Math.floor(((lower + upper) / 2) / this._delta))); - } - - _getAnchor(lower, upper) { - if (this._physicalItems.size === 0) { - return this._calculateAnchor(lower, upper); - } - if (this._first < 0) { - console.error('_getAnchor: negative _first'); - return this._calculateAnchor(lower, upper); - } - if (this._last < 0) { - console.error('_getAnchor: negative _last'); - return this._calculateAnchor(lower, upper); - } - - const firstItem = this._getPhysicalItem(this._first), - lastItem = this._getPhysicalItem(this._last), - firstMin = firstItem.pos, firstMax = firstMin + firstItem.size, - lastMin = lastItem.pos, lastMax = lastMin + lastItem.size; - - if (lastMax < lower) { - // Window is entirely past physical items, calculate new anchor - return this._calculateAnchor(lower, upper); - } - if (firstMin > upper) { - // Window is entirely before physical items, calculate new anchor - return this._calculateAnchor(lower, upper); - } - if (firstMin >= lower || firstMax >= lower) { - // First physical item overlaps window, choose it - return this._first; - } - if (lastMax <= upper || lastMin <= upper) { - // Last physical overlaps window, choose it - return this._last; - } - // Window contains a physical item, but not the first or last - let maxIdx = this._last, minIdx = this._first; - - while (true) { - let candidateIdx = Math.round((maxIdx + minIdx) / 2), - candidate = this._physicalItems.get(candidateIdx), - cMin = candidate.pos, cMax = cMin + candidate.size; - - if ((cMin >= lower && cMin <= upper) || - (cMax >= lower && cMax <= upper)) { - return candidateIdx; - } else if (cMax < lower) { - minIdx = candidateIdx + 1; - } else if (cMin > upper) { - maxIdx = candidateIdx - 1; - } - } - } - - _getActiveItems() { - if (this._viewDim1 === 0 || this._totalItems === 0) { - this._clearItems(); - } else { - const upper = Math.min( - this._scrollSize, - this._scrollPosition + this._viewDim1 + this._overhang), - lower = Math.max(0, upper - this._viewDim1 - (2 * this._overhang)); - - this._getItems(lower, upper); - } - } - - _clearItems() { - this._first = -1; - this._last = -1; - this._physicalMin = 0; - this._physicalMax = 0; - const items = this._newPhysicalItems; - this._newPhysicalItems = this._physicalItems; - this._newPhysicalItems.clear(); - this._physicalItems = items; - this._stable = true; - } - - _getItems(lower, upper) { - const items = this._newPhysicalItems; - - // The anchorIdx is the anchor around which we reflow. - // It is designed to allow jumping to any point of the scroll size. - // We choose it once and stick with it until stable. first and last are - // deduced around it. - if (this._anchorIdx === null || this._anchorPos === null) { - this._anchorIdx = this._getAnchor(lower, upper); - this._anchorPos = this._getPosition(this._anchorIdx); - } - - let anchorSize = this._getSize(this._anchorIdx); - if (anchorSize === undefined) { - anchorSize = this._itemDim1; - } - - // Anchor might be outside bounds, so prefer correcting the error and keep - // that anchorIdx. - let anchorErr = 0; - - if (this._anchorPos + anchorSize + this._spacing < lower) { - anchorErr = lower - (this._anchorPos + anchorSize + this._spacing); - } - - if (this._anchorPos > upper) { - anchorErr = upper - this._anchorPos; - } - - if (anchorErr) { - this._scrollPosition -= anchorErr; - lower -= anchorErr; - upper -= anchorErr; - this._scrollError += anchorErr; - } - - items.set(this._anchorIdx, {pos: this._anchorPos, size: anchorSize}); - - this._first = (this._last = this._anchorIdx); - this._physicalMin = (this._physicalMax = this._anchorPos); - - this._stable = true; - - while (this._physicalMin > lower && this._first > 0) { - let size = this._getSize(--this._first); - if (size === undefined) { - this._stable = false; - size = this._itemDim1; - } - const pos = (this._physicalMin -= size + this._spacing); - items.set(this._first, {pos, size}); - if (this._stable === false && this._estimate === false) { - break; - } - } - - while (this._physicalMax < upper && this._last < this._totalItems) { - let size = this._getSize(this._last); - if (size === undefined) { - this._stable = false; - size = this._itemDim1; - } - items.set(this._last++, {pos: this._physicalMax, size}); - if (this._stable === false && this._estimate === false) { - break; - } else { - this._physicalMax += size + this._spacing; - } - } - - this._last--; - - // This handles the cases where we were relying on estimated sizes. - const extentErr = this._calculateError(); - if (extentErr) { - this._physicalMin -= extentErr; - this._physicalMax -= extentErr; - this._anchorPos -= extentErr; - this._scrollPosition -= extentErr; - items.forEach(item => item.pos -= extentErr); - this._scrollError += extentErr; - } - - if (this._stable) { - this._newPhysicalItems = this._physicalItems; - this._newPhysicalItems.clear(); - this._physicalItems = items; - } - } - - _calculateError() { - if (this._first === 0) { - return this._physicalMin; - } else if (this._physicalMin <= 0) { - return this._physicalMin - (this._first * this._delta); - } else if (this._last === this._maxIdx) { - return this._physicalMax - this._scrollSize; - } else if (this._physicalMax >= this._scrollSize) { - return ( - (this._physicalMax - this._scrollSize) + - ((this._maxIdx - this._last) * this._delta)); - } - return 0; - } - - _updateScrollSize() { - // Reuse previously calculated physical max, as it might be - // higher than the estimated size. - super._updateScrollSize(); - this._scrollSize = Math.max(this._physicalMax, this._scrollSize); - } - - // TODO: Can this be made to inherit from base, with proper hooks? - _reflow() { - const {_first, _last, _scrollSize} = this; - - this._updateScrollSize(); - this._getActiveItems(); - this._scrollIfNeeded(); - - if (this._scrollSize !== _scrollSize) { - this._emitScrollSize(); - } - - this._emitRange(); - if (this._first === -1 && this._last === -1) { - this._resetReflowState(); - } else if ( - this._first !== _first || this._last !== _last || - this._needsRemeasure) { - this._emitChildPositions(); - this._emitScrollError(); - } else { - this._emitChildPositions(); - this._emitScrollError(); - this._resetReflowState(); - } - } - - _resetReflowState() { - this._anchorIdx = null; - this._anchorPos = null; - this._stable = true; - } - - _getItemPosition(idx) { - return { - [this._positionDim]: this._getPosition(idx), - [this._secondaryPositionDim]: 0 - } - } - - _getItemSize(idx) { - return { - [this._sizeDim]: this._getSize(idx) || this._itemDim1, - [this._secondarySizeDim]: this._itemDim2, - }; - } - - _viewDim2Changed() { - this._needsRemeasure = true; - this._scheduleReflow(); - } - - _emitRange() { - const remeasure = this._needsRemeasure; - const stable = this._stable; - this._needsRemeasure = false; - super._emitRange({remeasure, stable}); - } -}
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-repeater.mjs b/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-repeater.mjs deleted file mode 100644 index 3d3cb6a..0000000 --- a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-repeater.mjs +++ /dev/null
@@ -1,531 +0,0 @@ -export const Repeats = Superclass => class extends Superclass { - constructor(config) { - super(); - - this._createElementFn = null; - this._updateElementFn = null; - this._recycleElementFn = null; - this._elementKeyFn = null; - - this._measureCallback = null; - - this._totalItems = 0; - // Consider renaming this. firstVisibleIndex? - this._first = 0; - // Consider renaming this. count? visibleElements? - this._num = Infinity; - - this.__incremental = false; - - // used only internally.. - // legacy from 1st approach to preact integration - this._manageDom = true; - // used to check if it is more perf if you don't care of dom order? - this._maintainDomOrder = true; - - this._last = 0; - this._prevFirst = 0; - this._prevLast = 0; - - this._needsReset = false; - this._needsRemeasure = false; - this._pendingRender = null; - - // Contains child nodes in the rendered order. - this._ordered = []; - // this._pool = []; - this._active = new Map(); - this._prevActive = new Map(); - // Both used for recycling purposes. - this._keyToChild = new Map(); - this._childToKey = new WeakMap(); - // Used to keep track of measures by index. - this._indexToMeasure = {}; - // Used to debounce _measureChildren calls. - this._measuringId = -1; - - if (config) { - Object.assign(this, config); - } - } - - // API - - get container() { - return this._container; - } - set container(container) { - if (container === this._container) { - return; - } - if (this._container) { - // Remove children from old container. - this._ordered.forEach((child) => this._removeChild(child)); - } - - this._container = container; - - if (container) { - // Insert children in new container. - this._ordered.forEach((child) => this._insertBefore(child, null)); - } else { - this._ordered.length = 0; - this._active.clear(); - this._prevActive.clear(); - } - this.requestReset(); - } - - get createElement() { - return this._createElementFn; - } - set createElement(fn) { - if (fn !== this._createElementFn) { - this._createElementFn = fn; - this._keyToChild.clear(); - this.requestReset(); - } - } - - get updateElement() { - return this._updateElementFn; - } - set updateElement(fn) { - if (fn !== this._updateElementFn) { - this._updateElementFn = fn; - this.requestReset(); - } - } - - get recycleElement() { - return this._recycleElementFn; - } - set recycleElement(fn) { - if (fn !== this._recycleElementFn) { - this._recycleElementFn = fn; - this.requestReset(); - } - } - - get elementKey() { - return this._elementKeyFn; - } - set elementKey(fn) { - if (fn !== this._elementKeyFn) { - this._elementKeyFn = fn; - this._keyToChild.clear(); - this.requestReset(); - } - } - - get first() { - return this._first; - } - - set first(idx) { - if (typeof idx === 'number') { - const newFirst = Math.max(0, Math.min(idx, this._totalItems - this._num)); - if (newFirst !== this._first) { - this._first = newFirst; - this._scheduleRender(); - } - } - } - - get num() { - return this._num; - } - - set num(n) { - if (typeof n === 'number') { - if (n !== this._num) { - this._num = n; - this.first = this._first; - this._scheduleRender(); - } - } - } - - get totalItems() { - return this._totalItems; - } - - set totalItems(num) { - // TODO(valdrin) should we check if it is a finite number? - // Technically, Infinity would break Layout, not VirtualRepeater. - if (typeof num === 'number' && num !== this._totalItems) { - this._totalItems = num; - this.first = this._first; - this.requestReset(); - } - } - - get _incremental() { - return this.__incremental; - } - - set _incremental(inc) { - if (inc !== this.__incremental) { - this.__incremental = inc; - this._scheduleRender(); - } - } - - requestReset() { - this._needsReset = true; - this._scheduleRender(); - } - - requestRemeasure() { - this._needsRemeasure = true; - this._scheduleRender(); - } - - // Core functionality - - /** - * @protected - */ - _shouldRender() { - return Boolean(this.container && this.createElement); - } - - /** - * @private - */ - _scheduleRender() { - if (!this._pendingRender) { - this._pendingRender = requestAnimationFrame(() => { - this._pendingRender = null; - if (this._shouldRender()) { - this._render(); - } - }); - } - } - - /** - * Returns those children that are about to be displayed and that - * require to be positioned. If reset or remeasure has been triggered, - * all children are returned. - * @return {{indices:Array<number>,children:Array<Element>}} - * @private - */ - get _toMeasure() { - return this._ordered.reduce((toMeasure, c, i) => { - const idx = this._first + i; - if (this._needsReset || this._needsRemeasure || idx < this._prevFirst || - idx > this._prevLast) { - toMeasure.indices.push(idx); - toMeasure.children.push(c); - } - return toMeasure; - }, {indices: [], children: []}); - } - - /** - * Measures each child bounds and builds a map of index/bounds to be passed to - * the `_measureCallback` - * @private - */ - _measureChildren({indices, children}) { - let pm = children.map( - (c, i) => this._indexToMeasure[indices[i]] || this._measureChild(c)); - const mm = /** @type {{ number: { width: number, height: number } }} */ - (pm.reduce((out, cur, i) => { - out[indices[i]] = this._indexToMeasure[indices[i]] = cur; - return out; - }, {})); - this._measureCallback(mm); - } - - /** - * @protected - */ - _render() { - const rangeChanged = - this._first !== this._prevFirst || this._num !== this._prevNum; - // Create/update/recycle DOM. - if (rangeChanged || this._needsReset) { - this._last = - this._first + Math.min(this._num, this._totalItems - this._first) - 1; - if (this._num || this._prevNum) { - if (this._needsReset) { - this._reset(this._first, this._last); - } else { - this._discardHead(); - this._discardTail(); - this._addHead(); - this._addTail(); - } - } - } - if (this._needsRemeasure || this._needsReset) { - this._indexToMeasure = {}; - } - // Retrieve DOM to be measured. - // Do it right before cleanup and reset of properties. - const shouldMeasure = this._num > 0 && this._measureCallback && - (rangeChanged || this._needsRemeasure || this._needsReset); - const toMeasure = shouldMeasure ? this._toMeasure : null; - - // Cleanup. - if (!this._incremental) { - this._prevActive.forEach((idx, child) => this._unassignChild(child, idx)); - this._prevActive.clear(); - } - // Reset internal properties. - this._prevFirst = this._first; - this._prevLast = this._last; - this._prevNum = this._num; - this._needsReset = false; - this._needsRemeasure = false; - - // Notify render completed. - this._didRender(); - // Measure DOM. - if (toMeasure) { - this._measureChildren(toMeasure); - } - } - - /** - * Invoked after DOM is updated, and before it gets measured. - * @protected - */ - _didRender() { - } - - /** - * @private - */ - _discardHead() { - const o = this._ordered; - for (let idx = this._prevFirst; o.length && idx < this._first; idx++) { - this._unassignChild(o.shift(), idx); - } - } - - /** - * @private - */ - _discardTail() { - const o = this._ordered; - for (let idx = this._prevLast; o.length && idx > this._last; idx--) { - this._unassignChild(o.pop(), idx); - } - } - - /** - * @private - */ - _addHead() { - const start = this._first; - const end = Math.min(this._last, this._prevFirst - 1); - for (let idx = end; idx >= start; idx--) { - const child = this._assignChild(idx); - if (this._manageDom) { - if (this._maintainDomOrder || !this._childIsAttached(child)) { - this._insertBefore(child, this._firstChild); - } - } - if (this.updateElement) { - this.updateElement(child, idx); - } - this._ordered.unshift(child); - } - } - - /** - * @private - */ - _addTail() { - const start = Math.max(this._first, this._prevLast + 1); - const end = this._last; - for (let idx = start; idx <= end; idx++) { - const child = this._assignChild(idx); - if (this._manageDom) { - if (this._maintainDomOrder || !this._childIsAttached(child)) { - this._insertBefore(child, null); - } - } - if (this.updateElement) { - this.updateElement(child, idx); - } - this._ordered.push(child); - } - } - - /** - * @param {number} first - * @param {number} last - * @private - */ - _reset(first, last) { - const len = last - first + 1; - // Explain why swap prevActive with active - affects _assignChild. - const prevActive = this._active; - this._active = this._prevActive; - this._prevActive = prevActive; - let currentMarker = this._manageDom && this._firstChild; - this._ordered.length = 0; - for (let n = 0; n < len; n++) { - const idx = first + n; - const child = this._assignChild(idx); - this._ordered.push(child); - if (this._manageDom) { - if (currentMarker && this._maintainDomOrder) { - if (currentMarker === this._node(child)) { - currentMarker = this._nextSibling(child); - } else { - this._insertBefore(child, currentMarker); - } - } else if (!this._childIsAttached(child)) { - this._insertBefore(child, null); - } - } - if (this.updateElement) { - this.updateElement(child, idx); - } - } - } - - /** - * @param {number} idx - * @private - */ - _assignChild(idx) { - const key = this.elementKey ? this.elementKey(idx) : idx; - let child; - if (child = this._keyToChild.get(key)) { - this._prevActive.delete(child); - } else { - child = this.createElement(idx); - this._keyToChild.set(key, child); - this._childToKey.set(child, key); - } - this._showChild(child); - this._active.set(child, idx); - return child; - } - - /** - * @param {*} child - * @param {number} idx - * @private - */ - _unassignChild(child, idx) { - this._hideChild(child); - if (this._incremental) { - this._active.delete(child); - this._prevActive.set(child, idx); - } else { - const key = this._childToKey.get(child); - this._childToKey.delete(child); - this._keyToChild.delete(key); - this._active.delete(child); - if (this.recycleElement) { - this.recycleElement(child, idx); - } else if (this._node(child).parentNode) { - this._removeChild(child); - } - } - } - - // TODO: Is this the right name? - /** - * @private - */ - get _firstChild() { - return this._ordered.length && this._childIsAttached(this._ordered[0]) ? - this._node(this._ordered[0]) : - null; - } - - // Overridable abstractions for child manipulation - /** - * @protected - */ - _node(child) { - return child; - } - /** - * @protected - */ - _nextSibling(child) { - return child.nextSibling; - } - /** - * @protected - */ - _insertBefore(child, referenceNode) { - this._container.insertBefore(child, referenceNode); - } - /** - * @protected - */ - _childIsAttached(child) { - const node = this._node(child); - return node && node.parentNode === this._container; - } - /** - * @protected - */ - _hideChild(child) { - if (child.style) { - child.style.display = 'none'; - } - } - /** - * @protected - */ - _showChild(child) { - if (child.style) { - child.style.display = null; - } - } - - /** - * - * @param {!Element} child - * @return {{width: number, height: number, marginTop: number, marginBottom: number, marginLeft: number, marginRight: number}} childMeasures - * @protected - */ - _measureChild(child) { - // offsetWidth doesn't take transforms in consideration, - // so we use getBoundingClientRect which does. - const {width, height} = child.getBoundingClientRect(); - // console.debug(`_measureChild #${this._container.id} > #${ - // child.id}: height: ${height}px`); - return Object.assign({width, height}, getMargins(child)); - } - - /** - * Remove child. - * Override to control child removal. - * - * @param {*} child - * @protected - */ - _removeChild(child) { - child.parentNode.removeChild(child); - } -} - -function getMargins(el) { - const style = window.getComputedStyle(el); - // console.log(el.id, style.position); - return { - marginLeft: getMarginValue(style.marginLeft), - marginRight: getMarginValue(style.marginRight), - marginTop: getMarginValue(style.marginTop), - marginBottom: getMarginValue(style.marginBottom), - }; -} - -function getMarginValue(value) { - value = value ? parseFloat(value) : NaN; - return value !== value ? 0 : value; -} - -export const VirtualRepeater = Repeats(class {}); \ No newline at end of file
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-scroller.mjs b/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-scroller.mjs deleted file mode 100644 index 049501e6..0000000 --- a/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-scroller.mjs +++ /dev/null
@@ -1,444 +0,0 @@ -import {Repeats} from './virtual-repeater.mjs'; - -export class RangeChangeEvent extends Event { - constructor(type, init) { - super(type, init); - this._first = Math.floor(init.first || 0); - this._last = Math.floor(init.last || 0); - } - get first() { - return this._first; - } - get last() { - return this._last; - } -} - -export const RepeatsAndScrolls = Superclass => class extends Repeats -(Superclass) { - constructor(config) { - super(); - this._num = 0; - this._first = -1; - this._last = -1; - this._prevFirst = -1; - this._prevLast = -1; - - this._needsUpdateView = false; - this._containerElement = null; - this._layout = null; - this._scrollTarget = null; - // Keep track of original inline style of the container, - // so it can be restored when container is changed. - this._containerInlineStyle = null; - // A sentinel element that sizes the container when - // it is a scrolling element. - this._sizer = null; - // Layout provides these values, we set them on _render(). - this._scrollSize = null; - this._scrollErr = null; - this._childrenPos = null; - - this._containerSize = null; - this._containerRO = new ResizeObserver( - (entries) => this._containerSizeChanged(entries[0].contentRect)); - - this._skipNextChildrenSizeChanged = false; - this._childrenRO = - new ResizeObserver((entries) => this._childrenSizeChanged(entries)); - - if (config) { - Object.assign(this, config); - } - } - - get container() { - return this._container; - } - set container(container) { - super.container = container; - - const oldEl = this._containerElement; - // Consider document fragments as shadowRoots. - const newEl = - (container && container.nodeType === Node.DOCUMENT_FRAGMENT_NODE) ? - container.host : - container; - if (oldEl === newEl) { - return; - } - - this._containerRO.disconnect(); - this._containerSize = null; - - if (oldEl) { - if (this._containerInlineStyle) { - oldEl.setAttribute('style', this._containerInlineStyle); - } else { - oldEl.removeAttribute('style'); - } - this._containerInlineStyle = null; - if (oldEl === this._scrollTarget) { - oldEl.removeEventListener('scroll', this, {passive: true}); - this._sizer && this._sizer.remove(); - } - } else { - // First time container was setup, add listeners only now. - addEventListener('scroll', this, {passive: true}); - } - - this._containerElement = newEl; - - if (newEl) { - this._containerInlineStyle = newEl.getAttribute('style') || null; - if (newEl === this._scrollTarget) { - this._sizer = this._sizer || this._createContainerSizer(); - this._container.prepend(this._sizer); - } - this._scheduleUpdateView(); - this._containerRO.observe(newEl); - } - } - - get layout() { - return this._layout; - } - set layout(layout) { - if (layout === this._layout) { - return; - } - - if (this._layout) { - this._measureCallback = null; - this._layout.removeEventListener('scrollsizechange', this); - this._layout.removeEventListener('scrollerrorchange', this); - this._layout.removeEventListener('itempositionchange', this); - this._layout.removeEventListener('rangechange', this); - // Reset container size so layout can get correct viewport size. - if (this._containerElement) { - this._sizeContainer(); - } - } - - this._layout = layout; - - if (this._layout) { - if (typeof this._layout.updateItemSizes === 'function') { - this._measureCallback = this._layout.updateItemSizes.bind(this._layout); - this.requestRemeasure(); - } - this._layout.addEventListener('scrollsizechange', this); - this._layout.addEventListener('scrollerrorchange', this); - this._layout.addEventListener('itempositionchange', this); - this._layout.addEventListener('rangechange', this); - this._scheduleUpdateView(); - } - } - - /** - * The element that generates scroll events and defines the container - * viewport. The value `null` (default) corresponds to `window` as scroll - * target. - * @type {Element|null} - */ - get scrollTarget() { - return this._scrollTarget; - } - /** - * @param {Element|null} target - */ - set scrollTarget(target) { - // Consider window as null. - if (target === window) { - target = null; - } - if (this._scrollTarget === target) { - return; - } - if (this._scrollTarget) { - this._scrollTarget.removeEventListener('scroll', this, {passive: true}); - if (this._sizer && this._scrollTarget === this._containerElement) { - this._sizer.remove(); - } - } - - this._scrollTarget = target; - - if (target) { - target.addEventListener('scroll', this, {passive: true}); - if (target === this._containerElement) { - this._sizer = this._sizer || this._createContainerSizer(); - this._container.prepend(this._sizer); - } - } - } - - /** - * @protected - */ - _render() { - // console.time(`render ${this._containerElement.localName}#${ - // this._containerElement.id}`); - - this._childrenRO.disconnect(); - - // Update layout properties before rendering to have correct - // first, num, scroll size, children positions. - this._layout.totalItems = this.totalItems; - if (this._needsUpdateView) { - this._needsUpdateView = false; - this._updateView(); - } - this._layout.reflowIfNeeded(); - // Keep rendering until there is no more scheduled renders. - while (true) { - if (this._pendingRender) { - cancelAnimationFrame(this._pendingRender); - this._pendingRender = null; - } - // Update scroll size and correct scroll error before rendering. - this._sizeContainer(this._scrollSize); - if (this._scrollErr) { - // This triggers a 'scroll' event (async) which triggers another - // _updateView(). - this._correctScrollError(this._scrollErr); - this._scrollErr = null; - } - // Position children (_didRender()), and provide their measures to layout. - super._render(); - this._layout.reflowIfNeeded(); - // If layout reflow did not provoke another render, we're done. - if (!this._pendingRender) { - break; - } - } - // We want to skip the first ResizeObserver callback call as we already - // measured the children. - this._skipNextChildrenSizeChanged = true; - this._kids.forEach(child => this._childrenRO.observe(child)); - - // console.timeEnd(`render ${this._containerElement.localName}#${ - // this._containerElement.id}`); - } - - /** - * Position children before they get measured. - * Measuring will force relayout, so by positioning - * them first, we reduce computations. - * @protected - */ - _didRender() { - if (this._childrenPos) { - this._positionChildren(this._childrenPos); - this._childrenPos = null; - } - } - - /** - * @param {!Event} event - * @private - */ - handleEvent(event) { - switch (event.type) { - case 'scroll': - if (!this._scrollTarget || event.target === this._scrollTarget) { - this._scheduleUpdateView(); - } - break; - case 'scrollsizechange': - this._scrollSize = event.detail; - this._scheduleRender(); - break; - case 'scrollerrorchange': - this._scrollErr = event.detail; - this._scheduleRender(); - break; - case 'itempositionchange': - this._childrenPos = event.detail; - this._scheduleRender(); - break; - case 'rangechange': - this._adjustRange(event.detail); - break; - default: - console.warn('event not handled', event); - } - } - /** - * @return {!Element} - * @private - */ - _createContainerSizer() { - const sizer = document.createElement('div'); - // When the scrollHeight is large, the height - // of this element might be ignored. - // Setting content and font-size ensures the element - // has a size. - Object.assign(sizer.style, { - position: 'absolute', - margin: '-2px 0 0 0', - padding: 0, - visibility: 'hidden', - fontSize: '2px', - }); - sizer.innerHTML = ' '; - return sizer; - } - - // Rename _ordered to _kids? - /** - * @protected - */ - get _kids() { - return this._ordered; - } - /** - * @private - */ - _scheduleUpdateView() { - this._needsUpdateView = true; - this._scheduleRender(); - } - /** - * @private - */ - _updateView() { - let width, height, top, left; - if (this._scrollTarget === this._containerElement) { - width = this._containerSize.width; - height = this._containerSize.height; - left = this._containerElement.scrollLeft; - top = this._containerElement.scrollTop; - } else { - const containerBounds = this._containerElement.getBoundingClientRect(); - const scrollBounds = this._scrollTarget ? - this._scrollTarget.getBoundingClientRect() : - {top: 0, left: 0, width: innerWidth, height: innerHeight}; - const scrollerWidth = scrollBounds.width; - const scrollerHeight = scrollBounds.height; - const xMin = Math.max( - 0, Math.min(scrollerWidth, containerBounds.left - scrollBounds.left)); - const yMin = Math.max( - 0, Math.min(scrollerHeight, containerBounds.top - scrollBounds.top)); - const xMax = this._layout.direction === 'vertical' ? - Math.max( - 0, - Math.min( - scrollerWidth, containerBounds.right - scrollBounds.left)) : - scrollerWidth; - const yMax = this._layout.direction === 'vertical' ? - scrollerHeight : - Math.max( - 0, - Math.min( - scrollerHeight, containerBounds.bottom - scrollBounds.top)); - width = xMax - xMin; - height = yMax - yMin; - left = Math.max(0, -(containerBounds.x - scrollBounds.left)); - top = Math.max(0, -(containerBounds.y - scrollBounds.top)); - } - this._layout.viewportSize = {width, height}; - this._layout.viewportScroll = {top, left}; - } - /** - * @private - */ - _sizeContainer(size) { - if (this._scrollTarget === this._containerElement) { - const left = size && size.width ? size.width - 1 : 0; - const top = size && size.height ? size.height - 1 : 0; - this._sizer.style.transform = `translate(${left}px, ${top}px)`; - } else { - const style = this._containerElement.style; - style.minWidth = size && size.width ? size.width + 'px' : null; - style.minHeight = size && size.height ? size.height + 'px' : null; - } - } - /** - * @private - */ - _positionChildren(pos) { - const kids = this._kids; - Object.keys(pos).forEach(key => { - const idx = key - this._first; - const child = kids[idx]; - if (child) { - const {top, left} = pos[key]; - // console.debug(`_positionChild #${this._container.id} > - // #${child.id}: top ${top}`); - child.style.position = 'absolute'; - child.style.transform = `translate(${left}px, ${top}px)`; - } - }); - } - /** - * @private - */ - _adjustRange(range) { - this.num = range.num; - this.first = range.first; - this._incremental = !(range.stable); - if (range.remeasure) { - this.requestRemeasure(); - } else if (range.stable) { - this._notifyStable(); - } - } - /** - * @protected - */ - _shouldRender() { - if (!super._shouldRender() || !this._layout) { - return false; - } - // NOTE: we're about to render, but the ResizeObserver didn't execute yet. - // Since we want to keep rAF timing, we compute _containerSize now. - // Would be nice to have a way to flush ResizeObservers - if (this._containerSize === null) { - const {width, height} = this._containerElement.getBoundingClientRect(); - this._containerSize = {width, height}; - } - return this._containerSize.width > 0 || this._containerSize.height > 0; - } - /** - * @private - */ - _correctScrollError(err) { - if (this._scrollTarget) { - this._scrollTarget.scrollTop -= err.top; - this._scrollTarget.scrollLeft -= err.left; - } else { - window.scroll(window.scrollX - err.left, window.scrollY - err.top); - } - } - /** - * @protected - */ - _notifyStable() { - const {first, num} = this; - const last = first + num - 1; - this._container.dispatchEvent( - new RangeChangeEvent('rangechange', {first, last})); - } - /** - * @private - */ - _containerSizeChanged(size) { - const {width, height} = size; - this._containerSize = {width, height}; - // console.debug('container changed size', this._containerSize); - this._scheduleUpdateView(); - } - /** - * @private - */ - _childrenSizeChanged() { - if (this._skipNextChildrenSizeChanged) { - this._skipNextChildrenSizeChanged = false; - } else { - this.requestRemeasure(); - } - } -}; - -export const VirtualScroller = RepeatsAndScrolls(class {});
diff --git a/third_party/blink/renderer/core/scroll/scroll_animator_test.cc b/third_party/blink/renderer/core/scroll/scroll_animator_test.cc index 21f15d4..17d93abb 100644 --- a/third_party/blink/renderer/core/scroll/scroll_animator_test.cc +++ b/third_party/blink/renderer/core/scroll/scroll_animator_test.cc
@@ -139,8 +139,9 @@ ScrollableArea::Trace(visitor); } - virtual void PreFinalize() { + void DisposeImpl() override { timer_task_runner_.reset(); + ScrollableArea::DisposeImpl(); } private:
diff --git a/third_party/blink/renderer/core/scroll/scrollable_area.cc b/third_party/blink/renderer/core/scroll/scrollable_area.cc index d4467c7..b780226 100644 --- a/third_party/blink/renderer/core/scroll/scrollable_area.cc +++ b/third_party/blink/renderer/core/scroll/scrollable_area.cc
@@ -96,12 +96,13 @@ ScrollableArea::~ScrollableArea() = default; void ScrollableArea::Dispose() { - RunScrollCompleteCallbacks(); - fade_overlay_scrollbars_timer_.reset(); - PreFinalize(); + DisposeImpl(); } -void ScrollableArea::PreFinalize() {} +void ScrollableArea::DisposeImpl() { + RunScrollCompleteCallbacks(); + fade_overlay_scrollbars_timer_.reset(); +} void ScrollableArea::ClearScrollableArea() { #if defined(OS_MACOSX)
diff --git a/third_party/blink/renderer/core/scroll/scrollable_area.h b/third_party/blink/renderer/core/scroll/scrollable_area.h index c0756926..e420a921 100644 --- a/third_party/blink/renderer/core/scroll/scrollable_area.h +++ b/third_party/blink/renderer/core/scroll/scrollable_area.h
@@ -351,7 +351,7 @@ virtual ~ScrollableArea(); void Dispose(); - virtual void PreFinalize(); + virtual void DisposeImpl(); // Called when any of horizontal scrollbar, vertical scrollbar and scroll // corner is setNeedsPaintInvalidation.
diff --git a/third_party/blink/renderer/core/svg/animation/smil_time_container.cc b/third_party/blink/renderer/core/svg/animation/smil_time_container.cc index 7f87a93..3f6fd62 100644 --- a/third_party/blink/renderer/core/svg/animation/smil_time_container.cc +++ b/third_party/blink/renderer/core/svg/animation/smil_time_container.cc
@@ -499,6 +499,10 @@ } for (auto& animation : sandwich) { + animation->UpdateSyncbases(); + } + + for (auto& animation : sandwich) { animation->UpdateNextProgressTime(elapsed); } @@ -513,9 +517,8 @@ it = sandwich.erase(it); } - if (sandwich.IsEmpty()) { + if (sandwich.IsEmpty()) continue; - } for (auto& animation : sandwich) { SMILTime next_fire_time = animation->NextProgressTime();
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 e21bd225..70c3c096c 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
@@ -228,7 +228,8 @@ cached_repeat_dur_(kInvalidCachedTime), cached_repeat_count_(kInvalidCachedTime), cached_min_(kInvalidCachedTime), - cached_max_(kInvalidCachedTime) { + cached_max_(kInvalidCachedTime), + interval_has_changed_(false) { ResolveFirstInterval(); } @@ -1144,6 +1145,16 @@ ScheduleEvent(event_type_names::kEndEvent); } +void SVGSMILElement::UpdateSyncbases() { + if (!interval_has_changed_) + return; + interval_has_changed_ = false; + NotifyDependentsIntervalChanged(interval_); + next_progress_time_ = next_progress_time_.IsUnresolved() + ? interval_.begin + : std::min(next_progress_time_, interval_.begin); +} + void SVGSMILElement::UpdateNextProgressTime(double elapsed) { next_progress_time_ = CalculateNextProgressTime(elapsed); } @@ -1165,22 +1176,28 @@ base::Optional<SMILInterval> new_interval = CheckForNewRestartInterval(elapsed); - bool interval_did_restart = - (new_interval && elapsed >= (*new_interval).begin); + + // This boolean is quite intricate. (Bug 379751) + // + // The first part is easy, if we get a new interval we start or end. + // + // The second part, is primarily there for an edge case where + // the old interval began and ended on the same animation frame + // due to a really short interval. + bool interval_did_start_or_end = + (new_interval) || + (interval_.begin <= elapsed && interval_.end <= elapsed); if (new_interval) { interval_ = *new_interval; - NotifyDependentsIntervalChanged(interval_); - next_progress_time_ = next_progress_time_.IsUnresolved() - ? interval_.begin - : std::min(next_progress_time_, interval_.begin); + interval_has_changed_ = true; } ActiveState old_active_state = GetActiveState(); active_state_ = DetermineActiveState(elapsed); if (IsContributing(elapsed)) { - if (old_active_state == kInactive || interval_did_restart) { + if (old_active_state == kInactive || interval_did_start_or_end) { ScheduleEvent(event_type_names::kBeginEvent); StartedActiveInterval(); } @@ -1193,7 +1210,7 @@ } if ((old_active_state == kActive && GetActiveState() != kActive) || - interval_did_restart) { + interval_did_start_or_end) { ScheduleEvent(event_type_names::kEndEvent); EndedActiveInterval(); }
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 d5c47c3..31adf726 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
@@ -87,9 +87,10 @@ void SeekToIntervalCorrespondingToTime(double elapsed); bool NeedsToProgress(double elapsed, bool seek_to_time); - void TriggerPendingEvents(double elapsed); - void UpdateNextProgressTime(double elapsed); void Progress(double elapsed, bool seek_to_time); + void TriggerPendingEvents(double elapsed); + void UpdateSyncbases(); + void UpdateNextProgressTime(double elapsed); SMILTime NextProgressTime() const; void UpdateAnimatedValue(SVGSMILElement* result_element) { @@ -295,6 +296,7 @@ mutable SMILTime cached_max_; bool animated_property_locked_; + bool interval_has_changed_; friend class ConditionEventListener; };
diff --git a/third_party/blink/renderer/core/timing/performance_user_timing.cc b/third_party/blink/renderer/core/timing/performance_user_timing.cc index 1866557..5423a97 100644 --- a/third_party/blink/renderer/core/timing/performance_user_timing.cc +++ b/third_party/blink/renderer/core/timing/performance_user_timing.cc
@@ -110,6 +110,11 @@ DOMHighResTimeStamp start = 0.0; if (mark_options && mark_options->hasStartTime()) { start = mark_options->startTime(); + if (start < 0.0) { + exception_state.ThrowTypeError("'" + mark_name + + "' cannot have a negative start time."); + return nullptr; + } } else { start = performance_->now(); } @@ -192,14 +197,20 @@ return value - timing->navigationStart(); } -double UserTiming::GetTimeOrFindMarkTime(const StringOrDouble& mark_or_time, +double UserTiming::GetTimeOrFindMarkTime(const AtomicString& measure_name, + const StringOrDouble& mark_or_time, ExceptionState& exception_state) { if (mark_or_time.IsString()) { return FindExistingMarkStartTime(AtomicString(mark_or_time.GetAsString()), exception_state); } DCHECK(mark_or_time.IsDouble()); - return mark_or_time.GetAsDouble(); + const double time = mark_or_time.GetAsDouble(); + if (time < 0.0) { + exception_state.ThrowTypeError("'" + measure_name + + "' cannot have a negative time stamp."); + } + return time; } PerformanceMeasure* UserTiming::Measure(ScriptState* script_state, @@ -209,12 +220,15 @@ const ScriptValue& detail, ExceptionState& exception_state) { double start_time = - start.IsNull() ? 0.0 : GetTimeOrFindMarkTime(start, exception_state); + start.IsNull() + ? 0.0 + : GetTimeOrFindMarkTime(measure_name, start, exception_state); if (exception_state.HadException()) return nullptr; - double end_time = end.IsNull() ? performance_->now() - : GetTimeOrFindMarkTime(end, exception_state); + double end_time = + end.IsNull() ? performance_->now() + : GetTimeOrFindMarkTime(measure_name, end, exception_state); if (exception_state.HadException()) return nullptr;
diff --git a/third_party/blink/renderer/core/timing/performance_user_timing.h b/third_party/blink/renderer/core/timing/performance_user_timing.h index ffb07ce..fc8df66 100644 --- a/third_party/blink/renderer/core/timing/performance_user_timing.h +++ b/third_party/blink/renderer/core/timing/performance_user_timing.h
@@ -71,7 +71,8 @@ private: double FindExistingMarkStartTime(const AtomicString& mark_name, ExceptionState&); - double GetTimeOrFindMarkTime(const StringOrDouble& mark_or_time, + double GetTimeOrFindMarkTime(const AtomicString& measure_name, + const StringOrDouble& mark_or_time, ExceptionState&); Member<Performance> performance_;
diff --git a/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js b/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js index 26ee7ba7..a3e3931 100644 --- a/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js
@@ -1155,6 +1155,19 @@ } }; +ElementsTestRunner.dumpInspectorHighlightStyleJSON = async function(idValue) { + const node = await ElementsTestRunner.nodeWithIdPromise(idValue); + const result = await TestRunner.OverlayAgent.getHighlightObjectForTest(node.id, false, true /* includeStyle */); + const info = result['elementInfo'] ? result['elementInfo']['style'] : null; + if (!info) { + TestRunner.addResult(`${idValue}: No style info`); + } else { + if (info['font-family']) + info['font-family'] = '<font-family value>'; + TestRunner.addResult(idValue + JSON.stringify(info, null, 2)); + } +}; + ElementsTestRunner.waitForAnimationAdded = function(callback) { TestRunner.addSniffer(Animation.AnimationTimeline.prototype, '_addAnimationGroup', callback); };
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js b/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js index fbfe1f9..a534245 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js
@@ -111,7 +111,9 @@ const element = createElementWithClass('div', 'file-system-container'); const header = element.createChild('div', 'file-system-header'); - header.createChild('div', 'file-system-name').textContent = folderName; + const nameElement = header.createChild('div', 'file-system-name'); + nameElement.textContent = folderName; + UI.ARIAUtils.markAsHeading(nameElement, 2); const path = header.createChild('div', 'file-system-path'); path.textContent = fileSystemPath; path.title = fileSystemPath;
diff --git a/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js b/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js index 19a8d09..45309a2a 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js +++ b/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js
@@ -321,6 +321,7 @@ const uiSourceCodeNode = new Sources.NavigatorUISourceCodeTreeNode(this, uiSourceCode, frame); folderNode.appendChild(uiSourceCodeNode); this._uiSourceCodeNodes.set(uiSourceCode, uiSourceCodeNode); + this._selectDefaultTreeNode(); } /** @@ -363,6 +364,14 @@ return; this._rootNode.appendChild(new Sources.NavigatorGroupTreeNode( this, project, project.id(), Sources.NavigatorView.Types.FileSystem, project.displayName())); + this._selectDefaultTreeNode(); + } + + // TODO(einbinder) remove this code after crbug.com/964075 is fixed + _selectDefaultTreeNode() { + const children = this._rootNode.children(); + if (children.length && !this._scriptsTree.selectedTreeElement) + children[0].treeNode().select(true /* omitFocus */, false /* selectedByUser */); } _computeUniqueFileSystemProjectNames() {
diff --git a/third_party/blink/renderer/devtools/front_end/text_editor/cmdevtools.css b/third_party/blink/renderer/devtools/front_end/text_editor/cmdevtools.css index 5b4a749..7b5253ab 100644 --- a/third_party/blink/renderer/devtools/front_end/text_editor/cmdevtools.css +++ b/third_party/blink/renderer/devtools/front_end/text_editor/cmdevtools.css
@@ -115,7 +115,7 @@ } .CodeMirror-linenumber { - color: rgb(128, 128, 128); + color: hsl(0, 0%, 46%); padding: 0 3px 0 5px; min-width: 22px; text-align: right;
diff --git a/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc b/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc index 668d3a1b..f365ea3b 100644 --- a/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc +++ b/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc
@@ -113,10 +113,12 @@ void ClipboardPromise::RejectFromReadOrDecodeFailure() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK_GE(clipboard_representation_index_, static_cast<wtf_size_t>(1)); script_promise_resolver_->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kDataError, "Failed to read or decode Blob for clipboard item type " + - clipboard_item_data_[clipboard_representation_index_].first + ".")); + clipboard_item_data_[clipboard_representation_index_ - 1].first + + ".")); } void ClipboardPromise::HandleRead() {
diff --git a/third_party/blink/renderer/modules/csspaint/paint_worklet_test.cc b/third_party/blink/renderer/modules/csspaint/paint_worklet_test.cc index 831a9e6e..95e0c78e 100644 --- a/third_party/blink/renderer/modules/csspaint/paint_worklet_test.cc +++ b/third_party/blink/renderer/modules/csspaint/paint_worklet_test.cc
@@ -5,6 +5,7 @@ #include "third_party/blink/renderer/modules/csspaint/paint_worklet.h" #include <memory> +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/bindings/core/v8/script_source_code.h" #include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h" @@ -202,10 +203,40 @@ EXPECT_TRUE(generator->HasAlpha()); } -TEST_F(PaintWorkletTest, ConsistentGlobalScopeOnMainThread) { +class MainOrOffThreadPaintWorkletTest + : public PageTestBase, + public ::testing::WithParamInterface<bool>, + private ScopedOffMainThreadCSSPaintForTest { + public: + MainOrOffThreadPaintWorkletTest() + : ScopedOffMainThreadCSSPaintForTest(GetParam()) {} +}; + +INSTANTIATE_TEST_SUITE_P(, MainOrOffThreadPaintWorkletTest, ::testing::Bool()); + +class MockObserver final : public CSSPaintImageGenerator::Observer { + public: + MOCK_METHOD0(PaintImageGeneratorReady, void()); +}; + +TEST_P(MainOrOffThreadPaintWorkletTest, ConsistentGlobalScopeOnMainThread) { PaintWorklet* paint_worklet_to_test = PaintWorklet::From(*GetFrame().GetDocument()->domWindow()); + MockObserver* observer = MakeGarbageCollected<MockObserver>(); + CSSPaintImageGeneratorImpl* generator_foo = + MakeGarbageCollected<CSSPaintImageGeneratorImpl>( + observer, paint_worklet_to_test, "foo"); + paint_worklet_to_test->AddPendingGenerator("foo", generator_foo); + CSSPaintImageGeneratorImpl* generator_bar = + MakeGarbageCollected<CSSPaintImageGeneratorImpl>( + observer, paint_worklet_to_test, "bar"); + paint_worklet_to_test->AddPendingGenerator("bar", generator_bar); + + // The generator should not fire unless it is the second registration + // for the main thread case + EXPECT_CALL(*observer, PaintImageGeneratorReady).Times(0); + Vector<Persistent<PaintWorkletGlobalScope>> global_scopes; for (size_t i = 0; i < PaintWorklet::kNumGlobalScopesPerThread; ++i) { paint_worklet_to_test->AddGlobalScopeForTesting(); @@ -247,6 +278,12 @@ EXPECT_TRUE(global_scopes[0]->FindDefinition("bar")); EXPECT_TRUE(paint_worklet_to_test->GetDocumentDefinitionMap().at("bar")); + // When running in main-thread mode, the generator is now ready after this + // call. For off-thread, we are still waiting on the cross-thread + // registration. + if (!RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) + EXPECT_CALL(*observer, PaintImageGeneratorReady).Times(1); + global_scopes[1]->ScriptController()->Evaluate( ScriptSourceCode(bar), SanitizeScriptErrors::kDoNotSanitize); @@ -254,9 +291,32 @@ } TEST_F(PaintWorkletTest, ConsistentGlobalScopeCrossThread) { + ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true); PaintWorklet* paint_worklet_to_test = PaintWorklet::From(*GetFrame().GetDocument()->domWindow()); + MockObserver* observer = MakeGarbageCollected<MockObserver>(); + CSSPaintImageGeneratorImpl* generator_foo = + MakeGarbageCollected<CSSPaintImageGeneratorImpl>( + observer, paint_worklet_to_test, "foo"); + paint_worklet_to_test->AddPendingGenerator("foo", generator_foo); + CSSPaintImageGeneratorImpl* generator_bar = + MakeGarbageCollected<CSSPaintImageGeneratorImpl>( + observer, paint_worklet_to_test, "bar"); + paint_worklet_to_test->AddPendingGenerator("bar", generator_bar); + CSSPaintImageGeneratorImpl* generator_loo = + MakeGarbageCollected<CSSPaintImageGeneratorImpl>( + observer, paint_worklet_to_test, "loo"); + paint_worklet_to_test->AddPendingGenerator("loo", generator_loo); + CSSPaintImageGeneratorImpl* generator_gar = + MakeGarbageCollected<CSSPaintImageGeneratorImpl>( + observer, paint_worklet_to_test, "gar"); + paint_worklet_to_test->AddPendingGenerator("gar", generator_gar); + + // None of the situations covered in this test should cause the generator to + // fire. + EXPECT_CALL(*observer, PaintImageGeneratorReady).Times(0); + Vector<Persistent<PaintWorkletGlobalScope>> global_scopes; for (size_t i = 0; i < PaintWorklet::kNumGlobalScopesPerThread; ++i) { paint_worklet_to_test->AddGlobalScopeForTesting(); @@ -399,18 +459,63 @@ EXPECT_FALSE(paint_worklet_to_test->GetDocumentDefinitionMap().at("gar")); } -class OffThreadPaintWorkletTest : public PageTestBase, - public ::testing::WithParamInterface<bool> { - public: - OffThreadPaintWorkletTest() : off_main_thread_css_paint_(GetParam()) {} +TEST_F(PaintWorkletTest, GeneratorNotifiedAfterAllRegistrations) { + ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true); + PaintWorklet* paint_worklet_to_test = + PaintWorklet::From(*GetFrame().GetDocument()->domWindow()); - private: - ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint_; -}; + MockObserver* observer = MakeGarbageCollected<MockObserver>(); + CSSPaintImageGeneratorImpl* generator = + MakeGarbageCollected<CSSPaintImageGeneratorImpl>( + observer, paint_worklet_to_test, "foo"); + paint_worklet_to_test->AddPendingGenerator("foo", generator); -INSTANTIATE_TEST_SUITE_P(, OffThreadPaintWorkletTest, ::testing::Bool()); + // The generator should not fire until the cross thread check + EXPECT_CALL(*observer, PaintImageGeneratorReady).Times(0); -TEST_P(OffThreadPaintWorkletTest, AllGlobalScopesMustBeCreated) { + Vector<Persistent<PaintWorkletGlobalScope>> global_scopes; + for (size_t i = 0; i < PaintWorklet::kNumGlobalScopesPerThread; ++i) { + paint_worklet_to_test->AddGlobalScopeForTesting(); + global_scopes.push_back( + PaintWorkletGlobalScopeProxy::From( + paint_worklet_to_test->GetGlobalScopesForTesting()[i]) + ->global_scope()); + } + + String foo = R"JS(registerPaint('foo', class { + static get inputProperties() { return ['--foo']; } + paint() {} + });)JS"; + + global_scopes[0]->ScriptController()->Evaluate( + ScriptSourceCode(foo), SanitizeScriptErrors::kDoNotSanitize); + + EXPECT_TRUE(global_scopes[0]->FindDefinition("foo")); + EXPECT_TRUE(paint_worklet_to_test->GetDocumentDefinitionMap().at("foo")); + + global_scopes[1]->ScriptController()->Evaluate( + ScriptSourceCode(foo), SanitizeScriptErrors::kDoNotSanitize); + + EXPECT_TRUE(paint_worklet_to_test->GetDocumentDefinitionMap().at("foo")); + + CSSPaintDefinition* definition = global_scopes[0]->FindDefinition("foo"); + Vector<String> custom_properties; + for (const auto& s : definition->CustomInvalidationProperties()) { + custom_properties.push_back(s); + } + + // The cross thread check should cause the generator to fire + EXPECT_CALL(*observer, PaintImageGeneratorReady).Times(1); + + paint_worklet_to_test->RegisterMainThreadDocumentPaintDefinition( + "foo", definition->NativeInvalidationProperties(), custom_properties, + definition->InputArgumentTypes(), + definition->GetPaintRenderingContext2DSettings()->alpha()); + + EXPECT_TRUE(paint_worklet_to_test->GetDocumentDefinitionMap().at("foo")); +} + +TEST_P(MainOrOffThreadPaintWorkletTest, AllGlobalScopesMustBeCreated) { PaintWorklet* paint_worklet_to_test = MakeGarbageCollected<PaintWorklet>(&GetFrame());
diff --git a/third_party/blink/renderer/modules/mediastream/track_audio_renderer.cc b/third_party/blink/renderer/modules/mediastream/track_audio_renderer.cc index a51ac652..28cf077 100644 --- a/third_party/blink/renderer/modules/mediastream/track_audio_renderer.cc +++ b/third_party/blink/renderer/modules/mediastream/track_audio_renderer.cc
@@ -114,8 +114,8 @@ } void TrackAudioRenderer::OnSetFormat(const media::AudioParameters& params) { - DVLOG(1) << "TrackAudioRenderer::OnSetFormat()"; - + DVLOG(1) << "TrackAudioRenderer::OnSetFormat: " + << params.AsHumanReadableString(); // If the parameters changed, the audio in the AudioShifter is invalid and // should be dropped. { @@ -299,8 +299,9 @@ DCHECK(task_runner_->BelongsToCurrentThread()); DVLOG(1) << "TrackAudioRenderer::MaybeStartSink()"; - if (!sink_ || !source_params_.IsValid() || !playing_) + if (!sink_ || !source_params_.IsValid() || !playing_) { return; + } // Re-create the AudioShifter to drop old audio data and reset to a starting // state. MaybeStartSink() is always called in a situation where either the @@ -354,8 +355,6 @@ void TrackAudioRenderer::ReconfigureSink(const media::AudioParameters& params) { DCHECK(task_runner_->BelongsToCurrentThread()); - DVLOG(1) << "TrackAudioRenderer::ReconfigureSink()"; - if (source_params_.Equals(params)) return; source_params_ = params;
diff --git a/third_party/blink/renderer/modules/modules_idl_files.gni b/third_party/blink/renderer/modules/modules_idl_files.gni index 1cedaaea..043fbb9 100644 --- a/third_party/blink/renderer/modules/modules_idl_files.gni +++ b/third_party/blink/renderer/modules/modules_idl_files.gni
@@ -253,6 +253,7 @@ "peerconnection/rtc_ice_transport.idl", "peerconnection/rtc_legacy_stats_report.idl", "peerconnection/rtc_peer_connection.idl", + "peerconnection/rtc_peer_connection_ice_error_event.idl", "peerconnection/rtc_peer_connection_ice_event.idl", "peerconnection/rtc_quic_stream.idl", "peerconnection/rtc_quic_stream_event.idl", @@ -715,6 +716,7 @@ "peerconnection/rtc_ice_server.idl", "peerconnection/rtc_offer_answer_options.idl", "peerconnection/rtc_offer_options.idl", + "peerconnection/rtc_peer_connection_ice_error_event_init.idl", "peerconnection/rtc_peer_connection_ice_event_init.idl", "peerconnection/rtc_quic_parameters.idl", "peerconnection/rtc_quic_stream_event_init.idl",
diff --git a/third_party/blink/renderer/modules/peerconnection/BUILD.gn b/third_party/blink/renderer/modules/peerconnection/BUILD.gn index a70ee803..98cef04 100644 --- a/third_party/blink/renderer/modules/peerconnection/BUILD.gn +++ b/third_party/blink/renderer/modules/peerconnection/BUILD.gn
@@ -81,6 +81,8 @@ "rtc_peer_connection.h", "rtc_peer_connection_controller.cc", "rtc_peer_connection_controller.h", + "rtc_peer_connection_ice_error_event.cc", + "rtc_peer_connection_ice_error_event.h", "rtc_peer_connection_ice_event.cc", "rtc_peer_connection_ice_event.h", "rtc_quic_stream.cc",
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc index ba9bbea..a9193de 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
@@ -89,6 +89,7 @@ #include "third_party/blink/renderer/modules/peerconnection/rtc_ice_server.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_offer_options.h" +#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.h" @@ -2668,6 +2669,15 @@ RTCIceCandidate::Create(std::move(web_candidate)); ScheduleDispatchEvent(RTCPeerConnectionIceEvent::Create(ice_candidate)); } +void RTCPeerConnection::DidFailICECandidate(const WebString& host_candidate, + const WebString& url, + int error_code, + const WebString& error_text) { + DCHECK(!closed_); + DCHECK(GetExecutionContext()->IsContextThread()); + ScheduleDispatchEvent(RTCPeerConnectionIceErrorEvent::Create( + host_candidate, url, error_code, error_text)); +} void RTCPeerConnection::DidChangeSignalingState( webrtc::PeerConnectionInterface::SignalingState new_state) {
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h index 3557fca..894c210e 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h
@@ -264,6 +264,7 @@ DEFINE_ATTRIBUTE_EVENT_LISTENER(icegatheringstatechange, kIcegatheringstatechange) DEFINE_ATTRIBUTE_EVENT_LISTENER(datachannel, kDatachannel) + DEFINE_ATTRIBUTE_EVENT_LISTENER(icecandidateerror, kIcecandidateerror) // Utility to note result of CreateOffer / CreateAnswer void NoteSdpCreated(const RTCSessionDescription&); @@ -283,6 +284,10 @@ // WebRTCPeerConnectionHandlerClient void NegotiationNeeded() override; void DidGenerateICECandidate(scoped_refptr<WebRTCICECandidate>) override; + void DidFailICECandidate(const WebString& host_candidate, + const WebString& url, + int error_code, + const WebString& error_text) override; void DidChangeSignalingState( webrtc::PeerConnectionInterface::SignalingState) override; void DidChangeIceGatheringState(
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl index d3c0890b..49a9464 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl
@@ -95,6 +95,7 @@ attribute EventHandler oniceconnectionstatechange; attribute EventHandler onconnectionstatechange; attribute EventHandler onicegatheringstatechange; + attribute EventHandler onicecandidateerror; // https://w3c.github.io/webrtc-pc/#legacy-interface-extensions // These methods return Promise<void> because having Promise-based versions requires that all overloads return Promises.
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.cc new file mode 100644 index 0000000..3f2b7f6 --- /dev/null +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.cc
@@ -0,0 +1,76 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/event_type_names.h" +#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.h" +#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event_init.h" + +namespace blink { + +RTCPeerConnectionIceErrorEvent* RTCPeerConnectionIceErrorEvent::Create( + const String& host_candidate, + const String& url, + int error_code, + const String& txt) { + DCHECK(error_code > 0 && error_code <= USHRT_MAX); + return MakeGarbageCollected<RTCPeerConnectionIceErrorEvent>( + host_candidate, url, static_cast<uint16_t>(error_code), txt); +} + +RTCPeerConnectionIceErrorEvent* RTCPeerConnectionIceErrorEvent::Create( + const AtomicString& type, + const RTCPeerConnectionIceErrorEventInit* initializer) { + return MakeGarbageCollected<RTCPeerConnectionIceErrorEvent>(type, + initializer); +} + +RTCPeerConnectionIceErrorEvent::RTCPeerConnectionIceErrorEvent( + const String& host_candidate, + const String& url, + uint16_t error_code, + const String& error_text) + : Event(event_type_names::kIcecandidateerror, + Bubbles::kNo, + Cancelable::kNo), + host_candidate_(host_candidate), + url_(url), + error_code_(error_code), + error_text_(error_text) {} + +RTCPeerConnectionIceErrorEvent::RTCPeerConnectionIceErrorEvent( + const AtomicString& type, + const RTCPeerConnectionIceErrorEventInit* initializer) + : Event(type, initializer), + host_candidate_(initializer->hostCandidate()), + url_(initializer->url()), + error_code_(initializer->errorCode()), + error_text_(initializer->statusText()) {} + +RTCPeerConnectionIceErrorEvent::~RTCPeerConnectionIceErrorEvent() = default; + +String RTCPeerConnectionIceErrorEvent::hostCandidate() const { + return host_candidate_; +} + +String RTCPeerConnectionIceErrorEvent::url() const { + return url_; +} + +uint16_t RTCPeerConnectionIceErrorEvent::errorCode() const { + return error_code_; +} + +String RTCPeerConnectionIceErrorEvent::errorText() const { + return error_text_; +} + +const AtomicString& RTCPeerConnectionIceErrorEvent::InterfaceName() const { + return event_interface_names::kRTCPeerConnectionIceErrorEvent; +} + +void RTCPeerConnectionIceErrorEvent::Trace(blink::Visitor* visitor) { + Event::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.h b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.h new file mode 100644 index 0000000..d3770c32 --- /dev/null +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.h
@@ -0,0 +1,54 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_PEER_CONNECTION_ICE_ERROR_EVENT_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_PEER_CONNECTION_ICE_ERROR_EVENT_H_ + +#include "third_party/blink/renderer/modules/event_modules.h" +#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" + +namespace blink { + +class RTCPeerConnectionIceErrorEventInit; + +class MODULES_EXPORT RTCPeerConnectionIceErrorEvent final : public Event { + DEFINE_WRAPPERTYPEINFO(); + + public: + RTCPeerConnectionIceErrorEvent(const String& host_candidate, + const String& url, + uint16_t error_code, + const String& error_text); + + RTCPeerConnectionIceErrorEvent(const AtomicString& type, + const RTCPeerConnectionIceErrorEventInit*); + ~RTCPeerConnectionIceErrorEvent() override; + + static RTCPeerConnectionIceErrorEvent* Create(const String& host_candidate, + const String& url, + int error_code, + const String& error_text); + + static RTCPeerConnectionIceErrorEvent* Create( + const AtomicString& type, + const RTCPeerConnectionIceErrorEventInit*); + + String hostCandidate() const; + String url() const; + uint16_t errorCode() const; + String errorText() const; + const AtomicString& InterfaceName() const override; + + void Trace(blink::Visitor*) override; + + private: + String host_candidate_; + String url_; + uint16_t error_code_; + String error_text_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_PEER_CONNECTION_ICE_ERROR_EVENT_H_
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.idl b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.idl new file mode 100644 index 0000000..f9adca4 --- /dev/null +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event.idl
@@ -0,0 +1,15 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//https://w3c.github.io/webrtc-pc/#rtcpeerconnectioniceerrorevent + +[ + Constructor (DOMString type, RTCPeerConnectionIceErrorEventInit eventInitDict), + Exposed=Window +] interface RTCPeerConnectionIceErrorEvent : Event { + readonly attribute DOMString hostCandidate; + readonly attribute DOMString url; + readonly attribute unsigned short errorCode; + readonly attribute USVString errorText; +}; \ No newline at end of file
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event_init.idl b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event_init.idl new file mode 100644 index 0000000..60aee0b71 --- /dev/null +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_error_event_init.idl
@@ -0,0 +1,12 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// https://w3c.github.io/webrtc-pc/#rtcpeerconnectioniceerrorevent + +dictionary RTCPeerConnectionIceErrorEventInit : EventInit { + DOMString hostCandidate; + DOMString url; + required unsigned short errorCode; + USVString statusText; +}; \ No newline at end of file
diff --git a/third_party/blink/renderer/modules/service_worker/service_worker.cc b/third_party/blink/renderer/modules/service_worker/service_worker.cc index 7948462..48192e8 100644 --- a/third_party/blink/renderer/modules/service_worker/service_worker.cc +++ b/third_party/blink/renderer/modules/service_worker/service_worker.cc
@@ -193,6 +193,11 @@ ServiceWorker::~ServiceWorker() = default; +void ServiceWorker::Dispose() { + host_.reset(); + binding_.Close(); +} + void ServiceWorker::Trace(blink::Visitor* visitor) { AbstractWorker::Trace(visitor); }
diff --git a/third_party/blink/renderer/modules/service_worker/service_worker.h b/third_party/blink/renderer/modules/service_worker/service_worker.h index 1d206bf..82a96ba 100644 --- a/third_party/blink/renderer/modules/service_worker/service_worker.h +++ b/third_party/blink/renderer/modules/service_worker/service_worker.h
@@ -53,7 +53,8 @@ public mojom::blink::ServiceWorkerObject { DEFINE_WRAPPERTYPEINFO(); USING_GARBAGE_COLLECTED_MIXIN(ServiceWorker); - + USING_PRE_FINALIZER(ServiceWorker, Dispose); + public: static ServiceWorker* From(ExecutionContext*, mojom::blink::ServiceWorkerObjectInfoPtr); @@ -73,8 +74,8 @@ ~ServiceWorker() override; void Trace(blink::Visitor*) override; - // Eager finalization needed to promptly release owned WebServiceWorker. - EAGERLY_FINALIZE(); + // Pre-finalization needed to promptly release owned WebServiceWorker. + void Dispose(); void postMessage(ScriptState*, const ScriptValue& message,
diff --git a/third_party/blink/renderer/modules/service_worker/service_worker_registration.cc b/third_party/blink/renderer/modules/service_worker/service_worker_registration.cc index 5800104..da65b523 100644 --- a/third_party/blink/renderer/modules/service_worker/service_worker_registration.cc +++ b/third_party/blink/renderer/modules/service_worker/service_worker_registration.cc
@@ -277,6 +277,11 @@ ServiceWorkerRegistration::~ServiceWorkerRegistration() = default; +void ServiceWorkerRegistration::Dispose() { + host_.reset(); + binding_.Close(); +} + void ServiceWorkerRegistration::Trace(blink::Visitor* visitor) { visitor->Trace(installing_); visitor->Trace(waiting_);
diff --git a/third_party/blink/renderer/modules/service_worker/service_worker_registration.h b/third_party/blink/renderer/modules/service_worker/service_worker_registration.h index 9325e98..89511e5 100644 --- a/third_party/blink/renderer/modules/service_worker/service_worker_registration.h +++ b/third_party/blink/renderer/modules/service_worker/service_worker_registration.h
@@ -33,6 +33,7 @@ public mojom::blink::ServiceWorkerRegistrationObject { DEFINE_WRAPPERTYPEINFO(); USING_GARBAGE_COLLECTED_MIXIN(ServiceWorkerRegistration); + USING_PRE_FINALIZER(ServiceWorkerRegistration, Dispose); public: // Called from CallbackPromiseAdapter. @@ -48,11 +49,6 @@ ExecutionContext*, mojom::blink::ServiceWorkerRegistrationObjectInfoPtr); - // Eager finalization needed to promptly invalidate the corresponding entry of - // the (registration id, WeakMember<ServiceWorkerRegistration>) map inside - // ServiceWorkerContainer. - EAGERLY_FINALIZE(); - // Called in 2 scenarios: // - when constructing |this|. // - when the browser process sends a new @@ -92,6 +88,8 @@ ~ServiceWorkerRegistration() override; + void Dispose(); + void Trace(blink::Visitor*) override; private:
diff --git a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc index bc1fe2b..e260d218 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc
@@ -743,6 +743,8 @@ } void WebGLRenderingContextBase::commit() { + if (!GetDrawingBuffer()) + return; int width = GetDrawingBuffer()->Size().Width(); int height = GetDrawingBuffer()->Size().Height();
diff --git a/third_party/blink/renderer/modules/webrtc/webrtc_audio_renderer.cc b/third_party/blink/renderer/modules/webrtc/webrtc_audio_renderer.cc index 32a2022..20e1bc3 100644 --- a/third_party/blink/renderer/modules/webrtc/webrtc_audio_renderer.cc +++ b/third_party/blink/renderer/modules/webrtc/webrtc_audio_renderer.cc
@@ -46,8 +46,6 @@ // Audio parameters that don't change. const media::AudioParameters::Format kFormat = media::AudioParameters::AUDIO_PCM_LOW_LATENCY; -const media::ChannelLayout kChannelLayout = media::CHANNEL_LAYOUT_STEREO; -const int kChannels = 2; // Used for UMA histograms. const int kRenderTimeHistogramMinMicroseconds = 100; @@ -194,7 +192,7 @@ source_(nullptr), play_ref_count_(0), start_ref_count_(0), - sink_params_(kFormat, kChannelLayout, 0, 0), + sink_params_(kFormat, media::CHANNEL_LAYOUT_STEREO, 0, 0), output_device_id_(device_id) { WebRtcLogMessage(base::StringPrintf("WAR::WAR. session_id=%d, effects=%i", session_id, sink_params_.effects())); @@ -464,7 +462,7 @@ const int source_frames_per_buffer = sink_params_.sample_rate() / 100; if (!audio_fifo_ && prior_frames_skipped != source_frames_per_buffer) { audio_fifo_ = std::make_unique<media::AudioPullFifo>( - kChannels, source_frames_per_buffer, + sink_params_.channels(), source_frames_per_buffer, ConvertToBaseCallback( CrossThreadBindRepeating(&WebRtcAudioRenderer::SourceCallback, CrossThreadUnretained(this)))); @@ -498,7 +496,7 @@ DCHECK(sink_->CurrentThreadIsRenderingThread()); base::TimeTicks start_time = base::TimeTicks::Now(); DVLOG(2) << "WebRtcAudioRenderer::SourceCallback(" << fifo_frame_delay << ", " - << audio_bus->frames() << ")"; + << audio_bus->channels() << ", " << audio_bus->frames() << ")"; int output_delay_milliseconds = static_cast<int>(audio_delay_.InMilliseconds()); @@ -656,6 +654,7 @@ } void WebRtcAudioRenderer::PrepareSink() { + DVLOG(1) << "WebRtcAudioRenderer::PrepareSink()"; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); media::AudioParameters new_sink_params; { @@ -665,6 +664,9 @@ const media::OutputDeviceInfo& device_info = sink_->GetOutputDeviceInfo(); DCHECK_EQ(device_info.device_status(), media::OUTPUT_DEVICE_STATUS_OK); + DVLOG(1) << "Sink parameters: " << sink_params_.AsHumanReadableString(); + DVLOG(1) << "Hardware parameters: " + << device_info.output_params().AsHumanReadableString(); // WebRTC does not yet support higher rates than 96000 on the client side // and 48000 is the preferred sample rate. Therefore, if 192000 is detected, @@ -693,11 +695,22 @@ const int source_frames_per_buffer = (sample_rate / 100); DVLOG(1) << "Using WebRTC output buffer size: " << source_frames_per_buffer; - // Setup sink parameters. + // Setup sink parameters using same channel configuration as the source. + // This sink is an AudioRendererSink which is implemented by an + // AudioOutputDevice. Note that we used to use hard-coded settings for + // stereo here but this has been changed since crbug.com/982276. + const int channels = device_info.output_params().channels(); + const media::ChannelLayout channel_layout = + device_info.output_params().channel_layout(); const int sink_frames_per_buffer = media::AudioLatency::GetRtcBufferSize( sample_rate, device_info.output_params().frames_per_buffer()); - new_sink_params.set_sample_rate(sample_rate); - new_sink_params.set_frames_per_buffer(sink_frames_per_buffer); + new_sink_params.Reset(kFormat, channel_layout, sample_rate, + sink_frames_per_buffer); + if (channel_layout == media::CHANNEL_LAYOUT_DISCRETE) { + new_sink_params.set_channels_for_discrete(channels); + } + DVLOG(1) << new_sink_params.AsHumanReadableString(); + DCHECK(new_sink_params.IsValid()); // Create a FIFO if re-buffering is required to match the source input with // the sink request. The source acts as provider here and the sink as @@ -714,7 +727,7 @@ (audio_fifo_ && audio_fifo_->SizeInFrames() != source_frames_per_buffer)) { audio_fifo_ = std::make_unique<media::AudioPullFifo>( - kChannels, source_frames_per_buffer, + channels, source_frames_per_buffer, ConvertToBaseCallback( CrossThreadBindRepeating(&WebRtcAudioRenderer::SourceCallback, CrossThreadUnretained(this))));
diff --git a/third_party/blink/renderer/modules/websockets/websocket_handle_impl.cc b/third_party/blink/renderer/modules/websockets/websocket_handle_impl.cc index 99bb582..85b4cfaf 100644 --- a/third_party/blink/renderer/modules/websockets/websocket_handle_impl.cc +++ b/third_party/blink/renderer/modules/websockets/websocket_handle_impl.cc
@@ -48,6 +48,8 @@ DCHECK(channel); channel_ = channel; + // Here we detect mojo connection errors on |client_binding_|. See also + // CreateWebSocket in //network/services/public/mojom/network_context.mojom. network::mojom::blink::WebSocketHandshakeClientPtr handshake_client_proxy; Vector<network::mojom::blink::HttpHeaderPtr> additional_headers; handshake_client_binding_.Bind(
diff --git a/third_party/blink/renderer/modules/webusb/usb_alternate_interface.cc b/third_party/blink/renderer/modules/webusb/usb_alternate_interface.cc index 0c43121..23edf415 100644 --- a/third_party/blink/renderer/modules/webusb/usb_alternate_interface.cc +++ b/third_party/blink/renderer/modules/webusb/usb_alternate_interface.cc
@@ -47,8 +47,14 @@ HeapVector<Member<USBEndpoint>> USBAlternateInterface::endpoints() const { HeapVector<Member<USBEndpoint>> endpoints; - for (wtf_size_t i = 0; i < Info().endpoints.size(); ++i) - endpoints.push_back(USBEndpoint::Create(this, i)); + for (wtf_size_t i = 0; i < Info().endpoints.size(); ++i) { + // Filter out control endpoints because there is no coresponding enum value + // defined in WebUSB. + if (Info().endpoints[i]->type != + device::mojom::blink::UsbTransferType::CONTROL) { + endpoints.push_back(USBEndpoint::Create(this, i)); + } + } return endpoints; }
diff --git a/third_party/blink/renderer/modules/xr/xr_frame_provider.cc b/third_party/blink/renderer/modules/xr/xr_frame_provider.cc index ba5aea1..73848ec 100644 --- a/third_party/blink/renderer/modules/xr/xr_frame_provider.cc +++ b/third_party/blink/renderer/modules/xr/xr_frame_provider.cc
@@ -390,15 +390,29 @@ for (unsigned i = 0; i < processing_sessions_.size(); ++i) { XRSession* session = processing_sessions_.at(i).Get(); + // If the session was terminated between requesting and now, we shouldn't + // process anything further. + if (session->ended()) + continue; + if (frame_pose_ && frame_pose_->input_state.has_value()) { session->OnInputStateChange(frame_id_, frame_pose_->input_state.value()); } + // If the input state change caused this session to end, we should stop + // processing. + if (session->ended()) + continue; + if (frame_pose_ && frame_pose_->pose_reset) { session->OnPoseReset(); } + // If the pose reset caused us to end, we should stop processing. + if (session->ended()) + continue; + std::unique_ptr<TransformationMatrix> pose_matrix = getPoseMatrix(frame_pose_); if (frame_data) {
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index 1f179ec..68ccb03 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -471,6 +471,7 @@ "exported/mediastream/media_stream_audio_processor_options.cc", "exported/mediastream/media_stream_audio_source.cc", "exported/mediastream/media_stream_audio_track.cc", + "exported/mediastream/web_media_element_source_utils.cc", "exported/mediastream/web_platform_media_stream_source.cc", "exported/mediastream/web_platform_media_stream_track.cc", "exported/mediastream/webaudio_media_stream_source.cc",
diff --git a/third_party/blink/renderer/platform/audio/vector_math_test.cc b/third_party/blink/renderer/platform/audio/vector_math_test.cc index 6c48cf6..d1b6327 100644 --- a/third_party/blink/renderer/platform/audio/vector_math_test.cc +++ b/third_party/blink/renderer/platform/audio/vector_math_test.cc
@@ -5,7 +5,6 @@ #include "third_party/blink/renderer/platform/audio/vector_math.h" #include <algorithm> -#include <array> #include <cmath> #include <limits> #include <numeric> @@ -168,10 +167,8 @@ // Get primary input vectors with difference memory layout and size // combinations. template <typename T> -std::array<TestVector<const T>, kVectorSizeCount * kMemoryLayoutCount> -GetPrimaryVectors(const T* base) { - std::array<TestVector<const T>, kVectorSizeCount * kMemoryLayoutCount> - vectors; +Vector<TestVector<const T>> GetPrimaryVectors(const T* base) { + Vector<TestVector<const T>> vectors(kVectorSizeCount * kMemoryLayoutCount); for (auto& vector : vectors) { ptrdiff_t i = &vector - &vectors[0]; ptrdiff_t memory_layout_index = i % kMemoryLayoutCount; @@ -191,11 +188,11 @@ // and which therefore is not aligned when the primary input vector is // aligned. template <typename T> -std::array<TestVector<T>, 2u> GetSecondaryVectors( +Vector<TestVector<T>> GetSecondaryVectors( T* base, const MemoryLayout* primary_memory_layout, size_t size) { - std::array<TestVector<T>, 2u> vectors; + Vector<TestVector<T>> vectors(2u); const MemoryLayout* other_memory_layout = &kMemoryLayouts[primary_memory_layout == &kMemoryLayouts[0]]; CHECK_NE(primary_memory_layout, other_memory_layout); @@ -207,7 +204,7 @@ } template <typename T> -std::array<TestVector<T>, 2u> GetSecondaryVectors( +Vector<TestVector<T>> GetSecondaryVectors( T* base, const TestVector<const float>& primary_vector) { return GetSecondaryVectors(base, primary_vector.memory_layout(), @@ -440,8 +437,9 @@ TEST_F(VectorMathTest, Zvmul) { constexpr float kMax = std::numeric_limits<float>::max(); - Vector<std::array<float, kFloatArraySize + 1u>> sources(4u); + Vector<Vector<float>> sources(4u); for (size_t i = 0u; i < sources.size(); ++i) { + sources[i].resize(kFloatArraySize); // Initialize a local source with a randomized test case source. std::copy_n(GetSource(i), kFloatArraySize, sources[i].begin()); // Put +FLT_MAX and -FLT_MAX in the middle of the source. Use a different
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string.cc b/third_party/blink/renderer/platform/bindings/parkable_string.cc index 05bd7d3..b1e4a30 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string.cc +++ b/third_party/blink/renderer/platform/bindings/parkable_string.cc
@@ -30,17 +30,15 @@ namespace { -void RecordParkingAction(ParkableStringImpl::ParkingAction action) { - UMA_HISTOGRAM_ENUMERATION("Memory.MovableStringParkingAction", action); -} +enum class ParkingAction { kParked, kUnparked }; void RecordStatistics(size_t size, base::TimeDelta duration, - ParkableStringImpl::ParkingAction action) { + ParkingAction action) { size_t throughput_mb_s = static_cast<size_t>(size / duration.InSecondsF()) / 1000000; size_t size_kb = size / 1000; - if (action == ParkableStringImpl::ParkingAction::kParkedInBackground) { + if (action == ParkingAction::kParked) { UMA_HISTOGRAM_COUNTS_10000("Memory.ParkableString.Compression.SizeKb", size_kb); // Size is at least 10kB, and at most ~1MB, and compression throughput @@ -409,7 +407,6 @@ // Parking can proceed synchronously. if (has_compressed_data()) { - RecordParkingAction(ParkingAction::kParkedInBackground); state_ = State::kParked; ParkableStringManager::Instance().OnParked(this); @@ -509,14 +506,9 @@ CHECK(compression::GzipUncompress(compressed_string_piece, uncompressed_string_piece)); - bool backgrounded = - ParkableStringManager::Instance().IsRendererBackgrounded(); - auto action = backgrounded ? ParkingAction::kUnparkedInBackground - : ParkingAction::kUnparkedInForeground; - RecordParkingAction(action); base::TimeDelta elapsed = timer.Elapsed(); ParkableStringManager::Instance().RecordUnparkingTime(elapsed); - RecordStatistics(CharactersSizeInBytes(), elapsed, action); + RecordStatistics(CharactersSizeInBytes(), elapsed, ParkingAction::kUnparked); return uncompressed; } @@ -542,7 +534,6 @@ // Both of these will make the string young again, and if so we don't // discard the compressed representation yet. if (CanParkNow() && compressed_) { - RecordParkingAction(ParkingAction::kParkedInBackground); state_ = State::kParked; ParkableStringManager::Instance().OnParked(this); @@ -638,7 +629,7 @@ }, WTF::Passed(std::move(params)), WTF::Passed(std::move(compressed)), thread_elapsed)); - RecordStatistics(size, timer.Elapsed(), ParkingAction::kParkedInBackground); + RecordStatistics(size, timer.Elapsed(), ParkingAction::kParked); } ParkableString::ParkableString(scoped_refptr<StringImpl>&& impl) {
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string.h b/third_party/blink/renderer/platform/bindings/parkable_string.h index 8e33ddfe..b5cd0091 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string.h +++ b/third_party/blink/renderer/platform/bindings/parkable_string.h
@@ -41,14 +41,6 @@ class PLATFORM_EXPORT ParkableStringImpl final : public RefCounted<ParkableStringImpl> { public: - // Histogram buckets, exported for testing. - enum class ParkingAction { - kParkedInBackground = 0, - kUnparkedInBackground = 1, - kUnparkedInForeground = 2, - kMaxValue = kUnparkedInForeground - }; - enum class ParkableState { kParkable, kNotParkable }; enum class ParkingMode { kIfCompressedDataExists, kAlways }; enum class AgeOrParkResult {
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc b/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc index d88b2d4..7040adb 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc +++ b/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc
@@ -353,15 +353,6 @@ str->Park(mode); total_size += str->CharactersSizeInBytes(); } - - // Only collect stats for "full" parking calls in background. - if (mode == ParkableStringImpl::ParkingMode::kAlways && - IsRendererBackgrounded()) { - size_t total_size_kb = total_size / 1000; - UMA_HISTOGRAM_COUNTS_100000("Memory.MovableStringsTotalSizeKb", - total_size_kb); - UMA_HISTOGRAM_COUNTS_1000("Memory.MovableStringsCount", Size()); - } } void ParkableStringManager::ParkAllIfRendererBackgrounded(
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 c26a69f0..e45425f 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string_test.cc +++ b/third_party/blink/renderer/platform/bindings/parkable_string_test.cc
@@ -228,8 +228,6 @@ } TEST_F(ParkableStringTest, Park) { - base::HistogramTester histogram_tester; - { ParkableString parkable(MakeLargeString('a').ReleaseImpl()); EXPECT_TRUE(parkable.may_be_parked()); @@ -246,11 +244,6 @@ large_string = String(); EXPECT_TRUE(ParkAndWait(parkable)); - histogram_tester.ExpectBucketCount( - "Memory.MovableStringParkingAction", - ParkableStringImpl::ParkingAction::kParkedInBackground, 2); - histogram_tester.ExpectTotalCount("Memory.MovableStringParkingAction", 2); - { ParkableString parkable(MakeLargeString('c').ReleaseImpl()); EXPECT_TRUE(parkable.may_be_parked()); @@ -374,8 +367,6 @@ } TEST_F(ParkableStringTest, Unpark) { - base::HistogramTester histogram_tester; - ParkableString parkable(MakeLargeString().Impl()); String unparked_copy = parkable.ToString().IsolatedCopy(); EXPECT_TRUE(parkable.may_be_parked()); @@ -386,14 +377,6 @@ String unparked = parkable.ToString(); EXPECT_EQ(unparked_copy, unparked); EXPECT_FALSE(parkable.Impl()->is_parked()); - - histogram_tester.ExpectTotalCount("Memory.MovableStringParkingAction", 2); - histogram_tester.ExpectBucketCount( - "Memory.MovableStringParkingAction", - ParkableStringImpl::ParkingAction::kParkedInBackground, 1); - histogram_tester.ExpectBucketCount( - "Memory.MovableStringParkingAction", - ParkableStringImpl::ParkingAction::kUnparkedInForeground, 1); } TEST_F(ParkableStringTest, LockUnlock) { @@ -441,8 +424,6 @@ } TEST_F(ParkableStringTest, ManagerSimple) { - base::HistogramTester histogram_tester; - ParkableString parkable(MakeLargeString().Impl()); ASSERT_FALSE(parkable.Impl()->is_parked()); @@ -459,13 +440,11 @@ ASSERT_FALSE(manager.IsRendererBackgrounded()); WaitForDelayedParking(); EXPECT_FALSE(parkable.Impl()->is_parked()); - histogram_tester.ExpectTotalCount("Memory.MovableStringsCount", 0); manager.SetRendererBackgrounded(true); ASSERT_TRUE(manager.IsRendererBackgrounded()); WaitForDelayedParking(); EXPECT_TRUE(parkable.Impl()->is_parked()); - histogram_tester.ExpectUniqueSample("Memory.MovableStringsCount", 1, 1); // Park and unpark. parkable.ToString(); @@ -473,7 +452,6 @@ manager.SetRendererBackgrounded(true); WaitForDelayedParking(); EXPECT_TRUE(parkable.Impl()->is_parked()); - histogram_tester.ExpectUniqueSample("Memory.MovableStringsCount", 1, 2); // More than one reference, no parking. manager.SetRendererBackgrounded(false); @@ -487,17 +465,6 @@ manager.SetRendererBackgrounded(true); WaitForDelayedParking(); EXPECT_TRUE(parkable.Impl()->is_parked()); - - histogram_tester.ExpectTotalCount("Memory.MovableStringParkingAction", 5); - histogram_tester.ExpectBucketCount( - "Memory.MovableStringParkingAction", - ParkableStringImpl::ParkingAction::kParkedInBackground, 3); - histogram_tester.ExpectBucketCount( - "Memory.MovableStringParkingAction", - ParkableStringImpl::ParkingAction::kUnparkedInBackground, 1); - histogram_tester.ExpectBucketCount( - "Memory.MovableStringParkingAction", - ParkableStringImpl::ParkingAction::kUnparkedInForeground, 1); } TEST_F(ParkableStringTest, ManagerMultipleStrings) { @@ -597,17 +564,6 @@ EXPECT_EQ(1u, manager.Size()); parkable4 = ParkableString(); EXPECT_EQ(0u, manager.Size()); - - // 1 parked, 1 unparked. Bucket count is 2 as we collected stats twice. - histogram_tester.ExpectUniqueSample("Memory.MovableStringsCount", 2, - parking_count); - histogram_tester.ExpectUniqueSample("Memory.MovableStringsTotalSizeKb", - 2 * kSizeKb, parking_count); - - histogram_tester.ExpectTotalCount("Memory.MovableStringParkingAction", 1); - histogram_tester.ExpectBucketCount( - "Memory.MovableStringParkingAction", - ParkableStringImpl::ParkingAction::kParkedInBackground, 1); } TEST_F(ParkableStringTest, ShouldPark) {
diff --git a/third_party/blink/renderer/platform/exported/mediastream/web_media_element_source_utils.cc b/third_party/blink/renderer/platform/exported/mediastream/web_media_element_source_utils.cc new file mode 100644 index 0000000..c044bab --- /dev/null +++ b/third_party/blink/renderer/platform/exported/mediastream/web_media_element_source_utils.cc
@@ -0,0 +1,20 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/public/platform/modules/mediastream/web_media_element_source_utils.h" + +#include "third_party/blink/public/platform/web_media_player_source.h" +#include "third_party/blink/public/platform/web_media_stream.h" + +namespace blink { + +WebMediaStream GetWebMediaStreamFromWebMediaPlayerSource( + const WebMediaPlayerSource& source) { + if (source.IsMediaStream()) + return source.GetAsMediaStream(); + + return WebMediaStream(); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc b/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc index 520a937..c436a83 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc
@@ -1114,24 +1114,26 @@ void ShapeResult::InsertRun(scoped_refptr<ShapeResult::RunInfo> run) { // The runs are stored in result->m_runs in visual order. For LTR, we place - // the run to be inserted before the next run with a bigger character - // start index. For RTL, we place the run before the next run with a lower - // character index. Otherwise, for both directions, at the end. - if (HB_DIRECTION_IS_FORWARD(run->direction_)) { - for (wtf_size_t pos = 0; pos < runs_.size(); ++pos) { - if (runs_.at(pos)->start_index_ > run->start_index_) { - runs_.insert(pos, std::move(run)); - break; - } - } - } else { - for (wtf_size_t pos = 0; pos < runs_.size(); ++pos) { - if (runs_.at(pos)->start_index_ < run->start_index_) { - runs_.insert(pos, std::move(run)); - break; - } - } - } + // the run to be inserted before the next run with a bigger character start + // index. + const auto ltr_comparer = [](scoped_refptr<RunInfo>& run, + unsigned start_index) { + return run->start_index_ < start_index; + }; + + // For RTL, we place the run before the next run with a lower character + // index. Otherwise, for both directions, at the end. + const auto rtl_comparer = [](scoped_refptr<RunInfo>& run, + unsigned start_index) { + return run->start_index_ > start_index; + }; + + Vector<scoped_refptr<RunInfo>>::iterator iterator = std::lower_bound( + runs_.begin(), runs_.end(), run->start_index_, + HB_DIRECTION_IS_FORWARD(run->direction_) ? ltr_comparer : rtl_comparer); + if (iterator != runs_.end()) + runs_.insert(iterator - runs_.begin(), std::move(run)); + // If we didn't find an existing slot to place it, append. if (run) runs_.push_back(std::move(run));
diff --git a/third_party/blink/renderer/platform/graphics/lab_color_space.h b/third_party/blink/renderer/platform/graphics/lab_color_space.h index c470604..e002057 100644 --- a/third_party/blink/renderer/platform/graphics/lab_color_space.h +++ b/third_party/blink/renderer/platform/graphics/lab_color_space.h
@@ -2,7 +2,6 @@ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_LAB_COLOR_SPACE_H_ #include <algorithm> -#include <array> #include <cmath> #include <initializer_list> #include <iterator>
diff --git a/third_party/blink/renderer/platform/heap/BlinkGCAPIReference.md b/third_party/blink/renderer/platform/heap/BlinkGCAPIReference.md index 880f6b4..0776f373 100644 --- a/third_party/blink/renderer/platform/heap/BlinkGCAPIReference.md +++ b/third_party/blink/renderer/platform/heap/BlinkGCAPIReference.md
@@ -98,8 +98,7 @@ Note that finalization is done at an arbitrary time after the object becomes unreachable. Any destructor executed within the finalization period must not touch any other on-heap object, because destructors -can be executed in any order. If there is a need of having such destructor, consider using -[EAGERLY_FINALIZE](#EAGERLY_FINALIZE). +can be executed in any order. Because `GarbageCollectedFinalized<T>` is a special case of `GarbageCollected<T>`, all the restrictions that apply to `GarbageCollected<T>` classes also apply to `GarbageCollectedFinalized<T>`. @@ -171,55 +170,63 @@ ### USING_PRE_FINALIZER -`USING_PRE_FINALIZER(ClassName, functionName)` in a class declaration declares the class has a *pre-finalizer* of name -`functionName`. +`USING_PRE_FINALIZER(ClassName, FunctionName)` in a class declaration declares the class has a *pre-finalizer* of name +`FunctionName`. +A pre-finalizer must have the function signature `void()` but can have any name. -A pre-finalizer is a user-defined member function of a garbage-collected class that is called when the object is going -to be swept but before the garbage collector actually sweeps any objects. Therefore, it is allowed for a pre-finalizer -to touch any other on-heap objects, while a destructor is not. It is useful for doing some cleanups that cannot be done -with a destructor. - -A pre-finalizer must have the following function signature: `void preFinalizer()`. You can change the function name. +A pre-finalizer is a user-defined member function of a garbage-collected class that is called when the object is going to be reclaimed. +It is invoked before the sweeping phase starts to allow a pre-finalizer to touch any other on-heap objects which is forbidden from destructors. +It is useful for doing cleanups that cannot be done with a destructor. ```c++ class YourClass : public GarbageCollectedFinalized<YourClass> { - USING_PRE_FINALIZER(YourClass, dispose); + USING_PRE_FINALIZER(YourClass, Dispose); public: - void dispose() - { - other_->dispose(); // OK; you can touch other on-heap objects in a pre-finalizer. + void Dispose() { + // OK: Other on-heap objects can be touched in a pre-finalizer. + other_->Dispose(); } - ~YourClass() - { - // other_->dispose(); // BAD. + + ~YourClass() { + // BAD: Not allowed. + // other_->Dispose(); } private: Member<OtherClass> other_; }; ``` +Sometimes it is necessary to further delegate pre-finalizers up the class hierarchy, similar to how destructors destruct in reverse order wrt. to construction. +It is possible to construct such delegations using virtual methods. -Pre-finalizers have some implications on the garbage collector's performance: the garbage-collector needs to iterate -all registered pre-finalizers at every GC. Therefore, a pre-finalizer should be avoided unless it is really necessary. +```c++ +class Parent : public GarbageCollectedFinalized<Parent> { + USING_PRE_FINALIZER(Parent, Dispose); + public: + void Dispose() { DisposeImpl(); } + + virtual void DisposeImpl() { + // Pre-finalizer for {Parent}. + } + // ... +}; + +class Child : public Parent { + public: + void DisposeImpl() { + // Pre-finalizer for {Child}. + Parent::DisposeImpl(); + } + // ... +}; +``` + +*Notes* +- Pre-finalizers are not allowed to resurrect objects, i.e., they are not allowed to relink dead objects into the object graph. +- Pre-finalizers have some implications on the garbage collector's performance: the garbage-collector needs to iterate all registered pre-finalizers at every GC. +Therefore, a pre-finalizer should be avoided unless it is really necessary. Especially, avoid defining a pre-finalizer in a class that can be allocated a lot. -### EAGERLY_FINALIZE - -A class-level annotation to indicate that class instances that the GC have determined as unreachable, should be eagerly -swept and finalized by the garbage collector, before the Blink thread (the mutator) resumes after a garbage -collection. The C++ destructor runs as part of this step. The default sweeping behavior is incremental, sweeping -pages as demanded by later heap allocations. - -Like for the pre-finalizer mechanism, an `EAGERLY_FINALIZE()`d class is allowed to touch other heap objects, which -is sometimes required, but the main use case for eager finalization is to promptly let go of off-heap resources -and associations, by unregistering and destructing those eagerly. If not done, these external references would -otherwise attempt to unsafely access an effectively-dead object (pending lazy sweeping of its heap page.) - -`EAGERLY_FINALIZE()` solves the same problem as pre-finalizers, but it arguably fits more naturally with the host -language's mechanism for finalization (C++ destructors.) One `EAGERLY_FINALIZE()` caveat is that the destructor -is not allowed to touch another eagerly finalized object (their finalization ordering isn't deterministic) nor -any pre-finalized objects. Choose the one you think best fits your need for prompt finalization. - ### STACK_ALLOCATED Class level annotation that should be used if the object is only stack allocated; it disallows use @@ -229,7 +236,7 @@ Classes with this annotation do not need a `Trace()` method, and should not inherit a garbage collected class. -### DISALLOW_NEW() +### DISALLOW_NEW Class-level annotation declaring the class cannot be separately allocated using `operator new`. It can be used on stack, as a part of object, or as a value in a heap collection.
diff --git a/third_party/blink/renderer/platform/heap/heap_test.cc b/third_party/blink/renderer/platform/heap/heap_test.cc index 4ec3955..10a2b62 100644 --- a/third_party/blink/renderer/platform/heap/heap_test.cc +++ b/third_party/blink/renderer/platform/heap/heap_test.cc
@@ -38,8 +38,10 @@ #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/synchronization/waitable_event.h" +#include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/platform/bindings/buildflags.h" #include "third_party/blink/renderer/platform/heap/address_cache.h" @@ -1872,6 +1874,11 @@ } TEST(HeapTest, LazySweepingLargeObjectPages) { + // Disable concurrent sweeping to check lazy sweeping on allocation. + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndDisableFeature( + blink::features::kBlinkHeapConcurrentSweeping); + ClearOutOldGarbage(); // Create free lists that can be reused for IntWrappers created in @@ -1909,70 +1916,6 @@ EXPECT_EQ(22, LargeHeapObject::destructor_calls_); } -class SimpleFinalizedEagerObjectBase - : public GarbageCollectedFinalized<SimpleFinalizedEagerObjectBase> { - public: - virtual ~SimpleFinalizedEagerObjectBase() = default; - void Trace(blink::Visitor* visitor) {} - - EAGERLY_FINALIZE(); - - protected: - SimpleFinalizedEagerObjectBase() = default; -}; - -class SimpleFinalizedEagerObject : public SimpleFinalizedEagerObjectBase { - public: - SimpleFinalizedEagerObject() = default; - ~SimpleFinalizedEagerObject() override { ++destructor_calls_; } - - static int destructor_calls_; -}; - -template <typename T> -class ParameterizedButEmpty { - public: - EAGERLY_FINALIZE(); -}; - -class SimpleFinalizedObjectInstanceOfTemplate final - : public GarbageCollectedFinalized<SimpleFinalizedObjectInstanceOfTemplate>, - public ParameterizedButEmpty<SimpleFinalizedObjectInstanceOfTemplate> { - public: - SimpleFinalizedObjectInstanceOfTemplate() = default; - ~SimpleFinalizedObjectInstanceOfTemplate() { ++destructor_calls_; } - - void Trace(blink::Visitor* visitor) {} - - static int destructor_calls_; -}; - -int SimpleFinalizedEagerObject::destructor_calls_ = 0; -int SimpleFinalizedObjectInstanceOfTemplate::destructor_calls_ = 0; - -TEST(HeapTest, EagerlySweepingPages) { - ClearOutOldGarbage(); - - SimpleFinalizedObject::destructor_calls_ = 0; - SimpleFinalizedEagerObject::destructor_calls_ = 0; - SimpleFinalizedObjectInstanceOfTemplate::destructor_calls_ = 0; - EXPECT_EQ(0, SimpleFinalizedObject::destructor_calls_); - EXPECT_EQ(0, SimpleFinalizedEagerObject::destructor_calls_); - for (int i = 0; i < 1000; i++) - MakeGarbageCollected<SimpleFinalizedObject>(); - for (int i = 0; i < 100; i++) - MakeGarbageCollected<SimpleFinalizedEagerObject>(); - for (int i = 0; i < 100; i++) - MakeGarbageCollected<SimpleFinalizedObjectInstanceOfTemplate>(); - ThreadState::Current()->CollectGarbage( - BlinkGC::kNoHeapPointersOnStack, BlinkGC::kAtomicMarking, - BlinkGC::kConcurrentAndLazySweeping, - BlinkGC::GCReason::kForcedGCForTesting); - EXPECT_EQ(0, SimpleFinalizedObject::destructor_calls_); - EXPECT_EQ(100, SimpleFinalizedEagerObject::destructor_calls_); - EXPECT_EQ(100, SimpleFinalizedObjectInstanceOfTemplate::destructor_calls_); -} - TEST(HeapTest, Finalization) { { HeapTestSubClass::destructor_calls_ = 0;
diff --git a/third_party/blink/renderer/platform/heap/incremental_marking_test.cc b/third_party/blink/renderer/platform/heap/incremental_marking_test.cc index ffd89bd..837ed0c 100644 --- a/third_party/blink/renderer/platform/heap/incremental_marking_test.cc +++ b/third_party/blink/renderer/platform/heap/incremental_marking_test.cc
@@ -5,7 +5,9 @@ #include <initializer_list> #include "base/bind.h" +#include "base/test/scoped_feature_list.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/heap/heap_allocator.h" @@ -1856,44 +1858,6 @@ driver.FinishGC(); } -namespace { - -class EagerlySweptWithVectorWithInlineStorage - : public GarbageCollected<EagerlySweptWithVectorWithInlineStorage> { - EAGERLY_FINALIZE(); - - public: - virtual void Trace(Visitor* visitor) { visitor->Trace(nested_); } - - HeapVector<HeapVector<Member<Object>>, 2>& nested() { return nested_; } - - private: - HeapVector<HeapVector<Member<Object>>, 2> nested_; -}; - -} // namespace - -TEST(IncrementalMarkingTest, - InPayloadWriteBarrierInEagerlyFinalizedRegistersInvalidSlotForCompaction) { - // Regression test: https://crbug.com/918064 - // - // Same as InPayloadWriteBarrierRegistersInvalidSlotForCompaction with the - // addition that the object is marked as EAGERLY_FINALIZE(). This requires - // that slots filtering happens before any eager sweep phase. - - IncrementalMarkingTestDriver driver(ThreadState::Current()); - ThreadState::Current()->EnableCompactionForNextGCForTesting(); - EagerlySweptWithVectorWithInlineStorage* eagerly = - MakeGarbageCollected<EagerlySweptWithVectorWithInlineStorage>(); - driver.Start(); - eagerly->nested().emplace_back(1); - eagerly->nested().at(0).emplace_back(MakeGarbageCollected<Object>()); - driver.FinishSteps(); - CHECK(!HeapObjectHeader::FromPayload(eagerly)->IsMarked()); - eagerly = nullptr; - driver.FinishGC(); -} - TEST(IncrementalMarkingTest, AdjustMarkedBytesOnMarkedBackingStore) { // Regression test: https://crbug.com/966456 // @@ -1901,6 +1865,11 @@ // marked bytes when the page is actually about to be swept and marking is not // in progress. + // Disable concurrent sweeping to check that sweeping is not in progress after + // the FinishGC call. + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndDisableFeature( + blink::features::kBlinkHeapConcurrentSweeping); using Container = HeapVector<Member<Object>>; Persistent<Container> holder(MakeGarbageCollected<Container>()); holder->push_back(MakeGarbageCollected<Object>());
diff --git a/third_party/blink/renderer/platform/image-decoders/segment_stream_test.cc b/third_party/blink/renderer/platform/image-decoders/segment_stream_test.cc index c17f3bc..a4c36cc 100644 --- a/third_party/blink/renderer/platform/image-decoders/segment_stream_test.cc +++ b/third_party/blink/renderer/platform/image-decoders/segment_stream_test.cc
@@ -4,7 +4,6 @@ #include "third_party/blink/renderer/platform/image-decoders/segment_stream.h" -#include <array> #include "base/memory/scoped_refptr.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/image-decoders/segment_reader.h" @@ -671,7 +670,7 @@ } scoped_refptr<SegmentReader> CreateSegmentReader() { - std::array<char, kBufferAllocationSize> raw_buffer; + Vector<char> raw_buffer(kBufferAllocationSize); scoped_refptr<SharedBuffer> shared_buffer = SharedBuffer::Create(raw_buffer.data(), kBufferAllocationSize); @@ -684,13 +683,13 @@ size_t ReadFromSegmentStream(SegmentStream& segment_stream, size_t amount_to_read) { - std::array<char, kBufferAllocationSize> read_buffer; + Vector<char> read_buffer(kBufferAllocationSize); return segment_stream.read(read_buffer.data(), amount_to_read); } size_t PeekIntoSegmentStream(SegmentStream& segment_stream, size_t amount_to_peek) { - std::array<char, kBufferAllocationSize> peek_buffer; + Vector<char> peek_buffer(kBufferAllocationSize); return segment_stream.peek(peek_buffer.data(), amount_to_peek); }
diff --git a/third_party/blink/renderer/platform/lifecycle_context_test.cc b/third_party/blink/renderer/platform/lifecycle_context_test.cc index ef1b388..a0ee46c42 100644 --- a/third_party/blink/renderer/platform/lifecycle_context_test.cc +++ b/third_party/blink/renderer/platform/lifecycle_context_test.cc
@@ -143,8 +143,10 @@ // This is a regression test for http://crbug.com/854639. TEST(LifecycleContextTest, ShouldNotHitCFICheckOnIncrementalMarking) { base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitAndEnableFeature( - blink::features::kBlinkHeapIncrementalMarking); + // Disable concurrent sweeping as worker_pool task environment is not set. + scoped_feature_list.InitWithFeatures( + {blink::features::kBlinkHeapIncrementalMarking}, + {blink::features::kBlinkHeapConcurrentSweeping}); ThreadState* thread_state = ThreadState::Current(); thread_state->IncrementalMarkingStart(BlinkGC::GCReason::kForcedGCForTesting);
diff --git a/third_party/blink/renderer/platform/loader/fetch/fetch_context.h b/third_party/blink/renderer/platform/loader/fetch/fetch_context.h index f298e32..ee03ed3 100644 --- a/third_party/blink/renderer/platform/loader/fetch/fetch_context.h +++ b/third_party/blink/renderer/platform/loader/fetch/fetch_context.h
@@ -142,6 +142,10 @@ return false; } + virtual WebURLRequest::PreviewsState previews_state() const { + return WebURLRequest::kPreviewsUnspecified; + } + private: DISALLOW_COPY_AND_ASSIGN(FetchContext); };
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc index e63450ae..2e89b6a 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
@@ -243,6 +243,33 @@ return new_priority; } +ResourceLoadPriority AdjustPriorityWithDeferScriptIntervention( + const FetchContext& fetch_context, + ResourceLoadPriority priority_so_far, + ResourceType type, + const ResourceRequest& resource_request, + FetchParameters::DeferOption defer_option, + bool is_link_preload) { + WebURLRequest::PreviewsState context_previews_state = + fetch_context.previews_state(); + + if (type != ResourceType::kScript) + return priority_so_far; + + // If none of the JavaScript resources are render blocking (due to the + // DeferAllScript intervention), then lower their priority so they do not + // contend for network resources with higher priority resources that may be + // render blocking (e.g., html, css). ResourceLoadPriority::kMedium + // corresponds to a network priority of + // network::mojom::blink::RequestPriority::kLow which is considered delayable + // by the resource scheduler on the browser side. + if (RuntimeEnabledFeatures::ForceDeferScriptInterventionEnabled() || + (context_previews_state & WebURLRequest::kDeferAllScriptOn)) { + return std::min(priority_so_far, ResourceLoadPriority::kMedium); + } + return priority_so_far; +} + std::unique_ptr<TracedValue> BeginResourceLoadData( const blink::ResourceRequest& request) { auto value = std::make_unique<TracedValue>(); @@ -429,19 +456,19 @@ std::move(callback)); } +// This method simply takes in information about a ResourceRequest, and returns +// a priority. It will not be called for ResourceRequests that already have a +// pre-set priority (e.g., requests coming from a Service Worker) except for +// images, which may need to be reprioritized. ResourceLoadPriority ResourceFetcher::ComputeLoadPriority( ResourceType type, const ResourceRequest& resource_request, ResourcePriority::VisibilityStatus visibility, FetchParameters::DeferOption defer_option, FetchParameters::SpeculativePreloadType speculative_preload_type, - bool is_link_preload, - bool is_stale_revalidation) { - // Stale revalidation resource requests should be very low regardless of - // the |type|. - if (is_stale_revalidation) - return ResourceLoadPriority::kVeryLow; - + bool is_link_preload) { + DCHECK(!resource_request.PriorityHasBeenSet() || + type == ResourceType::kImage); ResourceLoadPriority priority = TypeToPriority(type); // Visible resources (images in practice) get a boost to High priority. @@ -508,6 +535,10 @@ priority = AdjustPriorityWithPriorityHint(priority, type, resource_request, defer_option, is_link_preload); + priority = AdjustPriorityWithDeferScriptIntervention( + Context(), priority, type, resource_request, defer_option, + is_link_preload); + if (properties_->IsSubframeDeprioritizationEnabled()) { if (properties_->IsMainFrame()) { DEFINE_STATIC_LOCAL( @@ -534,12 +565,7 @@ } } - // A manually set priority acts as a floor. This is used to ensure that - // synchronous requests are always given the highest possible priority, as - // well as to ensure that there isn't priority churn if images move in and out - // of the viewport, or are displayed more than once, both in and out of the - // viewport. - return std::max(resource_request.Priority(), priority); + return priority; } ResourceFetcher::ResourceFetcher(const ResourceFetcherInit& init) @@ -837,10 +863,19 @@ if (!params.Url().IsValid()) return ResourceRequestBlockedReason::kOther; - resource_request.SetPriority(ComputeLoadPriority( - resource_type, params.GetResourceRequest(), ResourcePriority::kNotVisible, - params.Defer(), params.GetSpeculativePreloadType(), - params.IsLinkPreload(), params.IsStaleRevalidation())); + ResourceLoadPriority computed_load_priority = resource_request.Priority(); + // We should only compute the priority for ResourceRequests whose priority has + // not already been set. + if (!resource_request.PriorityHasBeenSet()) { + computed_load_priority = ComputeLoadPriority( + resource_type, params.GetResourceRequest(), + ResourcePriority::kNotVisible, params.Defer(), + params.GetSpeculativePreloadType(), params.IsLinkPreload()); + } + + DCHECK_NE(computed_load_priority, ResourceLoadPriority::kUnresolved); + resource_request.SetPriority(computed_load_priority); + if (resource_request.GetCacheMode() == mojom::FetchCacheMode::kDefault) { resource_request.SetCacheMode(Context().ResourceRequestCachePolicy( resource_request, resource_type, params.Defer())); @@ -1995,22 +2030,27 @@ continue; ResourcePriority resource_priority = resource->PriorityFromObservers(); - ResourceLoadPriority resource_load_priority = ComputeLoadPriority( + ResourceLoadPriority computed_load_priority = ComputeLoadPriority( ResourceType::kImage, resource->GetResourceRequest(), resource_priority.visibility); - if (resource_load_priority == resource->GetResourceRequest().Priority()) + // Only boost the priority of an image, never lower it. This ensures that + // there isn't priority churn if images move in and out of the viewport, or + // are displayed more than once, both in and out of the viewport. + if (computed_load_priority <= resource->GetResourceRequest().Priority()) continue; - resource->DidChangePriority(resource_load_priority, + DCHECK_GT(computed_load_priority, + resource->GetResourceRequest().Priority()); + resource->DidChangePriority(computed_load_priority, resource_priority.intra_priority_value); TRACE_EVENT_NESTABLE_ASYNC_INSTANT1( TRACE_DISABLED_BY_DEFAULT("network"), "ResourcePrioritySet", TRACE_ID_WITH_SCOPE("BlinkResourceID", TRACE_ID_LOCAL(resource->InspectorId())), - "data", ResourcePrioritySetData(resource_load_priority)); + "data", ResourcePrioritySetData(computed_load_priority)); DCHECK(!IsDetached()); resource_load_observer_->DidChangePriority( - resource->InspectorId(), resource_load_priority, + resource->InspectorId(), computed_load_priority, resource_priority.intra_priority_value); } } @@ -2108,6 +2148,9 @@ FetchParameters params(stale_resource->GetResourceRequest()); params.SetStaleRevalidation(true); params.MutableResourceRequest().SetSkipServiceWorker(true); + // Stale revalidation resource requests should be very low regardless of + // the |type|. + params.MutableResourceRequest().SetPriority(ResourceLoadPriority::kVeryLow); RawResource::Fetch( params, this, MakeGarbageCollected<StaleRevalidationResourceClient>(stale_resource));
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h index bea3bbfe..c69c755 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h +++ b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h
@@ -264,11 +264,9 @@ ResourcePriority::VisibilityStatus visibility_statue, FetchParameters::DeferOption defer_option, FetchParameters::SpeculativePreloadType speculative_preload_type, - bool is_link_preload, - bool is_stale_revalidation) { + bool is_link_preload) { return ComputeLoadPriority(type, request, visibility_statue, defer_option, - speculative_preload_type, is_link_preload, - is_stale_revalidation); + speculative_preload_type, is_link_preload); } private: @@ -294,8 +292,7 @@ FetchParameters::DeferOption = FetchParameters::kNoDefer, FetchParameters::SpeculativePreloadType = FetchParameters::SpeculativePreloadType::kNotSpeculative, - bool is_link_preload = false, - bool is_stale_revalidation = false); + bool is_link_preload = false); // |virtual_time_pauser| is an output parameter. PrepareRequest may // create a new WebScopedVirtualTimePauser and set it to
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher_test.cc b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher_test.cc index 68b1978..8e329875 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher_test.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher_test.cc
@@ -996,66 +996,66 @@ ResourceRequest request(KURL("https://www.example.com/")); { - // Subframe depriotization is disabled (main frame case). + // Subframe deprioritization is disabled (main frame case). properties.SetIsMainFrame(true); properties.SetIsSubframeDeprioritizationEnabled(false); const auto priority = fetcher->ComputeLoadPriorityForTesting( ResourceType::kScript, request, ResourcePriority::kNotVisible, FetchParameters::DeferOption::kNoDefer, FetchParameters::SpeculativePreloadType::kNotSpeculative, - false /* is_link_preload */, false /* is_stale_revalidation */); + false /* is_link_preload */); EXPECT_EQ(priority, ResourceLoadPriority::kHigh); } { - // Subframe depriotization is disabled (nested frame case). + // Subframe deprioritization is disabled (nested frame case). properties.SetIsMainFrame(false); properties.SetIsSubframeDeprioritizationEnabled(false); const auto priority = fetcher->ComputeLoadPriorityForTesting( ResourceType::kScript, request, ResourcePriority::kNotVisible, FetchParameters::DeferOption::kNoDefer, FetchParameters::SpeculativePreloadType::kNotSpeculative, - false /* is_link_preload */, false /* is_stale_revalidation */); + false /* is_link_preload */); EXPECT_EQ(priority, ResourceLoadPriority::kHigh); } { - // Subframe depriotization is enabled (main frame case), kHigh. + // Subframe deprioritization is enabled (main frame case), kHigh. properties.SetIsMainFrame(true); properties.SetIsSubframeDeprioritizationEnabled(true); const auto priority = fetcher->ComputeLoadPriorityForTesting( ResourceType::kScript, request, ResourcePriority::kNotVisible, FetchParameters::DeferOption::kNoDefer, FetchParameters::SpeculativePreloadType::kNotSpeculative, - false /* is_link_preload */, false /* is_stale_revalidation */); + false /* is_link_preload */); EXPECT_EQ(priority, ResourceLoadPriority::kHigh); } { - // Subframe depriotization is enabled (nested frame case), kHigh => kLow. + // Subframe deprioritization is enabled (nested frame case), kHigh => kLow. properties.SetIsMainFrame(false); properties.SetIsSubframeDeprioritizationEnabled(true); const auto priority = fetcher->ComputeLoadPriorityForTesting( ResourceType::kScript, request, ResourcePriority::kNotVisible, FetchParameters::DeferOption::kNoDefer, FetchParameters::SpeculativePreloadType::kNotSpeculative, - false /* is_link_preload */, false /* is_stale_revalidation */); + false /* is_link_preload */); EXPECT_EQ(priority, ResourceLoadPriority::kLow); } { - // Subframe depriotization is enabled (main frame case), kMedium. + // Subframe deprioritization is enabled (main frame case), kMedium. properties.SetIsMainFrame(true); properties.SetIsSubframeDeprioritizationEnabled(true); const auto priority = fetcher->ComputeLoadPriorityForTesting( ResourceType::kMock, request, ResourcePriority::kNotVisible, FetchParameters::DeferOption::kNoDefer, FetchParameters::SpeculativePreloadType::kNotSpeculative, - false /* is_link_preload */, false /* is_stale_revalidation */); + false /* is_link_preload */); EXPECT_EQ(priority, ResourceLoadPriority::kMedium); } { - // Subframe depriotization is enabled (nested frame case), kMedium => + // Subframe deprioritization is enabled (nested frame case), kMedium => // kLowest. properties.SetIsMainFrame(false); properties.SetIsSubframeDeprioritizationEnabled(true); @@ -1063,7 +1063,7 @@ ResourceType::kMock, request, ResourcePriority::kNotVisible, FetchParameters::DeferOption::kNoDefer, FetchParameters::SpeculativePreloadType::kNotSpeculative, - false /* is_link_preload */, false /* is_stale_revalidation */); + false /* is_link_preload */); EXPECT_EQ(priority, ResourceLoadPriority::kLowest); } }
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_request.cc b/third_party/blink/renderer/platform/loader/fetch/resource_request.cc index a02cfb3a..e956924 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_request.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource_request.cc
@@ -61,7 +61,7 @@ cache_mode_(mojom::FetchCacheMode::kDefault), skip_service_worker_(false), download_to_cache_only_(false), - priority_(ResourceLoadPriority::kLowest), + priority_(ResourceLoadPriority::kUnresolved), intra_priority_value_(0), requestor_id_(0), plugin_child_id_(-1), @@ -286,6 +286,10 @@ return intra_priority_value_; } +bool ResourceRequest::PriorityHasBeenSet() const { + return priority_ != ResourceLoadPriority::kUnresolved; +} + void ResourceRequest::SetPriority(ResourceLoadPriority priority, int intra_priority_value) { priority_ = priority;
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_request.h b/third_party/blink/renderer/platform/loader/fetch/resource_request.h index 80d73c3..c3b3345 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_request.h +++ b/third_party/blink/renderer/platform/loader/fetch/resource_request.h
@@ -253,6 +253,7 @@ // TODO(yhirano): Describe what Priority and IntraPriorityValue are. ResourceLoadPriority Priority() const; int IntraPriorityValue() const; + bool PriorityHasBeenSet() const; void SetPriority(ResourceLoadPriority, int intra_priority_value = 0); bool IsConditional() const;
diff --git a/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.cc b/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.cc index 5091f27..eaf5ab5 100644 --- a/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.cc +++ b/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.cc
@@ -96,7 +96,7 @@ source.CharactersSizeInBytes(), digest_value)) return nullptr; - Key key; + Key key(kKeySize); DCHECK_EQ(digest_value.size(), kKeySize); memcpy(key.data(), digest_value.data(), kKeySize); @@ -192,7 +192,7 @@ return; } - Key key; + Key key(kKeySize); std::copy(data, data + kKeySize, std::begin(key)); data += kKeySize; size_t entry_size = ReadVal<size_t>(data);
diff --git a/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.h b/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.h index b3af2d9..128ed42 100644 --- a/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.h +++ b/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.h
@@ -6,7 +6,6 @@ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_SOURCE_KEYED_CACHED_METADATA_HANDLER_H_ #include <stdint.h> -#include <array> #include "third_party/blink/renderer/platform/loader/fetch/cached_metadata.h" #include "third_party/blink/renderer/platform/loader/fetch/cached_metadata_handler.h" #include "third_party/blink/renderer/platform/loader/fetch/resource.h" @@ -51,7 +50,7 @@ private: // Keys are SHA-256, which are 256/8 = 32 bytes. static constexpr size_t kKeySize = 32; - typedef std::array<uint8_t, kKeySize> Key; + typedef Vector<uint8_t, kKeySize> Key; class SingleKeyHandler; class KeyHash;
diff --git a/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler_test.cc b/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler_test.cc index 81691ef..d335a4eb 100644 --- a/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler_test.cc +++ b/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler_test.cc
@@ -4,8 +4,6 @@ #include "third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.h" -#include <array> - #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_crypto.h" #include "third_party/blink/renderer/platform/crypto.h" @@ -88,16 +86,15 @@ const base::Time response_time_; }; -template <size_t N> ::testing::AssertionResult CachedMetadataFailure( const char* failure_msg, const char* actual_expression, - const std::array<uint8_t, N>& expected, + const Vector<uint8_t>& expected, const scoped_refptr<CachedMetadata>& actual) { ::testing::Message msg; msg << failure_msg << " for " << actual_expression; - msg << "\n Expected: [" << N << "] { "; - for (size_t i = 0; i < N; ++i) { + msg << "\n Expected: [" << expected.size() << "] { "; + for (size_t i = 0; i < expected.size(); ++i) { if (i > 0) msg << ", "; msg << std::hex << static_cast<int>(expected[i]); @@ -118,22 +115,21 @@ return testing::AssertionFailure() << msg; } -template <size_t N> ::testing::AssertionResult CachedMetadataEqual( const char* expected_expression, const char* actual_expression, - const std::array<uint8_t, N>& expected, + const Vector<uint8_t>& expected, const scoped_refptr<CachedMetadata>& actual) { if (!actual) { return CachedMetadataFailure("Expected non-null data", actual_expression, expected, actual); } - if (actual->size() != N) { + if (actual->size() != expected.size()) { return CachedMetadataFailure("Wrong size", actual_expression, expected, actual); } const uint8_t* actual_data = actual->Data(); - for (size_t i = 0; i < N; ++i) { + for (size_t i = 0; i < expected.size(); ++i) { if (actual_data[i] != expected[i]) { return CachedMetadataFailure("Wrong data", actual_expression, expected, actual); @@ -190,7 +186,7 @@ SingleCachedMetadataHandler* source2_handler = handler->HandlerForSource(source2); - std::array<uint8_t, 3> data1 = {1, 2, 3}; + Vector<uint8_t> data1 = {1, 2, 3}; source1_handler->SetCachedMetadata(0xbeef, data1.data(), data1.size()); EXPECT_NE(nullptr, source1_handler); @@ -217,10 +213,10 @@ SingleCachedMetadataHandler* source2_handler = handler->HandlerForSource(source2); - std::array<uint8_t, 3> data1 = {1, 2, 3}; + Vector<uint8_t> data1 = {1, 2, 3}; source1_handler->SetCachedMetadata(0xbeef, data1.data(), data1.size()); - std::array<uint8_t, 4> data2 = {3, 4, 5, 6}; + Vector<uint8_t> data2 = {3, 4, 5, 6}; source2_handler->SetCachedMetadata(0x5eed, data2.data(), data2.size()); EXPECT_NE(nullptr, source1_handler); @@ -266,10 +262,10 @@ SingleCachedMetadataHandler* source2_handler = handler->HandlerForSource(source2); - std::array<uint8_t, 3> data1 = {1, 2, 3}; + Vector<uint8_t> data1 = {1, 2, 3}; source1_handler->SetCachedMetadata(0xbeef, data1.data(), data1.size()); - std::array<uint8_t, 4> data2 = {3, 4, 5, 6}; + Vector<uint8_t> data2 = {3, 4, 5, 6}; source2_handler->SetCachedMetadata(0x5eed, data2.data(), data2.size()); // Load from platform @@ -296,11 +292,11 @@ SingleCachedMetadataHandler* source2_handler = handler->HandlerForSource(source2); - std::array<uint8_t, 3> data1 = {1, 2, 3}; + Vector<uint8_t> data1 = {1, 2, 3}; source1_handler->SetCachedMetadata(0xbeef, data1.data(), data1.size(), CachedMetadataHandler::kCacheLocally); - std::array<uint8_t, 4> data2 = {3, 4, 5, 6}; + Vector<uint8_t> data2 = {3, 4, 5, 6}; source2_handler->SetCachedMetadata(0x5eed, data2.data(), data2.size()); // Load from platform @@ -364,8 +360,8 @@ KURL url("http://SourceKeyedCachedMetadataHandlerTest.com"); WTF::String source1("source1"); WTF::String source2("source2"); - std::array<uint8_t, 3> data1 = {1, 2, 3}; - std::array<uint8_t, 4> data2 = {3, 4, 5, 6}; + Vector<uint8_t> data1 = {1, 2, 3}; + Vector<uint8_t> data2 = {3, 4, 5, 6}; { SourceKeyedCachedMetadataHandler* handler = MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
diff --git a/third_party/blink/renderer/platform/mojo/blink_typemaps.gni b/third_party/blink/renderer/platform/mojo/blink_typemaps.gni index 39a49ae0..7d8acc2 100644 --- a/third_party/blink/renderer/platform/mojo/blink_typemaps.gni +++ b/third_party/blink/renderer/platform/mojo/blink_typemaps.gni
@@ -4,6 +4,7 @@ typemaps = [ "//ui//gfx//mojo//transform.typemap", + "//services/network/public/cpp/http_request_headers.typemap", "//third_party/blink/renderer/core/messaging/blink_cloneable_message.typemap", "//third_party/blink/renderer/core/messaging/blink_transferable_message.typemap", "//third_party/blink/renderer/modules/indexeddb/indexed_db_blink.typemap", @@ -18,7 +19,6 @@ "//third_party/blink/renderer/platform/mojo/time.typemap", "//third_party/blink/renderer/platform/network/encoded_form_data_element.typemap", "//third_party/blink/renderer/platform/network/encoded_form_data.typemap", - "//third_party/blink/renderer/platform/network/http_request_headers.typemap", "//third_party/blink/public/common/manifest/display_mode.typemap", "//third_party/blink/public/common/screen_orientation/screen_orientation_lock_types.typemap", "//third_party/blink/public/mojom/bluetooth/bluetooth.typemap",
diff --git a/third_party/blink/renderer/platform/network/http_request_headers.typemap b/third_party/blink/renderer/platform/network/http_request_headers.typemap deleted file mode 100644 index 4a2fc001..0000000 --- a/third_party/blink/renderer/platform/network/http_request_headers.typemap +++ /dev/null
@@ -1,9 +0,0 @@ -# Copyright 2019 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -mojom = "//services/network/public/mojom/http_request_headers.mojom" -public_headers = - [ "//third_party/blink/renderer/platform/network/http_header_map.h" ] -traits_headers = [ "//third_party/blink/renderer/platform/network/http_request_headers_mojom_traits.h" ] -type_mappings = [ "network.mojom.HttpRequestHeaders=::blink::HTTPHeaderMap" ]
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index e53e5a69..3e1af82 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1441,7 +1441,7 @@ }, { name: "SignedExchangeSubresourcePrefetch", - origin_trial_feature_name: "SignedExchangeSubresourcePrefetch", + origin_trial_feature_name: "SignedExchangeSubresourcePrefetchM77", status: "experimental", }, { @@ -1460,7 +1460,7 @@ }, { name: "SmsReceiver", - status: "experimental", + status: {"Android": "experimental", "default": "test"}, }, // Used as argument in attribute of stable-release functions/interfaces // where a runtime-enabled feature name is required for correct IDL syntax.
diff --git a/third_party/blink/renderer/platform/scheduler/BUILD.gn b/third_party/blink/renderer/platform/scheduler/BUILD.gn index 0bd21e0..8bbc2b6 100644 --- a/third_party/blink/renderer/platform/scheduler/BUILD.gn +++ b/third_party/blink/renderer/platform/scheduler/BUILD.gn
@@ -61,6 +61,8 @@ "common/worker_pool.cc", "main_thread/auto_advancing_virtual_time_domain.cc", "main_thread/auto_advancing_virtual_time_domain.h", + "main_thread/compositor_priority_experiments.cc", + "main_thread/compositor_priority_experiments.h", "main_thread/deadline_task_runner.cc", "main_thread/deadline_task_runner.h", "main_thread/frame_origin_type.cc",
diff --git a/third_party/blink/renderer/platform/scheduler/common/features.h b/third_party/blink/renderer/platform/scheduler/common/features.h index 36dde17..aaffcec 100644 --- a/third_party/blink/renderer/platform/scheduler/common/features.h +++ b/third_party/blink/renderer/platform/scheduler/common/features.h
@@ -62,6 +62,13 @@ "BlinkSchedulerVeryHighPriorityForCompositingWhenFast", base::FEATURE_DISABLED_BY_DEFAULT}; +// If enabled, compositor priority will be set to kVeryHighPriority if the last +// task completed was not a compositor task, and kNormalPriority if the last +// task completed was a compositor task. +const base::Feature kVeryHighPriorityForCompositingAlternating{ + "BlinkSchedulerVeryHighPriorityForCompositingAlternating", + base::FEATURE_DISABLED_BY_DEFAULT}; + // LOAD PRIORITY EXPERIMENT CONTROLS // Enables setting the priority of background (with no audio) pages'
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/compositor_priority_experiments.cc b/third_party/blink/renderer/platform/scheduler/main_thread/compositor_priority_experiments.cc new file mode 100644 index 0000000..db3bbb4 --- /dev/null +++ b/third_party/blink/renderer/platform/scheduler/main_thread/compositor_priority_experiments.cc
@@ -0,0 +1,103 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/platform/scheduler/main_thread/compositor_priority_experiments.h" + +#include "third_party/blink/renderer/platform/scheduler/common/features.h" +#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h" +#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h" + +namespace blink { +namespace scheduler { + +using QueuePriority = base::sequence_manager::TaskQueue::QueuePriority; + +CompositorPriorityExperiments::CompositorPriorityExperiments( + MainThreadSchedulerImpl* scheduler) + : scheduler_(scheduler), experiment_(GetExperimentFromFeatureList()) {} + +CompositorPriorityExperiments::~CompositorPriorityExperiments() {} + +CompositorPriorityExperiments::Experiment +CompositorPriorityExperiments::GetExperimentFromFeatureList() { + if (base::FeatureList::IsEnabled(kVeryHighPriorityForCompositingAlways)) { + return Experiment::kVeryHighPriorityForCompositingAlways; + } else if (base::FeatureList::IsEnabled( + kVeryHighPriorityForCompositingWhenFast)) { + return Experiment::kVeryHighPriorityForCompositingWhenFast; + } else if (base::FeatureList::IsEnabled( + kVeryHighPriorityForCompositingAlternating)) { + return Experiment::kVeryHighPriorityForCompositingAlternating; + } else { + return Experiment::kNone; + } +} + +bool CompositorPriorityExperiments::IsExperimentActive() const { + if (experiment_ == Experiment::kNone) + return false; + return true; +} + +QueuePriority CompositorPriorityExperiments::GetCompositorPriority() const { + switch (experiment_) { + case Experiment::kVeryHighPriorityForCompositingAlways: + return QueuePriority::kVeryHighPriority; + case Experiment::kVeryHighPriorityForCompositingWhenFast: + if (compositing_is_fast_) { + return QueuePriority::kVeryHighPriority; + } + return QueuePriority::kNormalPriority; + case Experiment::kVeryHighPriorityForCompositingAlternating: + return alternating_compositor_priority_; + case Experiment::kNone: + NOTREACHED(); + return QueuePriority::kNormalPriority; + } +} + +void CompositorPriorityExperiments::SetCompositingIsFast( + bool compositing_is_fast) { + compositing_is_fast_ = compositing_is_fast; +} + +void CompositorPriorityExperiments::OnTaskCompleted( + MainThreadTaskQueue* queue, + QueuePriority current_compositor_priority) { + if (!queue) + return; + + // Don't change priorities if compositor priority is already set to highest + // or higher. + if (current_compositor_priority <= QueuePriority::kHighestPriority) + return; + + switch (experiment_) { + case Experiment::kVeryHighPriorityForCompositingAlways: + return; + case Experiment::kVeryHighPriorityForCompositingWhenFast: + return; + case Experiment::kVeryHighPriorityForCompositingAlternating: + // Deprioritize the compositor if it has just run a task. Prioritize the + // compositor if another task has run regardless of its priority. This + // prevents starving the compositor while allowing other work to run + // in-between. + if (queue->queue_type() == MainThreadTaskQueue::QueueType::kCompositor && + alternating_compositor_priority_ == + QueuePriority::kVeryHighPriority) { + alternating_compositor_priority_ = QueuePriority::kNormalPriority; + scheduler_->OnCompositorPriorityExperimentUpdateCompositorPriority(); + } else if (alternating_compositor_priority_ == + QueuePriority::kNormalPriority) { + alternating_compositor_priority_ = QueuePriority::kVeryHighPriority; + scheduler_->OnCompositorPriorityExperimentUpdateCompositorPriority(); + } + return; + case Experiment::kNone: + return; + } +} + +} // namespace scheduler +} // namespace blink
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/compositor_priority_experiments.h b/third_party/blink/renderer/platform/scheduler/main_thread/compositor_priority_experiments.h new file mode 100644 index 0000000..d2e19b5b --- /dev/null +++ b/third_party/blink/renderer/platform/scheduler/main_thread/compositor_priority_experiments.h
@@ -0,0 +1,63 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_COMPOSITOR_PRIORITY_EXPERIMENTS_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_COMPOSITOR_PRIORITY_EXPERIMENTS_H_ + +#include "base/task/sequence_manager/task_queue.h" +#include "third_party/blink/renderer/platform/platform_export.h" +#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" + +namespace blink { +namespace scheduler { + +using QueuePriority = base::sequence_manager::TaskQueue::QueuePriority; + +class MainThreadSchedulerImpl; +class MainThreadTaskQueue; + +class PLATFORM_EXPORT CompositorPriorityExperiments { + DISALLOW_NEW(); + + public: + explicit CompositorPriorityExperiments(MainThreadSchedulerImpl* scheduler); + ~CompositorPriorityExperiments(); + + enum class Experiment { + kNone, + kVeryHighPriorityForCompositingAlways, + kVeryHighPriorityForCompositingWhenFast, + kVeryHighPriorityForCompositingAlternating + }; + + bool IsExperimentActive() const; + + QueuePriority GetCompositorPriority() const; + + void SetCompositingIsFast(bool compositing_is_fast); + + void OnTaskCompleted(MainThreadTaskQueue* queue, + QueuePriority current_priority); + + QueuePriority GetAlternatingPriority() const { + return alternating_compositor_priority_; + } + + private: + MainThreadSchedulerImpl* scheduler_; // Not owned. + + static Experiment GetExperimentFromFeatureList(); + + const Experiment experiment_; + + QueuePriority alternating_compositor_priority_ = + QueuePriority::kVeryHighPriority; + + bool compositing_is_fast_ = false; +}; + +} // namespace scheduler +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_COMPOSITOR_PRIORITY_EXPERIMENTS_H_
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc index 709ba156..44106d40 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc
@@ -472,7 +472,8 @@ virtual_time_stopped(false), nested_runloop(false), compositing_experiment(main_thread_scheduler_impl), - should_prioritize_compositing(false) {} + should_prioritize_compositing(false), + compositor_priority_experiments(main_thread_scheduler_impl) {} MainThreadSchedulerImpl::MainThreadOnly::~MainThreadOnly() = default; @@ -561,11 +562,6 @@ use_resource_priorities_only_during_loading = base::FeatureList::IsEnabled(kUseResourceFetchPriorityOnlyWhenLoading); - compositor_very_high_priority_always = - base::FeatureList::IsEnabled(kVeryHighPriorityForCompositingAlways); - compositor_very_high_priority_when_fast = - base::FeatureList::IsEnabled(kVeryHighPriorityForCompositingWhenFast); - if (use_resource_fetch_priority || use_resource_priorities_only_during_loading) { base::FieldTrialParams params; @@ -1493,19 +1489,15 @@ NOTREACHED(); } - if (scheduling_settings_.compositor_very_high_priority_always && - new_policy.compositor_priority() != - TaskQueue::QueuePriority::kHighestPriority) { + // Do not reset compositor priority if set to highest or higher. + if (new_policy.compositor_priority() > + TaskQueue::QueuePriority::kHighestPriority && + main_thread_only().compositor_priority_experiments.IsExperimentActive()) { + main_thread_only().compositor_priority_experiments.SetCompositingIsFast( + main_thread_compositing_is_fast); new_policy.compositor_priority() = - TaskQueue::QueuePriority::kVeryHighPriority; - } - - if (scheduling_settings_.compositor_very_high_priority_when_fast && - main_thread_compositing_is_fast && - new_policy.compositor_priority() != - TaskQueue::QueuePriority::kHighestPriority) { - new_policy.compositor_priority() = - TaskQueue::QueuePriority::kVeryHighPriority; + main_thread_only() + .compositor_priority_experiments.GetCompositorPriority(); } // TODO(skyostil): Add an idle state for foreground tabs too. @@ -2443,6 +2435,9 @@ main_thread_only().task_priority_for_tracing = base::nullopt; RecordTaskUkm(queue.get(), task, *task_timing); + + main_thread_only().compositor_priority_experiments.OnTaskCompleted( + queue.get(), main_thread_only().current_policy.compositor_priority()); } void MainThreadSchedulerImpl::RecordTaskUkm( @@ -2707,6 +2702,11 @@ UpdatePolicy(); } +void MainThreadSchedulerImpl:: + OnCompositorPriorityExperimentUpdateCompositorPriority() { + UpdatePolicy(); +} + void MainThreadSchedulerImpl::OnSafepointEntered() { DCHECK(WTF::IsMainThread()); DCHECK(!main_thread_only().nested_runloop);
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h index f12a061..aece952 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h
@@ -30,6 +30,7 @@ #include "third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h" #include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h" #include "third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.h" +#include "third_party/blink/renderer/platform/scheduler/main_thread/compositor_priority_experiments.h" #include "third_party/blink/renderer/platform/scheduler/main_thread/deadline_task_runner.h" #include "third_party/blink/renderer/platform/scheduler/main_thread/idle_time_estimator.h" #include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.h" @@ -121,10 +122,6 @@ bool use_resource_fetch_priority; bool use_resource_priorities_only_during_loading; - // Compositor priority experiment (crbug.com/966177). - bool compositor_very_high_priority_always; - bool compositor_very_high_priority_when_fast; - // Contains a mapping from net::RequestPriority to TaskQueue::QueuePriority // when use_resource_fetch_priority is enabled. std::array<base::sequence_manager::TaskQueue::QueuePriority, @@ -393,6 +390,8 @@ void SetShouldPrioritizeCompositing(bool should_prioritize_compositing); + void OnCompositorPriorityExperimentUpdateCompositorPriority(); + // Allow places in the scheduler to do some work after the current task. // The primary use case here is batching – to allow updates to be processed // only once per task. @@ -429,6 +428,8 @@ MainThreadSchedulerImplForTest; friend class main_thread_scheduler_impl_unittest::MainThreadSchedulerImplTest; + friend class CompositorPriorityExperiments; + FRIEND_TEST_ALL_PREFIXES( main_thread_scheduler_impl_unittest::MainThreadSchedulerImplTest, ShouldIgnoreTaskForUkm); @@ -891,6 +892,9 @@ // List of callbacks to execute after the current task. WTF::Vector<base::OnceClosure> on_task_completion_callbacks; + + // Compositing priority experiments (crbug.com/966177). + CompositorPriorityExperiments compositor_priority_experiments; }; struct AnyThread {
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 72645360..c515797 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
@@ -3650,6 +3650,49 @@ EXPECT_EQ(UseCase::kMainThreadCustomInputHandling, CurrentUseCase()); } +class VeryHighPriorityForCompositingAlternatingExperimentTest + : public MainThreadSchedulerImplTest { + public: + VeryHighPriorityForCompositingAlternatingExperimentTest() + : MainThreadSchedulerImplTest( + {kVeryHighPriorityForCompositingAlternating}, + {}) {} +}; + +INSTANTIATE_TEST_SUITE_P( + , + VeryHighPriorityForCompositingAlternatingExperimentTest, + testing::Values(AntiStarvationLogic::kEnabled, + AntiStarvationLogic::kDisabled), + GetTestNameSuffix); + +TEST_P(VeryHighPriorityForCompositingAlternatingExperimentTest, + TestCompositorPolicy_AlternatingCompositorTasks) { + Vector<String> run_order; + PostTestTasks(&run_order, "D1 D2 D3 C1 C2 C3"); + + EnableIdleTasks(); + base::RunLoop().RunUntilIdle(); + EXPECT_THAT(run_order, + testing::ElementsAre("C1", "D1", "C2", "D2", "C3", "D3")); + EXPECT_EQ(UseCase::kNone, CurrentUseCase()); +} + +TEST_P(VeryHighPriorityForCompositingAlternatingExperimentTest, + TestCompositorPolicy_AlternatingCompositorStaysAtHighest) { + Vector<String> run_order; + PostTestTasks(&run_order, "D1 D2 D3 C1 C2 C3"); + + scheduler_->SetHasVisibleRenderWidgetWithTouchHandler(true); + EnableIdleTasks(); + SimulateMainThreadGestureStart(TouchEventPolicy::kSendTouchStart, + blink::WebInputEvent::kGestureScrollBegin); + base::RunLoop().RunUntilIdle(); + EXPECT_THAT(run_order, + testing::ElementsAre("C1", "C2", "C3", "D1", "D2", "D3")); + EXPECT_EQ(UseCase::kMainThreadCustomInputHandling, CurrentUseCase()); +} + } // namespace main_thread_scheduler_impl_unittest } // namespace scheduler } // namespace blink
diff --git a/third_party/blink/renderer/platform/wtf/vector.h b/third_party/blink/renderer/platform/wtf/vector.h index 0b07e0c..fbe2e3d7 100644 --- a/third_party/blink/renderer/platform/wtf/vector.h +++ b/third_party/blink/renderer/platform/wtf/vector.h
@@ -1176,15 +1176,24 @@ // pointing to an element after |position| will be invalidated. // // insert(position, value) - // Insert a single element at |position|. + // Insert a single element at |position|, where |position| is an index. // insert(position, buffer, size) // InsertVector(position, vector) // Insert multiple elements represented by either |buffer| and |size| // or |vector| at |position|. The elements will be copied. + // InsertAt(position, value) + // Insert a single element at |position|, where |position| is an iterator. + // InsertAt(position, buffer, size) + // Insert multiple elements represented by either |buffer| and |size| + // or |vector| at |position|. The elements will be copied. template <typename U> void insert(wtf_size_t position, U&&); template <typename U> void insert(wtf_size_t position, const U*, wtf_size_t); + template <typename U> + void InsertAt(iterator position, U&&); + template <typename U> + void InsertAt(iterator position, const U*, wtf_size_t); template <typename U, wtf_size_t otherCapacity, typename OtherAllocator> void InsertVector(wtf_size_t position, const Vector<U, otherCapacity, OtherAllocator>&); @@ -1857,6 +1866,20 @@ } template <typename T, wtf_size_t inlineCapacity, typename Allocator> +template <typename U> +void Vector<T, inlineCapacity, Allocator>::InsertAt(T* position, U&& val) { + insert(position - begin(), val); +} + +template <typename T, wtf_size_t inlineCapacity, typename Allocator> +template <typename U> +void Vector<T, inlineCapacity, Allocator>::InsertAt(T* position, + const U* data, + wtf_size_t data_size) { + insert(position - begin(), data, data_size); +} + +template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U, wtf_size_t otherCapacity, typename OtherAllocator> inline void Vector<T, inlineCapacity, Allocator>::InsertVector( wtf_size_t position,
diff --git a/third_party/blink/renderer/platform/wtf/vector_test.cc b/third_party/blink/renderer/platform/wtf/vector_test.cc index 7c36e76f..d3baf39 100644 --- a/third_party/blink/renderer/platform/wtf/vector_test.cc +++ b/third_party/blink/renderer/platform/wtf/vector_test.cc
@@ -27,6 +27,7 @@ #include <memory> #include "base/optional.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -662,6 +663,28 @@ EXPECT_EQ(42, v[2]); } +TEST(VectorTest, IteratorSingleInsertion) { + Vector<int> v; + + v.InsertAt(v.begin(), 1); + EXPECT_EQ(1, v[0]); + + for (int i : {9, 5, 2, 3, 3, 7, 7, 8, 2, 4, 6}) + v.InsertAt(std::lower_bound(v.begin(), v.end(), i), i); + + EXPECT_TRUE(std::is_sorted(v.begin(), v.end())); +} + +TEST(VectorTest, IteratorMultipleInsertion) { + Vector<int> v = {0, 0, 0, 3, 3, 3}; + + Vector<int> q = {1, 1, 1, 1}; + v.InsertAt(std::lower_bound(v.begin(), v.end(), q[0]), &q[0], q.size()); + + EXPECT_THAT(v, testing::ElementsAre(0, 0, 0, 1, 1, 1, 1, 3, 3, 3)); + EXPECT_TRUE(std::is_sorted(v.begin(), v.end())); +} + static_assert(VectorTraits<int>::kCanCopyWithMemcpy, "int should be copied with memcopy."); static_assert(VectorTraits<char>::kCanCopyWithMemcpy,
diff --git a/third_party/blink/tools/apache_config/mime.types b/third_party/blink/tools/apache_config/mime.types index 5c11e53..d319f04 100644 --- a/third_party/blink/tools/apache_config/mime.types +++ b/third_party/blink/tools/apache_config/mime.types
@@ -357,7 +357,7 @@ application/x-gtar gtar application/x-gzip application/x-hdf hdf -application/x-javascript js +application/x-javascript js mjs application/x-java-jnlp-file jnlp application/x-koan skp skd skt skm application/x-latex latex
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py index d82a12ee..721d8ee 100755 --- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py +++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -404,8 +404,10 @@ 'disallowed': [ ('base::Bind(|Once|Repeating)', 'Use WTF::Bind or WTF::BindRepeating.'), - ('std::(deque|map|set|vector)', - 'Use WTF containers like WTF::Deque, WTF::HashMap, WTF::HashSet or WTF::Vector instead of the banned std containers.'), + ('std::(deque|map|set|vector|unordered_set|unordered_map)', + 'Use WTF containers like WTF::Deque, WTF::HashMap, WTF::HashSet or WTF::Vector instead of the banned std containers. ' + 'However, it is fine to use std containers at the boundary layer between Blink and Chromium. ' + 'If you are in this case, you can use --bypass-hooks option to avoid the presubmit check when uploading your CL.'), ], }, { @@ -485,6 +487,13 @@ ], }, { + 'paths': ['third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.cc'], + 'allowed': [ + # Used by SignedExchangeRequestMatcher in //third_party/blink/common. + 'net::HttpRequestHeaders', + ], + }, + { 'paths': ['third_party/blink/renderer/core/paint'], 'allowed': [ # cc painting types. @@ -772,6 +781,10 @@ 'base::NullableString16', 'net::ParseMimeTypeWithoutParameter', ], + }, + { + 'paths': ['third_party/blink/renderer/core/fetch/fetch_request_data.cc'], + 'allowed': ['net::RequestPriority'], } ]
diff --git a/third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wptserve/wptserve/constants.py b/third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wptserve/wptserve/constants.py index e248280e..357a2e6d 100644 --- a/third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wptserve/wptserve/constants.py +++ b/third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wptserve/wptserve/constants.py
@@ -20,7 +20,7 @@ "text/css": ["css"], "text/event-stream": ["event_stream"], "text/html": ["htm", "html"], - "text/javascript": ["js"], + "text/javascript": ["js", "mjs"], "text/plain": ["txt", "md"], "text/vtt": ["vtt"], "video/mp4": ["mp4", "m4v"],
diff --git a/third_party/blink/tools/blinkpy/web_tests/servers/apache_http.py b/third_party/blink/tools/blinkpy/web_tests/servers/apache_http.py index 0a53250..75ca351 100644 --- a/third_party/blink/tools/blinkpy/web_tests/servers/apache_http.py +++ b/third_party/blink/tools/blinkpy/web_tests/servers/apache_http.py
@@ -91,6 +91,7 @@ '-c', 'Alias /webaudio-resources "%s"' % webaudio_resources_dir, '-c', 'Alias /inspector-sources "%s"' % inspector_sources_dir, '-c', 'Alias /gen "%s"' % generated_sources_dir, + '-c', 'Alias /wpt_internal "%s/wpt_internal"' % test_dir, '-c', 'TypesConfig "%s"' % mime_types_path, '-c', 'CustomLog "%s" common' % self._access_log_path, '-c', 'ErrorLog "%s"' % self._error_log_path,
diff --git a/third_party/blink/web_tests/MSANExpectations b/third_party/blink/web_tests/MSANExpectations index 62765e2..9eeec3c 100644 --- a/third_party/blink/web_tests/MSANExpectations +++ b/third_party/blink/web_tests/MSANExpectations
@@ -303,3 +303,6 @@ crbug.com/856601 [ Linux ] http/tests/devtools/indexeddb/live-update-indexeddb-content.js [ Pass Timeout ] crbug.com/856601 [ Linux ] http/tests/devtools/indexeddb/live-update-indexeddb-list.js [ Pass Timeout ] crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/interfaces-sw.https.html [ Pass Timeout ] + +# Sheriff 2019-07-11 +crbug.com/856601 [ Linux ] virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/interfaces-sw.https.html [ Pass Timeout ]
diff --git a/third_party/blink/web_tests/NeverFixTests b/third_party/blink/web_tests/NeverFixTests index da96ebf..d35050ff 100644 --- a/third_party/blink/web_tests/NeverFixTests +++ b/third_party/blink/web_tests/NeverFixTests
@@ -2145,6 +2145,9 @@ virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html [ WontFix ] virtual/not-omt-sw-fetch/external/wpt/xhr/send-authentication-existing-session-manual.htm [ WontFix ] virtual/not-omt-sw-fetch/external/wpt/xhr/send-authentication-prompt-2-manual.htm [ WontFix ] +virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-event-is-history-backward-navigation-manual.https.html [ WontFix ] +virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-event-is-history-forward-navigation-manual.https.html [ WontFix ] +virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html [ WontFix ] virtual/speech-with-unified-autoplay/external/wpt/speech-api/SpeechRecognition-abort-manual.https.html [ WontFix ] virtual/speech-with-unified-autoplay/external/wpt/speech-api/SpeechRecognition-onerror-manual.https.html [ WontFix ] virtual/speech-with-unified-autoplay/external/wpt/speech-api/SpeechRecognition-onresult-manual.https.html [ WontFix ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 099634c..e60318e 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -3066,6 +3066,7 @@ crbug.com/832071 virtual/blink-cors/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] crbug.com/832071 virtual/navigation-mojo-response/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] crbug.com/832071 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] +crbug.com/832071 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ] # failures in external/wpt/css/css-animations/ and web-animations/ from Mozilla tests crbug.com/849859 external/wpt/css/css-animations/CSSAnimation-pausing.tentative.html [ Failure ] @@ -3474,6 +3475,7 @@ crbug.com/626703 virtual/blink-cors/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ] crbug.com/626703 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ] crbug.com/626703 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ] +crbug.com/626703 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ] crbug.com/626703 [ Linux ] external/wpt/css/css-fonts/math-script-level-and-math-style/math-script-level-auto-and-math-style-002.tentative.html [ Failure ] crbug.com/626703 [ Mac ] external/wpt/css/css-fonts/math-script-level-and-math-style/math-script-level-auto-and-math-style-002.tentative.html [ Failure ] crbug.com/626703 [ Win ] external/wpt/css/css-fonts/math-script-level-and-math-style/math-script-level-auto-and-math-style-002.tentative.html [ Failure ] @@ -4307,6 +4309,7 @@ crbug.com/648295 virtual/blink-cors/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] crbug.com/648295 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] crbug.com/648295 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] +crbug.com/648295 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] crbug.com/626703 external/wpt/svg/linking/reftests/href-filter-element.html [ Failure ] crbug.com/626703 external/wpt/webvtt/rendering/cues-with-video/processing-model/2_cues_overlapping_completely_move_up.html [ Failure ] crbug.com/626703 external/wpt/webvtt/rendering/cues-with-video/processing-model/2_cues_overlapping_partially_move_down.html [ Failure ] @@ -4715,12 +4718,14 @@ crbug.com/691944 virtual/blink-cors/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] crbug.com/691944 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] crbug.com/691944 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] +crbug.com/691944 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] # These tests (erroneously) see a platform-specific User-Agent header crbug.com/595993 external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] crbug.com/595993 virtual/blink-cors/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] crbug.com/595993 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] crbug.com/595993 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] +crbug.com/595993 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] crbug.com/619427 [ Mac ] fast/overflow/overflow-height-float-not-removed-crash3.html [ Pass Failure ] @@ -5164,10 +5169,6 @@ crbug.com/783301 external/wpt/imagecapture/MediaStreamTrack-getSettings.html [ Pass Failure ] crbug.com/783301 external/wpt/imagecapture/MediaStreamTrack-getCapabilities.html [ Pass Failure ] -# Cookie Store API -crbug.com/827231 external/wpt/cookie-store/document_cookie.tentative.html [ Pass Failure ] -crbug.com/827231 external/wpt/cookie-store/document_cookie.tentative.https.html [ Pass Failure ] - # Failing SameSite cookies tests crbug.com/843945 external/wpt/cookies/samesite/form-get-blank-reload.html [ Failure ] crbug.com/843945 external/wpt/cookies/samesite/form-post-blank-reload.html [ Failure ] @@ -5862,6 +5863,7 @@ crbug.com/933880 virtual/blink-cors/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] crbug.com/933880 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] crbug.com/933880 virtual/not-omt-sw-fetch/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] +crbug.com/933880 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] crbug.com/933880 http/tests/inspector-protocol/network/interception-take-stream.js [ Failure ] crbug.com/933880 http/tests/inspector-protocol/network/xhr-interception-auth-fail.js [ Failure ] # This passes in content_shell but not in chrome with network service disabled, @@ -6250,5 +6252,16 @@ crbug.com/982289 virtual/gpu-rasterization/images/ycbcr-with-cmyk-color-profile.html [ Pass Failure ] crbug.com/982289 virtual/gpu-rasterization/images/color-profile-image.html [ Pass Failure ] -# Sheriff 2019-07-09 -crbug.com/966249 [ Mac ] external/wpt/css/css-fonts/inheritance.html [ Pass Failure ] +# Sheriff 2019-07-11 +crbug.com/982290 [ Win ] http/tests/devtools/elements/styles-4/styles-do-not-detach-sourcemap-on-edits.js [ Pass Timeout ] + +crbug.com/970079 external/wpt/animation-worklet/stateful-animator.https.html [ Pass Timeout ] +crbug.com/970079 external/wpt/html/browsers/history/the-history-interface/001.html [ Pass Failure ] +crbug.com/970079 external/wpt/html/browsers/history/the-history-interface/002.html [ Pass Failure ] +crbug.com/970079 fast/dom/Window/window-postmessage-clone.html [ Pass Failure ] +crbug.com/970079 fast/events/message-port-multi.html [ Pass Failure ] +crbug.com/970079 storage/indexeddb/structured-clone.html [ Pass Failure ] +crbug.com/970079 virtual/mouseevent_fractional/fast/events/message-port-multi.html [ Pass Failure ] +crbug.com/970079 virtual/threaded/external/wpt/animation-worklet/stateful-animator.https.html [ Pass Timeout ] +crbug.com/970079 external/wpt/html/infrastructure/safe-passing-of-structured-data/structuredclone_0.html [ Pass Failure ] +crbug.com/970079 external/wpt/html/infrastructure/safe-passing-of-structured-data/structured-cloning-error-stack-optional.sub.window.html [ Pass Failure ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index b14a2ae..1c7f08e 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -1136,5 +1136,10 @@ "prefix": "at-property", "base": "external/wpt/css/css-properties-values-api", "args": ["--enable-blink-features=CSSVariables2AtProperty"] + }, + { + "prefix": "cache-storage-sequence", + "base": "external/wpt/service-workers", + "args": ["--enable-features=CacheStorageSequence"] } ]
diff --git a/third_party/blink/web_tests/external/wpt/clipboard-apis/async-write-image-read-image-manual.https.html b/third_party/blink/web_tests/external/wpt/clipboard-apis/async-write-image-read-image-manual.https.html index 351e74b..ad1dc4f 100644 --- a/third_party/blink/web_tests/external/wpt/clipboard-apis/async-write-image-read-image-manual.https.html +++ b/third_party/blink/web_tests/external/wpt/clipboard-apis/async-write-image-read-image-manual.https.html
@@ -61,6 +61,14 @@ assert_equals(comparableOutput, comparableInput); }, 'Verify write and read clipboard [image/png Blob]'); + +promise_test(async t => { + const invalidPngBlob = new Blob(['this text is not a valid png image'], + {type: "image/png"}); + const clipboardItemInput = new ClipboardItem({'image/png' : invalidPngBlob}); + await promise_rejects(t, "DataError", + navigator.clipboard.write([clipboardItemInput])); +}, 'Verify write error on malformed data [image/png ClipboardItem]'); </script> <p> Note: This is a manual test because it writes/reads to the shared system
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-content-invalid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-content-invalid.html new file mode 100644 index 0000000..ae24438 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-content-invalid.html
@@ -0,0 +1,35 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing align-content with invalid values</title> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#propdef-align-content"> +<meta name="assert" content="align-content supports only the grammar 'normal | <baseline-position> | <content-distribution> | <overflow-position>? <content-position>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_invalid_value("align-content", "auto"); +test_invalid_value("align-content", "baseline last"); +test_invalid_value("align-content", "center baseline"); +test_invalid_value("align-content", "first"); +test_invalid_value("align-content", "flex-start flex-end"); +test_invalid_value("align-content", "last"); +test_invalid_value("align-content", "left"); +test_invalid_value("align-content", "legacy center"); +test_invalid_value("align-content", "legacy left"); +test_invalid_value("align-content", "legacy"); +test_invalid_value("align-content", "normal baseline"); +test_invalid_value("align-content", "right legacy"); +test_invalid_value("align-content", "safe self-end"); +test_invalid_value("align-content", "safe"); +test_invalid_value("align-content", "self-end unsafe"); +test_invalid_value("align-content", "self-start"); +test_invalid_value("align-content", "start safe"); +test_invalid_value("align-content", "unsafe right"); +test_invalid_value("align-content", "unsafe"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-content-valid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-content-valid.html new file mode 100644 index 0000000..46c4724 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-content-valid.html
@@ -0,0 +1,39 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing align-content with valid values</title> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#propdef-align-content"> +<meta name="assert" content="align-content supports the full grammar 'normal | <baseline-position> | <content-distribution> | <overflow-position>? <content-position>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_valid_value("align-content", "normal"); + +// <baseline-position> = [ first | last ]? baseline +test_valid_value("align-content", "baseline"); +test_valid_value("align-content", "first baseline", "baseline"); +test_valid_value("align-content", "last baseline"); + +// <content-distribution> = space-between | space-around | space-evenly | stretch +test_valid_value("align-content", "space-between"); +test_valid_value("align-content", "space-around"); +test_valid_value("align-content", "space-evenly"); +test_valid_value("align-content", "stretch"); + +// <overflow-position>? <content-position> +// <overflow-position> = unsafe | safe +// <content-position> = center | start | end | flex-start | flex-end +test_valid_value("align-content", "center"); +test_valid_value("align-content", "start"); +test_valid_value("align-content", "end"); +test_valid_value("align-content", "flex-start"); +test_valid_value("align-content", "flex-end"); +test_valid_value("align-content", "unsafe end"); +test_valid_value("align-content", "safe flex-start"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-items-invalid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-items-invalid.html new file mode 100644 index 0000000..8e329d50 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-items-invalid.html
@@ -0,0 +1,36 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing align-items with invalid values</title> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#propdef-align-items"> +<meta name="assert" content="align-items supports only the grammar 'normal | stretch | <baseline-position> | [ <overflow-position>? <self-position> ]'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_invalid_value("align-items", "auto"); +test_invalid_value("align-items", "baseline last"); +test_invalid_value("align-items", "center baseline"); +test_invalid_value("align-items", "first"); +test_invalid_value("align-items", "flex-start flex-end"); +test_invalid_value("align-items", "last"); +test_invalid_value("align-items", "left"); +test_invalid_value("align-items", "legacy center"); +test_invalid_value("align-items", "legacy left"); +test_invalid_value("align-items", "legacy"); +test_invalid_value("align-items", "normal baseline"); +test_invalid_value("align-items", "right legacy"); +test_invalid_value("align-items", "safe"); +test_invalid_value("align-items", "self-end unsafe"); +test_invalid_value("align-items", "space-around"); +test_invalid_value("align-items", "space-between"); +test_invalid_value("align-items", "space-evenly"); +test_invalid_value("align-items", "start safe"); +test_invalid_value("align-items", "unsafe right"); +test_invalid_value("align-items", "unsafe"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-items-valid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-items-valid.html new file mode 100644 index 0000000..e88845b9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-items-valid.html
@@ -0,0 +1,36 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing align-items with valid values</title> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#propdef-align-items"> +<meta name="assert" content="align-items supports the full grammar 'normal | stretch | <baseline-position> | [ <overflow-position>? <self-position> ]'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_valid_value("align-items", "normal"); +test_valid_value("align-items", "stretch"); + +// <baseline-position> = [ first | last ]? baseline +test_valid_value("align-items", "baseline"); +test_valid_value("align-items", "first baseline", "baseline"); +test_valid_value("align-items", "last baseline"); + +// <overflow-position>? <self-position> +// <overflow-position> = unsafe | safe +// <self-position> = center | start | end | self-start | self-end | flex-start | flex-end +test_valid_value("align-items", "center"); +test_valid_value("align-items", "start"); +test_valid_value("align-items", "end"); +test_valid_value("align-items", "self-start"); +test_valid_value("align-items", "self-end"); +test_valid_value("align-items", "flex-start"); +test_valid_value("align-items", "flex-end"); +test_valid_value("align-items", "unsafe center"); +test_valid_value("align-items", "safe self-end"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-self-invalid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-self-invalid.html new file mode 100644 index 0000000..27b0250 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-self-invalid.html
@@ -0,0 +1,35 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing align-self with invalid values</title> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#propdef-align-self"> +<meta name="assert" content="align-self supports only the grammar 'auto | normal | stretch | <baseline-position> | <overflow-position>? <self-position>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_invalid_value("align-self", "baseline last"); +test_invalid_value("align-self", "center baseline"); +test_invalid_value("align-self", "first"); +test_invalid_value("align-self", "flex-start flex-end"); +test_invalid_value("align-self", "last"); +test_invalid_value("align-self", "left"); +test_invalid_value("align-self", "legacy center"); +test_invalid_value("align-self", "legacy left"); +test_invalid_value("align-self", "legacy"); +test_invalid_value("align-self", "normal baseline"); +test_invalid_value("align-self", "right legacy"); +test_invalid_value("align-self", "safe"); +test_invalid_value("align-self", "self-end unsafe"); +test_invalid_value("align-self", "space-around"); +test_invalid_value("align-self", "space-between"); +test_invalid_value("align-self", "space-evenly"); +test_invalid_value("align-self", "start safe"); +test_invalid_value("align-self", "unsafe right"); +test_invalid_value("align-self", "unsafe"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-self-valid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-self-valid.html new file mode 100644 index 0000000..25ea093 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/align-self-valid.html
@@ -0,0 +1,37 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing align-self with valid values</title> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#propdef-align-self"> +<meta name="assert" content="align-self supports the full grammar 'auto | normal | stretch | <baseline-position> | <overflow-position>? <self-position>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_valid_value("align-self", "auto"); +test_valid_value("align-self", "normal"); +test_valid_value("align-self", "stretch"); + +// <baseline-position> = [ first | last ]? baseline +test_valid_value("align-self", "baseline"); +test_valid_value("align-self", "first baseline", "baseline"); +test_valid_value("align-self", "last baseline"); + +// <overflow-position>? <self-position> +// <overflow-position> = unsafe | safe +// <self-position> = center | start | end | self-start | self-end | flex-start | flex-end +test_valid_value("align-self", "center"); +test_valid_value("align-self", "start"); +test_valid_value("align-self", "end"); +test_valid_value("align-self", "self-start"); +test_valid_value("align-self", "self-end"); +test_valid_value("align-self", "flex-start"); +test_valid_value("align-self", "flex-end"); +test_valid_value("align-self", "unsafe center"); +test_valid_value("align-self", "safe self-end"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-content-invalid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-content-invalid.html new file mode 100644 index 0000000..971f94b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-content-invalid.html
@@ -0,0 +1,36 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing justify-content with invalid values</title> +<link rel="help" href="https://drafts.csswg.org/css-justify-3/#propdef-justify-content"> +<meta name="assert" content="justify-content supports only the grammar 'normal | <content-distribution> | <overflow-position>? [ <content-position> | left | right ]'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_invalid_value("justify-content", "auto"); +test_invalid_value("justify-content", "baseline last"); +test_invalid_value("justify-content", "baseline"); +test_invalid_value("justify-content", "center baseline"); +test_invalid_value("justify-content", "first baseline"); +test_invalid_value("justify-content", "first"); +test_invalid_value("justify-content", "flex-start flex-end"); +test_invalid_value("justify-content", "last baseline"); +test_invalid_value("justify-content", "last"); +test_invalid_value("justify-content", "legacy center"); +test_invalid_value("justify-content", "legacy left"); +test_invalid_value("justify-content", "legacy"); +test_invalid_value("justify-content", "normal baseline"); +test_invalid_value("justify-content", "right legacy"); +test_invalid_value("justify-content", "safe self-end"); +test_invalid_value("justify-content", "safe"); +test_invalid_value("justify-content", "self-end unsafe"); +test_invalid_value("justify-content", "self-start"); +test_invalid_value("justify-content", "start safe"); +test_invalid_value("justify-content", "unsafe"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-content-valid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-content-valid.html new file mode 100644 index 0000000..d476a268 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-content-valid.html
@@ -0,0 +1,36 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing justify-content with valid values</title> +<link rel="help" href="https://drafts.csswg.org/css-justify-3/#propdef-justify-content"> +<meta name="assert" content="justify-content supports the full grammar 'normal | <content-distribution> | <overflow-position>? [ <content-position> | left | right ]'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_valid_value("justify-content", "normal"); + +// <content-distribution> = space-between | space-around | space-evenly | stretch +test_valid_value("justify-content", "space-between"); +test_valid_value("justify-content", "space-around"); +test_valid_value("justify-content", "space-evenly"); +test_valid_value("justify-content", "stretch"); + +// <overflow-position>? [ <content-position> | left | right ] +// <overflow-position> = unsafe | safe +// <content-position> = center | start | end | flex-start | flex-end +test_valid_value("justify-content", "center"); +test_valid_value("justify-content", "start"); +test_valid_value("justify-content", "end"); +test_valid_value("justify-content", "flex-start"); +test_valid_value("justify-content", "flex-end"); +test_valid_value("justify-content", "unsafe end"); +test_valid_value("justify-content", "safe flex-start"); +test_valid_value("justify-content", "left"); +test_valid_value("justify-content", "unsafe right"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-items-invalid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-items-invalid.html new file mode 100644 index 0000000..18da059 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-items-invalid.html
@@ -0,0 +1,30 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing justify-items with invalid values</title> +<link rel="help" href="https://drafts.csswg.org/css-justify-3/#propdef-justify-items"> +<meta name="assert" content="justify-items supports only the grammar 'normal | stretch | <baseline-position> | <overflow-position>? [ <self-position> | left | right ] | legacy | legacy && [ left | right | center ]'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_invalid_value("justify-items", "auto"); +test_invalid_value("justify-items", "baseline last"); +test_invalid_value("justify-items", "center baseline"); +test_invalid_value("justify-items", "first"); +test_invalid_value("justify-items", "flex-start flex-end"); +test_invalid_value("justify-items", "last"); +test_invalid_value("justify-items", "normal baseline"); +test_invalid_value("justify-items", "safe"); +test_invalid_value("justify-items", "self-end unsafe"); +test_invalid_value("justify-items", "space-around"); +test_invalid_value("justify-items", "space-between"); +test_invalid_value("justify-items", "space-evenly"); +test_invalid_value("justify-items", "start safe"); +test_invalid_value("justify-items", "unsafe"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-items-valid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-items-valid.html new file mode 100644 index 0000000..36584f86 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-items-valid.html
@@ -0,0 +1,44 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing justify-items with valid values</title> +<link rel="help" href="https://drafts.csswg.org/css-justify-3/#propdef-justify-items"> +<meta name="assert" content="justify-items supports the full grammar 'normal | stretch | <baseline-position> | <overflow-position>? [ <self-position> | left | right ] | legacy | legacy && [ left | right | center ]'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_valid_value("justify-items", "normal"); +test_valid_value("justify-items", "stretch"); + +// <baseline-position> = [ first | last ]? baseline +test_valid_value("justify-items", "baseline"); +test_valid_value("justify-items", "first baseline", "baseline"); +test_valid_value("justify-items", "last baseline"); + +// <overflow-position>? [ <self-position> | left | right ] +// <overflow-position> = unsafe | safe +// <self-position> = center | start | end | self-start | self-end | flex-start | flex-end +test_valid_value("justify-items", "center"); +test_valid_value("justify-items", "start"); +test_valid_value("justify-items", "end"); +test_valid_value("justify-items", "self-start"); +test_valid_value("justify-items", "self-end"); +test_valid_value("justify-items", "flex-start"); +test_valid_value("justify-items", "flex-end"); +test_valid_value("justify-items", "unsafe center"); +test_valid_value("justify-items", "safe self-end"); +test_valid_value("justify-items", "right"); +test_valid_value("justify-items", "safe left"); + +// legacy | legacy && [ left | right | center ] +test_valid_value("justify-items", "legacy"); +test_valid_value("justify-items", "left legacy", "legacy left"); +test_valid_value("justify-items", "right legacy", "legacy right"); +test_valid_value("justify-items", "center legacy", "legacy center"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-self-invalid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-self-invalid.html new file mode 100644 index 0000000..846cdd8a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-self-invalid.html
@@ -0,0 +1,33 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing justify-self with invalid values</title> +<link rel="help" href="https://drafts.csswg.org/css-justify-3/#propdef-justify-self"> +<meta name="assert" content="justify-self supports only the grammar 'auto | normal | stretch | <baseline-position> | <overflow-position>? [ <self-position> | left | right ]'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_invalid_value("justify-self", "baseline last"); +test_invalid_value("justify-self", "center baseline"); +test_invalid_value("justify-self", "first"); +test_invalid_value("justify-self", "flex-start flex-end"); +test_invalid_value("justify-self", "last"); +test_invalid_value("justify-self", "legacy center"); +test_invalid_value("justify-self", "legacy left"); +test_invalid_value("justify-self", "legacy"); +test_invalid_value("justify-self", "normal baseline"); +test_invalid_value("justify-self", "right legacy"); +test_invalid_value("justify-self", "safe"); +test_invalid_value("justify-self", "self-end unsafe"); +test_invalid_value("justify-self", "space-around"); +test_invalid_value("justify-self", "space-between"); +test_invalid_value("justify-self", "space-evenly"); +test_invalid_value("justify-self", "start safe"); +test_invalid_value("justify-self", "unsafe"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-self-valid.html b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-self-valid.html new file mode 100644 index 0000000..1ee23af --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-align/parsing/justify-self-valid.html
@@ -0,0 +1,39 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Box Alignment Level 3: parsing justify-self with valid values</title> +<link rel="help" href="https://drafts.csswg.org/css-justify-3/#propdef-justify-self"> +<meta name="assert" content="justify-self supports the full grammar 'auto | normal | stretch | <baseline-position> | <overflow-position>? [ <self-position> | left | right ]'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_valid_value("justify-self", "auto"); +test_valid_value("justify-self", "normal"); +test_valid_value("justify-self", "stretch"); + +// <baseline-position> = [ first | last ]? baseline +test_valid_value("justify-self", "baseline"); +test_valid_value("justify-self", "first baseline", "baseline"); +test_valid_value("justify-self", "last baseline"); + +// <overflow-position>? [ <self-position> | left | right ] +// <overflow-position> = unsafe | safe +// <self-position> = center | start | end | self-start | self-end | flex-start | flex-end +test_valid_value("justify-self", "center"); +test_valid_value("justify-self", "start"); +test_valid_value("justify-self", "end"); +test_valid_value("justify-self", "self-start"); +test_valid_value("justify-self", "self-end"); +test_valid_value("justify-self", "flex-start"); +test_valid_value("justify-self", "flex-end"); +test_valid_value("justify-self", "unsafe center"); +test_valid_value("justify-self", "safe self-end"); +test_valid_value("justify-self", "left"); +test_valid_value("justify-self", "unsafe right"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-fonts/inheritance-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-fonts/inheritance-expected.txt index 069790b..7bd35fd 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-fonts/inheritance-expected.txt +++ b/third_party/blink/web_tests/external/wpt/css/css-fonts/inheritance-expected.txt
@@ -1,5 +1,4 @@ This is a testharness.js-based test. -PASS Property font-family has initial value "times new roman" PASS Property font-family inherits PASS Property font-feature-settings has initial value normal PASS Property font-feature-settings inherits
diff --git a/third_party/blink/web_tests/external/wpt/css/css-fonts/inheritance.html b/third_party/blink/web_tests/external/wpt/css/css-fonts/inheritance.html index 8ff02fb..f0c46be 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-fonts/inheritance.html +++ b/third_party/blink/web_tests/external/wpt/css/css-fonts/inheritance.html
@@ -12,7 +12,6 @@ <script src="/css/support/inheritance-testcommon.js"></script> <style> #box { - font: initial; font-size: medium; } </style> @@ -25,10 +24,9 @@ <script> 'use strict'; const box = document.getElementById('box'); -const initialFontFamily = getComputedStyle(box).fontFamily; const mediumFontSize = getComputedStyle(box).fontSize; -assert_inherited('font-family', initialFontFamily, '"Not Initial!"'); +assert_inherited('font-family', null, '"Not Initial!"'); // Initial value depends on user agent. assert_inherited('font-feature-settings', 'normal', '"smcp", "swsh" 2'); assert_inherited('font-kerning', 'auto', 'none'); assert_inherited('font-size', mediumFontSize /* medium */, '123px');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-013.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-013.html new file mode 100644 index 0000000..59541dd6 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-013.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<link rel="help" href="https://crbug.com/982403" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square.xht"> +<meta name="assert" content="Tests the static position of an inline-level absolute-positioned element." /> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div style="overflow: hidden;"> + <div style="float: left; width: 100px; height: 50px; background: green;"></div> + <div style="clear: both; width: 100px; height: 50px; background: red;"> + <div style="position: absolute; display: inline; width: 100px; height: 50px; background: green;"></div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-014.html b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-014.html new file mode 100644 index 0000000..69416c1c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-position/static-position/inline-level-absolute-in-block-level-context-014.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<link rel="help" href="https://crbug.com/982403" /> +<link rel="match" href="../../reference/ref-filled-green-100px-square.xht"> +<meta name="assert" content="Tests the static position of an inline-level absolute-positioned element." /> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div style="overflow: hidden;"> + <div style="float: left; width: 100px; height: 50px; background: green;"></div> + <div style="clear: both; width: 100px; height: 50px; background: red;"> + <div></div> + <div style="position: absolute; display: inline; width: 100px; height: 50px; background: green;"></div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/support/inheritance-testcommon.js b/third_party/blink/web_tests/external/wpt/css/support/inheritance-testcommon.js index 8d1645f9..38ac94eb 100644 --- a/third_party/blink/web_tests/external/wpt/css/support/inheritance-testcommon.js +++ b/third_party/blink/web_tests/external/wpt/css/support/inheritance-testcommon.js
@@ -33,7 +33,8 @@ * value. */ function assert_inherited(property, initial, other) { - assert_initial(property, initial); + if (initial) + assert_initial(property, initial); test(() => { const container = document.getElementById('container');
diff --git a/third_party/blink/web_tests/external/wpt/resources/chromium/webxr-test.js b/third_party/blink/web_tests/external/wpt/resources/chromium/webxr-test.js index 261e1cf..8257fbdc 100644 --- a/third_party/blink/web_tests/external/wpt/resources/chromium/webxr-test.js +++ b/third_party/blink/web_tests/external/wpt/resources/chromium/webxr-test.js
@@ -82,6 +82,17 @@ this.runtimes_ = []; } + removeRuntime(device) { + let index = this.runtimes_.indexOf(device); + if (index >= 0) { + this.runtimes_.splice(index, 1); + if (this.client_) { + console.error("Notifying client"); + this.client_.onDeviceChanged(); + } + } + } + // VRService implementation. requestDevice() { if (this.runtimes_.length > 0) { @@ -194,6 +205,16 @@ } // Test API methods. + disconnect() { + this.service_.removeRuntime(this); + this.presentation_provider_.Close(); + if (this.sessionClient_.ptr.isBound()) { + this.sessionClient_.ptr.reset(); + } + + return Promise.resolve(); + } + setViews(views) { if (views) { let changed = false; @@ -537,6 +558,11 @@ this.submitFrameClient_.onSubmitFrameTransferred(true); this.submitFrameClient_.onSubmitFrameRendered(); } + + // Utility methods + Close() { + this.binding_.close(); + } } // This is a temporary workaround for the fact that spinning up webxr before
diff --git a/third_party/blink/web_tests/external/wpt/std-toast/actions.html b/third_party/blink/web_tests/external/wpt/std-toast/actions.html index be453d5..018ce21 100644 --- a/third_party/blink/web_tests/external/wpt/std-toast/actions.html +++ b/third_party/blink/web_tests/external/wpt/std-toast/actions.html
@@ -8,7 +8,8 @@ <main></main> <script type="module"> -import { testActionToast, testToastElement } from './resources/helpers.js'; +import { testActionToast, testToastElement, assertActionButtonOnToast } from './resources/helpers.js'; +import { showToast } from 'std:elements/toast'; testActionToast((toast) => { assert_equals(toast.action.textContent, 'action'); @@ -28,5 +29,77 @@ <button slot="action" id="second">second</button>`; assert_equals(toast.action, toast.querySelector('#first')); -}) +}, 'toast action returns the first item with the action slot'); + +test(() => { + const toast = showToast('Message', {action: 'action'}); + const actionButton = toast.querySelector('button'); + + assertActionButtonOnToast(actionButton, toast); +}, 'passing an action via showToast creates a button'); + +test(() => { + const actionMarkup = '<b>strong text</b>'; + const toast = showToast('Message', {action: actionMarkup}); + const actionButton = toast.querySelector('button'); + + assert_equals(actionButton.textContent, actionMarkup); + assert_equals(toast.querySelector('b'), null); +}, 'passing markup to the action option represents as text'); + +test(() => { + const toast = document.createElement('std-toast'); + toast.textContent = 'Message'; + toast.show({action: 'action'}); + const actionButton = toast.querySelector('button'); + + assert_equals(actionButton, null); +}, 'passing action option to show does not create a button'); + +test(() => { + const toast = showToast('Message', {action: null}); + const actionButton = toast.querySelector('button'); + + assertActionButtonOnToast(actionButton, toast); + assert_equals(actionButton.textContent, 'null'); +}, 'passing non-string (null) as action option stringifies it and creates an action button'); + +test(() => { + const toast = showToast('Message', {action: false}); + const actionButton = toast.querySelector('button'); + + assertActionButtonOnToast(actionButton, toast); + assert_equals(actionButton.textContent, 'false'); +}, 'passing non-string (false) as action option stringifies it and creates an action button'); + +test(() => { + const toast = showToast('Message', {action: 0}); + const actionButton = toast.querySelector('button'); + + assertActionButtonOnToast(actionButton, toast); + assert_equals(actionButton.textContent, '0'); +}, 'passing non-string (0) as action option stringifies it and creates an action button'); + +test(() => { + const toast = showToast('Message', {action: 1}); + const actionButton = toast.querySelector('button'); + + assertActionButtonOnToast(actionButton, toast); + assert_equals(actionButton.textContent, '1'); +}, 'passing non-string (1) as action option stringifies it and creates an action button'); + +test(() => { + const toast = showToast('Message', {action: {field: 'value'}}); + const actionButton = toast.querySelector('button'); + + assertActionButtonOnToast(actionButton, toast); + assert_equals(actionButton.textContent, '[object Object]'); +}, 'passing non-string ({field: value}) as action option stringifies it and creates an action button'); + +test(() => { + const toast = showToast('Message', {}); + const actionButton = toast.querySelector('button'); + + assert_equals(actionButton, null); +}, 'passing non-string (undefined) as action option does not create an action button'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/std-toast/resources/helpers.js b/third_party/blink/web_tests/external/wpt/std-toast/resources/helpers.js index e1b55f4..62deb42 100644 --- a/third_party/blink/web_tests/external/wpt/std-toast/resources/helpers.js +++ b/third_party/blink/web_tests/external/wpt/std-toast/resources/helpers.js
@@ -64,6 +64,12 @@ assert_false(toast.open); }; +export const assertActionButtonOnToast = (action, toast) => { + assert_equals(toast.action, action); + assert_equals(action.getAttribute('slot'), 'action'); + assert_equals(action, toast.querySelector('button')); +}; + export class EventCollector { events = [];
diff --git a/third_party/blink/web_tests/external/wpt/user-timing/measure-with-dict.html b/third_party/blink/web_tests/external/wpt/user-timing/measure-with-dict.html index cdcc0ff..8ba7b9f 100644 --- a/third_party/blink/web_tests/external/wpt/user-timing/measure-with-dict.html +++ b/third_party/blink/web_tests/external/wpt/user-timing/measure-with-dict.html
@@ -96,10 +96,16 @@ test(function() { this.add_cleanup(cleanupPerformanceTimeline); assert_throws(new TypeError(), function() { - self.performance.measure("wrongUsage2", {'start': 2}, 12); + self.performance.measure("optionsAndNumberEnd", {'start': 2}, 12); }, "measure should throw a TypeError when passed an options object and an end time"); assert_throws(new TypeError(), function() { - self.performance.measure("wrongUsage3", {'start': 2}, 'mark1'); + self.performance.measure("optionsAndMarkEnd", {'start': 2}, 'mark1'); }, "measure should throw a TypeError when passed an options object and an end mark"); + assert_throws(new TypeError(), function() { + self.performance.measure("negativeStartInOptions", {'start': -1}); + }, "measure cannot have a negative time stamp."); + assert_throws(new TypeError(), function() { + self.performance.measure("negativeEndInOptions", {'end': -1}); + }, "measure cannot have a negative time stamp for end."); }, "measure should throw a TypeError when passed an invalid argument combination"); </script>
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-onicecandidateerror.html b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-onicecandidateerror.html new file mode 100644 index 0000000..e06c219 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-onicecandidateerror.html
@@ -0,0 +1,31 @@ +<!doctype html> +<meta charset=utf-8> +<title>RTCPeerConnection.prototype.onicecandidateerror</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="RTCPeerConnection-helper.js"></script> +<script> + +promise_test(async t => { + const config = { + iceServers: [{urls: "turn:123", username: "123", credential: "123"}] + }; + const pc = new RTCPeerConnection(config); + t.add_cleanup(() => pc.close()); + const onErrorPromise = addEventListenerPromise(t, pc, 'icecandidateerror', event => { + assert_true(event instanceof RTCPeerConnectionIceErrorEvent, + 'Expect event to be instance of RTCPeerConnectionIceErrorEvent'); + // Do not hardcode any specific errors here. Instead only verify + // that all the fields contain something expected. + // Testing of event.errorText can be added later once it's content is + // specified in spec with more detail. + assert_true(event.errorCode >= 300 && event.errorCode <= 799, "errorCode"); + assert_true(event.hostCandidate.includes(":"), "hostCandidate"); + assert_true(event.url.includes("123"), "url"); + }); + const offerOptions = {offerToReceiveAudio: 1}; + await pc.setLocalDescription(await pc.createOffer(offerOptions)); + await onErrorPromise; +}, 'Surfacing onicecandidateerror'); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt index 837daad..7f79a7c00 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 506 tests; 452 PASS, 54 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 506 tests; 470 PASS, 36 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS Test driver for asyncInitCertificate PASS Test driver for asyncInitTransports @@ -39,7 +39,7 @@ PASS RTCPeerConnection interface: operation close() PASS RTCPeerConnection interface: attribute onnegotiationneeded PASS RTCPeerConnection interface: attribute onicecandidate -FAIL RTCPeerConnection interface: attribute onicecandidateerror assert_true: The prototype object must have a property "onicecandidateerror" expected true got false +PASS RTCPeerConnection interface: attribute onicecandidateerror PASS RTCPeerConnection interface: attribute onsignalingstatechange PASS RTCPeerConnection interface: attribute oniceconnectionstatechange PASS RTCPeerConnection interface: attribute onicegatheringstatechange @@ -92,7 +92,7 @@ PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "close()" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onnegotiationneeded" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onicecandidate" with the proper type -FAIL RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onicecandidateerror" with the proper type assert_inherits: property "onicecandidateerror" not found in prototype chain +PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onicecandidateerror" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onsignalingstatechange" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "oniceconnectionstatechange" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onicegatheringstatechange" with the proper type @@ -192,22 +192,22 @@ PASS Stringification of new RTCPeerConnectionIceEvent('ice') PASS RTCPeerConnectionIceEvent interface: new RTCPeerConnectionIceEvent('ice') must inherit property "candidate" with the proper type FAIL RTCPeerConnectionIceEvent interface: new RTCPeerConnectionIceEvent('ice') must inherit property "url" with the proper type assert_inherits: property "url" not found in prototype chain -FAIL RTCPeerConnectionIceErrorEvent interface: existence and properties of interface object assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface object length assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface object name assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object's "constructor" property assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object's @@unscopables property assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: attribute hostCandidate assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: attribute url assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: attribute errorCode assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: attribute errorText assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent must be primary interface of new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" -FAIL Stringification of new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" -FAIL RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "hostCandidate" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" -FAIL RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "url" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" -FAIL RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "errorCode" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" -FAIL RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "errorText" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" +PASS RTCPeerConnectionIceErrorEvent interface: existence and properties of interface object +PASS RTCPeerConnectionIceErrorEvent interface object length +PASS RTCPeerConnectionIceErrorEvent interface object name +PASS RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object +PASS RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object's "constructor" property +PASS RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object's @@unscopables property +PASS RTCPeerConnectionIceErrorEvent interface: attribute hostCandidate +PASS RTCPeerConnectionIceErrorEvent interface: attribute url +PASS RTCPeerConnectionIceErrorEvent interface: attribute errorCode +PASS RTCPeerConnectionIceErrorEvent interface: attribute errorText +PASS RTCPeerConnectionIceErrorEvent must be primary interface of new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); +PASS Stringification of new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); +PASS RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "hostCandidate" with the proper type +PASS RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "url" with the proper type +PASS RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "errorCode" with the proper type +PASS RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "errorText" with the proper type PASS RTCCertificate interface: existence and properties of interface object PASS RTCCertificate interface object length PASS RTCCertificate interface object name
diff --git a/third_party/blink/web_tests/external/wpt/webxr/xrDevice_disconnect_ends.https.html b/third_party/blink/web_tests/external/wpt/webxr/xrDevice_disconnect_ends.https.html new file mode 100644 index 0000000..ace64e8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webxr/xrDevice_disconnect_ends.https.html
@@ -0,0 +1,39 @@ +<!DOCTYPE html> +<body> + <script src=/resources/testharness.js></script> + <script src=/resources/testharnessreport.js></script> + <script src="resources/webxr_util.js"></script> + <script src="resources/webxr_test_constants.js"></script> + <canvas></canvas> + + <script> + const testName = "Immersive session ends when device is disconnected"; + let watcherDone = new Event("watcherdone"); + const fakeDeviceInitParams = TRACKED_IMMERSIVE_DEVICE; + + let testFunction = function(session, testDeviceController, t) { + let sessionWatcher = new EventWatcher(t, session, ["end", "watcherdone"]); + let sessionPromise = sessionWatcher.wait_for(["end", "watcherdone"]); + + let xrWatcher = new EventWatcher(t, navigator.xr, ["devicechange"]); + let xrPromise = xrWatcher.wait_for(["devicechange"]); + + function onSessionEnd(event) { + t.step( () => { + assert_equals(event.session, session); + session.dispatchEvent(watcherDone); + }); + } + + session.addEventListener("end", onSessionEnd, false); + + // The javascript needs to yield so that the event registration processes. + t.step_timeout(() => { testDeviceController.disconnect(); }, 0); + + return Promise.all([sessionPromise, xrPromise]); + }; + + xr_session_promise_test(testName, testFunction, + fakeDeviceInitParams, 'immersive-vr'); + </script> +</body>
diff --git a/third_party/blink/web_tests/fast/events/layout_change_after_update_hover.html b/third_party/blink/web_tests/fast/events/layout_change_after_update_hover.html deleted file mode 100644 index 4e88fb0..0000000 --- a/third_party/blink/web_tests/fast/events/layout_change_after_update_hover.html +++ /dev/null
@@ -1,48 +0,0 @@ -<!DOCTYPE html> -<script src='../../resources/gesture-util.js'></script> -<script src="../../resources/testharness.js"></script> -<script src="../../resources/testharnessreport.js"></script> - -<style> -#blue { - background-color: rgb(0, 0, 255); - position: absolute; - left: 75px; - top: 75px; - height: 100px; - width: 100px; -} -#blue:hover { - top: 500px; -} -</style> -<div id="blue"></div> -<script> -const x = 100; -const y = 100; -var blue = document.getElementById('blue'); - -window.onload = async () => { - if (window.internals) { - internals.runtimeFlags.updateHoverFromLayoutChangeAtBeginFrameEnabled = true; - } - - promise_test(async () => { - await mouseMoveTo(x, y); - // Move the blue element away when it is hovered, so the blue element will oscillates - // between 75px and 500px at each animation frame. - assert_true(blue.matches(':hover'), "Hover on the blue element"); - assert_equals(blue.offsetTop, 500, "Check that the blue element is moved to 500px from the top"); - await raf(); - assert_false(blue.matches(':hover'), "The blue element is moved away from the mouse cursor after a begin frame"); - assert_equals(blue.offsetTop, 75, "The blue element is moved back to 75px from the top"); - await raf(); - assert_true(blue.matches(':hover'), "Hover on the blue element"); - assert_equals(blue.offsetTop, 500, "Check that the blue element is moved to 500px from the top"); - await raf(); - assert_false(blue.matches(':hover'), "The blue element is moved away from the mouse cursor after a begin frame"); - assert_equals(blue.offsetTop, 75, "The blue element is moved back to 75px from the top"); - }, 'The hover state is updated at the begin frame after the layout changes which is caused by hover update.'); - -} -</script> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..429b598d --- /dev/null +++ b/third_party/blink/web_tests/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic.html b/third_party/blink/web_tests/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic.html new file mode 100644 index 0000000..a62822d0 --- /dev/null +++ b/third_party/blink/web_tests/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic.html
@@ -0,0 +1,62 @@ +<!DOCTYPE html> +<script src="../../../../resources/run-after-layout-and-paint.js"></script> +<script src="../../resources/common.js"></script> +<body> + +<!-- no style for reference --> +<ul> + <li>Text: <input type="text" /></li> + <li>Number: <input type="number" /></li> + <li>Search: <input type="search" /></li> + <li>Email: <input type="email" /></li> + <li>Password: <input type="password" /></li> + <li>TextArea: <textarea></textarea></li> +</ul> + +<!-- border --> +<ul> + <li>Text border: <input type="text" style="border: 3px solid lime;"/></li> +</ul> + +<!-- shadow --> +<ul> + <li>Text shadow: <input type="text" style="box-shadow: 4px 4px 10px rgba(255,0,0,0.5), inset 4px 4px 4px rgba(0,255,0,0.5);"/></li> +</ul> + +<!-- disabled --> +<ul> + <li>Text disabled: <input type="text" disabled/></li> +</ul> + +<!-- hover --> +<ul> + <li>Text hover: <input type="text" id="hoverTarget"/></li> +</ul> + +<!-- zoom --> +<ul> + <li>Text zoom: 1.5: <input type="text" style="zoom: 1.5;"/></li> + <li>Text zoom: 4: <input type="text" style="zoom: 4;"/></li> +</ul> + +<div style="background-color: blue"> + <br> + <ul> + <li>Text: <input type="text /"></li> + </ul> + <br> +</div> + +<script> + +if (window.testRunner) + testRunner.setUseMockTheme(false); + +runAfterLayoutAndPaint(function() { + var target = document.getElementById('hoverTarget'); + hoverOverElement(target); +}, true); + +</script> + +</body> \ No newline at end of file
diff --git a/third_party/blink/web_tests/http/tests/clipboard/async-write-image-read-image.html b/third_party/blink/web_tests/http/tests/clipboard/async-write-image-read-image.html index 3cf6d9b..d94a6b4 100644 --- a/third_party/blink/web_tests/http/tests/clipboard/async-write-image-read-image.html +++ b/third_party/blink/web_tests/http/tests/clipboard/async-write-image-read-image.html
@@ -65,4 +65,15 @@ assert_equals(comparableOutput, comparableInput); }, 'Verify write and read clipboard [image/png ClipboardItem]'); + +promise_test(async t => { + await PermissionsHelper.setPermission('clipboard-read', 'granted'); + await PermissionsHelper.setPermission('clipboard-write', 'granted'); + + const invalidPngBlob = new Blob(['this text is not a valid png image'], + {type: "image/png"}); + const clipboardItemInput = new ClipboardItem({'image/png' : invalidPngBlob}); + await promise_rejects(t, "DataError", + navigator.clipboard.write([clipboardItemInput])); +}, 'Verify write error on malformed data [image/png ClipboardItem]'); </script>
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/settings-workspace-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/settings-workspace-a11y-test-expected.txt new file mode 100644 index 0000000..43c2233 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/settings-workspace-a11y-test-expected.txt
@@ -0,0 +1,4 @@ +Tests accessibility in the settings workspace view using the axe-core linter. +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/settings-workspace-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/settings-workspace-a11y-test.js new file mode 100644 index 0000000..c40065dd --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/settings-workspace-a11y-test.js
@@ -0,0 +1,20 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('bindings_test_runner'); + + TestRunner.addResult( + 'Tests accessibility in the settings workspace view using the axe-core linter.'); + + const fs = new BindingsTestRunner.TestFileSystem('file:///this/is/a/test'); + await fs.reportCreatedPromise(); + + await UI.viewManager.showView('workspace'); + const workspaceWidget = await UI.viewManager.view('workspace').widget(); + + await AxeCoreTestRunner.runValidation(workspaceWidget.element); + TestRunner.completeTest(); +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-contentscripts-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-contentscripts-a11y-test-expected.txt new file mode 100644 index 0000000..33f1203 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-contentscripts-a11y-test-expected.txt
@@ -0,0 +1,7 @@ +Tests accessibility in the Sources panel Navigator pane Contentscripts tab using axe-core. +top + (no domain) + contentScript1.js +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-contentscripts-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-contentscripts-a11y-test.js new file mode 100644 index 0000000..5df6ba3 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-contentscripts-a11y-test.js
@@ -0,0 +1,45 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function () { + TestRunner.addResult('Tests accessibility in the Sources panel Navigator pane Contentscripts tab using axe-core.'); + + // axe-core issue #1444 -- role="tree" requires children with role="treeitem", + // but it is reasonable to have trees with no leaves. + const NO_REQUIRED_CHILDREN_RULESET = { + 'aria-required-children': { + enabled: false, + }, + }; + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('sdk_test_runner'); + await TestRunner.loadModule('sources_test_runner'); + + await UI.viewManager.showView('sources'); + await setup(); + + await testA11yForView(NO_REQUIRED_CHILDREN_RULESET); + + TestRunner.completeTest(); + + async function setup() { + // Add content scripts + var pageMock = new SDKTestRunner.PageMock('http://example.com'); + pageMock.connectAsMainTarget('page-target'); + const url = 'contentScript1.js'; + pageMock.evalScript(url, 'var script', true /* isContentScript */); + await TestRunner.waitForUISourceCode(url) + } + + async function testA11yForView(ruleSet) { + await UI.viewManager.showView('navigator-contentScripts'); + const sourcesNavigatorView = new Sources.ContentScriptsNavigatorView(); + + sourcesNavigatorView.show(UI.inspectorView.element); + SourcesTestRunner.dumpNavigatorView(sourcesNavigatorView); + const element = UI.panels.sources._navigatorTabbedLocation._tabbedPane.element; + await AxeCoreTestRunner.runValidation(element, ruleSet); + } +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-filesystem-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-filesystem-a11y-test-expected.txt new file mode 100644 index 0000000..7b62f2e --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-filesystem-a11y-test-expected.txt
@@ -0,0 +1,5 @@ +Tests accessibility in the Sources panel Navigator pane FileSystem tab using axe-core. +www3 [dimmed] +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-filesystem-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-filesystem-a11y-test.js new file mode 100644 index 0000000..17cb15f --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-filesystem-a11y-test.js
@@ -0,0 +1,42 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function () { + TestRunner.addResult('Tests accessibility in the Sources panel Navigator pane FileSystem tab using axe-core.'); + + // axe-core issue #1444 -- role="tree" requires children with role="treeitem", + // but it is reasonable to have trees with no leaves. + const NO_REQUIRED_CHILDREN_RULESET = { + 'aria-required-children': { + enabled: false, + }, + }; + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('bindings_test_runner'); + await TestRunner.loadModule('sources_test_runner'); + + await UI.viewManager.showView('sources'); + await setup(); + + await testA11yForView(NO_REQUIRED_CHILDREN_RULESET); + + TestRunner.completeTest(); + + async function setup() { + // Add a filesystem folder + const testFileSystem = new BindingsTestRunner.TestFileSystem('file:///var/www3'); + await testFileSystem.reportCreatedPromise(); + } + + async function testA11yForView(ruleSet) { + await UI.viewManager.showView('navigator-files'); + const sourcesNavigatorView = new Sources.FilesNavigatorView(); + + sourcesNavigatorView.show(UI.inspectorView.element); + SourcesTestRunner.dumpNavigatorView(sourcesNavigatorView); + const element = UI.panels.sources._navigatorTabbedLocation._tabbedPane.element; + await AxeCoreTestRunner.runValidation(element, ruleSet); + } +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-network-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-network-a11y-test-expected.txt new file mode 100644 index 0000000..591b14e --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-network-a11y-test-expected.txt
@@ -0,0 +1,8 @@ +Tests accessibility in the Sources panel Navigator pane Network tab using axe-core. +top + 127.0.0.1:8000 + devtools/resources + inspected-page.html +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-network-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-network-a11y-test.js new file mode 100644 index 0000000..8486422 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-network-a11y-test.js
@@ -0,0 +1,33 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function () { + TestRunner.addResult('Tests accessibility in the Sources panel Navigator pane Network tab using axe-core.'); + + // axe-core issue #1444 -- role="tree" requires children with role="treeitem", + // but it is reasonable to have trees with no leaves. + const NO_REQUIRED_CHILDREN_RULESET = { + 'aria-required-children': { + enabled: false, + }, + }; + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('sources_test_runner'); + + await UI.viewManager.showView('sources'); + await testA11yForView(NO_REQUIRED_CHILDREN_RULESET); + + TestRunner.completeTest(); + + async function testA11yForView(ruleSet) { + await UI.viewManager.showView('navigator-network'); + const sourcesNavigatorView = new Sources.NetworkNavigatorView(); + + sourcesNavigatorView.show(UI.inspectorView.element); + SourcesTestRunner.dumpNavigatorView(sourcesNavigatorView); + const element = UI.panels.sources._navigatorTabbedLocation._tabbedPane.element; + await AxeCoreTestRunner.runValidation(element, ruleSet); + } +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-overrides-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-overrides-a11y-test-expected.txt new file mode 100644 index 0000000..ca6e28a --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-overrides-a11y-test-expected.txt
@@ -0,0 +1,5 @@ +Tests accessibility in the Sources panel Navigator pane Overrides tab using axe-core. + [dimmed] +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-overrides-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-overrides-a11y-test.js new file mode 100644 index 0000000..695dea6c8 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-overrides-a11y-test.js
@@ -0,0 +1,41 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function () { + TestRunner.addResult('Tests accessibility in the Sources panel Navigator pane Overrides tab using axe-core.'); + + // axe-core issue #1444 -- role="tree" requires children with role="treeitem", + // but it is reasonable to have trees with no leaves. + const NO_REQUIRED_CHILDREN_RULESET = { + 'aria-required-children': { + enabled: false, + }, + }; + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('bindings_test_runner'); + await TestRunner.loadModule('sources_test_runner'); + + await UI.viewManager.showView('sources'); + + await setup(); + await testA11yForView(NO_REQUIRED_CHILDREN_RULESET); + + TestRunner.completeTest(); + + async function setup() { + // Add an overrides folder + await BindingsTestRunner.createOverrideProject('file:///tmp/'); + } + + async function testA11yForView(ruleSet) { + await UI.viewManager.showView('navigator-overrides'); + const sourcesNavigatorView = new Sources.OverridesNavigatorView(); + + sourcesNavigatorView.show(UI.inspectorView.element); + SourcesTestRunner.dumpNavigatorView(sourcesNavigatorView); + const element = UI.panels.sources._navigatorTabbedLocation._tabbedPane.element; + await AxeCoreTestRunner.runValidation(element, ruleSet); + } +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-snippets-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-snippets-a11y-test-expected.txt new file mode 100644 index 0000000..4f508a6 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-snippets-a11y-test-expected.txt
@@ -0,0 +1,6 @@ +Tests accessibility in the Sources panel Navigator pane Snippets tab using axe-core. +Script snippet #1 +Script snippet #2 +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-snippets-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-snippets-a11y-test.js new file mode 100644 index 0000000..0a1c6e9 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/source-navigator-snippets-a11y-test.js
@@ -0,0 +1,41 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function () { + TestRunner.addResult('Tests accessibility in the Sources panel Navigator pane Snippets tab using axe-core.'); + + // axe-core issue #1444 -- role="tree" requires children with role="treeitem", + // but it is reasonable to have trees with no leaves. + const NO_REQUIRED_CHILDREN_RULESET = { + 'aria-required-children': { + enabled: false, + }, + }; + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('sources_test_runner'); + + await UI.viewManager.showView('sources'); + + await setup(); + await testA11yForView(NO_REQUIRED_CHILDREN_RULESET); + + TestRunner.completeTest(); + + async function setup() { + // Add snippets + await Snippets.project.createFile('s1', null, ''); + await Snippets.project.createFile('s2', null, ''); + } + + async function testA11yForView(ruleSet) { + await UI.viewManager.showView('navigator-snippets'); + const sourcesNavigatorView = new Sources.SnippetsNavigatorView(); + + sourcesNavigatorView.show(UI.inspectorView.element); + SourcesTestRunner.dumpNavigatorView(sourcesNavigatorView); + const element = UI.panels.sources._navigatorTabbedLocation._tabbedPane.element; + await AxeCoreTestRunner.runValidation(element, ruleSet); + } +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/sources-editor-pane-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/sources-editor-pane-a11y-test-expected.txt new file mode 100644 index 0000000..e2a9bdd8 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/sources-editor-pane-a11y-test-expected.txt
@@ -0,0 +1,9 @@ +Tests accessibility in the editor pane in sources panel using the axe-core linter. +All tabs: +Script snippet #1 +Script snippet #2 + + +aXe violations: [] + +
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/sources-editor-pane-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/sources-editor-pane-a11y-test.js new file mode 100644 index 0000000..edea7c3 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/sources-editor-pane-a11y-test.js
@@ -0,0 +1,54 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function () { + TestRunner.addResult('Tests accessibility in the editor pane in sources panel using the axe-core linter.'); + + // axe-core issue #1444 -- role="tree" requires children with role="treeitem", + // but it is reasonable to have trees with no leaves. + // Ignore 'aria-required-children' rule for tablist because it doesn't accommodate empty tablist. + const NO_REQUIRED_CHILDREN_RULESET = { + 'aria-required-children': { + enabled: false, + selector: ':not(.tabbed-pane-header-tabs)' + }, + }; + + await TestRunner.loadModule('axe_core_test_runner'); + await TestRunner.loadModule('sources_test_runner'); + + await UI.viewManager.showView('sources'); + + await setup(); + await runTest(); + + TestRunner.completeTest(); + + async function setup() { + const projects = Workspace.workspace.projectsForType(Workspace.projectTypes.FileSystem); + const snippetsProject = projects.find( + project => Persistence.FileSystemWorkspaceBinding.fileSystemType(project) === 'snippets'); + const uiSourceCode1 = await snippetsProject.createFile(''); + await Common.Revealer.reveal(uiSourceCode1); + const uiSourceCode2 = await snippetsProject.createFile(''); + await Common.Revealer.reveal(uiSourceCode2); + } + + async function runTest() { + // Verify contents of the TabHeader to make sure files are open + const tabbedPane = UI.panels.sources._sourcesView._editorContainer._tabbedPane; + const tabs = tabbedPane._tabs; + TestRunner.addResult('All tabs:'); + tabs.forEach(tab => TestRunner.addResult(tab.title)); + TestRunner.addResult('\n'); + + await runA11yTest(); + } + + async function runA11yTest() { + await UI.viewManager.showView('sources'); + const element = UI.panels.sources._sourcesView.contentElement; + await AxeCoreTestRunner.runValidation(element, NO_REQUIRED_CHILDREN_RULESET); + } +})();
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-node-styles-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-node-styles-expected.txt new file mode 100644 index 0000000..0886885 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-node-styles-expected.txt
@@ -0,0 +1,17 @@ +This test verifies the style info overlaid on an inspected node. + +empty-div{ + "padding": "0px", + "margin": "0px", + "background-color": "#0000FFFF" +} +div-with-text{ + "color": "#FF0000FF", + "font-family": "<font-family value>", + "font-size": "20px", + "line-height": "normal", + "padding": "0px", + "margin": "0px", + "background-color": "#0000FFFF" +} +
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-node-styles.js b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-node-styles.js new file mode 100644 index 0000000..d784429 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-node-styles.js
@@ -0,0 +1,24 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + TestRunner.addResult(`This test verifies the style info overlaid on an inspected node.\n`); + await TestRunner.loadModule('elements_test_runner'); + await TestRunner.showPanel('elements'); + await TestRunner.loadHTML(` + <style> + div { + color: red; + background-color: blue; + font-size: 20px; + } + </style> + <div id="empty-div"></div> + <div id="div-with-text">I have text</div> + `); + + await ElementsTestRunner.dumpInspectorHighlightStyleJSON('empty-div'); + await ElementsTestRunner.dumpInspectorHighlightStyleJSON('div-with-text'); + TestRunner.completeTest(); +})();
diff --git a/third_party/blink/web_tests/http/tests/loading/sxg/sxg-subresource-origin-trial.https.html b/third_party/blink/web_tests/http/tests/loading/sxg/sxg-subresource-origin-trial.https.html index d1931a9b..e2ede32 100644 --- a/third_party/blink/web_tests/http/tests/loading/sxg/sxg-subresource-origin-trial.https.html +++ b/third_party/blink/web_tests/http/tests/loading/sxg/sxg-subresource-origin-trial.https.html
@@ -2,9 +2,9 @@ <head> <title>Signed Exchange subresource Origin Trial</title> <!-- Generate token with the command: -generate_token.py https://127.0.0.1:8443 SignedExchangeSubresourcePrefetch --expire-timestamp=2000000000 --- --> -<meta http-equiv="origin-trial" content="AkPuNZ6wN6pkhO5BsawPJCR9+8TDqRn4NUKsrhif+5Hs6l3dbRCdhhBpImxV13ZM8luH7wYH+rC9LYwD9xIQOAwAAABqeyJvcmlnaW4iOiAiaHR0cHM6Ly8xMjcuMC4wLjE6ODQ0MyIsICJmZWF0dXJlIjogIlNpZ25lZEV4Y2hhbmdlU3VicmVzb3VyY2VQcmVmZXRjaCIsICJleHBpcnkiOiAyMDAwMDAwMDAwfQ=="> +generate_token.py https://127.0.0.1:8443 SignedExchangeSubresourcePrefetchM77 --expire-timestamp=2000000000 +--> +<meta http-equiv="origin-trial" content="Ao1Rkqe2U6oCso2tOgrDsHafv0e4DMSR23+UmpE4W2Bz2xzSrfolPczSFvjHdAK1kviH9mqVaZarc1Y9vCyWqgAAAABteyJvcmlnaW4iOiAiaHR0cHM6Ly8xMjcuMC4wLjE6ODQ0MyIsICJmZWF0dXJlIjogIlNpZ25lZEV4Y2hhbmdlU3VicmVzb3VyY2VQcmVmZXRjaE03NyIsICJleHBpcnkiOiAyMDAwMDAwMDAwfQ=="> <script src="./resources/sxg-util.js"></script> </head> <body>
diff --git a/third_party/blink/web_tests/http/tests/priorities/resource-load-priorities-service-worker.https-expected.txt b/third_party/blink/web_tests/http/tests/priorities/resource-load-priorities-service-worker.https-expected.txt deleted file mode 100644 index 2c48859..0000000 --- a/third_party/blink/web_tests/http/tests/priorities/resource-load-priorities-service-worker.https-expected.txt +++ /dev/null
@@ -1,14 +0,0 @@ -This is a testharness.js-based test. -PASS registering service worker -PASS Requests from the Fetch API passing through a Service Worker should be loaded with kHigh priority -PASS Render-blocking style sheets requests passing through a Service Worker should be loaded with kVeryHigh priority -FAIL Async scripts passing through a Service Worker should be loaded with kLow priority assert_equals: expected 1 but got 3 -FAIL Deferred scripts passing through a Service Worker should be loaded with kLow priority assert_equals: expected 1 but got 3 -PASS Module scripts passing through a Service Worker should be loaded with kHigh priority -PASS XHRs passing through a Service Worker should be loaded with kHigh priority -PASS Parser-blocking scripts passing through a Service Worker should be loaded with kHigh priority -FAIL Off-screen images passing through a Service Worker should be loaded with kLow priority assert_equals: expected 1 but got 3 -FAIL Prefetches passing through a Service Worker should be loaded with kLowest priority assert_equals: expected 0 but got 3 -PASS unregistering service worker -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-1-0px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-1-0px.html new file mode 100644 index 0000000..be2943d --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-1-0px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 1, margin: '0px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-1-10px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-1-10px.html new file mode 100644 index 0000000..209f1204 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-1-10px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 1, margin: '10px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-2-0px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-2-0px.html new file mode 100644 index 0000000..0b52676 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-2-0px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 2, margin: '0px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-2-10px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-2-10px.html new file mode 100644 index 0000000..f9b9825 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-2-10px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 2, margin: '10px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-3-0px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-3-0px.html new file mode 100644 index 0000000..8a84b10 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-3-0px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 3, margin: '0px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-3-10px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-3-10px.html new file mode 100644 index 0000000..f67dbe5 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-3-10px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 3, margin: '10px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-62-0px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-62-0px.html new file mode 100644 index 0000000..4ca8f5e --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-62-0px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 62, margin: '0px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-62-10px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-62-10px.html new file mode 100644 index 0000000..855e007 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-62-10px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 62, margin: '10px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-63-0px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-63-0px.html new file mode 100644 index 0000000..603e7aa --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-63-0px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 63, margin: '0px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-63-10px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-63-10px.html new file mode 100644 index 0000000..296f8ff --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-63-10px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 63, margin: '10px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-64-0px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-64-0px.html new file mode 100644 index 0000000..cbc806b --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-64-0px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 64, margin: '0px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-64-10px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-64-10px.html new file mode 100644 index 0000000..e025198 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-64-10px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 64, margin: '10px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-65-0px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-65-0px.html new file mode 100644 index 0000000..fc7b7e1c7 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-65-0px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 65, margin: '0px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-65-10px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-65-10px.html new file mode 100644 index 0000000..0e5b23d --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-65-10px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 65, margin: '10px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-66-0px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-66-0px.html new file mode 100644 index 0000000..1e71259 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-66-0px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 66, margin: '0px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-66-10px.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-66-10px.html new file mode 100644 index 0000000..61ab6645 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element-66-10px.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as helpers from './resources/helpers.mjs'; + + helpers.testFindElement({elementCount: 66, margin: '10px'}); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/find-element.html b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element.html new file mode 100644 index 0000000..d5980a2 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/find-element.html
@@ -0,0 +1,42 @@ +<!DOCTYPE html> +<title>Test the find-element.mjs functions.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import * as findElement from '/gen/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs'; + import * as helpers from './resources/helpers.mjs'; + import * as wptHelpers from '/wpt_internal/virtual-scroller/resources/helpers.mjs'; + + test(() => { + helpers.assertFindsElement([], 100, findElement.BIAS_LOW, null); + helpers.assertFindsElement([], 100, findElement.BIAS_HIGH, null); + }, 'Test findElement on empty array'); + + test(() => { + wptHelpers.withElement('div', containerDiv => { + // We set up a first and last div and between them there are 100 + // 0px divs (no height, no margin). Depending on the bias we + // should always find either the first or last div, never a 0px + // div. + const firstDiv = wptHelpers.div('first'); + firstDiv.style.margin = "0px"; + containerDiv.appendChild(firstDiv); + for (let i = 0; i < 100; i++) { + const d = wptHelpers.div('d' + i); + d.style.margin = "0px"; + d.style.height = "0px"; + containerDiv.appendChild(d); + } + const lastDiv = wptHelpers.div('lastDiv'); + lastDiv.style.margin = "0px"; + containerDiv.appendChild(lastDiv); + + const elements = containerDiv.children; + const offset = helpers.bottomOf(firstDiv); // Also helpers.topOf(lastDiv). + helpers.assertFindsElement(elements, offset, findElement.BIAS_LOW, firstDiv); + helpers.assertFindsElement(elements, offset, findElement.BIAS_HIGH, lastDiv); + }); + }, 'Test findElement skips 0px elements'); + +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/helpers.html b/third_party/blink/web_tests/http/tests/virtual-scroller/helpers.html new file mode 100644 index 0000000..94be61e --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/helpers.html
@@ -0,0 +1,159 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script src="resources/helpers.js"></script> +<div id=contentDiv> +</div> + +<script type="module"> + 'use strict'; + + import * as findElement from '/gen/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs'; + import * as helpers from './resources/helpers.mjs'; + import * as wptHelpers from '/wpt_internal/virtual-scroller/resources/helpers.mjs'; + + /** + * Asserts that we find |element| when we search in |elements| with this |offset| and |bias|. + */ + function assertFindsElement(elements, offset, bias, element) { + const found = helpers.simpleFindElement(elements, offset, bias); + assert_equals(found, element, `Searching offset=${offset}, bias=${bias.toString()}`); + } + + // Since even simpleFindElement isn't that simple, we have some tests for it too. + test(() => { + assertFindsElement([], 100, findElement.BIAS_LOW, null); + assertFindsElement([], 100, findElement.BIAS_HIGH, null); + }, 'Test simpleFindElement no elements'); + + test(() => { + wptHelpers.withElement('div', containerDiv => { + wptHelpers.appendDivs(containerDiv, 2, "10px"); + const elements = containerDiv.children; + // Check all boundaries of the first element. + // Check 1px before the top. + assertFindsElement( + elements, helpers.topOf(elements[0]) - 1, findElement.BIAS_LOW, null); + assertFindsElement( + elements, helpers.topOf(elements[0]) - 1, findElement.BIAS_HIGH, null); + // Check at the top. + assertFindsElement( + elements, helpers.topOf(elements[0]), findElement.BIAS_LOW, elements[0]); + assertFindsElement( + elements, helpers.topOf(elements[0]), findElement.BIAS_HIGH, elements[0]); + // Check 1px after the top. + assertFindsElement( + elements, helpers.topOf(elements[0]) + 1, findElement.BIAS_LOW, elements[0]); + assertFindsElement( + elements, helpers.topOf(elements[0]) + 1, findElement.BIAS_HIGH, elements[0]); + + // Check 1px before the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[0]) - 1, findElement.BIAS_LOW, elements[0]); + assertFindsElement( + elements, helpers.bottomOf(elements[0]) - 1, findElement.BIAS_HIGH, elements[0]); + // Check at the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[0]), findElement.BIAS_LOW, elements[0]); + assertFindsElement( + elements, helpers.bottomOf(elements[0]), findElement.BIAS_HIGH, elements[0]); + // Check 1px after the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[0]) + 1, findElement.BIAS_LOW, elements[0]); + assertFindsElement( + elements, helpers.bottomOf(elements[0]) + 1, findElement.BIAS_HIGH, elements[1]); + + // Check all boundaries of the second (last) element. + // Check 1px before the top. + assertFindsElement( + elements, helpers.topOf(elements[1]) - 1, findElement.BIAS_LOW, elements[0]); + assertFindsElement( + elements, helpers.topOf(elements[1]) - 1, findElement.BIAS_HIGH, elements[1]); + // Check at the top. + assertFindsElement( + elements, helpers.topOf(elements[1]), findElement.BIAS_LOW, elements[1]); + assertFindsElement( + elements, helpers.topOf(elements[1]), findElement.BIAS_HIGH, elements[1]); + // Check 1px after the top. + assertFindsElement( + elements, helpers.topOf(elements[1]) + 1, findElement.BIAS_LOW, elements[1]); + assertFindsElement( + elements, helpers.topOf(elements[1]) + 1, findElement.BIAS_HIGH, elements[1]); + + // Check 1px before the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[1]) - 1, findElement.BIAS_LOW, elements[1]); + assertFindsElement( + elements, helpers.bottomOf(elements[1]) - 1, findElement.BIAS_HIGH, elements[1]); + // Check at the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[1]), findElement.BIAS_LOW, elements[1]); + assertFindsElement( + elements, helpers.bottomOf(elements[1]), findElement.BIAS_HIGH, elements[1]); + // Check 1px after the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[1]) + 1, findElement.BIAS_LOW, null); + assertFindsElement( + elements, helpers.bottomOf(elements[1]) + 1, findElement.BIAS_HIGH, null); + }); + }, 'Test simpleFindElement 10px margin'); + + test(() => { + wptHelpers.withElement('div', containerDiv => { + wptHelpers.appendDivs(containerDiv, 2, "10px"); + const elements = containerDiv.children; + // Check all boundaries of the first element. + // Check 1px before the top. + assertFindsElement( + elements, helpers.topOf(elements[0]) - 1, findElement.BIAS_LOW, null); + assertFindsElement( + elements, helpers.topOf(elements[0]) - 1, findElement.BIAS_HIGH, null); + // Check at the top. + assertFindsElement( + elements, helpers.topOf(elements[0]), findElement.BIAS_LOW, elements[0]); + assertFindsElement( + elements, helpers.topOf(elements[0]), findElement.BIAS_HIGH, elements[0]); + // Check 1px after the top. + assertFindsElement( + elements, helpers.topOf(elements[0]) + 1, findElement.BIAS_LOW, elements[0]); + assertFindsElement( + elements, helpers.topOf(elements[0]) + 1, findElement.BIAS_HIGH, elements[0]); + + // Check 1px before the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[0]) - 1, findElement.BIAS_LOW, elements[0]); + assertFindsElement( + elements, helpers.bottomOf(elements[0]) - 1, findElement.BIAS_HIGH, elements[0]); + // Check at the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[0]), findElement.BIAS_LOW, elements[0]); + assertFindsElement( + elements, helpers.bottomOf(elements[0]), findElement.BIAS_HIGH, elements[0]); + + // Bottom of first == top of second. + + // Check all boundaries of the second (last) element. + // Check 1px after the top. + assertFindsElement( + elements, helpers.topOf(elements[1]) + 1, findElement.BIAS_LOW, elements[1]); + assertFindsElement( + elements, helpers.topOf(elements[1]) + 1, findElement.BIAS_HIGH, elements[1]); + + // Check 1px before the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[1]) - 1, findElement.BIAS_LOW, elements[1]); + assertFindsElement( + elements, helpers.bottomOf(elements[1]) - 1, findElement.BIAS_HIGH, elements[1]); + // Check at the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[1]), findElement.BIAS_LOW, elements[1]); + assertFindsElement( + elements, helpers.bottomOf(elements[1]), findElement.BIAS_HIGH, elements[1]); + // Check 1px after the bottom. + assertFindsElement( + elements, helpers.bottomOf(elements[1]) + 1, findElement.BIAS_LOW, null); + assertFindsElement( + elements, helpers.bottomOf(elements[1]) + 1, findElement.BIAS_HIGH, null); + }); + }, 'Test simpleFindElement 0px margin'); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/resources/helpers.mjs b/third_party/blink/web_tests/http/tests/virtual-scroller/resources/helpers.mjs new file mode 100644 index 0000000..3881914 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/resources/helpers.mjs
@@ -0,0 +1,124 @@ +/** + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + * + * @fileoverview Helpers for testing virtual-scroller code. + * @package + */ + +import * as wptHelpers from '/wpt_internal/virtual-scroller/resources/helpers.mjs'; + +import * as findElement from '/gen/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs'; + +export function topOf(element) { + return element.getBoundingClientRect().top; +} + +export function bottomOf(element) { + return element.getBoundingClientRect().bottom; +} + +/** + * An inefficient but simple implementation of findElement that searches + * linearly. + */ +export function simpleFindElement(elements, offset, bias) { + if (elements.length === 0) { + return null; + } + const lastIndex = elements.length - 1; + + if (bias === findElement.BIAS_LOW) { + if (offset < topOf(elements[0])) { + // Lower than first element. + return null; + } + // We bias low, so we accept the first element that either + // contains offset or is followed by an element that is fully + // higher than offset. + for (let i = 0; i < elements.length; i++) { + const element = elements[i]; + // We already know that offset >= top. + if (offset <= bottomOf(element) || + (i < lastIndex && offset < topOf(elements[i + 1]))) { + return element; + } + } + } else { + if (offset > bottomOf(elements[lastIndex])) { + // Higher than last element. + return null; + } + // We bias high, so we iterate backwards and accept the first + // element that either contains offset or is followed by an + // element that is fully lower than offset. + for (let i = lastIndex; i >= 0; i--) { + const element = elements[i]; + // We already know that offset <= bottom. + if (offset >= topOf(element) || + (i > 0 && offset > bottomOf(elements[i - 1]))) { + return element; + } + } + } + // We went through all the elements without accepting any. + return null; +} + +/** + * Asserts that we find |element| when we search in |elements| with this + * |offset| and |bias|. + */ +export function assertFindsElement(elements, offset, bias, element) { + const found = findElement.findElement(elements, offset, bias); + window.assert_equals( + found, element, `Searching offset=${offset}, bias=${bias.toString()}`); +} + +/** + * Starts 10px before the first element and iterates until 10px after the last + * element. At each point compares the results of simpleFindElement with the + * real findElement. + */ +function testFindElementAtAllOffsets(elements, margin, bias) { + const startPx = topOf(elements[0]); + const endPx = bottomOf(elements[elements.length - 1]); + const BUFFER_PX = 10; + // index will go from -1 to length (both are out of bounds) + for (let offset = startPx - BUFFER_PX; + offset <= endPx + BUFFER_PX; + offset++) { + const element = simpleFindElement(elements, offset, bias); + assertFindsElement(elements, offset, bias, element); + } +} + +/** + * Constructs a container with |elementCount| divs each with margin |margin| and + * exhaustively tests findElement against this. + */ +export function testFindElement({elementCount, margin}) { + window.test(() => { + wptHelpers.withElement('div', containerDiv => { + wptHelpers.appendDivs(containerDiv, elementCount, margin); + const elements = containerDiv.children; + testFindElementAtAllOffsets(elements, margin, findElement.BIAS_LOW); + testFindElementAtAllOffsets(elements, margin, findElement.BIAS_HIGH); + }); + }, `Test findElement elementCount=${elementCount}, margin=${margin}`); +} + +/** + * Asserts that the elements of actual and expected are the same, ignoring + * order. This uses Array#sort() so will only work for elements that can be + * sorted. +*/ +export function assertElementsEqual(actual, expected, description) { + const actualArray = Array.from(actual); + actualArray.sort(); + const expectedArray = Array.from(expected); + expectedArray.sort(); + window.assert_array_equals(actualArray, expectedArray, description); +} +
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/sets.html b/third_party/blink/web_tests/http/tests/virtual-scroller/sets.html new file mode 100644 index 0000000..8bcb8dd --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/sets.html
@@ -0,0 +1,36 @@ +<!DOCTYPE html> +<title>Test the sets.mjs functions.</title> + +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script type="module"> + import * as sets from '/gen/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs'; + import * as helpers from './resources/helpers.mjs'; + + test(() => { + const s1 = new Set([1, 2, 3]); + const s2 = new Set([1, 2, 3]); + helpers.assertElementsEqual(sets.difference(s1, s2), []); + }, 'diff self is empty'); + + test(() => { + const s1 = new Set([1, 2, 3, 4]); + const s2 = new Set([3, 4, 5, 6]); + helpers.assertElementsEqual(sets.difference(s1, s2), [1, 2]); + helpers.assertElementsEqual(sets.difference(s2, s1), [5, 6]); + }, 'two overlapping'); + + test(() => { + const s1 = new Set([3, 4]); + const s2 = new Set([3, 4, 5, 6]); + helpers.assertElementsEqual(sets.difference(s1, s2), []); + helpers.assertElementsEqual(sets.difference(s2, s1), [5, 6]); + }, 'one-sided overlapping'); + + test(() => { + const s1 = new Set([]); + const s2 = new Set([3, 4]); + helpers.assertElementsEqual(sets.difference(s1, s2), []); + helpers.assertElementsEqual(sets.difference(s2, s1), [3, 4]); + }, 'empty set'); +</script>
diff --git a/third_party/blink/web_tests/http/tests/virtual-scroller/virtual-scroller-element.html b/third_party/blink/web_tests/http/tests/virtual-scroller/virtual-scroller-element.html new file mode 100644 index 0000000..84a6161 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/virtual-scroller/virtual-scroller-element.html
@@ -0,0 +1,24 @@ +<!DOCTYPE html> +<title>Test the virtual-scroller element.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> + +<script type="module"> + import {VirtualScrollerElement} from 'std:elements/virtual-scroller'; + import * as helpers from './resources/helpers.mjs'; + import * as wptHelpers from '/wpt_internal/virtual-scroller/resources/helpers.mjs'; + + test(() => { + wptHelpers.withElement('virtual-scroller', vc => { + assert_not_equals(vc, null); + assert_true(vc instanceof VirtualScrollerElement);}); + }, 'Test no content'); + + test(() => { + wptHelpers.withElement('virtual-scroller', vc => { + helpers.assertElementsEqual( + Object.getOwnPropertyNames(vc.__proto__), + ['constructor']); + }); + }, 'Only exposes certain properties'); +</script>
diff --git a/third_party/blink/web_tests/platform/linux/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/platform/linux/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..28c2d82 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/platform/linux/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..f714cf8 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..1990a7c --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..5190c10 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.10/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.11/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/platform/mac-mac10.11/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..5190c10 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.11/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/platform/mac-mac10.12/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..5190c10 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.12/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-retina/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/platform/mac-retina/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..5190c10 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-retina/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/platform/mac/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..539af0b --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/platform/mac/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..5190c10 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/svg/animations/correct-events-from-short-animations.html b/third_party/blink/web_tests/svg/animations/correct-events-from-short-animations.html new file mode 100644 index 0000000..4d09a25 --- /dev/null +++ b/third_party/blink/web_tests/svg/animations/correct-events-from-short-animations.html
@@ -0,0 +1,36 @@ +<!DOCTYPE html> + +<title>Correct events from short elements</title> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> + +<svg viewBox="0 0 100 50" xmlns="http://www.w3.org/2000/svg"> + <g opacity="0"> + <animate attributeName="opacity" from="0" to="1" begin="0ms;last.end+20ms" dur="10ms" fill="freeze" + id="first"/> + <animate attributeName="opacity" from="1" to="0" begin="last.end" dur="1ms" fill="freeze"/> + <rect x="0" y="0" width="50" height="50" fill="#0F0"/> + </g> + <g opacity="0"> + <animate attributeName="opacity" from="1" to="1" begin="first.end+40ms" dur="100ms" fill="freeze" + id="last" onend="onend_filling()"/> + <animate attributeName="opacity" from="1" to="0" begin="last.end" dur="1ms" fill="freeze" + onend="onend_clearing()"/> + <rect x="50" y="0" width="50" height="50" fill="#0F0"/> + </g> +</svg> +<script> + let onend_filling = null; + let onend_clearing = null; + async_test(t => { + var passed = false; + var end_events = 0; + onend_filling = t.step_func(() => { + end_events++; + if (end_events != 2) return; + assert_unreached("Should only get one 'end' event"); + }); + // Finished if we get one of these + onend_clearing = t.step_func_done(() => {}); + }); +</script>
diff --git a/third_party/blink/web_tests/virtual/cache-storage-sequence/external/wpt/service-workers/README.txt b/third_party/blink/web_tests/virtual/cache-storage-sequence/external/wpt/service-workers/README.txt new file mode 100644 index 0000000..7ad2004b --- /dev/null +++ b/third_party/blink/web_tests/virtual/cache-storage-sequence/external/wpt/service-workers/README.txt
@@ -0,0 +1,3 @@ +This suite runs the ServiceWorker and CacheStorage tests with the +CacheStorageSequence feature enabled. This makes CacheStorage operate off +the IO thread in the browser process.
diff --git a/third_party/blink/web_tests/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png b/third_party/blink/web_tests/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png new file mode 100644 index 0000000..b2a08eb --- /dev/null +++ b/third_party/blink/web_tests/virtual/controls-refresh/fast/forms/controls-new-ui/text/input-basic-box-appearance-basic-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt index 55b596de..b3b5b484a 100644 --- a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -5062,6 +5062,7 @@ getter onconnectionstatechange getter ondatachannel getter onicecandidate + getter onicecandidateerror getter oniceconnectionstatechange getter onicegatheringstatechange getter onnegotiationneeded @@ -5099,12 +5100,20 @@ setter onconnectionstatechange setter ondatachannel setter onicecandidate + setter onicecandidateerror setter oniceconnectionstatechange setter onicegatheringstatechange setter onnegotiationneeded setter onremovestream setter onsignalingstatechange setter ontrack +interface RTCPeerConnectionIceErrorEvent : Event + attribute @@toStringTag + getter errorCode + getter errorText + getter hostCandidate + getter url + method constructor interface RTCPeerConnectionIceEvent : Event attribute @@toStringTag getter candidate @@ -8664,6 +8673,7 @@ getter onconnectionstatechange getter ondatachannel getter onicecandidate + getter onicecandidateerror getter oniceconnectionstatechange getter onicegatheringstatechange getter onnegotiationneeded @@ -8701,6 +8711,7 @@ setter onconnectionstatechange setter ondatachannel setter onicecandidate + setter onicecandidateerror setter oniceconnectionstatechange setter onicegatheringstatechange setter onnegotiationneeded
diff --git a/third_party/blink/web_tests/virtual/user-timing-l2/external/wpt/user-timing/measure-with-dict-expected.txt b/third_party/blink/web_tests/virtual/user-timing-l2/external/wpt/user-timing/measure-with-dict-expected.txt index 479a68d..76ea135 100644 --- a/third_party/blink/web_tests/virtual/user-timing-l2/external/wpt/user-timing/measure-with-dict-expected.txt +++ b/third_party/blink/web_tests/virtual/user-timing-l2/external/wpt/user-timing/measure-with-dict-expected.txt
@@ -1,7 +1,7 @@ This is a testharness.js-based test. FAIL measure entries' detail and start/end are customizable Cannot read property 'name' of null FAIL measure should throw a TypeError when passed an invalid argument combination assert_throws: measure should throw a TypeError when passed an options object and an end time function "function() { - self.performance.measure("wrongUsage2", {'start': 2}, 12); + self.performance.measure("optionsAndNumberEnd", {'start': 2}, 12); }" threw object "SyntaxError: Failed to execute 'measure' on 'Performance': The mark '12' does not exist." ("SyntaxError") expected object "TypeError" ("TypeError") Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt index df7193d..855af64a 100644 --- a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 506 tests; 382 PASS, 124 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 506 tests; 400 PASS, 106 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS Test driver for asyncInitCertificate FAIL Test driver for asyncInitTransports assert_unreached: Failed to run asyncInitTransports: Error: assert_true: Expect pc.sctp to be instance of RTCSctpTransport expected true got false Reached unreachable code @@ -39,7 +39,7 @@ PASS RTCPeerConnection interface: operation close() PASS RTCPeerConnection interface: attribute onnegotiationneeded PASS RTCPeerConnection interface: attribute onicecandidate -FAIL RTCPeerConnection interface: attribute onicecandidateerror assert_true: The prototype object must have a property "onicecandidateerror" expected true got false +PASS RTCPeerConnection interface: attribute onicecandidateerror PASS RTCPeerConnection interface: attribute onsignalingstatechange PASS RTCPeerConnection interface: attribute oniceconnectionstatechange PASS RTCPeerConnection interface: attribute onicegatheringstatechange @@ -92,7 +92,7 @@ PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "close()" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onnegotiationneeded" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onicecandidate" with the proper type -FAIL RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onicecandidateerror" with the proper type assert_inherits: property "onicecandidateerror" not found in prototype chain +PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onicecandidateerror" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onsignalingstatechange" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "oniceconnectionstatechange" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "onicegatheringstatechange" with the proper type @@ -192,22 +192,22 @@ PASS Stringification of new RTCPeerConnectionIceEvent('ice') PASS RTCPeerConnectionIceEvent interface: new RTCPeerConnectionIceEvent('ice') must inherit property "candidate" with the proper type FAIL RTCPeerConnectionIceEvent interface: new RTCPeerConnectionIceEvent('ice') must inherit property "url" with the proper type assert_inherits: property "url" not found in prototype chain -FAIL RTCPeerConnectionIceErrorEvent interface: existence and properties of interface object assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface object length assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface object name assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object's "constructor" property assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object's @@unscopables property assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: attribute hostCandidate assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: attribute url assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: attribute errorCode assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent interface: attribute errorText assert_own_property: self does not have own property "RTCPeerConnectionIceErrorEvent" expected property "RTCPeerConnectionIceErrorEvent" missing -FAIL RTCPeerConnectionIceErrorEvent must be primary interface of new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" -FAIL Stringification of new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" -FAIL RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "hostCandidate" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" -FAIL RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "url" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" -FAIL RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "errorCode" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" -FAIL RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "errorText" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: RTCPeerConnectionIceErrorEvent is not defined" +PASS RTCPeerConnectionIceErrorEvent interface: existence and properties of interface object +PASS RTCPeerConnectionIceErrorEvent interface object length +PASS RTCPeerConnectionIceErrorEvent interface object name +PASS RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object +PASS RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object's "constructor" property +PASS RTCPeerConnectionIceErrorEvent interface: existence and properties of interface prototype object's @@unscopables property +PASS RTCPeerConnectionIceErrorEvent interface: attribute hostCandidate +PASS RTCPeerConnectionIceErrorEvent interface: attribute url +PASS RTCPeerConnectionIceErrorEvent interface: attribute errorCode +PASS RTCPeerConnectionIceErrorEvent interface: attribute errorText +PASS RTCPeerConnectionIceErrorEvent must be primary interface of new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); +PASS Stringification of new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); +PASS RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "hostCandidate" with the proper type +PASS RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "url" with the proper type +PASS RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "errorCode" with the proper type +PASS RTCPeerConnectionIceErrorEvent interface: new RTCPeerConnectionIceErrorEvent('ice-error', { errorCode: 701 }); must inherit property "errorText" with the proper type PASS RTCCertificate interface: existence and properties of interface object PASS RTCCertificate interface object length PASS RTCCertificate interface object name
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt index 2e41760..eb72f2d 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt
@@ -5850,6 +5850,7 @@ getter onconnectionstatechange getter ondatachannel getter onicecandidate + getter onicecandidateerror getter oniceconnectionstatechange getter onicegatheringstatechange getter onnegotiationneeded @@ -5887,12 +5888,20 @@ setter onconnectionstatechange setter ondatachannel setter onicecandidate + setter onicecandidateerror setter oniceconnectionstatechange setter onicegatheringstatechange setter onnegotiationneeded setter onremovestream setter onsignalingstatechange setter ontrack +interface RTCPeerConnectionIceErrorEvent : Event + attribute @@toStringTag + getter errorCode + getter errorText + getter hostCandidate + getter url + method constructor interface RTCPeerConnectionIceEvent : Event attribute @@toStringTag getter candidate @@ -10794,6 +10803,7 @@ getter onconnectionstatechange getter ondatachannel getter onicecandidate + getter onicecandidateerror getter oniceconnectionstatechange getter onicegatheringstatechange getter onnegotiationneeded @@ -10831,6 +10841,7 @@ setter onconnectionstatechange setter ondatachannel setter onicecandidate + setter onicecandidateerror setter oniceconnectionstatechange setter onicegatheringstatechange setter onnegotiationneeded
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/full-ref.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/full-ref.html new file mode 100644 index 0000000..8b0bbbb --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/full-ref.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <style>body { overflow:hidden; }</style> + <script type="module"> + import * as refTests from './resources/ref-tests.mjs'; + refTests.withDiv(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/full-scroll-500px-ref.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/full-scroll-500px-ref.html new file mode 100644 index 0000000..8b0bbbb --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/full-scroll-500px-ref.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <style>body { overflow:hidden; }</style> + <script type="module"> + import * as refTests from './resources/ref-tests.mjs'; + refTests.withDiv(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/full-scroll-500px.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/full-scroll-500px.html new file mode 100644 index 0000000..df3e9e0 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/full-scroll-500px.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <meta charset="utf8"> + <title>Creates more than a screenful of divs and scrolls down.</title> + <style>body { overflow:hidden; }</style> + <link rel="author" title="Fergal Daly" href="mailto:fergal@chromium.org"> + <link rel="match" href="full-scroll-500px-ref.html"> + <script type="module"> + import 'std:elements/virtual-scroller'; + import * as refTests from './resources/ref-tests.mjs'; + refTests.withVirtualScroller(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/full.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/full.html new file mode 100644 index 0000000..da670a20 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/full.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <meta charset="utf8"> + <title>Creates more than a screenful of divs.</title> + <style>body { overflow:hidden; }</style> + <link rel="author" title="Fergal Daly" href="mailto:fergal@chromium.org"> + <link rel="match" href="full-scroll-500px-ref.html"> + <script type="module"> + import 'std:elements/virtual-scroller'; + import * as refTests from './resources/ref-tests.mjs'; + refTests.withVirtualScroller(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element-ref.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element-ref.html new file mode 100644 index 0000000..8b0bbbb --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element-ref.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <style>body { overflow:hidden; }</style> + <script type="module"> + import * as refTests from './resources/ref-tests.mjs'; + refTests.withDiv(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element-scroll-into-view-ref.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element-scroll-into-view-ref.html new file mode 100644 index 0000000..8b0bbbb --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element-scroll-into-view-ref.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <style>body { overflow:hidden; }</style> + <script type="module"> + import * as refTests from './resources/ref-tests.mjs'; + refTests.withDiv(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element-scroll-into-view.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element-scroll-into-view.html new file mode 100644 index 0000000..7c3e3aa0 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element-scroll-into-view.html
@@ -0,0 +1,16 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <meta charset="utf8"> + <title> + Creates more than a screenful of divs and moves the first to the + end and scrolls to it. + </title> + <style>body { overflow:hidden; }</style> + <link rel="author" title="Fergal Daly" href="mailto:fergal@chromium.org"> + <link rel="match" href="full-scroll-500px-ref.html"> + <script type="module"> + import 'std:elements/virtual-scroller'; + import * as refTests from './resources/ref-tests.mjs'; + refTests.withVirtualScroller(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element.html new file mode 100644 index 0000000..f35de120 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/move-element.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <meta charset="utf8"> + <title>Creates more than a screenful of divs and moves the first to the end.</title> + <style>body { overflow:hidden; }</style> + <link rel="author" title="Fergal Daly" href="mailto:fergal@chromium.org"> + <link rel="match" href="full-scroll-500px-ref.html"> + <script type="module"> + import 'std:elements/virtual-scroller'; + import * as refTests from './resources/ref-tests.mjs'; + refTests.withVirtualScroller(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/part-ref.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/part-ref.html new file mode 100644 index 0000000..8b0bbbb --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/part-ref.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <style>body { overflow:hidden; }</style> + <script type="module"> + import * as refTests from './resources/ref-tests.mjs'; + refTests.withDiv(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/part.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/part.html new file mode 100644 index 0000000..f3996765 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/part.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <meta charset="utf8"> + <title>Creates less than a screenful of divs.</title> + <style>body { overflow:hidden; }</style> + <link rel="author" title="Fergal Daly" href="mailto:fergal@chromium.org"> + <link rel="match" href="full-scroll-500px-ref.html"> + <script type="module"> + import 'std:elements/virtual-scroller'; + import * as refTests from './resources/ref-tests.mjs'; + refTests.withVirtualScroller(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/resize-ref.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/resize-ref.html new file mode 100644 index 0000000..8b0bbbb --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/resize-ref.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <style>body { overflow:hidden; }</style> + <script type="module"> + import * as refTests from './resources/ref-tests.mjs'; + refTests.withDiv(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/resize.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/resize.html new file mode 100644 index 0000000..e492fc60 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/resize.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <meta charset="utf8"> + <title>Creates more than a screenful of divs and then resizes the container.</title> + <style>body { overflow:hidden; }</style> + <link rel="author" title="Fergal Daly" href="mailto:fergal@chromium.org"> + <link rel="match" href="full-scroll-500px-ref.html"> + <script type="module"> + import 'std:elements/virtual-scroller'; + import * as refTests from './resources/ref-tests.mjs'; + refTests.withVirtualScroller(refTests.testFullScroll500px); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/resources/helpers.mjs b/third_party/blink/web_tests/wpt_internal/virtual-scroller/resources/helpers.mjs new file mode 100644 index 0000000..ed09be3 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/resources/helpers.mjs
@@ -0,0 +1,71 @@ +/** + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + * + * @fileoverview Helpers for testing virtual-scroller code. + * @package + */ + +/** + * Creates a DIV with id and textContent set to |id|. + */ +export function div(id) { + const d = document.createElement('div'); + d.id = id; + d.textContent = id; + return d; +} + +/** + * Creates a container DIV with |n| child DIVs with their margin=|margin|. + */ +export function appendDivs(container, n, margin) { + for (let i = 0; i < n; i++) { + const d = div('d' + i); + d.style.margin = margin; + container.append(d); + } +} + +/* + * Creates an element, appends it to the BODY, passes it to |callback| and + * removes it in a finally. + */ +export function withElement(name, callback) { + const element = document.createElement(name); + try { + document.body.appendChild(element); + callback(element); + } finally { + element.remove(); + } +} + +/** + * Remove the reftest-wait class from the HTML element. +*/ +export function stopWaiting() { + document.documentElement.classList.remove('reftest-wait'); +} + +/** + * Generate a string with |n| words. + */ +export function words(n) { + let w = ''; + for (let i = 0; i < n; i++) { + w += 'word '; + } + return w; +} + +/** + * Allow the current frame to end and then call |callback| asap in the next + * frame. +*/ +export function nextFrame(callback) { + window.requestAnimationFrame(() => { + window.setTimeout(callback, 0); + }); +}
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/resources/ref-tests.mjs b/third_party/blink/web_tests/wpt_internal/virtual-scroller/resources/ref-tests.mjs new file mode 100644 index 0000000..358259b2 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/resources/ref-tests.mjs
@@ -0,0 +1,88 @@ +/** + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + * + * @fileoverview Runs a ref-test based on the filename. + * @package + */ + +import * as helpers from './helpers.mjs'; + +const LESS_THAN_SCREENFUL = 5; +const MORE_THAN_SCREENFUL = 100; +const WORDS_IN_PARAGRAPH = 50; + +export function testFull(target) { + helpers.appendDivs(target, MORE_THAN_SCREENFUL, '10px'); + helpers.stopWaiting(); +} + +export function testFullScroll500px(target) { + helpers.appendDivs(target, MORE_THAN_SCREENFUL, '10px'); + helpers.nextFrame(() => { + window.scrollBy(0, 500); // eslint-disable-line no-magic-numbers + helpers.stopWaiting(); + }); +}; + +export function testMoveElement(target) { + helpers.appendDivs(target, MORE_THAN_SCREENFUL, '10px'); + helpers.nextFrame(() => { + const element = target.firstElementChild; + target.appendChild(element); + helpers.stopWaiting(); + }); +} + +export function testMoveElementScrollIntoView(target) { + helpers.appendDivs(target, MORE_THAN_SCREENFUL, '10px'); + const element = target.firstElementChild; + target.appendChild(element); + helpers.nextFrame(() => { + element.scrollIntoView(); + helpers.stopWaiting(); + }); +} + +export function testPart(target) { + helpers.appendDivs(target, LESS_THAN_SCREENFUL, '10px'); + helpers.stopWaiting(); +} + +export function testResize(target) { + target.style.overflow = 'hidden'; + target.style.width = '500px'; + helpers.appendDivs(target, MORE_THAN_SCREENFUL, '10px'); + const text = helpers.words(WORDS_IN_PARAGRAPH); + for (const e of target.children) { + e.innerText = text; + } + helpers.nextFrame(() => { + target.style.width = '300px'; + helpers.stopWaiting(); + }); +} + +/** + * Runs |test| with a <virtual-scroller>, waiting until the custom element is + * defined. +*/ +export function withVirtualScroller(test) { + customElements.whenDefined('virtual-scroller').then(() => { + runTest("virtual-scroller", test); + }); +} + +/** + * Runs |test| with a <div>. +*/ +export function withDiv(test) { + runTest("div", test); +} + +function runTest(elementName, test) { + const element = document.createElement(elementName); + document.body.appendChild(element); + test(element); +}
diff --git a/third_party/blink/web_tests/xr/events_deviceconnect.html b/third_party/blink/web_tests/xr/events_deviceconnect.html index 95633fb3..a03f7a1 100644 --- a/third_party/blink/web_tests/xr/events_deviceconnect.html +++ b/third_party/blink/web_tests/xr/events_deviceconnect.html
@@ -9,28 +9,21 @@ <canvas id="webgl-canvas"></canvas> <script> promise_test((t) => { - let watcherDone = new Event("watcherdone"); - let eventWatcher = new EventWatcher(t, navigator.xr, ["devicechange", - "watcherdone"]); + let eventWatcher = new EventWatcher(t, navigator.xr, ["devicechange"]); - // The event should fire when a listener is added even if the devices are not - // explicity queried with navigator.xr.requestDevice(). + // The event should fire when a listener is added (which EventWatcher does) + // even if the devices are not explicity queried with navigator.xr.requestDevice(). // Note: This behaviour is chrome specific, the spec does not explicitly // state when devicechange events should occur. - function onDeviceChange() { - navigator.xr.dispatchEvent(watcherDone); - }; - navigator.xr.addEventListener("devicechange", onDeviceChange, false); - - let promise = eventWatcher.wait_for(["devicechange", "watcherdone"]); + let promise = eventWatcher.wait_for(["devicechange"]); // Timeout here is required because addEventListener sends a call to mojo to // register the listener on the backend, which doesn't go through until the // javascript pauses. setTimeout(() => { navigator.xr.test.simulateDeviceConnection(TRACKED_IMMERSIVE_DEVICE); - }, 100); + }, 0); return promise;
diff --git a/third_party/boringssl/BUILD.generated.gni b/third_party/boringssl/BUILD.generated.gni index c07e0ecc..6556852 100644 --- a/third_party/boringssl/BUILD.generated.gni +++ b/third_party/boringssl/BUILD.generated.gni
@@ -175,6 +175,7 @@ "src/crypto/refcount_lock.c", "src/crypto/rsa_extra/rsa_asn1.c", "src/crypto/rsa_extra/rsa_print.c", + "src/crypto/siphash/siphash.c", "src/crypto/stack/stack.c", "src/crypto/thread.c", "src/crypto/thread_none.c", @@ -349,6 +350,7 @@ "src/include/openssl/rsa.h", "src/include/openssl/safestack.h", "src/include/openssl/sha.h", + "src/include/openssl/siphash.h", "src/include/openssl/span.h", "src/include/openssl/stack.h", "src/include/openssl/thread.h",
diff --git a/third_party/boringssl/BUILD.generated_tests.gni b/third_party/boringssl/BUILD.generated_tests.gni index 2b07a8f..1b09035 100644 --- a/third_party/boringssl/BUILD.generated_tests.gni +++ b/third_party/boringssl/BUILD.generated_tests.gni
@@ -75,6 +75,7 @@ "src/crypto/refcount_test.cc", "src/crypto/rsa_extra/rsa_test.cc", "src/crypto/self_test.cc", + "src/crypto/siphash/siphash_test.cc", "src/crypto/stack/stack_test.cc", "src/crypto/test/abi_test.cc", "src/crypto/test/file_test_gtest.cc", @@ -135,6 +136,7 @@ "src/crypto/fipsmodule/rand/ctrdrbg_vectors.txt", "src/crypto/hmac_extra/hmac_tests.txt", "src/crypto/poly1305/poly1305_tests.txt", + "src/crypto/siphash/siphash_tests.txt", "src/crypto/x509/many_constraints.pem", "src/crypto/x509/many_names1.pem", "src/crypto/x509/many_names2.pem",
diff --git a/tools/android/roll/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy b/tools/android/roll/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy index e820dc9..0f3fe2b 100644 --- a/tools/android/roll/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy +++ b/tools/android/roll/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy
@@ -239,6 +239,10 @@ } } switch(dependencyId) { + case 'android_arch_lifecycle_runtime_java': + sb.append(' # https://crbug.com/887942#c1\n') + sb.append(' ignore_proguard_configs = true\n') + break case 'com_android_support_support_compat': case 'com_android_support_support_media_compat': // Target has AIDL, but we don't support it yet: http://crbug.com/644439
diff --git a/tools/android/roll/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy b/tools/android/roll/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy index fdc6ae3a..6fb7cee4 100644 --- a/tools/android/roll/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy +++ b/tools/android/roll/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy
@@ -52,6 +52,9 @@ url: "https://github.com/google-ar/arcore-android-sdk", licenseUrl: "https://raw.githubusercontent.com/google-ar/arcore-android-sdk/master/LICENSE", licenseName: "Apache 2.0"), + 'javax_annotation_jsr250_api': new DependencyDescription( + licenseName: "CDDLv1.0", + licensePath: "licenses/CDDLv1.0.txt"), 'net_sf_kxml_kxml2': new DependencyDescription( licenseUrl: "https://raw.githubusercontent.com/stefanhaustein/kxml2/master/license.txt", licenseName: "MIT"),
diff --git a/tools/android/roll/android_deps/fetch_all.py b/tools/android/roll/android_deps/fetch_all.py index e537896..196a8c9 100755 --- a/tools/android/roll/android_deps/fetch_all.py +++ b/tools/android/roll/android_deps/fetch_all.py
@@ -340,8 +340,8 @@ parser.add_argument('--reset-workspace', action='store_true', help='Reset your Chromium workspace to its HEAD state, but preserves ' 'build.gradle changes. Use this to undo previous --update-all changes.') - parser.add_argument('--log-level', help='Set log level (e.g. \'info\' or ' - '\'debug\')') + parser.add_argument( + '--debug', actino='store_true', help='Enable debug logging') args = parser.parse_args() # Determine Chromium source tree. @@ -373,8 +373,8 @@ logging.basicConfig(format='%(message)s') logger = logging.getLogger() - if args.log_level: - logger.setLevel(args.log_level.upper()) + if args.debug: + logger.setLevel('DEBUG') # Handle --reset-workspace here. if args.reset_workspace: @@ -435,6 +435,9 @@ 'setupRepository', '--stacktrace', ] + if args.debug: + gradle_cmd.append('--debug') + RunCommand(gradle_cmd) libs_dir = os.path.join(build_dir, args.git_dir, _ANDROID_DEPS_LIBS_SUBDIR)
diff --git a/tools/idl_parser/idl_lexer.py b/tools/idl_parser/idl_lexer.py index b7e0674..ba13713 100755 --- a/tools/idl_parser/idl_lexer.py +++ b/tools/idl_parser/idl_lexer.py
@@ -61,7 +61,6 @@ 'callback' : 'CALLBACK', 'const' : 'CONST', 'creator' : 'CREATOR', - 'Date' : 'DATE', 'deleter' : 'DELETER', 'dictionary' : 'DICTIONARY', 'DOMString' : 'DOMSTRING', @@ -90,7 +89,6 @@ 'partial' : 'PARTIAL', 'Promise' : 'PROMISE', 'readonly' : 'READONLY', - 'RegExp' : 'REGEXP', 'record' : 'RECORD', 'required' : 'REQUIRED', 'sequence' : 'SEQUENCE',
diff --git a/tools/idl_parser/idl_parser.py b/tools/idl_parser/idl_parser.py index 17f05c3..8ab0d042 100755 --- a/tools/idl_parser/idl_parser.py +++ b/tools/idl_parser/idl_parser.py
@@ -877,7 +877,7 @@ if len(p) > 2: p[0] = ListFromConcat(p[2], p[3]) - # Moved BYTESTRING, DOMSTRING, OBJECT, DATE, REGEXP to PrimitiveType + # Moved BYTESTRING, DOMSTRING, OBJECT to PrimitiveType # Moving all built-in types into PrimitiveType makes it easier to # differentiate between them and 'identifier', since p[1] would be a string in # both cases. @@ -909,7 +909,7 @@ p[0] = p[1] - # Added StringType, OBJECT, DATE, REGEXP + # Added StringType, OBJECT def p_PrimitiveType(self, p): """PrimitiveType : UnsignedIntegerType | UnrestrictedFloatType @@ -917,9 +917,7 @@ | BOOLEAN | BYTE | OCTET - | OBJECT - | DATE - | REGEXP""" + | OBJECT""" if type(p[1]) == str: p[0] = self.BuildNamed('PrimitiveType', p, 1) else:
diff --git a/tools/idl_parser/test_lexer/keywords.in b/tools/idl_parser/test_lexer/keywords.in index c175d28..3e2b574b 100644 --- a/tools/idl_parser/test_lexer/keywords.in +++ b/tools/idl_parser/test_lexer/keywords.in
@@ -6,7 +6,6 @@ CALLBACK callback CONST const CREATOR creator -DATE Date DELETER deleter DICTIONARY dictionary DOMSTRING DOMString @@ -33,7 +32,6 @@ PROMISE Promise READONLY readonly RECORD record -REGEXP RegExp REQUIRED required SEQUENCE sequence SETLIKE setlike
diff --git a/tools/idl_parser/test_lexer/values.in b/tools/idl_parser/test_lexer/values.in index ad285895c..a4d96d7 100644 --- a/tools/idl_parser/test_lexer/values.in +++ b/tools/idl_parser/test_lexer/values.in
@@ -56,3 +56,5 @@ identifier include-hyphen identifier _leading_underscore identifier -leading_hyphen +identifier Date +identifier RegExp
diff --git a/tools/idl_parser/test_parser/typedef_web.idl b/tools/idl_parser/test_parser/typedef_web.idl index 177e7ab..13cf2033 100644 --- a/tools/idl_parser/test_parser/typedef_web.idl +++ b/tools/idl_parser/test_parser/typedef_web.idl
@@ -92,13 +92,6 @@ typedef object MyObject; /** TREE - *Typedef(MyDate) - * Type() - * PrimitiveType(Date) - */ -typedef Date MyDate; - -/** TREE *Typedef(MyFloat) * Type() * PrimitiveType(float) @@ -180,3 +173,10 @@ * ExtAttribute(Clamp) */ typedef ([TreatNullAs=EmptyString] DOMString or [Clamp] long) MyAnnotationInUnion; + +/** TREE + *Typedef(Date) + * Type() + * PrimitiveType(double) + */ +typedef double Date;
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index a41dee6..f8a6504 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -3406,6 +3406,13 @@ <int value="3" label="Cancelled"/> </enum> +<enum name="AutofillAssistantPaymentRequestPrefilled"> + <int value="0" label="Initially complete & Success"/> + <int value="1" label="Initially incomplete & Success"/> + <int value="2" label="Initially complete & Failure"/> + <int value="3" label="Initially incomplete & Failure"/> +</enum> + <enum name="AutofillCardholderNameFixFlowPromptEvent"> <int value="0" label="Shown"/> <int value="1" label="Accepted"/> @@ -17318,7 +17325,7 @@ <int value="515" label="PluginVmLicenseKey"/> <int value="516" label="ExtensionAllowInsecureUpdates"/> <int value="517" label="BrowserSwitcherEnabled"/> - <int value="518" label="CertificateManagementAllowed"/> + <int value="518" label="ClientCertificateManagementAllowed"/> <int value="519" label="BrowserSwitcherKeepLastChromeTab"/> <int value="520" label="DeviceRebootOnUserSignout"/> <int value="521" label="ForceNetworkInProcess"/> @@ -17371,6 +17378,7 @@ <int value="570" label="UserFeedbackAllowed"/> <int value="571" label="DevicePowerwashAllowed"/> <int value="572" label="ExternalPrintServers"/> + <int value="573" label="SelectToSpeakEnabled"/> </enum> <enum name="EnterprisePolicyInvalidations"> @@ -33685,6 +33693,7 @@ <int value="-1930720286" label="nacl-debug-mask"/> <int value="-1928198763" label="enable-async-dns"/> <int value="-1925117279" label="disable-quic-https"/> + <int value="-1925106340" label="CameraSystemWebApp:disabled"/> <int value="-1919199528" label="AlwaysShowServerCardsInSyncTransport:disabled"/> <int value="-1916060206" label="enable-display-zoom-setting"/> @@ -34623,6 +34632,7 @@ <int value="-633274640" label="WebRTCPipeWireCapturer:enabled"/> <int value="-632030508" label="NativeWindowNavButtons:disabled"/> <int value="-631740127" label="inert-visual-viewport"/> + <int value="-631614101" label="CameraSystemWebApp:enabled"/> <int value="-624221121" label="CommandLineOnNonRooted:enabled"/> <int value="-623364791" label="ClickToCallReceiver:disabled"/> <int value="-622685174" label="enable-pdf-material-ui"/> @@ -35121,6 +35131,7 @@ <int value="91938915" label="enable-suggestions-service"/> <int value="92327255" label="DisplayMoveWindowAccels:disabled"/> <int value="93832899" label="NtpCustomizationMenuV2:enabled"/> + <int value="97091906" label="AutofillSaveCardShowNoThanks:enabled"/> <int value="98134240" label="material-design-ink-drop-animation-speed"/> <int value="98218116" label="ContextualSearchLongpressResolve:disabled"/> <int value="99177659" label="OmniboxUICuesForSearchHistoryMatches:disabled"/> @@ -35485,6 +35496,7 @@ <int value="652561231" label="CustomContextMenu:enabled"/> <int value="656864700" label="FillOnAccountSelectHttp:disabled"/> <int value="659086147" label="OverlayScrollbarFlashWhenMouseEnter:enabled"/> + <int value="661020875" label="AutofillSaveCardShowNoThanks:disabled"/> <int value="663027937" label="NewTabPageCustomLinks:enabled"/> <int value="663069508" label="TabToGTSAnimation:enabled"/> <int value="663294302" label="ForceUseAPDownloadProtection:disabled"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 842d6ccc2..4a3ecc5 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -1437,6 +1437,18 @@ </summary> </histogram> +<histogram name="Android.AutofillAssistant.PaymentRequest.Prefilled" + enum="AutofillAssistantPaymentRequestPrefilled" expires_after="2020-01-25"> + <owner>arbesser@google.com</owner> + <owner>mcarlen@chromium.org</owner> + <summary> + Reports whether the autofill assistant payment request was successfully + completed (i.e., the continue button was tapped) or not, and whether the + payment request was initially pre-filled completely or not. This is recorded + every time the user sees the autofill assistant payment request. + </summary> +</histogram> + <histogram name="Android.BackgroundTaskScheduler.TaskCanceled" enum="BackgroundTaskId"> <owner>fgorski@chromium.org</owner> @@ -6365,7 +6377,7 @@ </histogram> <histogram name="Ash.Login.Login.UserClicks" enum="LoginScreenUserClickTarget" - expires_after="M77"> + expires_after="M82"> <owner>agawronska@google.com</owner> <summary> The numbers of times that users click on the shelf buttons and trays on the @@ -23966,7 +23978,8 @@ </summary> </histogram> -<histogram name="Cryptohome.MigrationUI.ConsumedBatteryPercent" units="%"> +<histogram name="Cryptohome.MigrationUI.ConsumedBatteryPercent" units="%" + expires_after="2020-07-01"> <owner>fukino@chromium.org</owner> <summary> The amount of consumed battery level during cryptohome encryption migration. @@ -23977,7 +23990,7 @@ </histogram> <histogram name="Cryptohome.MigrationUI.FirstScreen" - enum="MigrationUIFirstScreen"> + enum="MigrationUIFirstScreen" expires_after="2020-07-01"> <owner>fukino@chromium.org</owner> <summary> The first screen in the encryption migration UI, which is shown when a user @@ -23986,7 +23999,7 @@ </histogram> <histogram name="Cryptohome.MigrationUI.MigrationResult" - enum="MigrationUIMigrationResult" expires_after="M77"> + enum="MigrationUIMigrationResult" expires_after="2020-07-01"> <owner>fukino@chromium.org</owner> <summary> The result of encryption migration from eCryptfs to Ext4 dircrypto. The @@ -23996,7 +24009,7 @@ </histogram> <histogram name="Cryptohome.MigrationUI.RemoveCryptohomeResult" - enum="MigrationUIRemoveCryptohomeResult"> + enum="MigrationUIRemoveCryptohomeResult" expires_after="2020-07-01"> <owner>fukino@chromium.org</owner> <summary> The result of the removal of user's cryptohome. When the migration UI is @@ -24007,7 +24020,7 @@ </histogram> <histogram name="Cryptohome.MigrationUI.UserChoice" - enum="MigrationUIUserChoice"> + enum="MigrationUIUserChoice" expires_after="2020-07-01"> <owner>fukino@chromium.org</owner> <summary> User's choice when the system is ready to migrate encryption. The user can @@ -24016,7 +24029,8 @@ </summary> </histogram> -<histogram name="Cryptohome.MigrationUI.VisibleScreen" enum="MigrationUIScreen"> +<histogram name="Cryptohome.MigrationUI.VisibleScreen" enum="MigrationUIScreen" + expires_after="2020-07-01"> <owner>fukino@chromium.org</owner> <summary> How many times each screen in migration UI is shown to the user. A screen is @@ -33157,6 +33171,75 @@ </summary> </histogram> +<histogram name="Enterprise.FCMInvalidationService.DevicePolicyInvalidations" + enum="EnterprisePolicyInvalidations" expires_after="2020-01-01"> + <owner>askaraitzhan@google.com</owner> + <owner>isandrk@chromium.org</owner> + <summary> + Events for counting device policy invalidations received with and without + payloads. Invalidations indicate that a policy has been updated and should + be refreshed. Payloads provide context about the policy update, but may be + absent if dropped by the invalidation service. Subset of + "Enterprise.DevicePolicyInvalidations". Gets recorded only when + FCMInvalidationService is used as InvalidationService; + </summary> +</histogram> + +<histogram name="Enterprise.FCMInvalidationService.DevicePolicyRefresh" + enum="EnterprisePolicyRefresh" expires_after="2020-01-01"> + <owner>askaraitzhan@google.com</owner> + <owner>isandrk@chromium.org</owner> + <summary> + Events measuring effectiveness of refreshing device policy when + invalidations are received from a service. For each refresh, indicates + whether the policy changed, and whether the policy was invalidated at the + time of the refresh. Subset of "Enterprise.DevicePolicyRefresh". + Gets recorded only when FCMInvalidationService is used as + InvalidationService. + </summary> +</histogram> + +<histogram name="Enterprise.FCMInvalidationService.PolicyInvalidations" + enum="EnterprisePolicyInvalidations" expires_after="2020-01-01"> + <owner>askaraitzhan@google.com</owner> + <owner>isandrk@chromium.org</owner> + <summary> + Events for counting user policy invalidations received with and without + payloads. Invalidations indicate that a policy has been updated and should + be refreshed. Payloads provide context about the policy update, but may be + absent if dropped by the invalidation service. Subset of + "Enterprise.PolicyInvalidations". Gets recorded only when + FCMInvalidationService is used as InvalidationService. + </summary> +</histogram> + +<histogram + name="Enterprise.FCMInvalidationService.PolicyInvalidationsRegistrationResult" + enum="BooleanSuccess" expires_after="2020-01-01"> + <owner>askaraitzhan@google.com</owner> + <owner>isandrk@chromium.org</owner> + <summary> + Tracks the result of registration for policy invalidations. It will fail + when duplicate invalidation names are used for different policies due to + http://b/119860379. Subset of + "Enterprise.PolicyInvalidationsRegistrationResult". Gets recorded + only when FCMInvalidationService is used as InvalidationService. + </summary> +</histogram> + +<histogram name="Enterprise.FCMInvalidationService.PolicyRefresh" + enum="EnterprisePolicyRefresh" expires_after="2020-01-01"> + <owner>askaraitzhan@google.com</owner> + <owner>isandrk@chromium.org</owner> + <summary> + Events measuring effectiveness of refreshing user policy when invalidations + are received from a service. For each refresh, indicates whether the policy + changed, and whether the policy was invalidated at the time of the refresh. + Subset of "Enterprise.PolicyRefresh". Gets recorded only when + FCMInvalidationService is used as InvalidationService. + </summary> +</histogram> + <histogram name="Enterprise.InitialEnrollmentRequirement" enum="EnterpriseInitialEnrollmentRequirement" expires_after="M77"> <owner>pmarko@chromium.org</owner> @@ -33357,7 +33440,7 @@ </histogram> <histogram name="Enterprise.PolicyRefresh" enum="EnterprisePolicyRefresh" - expires_after="M77"> + expires_after="2020-01-01"> <owner>mnissler@chromium.org</owner> <summary> Events measuring effectiveness of refreshing user policy when invalidations @@ -33490,6 +33573,75 @@ </summary> </histogram> +<histogram name="Enterprise.TiclInvalidationService.DevicePolicyInvalidations" + enum="EnterprisePolicyInvalidations" expires_after="2020-01-01"> + <owner>askaraitzhan@google.com</owner> + <owner>isandrk@chromium.org</owner> + <summary> + Events for counting device policy invalidations received with and without + payloads. Invalidations indicate that a policy has been updated and should + be refreshed. Payloads provide context about the policy update, but may be + absent if dropped by the invalidation service. Subset of + "Enterprise.DevicePolicyInvalidations". Gets recorded only when + TiclInvalidationService is used as InvalidationService; + </summary> +</histogram> + +<histogram name="Enterprise.TiclInvalidationService.DevicePolicyRefresh" + enum="EnterprisePolicyRefresh" expires_after="2020-01-01"> + <owner>askaraitzhan@google.com</owner> + <owner>isandrk@chromium.org</owner> + <summary> + Events measuring effectiveness of refreshing device policy when + invalidations are received from a service. For each refresh, indicates + whether the policy changed, and whether the policy was invalidated at the + time of the refresh. Subset of "Enterprise.DevicePolicyRefresh". + Gets recorded only when TiclInvalidationService is used as + InvalidationService. + </summary> +</histogram> + +<histogram name="Enterprise.TiclInvalidationService.PolicyInvalidations" + enum="EnterprisePolicyInvalidations" expires_after="2020-01-01"> + <owner>askaraitzhan@google.com</owner> + <owner>isandrk@chromium.org</owner> + <summary> + Events for counting user policy invalidations received with and without + payloads. Invalidations indicate that a policy has been updated and should + be refreshed. Payloads provide context about the policy update, but may be + absent if dropped by the invalidation service. Subset of + "Enterprise.PolicyInvalidations". Recorded only when + TiclInvalidationService was used as InvalidationService. + </summary> +</histogram> + +<histogram + name="Enterprise.TiclInvalidationService.PolicyInvalidationsRegistrationResult" + enum="BooleanSuccess" expires_after="2020-01-01"> + <owner>askaraitzhan@google.com</owner> + <owner>isandrk@chromium.org</owner> + <summary> + Tracks the result of registration for policy invalidations. It will fail + when duplicate invalidation names are used for different policies due to + http://b/119860379. Subset of + "Enterprise.PolicyInvalidationsRegistrationResult". Gets recorded + only when TiclInvalidationService is used as InvalidationService. + </summary> +</histogram> + +<histogram name="Enterprise.TiclInvalidationService.PolicyRefresh" + enum="EnterprisePolicyRefresh" expires_after="2020-01-01"> + <owner>askaraitzhan@google.com</owner> + <owner>isandrk@chromium.org</owner> + <summary> + Events measuring effectiveness of refreshing user policy when invalidations + are received from a service. For each refresh, indicates whether the policy + changed, and whether the policy was invalidated at the time of the refresh. + Subset of "Enterprise.PolicyRefresh". Recorded only when + TiclInvalidationService was used as InvalidationService. + </summary> +</histogram> + <histogram name="Enterprise.UploadJobSuccess" enum="EnterpriseUploadJobSuccess"> <owner>poromov@chromium.org</owner> <summary> @@ -57537,7 +57689,8 @@ <histogram name="Media.MSE.AudioCodec" enum="MSECodec" expires_after="never"> <!-- expires-never: Codec support planning metric. --> - <owner>acolwell@chromium.org</owner> + <owner>wolenetz@chromium.org</owner> + <owner>media-dev@chromium.org</owner> <summary> Audio codec used in Media Source Extensions playback. Set when AddId() is called during playback. @@ -57569,8 +57722,9 @@ </histogram> <histogram name="Media.MSE.DemuxerDestructionTime" units="ms" - expires_after="M77"> + expires_after="M82"> <owner>wolenetz@chromium.org</owner> + <owner>media-dev@chromium.org</owner> <summary> Amount of time taken to destroy one ChunkDemuxer object, not including initial background task scheduling delay. @@ -57752,14 +57906,19 @@ <histogram name="Media.MSE.VideoCodec" enum="MSECodec" expires_after="never"> <!-- expires-never: Codec support planning metric. --> - <owner>acolwell@chromium.org</owner> + <owner>wolenetz@chromium.org</owner> + <owner>media-dev@chromium.org</owner> <summary> Video codec used in Media Source Extensions playback. Set when AddId() is called during playback. </summary> </histogram> -<histogram name="Media.MSE.VideoCodec.MP4" enum="MSECodec" expires_after="M77"> +<histogram name="Media.MSE.VideoCodec.MP4" enum="MSECodec" + expires_after="never"> +<!-- expires-never: Codec and container support planning metric. --> + + <owner>wolenetz@chromium.org</owner> <owner>media-dev@chromium.org</owner> <summary> Video codec used in Media Source Extensions playback if the media container @@ -57767,7 +57926,11 @@ </summary> </histogram> -<histogram name="Media.MSE.VideoCodec.WebM" enum="MSECodec" expires_after="M77"> +<histogram name="Media.MSE.VideoCodec.WebM" enum="MSECodec" + expires_after="never"> +<!-- expires-never: Codec and container support planning metric. --> + + <owner>wolenetz@chromium.org</owner> <owner>media-dev@chromium.org</owner> <summary> Video codec used in Media Source Extensions playback if the media container @@ -58388,7 +58551,9 @@ </histogram> <histogram name="Media.SRC.VideoCodec.MP4" enum="VideoCodec" - expires_after="M77"> + expires_after="never"> +<!-- expires-never: Codec and container support planning metric. --> + <owner>media-dev@chromium.org</owner> <summary> Video codec used in plain src= (not MSE) HTML5 media if the media container @@ -58397,7 +58562,9 @@ </histogram> <histogram name="Media.SRC.VideoCodec.WebM" enum="VideoCodec" - expires_after="M77"> + expires_after="never"> +<!-- expires-never: Codec and container support planning metric. --> + <owner>media-dev@chromium.org</owner> <summary> Video codec used in plain src= (not MSE) HTML5 media if the media container @@ -61637,6 +61804,9 @@ <histogram name="Memory.MovableStringParkingAction" enum="ParkingAction" expires_after="M77"> + <obsolete> + Deprecated 7/2019. No longer recorded. + </obsolete> <owner>lizeb@chromium.org</owner> <summary> Recorded each time a Movable String is (un)parked, with the context: @@ -61645,6 +61815,9 @@ </histogram> <histogram name="Memory.MovableStringsCount" units="count" expires_after="M77"> + <obsolete> + Deprecated 7/2019. No longer recorded. + </obsolete> <owner>lizeb@chromium.org</owner> <summary> This records the number of movable Javascript source string resources in a @@ -61655,6 +61828,9 @@ <histogram name="Memory.MovableStringsTotalSizeKb" units="KB" expires_after="M77"> + <obsolete> + Deprecated 7/2019. No longer recorded. + </obsolete> <owner>lizeb@chromium.org</owner> <summary> This records the total size of movable Javascript source string resources in @@ -78317,9 +78493,10 @@ </summary> </histogram> -<histogram name="Network.Shill.CumulativeTimeOnline" units="seconds"> +<histogram name="Network.Shill.CumulativeTimeOnline" units="seconds" + expires_after="2020-06-01"> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS device time on line in the previous 24-hour sample period. "On line" means shill believes the device is on the internet. The @@ -78331,10 +78508,10 @@ </histogram> <histogram name="Network.Shill.DailyChosenFractionOnline.Cellular" units="%" - expires_after="M77"> + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS fraction of daily cumulative time on a cellular connection when both cellular and WiFi adaptors are available. Each sample is the ratio of @@ -78345,10 +78522,10 @@ </histogram> <histogram name="Network.Shill.DailyChosenFractionOnline.Wifi" units="%" - expires_after="M77"> + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS fraction of daily cumulative time on a WiFi connection when both cellular and WiFi adaptors are available. Each sample is the ratio of the @@ -78359,10 +78536,10 @@ </histogram> <histogram name="Network.Shill.DailyChosenTimeOnline.Any" units="seconds" - expires_after="M77"> + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS daily cumulative time on line when both cellular and WiFi adaptors are available. Reported only when both kinds of adaptor are present @@ -78372,10 +78549,11 @@ </summary> </histogram> -<histogram name="Network.Shill.DailyChosenTimeOnline.Cellular" units="seconds"> +<histogram name="Network.Shill.DailyChosenTimeOnline.Cellular" units="seconds" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS daily cumulative time on a cellular connection when both cellular and WiFi adaptors are available. Reported only when both kinds of adaptor @@ -78385,10 +78563,11 @@ </summary> </histogram> -<histogram name="Network.Shill.DailyChosenTimeOnline.Wifi" units="seconds"> +<histogram name="Network.Shill.DailyChosenTimeOnline.Wifi" units="seconds" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS daily cumulative time on a WiFi connection when both cellular and WiFi adaptors are available. Reported only when both kinds of adaptor are @@ -78446,8 +78625,10 @@ </summary> </histogram> -<histogram name="Network.Shill.DeviceConnectionStatus" enum="ConnectionStatus"> +<histogram name="Network.Shill.DeviceConnectionStatus" enum="ConnectionStatus" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network performance metric that tracks the connection status of the device. A sample is emitted once every 3 minutes. @@ -78455,8 +78636,9 @@ </histogram> <histogram name="Network.Shill.DeviceRemovedEvent" enum="DeviceTechnologyType" - expires_after="M77"> + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network metric that tracks the network device removed events for each device type. @@ -78493,8 +78675,9 @@ </histogram> <histogram name="Network.Shill.Ethernet.DevicePresenceStatus" - enum="BooleanPresent"> + enum="BooleanPresent" expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network metric that tracks the presence of an Ethernet device in the system. A sample is emitted once every 3 minutes. @@ -78516,8 +78699,9 @@ </histogram> <histogram name="Network.Shill.Ethernet.Disconnect" - enum="NetworkDisconnectType"> + enum="NetworkDisconnectType" expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network usage metric that tracks whether the Ethernet network was disconnected due to an error or was explicitly disconnected by the user. @@ -78540,8 +78724,9 @@ </histogram> <histogram name="Network.Shill.Ethernet.ExpiredLeaseLengthSeconds2" - units="seconds" expires_after="M77"> + units="seconds" expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network performance metric that tracks the length of a lease for an Ethernet network at the time it expired without the DHCP client being @@ -78549,8 +78734,10 @@ </summary> </histogram> -<histogram name="Network.Shill.Ethernet.LinkMonitorBroadcastErrorsAtFailure"> +<histogram name="Network.Shill.Ethernet.LinkMonitorBroadcastErrorsAtFailure" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network performance metric that tracks the number of LinkMonitor broadcast errors that were accrued on an Ethernet network at the time that @@ -78559,8 +78746,9 @@ </histogram> <histogram name="Network.Shill.Ethernet.LinkMonitorFailure" - enum="LinkMonitorFailureType"> + enum="LinkMonitorFailureType" expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS metric that signals the type of failure the LinkMonitor encountered which caused it to stop monitoring an Ethernet network. @@ -78568,8 +78756,9 @@ </histogram> <histogram name="Network.Shill.Ethernet.LinkMonitorResponseTimeSample" - units="ms"> + units="ms" expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network performance metric that tracks the number of milliseconds between an ARP request and a received reply on an Ethernet network. @@ -78577,16 +78766,19 @@ </histogram> <histogram name="Network.Shill.Ethernet.LinkMonitorSecondsToFailure" - units="seconds"> + units="seconds" expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network performance metric that tracks the number of seconds from the start of the LinkMonitor until failure on an Ethernet network. </summary> </histogram> -<histogram name="Network.Shill.Ethernet.LinkMonitorUnicastErrorsAtFailure"> +<histogram name="Network.Shill.Ethernet.LinkMonitorUnicastErrorsAtFailure" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network performance metric that tracks the number of LinkMonitor unicast errors that were accrued on an Ethernet network at the time that the @@ -78594,8 +78786,10 @@ </summary> </histogram> -<histogram name="Network.Shill.Ethernet.PortalAttempts" expires_after="M77"> +<histogram name="Network.Shill.Ethernet.PortalAttempts" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network diagnostic metric sampling the number of portal detection attempts per pass for an Ethernet network. This includes failure, timeout @@ -78603,8 +78797,10 @@ </summary> </histogram> -<histogram name="Network.Shill.Ethernet.PortalAttemptsToOnline"> +<histogram name="Network.Shill.Ethernet.PortalAttemptsToOnline" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network diagnostic metric sampling the total number of portal detection attempts performed for an Ethernet network between the Connected @@ -78613,16 +78809,19 @@ </histogram> <histogram name="Network.Shill.Ethernet.PortalResult" - enum="NetworkPortalResult" expires_after="M77"> + enum="NetworkPortalResult" expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network diagnostic metric sampling the result of portal detections for an Ethernet network. </summary> </histogram> -<histogram name="Network.Shill.Ethernet.TimeOnline" units="seconds"> +<histogram name="Network.Shill.Ethernet.TimeOnline" units="seconds" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network metric sampling the time spent using Ethernet to transport data. These data are mostly useful when summed and compared to TimeOnline @@ -78631,8 +78830,9 @@ </histogram> <histogram name="Network.Shill.Ethernet.TimeToConfig" units="ms" - expires_after="M77"> + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network performance metric sampling the time to join a wired Ethernet network and configure Layer 3 state (typically acquire a DHCP @@ -78641,16 +78841,19 @@ </histogram> <histogram name="Network.Shill.Ethernet.TimeToInitialize" units="ms" - expires_after="M77"> + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network performance metric sampling the time to initialize an Ethernet device. </summary> </histogram> -<histogram name="Network.Shill.Ethernet.TimeToOnline" units="ms"> +<histogram name="Network.Shill.Ethernet.TimeToOnline" units="ms" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network performance metric sampling the time to determine that an Ethernet network is online after configuring Layer 3 state. @@ -78658,8 +78861,9 @@ </histogram> <histogram name="Network.Shill.Ethernet.TimeToPortal" units="ms" - expires_after="M77"> + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network performance metric sampling the time to determine that an Ethernet network is in a captive portal after configuring Layer 3 state. @@ -78677,10 +78881,11 @@ </summary> </histogram> -<histogram name="Network.Shill.MonthlyChosenFractionOnline.Cellular" units="%"> +<histogram name="Network.Shill.MonthlyChosenFractionOnline.Cellular" units="%" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS fraction of monthly cumulative time on a cellular connection when both cellular and WiFi adaptors are available. Each sample is the ratio of @@ -78691,10 +78896,10 @@ </histogram> <histogram name="Network.Shill.MonthlyChosenFractionOnline.Wifi" units="%" - expires_after="M77"> + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS fraction of monthly cumulative time on a WiFi connection when both cellular and WiFi adaptors are available. Each sample is the ratio of the @@ -78705,10 +78910,10 @@ </histogram> <histogram name="Network.Shill.MonthlyChosenTimeOnline.Any" units="seconds" - expires_after="M77"> + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS monthly cumulative time on line when both cellular and WiFi adaptors are available. Reported only when both kinds of adaptor are present @@ -78719,10 +78924,10 @@ </histogram> <histogram name="Network.Shill.MonthlyChosenTimeOnline.Cellular" - units="seconds" expires_after="M77"> + units="seconds" expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS monthly cumulative time on a cellular connection when both cellular and WiFi adaptors are available. Reported only when both kinds of @@ -78733,10 +78938,10 @@ </histogram> <histogram name="Network.Shill.MonthlyChosenTimeOnline.Wifi" units="seconds" - expires_after="M77"> + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> <owner>kirtika@chromium.org</owner> - <owner>semenzato@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS monthly cumulative time on a WiFi connection when both cellular and WiFi adaptors are available. Reported only when both kinds of adaptor @@ -78899,8 +79104,10 @@ </summary> </histogram> -<histogram name="Network.Shill.TimeToDrop" units="seconds" expires_after="M77"> +<histogram name="Network.Shill.TimeToDrop" units="seconds" + expires_after="2020-06-01"> <owner>benchan@chromium.org</owner> + <owner>cros-network-metrics@google.com</owner> <summary> Chrome OS network stability metric sampling the time in seconds between the networking going online to going offline. Offline events due to device @@ -110351,7 +110558,7 @@ </histogram> <histogram name="ResourceReporter.BrowserProcess.MemoryUsage" - enum="ResourceReporterMemoryUsage" expires_after="M77"> + enum="ResourceReporterMemoryUsage" expires_after="M79"> <owner>afakhry@chromium.org</owner> <summary> The system memory usage range reported for the browser process when the @@ -110373,7 +110580,7 @@ </histogram> <histogram name="ResourceReporter.GpuProcess.MemoryUsage" - enum="ResourceReporterMemoryUsage" expires_after="M77"> + enum="ResourceReporterMemoryUsage" expires_after="M79"> <owner>afakhry@chromium.org</owner> <summary> The system's RAM memory usage range reported for the GPU process when the @@ -125203,6 +125410,11 @@ <histogram name="SiteIsolation.IsolateAllSitesProcessCountEstimate" expires_after="M82"> + <obsolete> + Logging code has been removed in M77 - the histogram is no longer useful + since site-per-process has already shipped on desktop in M67 (see + https://crbug.com/810843). + </obsolete> <owner>creis@chromium.org</owner> <summary> The upper bound of the predicted renderer process count if we isolated all @@ -125212,6 +125424,11 @@ <histogram name="SiteIsolation.IsolateAllSitesProcessCountLowerBound" expires_after="M82"> + <obsolete> + Logging code has been removed in M77 - the histogram is no longer useful + since site-per-process has already shipped on desktop in M67 (see + https://crbug.com/810843). + </obsolete> <owner>creis@chromium.org</owner> <summary> The lower bound of the predicted renderer process count if we isolated all @@ -125222,6 +125439,11 @@ <histogram name="SiteIsolation.IsolateAllSitesProcessCountNoLimit" expires_after="M82"> + <obsolete> + Logging code has been removed in M77 - the histogram is no longer useful + since site-per-process has already shipped on desktop in M67 (see + https://crbug.com/810843). + </obsolete> <owner>creis@chromium.org</owner> <summary> The predicted renderer process count if we isolated all sites and if there @@ -125231,6 +125453,11 @@ <histogram name="SiteIsolation.IsolateAllSitesTotalProcessCountEstimate" expires_after="M82"> + <obsolete> + Logging code has been removed in M77 - the histogram is no longer useful + since site-per-process has already shipped on desktop in M67 (see + https://crbug.com/810843). + </obsolete> <owner>creis@chromium.org</owner> <summary> The predicted total process count if we isolated all sites, subject to the @@ -125240,6 +125467,11 @@ <histogram name="SiteIsolation.IsolateExtensionsProcessCountEstimate" expires_after="M77"> + <obsolete> + Logging code has been removed in M77 - the histogram is no longer useful + since isolate-extensions has already shipped in M56 (see + https://crbug.com/545200). + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125251,6 +125483,11 @@ <histogram name="SiteIsolation.IsolateExtensionsProcessCountLowerBound" expires_after="M77"> + <obsolete> + Logging code has been removed in M77 - the histogram is no longer useful + since isolate-extensions has already shipped in M56 (see + https://crbug.com/545200). + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125262,6 +125499,11 @@ <histogram name="SiteIsolation.IsolateExtensionsProcessCountNoLimit" expires_after="M77"> + <obsolete> + Logging code has been removed in M77 - the histogram is no longer useful + since isolate-extensions has already shipped in M56 (see + https://crbug.com/545200). + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125273,6 +125515,11 @@ <histogram name="SiteIsolation.IsolateExtensionsTotalProcessCountEstimate" expires_after="M77"> + <obsolete> + Logging code has been removed in M77 - the histogram is no longer useful + since isolate-extensions has already shipped in M56 (see + https://crbug.com/545200). + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125284,6 +125531,9 @@ <histogram name="SiteIsolation.IsolateHttpsSitesProcessCountEstimate" expires_after="M82"> + <obsolete> + Logging code has been removed in M77. + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125296,6 +125546,9 @@ <histogram name="SiteIsolation.IsolateHttpsSitesProcessCountLowerBound" expires_after="M82"> + <obsolete> + Logging code has been removed in M77. + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125308,6 +125561,9 @@ <histogram name="SiteIsolation.IsolateHttpsSitesProcessCountNoLimit" expires_after="M82"> + <obsolete> + Logging code has been removed in M77. + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125319,6 +125575,9 @@ <histogram name="SiteIsolation.IsolateHttpsSitesTotalProcessCountEstimate" expires_after="M82"> + <obsolete> + Logging code has been removed in M77. + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125330,6 +125589,9 @@ <histogram name="SiteIsolation.IsolateNothingProcessCountEstimate" expires_after="M82"> + <obsolete> + Logging code has been removed in M77. + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125341,6 +125603,9 @@ <histogram name="SiteIsolation.IsolateNothingProcessCountLowerBound" expires_after="M82"> + <obsolete> + Logging code has been removed in M77. + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125353,6 +125618,9 @@ <histogram name="SiteIsolation.IsolateNothingProcessCountNoLimit" expires_after="M82"> + <obsolete> + Logging code has been removed in M77. + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner> @@ -125364,6 +125632,9 @@ <histogram name="SiteIsolation.IsolateNothingTotalProcessCountEstimate" expires_after="M82"> + <obsolete> + Logging code has been removed in M77. + </obsolete> <owner>creis@chromium.org</owner> <owner>lukasza@chromium.org</owner> <owner>site-isolation-dev@chromium.org</owner>
diff --git a/tools/perf/benchmarks/blink_perf.py b/tools/perf/benchmarks/blink_perf.py index 41676e3d..68c8994 100644 --- a/tools/perf/benchmarks/blink_perf.py +++ b/tools/perf/benchmarks/blink_perf.py
@@ -247,6 +247,7 @@ with open(os.path.join(os.path.dirname(__file__), 'blink_perf.js'), 'r') as f: self._blink_perf_js = f.read() + self._is_tracing = False self._extra_chrome_categories = None self._enable_systrace = None @@ -256,9 +257,7 @@ def DidNavigateToPage(self, page, tab): tab.WaitForJavaScriptCondition('testRunner.isWaitingForTelemetry') - tracing_categories = tab.EvaluateJavaScript('testRunner.tracingCategories') - if tracing_categories: - self._StartTracing(tab, tracing_categories) + self._StartTracingIfNeeded(tab) def CustomizeBrowserOptions(self, options): options.AppendExtraBrowserArgs([ @@ -277,13 +276,20 @@ if options.enable_systrace: self._enable_systrace = True - def _StartTracing(self, tab, tracing_categories): + def _StartTracingIfNeeded(self, tab): + tracing_categories = tab.EvaluateJavaScript('testRunner.tracingCategories') + if (not tracing_categories and not self._extra_chrome_categories and + not self._enable_systrace): + return + + self._is_tracing = True config = tracing_config.TracingConfig() config.enable_chrome_trace = True config.chrome_trace_config.category_filter.AddFilterString( 'blink.console') # This is always required for js land trace event - config.chrome_trace_config.category_filter.AddFilterString( - tracing_categories) + if tracing_categories: + config.chrome_trace_config.category_filter.AddFilterString( + tracing_categories) if self._extra_chrome_categories: config.chrome_trace_config.category_filter.AddFilterString( self._extra_chrome_categories) @@ -311,16 +317,17 @@ def ValidateAndMeasurePage(self, page, tab, results): trace_cpu_time_metrics = {} - if tab.EvaluateJavaScript('testRunner.tracingCategories'): + if self._is_tracing: trace_data = tab.browser.platform.tracing_controller.StopTracing() results.AddTraces(trace_data) trace_events_to_measure = tab.EvaluateJavaScript( 'window.testRunner.traceEventsToMeasure') - model = model_module.TimelineModel(trace_data) - renderer_thread = model.GetFirstRendererThread(tab.id) - trace_cpu_time_metrics = _ComputeTraceEventsThreadTimeForBlinkPerf( - model, renderer_thread, trace_events_to_measure) + if trace_events_to_measure: + model = model_module.TimelineModel(trace_data) + renderer_thread = model.GetFirstRendererThread(tab.id) + trace_cpu_time_metrics = _ComputeTraceEventsThreadTimeForBlinkPerf( + model, renderer_thread, trace_events_to_measure) log = tab.EvaluateJavaScript('document.getElementById("log").innerHTML')
diff --git a/tools/perf/benchmarks/blink_perf_unittest.py b/tools/perf/benchmarks/blink_perf_unittest.py index 9a6c13c..2223ab7 100644 --- a/tools/perf/benchmarks/blink_perf_unittest.py +++ b/tools/perf/benchmarks/blink_perf_unittest.py
@@ -152,6 +152,16 @@ 'lifecycle-methods.html'), options=self._options) self.assertFalse(results.had_failures) + self.assertEquals(len(list(results.IterRunsWithTraces())), 0) + + def testExtraChromeCategories(self): + self._options.extra_chrome_categories = 'cc,blink' + results = self.RunMeasurement(measurement=self._measurement, + ps=self._CreateStorySetForTestFile( + 'lifecycle-methods.html'), + options=self._options) + self.assertFalse(results.had_failures) + self.assertEquals(len(list(results.IterRunsWithTraces())), 1) # pylint: disable=protected-access
diff --git a/tools/perf/benchmarks/media.py b/tools/perf/benchmarks/media.py index 9e94ff3..85b7b33 100644 --- a/tools/perf/benchmarks/media.py +++ b/tools/perf/benchmarks/media.py
@@ -2,8 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import re - from core import perf_benchmark from telemetry import benchmark @@ -17,12 +15,6 @@ # TODO(rnephew): Revisit the re-enabled benchmarks on Wed, Aug 8 2017. -# Regex to filter out a few names of statistics supported by -# Histogram.getStatisticScalar(), see: -# https://github.com/catapult-project/catapult/blob/d4179a05/tracing/tracing/value/histogram.html#L645 pylint: disable=line-too-long -_IGNORED_STATS_RE = re.compile( - r'(?<!dump)(?<!process)_(std|count|max|min|sum|pct_\d{4}(_\d+)?)$') - class _MediaBenchmark(perf_benchmark.PerfBenchmark): """Base class for TBMv2-based media benchmarks (MediaDesktop and @@ -51,13 +43,6 @@ 'memoryMetric']) return options - @classmethod - def ShouldAddValue(cls, name, from_first_story_run): - del from_first_story_run # unused - # TODO(crbug.com/610962): Remove this stopgap when the perf dashboard - # is able to cope with the data load generated by TBMv2 metrics. - return not _IGNORED_STATS_RE.search(name) - @benchmark.Info(emails=['dalecurtis@chromium.org'], component='Internals>Media')
diff --git a/tools/perf/benchmarks/memory.py b/tools/perf/benchmarks/memory.py index 957f2d56..d28deb31 100644 --- a/tools/perf/benchmarks/memory.py +++ b/tools/perf/benchmarks/memory.py
@@ -2,8 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import re - from core import perf_benchmark from telemetry import benchmark @@ -15,13 +13,6 @@ import page_sets -# Regex to filter out a few names of statistics supported by -# Histogram.getStatisticScalar(), see: -# https://github.com/catapult-project/catapult/blob/d4179a05/tracing/tracing/value/histogram.html#L645 pylint: disable=line-too-long -_IGNORED_STATS_RE = re.compile( - r'(?<!dump)(?<!process)_(std|count|max|min|sum|pct_\d{4}(_\d+)?)$') - - def CreateCoreTimelineBasedMemoryMeasurementOptions(): """Creates necessary TBM options for measuring memory usage. @@ -55,16 +46,6 @@ options.flush_os_page_caches_on_start = True -def DefaultShouldAddValueForMemoryMeasurement(name): - """Default predicate when measuring memory usage. - - Separated out so that code can be re-used in other benchmarks. - """ - # TODO(crbug.com/610962): Remove this stopgap when the perf dashboard - # is able to cope with the data load generated by TBMv2 metrics. - return not _IGNORED_STATS_RE.search(name) - - class _MemoryInfra(perf_benchmark.PerfBenchmark): """Base class for new-generation memory benchmarks based on memory-infra. @@ -95,7 +76,3 @@ @classmethod def Name(cls): return 'memory.desktop' - - @classmethod - def ShouldAddValue(cls, name, _): - return DefaultShouldAddValueForMemoryMeasurement(name)
diff --git a/tools/perf/benchmarks/system_health.py b/tools/perf/benchmarks/system_health.py index 4a5fcf8..6be4b27a 100644 --- a/tools/perf/benchmarks/system_health.py +++ b/tools/perf/benchmarks/system_health.py
@@ -2,8 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import re - from benchmarks import loading_metrics_category from core import perf_benchmark @@ -16,12 +14,6 @@ import page_sets -# Regex to filter out a few names of statistics supported by -# Histogram.getStatisticScalar(), see: -# https://github.com/catapult-project/catapult/blob/d4179a05/tracing/tracing/value/histogram.html#L645 pylint: disable=line-too-long -_IGNORED_STATS_RE = re.compile(r'_(std|count|max|min|sum|pct_\d{4}(_\d+)?)$') - - class _CommonSystemHealthBenchmark(perf_benchmark.PerfBenchmark): """Chrome Common System Health Benchmark. @@ -121,13 +113,6 @@ return page_sets.SystemHealthStorySet(platform=self.PLATFORM, take_memory_measurement=True) - @classmethod - def ShouldAddValue(cls, name, from_first_story_run): - del from_first_story_run # unused - # TODO(crbug.com/610962): Remove this stopgap when the perf dashboard - # is able to cope with the data load generated by TBMv2 metrics. - return not _IGNORED_STATS_RE.search(name) - @benchmark.Info(emails=['perezju@chromium.org'], documentation_url='https://bit.ly/system-health-benchmarks')
diff --git a/tools/perf/benchmarks/v8_browsing.py b/tools/perf/benchmarks/v8_browsing.py index 014787f..308d18d 100644 --- a/tools/perf/benchmarks/v8_browsing.py +++ b/tools/perf/benchmarks/v8_browsing.py
@@ -12,11 +12,6 @@ import page_sets -# Regex to filter out a few names of statistics supported by -# Histogram.getStatisticScalar(), see: -# https://github.com/catapult-project/catapult/blob/d4179a05/tracing/tracing/value/histogram.html#L645 pylint: disable=line-too-long -_IGNORED_MEMORY_STATS_RE = re.compile(r'_(std|count|min|sum|pct_\d{4}(_\d+)?)$') - # Track only the high-level GC stats to reduce the data load on dashboard. _IGNORED_V8_STATS_RE = re.compile( r'_(idle_deadline_overrun|percentage_idle|outside_idle)') @@ -30,17 +25,12 @@ r'scavenger_|' r'total_)') + def V8BrowsingShouldAddValue(name): - # TODO(crbug.com/775942): This is needed because of a race condition in - # the memory dump manager. Remove this once the bug is fixed. - if 'memory:unknown_browser' in name: - return ('renderer_processes' in name and - not _IGNORED_MEMORY_STATS_RE.search(name)) - # TODO(crbug.com/610962): Remove this stopgap when the perf dashboard - # is able to cope with the data load generated by TBMv2 metrics. - if 'memory:chrome' in name: - return ('renderer_processes' in name and - not _IGNORED_MEMORY_STATS_RE.search(name)) + # TODO(crbug.com/775942): The "unknown_browser" is needed because of a race + # condition in the memory dump manager. Remove this once the bug is fixed. + if 'memory:chrome' in name or 'memory:unknown_browser' in name: + return 'renderer_processes' in name if 'v8-gc' in name: return (_V8_GC_HIGH_LEVEL_STATS_RE.search(name) and not _IGNORED_V8_STATS_RE.search(name))
diff --git a/tools/perf/cli_tools/soundwave/studies/__init__.py b/tools/perf/cli_tools/soundwave/studies/__init__.py index 089007a7..8e18c687 100644 --- a/tools/perf/cli_tools/soundwave/studies/__init__.py +++ b/tools/perf/cli_tools/soundwave/studies/__init__.py
@@ -26,11 +26,6 @@ df['reference'] = df['timestamp'].dt.date == df.groupby( 'quarter')['timestamp'].transform('max').dt.date - # TODO(crbug.com/900218): This is needed for timeseries still using the - # legacy API with no units information. Remove when studies finally use - # timeseries.Key to identify all of their timeseries. - df['units'] = df['units'].fillna('') - # Change units for values in ms to seconds, and percent values. is_ms_unit = df['units'].str.startswith('ms_') df.loc[is_ms_unit, 'value'] = df['value'] / 1000
diff --git a/tools/perf/cli_tools/soundwave/studies/health_study.py b/tools/perf/cli_tools/soundwave/studies/health_study.py index a8a62754..ddf4956 100644 --- a/tools/perf/cli_tools/soundwave/studies/health_study.py +++ b/tools/perf/cli_tools/soundwave/studies/health_study.py
@@ -33,6 +33,12 @@ } } +APK_SIZE = { + 'test_suite': 'resource_sizes:Monochrome.minimal.apks', + 'measurement': 'Specifics:normalized apk size', + 'bot': 'ChromiumPerf:android-builder-perf', +} + def IterSystemHealthBots(): yield 'ChromiumPerf:android-go-perf' @@ -54,24 +60,21 @@ test_cases = GetHealthCheckStories() for bot in IterSystemHealthBots(): browser = GetBrowserFromBot(bot) - series = STARTUP_BY_BROWSER[browser].copy() - series['bot'] = bot - yield timeseries.Key.FromDict(series) + # Startup. + yield timeseries.Key.FromDict(STARTUP_BY_BROWSER[browser], bot=bot) + + # Memory. if bot == 'ChromiumPerf:android-pixel2_webview-perf': # The pixel2 webview bot incorrectly reports memory as if coming from # chrome. TODO(crbug.com/972620): Remove this when bug is fixed. browser = 'chrome' for series in SYSTEM_HEALTH: - series = series.copy() - series['bot'] = bot - series['measurement'] = series['measurement'].format(browser=browser) + measurement = series['measurement'].format(browser=browser) for test_case in test_cases: - series['test_case'] = test_case - yield timeseries.Key.FromDict(series) + yield timeseries.Key.FromDict( + series, bot=bot, measurement=measurement, test_case=test_case) - # TODO(crbug.com/981283): Switch to timeseries.Key when bug is resolved. - yield ('ChromiumPerf/android-builder-perf/' - 'resource_sizes (MonochromePublic.minimal.apks)/' - 'Specifics/normalized apk size') + # APK size. + yield timeseries.Key.FromDict(APK_SIZE)
diff --git a/tools/perf/contrib/memory_extras/OWNERS b/tools/perf/contrib/memory_extras/OWNERS index e15131b0..67bf9fd 100644 --- a/tools/perf/contrib/memory_extras/OWNERS +++ b/tools/perf/contrib/memory_extras/OWNERS
@@ -1,3 +1,2 @@ -hjd@chromium.org perezju@chromium.org -primiano@chromium.org +etienneb@chromium.org
diff --git a/tools/perf/contrib/memory_extras/memory_extras.py b/tools/perf/contrib/memory_extras/memory_extras.py index 7c76051..b2bffdd 100644 --- a/tools/perf/contrib/memory_extras/memory_extras.py +++ b/tools/perf/contrib/memory_extras/memory_extras.py
@@ -9,57 +9,6 @@ # pylint: disable=protected-access -@benchmark.Info(emails=['perezju@chromium.org']) -class DualBrowserBenchmark(memory._MemoryInfra): - """Measures memory usage while interacting with two different browsers. - - The user story involves going back and forth between doing Google searches - on a webview-based browser (a stand in for the Search app), and loading - pages on a select browser. - """ - options = {'pageset_repeat': 5} - - @classmethod - def Name(cls): - return 'memory.dual_browser_test' - - def CreateStorySet(self, options): - del options - return page_sets.DualBrowserStorySet() - - @classmethod - def ShouldAddValue(cls, name, from_first_story_run): - del from_first_story_run # unused - # TODO(crbug.com/610962): Remove this stopgap when the perf dashboard - # is able to cope with the data load generated by TBMv2 metrics. - return not memory._IGNORED_STATS_RE.search(name) - - -@benchmark.Info(emails=['perezju@chromium.org']) -class LongRunningDualBrowserBenchmark(memory._MemoryInfra): - """Measures memory during prolonged usage of alternating browsers. - - Same as memory.dual_browser_test, but the test is run for 60 iterations - and the browser is *not* restarted between page set repeats. - """ - options = {'pageset_repeat': 60} - - @classmethod - def Name(cls): - return 'memory.long_running_dual_browser_test' - - def CreateStorySet(self, options): - del options - return page_sets.DualBrowserStorySet(long_running=True) - - @classmethod - def ShouldAddValue(cls, name, from_first_story_run): - del from_first_story_run # unused - # TODO(crbug.com/610962): Remove this stopgap when the perf dashboard - # is able to cope with the data load generated by TBMv2 metrics. - return not memory._IGNORED_STATS_RE.search(name) - - @benchmark.Info(emails=['etienneb@chromium.org']) class LongRunningMemoryBenchmarkSitesDesktop(memory._MemoryInfra): """Measure memory usage on popular sites. @@ -90,10 +39,3 @@ @classmethod def Name(cls): return 'memory.long_running_desktop_sites' - - @classmethod - def ShouldAddValue(cls, name, from_first_story_run): - del from_first_story_run # unused - # TODO(crbug.com/610962): Remove this stopgap when the perf dashboard - # is able to cope with the data load generated by TBMv2 metrics. - return not memory._IGNORED_STATS_RE.search(name)
diff --git a/tools/perf/contrib/vr_benchmarks/vr_benchmarks.py b/tools/perf/contrib/vr_benchmarks/vr_benchmarks.py index 129b1140..717a308d 100644 --- a/tools/perf/contrib/vr_benchmarks/vr_benchmarks.py +++ b/tools/perf/contrib/vr_benchmarks/vr_benchmarks.py
@@ -117,11 +117,6 @@ chrome_trace_config.MemoryDumpConfig()) return options - @classmethod - def ShouldAddValue(cls, name, from_first_story_run): - del from_first_story_run # unused - return memory.DefaultShouldAddValueForMemoryMeasurement(name) - class _BaseWebVRBenchmark(_BaseWebVRWebXRBenchmark):
diff --git a/tools/perf/expectations.config b/tools/perf/expectations.config index 5845655..d647dbce 100644 --- a/tools/perf/expectations.config +++ b/tools/perf/expectations.config
@@ -204,12 +204,6 @@ crbug.com/865400 [ Pixel2_Webview ] loading.mobile/VoiceMemos_cold_3g [ Skip ] crbug.com/919191 [ Nexus5X_Webview ] loading.mobile/OLX_3g [ Skip ] -# Benchmark: media.desktop -crbug.com/978045 [ All ] media.desktop/mse.html?media=tulip2.vp9.webm [ Skip ] - -# Benchmark: media.mobile -crbug.com/978045 [ All ] media.mobile/mse.html?media=tulip2.vp9.webm [ Skip ] - # Benchmark: oilpan_gc_times.key_silk_cases crbug.com/446332 [ All ] oilpan_gc_times.key_silk_cases/slide_drawer [ Skip ] crbug.com/507865 [ All ] oilpan_gc_times.key_silk_cases/polymer_topeka [ Skip ]
diff --git a/tools/perf/page_sets/data/dual_browser_story.json b/tools/perf/page_sets/data/dual_browser_story.json deleted file mode 100644 index 3629d276..0000000 --- a/tools/perf/page_sets/data/dual_browser_story.json +++ /dev/null
@@ -1,75 +0,0 @@ -{ - "archives": { - "google_1600_amphitheatre_pkwy_mountain_view_ca": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "google_cat_pictures": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "google_goog": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "google_movies_94110": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "google_population_of_california": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "google_science": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "google_sfo_jfk_flights": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "google_tip_on_100_bill": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "google_tom_hanks": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "google_weather_94110": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "http_en_m_wikipedia_org_wiki_Science": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "http_m_intl_taobao_com_group_purchase_html": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "http_m_taobao_com_channel_act_mobile_20131111_women_html": { - "DEFAULT": "dual_browser_story_001.wprgo" - }, - "http_m_youtube_com_results_q_science": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "http_search_yahoo_com_search__ylt_p_google": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "http_www_amazon_com_gp_aw_s_k_nexus": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "http_www_baidu_com_s_word_google": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "http_yandex_ru_touchsearch_text_science": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "https_m_facebook_com_rihanna": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "https_mobile_twitter_com_justinbieber_skip_interstitial_true": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "https_www_google_ca_hl_en_q_science": { - "DEFAULT": "dual_browser_story_001.wprgo" - }, - "https_www_google_co_uk_hl_en_q_science": { - "DEFAULT": "dual_browser_story_002.wprgo" - }, - "https_www_google_com_hl_en_q_science": { - "DEFAULT": "dual_browser_story_000.wprgo" - } - }, - "description": "Describes the Web Page Replay archives for a story set. Don't edit by hand! Use record_wpr for updating.", - "platform_specific": true -} \ No newline at end of file
diff --git a/tools/perf/page_sets/data/dual_browser_story_000.wprgo.sha1 b/tools/perf/page_sets/data/dual_browser_story_000.wprgo.sha1 deleted file mode 100644 index b856290..0000000 --- a/tools/perf/page_sets/data/dual_browser_story_000.wprgo.sha1 +++ /dev/null
@@ -1 +0,0 @@ -ca48d28c1d2f04a6a2e84481e99a121090314ce4 \ No newline at end of file
diff --git a/tools/perf/page_sets/data/dual_browser_story_001.wprgo.sha1 b/tools/perf/page_sets/data/dual_browser_story_001.wprgo.sha1 deleted file mode 100644 index 631ded7..0000000 --- a/tools/perf/page_sets/data/dual_browser_story_001.wprgo.sha1 +++ /dev/null
@@ -1 +0,0 @@ -b90cd02a29677862b554f5989549805eefb6ad93 \ No newline at end of file
diff --git a/tools/perf/page_sets/data/dual_browser_story_002.wprgo.sha1 b/tools/perf/page_sets/data/dual_browser_story_002.wprgo.sha1 deleted file mode 100644 index 3e7823cd..0000000 --- a/tools/perf/page_sets/data/dual_browser_story_002.wprgo.sha1 +++ /dev/null
@@ -1 +0,0 @@ -f2e595833a8b774bf56aa1152868afdf24b8069e \ No newline at end of file
diff --git a/tools/perf/page_sets/dual_browser_story.py b/tools/perf/page_sets/dual_browser_story.py deleted file mode 100644 index 2577121..0000000 --- a/tools/perf/page_sets/dual_browser_story.py +++ /dev/null
@@ -1,283 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import collections -import logging -import re -import urllib - -from telemetry import story as story_module -# TODO(perezju): Remove references to telementry.internal when -# https://github.com/catapult-project/catapult/issues/2102 is resolved. -from telemetry.internal.browser import browser_finder -from telemetry.internal.browser import browser_finder_exceptions -from telemetry.util import wpr_modes - -from page_sets.top_10_mobile import URL_LIST - - -GOOGLE_SEARCH = 'https://www.google.co.uk/search?' - -SEARCH_QUERIES = [ - 'science', - 'cat pictures', - '1600 Amphitheatre Pkwy, Mountain View, CA', - 'tom hanks', - 'weather 94110', - 'goog', - 'population of california', - 'sfo jfk flights', - 'movies 94110', - 'tip on 100 bill' -] - - -def _OptionsForBrowser(browser_type, finder_options): - """Return options used to get a browser of the given type. - - TODO(perezju): Currently this clones the finder_options passed via the - command line to telemetry. When browser_options are split appart from - finder_options (crbug.com/570348) we will be able to construct our own - browser_options as needed. - """ - finder_options = finder_options.Copy() - finder_options.browser_type = browser_type - finder_options.browser_executable = None - finder_options.browser_options.browser_type = browser_type - - # TODO(crbug.com/881469): remove this once Webview supports - # VizDisplayCompositor. - if browser_type and 'android-webview' in browser_type: - finder_options.browser_options.AppendExtraBrowserArgs( - '--disable-features=VizDisplayCompositor') - - return finder_options - - -class MultiBrowserSharedState(story_module.SharedState): - def __init__(self, test, finder_options, story_set, possible_browser=None): - """A shared state to run a test involving multiple browsers. - - The story_set is expected to include SinglePage instances (class defined - below) mapping each page to a browser on which to run. The state - requires at least one page to run on the 'default' browser, i.e. the - browser selected from the command line by the user. - """ - super(MultiBrowserSharedState, self).__init__( - test, finder_options, story_set, possible_browser) - self._platform = None - self._story_set = story_set - self._possible_browsers = {} - # We use an ordered dict to record the order in which browsers appear on - # the story set. However, browsers are not created yet. - self._browsers_created = False - self._browsers = collections.OrderedDict( - (s.browser_type, None) for s in story_set) - self._current_story = None - self._current_browser = None - self._current_tab = None - - # TODO(khokhlov): Use the supplied possible_browser as the default. - possible_browser = self._PrepareBrowser('default', finder_options) - if not possible_browser: - raise browser_finder_exceptions.BrowserFinderException( - 'No browser found.\n\nAvailable browsers:\n%s\n' % - '\n'.join(browser_finder.GetAllAvailableBrowserTypes(finder_options))) - - extra_browser_types = set(story.browser_type for story in story_set) - extra_browser_types.remove('default') # Must include 'default' browser. - for browser_type in extra_browser_types: - finder_options_copy = _OptionsForBrowser(browser_type, finder_options) - if not self._PrepareBrowser(browser_type, finder_options_copy): - logging.warning( - 'Cannot run %s (%s) because %s browser is not available', - test.__name__, str(test), browser_type) - logging.warning('Install %s to be able to run the test.', browser_type) - raise Exception("Browser not available, unable to run benchmark.") - - # TODO(crbug/404771): Move network controller options out of - # browser_options and into finder_options. - browser_options = finder_options.browser_options - if finder_options.use_live_sites: - wpr_mode = wpr_modes.WPR_OFF - elif browser_options.wpr_mode == wpr_modes.WPR_RECORD: - wpr_mode = wpr_modes.WPR_RECORD - else: - wpr_mode = wpr_modes.WPR_REPLAY - self._extra_wpr_args = browser_options.extra_wpr_args - - self.platform.network_controller.Open(wpr_mode) - - @property - def current_tab(self): - return self._current_tab - - @property - def platform(self): - return self._platform - - def _PrepareBrowser(self, browser_type, finder_options): - """Add a browser to the dict of possible browsers. - - TODO(perezju): When available, use the GetBrowserForPlatform API instead. - See: crbug.com/570348 - - Returns: - The possible browser if found, or None otherwise. - """ - possible_browser = browser_finder.FindBrowser(finder_options) - if possible_browser is None: - return None - - if self._platform is None: - self._platform = possible_browser.platform - else: - assert self._platform is possible_browser.platform - self._possible_browsers[browser_type] = ( - possible_browser, finder_options.browser_options) - return possible_browser - - def _CreateAllBrowsersIfNeeeded(self): - """Launch all browsers needed for the story set, if not already done. - - This ensures that all browsers are alive during the whole duration of the - benchmark and, therefore, e.g. memory dumps are always provided for all - of them. - """ - if self._browsers_created: - return - self.platform.FlushDnsCache() - for browser_type in self._browsers: - possible_browser, browser_options = self._possible_browsers[browser_type] - possible_browser.SetUpEnvironment(browser_options) - possible_browser.FlushOsPageCaches() - self._browsers[browser_type] = possible_browser.Create() - self._browsers_created = True - - def _CloseAllBrowsers(self): - """Close all of the browsers that were launched for this benchmark.""" - for browser_type, browser in list(self._browsers.iteritems()): - if browser is not None: - try: - browser.Close() - except Exception: - logging.exception('Error while closing %s browser', browser_type) - self._browsers[browser_type] = None - possible_browser, _ = self._possible_browsers[browser_type] - try: - possible_browser.CleanUpEnvironment() - except Exception: - logging.exception( - 'Error while cleaning up environment for %s', browser_type) - self._browsers_created = False - - def CanRunStory(self, _): - return True - - def WillRunStory(self, story): - self._current_story = story - - self.platform.network_controller.StartReplay( - self._story_set.WprFilePathForStory(story), - story.make_javascript_deterministic, - self._extra_wpr_args) - - # Note: browsers need to be created after replay has been started. - self._CreateAllBrowsersIfNeeeded() - self._current_browser = self._browsers[story.browser_type] - self._current_browser.Foreground() - self._current_tab = self._current_browser.foreground_tab - - def RunStory(self, _): - self._current_story.Run(self) - - def DidRunStory(self, _): - if (not self._story_set.long_running and - self._story_set[-1] == self._current_story): - # In long_running mode we never close the browsers; otherwise we close - # them only after the last story in the set runs. - self._CloseAllBrowsers() - self._current_story = None - - def TakeMemoryMeasurement(self): - self.current_tab.action_runner.ForceGarbageCollection() - self.platform.FlushEntireSystemCache() - if not self.platform.tracing_controller.is_tracing_running: - return # Tracing is not running, e.g., when recording a WPR archive. - for browser_type, browser in self._browsers.iteritems(): - if not browser.DumpMemory(): - logging.error('Unable to dump memory for %s', browser_type) - - def TearDownState(self): - self.platform.network_controller.Close() - self._CloseAllBrowsers() - - def DumpStateUponStoryRunFailure(self, results): - del results # Unused. - if self._browsers: - for browser_type, browser in self._browsers.iteritems(): - if browser is not None: - logging.info("vvvvv BROWSER STATE BELOW FOR '%s' vvvvv", browser_type) - browser.DumpStateUponFailure() - else: - logging.info("browser '%s' not yet created", browser_type) - else: - logging.warning('Cannot dump browser states: No browsers.') - - -class SinglePage(story_module.Story): - def __init__(self, name, url, browser_type, phase): - """A story that associates a particular page with a browser to view it. - - Args: - name: A string with the name of the page as it will appear reported, - e.g., on results and dashboards. - url: A string with the url of the page to load. - browser_type: A string identifying the browser where this page should be - displayed. Accepts the same strings as the command line --browser - option (e.g. 'android-webview'), and the special value 'default' to - select the browser chosen by the user on the command line. - """ - super(SinglePage, self).__init__(MultiBrowserSharedState, name=name) - self._url = url - self._browser_type = browser_type - self.grouping_keys['phase'] = phase - - @property - def url(self): - return self._url - - @property - def browser_type(self): - return self._browser_type - - def Run(self, shared_state): - shared_state.current_tab.Navigate(self._url) - shared_state.current_tab.WaitForDocumentReadyStateToBeComplete() - shared_state.TakeMemoryMeasurement() - - -class DualBrowserStorySet(story_module.StorySet): - """A story set that switches back and forth between two browsers.""" - - def __init__(self, long_running=False): - super(DualBrowserStorySet, self).__init__( - archive_data_file='data/dual_browser_story.json', - cloud_storage_bucket=story_module.PARTNER_BUCKET) - self.long_running = long_running - - for query, url in zip(SEARCH_QUERIES, URL_LIST): - # Stories that run on the android-webview browser. - self.AddStory(SinglePage( - name='google_%s' % re.sub(r'\W+', '_', query.lower()), - url=GOOGLE_SEARCH + urllib.urlencode({'q': query}), - browser_type='android-webview', - phase='on_webview')) - - # Stories that run on the browser selected by command line options. - self.AddStory(SinglePage( - name=re.sub(r'\W+', '_', url), - url=url, - browser_type='default', - phase='on_chrome'))
diff --git a/tools/perf/page_sets/media_cases.py b/tools/perf/page_sets/media_cases.py index 6e39f55..075d4e1 100644 --- a/tools/perf/page_sets/media_cases.py +++ b/tools/perf/page_sets/media_cases.py
@@ -309,7 +309,10 @@ page_set=page_set, tags=['vp9', 'opus', 'audio_video']), - # Basic MSE test pages for common configurations. + # Basic MSE test pages for common configurations. Note: By default the + # test will only append the first 128k of the specified files, so when + # adding tests ensure that is enough to trigger a timeupdate event. If not + # you'll need to specify an additional appendSize parameter. _MSEPage( url=_URL_BASE + 'mse.html?media=aac_audio.mp4,h264_video.mp4', page_set=page_set,
diff --git a/tools/perf/page_sets/media_cases/mse.js b/tools/perf/page_sets/media_cases/mse.js index 794315f5..37a7eae8 100644 --- a/tools/perf/page_sets/media_cases/mse.js +++ b/tools/perf/page_sets/media_cases/mse.js
@@ -10,10 +10,10 @@ // Map from media content to MIME type. All test content must be added to this // map. (Feel free to extend it for your test case!) const MEDIA_MIMES = { - "aac_audio.mp4": "audio/mp4; codecs=\"mp4a.40.2\"", - "h264_video.mp4": "video/mp4; codecs=\"avc1.640028\"", - "tulip0.av1.mp4": "video/mp4; codecs=\"av01.0.05M.08\"", - "tulip2.vp9.webm": "video/webm; codecs=\"opus,vp9\"", + 'aac_audio.mp4': 'audio/mp4; codecs="mp4a.40.2"', + 'h264_video.mp4': 'video/mp4; codecs="avc1.640028"', + 'tulip0.av1.mp4': 'video/mp4; codecs="av01.0.05M.08"', + 'tulip2.vp9.webm': 'video/webm; codecs="opus,vp9"', }; const testParams = {} @@ -33,16 +33,16 @@ // waitForPageLoaded determines whether to wait for body.onload event or // to start right away. testParams.waitForPageLoaded = - (queryParameters["waitForPageLoaded"] === "true"); + (queryParameters['waitForPageLoaded'] === 'true'); // startOffset is used to start the media at an offset instead of at the // beginning of the file. - testParams.startOffset = parseInt(queryParameters["startOffset"] || "0"); - // appendSize determines how large a chuck of the media file to append. - testParams.appendSize = parseInt(queryParameters["appendSize"] || "65536"); + testParams.startOffset = parseInt(queryParameters['startOffset'] || '0'); + // appendSize determines how large a chunk of the media file to append. + testParams.appendSize = parseInt(queryParameters['appendSize'] || '128000'); // media argument lists the media files to play. - testParams.media = queryParameters["media"]; + testParams.media = queryParameters['media']; if (!testParams.media) - throw Error("media parameter must be defined to provide test content"); + throw Error('media parameter must be defined to provide test content'); if (!Array.isArray(testParams.media)) testParams.media = [testParams.media]; } @@ -55,7 +55,7 @@ key = decodeURIComponent(match[1]) value = decodeURIComponent(match[2]); if (value.includes(',')) { - value = value.split(","); + value = value.split(','); } params[key] = value; } @@ -64,21 +64,31 @@ function runTest() { let appenders = []; - let mediaElement = document.getElementById("video_id"); + let mediaElement = document.getElementById('video_id'); let mediaSource = new window.MediaSource(); window.__mediaSource = mediaSource; // Pass the test if currentTime of the media increases since that means that // the file has started playing. // This code can be modified in the future for full playback tests. - mediaElement.addEventListener("timeupdate", () => { + mediaElement.addEventListener('timeupdate', () => { window.clearTimeout(timeout); - PassTest("Test completed after timeupdate event was received.") + PassTest('Test completed after timeupdate event was received.') + }, {once: true}); + + // Also pass the test if ended occurs; since we're appending small chunks + // there are cases where 'timeupdate' may not necessarily fire. + mediaElement.addEventListener('ended', () => { + window.clearTimeout(timeout); + if (mediaElement.currentTime > 0) + PassTest('Test completed after ended event was received.') + else + FailTest('Test failed because ended occured before currentTime > 0.') }, {once: true}); // Fail the test if we time out. var timeout = setTimeout(function() { - FailTest("Test timed out waiting for a mediaElement timeupdate event."); + FailTest('Test timed out waiting for a timeupdate or ended event.'); }, 10000); mediaSource.addEventListener('sourceopen', (open_event) => { @@ -86,10 +96,18 @@ for (let i = 0; i < appenders.length; ++i) { appenders[i].onSourceOpen(mediaSource); } + + // Append each segment and wait for the append to complete. + let num_complete_appends = 0; for (let i = 0; i < appenders.length; ++i) { - appenders[i].attemptAppend(mediaSource); + appenders[i].attemptAppend(() => { + num_complete_appends++; + if (num_complete_appends === testParams.media.length) { + mediaSource.endOfStream(); + mediaElement.play(); + } + }); } - mediaElement.play(); }); // Do not attach MediaSource object until all the buffer appenders have @@ -120,7 +138,7 @@ this.sourceBuffer = null; } requestMediaBytes(callback) { - this.xhr.addEventListener('loadend', callback); + this.xhr.addEventListener('loadend', callback, {once: true}); this.xhr.open('GET', this.media_file); this.xhr.setRequestHeader( 'Range', 'bytes=' + testParams.startOffset + '-' + @@ -133,21 +151,22 @@ return; this.sourceBuffer = mediaSource.addSourceBuffer(this.mimetype); } - attemptAppend() { + attemptAppend(callback) { if (!this.xhr.response || !this.sourceBuffer) return; + this.sourceBuffer.addEventListener('updateend', callback, {once: true}); this.sourceBuffer.appendBuffer(this.xhr.response); this.xhr = null; } } // End BufferAppender function PassTest(message) { - console.log("Test passed: " + message); + console.log('Test passed: ' + message); window.__testDone = true; } function FailTest(error_message) { - console.error("Test failed: " + error_message); + console.error('Test failed: ' + error_message); window.__testFailed = true; window.__testError = error_message; window.__testDone = true; @@ -163,5 +182,5 @@ // These are outputs to be consumed by media Telemetry test driver code. window.__testDone = false; window.__testFailed = false; - window.__testError = ""; + window.__testError = ''; })();
diff --git a/tools/perf/page_sets/media_cases/tulip2.vp9.webm.sha1 b/tools/perf/page_sets/media_cases/tulip2.vp9.webm.sha1 index 8f57ee3..6c0e3b8 100644 --- a/tools/perf/page_sets/media_cases/tulip2.vp9.webm.sha1 +++ b/tools/perf/page_sets/media_cases/tulip2.vp9.webm.sha1
@@ -1 +1 @@ -ed72683c4dcea40bf452b64cb42d54fbdcb1c169 \ No newline at end of file +bfb14ee1e08d13c795d20d6ede452255009d5e91 \ No newline at end of file
diff --git a/ui/accessibility/ax_event_generator.cc b/ui/accessibility/ax_event_generator.cc index e6a311b..8dbd24b 100644 --- a/ui/accessibility/ax_event_generator.cc +++ b/ui/accessibility/ax_event_generator.cc
@@ -123,14 +123,6 @@ if (new_node_data.child_ids != old_node_data.child_ids && new_node_data.role != ax::mojom::Role::kStaticText) { AXNode* node = tree_->GetFromId(new_node_data.id); - - // If this node is ignored, fire the CHILDREN_CHANGED on - // the unignored parent if available. - if (new_node_data.HasState(ax::mojom::State::kIgnored)) - node = node->GetUnignoredParent(); - if (!node) - return; - tree_events_[node].emplace(Event::CHILDREN_CHANGED, ax::mojom::EventFrom::kNone); }
diff --git a/ui/accessibility/ax_event_generator.h b/ui/accessibility/ax_event_generator.h index 2ff2228d4..417f17d5 100644 --- a/ui/accessibility/ax_event_generator.h +++ b/ui/accessibility/ax_event_generator.h
@@ -40,6 +40,7 @@ DROPEFFECT_CHANGED, ENABLED_CHANGED, EXPANDED, + FOCUS_CHANGED, FLOW_FROM_CHANGED, FLOW_TO_CHANGED, GRABBED_CHANGED,
diff --git a/ui/accessibility/ax_event_generator_unittest.cc b/ui/accessibility/ax_event_generator_unittest.cc index dbfa59961..6a5f519 100644 --- a/ui/accessibility/ax_event_generator_unittest.cc +++ b/ui/accessibility/ax_event_generator_unittest.cc
@@ -943,6 +943,44 @@ DumpEvents(&event_generator)); } +TEST(AXEventGeneratorTest, NodeBecomesIgnored2) { + AXTreeUpdate initial_state; + initial_state.root_id = 1; + initial_state.nodes.resize(5); + initial_state.nodes[0].id = 1; + initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea; + initial_state.nodes[0].child_ids.push_back(2); + initial_state.nodes[1].id = 2; + initial_state.nodes[1].role = ax::mojom::Role::kArticle; + initial_state.nodes[1].child_ids.push_back(3); + initial_state.nodes[2].id = 3; + initial_state.nodes[2].role = ax::mojom::Role::kGroup; + initial_state.nodes[2].AddState(ax::mojom::State::kIgnored); + initial_state.nodes[2].child_ids.push_back(4); + initial_state.nodes[3].id = 4; + initial_state.nodes[3].role = ax::mojom::Role::kGroup; + initial_state.nodes[3].child_ids.push_back(5); + initial_state.nodes[4].id = 5; + initial_state.nodes[4].role = ax::mojom::Role::kStaticText; + + AXTree tree(initial_state); + + AXEventGenerator event_generator(&tree); + AXTreeUpdate update = initial_state; + // Marking as ignored should fire CHILDREN_CHANGED on 2 + update.nodes[3].AddState(ax::mojom::State::kIgnored); + // Remove node id 5 so it also fires CHILDREN_CHANGED on 4. + update.nodes.pop_back(); + update.nodes[3].child_ids.clear(); + ASSERT_TRUE(tree.Unserialize(update)); + EXPECT_EQ( + "CHILDREN_CHANGED on 2, " + "CHILDREN_CHANGED on 4, " + "IGNORED_CHANGED on 4, " + "STATE_CHANGED on 4", + DumpEvents(&event_generator)); +} + TEST(AXEventGeneratorTest, NodeBecomesUnignored) { AXTreeUpdate initial_state; initial_state.root_id = 1; @@ -977,6 +1015,45 @@ DumpEvents(&event_generator)); } +TEST(AXEventGeneratorTest, NodeBecomesUnignored2) { + AXTreeUpdate initial_state; + initial_state.root_id = 1; + initial_state.nodes.resize(5); + initial_state.nodes[0].id = 1; + initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea; + initial_state.nodes[0].child_ids.push_back(2); + initial_state.nodes[1].id = 2; + initial_state.nodes[1].role = ax::mojom::Role::kArticle; + initial_state.nodes[1].child_ids.push_back(3); + initial_state.nodes[2].id = 3; + initial_state.nodes[2].role = ax::mojom::Role::kGroup; + initial_state.nodes[2].AddState(ax::mojom::State::kIgnored); + initial_state.nodes[2].child_ids.push_back(4); + initial_state.nodes[3].id = 4; + initial_state.nodes[3].role = ax::mojom::Role::kGroup; + initial_state.nodes[3].AddState(ax::mojom::State::kIgnored); + initial_state.nodes[3].child_ids.push_back(5); + initial_state.nodes[4].id = 5; + initial_state.nodes[4].role = ax::mojom::Role::kStaticText; + + AXTree tree(initial_state); + + AXEventGenerator event_generator(&tree); + AXTreeUpdate update = initial_state; + // Marking as no longer ignored should fire CHILDREN_CHANGED on 2 + update.nodes[3].state = 0; + // Remove node id 5 so it also fires CHILDREN_CHANGED on 4. + update.nodes.pop_back(); + update.nodes[3].child_ids.clear(); + ASSERT_TRUE(tree.Unserialize(update)); + EXPECT_EQ( + "CHILDREN_CHANGED on 2, " + "CHILDREN_CHANGED on 4, " + "IGNORED_CHANGED on 4, " + "STATE_CHANGED on 4", + DumpEvents(&event_generator)); +} + TEST(AXEventGeneratorTest, ActiveDescendantChangeOnDescendant) { AXTreeUpdate initial_state; initial_state.root_id = 1;
diff --git a/ui/accessibility/platform/ax_platform_node_base.cc b/ui/accessibility/platform/ax_platform_node_base.cc index 5a5394f..e99c109 100644 --- a/ui/accessibility/platform/ax_platform_node_base.cc +++ b/ui/accessibility/platform/ax_platform_node_base.cc
@@ -733,7 +733,6 @@ bool AXPlatformNodeBase::IsInvisibleOrIgnored() const { const AXNodeData& data = GetData(); return data.HasState(ax::mojom::State::kInvisible) || - data.HasState(ax::mojom::State::kIgnored) || data.role == ax::mojom::Role::kIgnored; }
diff --git a/ui/base/ime/chromeos/input_method_chromeos.cc b/ui/base/ime/chromeos/input_method_chromeos.cc index ec5b5da..e772894 100644 --- a/ui/base/ime/chromeos/input_method_chromeos.cc +++ b/ui/base/ime/chromeos/input_method_chromeos.cc
@@ -346,9 +346,7 @@ } void InputMethodChromeOS::ConfirmCompositionText() { - TextInputClient* client = GetTextInputClient(); - if (client && client->HasCompositionText()) - client->ConfirmCompositionText(); + InputMethodBase::ConfirmCompositionText(); ResetContext(); }
diff --git a/ui/base/ime/chromeos/input_method_chromeos.h b/ui/base/ime/chromeos/input_method_chromeos.h index 23fb226..d8978bd2 100644 --- a/ui/base/ime/chromeos/input_method_chromeos.h +++ b/ui/base/ime/chromeos/input_method_chromeos.h
@@ -52,6 +52,7 @@ uint32_t before, uint32_t after, const std::vector<ui::ImeTextSpan>& text_spans) override; + void ConfirmCompositionText() override; protected: // Converts |text| into CompositionText. @@ -84,9 +85,6 @@ std::vector<ui::ImeTextSpan> text_spans; }; - // Asks the client to confirm current composition text. - void ConfirmCompositionText(); - // Checks the availability of focused text input client and update focus // state. void UpdateContextFocusState();
diff --git a/ui/base/ime/chromeos/input_method_chromeos_unittest.cc b/ui/base/ime/chromeos/input_method_chromeos_unittest.cc index 2573439..ed80ea4b 100644 --- a/ui/base/ime/chromeos/input_method_chromeos_unittest.cc +++ b/ui/base/ime/chromeos/input_method_chromeos_unittest.cc
@@ -305,6 +305,13 @@ void OnInputMethodChanged() override { ++on_input_method_changed_call_count_; } + bool SetCompositionFromExistingText( + const gfx::Range& range, + const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) override { + composition_text_ = CompositionText(); + GetTextFromRange(range, &composition_text_.text); + return true; + } bool HasNativeEvent() const { return dispatched_key_event_.HasNativeEvent(); @@ -898,6 +905,48 @@ EXPECT_EQ(0U, composition_text_.text.length()); } +TEST_F(InputMethodChromeOSTest, ConfirmCompositionText_NoComposition) { + // Focus on a text field. + input_type_ = TEXT_INPUT_TYPE_TEXT; + ime_->OnTextInputTypeChanged(this); + + ime_->ConfirmCompositionText(); + + EXPECT_TRUE(confirmed_text_.text.empty()); + EXPECT_TRUE(composition_text_.text.empty()); +} + +TEST_F(InputMethodChromeOSTest, ConfirmCompositionText_SetComposition) { + // Focus on a text field. + input_type_ = TEXT_INPUT_TYPE_TEXT; + ime_->OnTextInputTypeChanged(this); + + CompositionText composition_text; + composition_text.text = base::UTF8ToUTF16("hello"); + SetCompositionText(composition_text); + ime_->ConfirmCompositionText(); + + EXPECT_EQ(base::ASCIIToUTF16("hello"), confirmed_text_.text); + EXPECT_TRUE(composition_text_.text.empty()); +} + +TEST_F(InputMethodChromeOSTest, ConfirmCompositionText_SetCompositionRange) { + // Focus on a text field. + input_type_ = TEXT_INPUT_TYPE_TEXT; + ime_->OnTextInputTypeChanged(this); + + // Place some text. + surrounding_text_ = UTF8ToUTF16("abc"); + text_range_ = gfx::Range(0, 3); + + // "abc" is in composition. Put the two characters in composition. + ime_->SetCompositionRange(0, 2, {}); + ime_->ConfirmCompositionText(); + + EXPECT_EQ(base::ASCIIToUTF16("ab"), confirmed_text_.text); + EXPECT_TRUE(composition_text_.text.empty()); +} + class InputMethodChromeOSKeyEventTest : public InputMethodChromeOSTest { public: InputMethodChromeOSKeyEventTest() = default;
diff --git a/ui/base/ime/ime_input_context_handler_interface.h b/ui/base/ime/ime_input_context_handler_interface.h index 88abe7dd..fd46682 100644 --- a/ui/base/ime/ime_input_context_handler_interface.h +++ b/ui/base/ime/ime_input_context_handler_interface.h
@@ -50,6 +50,9 @@ // Gets the input method pointer. virtual InputMethod* GetInputMethod() = 0; + + // Commits any composition text. + virtual void ConfirmCompositionText() = 0; }; } // namespace ui
diff --git a/ui/base/ime/input_method_base.cc b/ui/base/ime/input_method_base.cc index 8096412..aa1631a 100644 --- a/ui/base/ime/input_method_base.cc +++ b/ui/base/ime/input_method_base.cc
@@ -284,6 +284,12 @@ return this; } +void InputMethodBase::ConfirmCompositionText() { + TextInputClient* client = GetTextInputClient(); + if (client && client->HasCompositionText()) + client->ConfirmCompositionText(); +} + const std::vector<std::unique_ptr<ui::KeyEvent>>& InputMethodBase::GetKeyEventsForTesting() { return key_events_for_testing_;
diff --git a/ui/base/ime/input_method_base.h b/ui/base/ime/input_method_base.h index d6c0f534..83ff2fe 100644 --- a/ui/base/ime/input_method_base.h +++ b/ui/base/ime/input_method_base.h
@@ -98,6 +98,7 @@ SurroundingTextInfo GetSurroundingTextInfo() override; void SendKeyEvent(KeyEvent* event) override; InputMethod* GetInputMethod() override; + void ConfirmCompositionText() override; // Sends a fake key event for IME composing without physical key events. // Returns true if the faked key event is stopped propagation.
diff --git a/ui/base/ime/linux/input_method_auralinux.cc b/ui/base/ime/linux/input_method_auralinux.cc index 0393ec85..6df153c1 100644 --- a/ui/base/ime/linux/input_method_auralinux.cc +++ b/ui/base/ime/linux/input_method_auralinux.cc
@@ -450,14 +450,9 @@ } void InputMethodAuraLinux::ConfirmCompositionText() { - TextInputClient* client = GetTextInputClient(); - if (client && client->HasCompositionText()) { - client->ConfirmCompositionText(); - - if (GetEngine()) - GetEngine()->Reset(); - } - + InputMethodBase::ConfirmCompositionText(); + if (GetEngine()) + GetEngine()->Reset(); ResetContext(); }
diff --git a/ui/base/ime/linux/input_method_auralinux.h b/ui/base/ime/linux/input_method_auralinux.h index 39e2094..0ff674b 100644 --- a/ui/base/ime/linux/input_method_auralinux.h +++ b/ui/base/ime/linux/input_method_auralinux.h
@@ -47,13 +47,13 @@ TextInputClient* focused) override; void OnDidChangeFocusedClient(TextInputClient* focused_before, TextInputClient* focused) override; + void ConfirmCompositionText() override; private: bool HasInputMethodResult(); bool NeedInsertChar() const; ui::EventDispatchDetails SendFakeProcessKeyEvent(ui::KeyEvent* event) const WARN_UNUSED_RESULT; - void ConfirmCompositionText(); void UpdateContextFocusState(); void ResetContext(); bool IgnoringNonKeyInput() const;
diff --git a/ui/base/ime/mock_ime_input_context_handler.cc b/ui/base/ime/mock_ime_input_context_handler.cc index fdb9a392..d7db4d06 100644 --- a/ui/base/ime/mock_ime_input_context_handler.cc +++ b/ui/base/ime/mock_ime_input_context_handler.cc
@@ -4,6 +4,7 @@ #include "ui/base/ime/mock_ime_input_context_handler.h" +#include "base/strings/utf_string_conversions.h" #include "ui/base/ime/composition_text.h" #include "ui/base/ime/input_method.h" @@ -37,7 +38,10 @@ uint32_t before, uint32_t after, const std::vector<ui::ImeTextSpan>& text_spans) { - return false; + // TODO(shend): Make this work with before, after and different text contents. + last_update_composition_arg_.composition_text.text = + base::UTF8ToUTF16(last_commit_text_); + return true; } #endif @@ -67,4 +71,11 @@ InputMethod* MockIMEInputContextHandler::GetInputMethod() { return nullptr; } + +void MockIMEInputContextHandler::ConfirmCompositionText() { + CommitText( + base::UTF16ToUTF8(last_update_composition_arg_.composition_text.text)); + last_update_composition_arg_.composition_text.text = base::string16(); +} + } // namespace ui
diff --git a/ui/base/ime/mock_ime_input_context_handler.h b/ui/base/ime/mock_ime_input_context_handler.h index 9e66f32..6a9afe4 100644 --- a/ui/base/ime/mock_ime_input_context_handler.h +++ b/ui/base/ime/mock_ime_input_context_handler.h
@@ -48,6 +48,7 @@ SurroundingTextInfo GetSurroundingTextInfo() override; void SendKeyEvent(KeyEvent* event) override; InputMethod* GetInputMethod() override; + void ConfirmCompositionText() override; int commit_text_call_count() const { return commit_text_call_count_; }
diff --git a/ui/base/ime/win/input_method_win_imm32.cc b/ui/base/ime/win/input_method_win_imm32.cc index 2bd1043..1e09c86b 100644 --- a/ui/base/ime/win/input_method_win_imm32.cc +++ b/ui/base/ime/win/input_method_win_imm32.cc
@@ -323,17 +323,13 @@ } void InputMethodWinImm32::ConfirmCompositionText() { + InputMethodBase::ConfirmCompositionText(); + InputMethodWinBase::ResetEngine(); + + // Makes sure the native IME app can be informed about the composition is + // cleared, so that it can clean up its internal states. if (composing_window_handle_) imm32_manager_.CleanupComposition(composing_window_handle_); - - // Though above line should confirm the client's composition text by sending a - // result text to us, in case the input method and the client are in - // inconsistent states, we check the client's composition state again. - if (!IsTextInputTypeNone() && GetTextInputClient()->HasCompositionText()) { - GetTextInputClient()->ConfirmCompositionText(); - - InputMethodWinBase::ResetEngine(); - } } void InputMethodWinImm32::UpdateIMEState() {
diff --git a/ui/base/ime/win/input_method_win_imm32.h b/ui/base/ime/win/input_method_win_imm32.h index 819912d..672a308 100644 --- a/ui/base/ime/win/input_method_win_imm32.h +++ b/ui/base/ime/win/input_method_win_imm32.h
@@ -27,6 +27,7 @@ // Overridden from InputMethodBase: void OnFocus() override; + void ConfirmCompositionText() override; // Overridden from InputMethod: bool OnUntranslatedIMEMessage(const MSG event, @@ -75,9 +76,6 @@ void RefreshInputLanguage(); - // Asks the client to confirm current composition text. - void ConfirmCompositionText(); - // Enables or disables the IME according to the current text input type. void UpdateIMEState();
diff --git a/ui/base/ime/win/input_method_win_tsf.h b/ui/base/ime/win/input_method_win_tsf.h index 9fcf1701..b6c2095 100644 --- a/ui/base/ime/win/input_method_win_tsf.h +++ b/ui/base/ime/win/input_method_win_tsf.h
@@ -41,13 +41,11 @@ TextInputClient* focused) override; void OnDidChangeFocusedClient(TextInputClient* focused_before, TextInputClient* focused) override; + void ConfirmCompositionText() override; private: class TSFEventObserver; - // Asks the client to confirm current composition text. - void ConfirmCompositionText(); - // TSF event router and observer. std::unique_ptr<TSFEventObserver> tsf_event_observer_; std::unique_ptr<TSFEventRouter> tsf_event_router_;
diff --git a/ui/base/ime/win/tsf_text_store.cc b/ui/base/ime/win/tsf_text_store.cc index ee6a31bc..06495bb 100644 --- a/ui/base/ime/win/tsf_text_store.cc +++ b/ui/base/ime/win/tsf_text_store.cc
@@ -263,10 +263,12 @@ text_buffer[i] = result[i]; } - if (run_info_buffer_size) { + if (*text_buffer_copied > 0 && run_info_buffer_size) { run_info_buffer[0].uCount = *text_buffer_copied; run_info_buffer[0].type = TS_RT_PLAIN; *run_info_buffer_copied = 1; + } else { + *run_info_buffer_copied = 0; } *next_acp = acp_end;
diff --git a/ui/base/ime/win/tsf_text_store_unittest.cc b/ui/base/ime/win/tsf_text_store_unittest.cc index e66184d5..f49580c 100644 --- a/ui/base/ime/win/tsf_text_store_unittest.cc +++ b/ui/base/ime/win/tsf_text_store_unittest.cc
@@ -273,10 +273,14 @@ ASSERT_EQ(expected_string.size(), text_buffer_copied); EXPECT_EQ(expected_string, base::string16(buffer, buffer + text_buffer_copied)); - EXPECT_EQ(1u, run_info_buffer_copied); - EXPECT_EQ(expected_string.size(), run_info.uCount); - EXPECT_EQ(TS_RT_PLAIN, run_info.type); - EXPECT_EQ(expected_next_acp, next_acp); + if (text_buffer_copied > 0) { + EXPECT_EQ(1u, run_info_buffer_copied); + EXPECT_EQ(expected_string.size(), run_info.uCount); + EXPECT_EQ(TS_RT_PLAIN, run_info.type); + EXPECT_EQ(expected_next_acp, next_acp); + } else { + EXPECT_EQ(0u, run_info_buffer_copied); + } } void GetTextErrorTest(LONG acp_start, LONG acp_end, HRESULT error_code) {
diff --git a/ui/base/mpris/BUILD.gn b/ui/base/mpris/BUILD.gn index 0e417f812..7ffb7c04 100644 --- a/ui/base/mpris/BUILD.gn +++ b/ui/base/mpris/BUILD.gn
@@ -15,7 +15,7 @@ deps = [ "//base", - "//components/dbus:dbus_thread_linux", + "//components/dbus/thread_linux", "//dbus", ] } @@ -29,7 +29,7 @@ ":mpris", "//base", "//base/test:test_support", - "//components/dbus:dbus_thread_linux", + "//components/dbus/thread_linux", "//dbus", "//dbus:test_support", "//testing/gmock",
diff --git a/ui/base/mpris/mpris_service_impl.cc b/ui/base/mpris/mpris_service_impl.cc index f5a74f7..0ba6bab4 100644 --- a/ui/base/mpris/mpris_service_impl.cc +++ b/ui/base/mpris/mpris_service_impl.cc
@@ -12,7 +12,7 @@ #include "base/process/process.h" #include "base/unguessable_token.h" #include "base/values.h" -#include "components/dbus/dbus_thread_linux.h" +#include "components/dbus/thread_linux/dbus_thread_linux.h" #include "dbus/bus.h" #include "dbus/exported_object.h" #include "dbus/message.h"
diff --git a/ui/base/mpris/mpris_service_impl_unittest.cc b/ui/base/mpris/mpris_service_impl_unittest.cc index 42cfa84..5ee9b87 100644 --- a/ui/base/mpris/mpris_service_impl_unittest.cc +++ b/ui/base/mpris/mpris_service_impl_unittest.cc
@@ -11,7 +11,7 @@ #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_task_environment.h" -#include "components/dbus/dbus_thread_linux.h" +#include "components/dbus/thread_linux/dbus_thread_linux.h" #include "dbus/message.h" #include "dbus/mock_bus.h" #include "dbus/mock_exported_object.h"
diff --git a/ui/chromeos/search_box/search_box_view_base.cc b/ui/chromeos/search_box/search_box_view_base.cc index aba1059..eefdc35 100644 --- a/ui/chromeos/search_box/search_box_view_base.cc +++ b/ui/chromeos/search_box/search_box_view_base.cc
@@ -450,6 +450,10 @@ } void SearchBoxViewBase::ClearSearch() { + // Avoid setting |search_box_| text to empty if it is already empty. + if (search_box_->text() == base::string16()) + return; + search_box_->SetText(base::string16()); UpdateButtonsVisisbility(); // Updates model and fires query changed manually because SetText() above
diff --git a/ui/events/ozone/evdev/touch_event_converter_evdev.cc b/ui/events/ozone/evdev/touch_event_converter_evdev.cc index b1d83fa..a713142a 100644 --- a/ui/events/ozone/evdev/touch_event_converter_evdev.cc +++ b/ui/events/ozone/evdev/touch_event_converter_evdev.cc
@@ -250,7 +250,7 @@ events_[0].cancelled = false; } if (cancelled_state) - CancelAllTouches(); + MaybeCancelAllTouches(); false_touch_finder_ = FalseTouchFinder::Create(GetTouchscreenSize()); } @@ -514,12 +514,12 @@ details, timestamp, flags)); } -void TouchEventConverterEvdev::CancelAllTouches() { +bool TouchEventConverterEvdev::MaybeCancelAllTouches() { // TODO(denniskempin): Remove once upper layers properly handle single // cancelled touches. if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableCancelAllTouches)) { - return; + return false; } for (size_t i = 0; i < events_.size(); i++) { InProgressTouchEvdev* event = &events_[i]; @@ -528,6 +528,7 @@ event->altered = true; } } + return true; } bool TouchEventConverterEvdev::IsPalm(const InProgressTouchEvdev& touch) { @@ -552,8 +553,9 @@ if (event->altered && (event->cancelled || (false_touch_finder_ && false_touch_finder_->SlotHasNoise(event->slot)))) { - CancelAllTouches(); - break; + if (MaybeCancelAllTouches()) { + break; + } } }
diff --git a/ui/events/ozone/evdev/touch_event_converter_evdev.h b/ui/events/ozone/evdev/touch_event_converter_evdev.h index 991f88b..bfa6f5c 100644 --- a/ui/events/ozone/evdev/touch_event_converter_evdev.h +++ b/ui/events/ozone/evdev/touch_event_converter_evdev.h
@@ -90,7 +90,8 @@ void UpdateTrackingId(int slot, int tracking_id); void ReleaseTouches(); - void CancelAllTouches(); + // Returns true if all touches were marked cancelled. Otherwise false. + bool MaybeCancelAllTouches(); bool IsPalm(const InProgressTouchEvdev& touch); // Normalize pressure value to [0, 1]. float ScalePressure(int32_t value) const;
diff --git a/ui/file_manager/file_manager/foreground/css/file_manager.css b/ui/file_manager/file_manager/foreground/css/file_manager.css index ade3c7f..02d2157 100644 --- a/ui/file_manager/file_manager/foreground/css/file_manager.css +++ b/ui/file_manager/file_manager/foreground/css/file_manager.css
@@ -2148,13 +2148,20 @@ /* Feedback panels */ -.feedback-panels { +.files-feedback-panels { + align-items: flex-end; bottom: 24px; + display: flex; + flex-direction: column; position: absolute; right: 24px; z-index: 502; /* Above splitter, but below quickview. */ } +.files-vertical-padder-8 { + height: 8px; +} + #completed-panel { padding-bottom: 8px; }
diff --git a/ui/file_manager/file_manager/foreground/elements/BUILD.gn b/ui/file_manager/file_manager/foreground/elements/BUILD.gn index 20383d2..a8f3f592 100644 --- a/ui/file_manager/file_manager/foreground/elements/BUILD.gn +++ b/ui/file_manager/file_manager/foreground/elements/BUILD.gn
@@ -30,6 +30,11 @@ ":files_toast", ":files_toggle_ripple", ":files_tooltip", + ":xf_activity_complete", + ":xf_button", + ":xf_circular_progress", + ":xf_display_panel", + ":xf_panel_item", ] } @@ -127,6 +132,9 @@ } js_library("xf_button") { + deps = [ + "//ui/webui/resources/cr_elements/cr_icon_button:cr_icon_button", + ] } js_library("xf_circular_progress") {
diff --git a/ui/file_manager/file_manager/foreground/elements/elements_bundle.html b/ui/file_manager/file_manager/foreground/elements/elements_bundle.html index 103ef85..c90cfe1 100644 --- a/ui/file_manager/file_manager/foreground/elements/elements_bundle.html +++ b/ui/file_manager/file_manager/foreground/elements/elements_bundle.html
@@ -14,5 +14,5 @@ <link rel="import" href="files_toast.html"> <link rel="import" href="files_toggle_ripple.html"> <link rel="import" href="files_tooltip.html"> +<link rel="import" href="files_xf_elements.html"> <link rel="import" href="icons.html"> -<link rel="import" href="files_xf_elements.css">
diff --git a/ui/file_manager/file_manager/foreground/elements/files_metadata_box.js b/ui/file_manager/file_manager/foreground/elements/files_metadata_box.js index e7c5a5b..54244d9c 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_metadata_box.js +++ b/ui/file_manager/file_manager/foreground/elements/files_metadata_box.js
@@ -215,7 +215,9 @@ return ''; } - // TODO(noel): add ifd.raw cameraModel support. + if (ifd['raw']) { + return ifd['raw']['cameraModel'] || ''; + } const id = 272; const model = (ifd.image && ifd.image[id] && ifd.image[id].value) || ''; @@ -274,9 +276,9 @@ deviceSettings_: function(ifd) { let result = ''; - // TODO(noel): add ifd.raw device settings support. - - if (ifd) { + if (ifd && ifd['raw']) { + result = this.rawDeviceSettings_(ifd['raw']); + } else if (ifd) { result = this.ifdDeviceSettings_(ifd); } @@ -284,7 +286,39 @@ }, /** - * @param {Object} ifd + * @param {!Object} raw + * @return {string} + * + * @private + */ + rawDeviceSettings_: function(raw) { + let result = ''; + + const aperture = raw['aperture'] || 0; + if (aperture) { + result += 'f/' + aperture + ' '; + } + + const exposureTime = raw['exposureTime'] || 0; + if (exposureTime) { + result += exposureTime + ' '; + } + + const focalLength = raw['focalLength'] || 0; + if (focalLength) { + result += focalLength + 'mm '; + } + + const isoSpeed = raw['isoSpeed'] || 0; + if (isoSpeed) { + result += 'ISO' + isoSpeed + ' '; + } + + return result.trimEnd(); + }, + + /** + * @param {!Object} ifd * @return {string} * * @private
diff --git a/ui/file_manager/file_manager/foreground/elements/files_xf_elements.css b/ui/file_manager/file_manager/foreground/elements/files_xf_elements.css deleted file mode 100644 index d24ae42..0000000 --- a/ui/file_manager/file_manager/foreground/elements/files_xf_elements.css +++ /dev/null
@@ -1,19 +0,0 @@ -/* Copyright 2019 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -/* TODO(crbug.com/947388) revisit the 'xf-' prefix naming for better search. */ -xf-display-panel { - max-width: 400px; -} - -.feedback-panels { - align-items: flex-end; - display: flex; - flex-direction: column; -} - - -.xf-vertical-padder-8 { - height: 8px; -}
diff --git a/ui/file_manager/file_manager/foreground/elements/files_xf_elements.html b/ui/file_manager/file_manager/foreground/elements/files_xf_elements.html new file mode 100644 index 0000000..8f3b026 --- /dev/null +++ b/ui/file_manager/file_manager/foreground/elements/files_xf_elements.html
@@ -0,0 +1,9 @@ +<!-- Copyright 2019 The Chromium Authors. All rights reserved. + -- Use of this source code is governed by a BSD-style license that can be + -- found in the LICENSE file. + --> +<script src="xf_activity_complete.js"></script> +<script src="xf_button.js"></script> +<script src="xf_circular_progress.js"></script> +<script src="xf_display_panel.js"></script> +<script src="xf_panel_item.js"></script>
diff --git a/ui/file_manager/file_manager/foreground/elements/xf_button.js b/ui/file_manager/file_manager/foreground/elements/xf_button.js index 191306f7..6d9dbd5 100644 --- a/ui/file_manager/file_manager/foreground/elements/xf_button.js +++ b/ui/file_manager/file_manager/foreground/elements/xf_button.js
@@ -34,16 +34,33 @@ } :host([data-category='pause']) { - background: url(../images/files/ui/pause.svg) no-repeat center; + background: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR\ + 0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHdpZHRoPSczNnB4JyBoZWlnaHQ\ + 9JzM2cHgnIHZpZXdCb3g9JzAgMCAzNiAzNic+CiAgICA8ZyBzdHJva2U9JyM\ + 1RjYzNjgnIHN0cm9rZS13aWR0aD0nMyc+CiAgICAgICAgPGxpbmUgeDE9JzE\ + 1JyB5MT0nMTInIHgyPScxNScgeTI9JzI0Jy8+CiAgICAgICAgPGxpbmUgeDE\ + 9JzIxJyB5MT0nMTInIHgyPScyMScgeTI9JzI0Jy8+CiAgICA8L2c+Cjwvc3Z\ + nPg==') no-repeat center; } :host([data-category='cancel']) { - background: url(../images/files/ui/cancel.svg) no-repeat center; + background: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR\ + 0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHdpZHRoPSczNnB4JyBoZWlnaHQ\ + 9JzM2cHgnIHZpZXdCb3g9JzAgMCAzNiAzNic+CiAgICA8ZyBzdHJva2U9JyM\ + 1RjYzNjgnIHN0cm9rZS13aWR0aD0nMic+CiAgICAgICAgPGxpbmUgeDE9JzE\ + yJyB5MT0nMTInIHgyPScyNCcgeTI9JzI0Jy8+CiAgICAgICAgPGxpbmUgeDE\ + 9JzI0JyB5MT0nMTInIHgyPScxMicgeTI9JzI0Jy8+CiAgICA8L2c+Cjwvc3Z\ + nPg==') no-repeat center; } :host([data-category='expand']), :host([data-category='collapse']) { - background: url(../images/files/ui/expand.svg) no-repeat center; + background: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR\ + 0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHdpZHRoPSczNnB4JyBoZWlnaHQ\ + 9JzM2cHgnIHZpZXdCb3g9JzAgMCAzNiAzNic+CiAgICA8ZyBzdHJva2U9JyM\ + 1RjYzNjgnIHN0cm9rZS13aWR0aD0nMic+CiAgICAgICAgPHBhdGggZmlsbD0\ + ibm9uZSIgZD0nTTEyLDIxbDYsLTYgNiw2Jy8+CiAgICA8L2c+Cjwvc3ZnPg==' + ) no-repeat center; } @keyframes setcollapse {
diff --git a/ui/file_manager/file_manager/foreground/elements/xf_display_panel.js b/ui/file_manager/file_manager/foreground/elements/xf_display_panel.js index c6a352a..a47fe4ce 100644 --- a/ui/file_manager/file_manager/foreground/elements/xf_display_panel.js +++ b/ui/file_manager/file_manager/foreground/elements/xf_display_panel.js
@@ -62,6 +62,9 @@ */ static html_() { return `<style> + :host { + max-width: 400px; + } #container { align-items: stretch; background-color: #FFF;
diff --git a/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js b/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js index ad8d1307..7bd7d4b 100644 --- a/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js +++ b/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js
@@ -212,7 +212,7 @@ secondaryButton = document.createElement('xf-button'); secondaryButton.id = 'secondary-action'; secondaryButton.onclick = this.onclick; - secondaryButton.dataset.category = 'retry'; + secondaryButton.dataset.category = 'dismiss'; buttonSpacer.insertAdjacentElement('afterend', secondaryButton); break; case this.panelTypeInfo:
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/cancel.svg b/ui/file_manager/file_manager/foreground/images/files/ui/cancel.svg deleted file mode 100644 index 2ea9910..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/cancel.svg +++ /dev/null
@@ -1,6 +0,0 @@ -<svg xmlns='http://www.w3.org/2000/svg' width='36px' height='36px' viewBox='0 0 36 36'> - <g stroke='#5F6368' stroke-width='2'> - <line x1='12' y1='12' x2='24' y2='24'/> - <line x1='24' y1='12' x2='12' y2='24'/> - </g> -</svg>
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/expand.svg b/ui/file_manager/file_manager/foreground/images/files/ui/expand.svg deleted file mode 100644 index 8d87a78..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/expand.svg +++ /dev/null
@@ -1,5 +0,0 @@ -<svg xmlns='http://www.w3.org/2000/svg' width='36px' height='36px' viewBox='0 0 36 36'> - <g stroke='#5F6368' stroke-width='2'> - <path fill="none" d='M12,21l6,-6 6,6'/> - </g> -</svg>
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/pause.svg b/ui/file_manager/file_manager/foreground/images/files/ui/pause.svg deleted file mode 100644 index 78f65b8..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/pause.svg +++ /dev/null
@@ -1,6 +0,0 @@ -<svg xmlns='http://www.w3.org/2000/svg' width='36px' height='36px' viewBox='0 0 36 36'> - <g stroke='#5F6368' stroke-width='3'> - <line x1='15' y1='12' x2='15' y2='24'/> - <line x1='21' y1='12' x2='21' y2='24'/> - </g> -</svg>
diff --git a/ui/file_manager/file_manager/foreground/js/main_scripts.js b/ui/file_manager/file_manager/foreground/js/main_scripts.js index 3206805..f33d0df 100644 --- a/ui/file_manager/file_manager/foreground/js/main_scripts.js +++ b/ui/file_manager/file_manager/foreground/js/main_scripts.js
@@ -181,11 +181,6 @@ // <include src="main_window_component.js"> // <include src="../../../base/js/filtered_volume_manager.js"> // <include src="webui_command_extender.js"> -// <include src="../elements/xf_activity_complete.js"> -// <include src="../elements/xf_button.js"> -// <include src="../elements/xf_circular_progress.js"> -// <include src="../elements/xf_display_panel.js"> -// <include src="../elements/xf_panel_item.js"> // // For accurate load performance tracking place main.js should be // // the last include to include.
diff --git a/ui/file_manager/file_manager/foreground/js/metadata/BUILD.gn b/ui/file_manager/file_manager/foreground/js/metadata/BUILD.gn index 65c11c4..b443bd75 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata/BUILD.gn +++ b/ui/file_manager/file_manager/foreground/js/metadata/BUILD.gn
@@ -51,6 +51,7 @@ ":metadata_provider", "../../../common/js:file_type", "../../../common/js:util", + "../../js:thumbnail_loader", ] }
diff --git a/ui/file_manager/file_manager/foreground/js/metadata/content_metadata_provider.js b/ui/file_manager/file_manager/foreground/js/metadata/content_metadata_provider.js index 0579a5d..d3f73905 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata/content_metadata_provider.js +++ b/ui/file_manager/file_manager/foreground/js/metadata/content_metadata_provider.js
@@ -84,21 +84,18 @@ * @private */ getImpl_(entry, names, callback) { + // Directories do not have a thumbnail. if (entry.isDirectory) { - setTimeout( - callback.bind( - null, - this.createError_( - entry.toURL(), 'get', - 'we don\'t generate thumbnails for directory')), - 0); + const error = this.createError_(entry.toURL(), 'get', 'no thumbnail'); + setTimeout(callback.bind(null, error), 0); return; } - // TODO(ryoh): mediaGalleries API does not handle - // image metadata correctly. + + const type = FileType.getType(entry); + + // TODO(ryoh): mediaGalleries API does not handle image metadata correctly. // We parse it in our pure js parser. // chrome/browser/media_galleries/fileapi/supported_image_type_validator.cc - const type = FileType.getType(entry); if (type && type.type === 'image') { const url = entry.toURL(); if (this.callbacks_[url]) { @@ -109,6 +106,55 @@ } return; } + + if (type && type.type === 'raw' && names.includes('ifd')) { + names.splice(names.indexOf('ifd'), 1); // Remove ifd from names. + + /** + * Creates an ifdError metadata item: when reading the fileEntry failed + * or extracting its ifd data failed. + * @param {!Entry} fileEntry + * @param {string} error + */ + function createIfdError(fileEntry, error) { + const url = fileEntry.toURL(); + const step = 'read file entry'; + const item = new MetadataItem(); + item.ifdError = new ContentMetadataProvider.Error(url, step, error); + return item; + } + + new Promise((resolve, reject) => { + entry.file( + file => { + const request = LoadImageRequest.createForUrl(entry.toURL()); + request.maxWidth = ThumbnailLoader.THUMBNAIL_MAX_WIDTH; + request.maxHeight = ThumbnailLoader.THUMBNAIL_MAX_HEIGHT; + request.timestamp = file.lastModified; + request.cache = true; + request.priority = 0; + ImageLoaderClient.getInstance().load(request, resolve); + }, + error => { + callback(createIfdError(entry, error.toString())); + }); + }).then(result => { + if (result.status === LoadImageResponseStatus.SUCCESS) { + const item = new MetadataItem(); + if (result.ifd) { + item.ifd = /** @type {!Object} */ (JSON.parse(result.ifd)); + } + callback(item); + } else { + callback(createIfdError(entry, 'raw file has no ifd data')); + } + }); + + if (!names.length) { + return; + } + } + this.getFromMediaGalleries_(entry, names).then(callback); }
diff --git a/ui/file_manager/file_manager/foreground/js/metadata_box_controller.js b/ui/file_manager/file_manager/foreground/js/metadata_box_controller.js index 4ed41605e..1901096a 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata_box_controller.js +++ b/ui/file_manager/file_manager/foreground/js/metadata_box_controller.js
@@ -90,12 +90,28 @@ /** * @const {!Array<string>} */ -MetadataBoxController.GENERAL_METADATA_NAME = [ +MetadataBoxController.GENERAL_METADATA_NAMES = [ 'size', 'modificationTime', ]; /** + * @const {!Array<string>} + */ +MetadataBoxController.EXTRA_METADATA_NAMES = [ + 'ifd', + 'imageHeight', + 'imageWidth', + 'mediaAlbum', + 'mediaArtist', + 'mediaDuration', + 'mediaGenre', + 'mediaTitle', + 'mediaTrack', + 'mediaYearRecorded', +]; + +/** * Update the view of metadata box. * @param {!Event} event * @@ -125,7 +141,7 @@ // Do not clear isSizeLoading and size fields when the entry is not changed. this.metadataBox_.clear(isSameEntry); - const metadata = MetadataBoxController.GENERAL_METADATA_NAME.concat( + const metadata = MetadataBoxController.GENERAL_METADATA_NAMES.concat( ['alternateUrl', 'externalFileUrl', 'hosted']); this.metadataModel_.get([entry], metadata) .then(this.onGeneralMetadataLoaded_.bind(this, entry, isSameEntry)); @@ -170,46 +186,39 @@ if (['image', 'video', 'audio'].includes(type)) { if (item.externalFileUrl || item.alternateUrl) { - this.metadataModel_.get([entry], ['imageHeight', 'imageWidth']) - .then(items => { - const item = items[0]; - this.metadataBox_.imageHeight = - /** @type {number} */ (item.imageHeight); - this.metadataBox_.imageWidth = - /** @type {number} */ (item.imageWidth); - this.metadataBox_.metadataRendered('meta'); - }); + const data = ['imageHeight', 'imageWidth']; + this.metadataModel_.get([entry], data).then(items => { + this.metadataBox_.imageWidth = items[0].imageWidth || 0; + this.metadataBox_.imageHeight = items[0].imageHeight || 0; + this.metadataBox_.metadataRendered('meta'); + }); } else { - this.metadataModel_ - .get( - [entry], - [ - 'ifd', - 'imageHeight', - 'imageWidth', - 'mediaAlbum', - 'mediaArtist', - 'mediaDuration', - 'mediaGenre', - 'mediaTitle', - 'mediaTrack', - 'mediaYearRecorded', - ]) - .then(items => { - const item = items[0]; - this.metadataBox_.ifd = item.ifd || null; - this.metadataBox_.imageHeight = item.imageHeight || 0; - this.metadataBox_.imageWidth = item.imageWidth || 0; - this.metadataBox_.mediaAlbum = item.mediaAlbum || ''; - this.metadataBox_.mediaArtist = item.mediaArtist || ''; - this.metadataBox_.mediaDuration = item.mediaDuration || 0; - this.metadataBox_.mediaGenre = item.mediaGenre || ''; - this.metadataBox_.mediaTitle = item.mediaTitle || ''; - this.metadataBox_.mediaTrack = item.mediaTrack || ''; - this.metadataBox_.mediaYearRecorded = item.mediaYearRecorded || ''; - this.metadataBox_.metadataRendered('meta'); - }); + const data = MetadataBoxController.EXTRA_METADATA_NAMES; + this.metadataModel_.get([entry], data).then(items => { + const item = items[0]; + this.metadataBox_.ifd = item.ifd || null; + this.metadataBox_.imageHeight = item.imageHeight || 0; + this.metadataBox_.imageWidth = item.imageWidth || 0; + this.metadataBox_.mediaAlbum = item.mediaAlbum || ''; + this.metadataBox_.mediaArtist = item.mediaArtist || ''; + this.metadataBox_.mediaDuration = item.mediaDuration || 0; + this.metadataBox_.mediaGenre = item.mediaGenre || ''; + this.metadataBox_.mediaTitle = item.mediaTitle || ''; + this.metadataBox_.mediaTrack = item.mediaTrack || ''; + this.metadataBox_.mediaYearRecorded = item.mediaYearRecorded || ''; + this.metadataBox_.metadataRendered('meta'); + }); } + } else if (type === 'raw') { + const data = ['ifd']; + this.metadataModel_.get([entry], data).then(items => { + const raw = items[0].ifd ? items[0].ifd : {}; + this.metadataBox_.type = items[0].ifd ? 'image' : ''; + this.metadataBox_.ifd = items[0].ifd ? {raw} : null; + this.metadataBox_.imageWidth = raw.width || 0; + this.metadataBox_.imageHeight = raw.height || 0; + this.metadataBox_.metadataRendered('meta'); + }); } };
diff --git a/ui/file_manager/file_manager/foreground/js/task_controller.js b/ui/file_manager/file_manager/foreground/js/task_controller.js index d9f20a20..7a157cb0 100644 --- a/ui/file_manager/file_manager/foreground/js/task_controller.js +++ b/ui/file_manager/file_manager/foreground/js/task_controller.js
@@ -443,11 +443,16 @@ this.ui_.fileContextMenu.defaultTaskMenuItem.style.backgroundImage = ''; this.ui_.fileContextMenu.defaultTaskMenuItem.setAttribute( 'file-type-icon', defaultTask.iconType); + this.ui_.fileContextMenu.defaultTaskMenuItem.style.marginInlineEnd = + '28px'; } else if (defaultTask.iconUrl) { this.ui_.fileContextMenu.defaultTaskMenuItem.style.backgroundImage = 'url(' + defaultTask.iconUrl + ')'; + this.ui_.fileContextMenu.defaultTaskMenuItem.style.marginInlineEnd = + '28px'; } else { this.ui_.fileContextMenu.defaultTaskMenuItem.style.backgroundImage = ''; + this.ui_.fileContextMenu.defaultTaskMenuItem.style.marginInlineEnd = ''; } if (defaultTask.taskId === FileTasks.ZIP_ARCHIVER_UNZIP_TASK_ID) {
diff --git a/ui/file_manager/file_manager/foreground/js/thumbnail_loader.js b/ui/file_manager/file_manager/foreground/js/thumbnail_loader.js index 671168334..21ef2d2 100644 --- a/ui/file_manager/file_manager/foreground/js/thumbnail_loader.js +++ b/ui/file_manager/file_manager/foreground/js/thumbnail_loader.js
@@ -199,15 +199,15 @@ } /** - * Loads thumbnail as data url. If data url of thumbnail can be fetched from + * Loads thumbnail as dataUrl. If the thumbnail dataUrl can be fetched from * metadata, this fetches it from it. Otherwise, this tries to load it from * thumbnail loader. * Compared with ThumbnailLoader.load, this method does not provide a * functionality to fit image to a box. * - * @param {ThumbnailLoader.FillMode} fillMode Only FIT and OVER_FILL is - * supported. This takes effect only when external thumbnail source is - * used. + * @param {ThumbnailLoader.FillMode} fillMode Only FIT and OVER_FILL are + * supported. This takes effect only when an external thumbnail source + * is used. * @return {!Promise<{data:string, width:number, height:number}>} A promise * which is resolved when data url is fetched. * @@ -219,12 +219,26 @@ fillMode === ThumbnailLoader.FillMode.OVER_FILL); return new Promise((resolve, reject) => { - // Load by using ImageLoaderClient. + let requestUrl = this.thumbnailUrl_; + + if (fillMode === ThumbnailLoader.FillMode.OVER_FILL) { + // Use the croppedThumbnailUrl_ if available. + requestUrl = this.croppedThumbnailUrl_ || this.thumbnailUrl_; + } + + if (!requestUrl) { + const error = LoadImageResponseStatus.ERROR; + reject(new LoadImageResponse(error, 0)); + return; + } + const modificationTime = this.metadata_ && this.metadata_.filesystem && this.metadata_.filesystem.modificationTime && this.metadata_.filesystem.modificationTime.getTime(); - let request = LoadImageRequest.createRequest({ - url: this.thumbnailUrl_, + + // Load using ImageLoaderClient. + const request = LoadImageRequest.createRequest({ + url: requestUrl, maxWidth: ThumbnailLoader.THUMBNAIL_MAX_WIDTH, maxHeight: ThumbnailLoader.THUMBNAIL_MAX_HEIGHT, cache: true, @@ -234,10 +248,6 @@ }); if (fillMode === ThumbnailLoader.FillMode.OVER_FILL) { - // Use cropped thumbnail url if available. - request.url = this.croppedThumbnailUrl_ ? this.croppedThumbnailUrl_ : - this.thumbnailUrl_; - // Set crop option to image loader. Since image of croppedThumbnailUrl_ // is 360x360 with current implementation, it's no problem to crop it. request.width = 360;
diff --git a/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js b/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js index 00d6f53..07a5831 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js +++ b/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js
@@ -338,12 +338,25 @@ if (signal === 'cancel' && item.cancelCallback) { item.cancelCallback(); } + if (signal === 'dismiss') { + this.feedbackHost_.removePanelItem(panelItem); + } }; panelItem.progress = item.progressRateInPercent.toString(); - // Remove the feedback panel when complete, and create - // an activity complete panel. - if (item.state == 'completed') { - this.feedbackHost_.removePanelItem(panelItem); + switch (item.state) { + case 'completed': + case 'canceled': + // Remove the feedback panel when complete, and TODO(create + // an activity complete panel). + this.feedbackHost_.removePanelItem(panelItem); + break; + case 'error': + panelItem.panelType = panelItem.panelTypeError; + panelItem.setAttribute( + 'primary-text', item.message.replace(/\. .*/, '.')); + panelItem.setAttribute( + 'secondary-text', item.message.replace(/.*\. /, '')); + break; } } else if (panelItem) { this.feedbackHost_.removePanelItem(panelItem);
diff --git a/ui/file_manager/file_manager/main.html b/ui/file_manager/file_manager/main.html index 2650ee9..8b22663 100644 --- a/ui/file_manager/file_manager/main.html +++ b/ui/file_manager/file_manager/main.html
@@ -24,7 +24,6 @@ <link rel="stylesheet" href="foreground/css/file_status.css"> <link rel="stylesheet" href="foreground/css/file_types.css"> <link rel="stylesheet" href="foreground/css/common.css"> - <link rel="stylesheet" href="foreground/elements/files_xf_elements.css"> <link rel="stylesheet" href="cws_widget/cws_widget_container.css"> <script src="foreground/js/elements_importer.js"></script> @@ -543,10 +542,10 @@ </div> </div> </div> - <div class="feedback-panels"> + <div class="files-feedback-panels"> <xf-display-panel id="completed-panel"> </xf-display-panel> - <div class="xf-vertical-padder-8"></div> + <div class="files-vertical-padder-8"></div> <xf-display-panel id="progress-panel"> </xf-display-panel> </div>
diff --git a/ui/file_manager/file_manager/test/scripts/create_test_main.py b/ui/file_manager/file_manager/test/scripts/create_test_main.py index 976a6fb..d3b1b85 100755 --- a/ui/file_manager/file_manager/test/scripts/create_test_main.py +++ b/ui/file_manager/file_manager/test/scripts/create_test_main.py
@@ -236,7 +236,7 @@ ('foreground/elements/files_toast.html', ()), ('foreground/elements/files_toggle_ripple.html', ()), ('foreground/elements/files_tooltip.html', ()), - ('foreground/elements/files_xf_elements.css', ()), + ('foreground/elements/files_xf_elements.html', ()), ('foreground/elements/icons.html', ()), ): buf = i18n(read('ui/file_manager/file_manager/' + filename))
diff --git a/ui/file_manager/file_manager_resources.grd b/ui/file_manager/file_manager_resources.grd index 43cf66b8..aacbd78c 100644 --- a/ui/file_manager/file_manager_resources.grd +++ b/ui/file_manager/file_manager_resources.grd
@@ -57,6 +57,12 @@ <include name="IDR_FILE_MANAGER_ELEMENTS_FILES_TOOLTIP_HTML" file="file_manager/foreground/elements/files_tooltip.html" type="BINDATA" /> <include name="IDR_FILE_MANAGER_ELEMENTS_FILES_TOOLTIP_JS" file="file_manager/foreground/elements/files_tooltip.js" type="BINDATA" /> <include name="IDR_FILE_MANAGER_ELEMENTS_ICONS_HTML" file="file_manager/foreground/elements/icons.html" type="BINDATA" /> + <include name="IDR_FILE_MANAGER_ELEMENTS_XF_ACTIVITY_COMPLETE_JS" file="file_manager/foreground/elements/xf_activity_complete.js" type="BINDATA" /> + <include name="IDR_FILE_MANAGER_ELEMENTS_XF_BUTTON_JS" file="file_manager/foreground/elements/xf_button.js" type="BINDATA" /> + <include name="IDR_FILE_MANAGER_ELEMENTS_XF_CIRCULAR_PROGRESS_JS" file="file_manager/foreground/elements/xf_circular_progress.js" type="BINDATA" /> + <include name="IDR_FILE_MANAGER_ELEMENTS_XF_DISPLAY_PANEL_JS" file="file_manager/foreground/elements/xf_display_panel.js" type="BINDATA" /> + <include name="IDR_FILE_MANAGER_ELEMENTS_XF_PANEL_ITEM_JS" file="file_manager/foreground/elements/xf_panel_item.js" type="BINDATA" /> + <include name="IDR_FILE_MANAGER_ELEMENTS_FILES_XF_ELEMENTS_HTML" file="file_manager/foreground/elements/files_xf_elements.html" type="BINDATA" /> <!-- Scripts required by the metadata parser worker. --> <include name="IDR_FILE_MANAGER_UTIL" file="file_manager/common/js/util.js" type="BINDATA" /> @@ -137,7 +143,6 @@ <include name="IDR_FILE_MANAGER_IMG_UI_2X_DRIVE_WELCOME_LOGO" file="file_manager/foreground/images/files/ui/2x/drive_logo.png" type="BINDATA" /> <include name="IDR_FILE_MANAGER_IMG_UI_DRIVE_WELCOME_PEOPLE" file="file_manager/foreground/images/files/ui/drive_banner_people.png" type="BINDATA" /> <include name="IDR_FILE_MANAGER_IMG_UI_2X_DRIVE_WELCOME_PEOPLE" file="file_manager/foreground/images/files/ui/2x/drive_banner_people.png" type="BINDATA" /> - <include name="IDR_FILE_MANAGER_ELEMENTS_FILES_XF_ELEMENTS_CSS" file="file_manager/foreground/elements/files_xf_elements.css" type="BINDATA" /> <!-- The VideoPlayer app pages and scripts. --> <include name="IDR_VIDEO_PLAYER_MANIFEST" file="video_player/manifest.json" type="BINDATA" />
diff --git a/ui/file_manager/integration_tests/file_manager/quick_view.js b/ui/file_manager/integration_tests/file_manager/quick_view.js index 30e9cd5..c2676ed 100644 --- a/ui/file_manager/integration_tests/file_manager/quick_view.js +++ b/ui/file_manager/integration_tests/file_manager/quick_view.js
@@ -855,9 +855,13 @@ const mimeType = await getQuickViewMetadataBoxField(appId, 'Type'); chrome.test.assertEq('image/x-olympus-orf', mimeType); - // Check: the image EXIF metadata should be displayed. - // TODO(crbug.com/965370) Make the metadata controller extract and display - // the RAW image EXIF metadata in the metadata box. + // Check: the RAW image EXIF metadata should be displayed. + const size = await getQuickViewMetadataBoxField(appId, 'Dimensions'); + chrome.test.assertEq('4608 x 3456', size); + const model = await getQuickViewMetadataBoxField(appId, 'Device model'); + chrome.test.assertEq(model, 'E-M1'); + const film = await getQuickViewMetadataBoxField(appId, 'Device settings'); + chrome.test.assertEq('f/8 0.002 12mm ISO200', film); }; /**
diff --git a/ui/native_theme/native_theme_aura.cc b/ui/native_theme/native_theme_aura.cc index 0e50ee39..5cf936b 100644 --- a/ui/native_theme/native_theme_aura.cc +++ b/ui/native_theme/native_theme_aura.cc
@@ -57,6 +57,12 @@ const SkColor kCheckboxAndRadioStrokeDisabledColor = SkColorSetRGB(0xC5, 0xC5, 0xC5); +const int kInputBorderRadius = 2; +const int kInputBorderWidth = 1; +const SkColor kInputBorderColor = SkColorSetRGB(0xCE, 0xCE, 0xCE); +const SkColor kInputBorderHoveredColor = SkColorSetRGB(0x9D, 0x9D, 0x9D); +const SkColor kInputBorderDisabledColor = SkColorSetRGB(0xC5, 0xC5, 0xC5); + } // namespace //////////////////////////////////////////////////////////////////////////////// @@ -444,6 +450,40 @@ return skrect; } +void NativeThemeAura::PaintTextField(cc::PaintCanvas* canvas, + State state, + const gfx::Rect& rect, + const TextFieldExtraParams& text) const { + if (!features::IsFormControlsRefreshEnabled()) { + return NativeThemeBase::PaintTextField(canvas, state, rect, text); + } + + SkRect bounds = gfx::RectToSkRect(rect); + const SkScalar borderWidth = SkIntToScalar(kInputBorderWidth); + + // Paint the background (is not visible behind the rounded corners). + bounds.inset(borderWidth / 2, borderWidth / 2); + cc::PaintFlags fill_flags; + fill_flags.setStyle(cc::PaintFlags::kFill_Style); + fill_flags.setColor(text.background_color); + canvas->drawRoundRect(bounds, SkIntToScalar(kInputBorderRadius), + SkIntToScalar(kInputBorderRadius), fill_flags); + + // Paint the border: 1px solid. + cc::PaintFlags stroke_flags; + if (state == kHovered) { + stroke_flags.setColor(kInputBorderHoveredColor); + } else if (state == kDisabled) { + stroke_flags.setColor(kInputBorderDisabledColor); + } else { + stroke_flags.setColor(kInputBorderColor); + } + stroke_flags.setStyle(cc::PaintFlags::kStroke_Style); + stroke_flags.setStrokeWidth(borderWidth); + canvas->drawRoundRect(bounds, SkIntToScalar(kInputBorderRadius), + SkIntToScalar(kInputBorderRadius), stroke_flags); +} + gfx::Size NativeThemeAura::GetPartSize(Part part, State state, const ExtraParams& extra) const {
diff --git a/ui/native_theme/native_theme_aura.h b/ui/native_theme/native_theme_aura.h index 5c08f42..e16358b 100644 --- a/ui/native_theme/native_theme_aura.h +++ b/ui/native_theme/native_theme_aura.h
@@ -60,6 +60,10 @@ State state, const gfx::Rect& rect, const ButtonExtraParams& button) const override; + void PaintTextField(cc::PaintCanvas* canvas, + State state, + const gfx::Rect& rect, + const TextFieldExtraParams& text) const override; gfx::Size GetPartSize(Part part, State state, const ExtraParams& extra) const override;
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn index 5d8a5a1..a83c5c3 100644 --- a/ui/views/BUILD.gn +++ b/ui/views/BUILD.gn
@@ -1007,6 +1007,7 @@ "controls/editable_combobox/editable_combobox_unittest.cc", "controls/image_view_unittest.cc", "controls/label_unittest.cc", + "controls/menu/menu_closure_animation_mac_unittest.cc", "controls/menu/menu_controller_unittest.cc", "controls/menu/menu_item_view_unittest.cc", "controls/menu/menu_model_adapter_unittest.cc", @@ -1041,6 +1042,7 @@ "focus/focus_traversal_unittest.cc", "layout/box_layout_unittest.cc", "layout/fill_layout_unittest.cc", + "layout/flex_layout_types_internal_unittest.cc", "layout/flex_layout_unittest.cc", "layout/grid_layout_unittest.cc", "layout/interpolating_layout_manager_unittest.cc",
diff --git a/ui/views/animation/animation_delegate_views.cc b/ui/views/animation/animation_delegate_views.cc index 0068b6ba..8df39d58 100644 --- a/ui/views/animation/animation_delegate_views.cc +++ b/ui/views/animation/animation_delegate_views.cc
@@ -12,7 +12,8 @@ namespace views { AnimationDelegateViews::AnimationDelegateViews(View* view) : view_(view) { - scoped_observer_.Add(view); + if (view) + scoped_observer_.Add(view); } AnimationDelegateViews::~AnimationDelegateViews() {
diff --git a/ui/views/animation/animation_delegate_views.h b/ui/views/animation/animation_delegate_views.h index 37f8e7c..ee025be 100644 --- a/ui/views/animation/animation_delegate_views.h +++ b/ui/views/animation/animation_delegate_views.h
@@ -18,7 +18,7 @@ class View; // Provides default implementaton to adapt CompositorAnimationRunner for -// Animation. +// Animation. Falls back to the default animation runner when |view| is nullptr. class VIEWS_EXPORT AnimationDelegateViews : public gfx::AnimationDelegate, public ViewObserver,
diff --git a/ui/views/bubble/bubble_dialog_delegate_view.cc b/ui/views/bubble/bubble_dialog_delegate_view.cc index 96d3642..d5458e6 100644 --- a/ui/views/bubble/bubble_dialog_delegate_view.cc +++ b/ui/views/bubble/bubble_dialog_delegate_view.cc
@@ -265,6 +265,15 @@ } void BubbleDialogDelegateView::SetArrow(BubbleBorder::Arrow arrow) { + SetArrowWithoutResizing(arrow); + // If SetArrow() is called before CreateWidget(), there's no need to update + // the BubbleFrameView. + if (GetBubbleFrameView()) + SizeToContents(); +} + +void BubbleDialogDelegateView::SetArrowWithoutResizing( + BubbleBorder::Arrow arrow) { if (base::i18n::IsRTL()) arrow = BubbleBorder::horizontal_mirror(arrow); if (arrow_ == arrow) @@ -273,10 +282,8 @@ // If SetArrow() is called before CreateWidget(), there's no need to update // the BubbleFrameView. - if (GetBubbleFrameView()) { + if (GetBubbleFrameView()) GetBubbleFrameView()->SetArrow(arrow); - SizeToContents(); - } } gfx::Rect BubbleDialogDelegateView::GetAnchorRect() const {
diff --git a/ui/views/bubble/bubble_dialog_delegate_view.h b/ui/views/bubble/bubble_dialog_delegate_view.h index cd25d7c..e11681e 100644 --- a/ui/views/bubble/bubble_dialog_delegate_view.h +++ b/ui/views/bubble/bubble_dialog_delegate_view.h
@@ -79,9 +79,19 @@ // The anchor rect is used in the absence of an assigned anchor view. const gfx::Rect& anchor_rect() const { return anchor_rect_; } - // Set the desired arrow for the bubble. The arrow will be mirrored for RTL. + // Set the desired arrow for the bubble and updates the bubble's bounds + // accordingly. The arrow will be mirrored for RTL. void SetArrow(BubbleBorder::Arrow arrow); + // Sets the arrow without recaluclating or updating bounds. This could be used + // proceeding another function call which also sets bounds, so that bounds are + // not set multiple times in a row. When animating bounds changes, setting + // bounds twice in a row can make the widget position jump. + // TODO(crbug.com/982880) It would be good to be able to re-target the + // animation rather than expet callers to use SetArrowWithoutResizing if they + // are also changing the anchor rect, or similar. + void SetArrowWithoutResizing(BubbleBorder::Arrow arrow); + BubbleBorder::Shadow GetShadow() const; void set_shadow(BubbleBorder::Shadow shadow) { shadow_ = shadow; }
diff --git a/ui/views/controls/menu/menu_closure_animation_mac.h b/ui/views/controls/menu/menu_closure_animation_mac.h index e966edd..fecbe83fc 100644 --- a/ui/views/controls/menu/menu_closure_animation_mac.h +++ b/ui/views/controls/menu/menu_closure_animation_mac.h
@@ -6,6 +6,7 @@ #define UI_VIEWS_CONTROLS_MENU_MENU_CLOSURE_ANIMATION_MAC_H_ #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "base/timer/timer.h" #include "ui/gfx/animation/animation.h" #include "ui/gfx/animation/animation_delegate.h" @@ -29,7 +30,9 @@ // This class also supports animating a menu away without animating the // selection effect, which is achieved by passing nullptr for the item to // animate. In this case, the animation skips straight to step 3 above. -class VIEWS_EXPORT MenuClosureAnimationMac : public gfx::AnimationDelegate { +class VIEWS_EXPORT MenuClosureAnimationMac + : public gfx::AnimationDelegate, + public base::SupportsWeakPtr<MenuClosureAnimationMac> { public: // After this closure animation is done, |callback| is run to finish // dismissing the menu. If |item| is given, this will animate the item being
diff --git a/ui/views/controls/menu/menu_closure_animation_mac.mm b/ui/views/controls/menu/menu_closure_animation_mac.mm index 1ebd33f..b4d8b6fd 100644 --- a/ui/views/controls/menu/menu_closure_animation_mac.mm +++ b/ui/views/controls/menu/menu_closure_animation_mac.mm
@@ -39,7 +39,7 @@ step_ = AnimationStep::kFading; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&MenuClosureAnimationMac::AdvanceAnimation, - base::Unretained(this))); + AsWeakPtr())); return; } AdvanceAnimation();
diff --git a/ui/views/controls/menu/menu_closure_animation_mac_unittest.cc b/ui/views/controls/menu/menu_closure_animation_mac_unittest.cc new file mode 100644 index 0000000..ef40b47 --- /dev/null +++ b/ui/views/controls/menu/menu_closure_animation_mac_unittest.cc
@@ -0,0 +1,28 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/views/controls/menu/menu_closure_animation_mac.h" + +#include "base/test/bind_test_util.h" +#include "base/test/scoped_task_environment.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/views/test/menu_test_utils.h" + +TEST(MenuClosureAnimationMacTest, DestructCancelsCleanly) { + views::test::DisableMenuClosureAnimations(); + base::test::ScopedTaskEnvironment environment; + + bool called = false; + auto animation = std::make_unique<views::MenuClosureAnimationMac>( + nullptr, nullptr, base::BindLambdaForTesting([&]() { called = true; })); + + animation->Start(); + animation.reset(); + + // If the animation callback runs after the animation is destroyed, this line + // may crash; if not, |called| will get set to true and fail the test below. + views::test::WaitForMenuClosureAnimation(); + + EXPECT_FALSE(called); +}
diff --git a/ui/views/layout/flex_layout.cc b/ui/views/layout/flex_layout.cc index 8c76abb2..d36cf00 100644 --- a/ui/views/layout/flex_layout.cc +++ b/ui/views/layout/flex_layout.cc
@@ -229,7 +229,7 @@ // The total size of the layout (minus parent insets). NormalizedSize total_size; NormalizedInsets interior_margin; - gfx::Insets host_insets; + NormalizedInsets host_insets; private: DISALLOW_COPY_AND_ASSIGN(FlexLayoutData); @@ -305,10 +305,10 @@ const SizeBounds& size_bounds) const { FlexLayoutData data; - data.host_insets = host_view()->GetInsets(); + data.host_insets = Normalize(orientation(), host_view()->GetInsets()); data.interior_margin = Normalize(orientation(), interior_margin()); NormalizedSizeBounds bounds = Normalize(orientation(), size_bounds); - bounds.Inset(Normalize(orientation(), data.host_insets)); + bounds.Inset(data.host_insets); if (bounds.cross() && *bounds.cross() < minimum_cross_axis_size()) bounds.set_cross(minimum_cross_axis_size()); @@ -334,9 +334,10 @@ } // Calculate the size of the host view. - data.layout.host_size = Denormalize(orientation(), data.total_size); - data.layout.host_size.Enlarge(data.host_insets.width(), - data.host_insets.height()); + NormalizedSize host_size = data.total_size; + host_size.Enlarge(data.host_insets.main_size(), + data.host_insets.cross_size()); + data.layout.host_size = Denormalize(orientation(), host_size); // Size and position the children in screen space. CalculateChildBounds(size_bounds, &data); @@ -408,11 +409,10 @@ // Apply main axis alignment (we've already done cross-axis alignment above). int available_main = (size_bounds.width() ? *size_bounds.width() : data->layout.host_size.width()); - available_main = std::max(0, available_main - data->host_insets.width()); + available_main = std::max(0, available_main - data->host_insets.main_size()); const int excess_main = available_main - data->total_size.main(); - NormalizedPoint start = - Normalize(orientation(), - gfx::Point(data->host_insets.left(), data->host_insets.top())); + NormalizedPoint start(data->host_insets.main_leading(), + data->host_insets.cross_leading()); switch (main_axis_alignment()) { case LayoutAlignment::kStart: break;
diff --git a/ui/views/layout/flex_layout_types_internal.cc b/ui/views/layout/flex_layout_types_internal.cc index 7e467f9..f6c636a 100644 --- a/ui/views/layout/flex_layout_types_internal.cc +++ b/ui/views/layout/flex_layout_types_internal.cc
@@ -206,6 +206,7 @@ origin_.SetPoint(origin_main, origin_cross); size_.SetSize(size_main, size_cross); } + void NormalizedRect::SetByBounds(int origin_main, int origin_cross, int max_main, @@ -214,17 +215,25 @@ size_.SetSize(std::max(0, max_main - origin_main), std::max(0, max_cross - origin_cross)); } + void NormalizedRect::Inset(const NormalizedInsets& insets) { Inset(insets.main_leading(), insets.cross_leading(), insets.main_trailing(), insets.cross_trailing()); } + void NormalizedRect::Inset(int main, int cross) { Inset(main, cross, main, cross); } + void NormalizedRect::Inset(int main_leading, int cross_leading, int main_trailing, - int cross_trailing) {} + int cross_trailing) { + origin_.Offset(main_leading, cross_leading); + size_.Enlarge(-(main_leading + main_trailing), + -(cross_leading + cross_trailing)); +} + void NormalizedRect::Offset(int main, int cross) { origin_.Offset(main, cross); }
diff --git a/ui/views/layout/flex_layout_types_internal.h b/ui/views/layout/flex_layout_types_internal.h index bdefe8e..b52361b 100644 --- a/ui/views/layout/flex_layout_types_internal.h +++ b/ui/views/layout/flex_layout_types_internal.h
@@ -9,6 +9,7 @@ #include "base/optional.h" #include "ui/views/layout/flex_layout_types.h" +#include "ui/views/views_export.h" namespace gfx { class Insets; @@ -23,10 +24,13 @@ namespace internal { +// NOTE: classes in this namespace are marked as VIEWS_EXPORT for unit testing +// purposes only and should not be used outside the views library. + // Represents a point in layout space - that is, a point on the main and cross // axes of the layout (regardless of whether it is vertically or horizontally // oriented. -class NormalizedPoint { +class VIEWS_EXPORT NormalizedPoint { public: constexpr NormalizedPoint() = default; constexpr NormalizedPoint(int main, int cross) : main_(main), cross_(cross) {} @@ -54,7 +58,7 @@ // Represents a size in layout space - that is, a size on the main and cross // axes of the layout (regardless of whether it is vertically or horizontally // oriented. -class NormalizedSize { +class VIEWS_EXPORT NormalizedSize { public: constexpr NormalizedSize() = default; constexpr NormalizedSize(int main, int cross) : main_(main), cross_(cross) {} @@ -88,7 +92,7 @@ // Represents insets in layout space - that is, insets on the main and cross // axes of the layout (regardless of whether it is vertically or horizontally // oriented. -class NormalizedInsets { +class VIEWS_EXPORT NormalizedInsets { public: constexpr NormalizedInsets() = default; constexpr explicit NormalizedInsets(int all) : main_(all), cross_(all) {} @@ -145,7 +149,7 @@ // Represents size bounds in layout space - that is, a set of size bounds using // the main and cross axes of the layout (regardless of whether it is vertically // or horizontally oriented). -class NormalizedSizeBounds { +class VIEWS_EXPORT NormalizedSizeBounds { public: NormalizedSizeBounds(); NormalizedSizeBounds(const base::Optional<int>& main, @@ -176,7 +180,7 @@ // Represents a rectangle in layout space - that is, a rectangle whose // dimensions align with the main and cross axis of the layout (regardless of // whether the layout is vertically or horizontally oriented). -class NormalizedRect { +class VIEWS_EXPORT NormalizedRect { public: constexpr NormalizedRect() = default; constexpr NormalizedRect(const NormalizedPoint& origin,
diff --git a/ui/views/layout/flex_layout_types_internal_unittest.cc b/ui/views/layout/flex_layout_types_internal_unittest.cc new file mode 100644 index 0000000..8dceb4e --- /dev/null +++ b/ui/views/layout/flex_layout_types_internal_unittest.cc
@@ -0,0 +1,50 @@ +// Copyright (c) 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/views/layout/flex_layout_types_internal.h" + +#include "testing/gtest/include/gtest/gtest.h" + +namespace views { +namespace internal { + +TEST(NormalizedRectTest, Inset_NormalizedInsets) { + NormalizedRect rect(1, 2, 10, 11); + constexpr NormalizedInsets kInsets(1, 2, 3, 4); + rect.Inset(kInsets); + EXPECT_EQ(2, rect.origin_main()); + EXPECT_EQ(4, rect.origin_cross()); + EXPECT_EQ(6, rect.size_main()); + EXPECT_EQ(5, rect.size_cross()); +} + +TEST(NormalizedRectTest, Inset_FourValue) { + NormalizedRect rect(1, 2, 10, 11); + rect.Inset(1, 2, 3, 4); + EXPECT_EQ(2, rect.origin_main()); + EXPECT_EQ(4, rect.origin_cross()); + EXPECT_EQ(6, rect.size_main()); + EXPECT_EQ(5, rect.size_cross()); +} + +TEST(NormalizedRectTest, Inset_TwoValue) { + NormalizedRect rect(1, 2, 10, 11); + rect.Inset(3, 4); + EXPECT_EQ(4, rect.origin_main()); + EXPECT_EQ(6, rect.origin_cross()); + EXPECT_EQ(4, rect.size_main()); + EXPECT_EQ(3, rect.size_cross()); +} + +TEST(NormalizedRectTest, Inset_Negative) { + NormalizedRect rect(1, 2, 10, 11); + rect.Inset(-1, -2, -3, -4); + EXPECT_EQ(0, rect.origin_main()); + EXPECT_EQ(0, rect.origin_cross()); + EXPECT_EQ(14, rect.size_main()); + EXPECT_EQ(17, rect.size_cross()); +} + +} // namespace internal +} // namespace views
diff --git a/ui/views/layout/flex_layout_unittest.cc b/ui/views/layout/flex_layout_unittest.cc index 5bda1d2c4..152b8cf 100644 --- a/ui/views/layout/flex_layout_unittest.cc +++ b/ui/views/layout/flex_layout_unittest.cc
@@ -117,6 +117,7 @@ protected: // Constants re-used in many tests. + static const Insets kSmallInsets; static const Insets kLayoutInsets; static const Insets kLargeInsets; static const Size kChild1Size; @@ -148,6 +149,7 @@ FlexLayout* layout_; }; +const Insets FlexLayoutTest::kSmallInsets{1, 2, 3, 4}; const Insets FlexLayoutTest::kLayoutInsets{5, 6, 7, 9}; const Insets FlexLayoutTest::kLargeInsets{10, 11, 12, 13}; const Size FlexLayoutTest::kChild1Size{12, 10}; @@ -210,13 +212,20 @@ EXPECT_EQ(Size(0, 0), host_->GetMinimumSize()); } -TEST_F(FlexLayoutTest, GetMinimumSize_Empty_ViewInsets) { +TEST_F(FlexLayoutTest, GetMinimumSize_Empty_ViewInsets_Horizontal) { layout_->SetOrientation(LayoutOrientation::kHorizontal); layout_->SetCollapseMargins(false); host_->SetBorder(CreateEmptyBorder(kLayoutInsets)); EXPECT_EQ(Size(15, 12), host_->GetMinimumSize()); } +TEST_F(FlexLayoutTest, GetMinimumSize_Empty_ViewInsets_Vertical) { + layout_->SetOrientation(LayoutOrientation::kVertical); + layout_->SetCollapseMargins(false); + host_->SetBorder(CreateEmptyBorder(kLayoutInsets)); + EXPECT_EQ(Size(15, 12), host_->GetMinimumSize()); +} + TEST_F(FlexLayoutTest, GetMinimumSize_Empty_InternalMargin_Collapsed) { layout_->SetOrientation(LayoutOrientation::kHorizontal); layout_->SetCollapseMargins(true); @@ -248,8 +257,8 @@ EXPECT_EQ(Size(9, 7), host_->GetMinimumSize()); layout_->SetMinimumCrossAxisSize(10); EXPECT_EQ(Size(9, 10), host_->GetMinimumSize()); - host_->SetBorder(CreateEmptyBorder(2, 2, 2, 2)); - EXPECT_EQ(Size(13, 14), host_->GetMinimumSize()); + host_->SetBorder(CreateEmptyBorder(kSmallInsets)); + EXPECT_EQ(Size(15, 14), host_->GetMinimumSize()); } TEST_F(FlexLayoutTest, GetMinimumSize_MinimumCross_Vertical) { @@ -260,8 +269,8 @@ EXPECT_EQ(Size(9, 7), host_->GetMinimumSize()); layout_->SetMinimumCrossAxisSize(10); EXPECT_EQ(Size(10, 7), host_->GetMinimumSize()); - host_->SetBorder(CreateEmptyBorder(2, 2, 2, 2)); - EXPECT_EQ(Size(14, 11), host_->GetMinimumSize()); + host_->SetBorder(CreateEmptyBorder(kSmallInsets)); + EXPECT_EQ(Size(16, 11), host_->GetMinimumSize()); } // Visibility and Inclusion Tests ---------------------------------------------- @@ -721,6 +730,97 @@ EXPECT_EQ(Size(70, 50), host_->GetPreferredSize()); } +// Host insets tests ----------------------------------------------------------- + +TEST_F(FlexLayoutTest, Layout_HostInsets_Horizontal) { + layout_->SetOrientation(LayoutOrientation::kHorizontal); + host_->SetBorder(CreateEmptyBorder(kLayoutInsets)); + View* child = AddChild(kChild1Size); + host_->Layout(); + EXPECT_EQ(Rect(6, 5, 12, 10), child->bounds()); +} + +TEST_F(FlexLayoutTest, Layout_HostInsets_Vertical) { + layout_->SetOrientation(LayoutOrientation::kVertical); + host_->SetBorder(CreateEmptyBorder(kLayoutInsets)); + View* child = AddChild(kChild1Size); + host_->Layout(); + EXPECT_EQ(Rect(6, 5, 12, 10), child->bounds()); +} + +TEST_F(FlexLayoutTest, Layout_HostInsets_Horizontal_Leading) { + layout_->SetOrientation(LayoutOrientation::kHorizontal); + layout_->SetMainAxisAlignment(LayoutAlignment::kStart); + layout_->SetCrossAxisAlignment(LayoutAlignment::kStart); + host_->SetBorder(CreateEmptyBorder(kLayoutInsets)); + View* child = AddChild(kChild1Size); + host_->SetSize({100, 100}); + EXPECT_EQ(Rect(6, 5, 12, 10), child->bounds()); +} + +TEST_F(FlexLayoutTest, Layout_HostInsets_Vertical_Leading) { + layout_->SetOrientation(LayoutOrientation::kVertical); + layout_->SetMainAxisAlignment(LayoutAlignment::kStart); + layout_->SetCrossAxisAlignment(LayoutAlignment::kStart); + host_->SetBorder(CreateEmptyBorder(kLayoutInsets)); + View* child = AddChild(kChild1Size); + host_->SetSize({100, 100}); + EXPECT_EQ(Rect(6, 5, 12, 10), child->bounds()); +} + +TEST_F(FlexLayoutTest, Layout_HostInsets_Horizontal_Center) { + layout_->SetOrientation(LayoutOrientation::kHorizontal); + layout_->SetMainAxisAlignment(LayoutAlignment::kCenter); + layout_->SetCrossAxisAlignment(LayoutAlignment::kStart); + host_->SetBorder(CreateEmptyBorder(kLayoutInsets)); + View* child = AddChild(kChild1Size); + host_->SetSize({100, 100}); + const int expected_x = + kLayoutInsets.left() + + (host_->size().width() - kChild1Size.width() - kLayoutInsets.width()) / 2; + EXPECT_EQ(Rect(expected_x, 5, 12, 10), child->bounds()); +} + +TEST_F(FlexLayoutTest, Layout_HostInsets_Vertical_Center) { + layout_->SetOrientation(LayoutOrientation::kVertical); + layout_->SetMainAxisAlignment(LayoutAlignment::kCenter); + layout_->SetCrossAxisAlignment(LayoutAlignment::kStart); + host_->SetBorder(CreateEmptyBorder(kLayoutInsets)); + View* child = AddChild(kChild1Size); + host_->SetSize({100, 100}); + const int expected_y = + kLayoutInsets.top() + + (host_->size().height() - kChild1Size.height() - kLayoutInsets.height()) / + 2; + EXPECT_EQ(Rect(6, expected_y, 12, 10), child->bounds()); +} + +TEST_F(FlexLayoutTest, Layout_HostInsets_Horizontal_End) { + layout_->SetOrientation(LayoutOrientation::kHorizontal); + layout_->SetMainAxisAlignment(LayoutAlignment::kEnd); + layout_->SetCrossAxisAlignment(LayoutAlignment::kStart); + host_->SetBorder(CreateEmptyBorder(kLayoutInsets)); + View* child = AddChild(kChild1Size); + host_->SetSize({100, 100}); + const int expected_x = + kLayoutInsets.left() + + (host_->size().width() - kChild1Size.width() - kLayoutInsets.width()); + EXPECT_EQ(Rect(expected_x, 5, 12, 10), child->bounds()); +} + +TEST_F(FlexLayoutTest, Layout_HostInsets_Vertical_End) { + layout_->SetOrientation(LayoutOrientation::kVertical); + layout_->SetMainAxisAlignment(LayoutAlignment::kEnd); + layout_->SetCrossAxisAlignment(LayoutAlignment::kStart); + host_->SetBorder(CreateEmptyBorder(kLayoutInsets)); + View* child = AddChild(kChild1Size); + host_->SetSize({100, 100}); + const int expected_y = + kLayoutInsets.top() + + (host_->size().height() - kChild1Size.height() - kLayoutInsets.height()); + EXPECT_EQ(Rect(6, expected_y, 12, 10), child->bounds()); +} + // Alignment Tests ------------------------------------------------------------- TEST_F(FlexLayoutTest, Layout_CrossStart) {
diff --git a/ui/views/test/menu_test_utils.cc b/ui/views/test/menu_test_utils.cc index bd426f0..3544c40 100644 --- a/ui/views/test/menu_test_utils.cc +++ b/ui/views/test/menu_test_utils.cc
@@ -85,6 +85,7 @@ void WaitForMenuClosureAnimation() { #if defined(OS_MACOSX) + // TODO(https://crbug.com/982815): Replace this with Quit+Run. base::RunLoop().RunUntilIdle(); #endif }
diff --git a/ui/webui/resources/cr_components/certificate_manager/certificate_manager.html b/ui/webui/resources/cr_components/certificate_manager/certificate_manager.html index 10ffddf..c7f8593 100644 --- a/ui/webui/resources/cr_components/certificate_manager/certificate_manager.html +++ b/ui/webui/resources/cr_components/certificate_manager/certificate_manager.html
@@ -56,7 +56,7 @@ <certificate-list id="personalCerts" certificates="[[personalCerts]]" certificate-type="[[certificateTypeEnum_.PERSONAL]]" - import-allowed="[[importAllowed]]"> + import-allowed="[[clientImportAllowed]]"> </certificate-list> </div> <div> @@ -64,7 +64,7 @@ <certificate-list id="serverCerts" certificates="[[serverCerts]]" certificate-type="[[certificateTypeEnum_.SERVER]]" - import-allowed="[[importAllowed]]"> + import-allowed="true"> </certificate-list> </template> </div> @@ -73,7 +73,7 @@ <certificate-list id="caCerts" certificates="[[caCerts]]" certificate-type="[[certificateTypeEnum_.CA]]" - import-allowed="[[importAllowed]]"> + import-allowed="true"> </certificate-list> </template> </div> @@ -82,7 +82,7 @@ <certificate-list id="otherCerts" certificates="[[otherCerts]]" certificate-type="[[certificateTypeEnum_.OTHER]]" - import-allowed="[[importAllowed]]"> + import-allowed="false"> </certificate-list> </template> </div>
diff --git a/ui/webui/resources/cr_components/certificate_manager/certificate_manager.js b/ui/webui/resources/cr_components/certificate_manager/certificate_manager.js index 72d0ed9..b6ce82c 100644 --- a/ui/webui/resources/cr_components/certificate_manager/certificate_manager.js +++ b/ui/webui/resources/cr_components/certificate_manager/certificate_manager.js
@@ -54,7 +54,7 @@ * CertificateManagementAllowed. * Value exists only for Chrome OS. */ - importAllowed: { + clientImportAllowed: { type: Boolean, value: true, }, @@ -127,14 +127,14 @@ attached: function() { this.addWebUIListener('certificates-changed', this.set.bind(this)); this.addWebUIListener( - 'certificates-model-ready', this.setImportAllowed.bind(this)); + 'certificates-model-ready', this.setClientImportAllowed.bind(this)); certificate_manager.CertificatesBrowserProxyImpl.getInstance() .refreshCertificates(); }, /** @private */ - setImportAllowed: function(allowed) { - this.importAllowed = allowed; + setClientImportAllowed: function(allowed) { + this.clientImportAllowed = allowed; }, /**