diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-05-15 10:20:33 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-05-15 10:28:57 +0000 |
commit | d17ea114e5ef69ad5d5d7413280a13e6428098aa (patch) | |
tree | 2c01a75df69f30d27b1432467cfe7c1467a498da /chromium/chrome/browser/ui | |
parent | 8c5c43c7b138c9b4b0bf56d946e61d3bbc111bec (diff) | |
download | qtwebengine-chromium-d17ea114e5ef69ad5d5d7413280a13e6428098aa.tar.gz |
BASELINE: Update Chromium to 67.0.3396.47
Change-Id: Idcb1341782e417561a2473eeecc82642dafda5b7
Reviewed-by: Michal Klocek <michal.klocek@qt.io>
Diffstat (limited to 'chromium/chrome/browser/ui')
297 files changed, 5061 insertions, 5181 deletions
diff --git a/chromium/chrome/browser/ui/BUILD.gn b/chromium/chrome/browser/ui/BUILD.gn index e89ff1f97be..72dde06a99a 100644 --- a/chromium/chrome/browser/ui/BUILD.gn +++ b/chromium/chrome/browser/ui/BUILD.gn @@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//build/config/chromecast_build.gni") +import("//build/config/compiler/compiler.gni") import("//build/config/crypto.gni") import("//build/config/features.gni") import("//build/config/ui.gni") @@ -10,11 +11,11 @@ import("//chrome/common/features.gni") import("//components/nacl/features.gni") import("//components/offline_pages/buildflags/features.gni") import("//components/signin/features.gni") -import("//extensions/features/features.gni") +import("//extensions/buildflags/buildflags.gni") import("//media/media_options.gni") -import("//ppapi/features/features.gni") -import("//printing/features/features.gni") -import("//rlz/features/features.gni") +import("//ppapi/buildflags/buildflags.gni") +import("//printing/buildflags/buildflags.gni") +import("//rlz/buildflags/buildflags.gni") import("//ui/base/ui_features.gni") import("//ui/views/features.gni") @@ -346,6 +347,8 @@ split_static_library("ui") { "cocoa/infobars/before_translate_infobar_controller.mm", "cocoa/infobars/confirm_infobar_controller.h", "cocoa/infobars/confirm_infobar_controller.mm", + "cocoa/infobars/infobar_background_view.h", + "cocoa/infobars/infobar_background_view.mm", "cocoa/infobars/infobar_cocoa.h", "cocoa/infobars/infobar_cocoa.mm", "cocoa/infobars/infobar_container_cocoa.h", @@ -354,8 +357,6 @@ split_static_library("ui") { "cocoa/infobars/infobar_container_controller.mm", "cocoa/infobars/infobar_controller.h", "cocoa/infobars/infobar_controller.mm", - "cocoa/infobars/infobar_gradient_view.h", - "cocoa/infobars/infobar_gradient_view.mm", "cocoa/infobars/infobar_utilities.h", "cocoa/infobars/infobar_utilities.mm", "cocoa/infobars/translate_infobar_base.h", @@ -488,8 +489,6 @@ split_static_library("ui") { "cocoa/profiles/avatar_icon_controller.mm", "cocoa/profiles/profile_chooser_bridge_views.h", "cocoa/profiles/profile_chooser_bridge_views.mm", - "cocoa/profiles/profile_chooser_controller.h", - "cocoa/profiles/profile_chooser_controller.mm", "cocoa/profiles/profile_signin_confirmation_dialog_cocoa.h", "cocoa/profiles/profile_signin_confirmation_dialog_cocoa.mm", "cocoa/profiles/profile_signin_confirmation_view_controller.h", @@ -506,7 +505,6 @@ split_static_library("ui") { "cocoa/screen_capture_notification_ui_cocoa.mm", "cocoa/separate_fullscreen_window.h", "cocoa/separate_fullscreen_window.mm", - "cocoa/session_crashed_bubble.mm", "cocoa/simple_message_box_bridge_views.mm", "cocoa/simple_message_box_cocoa.h", "cocoa/simple_message_box_cocoa.mm", @@ -665,7 +663,6 @@ split_static_library("ui") { "blocked_content/tab_under_navigation_throttle.cc", "blocked_content/tab_under_navigation_throttle.h", "bookmarks/bookmark_bar.h", - "bookmarks/bookmark_bar_constants.h", "bookmarks/bookmark_bar_instructions_delegate.h", "bookmarks/bookmark_bubble_observer.h", "bookmarks/bookmark_editor.cc", @@ -748,6 +745,8 @@ split_static_library("ui") { "simple_message_box.h", "simple_message_box_internal.cc", "simple_message_box_internal.h", + "startup/bad_flags_prompt.cc", + "startup/bad_flags_prompt.h", "status_bubble.h", "sync/bubble_sync_promo_delegate.h", "sync/profile_signin_confirmation_helper.cc", @@ -828,9 +827,6 @@ split_static_library("ui") { "webui/memory_internals_ui.h", "webui/metrics_handler.cc", "webui/metrics_handler.h", - "webui/mojo_web_ui_controller.cc", - "webui/mojo_web_ui_controller.h", - "webui/mojo_web_ui_handler.h", "webui/net_export_ui.cc", "webui/net_export_ui.h", "webui/net_internals/net_internals_ui.cc", @@ -895,6 +891,14 @@ split_static_library("ui") { allow_circular_includes_from = [] defines = [] + if (is_win) { + # For version_ui.cc: + if (use_lld) { + defines += [ "CHROMIUM_LINKER_NAME=\"lld-link\"" ] + } else { + defines += [ "CHROMIUM_LINKER_NAME=\"link.exe\"" ] + } + } libs = [] configs += [ @@ -931,7 +935,9 @@ split_static_library("ui") { "//chrome/browser/devtools", "//chrome/browser/engagement:mojo_bindings", "//chrome/browser/media:mojo_bindings", + "//chrome/browser/profiling_host", "//chrome/browser/safe_browsing", + "//chrome/browser/ssl:proto", "//chrome/browser/ui/webui/bluetooth_internals", "//chrome/browser/ui/webui/interventions_internals:mojo_bindings", "//chrome/browser/ui/webui/omnibox:mojo_bindings", @@ -949,7 +955,6 @@ split_static_library("ui") { "//components/browsing_data/content", "//components/browsing_data/core", "//components/bubble:bubble", - "//components/certificate_reporting:cert_logger_proto", "//components/consent_auditor/", "//components/content_settings/core/browser", "//components/crx_file", @@ -993,12 +998,12 @@ split_static_library("ui") { "//components/pref_registry", "//components/previews/content", "//components/previews/core", - "//components/proximity_auth", "//components/proxy_config", "//components/query_parser", "//components/rappor", "//components/renderer_context_menu", "//components/resources", + "//components/safe_browsing:features", "//components/safe_browsing/common:safe_browsing_prefs", "//components/safe_browsing/db:database_manager", "//components/safe_browsing/db:util", @@ -1006,13 +1011,14 @@ split_static_library("ui") { "//components/safe_browsing/web_ui", "//components/search", "//components/search_engines", + "//components/security_interstitials/content:security_interstitial_page", "//components/security_interstitials/core", "//components/security_state/content", "//components/security_state/core", "//components/sessions", "//components/signin/core/account_id", "//components/signin/core/browser", - "//components/signin/core/browser:signin_features", + "//components/signin/core/browser:signin_buildflags", "//components/spellcheck/browser", "//components/ssl_errors", "//components/startup_metric_utils/browser:lib", @@ -1046,21 +1052,21 @@ split_static_library("ui") { "//crypto", "//device/base", "//device/usb", - "//extensions/features", + "//extensions/buildflags", "//media", "//net:net", - "//ppapi/features", - "//printing/features", - "//rlz/features", + "//ppapi/buildflags", + "//printing/buildflags", + "//rlz/buildflags", "//services/metrics/public/cpp:ukm_builders", "//services/service_manager/runner/common", "//skia", "//storage/browser", "//storage/common", - "//third_party/WebKit/public:features", - "//third_party/WebKit/public:resources", - "//third_party/WebKit/public/common", "//third_party/adobe/flash:flapper_version_h", + "//third_party/blink/public:buildflags", + "//third_party/blink/public:resources", + "//third_party/blink/public/common", "//third_party/brotli:dec", "//third_party/cacheinvalidation", "//third_party/icu", @@ -1088,6 +1094,7 @@ split_static_library("ui") { "//ui/strings", "//ui/surface", "//ui/web_dialogs", + "//ui/webui", "//v8:v8_version", ] allow_circular_includes_from += @@ -1194,6 +1201,7 @@ split_static_library("ui") { "android/omnibox/omnibox_url_emphasizer.h", "android/omnibox/omnibox_view_util.cc", "android/omnibox/omnibox_view_util.h", + "android/overlay/overlay_window_android.cc", "android/page_info/certificate_chain_helper.cc", "android/page_info/certificate_viewer_android.cc", "android/page_info/connection_info_popup_android.cc", @@ -1249,7 +1257,7 @@ split_static_library("ui") { "//device/usb/mojo", "//device/usb/public/cpp", "//device/usb/public/mojom", - "//device/vr/features", + "//device/vr/buildflags", "//ui/android", ] } else { @@ -1356,6 +1364,8 @@ split_static_library("ui") { "exclusive_access/fullscreen_controller.h", "exclusive_access/fullscreen_within_tab_helper.cc", "exclusive_access/fullscreen_within_tab_helper.h", + "exclusive_access/keyboard_lock_controller.cc", + "exclusive_access/keyboard_lock_controller.h", "exclusive_access/mouse_lock_controller.cc", "exclusive_access/mouse_lock_controller.h", "fast_unload_controller.cc", @@ -1371,19 +1381,29 @@ split_static_library("ui") { "global_error/global_error_service_factory.h", "hung_renderer/hung_renderer_core.cc", "hung_renderer/hung_renderer_core.h", - "infobar_container_delegate.cc", - "infobar_container_delegate.h", "javascript_dialogs/javascript_dialog_views.cc", "javascript_dialogs/javascript_dialog_views.h", "layout_constants.cc", "layout_constants.h", "location_bar/location_bar.cc", "location_bar/location_bar.h", + "media_router/cast_modes_with_media_sources.cc", + "media_router/cast_modes_with_media_sources.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_sink_with_cast_modes.cc", + "media_router/media_sink_with_cast_modes.h", "media_router/presentation_receiver_window.h", "media_router/presentation_receiver_window_controller.cc", "media_router/presentation_receiver_window_controller.h", "media_router/presentation_receiver_window_delegate.h", "media_router/presentation_receiver_window_factory_mac.cc", + "media_router/query_result_manager.cc", + "media_router/query_result_manager.h", "native_window_tracker.h", "omnibox/alternate_nav_infobar_delegate.cc", "omnibox/alternate_nav_infobar_delegate.h", @@ -1397,9 +1417,8 @@ split_static_library("ui") { "omnibox/clipboard_utils.h", "omnibox/favicon_cache.cc", "omnibox/favicon_cache.h", - "overlay/overlay_surface_embedder.cc", - "overlay/overlay_surface_embedder.h", - "overlay/overlay_window.h", + "omnibox/omnibox_theme.cc", + "omnibox/omnibox_theme.h", "page_info/page_info_dialog.cc", "page_info/page_info_dialog.h", "page_info/page_info_infobar_delegate.cc", @@ -1448,8 +1467,6 @@ split_static_library("ui") { "singleton_tabs.h", "startup/automation_infobar_delegate.cc", "startup/automation_infobar_delegate.h", - "startup/bad_flags_prompt.cc", - "startup/bad_flags_prompt.h", "startup/google_api_keys_infobar_delegate.cc", "startup/google_api_keys_infobar_delegate.h", "startup/obsolete_system_infobar_delegate.cc", @@ -1581,14 +1598,12 @@ split_static_library("ui") { "webui/md_downloads/md_downloads_ui.h", "webui/md_history_ui.cc", "webui/md_history_ui.h", - "webui/media_router/cast_modes_with_media_sources.cc", - "webui/media_router/cast_modes_with_media_sources.h", - "webui/media_router/media_cast_mode.cc", - "webui/media_router/media_cast_mode.h", - "webui/media_router/media_router_dialog_controller_impl.cc", - "webui/media_router/media_router_dialog_controller_impl.h", - "webui/media_router/media_router_file_dialog.cc", - "webui/media_router/media_router_file_dialog.h", + "webui/media_router/media_router_dialog_controller_webui_impl.cc", + "webui/media_router/media_router_dialog_controller_webui_impl.h", + "webui/media_router/media_router_internals_ui.cc", + "webui/media_router/media_router_internals_ui.h", + "webui/media_router/media_router_internals_webui_message_handler.cc", + "webui/media_router/media_router_internals_webui_message_handler.h", "webui/media_router/media_router_localized_strings_provider.cc", "webui/media_router/media_router_localized_strings_provider.h", "webui/media_router/media_router_resources_provider.cc", @@ -1601,10 +1616,6 @@ split_static_library("ui") { "webui/media_router/media_router_ui_service_factory.h", "webui/media_router/media_router_webui_message_handler.cc", "webui/media_router/media_router_webui_message_handler.h", - "webui/media_router/media_sink_with_cast_modes.cc", - "webui/media_router/media_sink_with_cast_modes.h", - "webui/media_router/query_result_manager.cc", - "webui/media_router/query_result_manager.h", "webui/media_router/web_contents_display_observer.h", "webui/ntp/app_icon_webui_handler.cc", "webui/ntp/app_icon_webui_handler.h", @@ -1676,8 +1687,6 @@ split_static_library("ui") { "webui/settings/settings_cookies_view_handler.h", "webui/settings/settings_import_data_handler.cc", "webui/settings/settings_import_data_handler.h", - "webui/settings/settings_manage_profile_handler.cc", - "webui/settings/settings_manage_profile_handler.h", "webui/settings/settings_media_devices_selection_handler.cc", "webui/settings/settings_media_devices_selection_handler.h", "webui/settings/settings_page_ui_handler.cc", @@ -1730,7 +1739,6 @@ split_static_library("ui") { "//components/feedback/proto", "//components/keep_alive_registry", "//components/network_session_configurator/common", - "//components/proximity_auth/webui", "//components/ui_metrics", "//components/vector_icons", "//components/vector_icons", @@ -1751,6 +1759,15 @@ split_static_library("ui") { assert(enable_extensions) assert(toolkit_views) sources += [ + "app_list/app_list_controller_impl.cc", + "app_list/app_list_controller_impl.h", + "app_list/app_sync_ui_state.cc", + "app_list/app_sync_ui_state.h", + "app_list/app_sync_ui_state_factory.cc", + "app_list/app_sync_ui_state_factory.h", + "app_list/app_sync_ui_state_observer.h", + "app_list/app_sync_ui_state_watcher.cc", + "app_list/app_sync_ui_state_watcher.h", "app_list/search/launcher_search/launcher_search_icon_image_loader.cc", "app_list/search/launcher_search/launcher_search_icon_image_loader.h", "app_list/search/launcher_search/launcher_search_icon_image_loader_impl.cc", @@ -1761,21 +1778,6 @@ split_static_library("ui") { "app_list/search/launcher_search/launcher_search_result.h", "ash/accessibility/accessibility_controller_client.cc", "ash/accessibility/accessibility_controller_client.h", - "ash/app_list/app_list_controller_ash.cc", - "ash/app_list/app_list_controller_ash.h", - "ash/app_list/app_list_presenter_delegate_mus.cc", - "ash/app_list/app_list_presenter_delegate_mus.h", - "ash/app_list/app_list_presenter_service.cc", - "ash/app_list/app_list_presenter_service.h", - "ash/app_list/app_list_service_ash.cc", - "ash/app_list/app_list_service_ash.h", - "ash/app_list/app_sync_ui_state_watcher.cc", - "ash/app_list/app_sync_ui_state_watcher.h", - "ash/app_sync_ui_state.cc", - "ash/app_sync_ui_state.h", - "ash/app_sync_ui_state_factory.cc", - "ash/app_sync_ui_state_factory.h", - "ash/app_sync_ui_state_observer.h", "ash/ash_shell_init.cc", "ash/ash_shell_init.h", "ash/ash_util.cc", @@ -1874,7 +1876,6 @@ split_static_library("ui") { "ash/session_controller_client.h", "ash/session_util.cc", "ash/session_util.h", - "ash/sort_windows_by_z_index.cc", "ash/system_tray_client.cc", "ash/system_tray_client.h", "ash/tab_scrubber.cc", @@ -1898,7 +1899,6 @@ split_static_library("ui") { "settings_window_manager_chromeos.cc", "settings_window_manager_chromeos.h", "settings_window_manager_observer_chromeos.h", - "sort_windows_by_z_index.h", "views/apps/app_info_dialog/arc_app_info_links_panel.cc", "views/apps/app_info_dialog/arc_app_info_links_panel.h", "views/apps/chrome_native_app_window_views_aura_ash.cc", @@ -1935,6 +1935,11 @@ split_static_library("ui") { "views/select_file_dialog_extension_factory.h", "views/tabs/window_finder_ash.cc", "views/touch_uma/touch_uma_ash.cc", + "webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h", + "webui/chromeos/assistant_optin/assistant_optin_ui.cc", + "webui/chromeos/assistant_optin/assistant_optin_ui.h", + "webui/chromeos/assistant_optin/value_prop_screen_handler.cc", + "webui/chromeos/assistant_optin/value_prop_screen_handler.h", "webui/chromeos/bluetooth_dialog_localized_strings_provider.cc", "webui/chromeos/bluetooth_dialog_localized_strings_provider.h", "webui/chromeos/bluetooth_pairing_dialog.cc", @@ -1979,6 +1984,8 @@ split_static_library("ui") { "webui/chromeos/login/controller_pairing_screen_handler.h", "webui/chromeos/login/core_oobe_handler.cc", "webui/chromeos/login/core_oobe_handler.h", + "webui/chromeos/login/demo_setup_screen_handler.cc", + "webui/chromeos/login/demo_setup_screen_handler.h", "webui/chromeos/login/device_disabled_screen_handler.cc", "webui/chromeos/login/device_disabled_screen_handler.h", "webui/chromeos/login/enable_debugging_screen_handler.cc", @@ -2050,6 +2057,8 @@ split_static_library("ui") { "webui/chromeos/mobile_setup_dialog.h", "webui/chromeos/mobile_setup_ui.cc", "webui/chromeos/mobile_setup_ui.h", + "webui/chromeos/multidevice_setup/multidevice_setup_dialog.cc", + "webui/chromeos/multidevice_setup/multidevice_setup_dialog.h", "webui/chromeos/network_element_localized_strings_provider.cc", "webui/chromeos/network_element_localized_strings_provider.h", "webui/chromeos/network_ui.cc", @@ -2104,6 +2113,10 @@ split_static_library("ui") { "webui/settings/chromeos/google_assistant_handler.h", "webui/settings/chromeos/internet_handler.cc", "webui/settings/chromeos/internet_handler.h", + "webui/settings/chromeos/smb_handler.cc", + "webui/settings/chromeos/smb_handler.h", + "webui/settings/tts_handler.cc", + "webui/settings/tts_handler.h", "webui/version_handler_chromeos.cc", "webui/version_handler_chromeos.h", "window_sizer/window_sizer_ash.cc", @@ -2111,13 +2124,16 @@ split_static_library("ui") { deps += [ "//ash", "//ash:ash_with_content", + "//ash/app_list/presenter", "//ash/components/shortcut_viewer:ksv", "//ash/public/cpp", "//ash/public/cpp/vector_icons", - "//ash/resources/vector_icons", "//ash/strings", "//chrome/browser/chromeos", "//chromeos:cryptohome_proto", + "//chromeos/components/proximity_auth", + "//chromeos/components/proximity_auth/logging", + "//chromeos/components/proximity_auth/webui", "//chromeos/components/tether", "//components/arc", "//components/consent_auditor:consent_auditor", @@ -2125,7 +2141,6 @@ split_static_library("ui") { "//components/drive:drive_chromeos", "//components/exo", "//components/login", - "//components/proximity_auth/logging", "//components/session_manager/core", "//components/user_manager", "//services/data_decoder/public/cpp", @@ -2133,11 +2148,10 @@ split_static_library("ui") { "//services/device/public/mojom", "//services/ui/public/cpp", "//services/ui/public/interfaces", - "//ui/app_list/presenter", - "//ui/app_list/presenter:mojom", "//ui/base/ime", "//ui/chromeos", "//ui/chromeos/events", + "//ui/compositor_extra", "//ui/keyboard:mojom", ] allow_circular_includes_from += [ "//chrome/browser/chromeos" ] @@ -2165,6 +2179,7 @@ split_static_library("ui") { "webui/discards/discards_ui.cc", "webui/discards/discards_ui.h", ] + deps += [ "//ui/webui" ] } if (is_win || is_mac || is_desktop_linux) { @@ -2207,6 +2222,8 @@ split_static_library("ui") { "webui/profile_helper.h", "webui/settings/settings_default_browser_handler.cc", "webui/settings/settings_default_browser_handler.h", + "webui/settings/settings_manage_profile_handler.cc", + "webui/settings/settings_manage_profile_handler.h", "webui/settings/system_handler.cc", "webui/settings/system_handler.h", "webui/signin/inline_login_handler.cc", @@ -2468,6 +2485,17 @@ split_static_library("ui") { "views/tab_contents/chrome_web_contents_view_delegate_views_mac.mm", "views/tabs/window_finder_mac.mm", ] + + # MacViews browser windows are loudly marked in Chromium builds so that + # developers notice when they're being used. See comment in + # macviews_under_construction_window_mac.h for details. + if (!is_chrome_branded) { + sources += [ + "views/frame/macviews_under_construction_window_mac.h", + "views/frame/macviews_under_construction_window_mac.mm", + ] + } + deps += [ "//extensions/components/native_app_window" ] # Truly cocoa-browser-specific sources. These are secondary UI pieces that @@ -2476,19 +2504,41 @@ split_static_library("ui") { sources -= [ "cocoa/bookmarks/bookmark_all_tabs_controller.h", "cocoa/bookmarks/bookmark_all_tabs_controller.mm", + "cocoa/bookmarks/bookmark_bubble_controller.h", + "cocoa/bookmarks/bookmark_bubble_controller.mm", "cocoa/bookmarks/bookmark_editor_base_controller.h", "cocoa/bookmarks/bookmark_editor_base_controller.mm", "cocoa/bookmarks/bookmark_editor_controller.h", "cocoa/bookmarks/bookmark_editor_controller.mm", "cocoa/constrained_web_dialog_delegate_mac.mm", + "cocoa/content_settings/blocked_plugin_bubble_controller.h", + "cocoa/content_settings/blocked_plugin_bubble_controller.mm", + "cocoa/content_settings/collected_cookies_mac.h", + "cocoa/content_settings/collected_cookies_mac.mm", + "cocoa/content_settings/content_setting_bubble_cocoa.h", + "cocoa/content_settings/content_setting_bubble_cocoa.mm", + "cocoa/content_settings/cookie_details.h", + "cocoa/content_settings/cookie_details.mm", + "cocoa/content_settings/cookie_details_view_controller.h", + "cocoa/content_settings/cookie_details_view_controller.mm", + "cocoa/content_settings/cookie_tree_node.h", + "cocoa/content_settings/cookie_tree_node.mm", + "cocoa/content_settings/cookies_tree_controller_bridge.h", + "cocoa/content_settings/cookies_tree_controller_bridge.mm", "cocoa/download/download_danger_prompt_impl.cc", "cocoa/extensions/chooser_dialog_cocoa.h", "cocoa/extensions/chooser_dialog_cocoa.mm", "cocoa/extensions/chooser_dialog_cocoa_controller.h", "cocoa/extensions/chooser_dialog_cocoa_controller.mm", + "cocoa/extensions/extension_install_dialog_controller.h", + "cocoa/extensions/extension_install_dialog_controller.mm", + "cocoa/extensions/extension_install_view_controller.h", + "cocoa/extensions/extension_install_view_controller.mm", "cocoa/extensions/extension_installed_bubble_controller.h", "cocoa/extensions/extension_installed_bubble_controller.mm", "cocoa/extensions/extension_uninstall_dialog_cocoa.mm", + "cocoa/extensions/windowed_install_dialog_controller.h", + "cocoa/extensions/windowed_install_dialog_controller.mm", "cocoa/external_protocol_dialog_views_mac.mm", "cocoa/global_error_bubble_controller.h", "cocoa/global_error_bubble_controller.mm", @@ -2502,13 +2552,11 @@ split_static_library("ui") { "cocoa/password_reuse_warning_view_controller.h", "cocoa/password_reuse_warning_view_controller.mm", "cocoa/passwords/password_prompt_views_mac.mm", - "cocoa/permission_bubble/chooser_bubble_ui_views_mac.mm", - "cocoa/session_crashed_bubble.mm", "cocoa/simple_message_box_bridge_views.mm", "cocoa/simple_message_box_cocoa.h", "cocoa/simple_message_box_cocoa.mm", - "cocoa/tab_dialogs_cocoa.h", - "cocoa/tab_dialogs_cocoa.mm", + "cocoa/subresource_filter/subresource_filter_bubble_controller.h", + "cocoa/subresource_filter/subresource_filter_bubble_controller.mm", "javascript_dialogs/javascript_dialog_cocoa.h", "javascript_dialogs/javascript_dialog_cocoa.mm", "javascript_dialogs/javascript_dialog_mac.cc", @@ -2748,6 +2796,12 @@ split_static_library("ui") { "views/apps/app_info_dialog/app_info_summary_panel.h", "views/apps/chrome_native_app_window_views.cc", "views/apps/chrome_native_app_window_views.h", + "views/autofill/autofill_popup_base_view.cc", + "views/autofill/autofill_popup_base_view.h", + "views/autofill/autofill_popup_view_native_views.cc", + "views/autofill/autofill_popup_view_native_views.h", + "views/autofill/autofill_popup_view_views.cc", + "views/autofill/autofill_popup_view_views.h", "views/autofill/card_unmask_prompt_views.cc", "views/autofill/card_unmask_prompt_views.h", "views/autofill/save_card_bubble_views.cc", @@ -2763,6 +2817,8 @@ split_static_library("ui") { "views/chrome_browser_main_extra_parts_views.h", "views/chrome_constrained_window_views_client.cc", "views/chrome_constrained_window_views_client.h", + "views/chrome_platform_style.cc", + "views/chrome_platform_style.h", "views/chrome_views_delegate.cc", "views/chrome_views_delegate.h", "views/collected_cookies_views.cc", @@ -2818,6 +2874,8 @@ split_static_library("ui") { "views/harmony/harmony_layout_provider.h", "views/harmony/harmony_typography_provider.cc", "views/harmony/harmony_typography_provider.h", + "views/harmony/material_refresh_layout_provider.cc", + "views/harmony/material_refresh_layout_provider.h", "views/harmony/textfield_layout.cc", "views/harmony/textfield_layout.h", "views/hover_button.cc", @@ -2849,8 +2907,6 @@ split_static_library("ui") { "views/passwords/auto_signin_first_run_dialog_view.h", "views/passwords/credentials_item_view.cc", "views/passwords/credentials_item_view.h", - "views/passwords/credentials_selection_view.cc", - "views/passwords/credentials_selection_view.h", "views/passwords/password_auto_sign_in_view.cc", "views/passwords/password_auto_sign_in_view.h", "views/passwords/password_bubble_view_base.cc", @@ -2863,8 +2919,6 @@ split_static_library("ui") { "views/passwords/password_save_confirmation_view.h", "views/passwords/password_sign_in_promo_view.cc", "views/passwords/password_sign_in_promo_view.h", - "views/passwords/password_update_pending_view.cc", - "views/passwords/password_update_pending_view.h", "views/payments/contact_info_editor_view_controller.cc", "views/payments/contact_info_editor_view_controller.h", "views/payments/credit_card_editor_view_controller.cc", @@ -2914,6 +2968,8 @@ split_static_library("ui") { "views/permission_bubble/permission_prompt_impl.h", "views/safe_browsing/password_reuse_modal_warning_dialog.cc", "views/safe_browsing/password_reuse_modal_warning_dialog.h", + "views/session_crashed_bubble_view.cc", + "views/session_crashed_bubble_view.h", "views/simple_message_box_views.cc", "views/simple_message_box_views.h", "views/subtle_notification_view.cc", @@ -2987,12 +3043,6 @@ split_static_library("ui") { "javascript_dialogs/javascript_dialog.cc", "views/accessibility/invert_bubble_view.cc", "views/accessibility/invert_bubble_view.h", - "views/autofill/autofill_popup_base_view.cc", - "views/autofill/autofill_popup_base_view.h", - "views/autofill/autofill_popup_view_native_views.cc", - "views/autofill/autofill_popup_view_native_views.h", - "views/autofill/autofill_popup_view_views.cc", - "views/autofill/autofill_popup_view_views.h", "views/autofill/password_generation_popup_view_views.cc", "views/autofill/password_generation_popup_view_views.h", "views/autofill/save_card_icon_view.cc", @@ -3043,6 +3093,8 @@ split_static_library("ui") { "views/find_bar_host.h", "views/find_bar_view.cc", "views/find_bar_view.h", + "views/frame/app_menu_button.cc", + "views/frame/app_menu_button.h", "views/frame/avatar_button_manager.cc", "views/frame/avatar_button_manager.h", "views/frame/browser_frame.cc", @@ -3053,7 +3105,8 @@ split_static_library("ui") { "views/frame/browser_root_view.h", "views/frame/browser_view.cc", "views/frame/browser_view.h", - "views/frame/browser_view_button_provider.h", + "views/frame/browser_view_commands_mac.h", + "views/frame/browser_view_commands_mac.mm", "views/frame/browser_view_layout.cc", "views/frame/browser_view_layout.h", "views/frame/browser_view_layout_delegate.h", @@ -3064,6 +3117,8 @@ split_static_library("ui") { "views/frame/contents_web_view.h", "views/frame/hosted_app_button_container.cc", "views/frame/hosted_app_button_container.h", + "views/frame/hosted_app_menu_button.cc", + "views/frame/hosted_app_menu_button.h", "views/frame/immersive_mode_controller.cc", "views/frame/immersive_mode_controller.h", "views/frame/immersive_mode_controller_factory_views.cc", @@ -3076,6 +3131,7 @@ split_static_library("ui") { "views/frame/system_menu_model_builder.h", "views/frame/system_menu_model_delegate.cc", "views/frame/system_menu_model_delegate.h", + "views/frame/toolbar_button_provider.h", "views/frame/top_container_view.cc", "views/frame/top_container_view.h", "views/frame/web_contents_close_handler.cc", @@ -3089,8 +3145,6 @@ split_static_library("ui") { "views/infobars/alternate_nav_infobar_view.h", "views/infobars/confirm_infobar.cc", "views/infobars/confirm_infobar.h", - "views/infobars/infobar_background.cc", - "views/infobars/infobar_background.h", "views/infobars/infobar_container_view.cc", "views/infobars/infobar_container_view.h", "views/infobars/infobar_view.cc", @@ -3121,6 +3175,8 @@ split_static_library("ui") { "views/location_bar/star_view.h", "views/location_bar/zoom_view.cc", "views/location_bar/zoom_view.h", + "views/media_router/media_router_dialog_controller_views.cc", + "views/media_router/media_router_dialog_controller_views.h", "views/media_router/presentation_receiver_window_factory.cc", "views/media_router/presentation_receiver_window_frame.cc", "views/media_router/presentation_receiver_window_frame.h", @@ -3134,6 +3190,8 @@ split_static_library("ui") { "views/omnibox/omnibox_result_view.h", "views/omnibox/omnibox_tab_switch_button.cc", "views/omnibox/omnibox_tab_switch_button.h", + "views/omnibox/omnibox_text_view.cc", + "views/omnibox/omnibox_text_view.h", "views/omnibox/omnibox_view_views.cc", "views/omnibox/omnibox_view_views.h", "views/omnibox/rounded_omnibox_results_frame.cc", @@ -3149,8 +3207,6 @@ split_static_library("ui") { "views/proximity_auth/proximity_auth_error_bubble_view.h", "views/sad_tab_view.cc", "views/sad_tab_view.h", - "views/session_crashed_bubble_view.cc", - "views/session_crashed_bubble_view.h", "views/ssl_client_certificate_selector.cc", "views/ssl_client_certificate_selector.h", "views/status_bubble_views.cc", @@ -3191,11 +3247,11 @@ split_static_library("ui") { "views/theme_copying_widget.h", "views/toolbar/app_menu.cc", "views/toolbar/app_menu.h", - "views/toolbar/app_menu_button.cc", - "views/toolbar/app_menu_button.h", "views/toolbar/app_menu_observer.h", "views/toolbar/browser_actions_container.cc", "views/toolbar/browser_actions_container.h", + "views/toolbar/browser_app_menu_button.cc", + "views/toolbar/browser_app_menu_button.h", "views/toolbar/extension_toolbar_menu_view.cc", "views/toolbar/extension_toolbar_menu_view.h", "views/toolbar/home_button.cc", @@ -3209,6 +3265,7 @@ split_static_library("ui") { "views/toolbar/toolbar_action_view_delegate_views.h", "views/toolbar/toolbar_button.cc", "views/toolbar/toolbar_button.h", + "views/toolbar/toolbar_ink_drop_util.h", "views/toolbar/toolbar_view.cc", "views/toolbar/toolbar_view.h", "views/touch_uma/touch_uma.h", @@ -3251,7 +3308,6 @@ split_static_library("ui") { "views/profiles/forced_reauthentication_dialog_view.h", "views/profiles/signin_view_controller_delegate_views.cc", "views/profiles/signin_view_controller_delegate_views.h", - "views/screen_capture_notification_ui_views.cc", "views/sync/one_click_signin_dialog_view.cc", "views/sync/one_click_signin_dialog_view.h", "views/touch_uma/touch_uma.cc", @@ -3289,6 +3345,10 @@ split_static_library("ui") { ] } + if (is_mac) { + sources += [ "views/chrome_platform_style_mac.mm" ] + } + if (is_win) { sources += [ "views/chrome_views_delegate_win.cc" ] } @@ -3324,6 +3384,7 @@ split_static_library("ui") { "views/relaunch_notification/relaunch_recommended_bubble_view.h", "views/relaunch_notification/relaunch_required_dialog_view.cc", "views/relaunch_notification/relaunch_required_dialog_view.h", + "views/screen_capture_notification_ui_views.cc", ] if (is_mac) { sources += [ @@ -3394,7 +3455,6 @@ split_static_library("ui") { deps += [ "//ui/aura", "//ui/keyboard", - "//ui/keyboard:keyboard_with_content", "//ui/keyboard:resources", "//ui/wm", ] @@ -3423,7 +3483,6 @@ split_static_library("ui") { "app_list/app_list_model_builder.h", "app_list/app_list_model_updater.h", "app_list/app_list_model_updater_delegate.h", - "app_list/app_list_service.cc", "app_list/app_list_service.h", "app_list/app_list_service_impl.cc", "app_list/app_list_service_impl.h", @@ -3445,9 +3504,6 @@ split_static_library("ui") { "app_list/extension_app_model_builder.h", "app_list/extension_uninstaller.cc", "app_list/extension_uninstaller.h", - "app_list/profile_loader.cc", - "app_list/profile_loader.h", - "app_list/profile_store.h", "app_list/search/answer_card/answer_card_contents.cc", "app_list/search/answer_card/answer_card_contents.h", "app_list/search/answer_card/answer_card_result.cc", @@ -3460,10 +3516,18 @@ split_static_library("ui") { "app_list/search/app_result.h", "app_list/search/app_search_provider.cc", "app_list/search/app_search_provider.h", + "app_list/search/arc/arc_app_data_search_provider.cc", + "app_list/search/arc/arc_app_data_search_provider.h", + "app_list/search/arc/arc_app_data_search_result.cc", + "app_list/search/arc/arc_app_data_search_result.h", "app_list/search/arc/arc_playstore_search_provider.cc", "app_list/search/arc/arc_playstore_search_provider.h", "app_list/search/arc/arc_playstore_search_result.cc", "app_list/search/arc/arc_playstore_search_result.h", + "app_list/search/arc/icon_decode_request.cc", + "app_list/search/arc/icon_decode_request.h", + "app_list/search/chrome_search_result.cc", + "app_list/search/chrome_search_result.h", "app_list/search/common/json_response_fetcher.cc", "app_list/search/common/json_response_fetcher.h", "app_list/search/common/url_icon_source.cc", @@ -3474,10 +3538,20 @@ split_static_library("ui") { "app_list/search/common/webservice_cache_factory.h", "app_list/search/common/webservice_search_provider.cc", "app_list/search/common/webservice_search_provider.h", + "app_list/search/dictionary_data_store.cc", + "app_list/search/dictionary_data_store.h", "app_list/search/extension_app_result.cc", "app_list/search/extension_app_result.h", + "app_list/search/history.cc", + "app_list/search/history.h", + "app_list/search/history_data.cc", + "app_list/search/history_data.h", + "app_list/search/history_data_observer.h", + "app_list/search/history_data_store.cc", + "app_list/search/history_data_store.h", "app_list/search/history_factory.cc", "app_list/search/history_factory.h", + "app_list/search/history_types.h", "app_list/search/mixer.cc", "app_list/search/mixer.h", "app_list/search/omnibox_provider.cc", @@ -3488,6 +3562,8 @@ split_static_library("ui") { "app_list/search/search_controller.h", "app_list/search/search_controller_factory.cc", "app_list/search/search_controller_factory.h", + "app_list/search/search_provider.cc", + "app_list/search/search_provider.h", "app_list/search/search_resource_manager.cc", "app_list/search/search_resource_manager.h", "app_list/search/search_util.cc", @@ -3504,6 +3580,7 @@ split_static_library("ui") { deps += [ "//ui/app_list", "//ui/app_list/vector_icons", + "//ui/views/mus/remote_view:remote_view_provider", ] if (is_chromeos) { @@ -3548,6 +3625,8 @@ split_static_library("ui") { "app_list/arc/arc_vpn_provider_manager.h", "app_list/arc/arc_vpn_provider_manager_factory.cc", "app_list/arc/arc_vpn_provider_manager_factory.h", + "app_list/crostini/crostini_app_context_menu.cc", + "app_list/crostini/crostini_app_context_menu.h", "app_list/crostini/crostini_app_item.cc", "app_list/crostini/crostini_app_item.h", "app_list/crostini/crostini_app_model_builder.cc", @@ -3556,8 +3635,12 @@ split_static_library("ui") { "app_list/crostini/crostini_installer_view.h", "app_list/crostini/crostini_util.cc", "app_list/crostini/crostini_util.h", + "app_list/internal_app/internal_app_metadata.cc", + "app_list/internal_app/internal_app_metadata.h", "app_list/search/arc_app_result.cc", "app_list/search/arc_app_result.h", + "app_list/search/internal_app_result.cc", + "app_list/search/internal_app_result.h", "ash/launcher/arc_app_deferred_launcher_controller.cc", "ash/launcher/arc_app_deferred_launcher_controller.h", "ash/launcher/arc_app_deferred_launcher_item_controller.cc", @@ -3572,19 +3655,20 @@ split_static_library("ui") { "ash/launcher/arc_app_window_launcher_item_controller.h", "ash/launcher/arc_launcher_context_menu.cc", "ash/launcher/arc_launcher_context_menu.h", + "ash/launcher/crostini_app_window.cc", + "ash/launcher/crostini_app_window.h", + "ash/launcher/crostini_app_window_shelf_controller.cc", + "ash/launcher/crostini_app_window_shelf_controller.h", + "ash/launcher/crostini_app_window_shelf_item_controller.cc", + "ash/launcher/crostini_app_window_shelf_item_controller.h", + "ash/launcher/crostini_shelf_context_menu.cc", + "ash/launcher/crostini_shelf_context_menu.h", "ash/launcher/launcher_arc_app_updater.cc", "ash/launcher/launcher_arc_app_updater.h", "views/arc_app_dialog_view.cc", ] deps += [ "//mash/common" ] } - } else { - sources += [ - "app_list/app_list_service.h", - "app_list/app_list_service_disabled.cc", - "app_list/app_list_service_disabled_mac.h", - "app_list/app_list_service_disabled_mac.mm", - ] } if (enable_extensions) { @@ -3721,8 +3805,8 @@ split_static_library("ui") { "webui/print_preview/print_preview_handler.h", "webui/print_preview/print_preview_ui.cc", "webui/print_preview/print_preview_ui.h", - "webui/print_preview/printer_capabilities.cc", - "webui/print_preview/printer_capabilities.h", + "webui/print_preview/print_preview_utils.cc", + "webui/print_preview/print_preview_utils.h", "webui/print_preview/printer_handler.cc", "webui/print_preview/printer_handler.h", "webui/print_preview/sticky_settings.cc", @@ -3863,19 +3947,25 @@ static_library("test_support") { "extensions/browser_action_test_util.h", "views/payments/test_chrome_payment_request_delegate.cc", "views/payments/test_chrome_payment_request_delegate.h", + "views/toolbar/browser_action_test_util_views_mac.mm", ] + if (is_mac) { + sources += [ + "cocoa/extensions/browser_action_test_util_views_cocoa.mm", + "cocoa/find_bar/find_bar_host_unittest_util_cocoa.mm", + ] + } if (!is_mac || mac_views_browser) { sources += [ "views/find_bar_host_unittest_util_views.cc", "views/toolbar/browser_action_test_util_views.cc", ] - if (!is_mac) { - deps += [ "//ui/aura" ] - } - } else { - sources += [ - "cocoa/extensions/browser_action_test_util_views_mac.mm", - "cocoa/find_bar/find_bar_host_unittest_util_cocoa.mm", + } + if (use_aura) { + sources += [ "views/toolbar/browser_action_test_util_views_aura.cc" ] + deps += [ + "//ui/aura", + "//ui/wm", ] } } @@ -3893,13 +3983,17 @@ static_library("test_support") { "passwords/password_dialog_controller_mock.h", "passwords/passwords_model_delegate_mock.cc", "passwords/passwords_model_delegate_mock.h", + "tabs/tab_ukm_test_helper.cc", + "tabs/tab_ukm_test_helper.h", "test/test_confirm_bubble_model.cc", "test/test_confirm_bubble_model.h", ] deps += [ "//chrome/test:test_support_ui", "//components/signin/core/browser", + "//components/ukm:test_support", "//components/zoom", + "//services/metrics/public/mojom", ] } diff --git a/chromium/chrome/browser/ui/libgtkui/BUILD.gn b/chromium/chrome/browser/ui/libgtkui/BUILD.gn index cc7663cbe6c..e9838d74e90 100644 --- a/chromium/chrome/browser/ui/libgtkui/BUILD.gn +++ b/chromium/chrome/browser/ui/libgtkui/BUILD.gn @@ -6,7 +6,7 @@ assert(is_linux, "This file should only be referenced on Linux") import("//build/config/features.gni") import("//build/config/linux/gtk/gtk.gni") -import("//printing/features/features.gni") +import("//printing/buildflags/buildflags.gni") # Automatically depends on the GTK version associated with the current build # flags. diff --git a/chromium/chrome/browser/ui/views/BUILD.gn b/chromium/chrome/browser/ui/views/BUILD.gn index db6b0359289..4831e458879 100644 --- a/chromium/chrome/browser/ui/views/BUILD.gn +++ b/chromium/chrome/browser/ui/views/BUILD.gn @@ -31,7 +31,7 @@ component("views") { "//components/keep_alive_registry", "//components/vector_icons", "//content/public/browser", - "//printing/features", + "//printing/buildflags", "//skia", "//ui/base", "//ui/events", diff --git a/chromium/chrome/browser/ui/webui/about_ui.cc b/chromium/chrome/browser/ui/webui/about_ui.cc index 808d6e76497..a54cb8f97e1 100644 --- a/chromium/chrome/browser/ui/webui/about_ui.cc +++ b/chromium/chrome/browser/ui/webui/about_ui.cc @@ -326,25 +326,6 @@ std::string ChromeURLs() { return html; } -std::string HelpCenterContent() { - std::string html; - AppendHeader(&html, 0, l10n_util::GetStringUTF8(IDS_CONNECTION_HELP_TITLE)); - html += - "<meta name=\"viewport\" content=\"initial-scale=1, minimum-scale=1, " - "width=device-width\">\n"; - webui::AppendWebUiCssTextDefaults(&html); - html += "<style>"; - html += l10n_util::GetStringUTF8(IDR_SECURITY_INTERSTITIAL_COMMON_CSS); - html += l10n_util::GetStringUTF8(IDR_SECURITY_INTERSTITIAL_CORE_CSS); - html += "</style>"; - AppendBody(&html); - html += "<div class=\"interstitial-wrapper\">\n"; - html += l10n_util::GetStringUTF8(IDS_CONNECTION_HELP_HTML); - html += "</div>\n"; - AppendFooter(&html); - return html; -} - // AboutDnsHandler bounces the request back to the IO thread to collect // the DNS information. class AboutDnsHandler : public base::RefCountedThreadSafe<AboutDnsHandler> { @@ -445,8 +426,6 @@ void AboutUIHTMLSource::StartDataRequest( // Add your data source here, in alphabetical order. if (source_name_ == chrome::kChromeUIChromeURLsHost) { response = ChromeURLs(); - } else if (source_name_ == chrome::kChromeUIConnectionHelpHost) { - response = HelpCenterContent(); } else if (source_name_ == chrome::kChromeUICreditsHost) { int idr = IDR_ABOUT_UI_CREDITS_HTML; if (path == kCreditsJsPath) diff --git a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc index b7ea9d79d7d..57d7d129909 100644 --- a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc @@ -11,7 +11,6 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/metrics/histogram_macros.h" -#include "base/metrics/user_metrics.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "build/build_config.h" @@ -36,6 +35,7 @@ #include "components/browser_sync/profile_sync_service.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_manager.h" +#include "components/signin/core/browser/signin_metrics.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -94,18 +94,22 @@ void AppLauncherLoginHandler::RegisterMessages() { base::Bind(&AppLauncherLoginHandler::UpdateLogin, base::Unretained(this)))); - web_ui()->RegisterMessageCallback("initializeSyncLogin", - base::Bind(&AppLauncherLoginHandler::HandleInitializeSyncLogin, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("showSyncLoginUI", - base::Bind(&AppLauncherLoginHandler::HandleShowSyncLoginUI, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("loginMessageSeen", - base::Bind(&AppLauncherLoginHandler::HandleLoginMessageSeen, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("showAdvancedLoginUI", - base::Bind(&AppLauncherLoginHandler::HandleShowAdvancedLoginUI, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "initializeSyncLogin", + base::BindRepeating(&AppLauncherLoginHandler::HandleInitializeSyncLogin, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "showSyncLoginUI", + base::BindRepeating(&AppLauncherLoginHandler::HandleShowSyncLoginUI, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "loginMessageSeen", + base::BindRepeating(&AppLauncherLoginHandler::HandleLoginMessageSeen, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "showAdvancedLoginUI", + base::BindRepeating(&AppLauncherLoginHandler::HandleShowAdvancedLoginUI, + base::Unretained(this))); } void AppLauncherLoginHandler::HandleInitializeSyncLogin( @@ -207,11 +211,11 @@ void AppLauncherLoginHandler::UpdateLogin() { sub_header = l10n_util::GetStringFUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_SUB_HEADER, signed_in_link); - base::RecordAction( + signin_metrics::RecordSigninImpressionUserActionForAccessPoint( web_ui()->GetWebContents()->GetURL().spec() == chrome::kChromeUIAppsURL - ? base::UserMetricsAction("Signin_Impression_FromAppsPageLink") - : base::UserMetricsAction("Signin_Impression_FromNTP")); + ? signin_metrics::AccessPoint::ACCESS_POINT_APPS_PAGE_LINK + : signin_metrics::AccessPoint::ACCESS_POINT_NTP_LINK); // Record that the user was shown the promo. RecordInHistogram(NTP_SIGN_IN_PROMO_VIEWED); } diff --git a/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn index f3e7c4bd926..15a534e3b70 100644 --- a/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn @@ -21,6 +21,7 @@ source_set("bluetooth_internals") { "//chrome/common", "//content/public/browser", "//device/bluetooth", + "//ui/webui", ] } diff --git a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h index 18fe64fdcc3..59cf500ef31 100644 --- a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h +++ b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h @@ -7,14 +7,12 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals.mojom.h" -#include "chrome/browser/ui/webui/mojo_web_ui_handler.h" #include "device/bluetooth/bluetooth_adapter.h" #include "mojo/public/cpp/bindings/binding.h" // Handles API requests from chrome://bluetooth-internals page by implementing // mojom::BluetoothInternalsHandler. -class BluetoothInternalsHandler : public mojom::BluetoothInternalsHandler, - public MojoWebUIHandler { +class BluetoothInternalsHandler : public mojom::BluetoothInternalsHandler { public: explicit BluetoothInternalsHandler( mojom::BluetoothInternalsHandlerRequest request); diff --git a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.cc b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.cc index 7e74cb2afda..63009911a06 100644 --- a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.cc @@ -11,7 +11,7 @@ #include "content/public/browser/web_ui_data_source.h" BluetoothInternalsUI::BluetoothInternalsUI(content::WebUI* web_ui) - : MojoWebUIController(web_ui) { + : ui::MojoWebUIController<mojom::BluetoothInternalsHandler>(web_ui) { // Set up the chrome://bluetooth-internals source. content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUIBluetoothInternalsHost); diff --git a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h index ed66bf4d218..e28b48d756b 100644 --- a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h +++ b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h @@ -7,19 +7,19 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals.mojom.h" -#include "chrome/browser/ui/webui/mojo_web_ui_controller.h" +#include "ui/webui/mojo_web_ui_controller.h" class BluetoothInternalsHandler; // The WebUI for chrome://bluetooth-internals class BluetoothInternalsUI - : public MojoWebUIController<mojom::BluetoothInternalsHandler> { + : public ui::MojoWebUIController<mojom::BluetoothInternalsHandler> { public: explicit BluetoothInternalsUI(content::WebUI* web_ui); ~BluetoothInternalsUI() override; private: - // MojoWebUIController overrides: + // ui::MojoWebUIController overrides: void BindUIHandler( // mojo::InterfaceRequest<mojom::BluetoothInternalsHandler> request) // override; diff --git a/chromium/chrome/browser/ui/webui/browsing_history_handler.cc b/chromium/chrome/browser/ui/webui/browsing_history_handler.cc index da08cc49277..4b542481235 100644 --- a/chromium/chrome/browser/ui/webui/browsing_history_handler.cc +++ b/chromium/chrome/browser/ui/webui/browsing_history_handler.cc @@ -243,29 +243,31 @@ void BrowsingHistoryHandler::RegisterMessages() { ProfileSyncServiceFactory::GetSyncServiceForBrowserContext(profile); browsing_history_service_ = std::make_unique<BrowsingHistoryService>( this, local_history, sync_service); - // Make sure BrowsingDataRemoverDelegate is initialized and listening - // for history deletions. - profile->GetBrowsingDataRemoverDelegate(); // Create our favicon data source. content::URLDataSource::Add(profile, new FaviconSource(profile)); - web_ui()->RegisterMessageCallback("queryHistory", - base::Bind(&BrowsingHistoryHandler::HandleQueryHistory, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "queryHistory", + base::BindRepeating(&BrowsingHistoryHandler::HandleQueryHistory, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "queryHistoryContinuation", - base::Bind(&BrowsingHistoryHandler::HandleQueryHistoryContinuation, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("removeVisits", - base::Bind(&BrowsingHistoryHandler::HandleRemoveVisits, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("clearBrowsingData", - base::Bind(&BrowsingHistoryHandler::HandleClearBrowsingData, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("removeBookmark", - base::Bind(&BrowsingHistoryHandler::HandleRemoveBookmark, - base::Unretained(this))); + base::BindRepeating( + &BrowsingHistoryHandler::HandleQueryHistoryContinuation, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "removeVisits", + base::BindRepeating(&BrowsingHistoryHandler::HandleRemoveVisits, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "clearBrowsingData", + base::BindRepeating(&BrowsingHistoryHandler::HandleClearBrowsingData, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "removeBookmark", + base::BindRepeating(&BrowsingHistoryHandler::HandleRemoveBookmark, + base::Unretained(this))); } void BrowsingHistoryHandler::HandleQueryHistory(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc b/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc index fb5013eaff2..90f6982423d 100644 --- a/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc @@ -10,7 +10,6 @@ #include <utility> #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/simple_test_clock.h" @@ -31,6 +30,7 @@ #include "components/sync/base/model_type.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" +#include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "net/http/http_status_code.h" @@ -153,6 +153,10 @@ class BrowsingHistoryHandlerTest : public ::testing::Test { return std::move(service); } + // TODO(lukasza): https://crbug.com/832100: Move the factory into + // TestingProfile, so individual tests don't need to worry about it. + content::ScopedMockRenderProcessHostFactory test_process_factory_; + content::TestBrowserThreadBundle thread_bundle_; std::unique_ptr<TestingProfile> profile_; TestSyncService* sync_service_; diff --git a/chromium/chrome/browser/ui/webui/certificate_viewer_webui.cc b/chromium/chrome/browser/ui/webui/certificate_viewer_webui.cc index 969c9bdfcc3..156ffb83470 100644 --- a/chromium/chrome/browser/ui/webui/certificate_viewer_webui.cc +++ b/chromium/chrome/browser/ui/webui/certificate_viewer_webui.cc @@ -345,12 +345,15 @@ CertificateViewerDialogHandler::~CertificateViewerDialogHandler() { } void CertificateViewerDialogHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("exportCertificate", - base::Bind(&CertificateViewerDialogHandler::ExportCertificate, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("requestCertificateFields", - base::Bind(&CertificateViewerDialogHandler::RequestCertificateFields, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "exportCertificate", + base::BindRepeating(&CertificateViewerDialogHandler::ExportCertificate, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "requestCertificateFields", + base::BindRepeating( + &CertificateViewerDialogHandler::RequestCertificateFields, + base::Unretained(this))); } void CertificateViewerDialogHandler::ExportCertificate( diff --git a/chromium/chrome/browser/ui/webui/certificates_handler.cc b/chromium/chrome/browser/ui/webui/certificates_handler.cc index 854bbb0ea62..53fafce0499 100644 --- a/chromium/chrome/browser/ui/webui/certificates_handler.cc +++ b/chromium/chrome/browser/ui/webui/certificates_handler.cc @@ -345,68 +345,72 @@ CertificatesHandler::~CertificatesHandler() {} void CertificatesHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "viewCertificate", base::Bind(&CertificatesHandler::HandleViewCertificate, - base::Unretained(this))); + "viewCertificate", + base::BindRepeating(&CertificatesHandler::HandleViewCertificate, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getCaCertificateTrust", - base::Bind(&CertificatesHandler::HandleGetCATrust, - base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleGetCATrust, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "editCaCertificateTrust", - base::Bind(&CertificatesHandler::HandleEditCATrust, - base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleEditCATrust, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "cancelImportExportCertificate", - base::Bind(&CertificatesHandler::HandleCancelImportExportProcess, - base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleCancelImportExportProcess, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "exportPersonalCertificate", - base::Bind(&CertificatesHandler::HandleExportPersonal, - base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleExportPersonal, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "exportPersonalCertificatePasswordSelected", - base::Bind(&CertificatesHandler::HandleExportPersonalPasswordSelected, - base::Unretained(this))); + base::BindRepeating( + &CertificatesHandler::HandleExportPersonalPasswordSelected, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "importPersonalCertificate", - base::Bind(&CertificatesHandler::HandleImportPersonal, - base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleImportPersonal, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "importPersonalCertificatePasswordSelected", - base::Bind(&CertificatesHandler::HandleImportPersonalPasswordSelected, - base::Unretained(this))); + base::BindRepeating( + &CertificatesHandler::HandleImportPersonalPasswordSelected, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "importCaCertificate", - base::Bind(&CertificatesHandler::HandleImportCA, base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleImportCA, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "importCaCertificateTrustSelected", - base::Bind(&CertificatesHandler::HandleImportCATrustSelected, - base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleImportCATrustSelected, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "importServerCertificate", - base::Bind(&CertificatesHandler::HandleImportServer, - base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleImportServer, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "exportCertificate", - base::Bind(&CertificatesHandler::HandleExportCertificate, - base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleExportCertificate, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "deleteCertificate", - base::Bind(&CertificatesHandler::HandleDeleteCertificate, - base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleDeleteCertificate, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "refreshCertificates", - base::Bind(&CertificatesHandler::HandleRefreshCertificates, - base::Unretained(this))); + base::BindRepeating(&CertificatesHandler::HandleRefreshCertificates, + base::Unretained(this))); } void CertificatesHandler::CertificatesRefreshed() { diff --git a/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index 8b87a09ec96..0dd6bc00d78 100644 --- a/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc @@ -80,16 +80,18 @@ #include "components/prefs/pref_service.h" #include "components/safe_browsing/web_ui/constants.h" #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/profile_management_switches.h" -#include "components/signin/core/browser/signin_features.h" +#include "components/signin/core/browser/signin_buildflags.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/content_client.h" #include "content/public/common/url_utils.h" -#include "extensions/features/features.h" -#include "media/media_features.h" -#include "ppapi/features/features.h" -#include "printing/features/features.h" +#include "extensions/buildflags/buildflags.h" +#include "media/media_buildflags.h" +#include "ppapi/buildflags/buildflags.h" +#include "printing/buildflags/buildflags.h" #include "ui/gfx/favicon_size.h" #include "ui/web_dialogs/web_dialog_ui.h" #include "url/gurl.h" @@ -108,6 +110,7 @@ #if !defined(OS_ANDROID) #include "chrome/browser/media/router/media_router_feature.h" +#include "chrome/browser/ui/webui/media_router/media_router_internals_ui.h" #include "chrome/browser/ui/webui/media_router/media_router_ui.h" #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS) @@ -119,8 +122,6 @@ #include "chrome/browser/ui/webui/snippets_internals_ui.h" #include "chrome/browser/ui/webui/webapks_ui.h" #else -#include "chrome/browser/signin/easy_unlock_service.h" -#include "chrome/browser/signin/easy_unlock_service_factory.h" #include "chrome/browser/ui/webui/devtools_ui.h" #include "chrome/browser/ui/webui/inspect_ui.h" #include "chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.h" @@ -133,6 +134,9 @@ #if defined(OS_CHROMEOS) #include "base/sys_info.h" +#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service.h" +#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_factory.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h" #include "chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.h" #include "chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.h" #include "chrome/browser/ui/webui/chromeos/cryptohome_ui.h" @@ -143,14 +147,15 @@ #include "chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/browser/ui/webui/chromeos/mobile_setup_ui.h" +#include "chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.h" #include "chrome/browser/ui/webui/chromeos/network_ui.h" #include "chrome/browser/ui/webui/chromeos/power_ui.h" #include "chrome/browser/ui/webui/chromeos/set_time_ui.h" #include "chrome/browser/ui/webui/chromeos/slow_trace_ui.h" #include "chrome/browser/ui/webui/chromeos/slow_ui.h" #include "chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_ui.h" -#include "components/proximity_auth/webui/proximity_auth_ui.h" -#include "components/proximity_auth/webui/url_constants.h" +#include "chromeos/components/proximity_auth/webui/proximity_auth_ui.h" +#include "chromeos/components/proximity_auth/webui/url_constants.h" #endif #if defined(OS_CHROMEOS) && !defined(OFFICIAL_BUILD) @@ -242,8 +247,9 @@ WebUIController* NewWebUI<proximity_auth::ProximityAuthUI>(WebUI* web_ui, content::BrowserContext* browser_context = web_ui->GetWebContents()->GetBrowserContext(); return new proximity_auth::ProximityAuthUI( - web_ui, EasyUnlockServiceFactory::GetForBrowserContext(browser_context) - ->proximity_auth_client()); + web_ui, + chromeos::EasyUnlockServiceFactory::GetForBrowserContext(browser_context) + ->proximity_auth_client()); } #endif @@ -277,10 +283,6 @@ WebUIController* NewWebUI<WelcomeWin10UI>(WebUI* web_ui, const GURL& url) { #endif // defined(OS_WIN) bool IsAboutUI(const GURL& url) { - if (base::FeatureList::IsEnabled(features::kBundledConnectionHelpFeature) && - url.host_piece() == chrome::kChromeUIConnectionHelpHost) { - return true; - } return (url.host_piece() == chrome::kChromeUIChromeURLsHost || url.host_piece() == chrome::kChromeUICreditsHost || url.host_piece() == chrome::kChromeUIDNSHost @@ -443,6 +445,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<KeyboardOverlayUI>; if (url.host_piece() == chrome::kChromeUIMobileSetupHost) return &NewWebUI<MobileSetupUI>; + if (url.host_piece() == chrome::kChromeUIMultiDeviceSetupHost) + return &NewWebUI<chromeos::multidevice_setup::MultiDeviceSetupDialogUI>; if (url.host_piece() == chrome::kChromeUINetworkHost) return &NewWebUI<chromeos::NetworkUI>; if (url.host_piece() == chrome::kChromeUIOobeHost) @@ -464,6 +468,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, if (url.host_piece() == chrome::kChromeUISysInternalsHost && SysInternalsUI::IsEnabled()) return &NewWebUI<SysInternalsUI>; + if (url.host_piece() == chrome::kChromeUIAssistantOptInHost) + return &NewWebUI<chromeos::AssistantOptInUI>; #if !defined(OFFICIAL_BUILD) if (!base::SysInfo::IsRunningOnChromeOS()) { if (url.host_piece() == chrome::kChromeUIDeviceEmulatorHost) @@ -573,6 +579,10 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, media_router::MediaRouterEnabled(profile)) { return &NewWebUI<media_router::MediaRouterUI>; } + if (url.host_piece() == chrome::kChromeUIMediaRouterInternalsHost && + media_router::MediaRouterEnabled(profile)) { + return &NewWebUI<media_router::MediaRouterInternalsUI>; + } #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS) if (url.host_piece() == chrome::kChromeUICastHost && @@ -592,6 +602,11 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, if (IsAboutUI(url)) return &NewWebUI<AboutUI>; + if (base::FeatureList::IsEnabled(features::kBundledConnectionHelpFeature) && + url.host_piece() == security_interstitials::kChromeUIConnectionHelpHost) { + return &NewWebUI<security_interstitials::ConnectionHelpUI>; + } + if (dom_distiller::IsEnableDomDistillerSet() && url.host_piece() == dom_distiller::kChromeUIDomDistillerHost) { return &NewWebUI<dom_distiller::DomDistillerUi>; diff --git a/chromium/chrome/browser/ui/webui/chromeos/DEPS b/chromium/chrome/browser/ui/webui/chromeos/DEPS index 2bc7e71f953..3a2bdd04a8d 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/DEPS +++ b/chromium/chrome/browser/ui/webui/chromeos/DEPS @@ -13,8 +13,4 @@ specific_include_rules = { # TODO(mash): Remove. http://crbug.com/770866 "+ash/shell.h", ], - "keyboard_overlay_ui_browsertest\.cc": [ - # TODO(mash): Remove. http://crbug.com/770866 - "+ash/accelerators/accelerator_table.h", - ], } diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h new file mode 100644 index 00000000000..d406d9e3326 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h @@ -0,0 +1,25 @@ +// 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_WEBUI_CHROMEOS_ASSISTANT_OPTIN_ASSISTANT_OPTIN_SCREEN_EXIT_CODE_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_ASSISTANT_OPTIN_SCREEN_EXIT_CODE_H_ + +#include <string> + +#include "base/callback.h" + +namespace chromeos { + +enum class AssistantOptInScreenExitCode { + VALUE_PROP_SKIPPED = 0, + VALUE_PROP_ACCEPTED = 1, + EXIT_CODES_COUNT +}; + +using OnAssistantOptInScreenExitCallback = + base::OnceCallback<void(AssistantOptInScreenExitCode exit_code)>; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_ASSISTANT_OPTIN_SCREEN_EXIT_CODE_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.cc new file mode 100644 index 00000000000..5699c5231b0 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.cc @@ -0,0 +1,124 @@ +// 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/webui/chromeos/assistant_optin/assistant_optin_ui.h" + +#include <memory> + +#include "base/bind.h" +#include "base/macros.h" +#include "chrome/browser/chromeos/arc/voice_interaction/arc_voice_interaction_arc_home_service.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.h" +#include "chrome/common/url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +namespace chromeos { + +namespace { + +bool is_active = false; + +constexpr int kAssistantOptInDialogWidth = 576; +constexpr int kAssistantOptInDialogHeight = 480; + +} // namespace + +AssistantOptInUI::AssistantOptInUI(content::WebUI* web_ui) + : ui::WebDialogUI(web_ui), weak_factory_(this) { + // Set up the chrome://assistant-optin source. + content::WebUIDataSource* source = + content::WebUIDataSource::Create(chrome::kChromeUIAssistantOptInHost); + + AddScreenHandler(std::make_unique<ValuePropScreenHandler>( + base::BindOnce(&AssistantOptInUI::OnExit, weak_factory_.GetWeakPtr()))); + + base::DictionaryValue localized_strings; + for (auto* handler : screen_handlers_) + handler->GetLocalizedStrings(&localized_strings); + source->AddLocalizedStrings(localized_strings); + + source->SetJsonPath("strings.js"); + + source->AddResourcePath("assistant_optin.js", IDR_ASSISTANT_OPTIN_JS); + source->SetDefaultResource(IDR_ASSISTANT_OPTIN_HTML); + + content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); +} + +AssistantOptInUI::~AssistantOptInUI() {} + +void AssistantOptInUI::AddScreenHandler( + std::unique_ptr<BaseWebUIHandler> handler) { + screen_handlers_.push_back(handler.get()); + web_ui()->AddMessageHandler(std::move(handler)); +} + +void AssistantOptInUI::OnExit(AssistantOptInScreenExitCode exit_code) { + switch (exit_code) { + case AssistantOptInScreenExitCode::VALUE_PROP_SKIPPED: + // TODO(updowndota) Update the action to use the new Assistant service. + GetVoiceInteractionHomeService()->OnAssistantCanceled(); + CloseDialog(nullptr); + break; + case AssistantOptInScreenExitCode::VALUE_PROP_ACCEPTED: + // TODO(updowndota) Update the action to use the new Assistant service. + GetVoiceInteractionHomeService()->OnAssistantAppRequested(); + CloseDialog(nullptr); + break; + default: + NOTREACHED(); + } +} + +arc::ArcVoiceInteractionArcHomeService* +AssistantOptInUI::GetVoiceInteractionHomeService() { + Profile* const profile = Profile::FromWebUI(web_ui()); + arc::ArcVoiceInteractionArcHomeService* const home_service = + arc::ArcVoiceInteractionArcHomeService::GetForBrowserContext(profile); + DCHECK(home_service); + return home_service; +} + +// AssistantOptInDialog + +// static +void AssistantOptInDialog::Show() { + DCHECK(!is_active); + AssistantOptInDialog* dialog = new AssistantOptInDialog(); + dialog->ShowSystemDialog(true); +} + +// static +bool AssistantOptInDialog::IsActive() { + return is_active; +} + +AssistantOptInDialog::AssistantOptInDialog() + : SystemWebDialogDelegate(GURL(chrome::kChromeUIAssistantOptInURL), + base::string16()) { + DCHECK(!is_active); + is_active = true; +} + +AssistantOptInDialog::~AssistantOptInDialog() { + is_active = false; +} + +void AssistantOptInDialog::GetDialogSize(gfx::Size* size) const { + size->SetSize(kAssistantOptInDialogWidth, kAssistantOptInDialogHeight); +} + +std::string AssistantOptInDialog::GetDialogArgs() const { + return std::string(); +} + +bool AssistantOptInDialog::ShouldShowDialogTitle() const { + return false; +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h new file mode 100644 index 00000000000..7fff5334be4 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h @@ -0,0 +1,70 @@ +// 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_WEBUI_CHROMEOS_ASSISTANT_OPTIN_ASSISTANT_OPTIN_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_ASSISTANT_OPTIN_UI_H_ + +#include <vector> + +#include "base/callback.h" +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h" +#include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" +#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" +#include "content/public/browser/web_ui_controller.h" +#include "ui/web_dialogs/web_dialog_ui.h" + +namespace arc { +class ArcVoiceInteractionArcHomeService; +} + +namespace chromeos { + +// Controller for chrome://assistant-optin/ page. +class AssistantOptInUI : public ui::WebDialogUI { + public: + explicit AssistantOptInUI(content::WebUI* web_ui); + ~AssistantOptInUI() override; + + private: + // Add message handler for optin screens. + void AddScreenHandler(std::unique_ptr<BaseWebUIHandler> handler); + + // Called by a screen when user's done with it. + void OnExit(AssistantOptInScreenExitCode exit_code); + + // Get ArcHomeService for user action handling. + arc::ArcVoiceInteractionArcHomeService* GetVoiceInteractionHomeService(); + + std::vector<BaseWebUIHandler*> screen_handlers_; + base::WeakPtrFactory<AssistantOptInUI> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(AssistantOptInUI); +}; + +// Dialog delegate for the assistant optin page. +class AssistantOptInDialog : public SystemWebDialogDelegate { + public: + // Shows the assistant optin dialog. + static void Show(); + + // Returns whether the dialog is being shown. + static bool IsActive(); + + protected: + AssistantOptInDialog(); + ~AssistantOptInDialog() override; + + // ui::WebDialogDelegate + void GetDialogSize(gfx::Size* size) const override; + std::string GetDialogArgs() const override; + bool ShouldShowDialogTitle() const override; + + private: + DISALLOW_COPY_AND_ASSIGN(AssistantOptInDialog); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_ASSISTANT_OPTIN_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.cc new file mode 100644 index 00000000000..e601e28f4a0 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.cc @@ -0,0 +1,66 @@ +// 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/webui/chromeos/assistant_optin/value_prop_screen_handler.h" + +#include "chrome/browser/browser_process.h" +#include "chrome/grit/generated_resources.h" +#include "components/login/localized_values_builder.h" + +namespace { + +const char kJsScreenPath[] = "AssistantValuePropScreen"; + +constexpr const char kUserActionSkipPressed[] = "skip-pressed"; +constexpr const char kUserActionNextPressed[] = "next-pressed"; + +} // namespace + +namespace chromeos { + +ValuePropScreenHandler::ValuePropScreenHandler( + OnAssistantOptInScreenExitCallback callback) + : BaseWebUIHandler(), exit_callback_(std::move(callback)) { + set_call_js_prefix(kJsScreenPath); +} + +ValuePropScreenHandler::~ValuePropScreenHandler() = default; + +void ValuePropScreenHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) { + builder->Add("locale", g_browser_process->GetApplicationLocale()); + builder->Add("voiceInteractionValuePropLoading", + IDS_VOICE_INTERACTION_VALUE_PROP_LOADING); + builder->Add("voiceInteractionValuePropLoadErrorTitle", + IDS_VOICE_INTERACTION_VALUE_PROP_LOAD_ERROR_TITLE); + builder->Add("voiceInteractionValuePropLoadErrorMessage", + IDS_VOICE_INTERACTION_VALUE_PROP_LOAD_ERROR_MESSAGE); + builder->Add("voiceInteractionValuePropSkipButton", + IDS_VOICE_INTERACTION_VALUE_PROP_SKIP_BUTTON); + builder->Add("voiceInteractionValuePropRetryButton", + IDS_VOICE_INTERACTION_VALUE_PROP_RETRY_BUTTON); + builder->Add("voiceInteractionValuePropNextButton", + IDS_VOICE_INTERACTION_VALUE_PROP_NEXT_BUTTION); + + builder->Add("back", IDS_EULA_BACK_BUTTON); + builder->Add("next", IDS_EULA_NEXT_BUTTON); +} + +void ValuePropScreenHandler::RegisterMessages() { + AddPrefixedCallback("userActed", &ValuePropScreenHandler::HandleUserAction); +} + +void ValuePropScreenHandler::Initialize() {} + +void ValuePropScreenHandler::HandleUserAction(const std::string& action) { + DCHECK(exit_callback_); + if (action == kUserActionSkipPressed) + std::move(exit_callback_) + .Run(AssistantOptInScreenExitCode::VALUE_PROP_SKIPPED); + else if (action == kUserActionNextPressed) + std::move(exit_callback_) + .Run(AssistantOptInScreenExitCode::VALUE_PROP_ACCEPTED); +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.h new file mode 100644 index 00000000000..ec8e0324871 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.h @@ -0,0 +1,38 @@ +// 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_WEBUI_CHROMEOS_ASSISTANT_OPTIN_VALUE_PROP_SCREEN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_VALUE_PROP_SCREEN_HANDLER_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h" +#include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" + +namespace chromeos { + +class ValuePropScreenHandler : public BaseWebUIHandler { + public: + explicit ValuePropScreenHandler(OnAssistantOptInScreenExitCallback callback); + ~ValuePropScreenHandler() override; + + // BaseWebUIHandler: + void DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) override; + void RegisterMessages() override; + void Initialize() override; + + private: + void HandleUserAction(const std::string& action); + + OnAssistantOptInScreenExitCallback exit_callback_; + + DISALLOW_COPY_AND_ASSIGN(ValuePropScreenHandler); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_VALUE_PROP_SCREEN_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc index 007928a7d0e..40d8a1a021e 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc @@ -22,9 +22,8 @@ CryptohomeWebUIHandler::~CryptohomeWebUIHandler() {} void CryptohomeWebUIHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "pageLoaded", - base::Bind(&CryptohomeWebUIHandler::OnPageLoaded, - weak_ptr_factory_.GetWeakPtr())); + "pageLoaded", base::BindRepeating(&CryptohomeWebUIHandler::OnPageLoaded, + weak_ptr_factory_.GetWeakPtr())); } void CryptohomeWebUIHandler::OnPageLoaded(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc index 5ee6b3b64bf..20001250450 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc @@ -375,28 +375,28 @@ void DriveInternalsWebUIHandler::OnGetAppList( void DriveInternalsWebUIHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "pageLoaded", - base::Bind(&DriveInternalsWebUIHandler::OnPageLoaded, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&DriveInternalsWebUIHandler::OnPageLoaded, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "periodicUpdate", - base::Bind(&DriveInternalsWebUIHandler::OnPeriodicUpdate, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&DriveInternalsWebUIHandler::OnPeriodicUpdate, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "clearAccessToken", - base::Bind(&DriveInternalsWebUIHandler::ClearAccessToken, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&DriveInternalsWebUIHandler::ClearAccessToken, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "clearRefreshToken", - base::Bind(&DriveInternalsWebUIHandler::ClearRefreshToken, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&DriveInternalsWebUIHandler::ClearRefreshToken, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "resetDriveFileSystem", - base::Bind(&DriveInternalsWebUIHandler::ResetDriveFileSystem, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&DriveInternalsWebUIHandler::ResetDriveFileSystem, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "listFileEntries", - base::Bind(&DriveInternalsWebUIHandler::ListFileEntries, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&DriveInternalsWebUIHandler::ListFileEntries, + weak_ptr_factory_.GetWeakPtr())); } drive::DriveIntegrationService* diff --git a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc index cc3b48bb8a2..72550162ed7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc @@ -476,72 +476,77 @@ void DeviceEmulatorMessageHandler::UpdatePowerSourceId( void DeviceEmulatorMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - kInitialize, - base::Bind(&DeviceEmulatorMessageHandler::Init, base::Unretained(this))); + kInitialize, base::BindRepeating(&DeviceEmulatorMessageHandler::Init, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kRequestPowerInfo, - base::Bind(&DeviceEmulatorMessageHandler::RequestPowerInfo, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::RequestPowerInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kUpdateBatteryPercent, - base::Bind(&DeviceEmulatorMessageHandler::UpdateBatteryPercent, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::UpdateBatteryPercent, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kUpdateBatteryState, - base::Bind(&DeviceEmulatorMessageHandler::UpdateBatteryState, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::UpdateBatteryState, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kUpdateTimeToEmpty, - base::Bind(&DeviceEmulatorMessageHandler::UpdateTimeToEmpty, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::UpdateTimeToEmpty, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kUpdateTimeToFull, - base::Bind(&DeviceEmulatorMessageHandler::UpdateTimeToFull, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::UpdateTimeToFull, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kUpdatePowerSources, - base::Bind(&DeviceEmulatorMessageHandler::UpdatePowerSources, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::UpdatePowerSources, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kUpdatePowerSourceId, - base::Bind(&DeviceEmulatorMessageHandler::UpdatePowerSourceId, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::UpdatePowerSourceId, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kRequestAudioNodes, - base::Bind(&DeviceEmulatorMessageHandler::HandleRequestAudioNodes, - base::Unretained(this))); + base::BindRepeating( + &DeviceEmulatorMessageHandler::HandleRequestAudioNodes, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kInsertAudioNode, - base::Bind(&DeviceEmulatorMessageHandler::HandleInsertAudioNode, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::HandleInsertAudioNode, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kRemoveAudioNode, - base::Bind(&DeviceEmulatorMessageHandler::HandleRemoveAudioNode, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::HandleRemoveAudioNode, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kBluetoothDiscoverFunction, - base::Bind(&DeviceEmulatorMessageHandler::HandleRequestBluetoothDiscover, - base::Unretained(this))); + base::BindRepeating( + &DeviceEmulatorMessageHandler::HandleRequestBluetoothDiscover, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kBluetoothPairFunction, - base::Bind(&DeviceEmulatorMessageHandler::HandleRequestBluetoothPair, - base::Unretained(this))); + base::BindRepeating( + &DeviceEmulatorMessageHandler::HandleRequestBluetoothPair, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kRequestBluetoothInfo, - base::Bind(&DeviceEmulatorMessageHandler::HandleRequestBluetoothInfo, - base::Unretained(this))); + base::BindRepeating( + &DeviceEmulatorMessageHandler::HandleRequestBluetoothInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kRemoveBluetoothDevice, - base::Bind(&DeviceEmulatorMessageHandler::HandleRemoveBluetoothDevice, - base::Unretained(this))); + base::BindRepeating( + &DeviceEmulatorMessageHandler::HandleRemoveBluetoothDevice, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kSetHasTouchpad, - base::Bind(&DeviceEmulatorMessageHandler::HandleSetHasTouchpad, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::HandleSetHasTouchpad, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kSetHasMouse, - base::Bind(&DeviceEmulatorMessageHandler::HandleSetHasMouse, - base::Unretained(this))); + base::BindRepeating(&DeviceEmulatorMessageHandler::HandleSetHasMouse, + base::Unretained(this))); } void DeviceEmulatorMessageHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.cc b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.cc index 9c2e91fe57a..0abfadebb2f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.cc @@ -6,7 +6,6 @@ #include <limits> -#include "base/memory/ptr_util.h" #include "base/values.h" namespace { diff --git a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc index 312a70506e7..5b5c071700f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc @@ -5,7 +5,6 @@ #include "chrome/browser/ui/webui/chromeos/first_run/first_run_handler.h" #include "base/bind.h" -#include "base/memory/ptr_util.h" #include "base/values.h" #include "chromeos/chromeos_switches.h" #include "content/public/browser/web_ui.h" @@ -88,23 +87,26 @@ bool FirstRunHandler::IsFinalizing() { } void FirstRunHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("initialized", - base::Bind(&FirstRunHandler::HandleInitialized, base::Unretained(this))); - web_ui()->RegisterMessageCallback("nextButtonClicked", - base::Bind(&FirstRunHandler::HandleNextButtonClicked, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("helpButtonClicked", - base::Bind(&FirstRunHandler::HandleHelpButtonClicked, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("stepShown", - base::Bind(&FirstRunHandler::HandleStepShown, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("stepHidden", - base::Bind(&FirstRunHandler::HandleStepHidden, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("finalized", - base::Bind(&FirstRunHandler::HandleFinalized, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "initialized", base::BindRepeating(&FirstRunHandler::HandleInitialized, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "nextButtonClicked", + base::BindRepeating(&FirstRunHandler::HandleNextButtonClicked, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "helpButtonClicked", + base::BindRepeating(&FirstRunHandler::HandleHelpButtonClicked, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "stepShown", base::BindRepeating(&FirstRunHandler::HandleStepShown, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "stepHidden", base::BindRepeating(&FirstRunHandler::HandleStepHidden, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "finalized", base::BindRepeating(&FirstRunHandler::HandleFinalized, + base::Unretained(this))); } void FirstRunHandler::HandleInitialized(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc index 3f191280d06..a05bb03c5dc 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc @@ -4,6 +4,7 @@ #include "chrome/browser/ui/webui/chromeos/internet_detail_dialog.h" +#include "base/json/json_writer.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h" @@ -13,6 +14,7 @@ #include "chromeos/network/network_handler.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" +#include "chromeos/network/network_util.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" @@ -54,12 +56,18 @@ void AddInternetStrings(content::WebUIDataSource* html_source) { html_source->AddLocalizedString(entry.name, entry.id); } -base::string16 GetNetworkName(const NetworkState& network) { +base::string16 GetNetworkName16(const NetworkState& network) { return network.Matches(NetworkTypePattern::Ethernet()) ? l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_ETHERNET) : base::UTF8ToUTF16(network.name()); } +std::string GetNetworkName8(const NetworkState& network) { + return network.Matches(NetworkTypePattern::Ethernet()) + ? l10n_util::GetStringUTF8(IDS_NETWORK_TYPE_ETHERNET) + : network.name(); +} + } // namespace // static @@ -85,8 +93,10 @@ void InternetDetailDialog::ShowDialog(const std::string& network_id) { InternetDetailDialog::InternetDetailDialog(const NetworkState& network) : SystemWebDialogDelegate(GURL(chrome::kChromeUIIntenetDetailDialogURL), - GetNetworkName(network)), - guid_(network.guid()) { + GetNetworkName16(network)), + network_id_(network.guid()), + network_type_(network_util::TranslateShillTypeToONC(network.type())), + network_name_(GetNetworkName8(network)) { ++s_internet_detail_dialog_count; } @@ -100,7 +110,13 @@ void InternetDetailDialog::GetDialogSize(gfx::Size* size) const { } std::string InternetDetailDialog::GetDialogArgs() const { - return guid_; + base::DictionaryValue args; + args.SetKey("type", base::Value(network_type_)); + args.SetKey("guid", base::Value(network_id_)); + args.SetKey("name", base::Value(network_name_)); + std::string json; + base::JSONWriter::Write(args, &json); + return json; } // InternetDetailDialogUI diff --git a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.h index 92b27a89dd1..c508049ce0a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.h +++ b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.h @@ -31,7 +31,9 @@ class InternetDetailDialog : public SystemWebDialogDelegate { std::string GetDialogArgs() const override; private: - std::string guid_; + std::string network_id_; + std::string network_type_; + std::string network_name_; DISALLOW_COPY_AND_ASSIGN(InternetDetailDialog); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc index d9eb8871542..c197c33b4de 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc @@ -393,15 +393,17 @@ KeyboardOverlayHandler::~KeyboardOverlayHandler() { } void KeyboardOverlayHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("getInputMethodId", - base::Bind(&KeyboardOverlayHandler::GetInputMethodId, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("getLabelMap", - base::Bind(&KeyboardOverlayHandler::GetLabelMap, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("openLearnMorePage", - base::Bind(&KeyboardOverlayHandler::OpenLearnMorePage, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getInputMethodId", + base::BindRepeating(&KeyboardOverlayHandler::GetInputMethodId, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getLabelMap", base::BindRepeating(&KeyboardOverlayHandler::GetLabelMap, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "openLearnMorePage", + base::BindRepeating(&KeyboardOverlayHandler::OpenLearnMorePage, + base::Unretained(this))); } void KeyboardOverlayHandler::GetInputMethodId(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui_browsertest.cc index 1e0bc93e3ea..d460b5a77da 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui_browsertest.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/accelerators/accelerator_table.h" +#include "ash/public/cpp/accelerators.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/url_constants.h" @@ -23,8 +23,9 @@ class TestWebUIMessageHandler : public content::WebUIMessageHandler { // content::WebUIMessageHandler: void RegisterMessages() override { web_ui()->RegisterMessageCallback( - "didPaint", base::Bind(&TestWebUIMessageHandler::HandleDidPaint, - base::Unretained(this))); + "didPaint", + base::BindRepeating(&TestWebUIMessageHandler::HandleDidPaint, + base::Unretained(this))); } private: @@ -124,11 +125,21 @@ bool ContainsShortcut(const std::string& shortcut, using KeyboardOverlayUIBrowserTest = InProcessBrowserTest; +// This test verifies two things: +// +// 1. That all accelerators in kAcceleratorData appear in the keyboard overlay +// UI. This will fail when a new shortcut is added (or replaced) in +// kAcceleratorData but not the overlay UI. +// +// 2. That the number of accelerators shared by the Ash table and the UI is the +// expected value. This will fail when a new shortcut is added to +// kAcceleratorData but not the overlay UI. IN_PROC_BROWSER_TEST_F(KeyboardOverlayUIBrowserTest, AcceleratorsShouldHaveKeyboardOverlay) { content::WebContents* const web_contents = StartKeyboardOverlayUI(browser()); const bool is_display_ui_scaling_enabled = IsDisplayUIScalingEnabled(web_contents); + int found_accelerators = 0; for (size_t i = 0; i < ash::kAcceleratorDataLength; ++i) { const ash::AcceleratorData& entry = ash::kAcceleratorData[i]; if (ShouldSkip(entry)) @@ -142,32 +153,26 @@ IN_PROC_BROWSER_TEST_F(KeyboardOverlayUIBrowserTest, } } - EXPECT_TRUE(ContainsShortcut(shortcut, web_contents)) - << "Please add the new accelerators to keyboard " - "overlay. Add one entry '" + - shortcut + - "' in the 'shortcut' section" - " at the bottom of the file of " - "'/chrome/browser/resources/chromeos/" - "keyboard_overlay_data.js'. Please keep it in " - "alphabetical order."; + if (ContainsShortcut(shortcut, web_contents)) { + found_accelerators++; + } else { + ADD_FAILURE() << "Please add the new accelerators to keyboard " + "overlay. Add one entry '" + + shortcut + + "' in the 'shortcut' section" + " at the bottom of the file of " + "'/chrome/browser/resources/chromeos/" + "keyboard_overlay_data.js'. Please keep it in " + "alphabetical order."; + } } -} -IN_PROC_BROWSER_TEST_F(KeyboardOverlayUIBrowserTest, - DeprecatedAcceleratorsShouldNotHaveKeyboardOverlay) { - content::WebContents* const web_contents = StartKeyboardOverlayUI(browser()); - for (size_t i = 0; i < ash::kDeprecatedAcceleratorsLength; ++i) { - const ash::AcceleratorData& entry = ash::kDeprecatedAccelerators[i]; - if (ShouldSkip(entry)) - continue; - - const std::string shortcut = GenerateShortcutKey(entry, web_contents); - EXPECT_FALSE(ContainsShortcut(shortcut, web_contents)) - << "Please remove the deprecated accelerator '" + shortcut + - "' from the 'shortcut' section" - " at the bottom of the file of " - "'/chrome/browser/resources/chromeos/" - "keyboard_overlay_data.js'."; - } + constexpr int kExpectedFoundAccelerators = 60; + DCHECK_EQ(kExpectedFoundAccelerators, found_accelerators) + << "It seems ash::kAcceleratorData or the 'shortcut' section of " + "'/chrome/browser/resources/chromeos/keyboard_overlay_data.js' has " + "changed. Please keep the two in sync. If you've deprecated an " + "accelerator, remove it from keyboard_overlay_data.js. If you have " + "added the accelerator in both places, update " + "kExpectedFoundAccelerators."; } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/DEPS b/chromium/chrome/browser/ui/webui/chromeos/login/DEPS index 7b8d6a6dd68..c2770adaae7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/DEPS +++ b/chromium/chrome/browser/ui/webui/chromeos/login/DEPS @@ -25,10 +25,12 @@ specific_include_rules = { "+ui/events/devices/device_data_manager.h", ], "signin_screen_handler\.cc": [ + "+ash/detachable_base", "+ash/shell.h", "+ash/wallpaper/wallpaper_controller.h", ], "signin_screen_handler\.h": [ + "+ash/detachable_base/detachable_base_observer.h", "+ash/wallpaper/wallpaper_controller_observer.h", ], "signin_userlist_unittest\.cc": [ diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.cc index 42a867d7dfc..1051eee4e93 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.cc @@ -13,6 +13,7 @@ #include "chrome/browser/consent_auditor/consent_auditor_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/grit/generated_resources.h" #include "chromeos/chromeos_switches.h" #include "chromeos/network/network_handler.h" @@ -22,6 +23,7 @@ #include "components/consent_auditor/consent_auditor.h" #include "components/login/localized_values_builder.h" #include "components/prefs/pref_service.h" +#include "components/signin/core/browser/signin_manager_base.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "ui/base/l10n/l10n_util.h" @@ -258,20 +260,24 @@ void ArcTermsOfServiceScreenHandler::HandleAccept( pref_handler_->EnableBackupRestore(enable_backup_restore); pref_handler_->EnableLocationService(enable_location_services); + Profile* profile = ProfileManager::GetActiveUserProfile(); consent_auditor::ConsentAuditor* consent_auditor = - ConsentAuditorFactory::GetForProfile( - ProfileManager::GetPrimaryUserProfile()); + ConsentAuditorFactory::GetForProfile(profile); + SigninManagerBase* signin_manager = + SigninManagerFactory::GetForProfile(profile); + DCHECK(signin_manager->IsAuthenticated()); + std::string account_id = signin_manager->GetAuthenticatedAccountId(); // Record acceptance of Play ToS. consent_auditor->RecordGaiaConsent( - consent_auditor::Feature::PLAY_STORE, + account_id, consent_auditor::Feature::PLAY_STORE, ArcSupportHost::ComputePlayToSConsentIds(tos_content), IDS_ARC_OOBE_TERMS_BUTTON_ACCEPT, consent_auditor::ConsentStatus::GIVEN); // If the user - not policy - chose Backup and Restore, record consent. if (enable_backup_restore && !backup_restore_managed_) { consent_auditor->RecordGaiaConsent( - consent_auditor::Feature::BACKUP_AND_RESTORE, + account_id, consent_auditor::Feature::BACKUP_AND_RESTORE, {IDS_ARC_OPT_IN_DIALOG_BACKUP_RESTORE}, IDS_ARC_OOBE_TERMS_BUTTON_ACCEPT, consent_auditor::ConsentStatus::GIVEN); @@ -280,7 +286,7 @@ void ArcTermsOfServiceScreenHandler::HandleAccept( // If the user - not policy - chose Location Services, record consent. if (enable_location_services && !location_services_managed_) { consent_auditor->RecordGaiaConsent( - consent_auditor::Feature::GOOGLE_LOCATION_SERVICE, + account_id, consent_auditor::Feature::GOOGLE_LOCATION_SERVICE, {IDS_ARC_OPT_IN_LOCATION_SETTING}, IDS_ARC_OOBE_TERMS_BUTTON_ACCEPT, consent_auditor::ConsentStatus::GIVEN); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.h index 3d959a75100..37835bcc32c 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.h @@ -185,15 +185,17 @@ class BaseWebUIHandler : public content::WebUIMessageHandler, void AddRawCallback(const std::string& name, void (T::*method)(const base::ListValue* args)) { web_ui()->RegisterMessageCallback( - name, base::Bind(method, base::Unretained(static_cast<T*>(this)))); + name, + base::BindRepeating(method, base::Unretained(static_cast<T*>(this)))); } template <typename T, typename... Args> void AddCallback(const std::string& name, void (T::*method)(Args...)) { - base::Callback<void(Args...)> callback = + base::RepeatingCallback<void(Args...)> callback = base::Bind(method, base::Unretained(static_cast<T*>(this))); web_ui()->RegisterMessageCallback( - name, base::Bind(&::login::CallbackWrapper<Args...>, callback)); + name, + base::BindRepeating(&::login::CallbackWrapper<Args...>, callback)); } template <typename Method> diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc index 1164b909f83..323811e0f43 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc @@ -6,7 +6,6 @@ #include <type_traits> -#include "ash/public/cpp/accessibility_types.h" #include "ash/shell.h" #include "base/bind.h" #include "base/strings/utf_string_conversions.h" @@ -195,7 +194,6 @@ void CoreOobeHandler::RegisterMessages() { &CoreOobeHandler::HandleSetOobeBootstrappingSlave); AddRawCallback("getPrimaryDisplayNameForTesting", &CoreOobeHandler::HandleGetPrimaryDisplayNameForTesting); - AddCallback("setupDemoMode", &CoreOobeHandler::HandleSetupDemoMode); } void CoreOobeHandler::ShowSignInError( @@ -333,8 +331,7 @@ void CoreOobeHandler::HandleEnableSpokenFeedback(bool /* enabled */) { // Checkbox is initialized on page init and updates when spoken feedback // setting is changed so just toggle spoken feedback here. AccessibilityManager* manager = AccessibilityManager::Get(); - manager->EnableSpokenFeedback(!manager->IsSpokenFeedbackEnabled(), - ash::A11Y_NOTIFICATION_NONE); + manager->EnableSpokenFeedback(!manager->IsSpokenFeedbackEnabled()); } void CoreOobeHandler::HandleSetDeviceRequisition( @@ -578,15 +575,6 @@ void CoreOobeHandler::HandleGetPrimaryDisplayNameForTesting( ResolveJavascriptCallback(*callback_id, base::Value(display_name)); } -void CoreOobeHandler::HandleSetupDemoMode() { - const bool is_demo_mode_enabled = - base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kEnableDemoMode); - if (is_demo_mode_enabled) { - NOTIMPLEMENTED(); - } -} - void CoreOobeHandler::InitDemoModeDetection() { demo_mode_detector_.InitDetection(); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h index 795c016df47..2579735ea1f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h @@ -130,7 +130,6 @@ class CoreOobeHandler : public BaseWebUIHandler, void HandleHeaderBarVisible(); void HandleSetOobeBootstrappingSlave(); void HandleGetPrimaryDisplayNameForTesting(const base::ListValue* args); - void HandleSetupDemoMode(); // When keyboard_utils.js arrow key down event is reached, raise it // to tab/shift-tab event. diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.cc new file mode 100644 index 00000000000..048e993ee7b --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.cc @@ -0,0 +1,45 @@ +// 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 "chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h" + +#include "chrome/browser/chromeos/login/oobe_screen.h" +#include "chrome/browser/chromeos/login/screens/demo_setup_screen.h" +#include "chrome/browser/chromeos/login/wizard_controller.h" + +namespace { + +constexpr char kJsScreenPath[] = "login.DemoSetupScreen"; + +} // namespace + +namespace chromeos { + +DemoSetupScreenHandler::DemoSetupScreenHandler() + : BaseScreenHandler(kScreenId) { + set_call_js_prefix(kJsScreenPath); +} + +DemoSetupScreenHandler::~DemoSetupScreenHandler() { + if (screen_) + screen_->OnViewDestroyed(this); +} + +void DemoSetupScreenHandler::Show() { + ShowScreen(kScreenId); +} + +void DemoSetupScreenHandler::Hide() {} + +void DemoSetupScreenHandler::Bind(DemoSetupScreen* screen) { + screen_ = screen; + BaseScreenHandler::SetBaseScreen(screen); +} + +void DemoSetupScreenHandler::Initialize() {} + +void DemoSetupScreenHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) {} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h new file mode 100644 index 00000000000..d75084d7c81 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h @@ -0,0 +1,49 @@ +// 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. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DEMO_SETUP_SCREEN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DEMO_SETUP_SCREEN_HANDLER_H_ + +#include "chrome/browser/chromeos/login/screens/demo_setup_screen_view.h" +#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" + +namespace chromeos { + +class DemoSetupScreen; + +// WebUI implementation of DemoSetupScreenView. It controlls UI, receives UI +// events and notifies the Delegate. +class DemoSetupScreenHandler : public BaseScreenHandler, + public DemoSetupScreenView { + public: + DemoSetupScreenHandler(); + ~DemoSetupScreenHandler() override; + + // DemoSetupScreenView: + void Show() override; + void Hide() override; + void Bind(DemoSetupScreen* screen) override; + + // BaseScreenHandler: + void Initialize() override; + void DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) override; + + private: + // Enumeration for UI states. These values have to be kept in sync with JS + // code in oobe_screen_demo_setup.js. + enum class UiState : int { + kError = -1, // Displaying error. + kDefault = 0, // Displaying initial UI. + kProcessing = 1, // Displaying setup in progress. + }; + + DemoSetupScreen* screen_ = nullptr; + + DISALLOW_COPY_AND_ASSIGN(DemoSetupScreenHandler); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DEMO_SETUP_SCREEN_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc index 3f3a9c1e27a..499a1fcd208 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc @@ -386,7 +386,7 @@ void EncryptionMigrationScreenHandler::SetFreeDiskSpaceFetcherForTesting( } void EncryptionMigrationScreenHandler::SetTickClockForTesting( - base::TickClock* tick_clock) { + const base::TickClock* tick_clock) { tick_clock_ = tick_clock; } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h index 48ce6f487b4..f13f58d641d 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h @@ -66,7 +66,7 @@ class EncryptionMigrationScreenHandler : public EncryptionMigrationScreenView, // migration. // This doesn't toke the ownership of the clock. |tick_clock| must outlive the // EncryptionMigrationScreenHandler instance. - void SetTickClockForTesting(base::TickClock* tick_clock); + void SetTickClockForTesting(const base::TickClock* tick_clock); virtual device::mojom::WakeLock* GetWakeLock(); @@ -182,7 +182,7 @@ class EncryptionMigrationScreenHandler : public EncryptionMigrationScreenView, std::unique_ptr<LoginFeedback> login_feedback_; // Used to measure elapsed time during migration. - base::TickClock* tick_clock_; + const base::TickClock* tick_clock_; FreeDiskSpaceFetcher free_disk_space_fetcher_; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc index 7df38e2a0c8..d2be8e2f957 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc @@ -26,7 +26,7 @@ #include "components/login/localized_values_builder.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_contents.h" -#include "rlz/features/features.h" +#include "rlz/buildflags/buildflags.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/widget/widget.h" #include "url/gurl.h" diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc index b54c7d66bc8..9a56f4b08db 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc @@ -397,7 +397,7 @@ void GaiaScreenHandler::LoadGaiaWithPartitionAndVersionAndConsent( params.SetString("clientVersion", version_info::GetVersionNumber()); if (!platform_version->empty()) params.SetString("platformVersion", *platform_version); - params.SetString("releaseChannel", chrome::GetChannelString()); + params.SetString("releaseChannel", chrome::GetChannelName()); params.SetString("endpointGen", kEndpointGen); std::string email_domain; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_app_menu_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_app_menu_handler.cc index 1ea68542836..c490f9533d6 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_app_menu_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_app_menu_handler.cc @@ -77,15 +77,18 @@ void KioskAppMenuHandler::GetLocalizedStrings( } void KioskAppMenuHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("initializeKioskApps", - base::Bind(&KioskAppMenuHandler::HandleInitializeKioskApps, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("kioskAppsLoaded", - base::Bind(&KioskAppMenuHandler::HandleKioskAppsLoaded, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("checkKioskAppLaunchError", - base::Bind(&KioskAppMenuHandler::HandleCheckKioskAppLaunchError, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "initializeKioskApps", + base::BindRepeating(&KioskAppMenuHandler::HandleInitializeKioskApps, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "kioskAppsLoaded", + base::BindRepeating(&KioskAppMenuHandler::HandleKioskAppsLoaded, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "checkKioskAppLaunchError", + base::BindRepeating(&KioskAppMenuHandler::HandleCheckKioskAppLaunchError, + base::Unretained(this))); } // static diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc index 87a5e5e2571..40285b1c400 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc @@ -18,6 +18,7 @@ #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chromeos/login/enrollment/auto_enrollment_check_screen_view.h" #include "chrome/browser/chromeos/login/enrollment/enrollment_screen_view.h" +#include "chrome/browser/chromeos/login/screens/demo_setup_screen_view.h" #include "chrome/browser/chromeos/login/screens/error_screen.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" #include "chrome/browser/chromeos/login/wizard_controller.h" @@ -36,6 +37,7 @@ #include "chrome/browser/ui/webui/chromeos/login/auto_enrollment_check_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/controller_pairing_screen_handler.h" +#include "chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h" @@ -112,6 +114,7 @@ const char kCustomElementsUserPodHTMLPath[] = "custom_elements_user_pod.html"; const char kEnrollmentHTMLPath[] = "enrollment.html"; const char kEnrollmentCSSPath[] = "enrollment.css"; const char kEnrollmentJSPath[] = "enrollment.js"; +const char kArcAssistantLogoPath[] = "assistant_logo.png"; const char kArcPlaystoreCSSPath[] = "playstore.css"; const char kArcPlaystoreJSPath[] = "playstore.js"; const char kArcPlaystoreLogoPath[] = "playstore.svg"; @@ -172,6 +175,9 @@ content::WebUIDataSource* CreateOobeUIDataSource( source->AddResourcePath(kArcPlaystoreLogoPath, IDR_ARC_SUPPORT_PLAYSTORE_LOGO); + // Required for Assistant OOBE. + source->AddResourcePath(kArcAssistantLogoPath, IDR_ASSISTANT_LOGO_PNG); + // Required in encryption migration screen. source->AddResourcePath(kProductLogoPath, IDR_PRODUCT_LOGO_64); @@ -290,6 +296,8 @@ OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url) AddScreenHandler(std::make_unique<UserBoardScreenHandler>()); + AddScreenHandler(std::make_unique<DemoSetupScreenHandler>()); + policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); ActiveDirectoryPasswordChangeScreenHandler* @@ -406,6 +414,10 @@ ResetView* OobeUI::GetResetView() { return GetView<ResetScreenHandler>(); } +DemoSetupScreenView* OobeUI::GetDemoSetupScreenView() { + return GetView<DemoSetupScreenHandler>(); +} + KioskAutolaunchScreenView* OobeUI::GetKioskAutolaunchScreenView() { return GetView<KioskAutolaunchScreenHandler>(); } @@ -524,11 +536,6 @@ void OobeUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) { g_browser_process->local_state()->GetBoolean(prefs::kOobeMdMode); localized_strings->SetString("newOobeUI", oobe_ui_md_mode_ ? "on" : "off"); localized_strings->SetString( - "errorScreenMDMode", base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kDisableMdErrorScreen) - ? "off" - : "on"); - localized_strings->SetString( "showViewsLock", ash::switches::IsUsingViewsLock() ? "on" : "off"); localized_strings->SetString( "showViewsLogin", ash::switches::IsUsingViewsLogin() ? "on" : "off"); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h index 4a1eb7d2094..38483573bff 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h @@ -54,6 +54,7 @@ class SigninScreenHandler; class SigninScreenHandlerDelegate; class SupervisedUserCreationScreenHandler; class ResetView; +class DemoSetupScreenView; class SyncConsentScreenView; class TermsOfServiceScreenView; class UserBoardView; @@ -104,6 +105,7 @@ class OobeUI : public content::WebUIController, EnableDebuggingScreenView* GetEnableDebuggingScreenView(); EnrollmentScreenView* GetEnrollmentScreenView(); ResetView* GetResetView(); + DemoSetupScreenView* GetDemoSetupScreenView(); KioskAutolaunchScreenView* GetKioskAutolaunchScreenView(); KioskEnableScreenView* GetKioskEnableScreenView(); TermsOfServiceScreenView* GetTermsOfServiceScreenView(); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc index aebb3b11c28..5eefbf79840 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc @@ -10,6 +10,7 @@ #include <utility> #include <vector> +#include "ash/detachable_base/detachable_base_handler.h" #include "ash/public/cpp/login_constants.h" #include "ash/public/interfaces/constants.mojom.h" #include "ash/public/interfaces/shutdown.mojom.h" @@ -40,6 +41,7 @@ #include "chrome/browser/chromeos/ash_config.h" #include "chrome/browser/chromeos/language_preferences.h" #include "chrome/browser/chromeos/lock_screen_apps/state_controller.h" +#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service.h" #include "chrome/browser/chromeos/login/error_screens_histogram_helper.h" #include "chrome/browser/chromeos/login/hwid_checker.h" #include "chrome/browser/chromeos/login/lock/screen_locker.h" @@ -66,7 +68,6 @@ #include "chrome/browser/io_thread.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_metrics.h" -#include "chrome/browser/signin/easy_unlock_service.h" #include "chrome/browser/ui/ash/session_controller_client.h" #include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chrome/browser/ui/webui/chromeos/internet_detail_dialog.h" @@ -80,6 +81,7 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "chromeos/chromeos_switches.h" +#include "chromeos/components/proximity_auth/screenlock_bridge.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power_manager_client.h" #include "chromeos/login/auth/key.h" @@ -90,7 +92,7 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/proximity_auth/screenlock_bridge.h" +#include "components/session_manager/core/session_manager.h" #include "components/strings/grit/components_strings.h" #include "components/user_manager/known_user.h" #include "components/user_manager/user.h" @@ -107,6 +109,7 @@ #include "ui/base/ime/chromeos/input_method_descriptor.h" #include "ui/base/ime/chromeos/input_method_manager.h" #include "ui/base/ime/chromeos/input_method_util.h" +#include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #include "ui/chromeos/devicetype_utils.h" #include "ui/gfx/color_analysis.h" @@ -218,6 +221,23 @@ std::string GetNetworkName(const std::string& service_path) { return network->name(); } +ash::mojom::UserInfoPtr GetUserInfoForAccount(const AccountId& account_id) { + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(account_id); + if (!user) + return nullptr; + + auto user_info = ash::mojom::UserInfo::New(); + user_info->type = user->GetType(); + user_info->account_id = account_id; + user_info->is_ephemeral = + user_manager::UserManager::Get()->IsUserNonCryptohomeDataEphemeral( + account_id); + user_info->display_name = base::UTF16ToUTF8(user->display_name()); + user_info->display_email = user->display_email(); + return user_info; +} + } // namespace // LoginScreenContext implementation ------------------------------------------ @@ -258,7 +278,9 @@ SigninScreenHandler::SigninScreenHandler( proxy_auth_dialog_reload_times_(kMaxGaiaReloadForProxyAuthDialog), gaia_screen_handler_(gaia_screen_handler), histogram_helper_(new ErrorScreensHistogramHelper("Signin")), + session_manager_observer_(this), lock_screen_apps_observer_(this), + detachable_base_observer_(this), weak_factory_(this) { DCHECK(network_state_informer_.get()); DCHECK(error_screen_); @@ -294,11 +316,16 @@ SigninScreenHandler::SigninScreenHandler( tablet_mode_client->AddObserver(this); OnTabletModeToggled(tablet_mode_client->tablet_mode_enabled()); + session_manager_observer_.Add(session_manager::SessionManager::Get()); if (lock_screen_apps::StateController::IsEnabled()) lock_screen_apps_observer_.Add(lock_screen_apps::StateController::Get()); // TODO(wzang): Make this work under mash. if (GetAshConfig() != ash::Config::MASH) ash::Shell::Get()->wallpaper_controller()->AddObserver(this); + // TODO(tbarzic): This is needed for login UI - remove it when login switches + // to views implementation (or otherwise, make it work under mash). + if (GetAshConfig() != ash::Config::MASH) + detachable_base_observer_.Add(ash::Shell::Get()->detachable_base_handler()); } SigninScreenHandler::~SigninScreenHandler() { @@ -532,8 +559,10 @@ void SigninScreenHandler::RegisterMessages() { &SigninScreenHandler::HandleFirstIncorrectPasswordAttempt); AddCallback("maxIncorrectPasswordAttempts", &SigninScreenHandler::HandleMaxIncorrectPasswordAttempts); + AddCallback("sendFeedback", &SigninScreenHandler::HandleSendFeedback); AddCallback("sendFeedbackAndResyncUserData", &SigninScreenHandler::HandleSendFeedbackAndResyncUserData); + AddCallback("setupDemoMode", &SigninScreenHandler::HandleSetupDemoMode); // This message is sent by the kiosk app menu, but is handled here // so we can tell the delegate to launch the app. @@ -1130,6 +1159,34 @@ void SigninScreenHandler::OnTabletModeToggled(bool enabled) { CallJSOrDefer("login.AccountPickerScreen.setTabletModeState", enabled); } +void SigninScreenHandler::OnSessionStateChanged() { + // If the session got unblocked, and the user for which the detachable base + // change notification was shown got added to the session, mark the paired + // base as used by the user, so they don't get further notifications about + // the detachable base change. + // The fact the user got added to the session implies that they have + // authenticated while the warning was displayed, so they should be aware + // of the base change at this point. + if (!account_with_detachable_base_error_.has_value()) + return; + + if (session_manager::SessionManager::Get()->IsUserSessionBlocked()) + return; + + const AccountId& account_id = *account_with_detachable_base_error_; + if (session_manager::SessionManager::Get()->HasSessionForAccountId( + account_id)) { + ash::mojom::UserInfoPtr user_info = GetUserInfoForAccount(account_id); + if (user_info) { + ash::Shell::Get() + ->detachable_base_handler() + ->SetPairedBaseAsLastUsedByUser(*user_info); + } + } + + HideDetachableBaseChangedError(); +} + void SigninScreenHandler::OnLockScreenNoteStateChanged( ash::mojom::TrayActionState state) { if (!ScreenLocker::default_screen_locker()) @@ -1285,6 +1342,11 @@ void SigninScreenHandler::HandleToggleEnableDebuggingScreen() { delegate_->ShowEnableDebuggingScreen(); } +void SigninScreenHandler::HandleSetupDemoMode() { + if (delegate_) + delegate_->ShowDemoModeSetupScreen(); +} + void SigninScreenHandler::HandleToggleKioskEnableScreen() { policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); @@ -1434,6 +1496,12 @@ void SigninScreenHandler::HandleLoginUIStateChanged(const std::string& source, ui_state_ = UI_STATE_GAIA_SIGNIN; } else if (source == kSourceAccountPicker) { ui_state_ = UI_STATE_ACCOUNT_PICKER; + + if (active) { + UpdateDetachableBaseChangedError(); + } else { + HideDetachableBaseChangedError(); + } } else { NOTREACHED(); return; @@ -1451,7 +1519,7 @@ void SigninScreenHandler::HandleShowLoadingTimeoutError() { } void SigninScreenHandler::HandleFocusPod(const AccountId& account_id, - bool load_wallpaper) { + bool is_large_pod) { proximity_auth::ScreenlockBridge::Get()->SetFocusedUser(account_id); if (delegate_) delegate_->CheckUserStatus(account_id); @@ -1469,7 +1537,7 @@ void SigninScreenHandler::HandleFocusPod(const AccountId& account_id, lock_screen_utils::SetUserInputMethod(account_id.GetUserEmail(), ime_state_.get()); lock_screen_utils::SetKeyboardSettings(account_id); - if (LoginDisplayHost::default_host() && load_wallpaper) + if (LoginDisplayHost::default_host() && is_large_pod) LoginDisplayHost::default_host()->LoadWallpaper(account_id); bool use_24hour_clock = false; @@ -1480,6 +1548,12 @@ void SigninScreenHandler::HandleFocusPod(const AccountId& account_id, ->SetLastFocusedPodHourClockType( use_24hour_clock ? base::k24HourClock : base::k12HourClock); } + + // Update the detachable base change warning visibility when the focused + // user pod changes. Note that this should only be done for large pods - the + // pods whose authentication method is shown in the sign-in UI. + if (is_large_pod) + UpdateDetachableBaseChangedError(); } } @@ -1545,16 +1619,27 @@ void SigninScreenHandler::HandleMaxIncorrectPasswordAttempts( RecordReauthReason(account_id, ReauthReason::INCORRECT_PASSWORD_ENTERED); } +void SigninScreenHandler::HandleSendFeedback() { + login_feedback_ = + std::make_unique<LoginFeedback>(Profile::FromWebUI(web_ui())); + login_feedback_->Request( + std::string(), base::BindOnce(&SigninScreenHandler::OnFeedbackFinished, + weak_factory_.GetWeakPtr())); +} + void SigninScreenHandler::HandleSendFeedbackAndResyncUserData() { const std::string description = base::StringPrintf( "Auto generated feedback for http://crbug.com/547857.\n" "(uniquifier:%s)", base::Int64ToString(base::Time::Now().ToInternalValue()).c_str()); - login_feedback_.reset(new LoginFeedback(Profile::FromWebUI(web_ui()))); - login_feedback_->Request(description, - base::Bind(&SigninScreenHandler::OnFeedbackFinished, - weak_factory_.GetWeakPtr())); + login_feedback_ = + std::make_unique<LoginFeedback>(Profile::FromWebUI(web_ui())); + login_feedback_->Request( + description, + base::BindOnce( + &SigninScreenHandler::OnUnrecoverableCryptohomeFeedbackFinished, + weak_factory_.GetWeakPtr())); } void SigninScreenHandler::HandleRequestNewNoteAction( @@ -1653,10 +1738,16 @@ void SigninScreenHandler::OnCapsLockChanged(bool enabled) { } void SigninScreenHandler::OnFeedbackFinished() { + login_feedback_.reset(); +} + +void SigninScreenHandler::OnUnrecoverableCryptohomeFeedbackFinished() { CallJS("login.UnrecoverableCryptohomeErrorScreen.resumeAfterFeedbackUI"); // Recreate user's cryptohome after the feedback is attempted. HandleResyncUserData(); + + login_feedback_.reset(); } void SigninScreenHandler::OnAllowedInputMethodsChanged() { @@ -1672,4 +1763,77 @@ void SigninScreenHandler::OnAllowedInputMethodsChanged() { } } +void SigninScreenHandler::OnDetachableBasePairingStatusChanged( + ash::DetachableBasePairingStatus status) { + UpdateDetachableBaseChangedError(); +} +void SigninScreenHandler::OnDetachableBaseRequiresUpdateChanged( + bool requires_update) {} + +void SigninScreenHandler::UpdateDetachableBaseChangedError() { + if (GetAshConfig() == ash::Config::MASH) + return; + + auto pairing_status = + ash::Shell::Get()->detachable_base_handler()->GetPairingStatus(); + if (pairing_status == ash::DetachableBasePairingStatus::kNone) { + HideDetachableBaseChangedError(); + return; + } + + // Requests to update the notification state will be postponed until a pod + // gets focused. Reasons for that are: + // * The warning bubble is anchored at a user pod authentication element, + // which is only shown when the pod is focused. + // * If two large pods are shown, it's unclear which one should be + // considered active if neither is focused. + // Send a request to the login UI to select/focus a use pod so the warning can + // be shown sooner, rather than later - the user might start typing without + // focusing a pod first, in which case showing the warning as the pod gets + // focused might be too late to warn the user their keyboard might not be + // trusted. + if (!focused_pod_account_id_) { + CallJSOrDefer( + "login.AccountPickerScreen.selectPodForDetachableBaseWarningBubble"); + return; + } + + bool base_trusted = + pairing_status == ash::DetachableBasePairingStatus::kAuthenticated; + if (base_trusted) { + ash::mojom::UserInfoPtr user_info = + GetUserInfoForAccount(*focused_pod_account_id_); + if (user_info) { + base_trusted = ash::Shell::Get() + ->detachable_base_handler() + ->PairedBaseMatchesLastUsedByUser(*user_info); + } + } + + if (base_trusted) { + HideDetachableBaseChangedError(); + } else { + ShowDetachableBaseChangedError(); + } +} + +void SigninScreenHandler::ShowDetachableBaseChangedError() { + account_with_detachable_base_error_ = *focused_pod_account_id_; + + CallJSOrDefer( + "cr.ui.login.DisplayManager.showDetachableBaseChangedWarning", + *focused_pod_account_id_, + l10n_util::GetStringUTF8(IDS_LOGIN_ERROR_DETACHABLE_BASE_CHANGED), + std::string(), 0); +} + +void SigninScreenHandler::HideDetachableBaseChangedError() { + if (!account_with_detachable_base_error_.has_value()) + return; + + CallJSOrDefer("cr.ui.login.DisplayManager.hideDetachableBaseChangedWarning", + *account_with_detachable_base_error_); + account_with_detachable_base_error_ = base::nullopt; +} + } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h index b2a51bc7ad8..75f54a36680 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h @@ -10,6 +10,7 @@ #include <set> #include <string> +#include "ash/detachable_base/detachable_base_observer.h" #include "ash/wallpaper/wallpaper_controller_observer.h" #include "base/callback.h" #include "base/compiler_specific.h" @@ -17,6 +18,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" +#include "base/optional.h" #include "base/scoped_observer.h" #include "chrome/browser/chromeos/lock_screen_apps/state_observer.h" #include "chrome/browser/chromeos/login/screens/error_screen.h" @@ -27,9 +29,10 @@ #include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" #include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" +#include "chromeos/components/proximity_auth/screenlock_bridge.h" #include "chromeos/dbus/power_manager_client.h" #include "chromeos/network/portal_detector/network_portal_detector.h" -#include "components/proximity_auth/screenlock_bridge.h" +#include "components/session_manager/core/session_manager_observer.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" @@ -44,8 +47,10 @@ class AccountId; namespace ash { namespace mojom { enum class TrayActionState; -} -} +} // namespace mojom + +class DetachableBaseHandler; +} // namespace ash namespace base { class DictionaryValue; @@ -56,6 +61,10 @@ namespace lock_screen_apps { class StateController; } +namespace session_manager { +class SessionManager; +} + namespace chromeos { class CoreOobeView; @@ -153,6 +162,9 @@ class SigninScreenHandlerDelegate { // Shows Enable Developer Features screen. virtual void ShowEnableDebuggingScreen() = 0; + // Shows Demo Mode Setup screen. + virtual void ShowDemoModeSetupScreen() = 0; + // Shows Kiosk Enable screen. virtual void ShowKioskEnableScreen() = 0; @@ -216,7 +228,9 @@ class SigninScreenHandler public TabletModeClientObserver, public lock_screen_apps::StateObserver, public OobeUI::Observer, - public ash::WallpaperControllerObserver { + public session_manager::SessionManagerObserver, + public ash::WallpaperControllerObserver, + public ash::DetachableBaseObserver { public: SigninScreenHandler( const scoped_refptr<NetworkStateInformer>& network_state_informer, @@ -260,6 +274,11 @@ class SigninScreenHandler void OnWallpaperColorsChanged() override; void OnWallpaperBlurChanged() override; + // ash::DetachableBaseObserver: + void OnDetachableBasePairingStatusChanged( + ash::DetachableBasePairingStatus pairing_status) override; + void OnDetachableBaseRequiresUpdateChanged(bool requires_update) override; + void SetFocusPODCallbackForTesting(base::Closure callback); // To avoid spurious error messages on flaky networks, the offline message is @@ -346,6 +365,9 @@ class SigninScreenHandler // TabletModeClientObserver: void OnTabletModeToggled(bool enabled) override; + // session_manager::SessionManagerObserver: + void OnSessionStateChanged() override; + // lock_screen_apps::StateObserver: void OnLockScreenNoteStateChanged(ash::mojom::TrayActionState state) override; @@ -374,6 +396,7 @@ class SigninScreenHandler void HandleToggleEnrollmentScreen(); void HandleToggleEnrollmentAd(); void HandleToggleEnableDebuggingScreen(); + void HandleSetupDemoMode(); void HandleToggleKioskEnableScreen(); void HandleToggleResetScreen(); void HandleToggleKioskAutolaunchScreen(); @@ -391,7 +414,7 @@ class SigninScreenHandler void HandleLoginScreenUpdate(); void HandleShowLoadingTimeoutError(); void HandleShowSupervisedUserCreationScreen(); - void HandleFocusPod(const AccountId& account_id, bool load_wallpaper); + void HandleFocusPod(const AccountId& account_id, bool is_large_pod); void HandleNoPodFocused(); void HandleHardlockPod(const std::string& user_id); void HandleLaunchKioskApp(const AccountId& app_account_id, @@ -403,6 +426,7 @@ class SigninScreenHandler void HandleLogRemoveUserWarningShown(); void HandleFirstIncorrectPasswordAttempt(const AccountId& account_id); void HandleMaxIncorrectPasswordAttempts(const AccountId& account_id); + void HandleSendFeedback(); void HandleSendFeedbackAndResyncUserData(); void HandleRequestNewNoteAction(const std::string& request_type); void HandleNewNoteLaunchAnimationDone(); @@ -449,6 +473,10 @@ class SigninScreenHandler // Callback invoked after the feedback is finished. void OnFeedbackFinished(); + // Callback invoked after the feedback sent from the unrecoverable cryptohome + // page is finished. + void OnUnrecoverableCryptohomeFeedbackFinished(); + // Called when the cros property controlling allowed input methods changes. void OnAllowedInputMethodsChanged(); @@ -456,6 +484,23 @@ class SigninScreenHandler // responding to network state notifications. void ReenableNetworkStateUpdatesAfterProxyAuth(); + // Determines whether a warning about the detachable base getting changed + // should be shown to the user. The warning is shown a detachable base is + // present, and the user whose pod is currently focused has used a different + // base last time. It updates the detachable base warning visibility as + // required. + void UpdateDetachableBaseChangedError(); + + // Sends a request to the UI to show a detachable base change warning for the + // currently focused user pod. The warning warns the user that the currently + // attached base is different than the one they last used, and that it might + // not be trusted. + void ShowDetachableBaseChangedError(); + + // If a detachable base change warning was requested to be shown, sends a + // request to UI to hide the warning. + void HideDetachableBaseChangedError(); + // Current UI state of the signin screen. UIState ui_state_ = UI_STATE_UNKNOWN; @@ -538,10 +583,20 @@ class SigninScreenHandler std::unique_ptr<AccountId> focused_pod_account_id_; + // If set, the account for which detachable base change warning was shown in + // the login UI. + base::Optional<AccountId> account_with_detachable_base_error_; + + ScopedObserver<session_manager::SessionManager, + session_manager::SessionManagerObserver> + session_manager_observer_; ScopedObserver<lock_screen_apps::StateController, lock_screen_apps::StateObserver> lock_screen_apps_observer_; + ScopedObserver<ash::DetachableBaseHandler, ash::DetachableBaseObserver> + detachable_base_observer_; + base::WeakPtrFactory<SigninScreenHandler> weak_factory_; DISALLOW_COPY_AND_ASSIGN(SigninScreenHandler); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc index 54e29d5cec6..da4ff412063 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc @@ -14,11 +14,9 @@ #include "chrome/browser/chromeos/login/users/multi_profile_user_controller_delegate.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" -#include "chrome/browser/ui/ash/test_wallpaper_controller.h" -#include "chrome/browser/ui/ash/wallpaper_controller_client.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile_manager.h" -#include "components/proximity_auth/screenlock_bridge.h" +#include "chromeos/components/proximity_auth/screenlock_bridge.h" #include "components/signin/core/account_id/account_id.h" #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user.h" @@ -69,16 +67,11 @@ class SigninPrepareUserListTest : public ash::AshTestBase, chromeos::DeviceSettingsService::Initialize(); chromeos::CrosSettings::Initialize(); - wallpaper_controller_client_ = - std::make_unique<WallpaperControllerClient>(); - wallpaper_controller_client_->InitForTesting( - test_wallpaper_controller_.CreateInterfacePtr()); } void TearDown() override { controller_.reset(); profile_manager_.reset(); - wallpaper_controller_client_.reset(); ash::AshTestBase::TearDown(); } @@ -90,8 +83,6 @@ class SigninPrepareUserListTest : public ash::AshTestBase, std::unique_ptr<TestingProfileManager> profile_manager_; std::map<std::string, proximity_auth::mojom::AuthType> user_auth_type_map; std::unique_ptr<MultiProfileUserController> controller_; - std::unique_ptr<WallpaperControllerClient> wallpaper_controller_client_; - TestWallpaperController test_wallpaper_controller_; DISALLOW_COPY_AND_ASSIGN(SigninPrepareUserListTest); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc index b21048cc482..4add2987606 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc @@ -65,8 +65,9 @@ void UserBoardScreenHandler::SetPublicSessionLocales( *locales, default_locale, multiple_recommended_locales); } -void UserBoardScreenHandler::ShowBannerMessage(const base::string16& message) { - CallJS("login.AccountPickerScreen.showBannerMessage", message); +void UserBoardScreenHandler::ShowBannerMessage(const base::string16& message, + bool is_warning) { + CallJS("login.AccountPickerScreen.showBannerMessage", message, is_warning); } void UserBoardScreenHandler::ShowUserPodCustomIcon( diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h index af2a912947a..0d3ee1cf816 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h @@ -45,7 +45,8 @@ class UserBoardScreenHandler : public BaseScreenHandler, public UserBoardView { std::unique_ptr<base::ListValue> locales, const std::string& default_locale, bool multiple_recommended_locales) override; - void ShowBannerMessage(const base::string16& message) override; + void ShowBannerMessage(const base::string16& message, + bool is_warning) override; void ShowUserPodCustomIcon( const AccountId& account_id, const proximity_auth::ScreenlockBridge::UserPodCustomIconOptions& diff --git a/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.cc index 69d436464fd..8c0b5f028fc 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.cc @@ -426,18 +426,22 @@ void MobileSetupHandler::GetPropertiesAndCallStatusChanged( } void MobileSetupHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback(kJsApiStartActivation, - base::Bind(&MobileSetupHandler::HandleStartActivation, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kJsApiSetTransactionStatus, - base::Bind(&MobileSetupHandler::HandleSetTransactionStatus, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kJsApiPaymentPortalLoad, - base::Bind(&MobileSetupHandler::HandlePaymentPortalLoad, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kJsGetDeviceInfo, - base::Bind(&MobileSetupHandler::HandleGetDeviceInfo, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiStartActivation, + base::BindRepeating(&MobileSetupHandler::HandleStartActivation, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiSetTransactionStatus, + base::BindRepeating(&MobileSetupHandler::HandleSetTransactionStatus, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiPaymentPortalLoad, + base::BindRepeating(&MobileSetupHandler::HandlePaymentPortalLoad, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsGetDeviceInfo, + base::BindRepeating(&MobileSetupHandler::HandleGetDeviceInfo, + base::Unretained(this))); } void MobileSetupHandler::HandleStartActivation(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/OWNERS b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/OWNERS new file mode 100644 index 00000000000..aef4ecb9195 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/OWNERS @@ -0,0 +1 @@ +file://chromeos/services/multidevice_setup/OWNERS diff --git a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.cc new file mode 100644 index 00000000000..bf9bf597fcc --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.cc @@ -0,0 +1,101 @@ +// 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/webui/chromeos/multidevice_setup/multidevice_setup_dialog.h" + +#include "chrome/browser/profiles/profile.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/generated_resources.h" +#include "chrome/grit/multidevice_setup_resources.h" +#include "chrome/grit/multidevice_setup_resources_map.h" +#include "components/strings/grit/components_strings.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" +#include "ui/base/l10n/l10n_util.h" + +namespace chromeos { + +namespace multidevice_setup { + +namespace { + +constexpr int kDialogHeightPx = 640; +constexpr int kDialogWidthPx = 768; + +void AddMultiDeviceSetupStrings(content::WebUIDataSource* html_source) { + // TODO(jordynass): Add translations for other strings appearing in the + // dialog by adding new name/translation pairs to |kLocalizedStrings| below. + // String definitions belong in //chrome/app/chromeos_strings.grdp. + static constexpr struct { + const char* name; + int id; + } kLocalizedStrings[] = { + {"title", IDS_MULTIDEVICE_SETUP_DIALOG_TITLE}, {"cancel", IDS_CANCEL}, + }; + + for (const auto& entry : kLocalizedStrings) + html_source->AddLocalizedString(entry.name, entry.id); +} + +} // namespace + +// static +MultiDeviceSetupDialog* MultiDeviceSetupDialog::current_instance_ = nullptr; + +// static +void MultiDeviceSetupDialog::Show() { + // The dialog is already showing, so there is nothing to do. + if (current_instance_) + return; + + current_instance_ = new MultiDeviceSetupDialog(); + current_instance_->ShowSystemDialog(); +} + +MultiDeviceSetupDialog::MultiDeviceSetupDialog() + : SystemWebDialogDelegate( + GURL(chrome::kChromeUIMultiDeviceSetupUrl), + l10n_util::GetStringUTF16(IDS_MULTIDEVICE_SETUP_DIALOG_TITLE)) {} + +MultiDeviceSetupDialog::~MultiDeviceSetupDialog() = default; + +void MultiDeviceSetupDialog::GetDialogSize(gfx::Size* size) const { + size->SetSize(kDialogWidthPx, kDialogHeightPx); +} + +void MultiDeviceSetupDialog::OnDialogClosed(const std::string& json_retval) { + DCHECK(this == current_instance_); + current_instance_ = nullptr; + + // Note: The call below deletes |this|, so there is no further need to keep + // track of the pointer. + SystemWebDialogDelegate::OnDialogClosed(json_retval); +} + +MultiDeviceSetupDialogUI::MultiDeviceSetupDialogUI(content::WebUI* web_ui) + : ui::WebDialogUI(web_ui) { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(chrome::kChromeUIMultiDeviceSetupHost); + + AddMultiDeviceSetupStrings(source); + source->SetJsonPath("strings.js"); + source->SetDefaultResource( + IDR_MULTIDEVICE_SETUP_MULTIDEVICE_SETUP_DIALOG_HTML); + + // Note: The |kMultiDeviceSetupResourcesSize| and |kMultideviceSetupResources| + // fields are defined in the generated file + // chrome/grit/multidevice_setup_resources_map.h. + for (size_t i = 0; i < kMultideviceSetupResourcesSize; ++i) { + source->AddResourcePath(kMultideviceSetupResources[i].name, + kMultideviceSetupResources[i].value); + } + + content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); +} + +MultiDeviceSetupDialogUI::~MultiDeviceSetupDialogUI() = default; + +} // namespace multidevice_setup + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.h new file mode 100644 index 00000000000..66433f09942 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.h @@ -0,0 +1,54 @@ +// 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_WEBUI_CHROMEOS_MULTIDEVICE_SETUP_MULTIDEVICE_SETUP_DIALOG_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_MULTIDEVICE_SETUP_MULTIDEVICE_SETUP_DIALOG_H_ + +#include <string> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" +#include "ui/web_dialogs/web_dialog_ui.h" + +namespace chromeos { + +namespace multidevice_setup { + +// Dialog which displays the multi-device setup flow which allows users to +// enable features involving communication between multiple devices (e.g., a +// Chromebook and a phone). +class MultiDeviceSetupDialog : public SystemWebDialogDelegate { + public: + // Shows the dialog; if the dialog is already displayed, this function is a + // no-op. + static void Show(); + + protected: + MultiDeviceSetupDialog(); + ~MultiDeviceSetupDialog() override; + + // ui::WebDialogDelegate + void GetDialogSize(gfx::Size* size) const override; + void OnDialogClosed(const std::string& json_retval) override; + + private: + static MultiDeviceSetupDialog* current_instance_; + + DISALLOW_COPY_AND_ASSIGN(MultiDeviceSetupDialog); +}; + +class MultiDeviceSetupDialogUI : public ui::WebDialogUI { + public: + explicit MultiDeviceSetupDialogUI(content::WebUI* web_ui); + ~MultiDeviceSetupDialogUI() override; + + private: + DISALLOW_COPY_AND_ASSIGN(MultiDeviceSetupDialogUI); +}; + +} // namespace multidevice_setup + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_MULTIDEVICE_SETUP_MULTIDEVICE_SETUP_DIALOG_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc index fc02a996fb7..8c92d8bbbde 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc @@ -134,8 +134,11 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { {"OncVPN-Host", IDS_ONC_VPN_HOST}, {"OncVPN-IPsec-Group", IDS_ONC_VPN_IPSEC_GROUP}, {"OncVPN-IPsec-PSK", IDS_ONC_VPN_IPSEC_PSK}, + {"OncVPN-L2TP-Password", IDS_ONC_VPN_PASSWORD}, + {"OncVPN-L2TP-Username", IDS_ONC_VPN_USERNAME}, {"OncVPN-OpenVPN-OTP", IDS_ONC_VPN_OPENVPN_OTP}, - {"OncVPN-Password", IDS_ONC_VPN_PASSWORD}, + {"OncVPN-OpenVPN-Password", IDS_ONC_VPN_PASSWORD}, + {"OncVPN-OpenVPN-Username", IDS_ONC_VPN_USERNAME}, {"OncVPN-ThirdPartyVPN-ProviderName", IDS_ONC_VPN_THIRD_PARTY_VPN_PROVIDER_NAME}, {"OncVPN-Type", IDS_ONC_VPN_TYPE}, @@ -144,7 +147,6 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { {"OncVPN-Type_L2TP_IPsec_Cert", IDS_ONC_VPN_TYPE_L2TP_IPSEC_CERT}, {"OncVPN-Type_OpenVPN", IDS_ONC_VPN_TYPE_OPENVPN}, {"OncVPN-Type_ARCVPN", IDS_ONC_VPN_TYPE_ARCVPN}, - {"OncVPN-Username", IDS_ONC_VPN_USERNAME}, {"OncWiFi-Frequency", IDS_ONC_WIFI_FREQUENCY}, {"OncWiFi-Passphrase", IDS_ONC_WIFI_PASSWORD}, {"OncWiFi-SSID", IDS_ONC_WIFI_SSID}, @@ -247,6 +249,7 @@ void AddDetailsLocalizedStrings(content::WebUIDataSource* html_source) { {"networkNameserversGoogle", IDS_SETTINGS_INTERNET_NETWORK_NAMESERVERS_GOOGLE}, {"networkProxyWpad", IDS_SETTINGS_INTERNET_NETWORK_PROXY_WPAD}, + {"networkProxyWpadNone", IDS_SETTINGS_INTERNET_NETWORK_PROXY_WPAD_NONE}, }; for (const auto& entry : localized_strings) html_source->AddLocalizedString(entry.name, entry.id); diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc index c41a3dbb84a..26d8445e314 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc @@ -84,15 +84,18 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler { void RegisterMessages() override { web_ui()->RegisterMessageCallback( kGetNetworkProperties, - base::Bind(&NetworkConfigMessageHandler::GetShillNetworkProperties, - base::Unretained(this))); + base::BindRepeating( + &NetworkConfigMessageHandler::GetShillNetworkProperties, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kGetDeviceProperties, - base::Bind(&NetworkConfigMessageHandler::GetShillDeviceProperties, - base::Unretained(this))); + base::BindRepeating( + &NetworkConfigMessageHandler::GetShillDeviceProperties, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "addNetwork", base::Bind(&NetworkConfigMessageHandler::AddNetwork, - base::Unretained(this))); + "addNetwork", + base::BindRepeating(&NetworkConfigMessageHandler::AddNetwork, + base::Unretained(this))); } private: diff --git a/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc index 6300c2895e5..21d6578d905 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc @@ -71,16 +71,16 @@ PowerMessageHandler::~PowerMessageHandler() { void PowerMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( kRequestBatteryChargeDataCallback, - base::Bind(&PowerMessageHandler::OnGetBatteryChargeData, - base::Unretained(this))); + base::BindRepeating(&PowerMessageHandler::OnGetBatteryChargeData, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kRequestCpuIdleDataCallback, - base::Bind(&PowerMessageHandler::OnGetCpuIdleData, - base::Unretained(this))); + base::BindRepeating(&PowerMessageHandler::OnGetCpuIdleData, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kRequestCpuFreqDataCallback, - base::Bind(&PowerMessageHandler::OnGetCpuFreqData, - base::Unretained(this))); + base::BindRepeating(&PowerMessageHandler::OnGetCpuFreqData, + base::Unretained(this))); } void PowerMessageHandler::OnGetBatteryChargeData(const base::ListValue* value) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc index d231988b6d6..95008b5f536 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc @@ -52,11 +52,12 @@ class SetTimeMessageHandler : public content::WebUIMessageHandler, void RegisterMessages() override { web_ui()->RegisterMessageCallback( "setTimeInSeconds", - base::Bind(&SetTimeMessageHandler::OnSetTime, base::Unretained(this))); + base::BindRepeating(&SetTimeMessageHandler::OnSetTime, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setTimezone", - base::Bind(&SetTimeMessageHandler::OnSetTimezone, - base::Unretained(this))); + base::BindRepeating(&SetTimeMessageHandler::OnSetTimezone, + base::Unretained(this))); } private: diff --git a/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc index f8696f971e2..2e5b4c353f2 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc @@ -87,12 +87,15 @@ SlowHandler::~SlowHandler() { } void SlowHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback(kJsApiDisableTracing, - base::Bind(&SlowHandler::HandleDisable, base::Unretained(this))); - web_ui()->RegisterMessageCallback(kJsApiEnableTracing, - base::Bind(&SlowHandler::HandleEnable, base::Unretained(this))); - web_ui()->RegisterMessageCallback(kJsApiLoadComplete, - base::Bind(&SlowHandler::LoadComplete, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiDisableTracing, + base::BindRepeating(&SlowHandler::HandleDisable, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiEnableTracing, + base::BindRepeating(&SlowHandler::HandleEnable, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiLoadComplete, + base::BindRepeating(&SlowHandler::LoadComplete, base::Unretained(this))); user_pref_registrar_.reset(new PrefChangeRegistrar); user_pref_registrar_->Init(profile_->GetPrefs()); diff --git a/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc index ad01a66dee4..eef91e13fa7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc @@ -205,8 +205,9 @@ SysInternalsMessageHandler::~SysInternalsMessageHandler() {} void SysInternalsMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "getSysInfo", base::Bind(&SysInternalsMessageHandler::HandleGetSysInfo, - base::Unretained(this))); + "getSysInfo", + base::BindRepeating(&SysInternalsMessageHandler::HandleGetSysInfo, + base::Unretained(this))); } void SysInternalsMessageHandler::HandleGetSysInfo(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc index c61dedb5e7d..6868a46961e 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc @@ -42,6 +42,10 @@ void SystemWebDialogDelegate::GetDialogSize(gfx::Size* size) const { size->SetSize(kDialogWidth, kDialogHeight); } +std::string SystemWebDialogDelegate::GetDialogArgs() const { + return std::string(); +} + void SystemWebDialogDelegate::OnDialogShown( content::WebUI* webui, content::RenderViewHost* render_view_host) { @@ -61,7 +65,7 @@ bool SystemWebDialogDelegate::ShouldShowDialogTitle() const { return !title_.empty(); } -void SystemWebDialogDelegate::ShowSystemDialog() { +void SystemWebDialogDelegate::ShowSystemDialog(bool is_minimal_style) { // NetworkConfigView does not interact well with web dialogs. For now, do // not show the dialog while NetworkConfigView is shown: crbug.com/791955. // TODO(stevenjb): Remove this when NetworkConfigView is deprecated. @@ -74,7 +78,8 @@ void SystemWebDialogDelegate::ShowSystemDialog() { int container_id = GetDialogModalType() == ui::MODAL_TYPE_NONE ? ash::kShellWindowId_AlwaysOnTopContainer : ash::kShellWindowId_LockSystemModalContainer; - chrome::ShowWebDialogInContainer(container_id, browser_context, this); + chrome::ShowWebDialogInContainer(container_id, browser_context, this, + is_minimal_style); } } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h index c91592c484c..6c248bb8cce 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h +++ b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h @@ -31,6 +31,7 @@ class SystemWebDialogDelegate : public ui::WebDialogDelegate { void GetWebUIMessageHandlers( std::vector<content::WebUIMessageHandler*>* handlers) const override; void GetDialogSize(gfx::Size* size) const override; + std::string GetDialogArgs() const override; void OnDialogShown(content::WebUI* webui, content::RenderViewHost* render_view_host) override; // Note: deletes |this|. @@ -41,7 +42,8 @@ class SystemWebDialogDelegate : public ui::WebDialogDelegate { // Show the dialog using the current ative profile and the proper ash // shell container. - void ShowSystemDialog(); + // |is_minimal_style| means whether title area of the dialog should be hide. + void ShowSystemDialog(bool is_minimal_style = false); content::WebUI* GetWebUIForTest() { return webui_; } diff --git a/chromium/chrome/browser/ui/webui/components_ui.cc b/chromium/chrome/browser/ui/webui/components_ui.cc index f58e2500837..8a5db7e83b4 100644 --- a/chromium/chrome/browser/ui/webui/components_ui.cc +++ b/chromium/chrome/browser/ui/webui/components_ui.cc @@ -99,13 +99,13 @@ ComponentsDOMHandler::ComponentsDOMHandler() { void ComponentsDOMHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "requestComponentsData", - base::Bind(&ComponentsDOMHandler::HandleRequestComponentsData, - base::Unretained(this))); + base::BindRepeating(&ComponentsDOMHandler::HandleRequestComponentsData, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "checkUpdate", - base::Bind(&ComponentsDOMHandler::HandleCheckUpdate, - base::Unretained(this))); + base::BindRepeating(&ComponentsDOMHandler::HandleCheckUpdate, + base::Unretained(this))); } void ComponentsDOMHandler::HandleRequestComponentsData( diff --git a/chromium/chrome/browser/ui/webui/conflicts_handler.cc b/chromium/chrome/browser/ui/webui/conflicts_handler.cc index abfae65137b..ee1e739dae9 100644 --- a/chromium/chrome/browser/ui/webui/conflicts_handler.cc +++ b/chromium/chrome/browser/ui/webui/conflicts_handler.cc @@ -22,8 +22,8 @@ ConflictsHandler::~ConflictsHandler() = default; void ConflictsHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "requestModuleList", - base::Bind(&ConflictsHandler::HandleRequestModuleList, - base::Unretained(this))); + base::BindRepeating(&ConflictsHandler::HandleRequestModuleList, + base::Unretained(this))); } void ConflictsHandler::OnScanCompleted() { diff --git a/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui.cc b/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui.cc index 0e061e83bf9..12f77178ea9 100644 --- a/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui.cc +++ b/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui.cc @@ -19,7 +19,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_message_handler.h" -#include "extensions/features/features.h" +#include "extensions/buildflags/buildflags.h" #include "ui/web_dialogs/web_dialog_delegate.h" #include "ui/web_dialogs/web_dialog_ui.h" @@ -67,9 +67,10 @@ ConstrainedWebDialogUI::~ConstrainedWebDialogUI() { void ConstrainedWebDialogUI::RenderFrameCreated( RenderFrameHost* render_frame_host) { // Add a "dialogClose" callback which matches WebDialogUI behavior. - web_ui()->RegisterMessageCallback("dialogClose", - base::Bind(&ConstrainedWebDialogUI::OnDialogCloseMessage, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "dialogClose", + base::BindRepeating(&ConstrainedWebDialogUI::OnDialogCloseMessage, + base::Unretained(this))); ConstrainedWebDialogDelegate* delegate = GetConstrainedDelegate(); if (!delegate) diff --git a/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc index 359260339ff..196111d5a60 100644 --- a/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc @@ -10,6 +10,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" +#include "build/buildflag.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -22,6 +23,7 @@ #include "content/public/browser/web_contents_observer.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" +#include "ui/base/ui_features.h" #include "ui/web_dialogs/test/test_web_dialog_delegate.h" using content::WebContents; @@ -194,12 +196,11 @@ IN_PROC_BROWSER_TEST_F(ConstrainedWebDialogBrowserTest, gfx::Size max_size = gfx::Size(200, 200); gfx::Size initial_dialog_size; - // OSX windows must be initially created with non-empty dimensions. The - // autoresizeable dialog's window dimensions are determined after initial - // creation. -#if defined(OS_MACOSX) +// When using Cocoa windows, the initial dimensions must be nonzero. +#if defined(OS_MACOSX) && !BUILDFLAG(MAC_VIEWS_BROWSER) initial_dialog_size = gfx::Size(1, 1); #endif + delegate->GetDialogSize(&initial_dialog_size); ConstrainedWebDialogDelegate* dialog_delegate = diff --git a/chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc b/chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc index f5ff4c37597..5dc7e8a55e9 100644 --- a/chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc +++ b/chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc @@ -20,7 +20,7 @@ #include "content/public/browser/cache_storage_context.h" #include "content/public/browser/indexed_db_context.h" #include "content/public/browser/service_worker_context.h" -#include "extensions/features/features.h" +#include "extensions/buildflags/buildflags.h" #include "net/cookies/canonical_cookie.h" #include "storage/common/fileapi/file_system_types.h" #include "ui/base/l10n/l10n_util.h" diff --git a/chromium/chrome/browser/ui/webui/crashes_ui.cc b/chromium/chrome/browser/ui/webui/crashes_ui.cc index d8444cb7987..296a09f0863 100644 --- a/chromium/chrome/browser/ui/webui/crashes_ui.cc +++ b/chromium/chrome/browser/ui/webui/crashes_ui.cc @@ -114,20 +114,20 @@ void CrashesDOMHandler::RegisterMessages() { base::Unretained(this))); web_ui()->RegisterMessageCallback( crash::kCrashesUIRequestCrashList, - base::Bind(&CrashesDOMHandler::HandleRequestCrashes, - base::Unretained(this))); + base::BindRepeating(&CrashesDOMHandler::HandleRequestCrashes, + base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( crash::kCrashesUIRequestCrashUpload, - base::Bind(&CrashesDOMHandler::HandleRequestUploads, - base::Unretained(this))); + base::BindRepeating(&CrashesDOMHandler::HandleRequestUploads, + base::Unretained(this))); #endif web_ui()->RegisterMessageCallback( crash::kCrashesUIRequestSingleCrashUpload, - base::Bind(&CrashesDOMHandler::HandleRequestSingleCrashUpload, - base::Unretained(this))); + base::BindRepeating(&CrashesDOMHandler::HandleRequestSingleCrashUpload, + base::Unretained(this))); } void CrashesDOMHandler::HandleRequestCrashes(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/device_log_ui.cc b/chromium/chrome/browser/ui/webui/device_log_ui.cc index 6f55ce9220a..22d484de53a 100644 --- a/chromium/chrome/browser/ui/webui/device_log_ui.cc +++ b/chromium/chrome/browser/ui/webui/device_log_ui.cc @@ -33,7 +33,8 @@ class DeviceLogMessageHandler : public content::WebUIMessageHandler { void RegisterMessages() override { web_ui()->RegisterMessageCallback( "DeviceLog.getLog", - base::Bind(&DeviceLogMessageHandler::GetLog, base::Unretained(this))); + base::BindRepeating(&DeviceLogMessageHandler::GetLog, + base::Unretained(this))); } private: diff --git a/chromium/chrome/browser/ui/webui/devtools_ui.cc b/chromium/chrome/browser/ui/webui/devtools_ui.cc index 4bae28351f1..a130596ccc9 100644 --- a/chromium/chrome/browser/ui/webui/devtools_ui.cc +++ b/chromium/chrome/browser/ui/webui/devtools_ui.cc @@ -28,7 +28,7 @@ #include "net/traffic_annotation/network_traffic_annotation.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/simple_url_loader.h" -#include "third_party/WebKit/public/public_features.h" +#include "third_party/blink/public/public_buildflags.h" using content::BrowserThread; using content::WebContents; @@ -85,7 +85,7 @@ class DevToolsDataSource : public content::URLDataSource { using GotDataCallback = content::URLDataSource::GotDataCallback; explicit DevToolsDataSource( - scoped_refptr<content::SharedURLLoaderFactory> url_loader_factory) + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : url_loader_factory_(std::move(url_loader_factory)) {} // content::URLDataSource implementation. @@ -144,7 +144,7 @@ class DevToolsDataSource : public content::URLDataSource { DISALLOW_COPY_AND_ASSIGN(PendingRequest); }; - scoped_refptr<content::SharedURLLoaderFactory> url_loader_factory_; + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; std::list<PendingRequest> pending_requests_; DISALLOW_COPY_AND_ASSIGN(DevToolsDataSource); diff --git a/chromium/chrome/browser/ui/webui/discards/discards.mojom b/chromium/chrome/browser/ui/webui/discards/discards.mojom index c1be52bd457..1cf89a7c276 100644 --- a/chromium/chrome/browser/ui/webui/discards/discards.mojom +++ b/chromium/chrome/browser/ui/webui/discards/discards.mojom @@ -4,6 +4,13 @@ module mojom; +// Identical to content::Visibility. +enum LifecycleUnitVisibility { + HIDDEN = 0, + OCCLUDED = 1, + VISIBLE = 2, +}; + // Discard related information about a single tab in a browser. struct TabDiscardsInfo { // The URL associated with the tab. This corresponds to GetLastCommittedURL, @@ -13,6 +20,8 @@ struct TabDiscardsInfo { string favicon_url; // The title of the tab, as displayed on the tab itself. string title; + // The visibility of the LifecycleUnit. + LifecycleUnitVisibility visibility; // If the tab is currently using media functionality (casting, WebRTC, playing // audio, etc) this is true. bool is_media; @@ -53,6 +62,9 @@ interface DiscardsDetailsProvider { // Invokes a callback when the discard is complete. DiscardById(int32 tab_id, bool urgent) => (); + // Freezes a tab given its |tab_id|. + FreezeById(int32 tab_id); + // Discards the least important tab. If |urgent| is specified the unload // handlers will not be run, and the tab will be unloaded with prejudice. // This can fail to discard a tab if no tabs are currently considered diff --git a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc index 2d53a02fc19..bcf0a16b0c2 100644 --- a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc +++ b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc @@ -7,16 +7,20 @@ #include <utility> #include <vector> +#include "base/logging.h" #include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/resource_coordinator/discard_reason.h" +#include "chrome/browser/resource_coordinator/lifecycle_unit.h" +#include "chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h" #include "chrome/browser/resource_coordinator/tab_manager.h" -#include "chrome/browser/resource_coordinator/tab_stats.h" #include "chrome/browser/resource_coordinator/time.h" #include "chrome/browser/ui/webui/discards/discards.mojom.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/browser_resources.h" +#include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/browser/web_ui_message_handler.h" @@ -30,6 +34,22 @@ resource_coordinator::DiscardReason GetDiscardReason(bool urgent) { : resource_coordinator::DiscardReason::kProactive; } +mojom::LifecycleUnitVisibility GetLifecycleUnitVisibility( + content::Visibility visibility) { + switch (visibility) { + case content::Visibility::HIDDEN: + return mojom::LifecycleUnitVisibility::HIDDEN; + case content::Visibility::OCCLUDED: + return mojom::LifecycleUnitVisibility::OCCLUDED; + case content::Visibility::VISIBLE: + return mojom::LifecycleUnitVisibility::VISIBLE; + } +#if defined(COMPILER_MSVC) + NOTREACHED(); + return mojom::LifecycleUnitVisibility::VISIBLE; +#endif +} + class DiscardsDetailsProviderImpl : public mojom::DiscardsDetailsProvider { public: // This instance is deleted when the supplied pipe is destroyed. @@ -43,31 +63,46 @@ class DiscardsDetailsProviderImpl : public mojom::DiscardsDetailsProvider { void GetTabDiscardsInfo(GetTabDiscardsInfoCallback callback) override { resource_coordinator::TabManager* tab_manager = g_browser_process->GetTabManager(); - resource_coordinator::TabStatsList stats = tab_manager->GetTabStats(); + const resource_coordinator::LifecycleUnitVector lifecycle_units = + tab_manager->GetSortedLifecycleUnits(); std::vector<mojom::TabDiscardsInfoPtr> infos; - infos.reserve(stats.size()); + infos.reserve(lifecycle_units.size()); - base::TimeTicks now = resource_coordinator::NowTicks(); + const base::TimeTicks now = resource_coordinator::NowTicks(); - // Convert the TabStatsList to a vector of TabDiscardsInfos. + // Convert the LifecycleUnits to a vector of TabDiscardsInfos. size_t rank = 1; - for (const auto& tab : stats) { + for (auto* lifecycle_unit : lifecycle_units) { mojom::TabDiscardsInfoPtr info(mojom::TabDiscardsInfo::New()); - info->tab_url = tab.tab_url; + resource_coordinator::TabLifecycleUnitExternal* + tab_lifecycle_unit_external = + lifecycle_unit->AsTabLifecycleUnitExternal(); + content::WebContents* contents = + tab_lifecycle_unit_external->GetWebContents(); + + info->tab_url = contents->GetLastCommittedURL().spec(); // This can be empty for pages without a favicon. The WebUI takes care of // showing the chrome://favicon default in that case. - info->favicon_url = tab.favicon_url; - info->title = base::UTF16ToUTF8(tab.title); - info->is_media = tab.is_media; - info->is_discarded = tab.is_discarded; - info->discard_count = tab.discard_count; + info->favicon_url = lifecycle_unit->GetIconURL(); + info->title = base::UTF16ToUTF8(lifecycle_unit->GetTitle()); + info->visibility = + GetLifecycleUnitVisibility(lifecycle_unit->GetVisibility()); + info->is_media = tab_lifecycle_unit_external->IsMediaTab(); + info->is_discarded = tab_lifecycle_unit_external->IsDiscarded(); + info->discard_count = tab_lifecycle_unit_external->GetDiscardCount(); info->utility_rank = rank++; - auto elapsed = now - tab.last_active; + const base::TimeTicks last_focused_time = + lifecycle_unit->GetSortKey().last_focused_time; + const base::TimeDelta elapsed = + (last_focused_time == base::TimeTicks::Max()) + ? base::TimeDelta() + : (now - last_focused_time); info->last_active_seconds = static_cast<int32_t>(elapsed.InSeconds()); - info->is_auto_discardable = tab.is_auto_discardable; - info->id = tab.id; + info->is_auto_discardable = + tab_lifecycle_unit_external->IsAutoDiscardable(); + info->id = lifecycle_unit->GetID(); infos.push_back(std::move(info)); } @@ -93,6 +128,12 @@ class DiscardsDetailsProviderImpl : public mojom::DiscardsDetailsProvider { std::move(callback).Run(); } + void FreezeById(int32_t tab_id) override { + resource_coordinator::TabManager* tab_manager = + g_browser_process->GetTabManager(); + tab_manager->FreezeTabById(tab_id); + } + void Discard(bool urgent, DiscardCallback callback) override { resource_coordinator::TabManager* tab_manager = g_browser_process->GetTabManager(); @@ -109,7 +150,7 @@ class DiscardsDetailsProviderImpl : public mojom::DiscardsDetailsProvider { } // namespace DiscardsUI::DiscardsUI(content::WebUI* web_ui) - : MojoWebUIController<mojom::DiscardsDetailsProvider>(web_ui) { + : ui::MojoWebUIController<mojom::DiscardsDetailsProvider>(web_ui) { std::unique_ptr<content::WebUIDataSource> source( content::WebUIDataSource::Create(chrome::kChromeUIDiscardsHost)); diff --git a/chromium/chrome/browser/ui/webui/discards/discards_ui.h b/chromium/chrome/browser/ui/webui/discards/discards_ui.h index 212c6646059..eec56b2ca9c 100644 --- a/chromium/chrome/browser/ui/webui/discards/discards_ui.h +++ b/chromium/chrome/browser/ui/webui/discards/discards_ui.h @@ -9,17 +9,18 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/discards/discards.mojom.h" -#include "chrome/browser/ui/webui/mojo_web_ui_controller.h" +#include "ui/webui/mojo_web_ui_controller.h" // Controller for chrome://discards. Corresponding resources are in // file://chrome/browser/resources/discards. -class DiscardsUI : public MojoWebUIController<mojom::DiscardsDetailsProvider> { +class DiscardsUI + : public ui::MojoWebUIController<mojom::DiscardsDetailsProvider> { public: explicit DiscardsUI(content::WebUI* web_ui); ~DiscardsUI() override; private: - // MojoWebUIController overrides: + // ui::MojoWebUIController overrides: void BindUIHandler(mojom::DiscardsDetailsProviderRequest request) override; std::unique_ptr<mojom::DiscardsDetailsProvider> ui_handler_; diff --git a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc index ba3525b6350..2afd8eb0cfd 100644 --- a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc @@ -29,9 +29,10 @@ DomainReliabilityInternalsUI::DomainReliabilityInternalsUI( html_source->SetDefaultResource(IDR_DOMAIN_RELIABILITY_INTERNALS_HTML); html_source->UseGzip(); - web_ui->RegisterMessageCallback("updateData", - base::Bind(&DomainReliabilityInternalsUI::UpdateData, - base::Unretained(this))); + web_ui->RegisterMessageCallback( + "updateData", + base::BindRepeating(&DomainReliabilityInternalsUI::UpdateData, + base::Unretained(this))); Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource::Add(profile, html_source); diff --git a/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc b/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc index 0b5991d6885..71265fb3900 100644 --- a/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc +++ b/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc @@ -76,7 +76,7 @@ class SiteEngagementDetailsProviderImpl } // namespace SiteEngagementUI::SiteEngagementUI(content::WebUI* web_ui) - : MojoWebUIController<mojom::SiteEngagementDetailsProvider>(web_ui) { + : ui::MojoWebUIController<mojom::SiteEngagementDetailsProvider>(web_ui) { // Set up the chrome://site-engagement/ source. std::unique_ptr<content::WebUIDataSource> source( content::WebUIDataSource::Create(chrome::kChromeUISiteEngagementHost)); diff --git a/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.h b/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.h index 3c26b626623..678050d38ce 100644 --- a/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.h +++ b/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.h @@ -7,17 +7,17 @@ #include "base/macros.h" #include "chrome/browser/engagement/site_engagement_details.mojom.h" -#include "chrome/browser/ui/webui/mojo_web_ui_controller.h" +#include "ui/webui/mojo_web_ui_controller.h" // The UI for chrome://site-engagement/. class SiteEngagementUI - : public MojoWebUIController<mojom::SiteEngagementDetailsProvider> { + : public ui::MojoWebUIController<mojom::SiteEngagementDetailsProvider> { public: explicit SiteEngagementUI(content::WebUI* web_ui); ~SiteEngagementUI() override; private: - // MojoWebUIController overrides: + // ui::MojoWebUIController overrides: void BindUIHandler( mojom::SiteEngagementDetailsProviderRequest request) override; diff --git a/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc b/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc index f6fed887a54..56b411c546d 100644 --- a/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc +++ b/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc @@ -129,27 +129,33 @@ void KioskAppsHandler::OnJavascriptDisallowed() { } void KioskAppsHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("initializeKioskAppSettings", - base::Bind(&KioskAppsHandler::HandleInitializeKioskAppSettings, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("getKioskAppSettings", - base::Bind(&KioskAppsHandler::HandleGetKioskAppSettings, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("addKioskApp", - base::Bind(&KioskAppsHandler::HandleAddKioskApp, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("removeKioskApp", - base::Bind(&KioskAppsHandler::HandleRemoveKioskApp, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("enableKioskAutoLaunch", - base::Bind(&KioskAppsHandler::HandleEnableKioskAutoLaunch, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("disableKioskAutoLaunch", - base::Bind(&KioskAppsHandler::HandleDisableKioskAutoLaunch, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("setDisableBailoutShortcut", - base::Bind(&KioskAppsHandler::HandleSetDisableBailoutShortcut, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "initializeKioskAppSettings", + base::BindRepeating(&KioskAppsHandler::HandleInitializeKioskAppSettings, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getKioskAppSettings", + base::BindRepeating(&KioskAppsHandler::HandleGetKioskAppSettings, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "addKioskApp", base::BindRepeating(&KioskAppsHandler::HandleAddKioskApp, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "removeKioskApp", + base::BindRepeating(&KioskAppsHandler::HandleRemoveKioskApp, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "enableKioskAutoLaunch", + base::BindRepeating(&KioskAppsHandler::HandleEnableKioskAutoLaunch, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "disableKioskAutoLaunch", + base::BindRepeating(&KioskAppsHandler::HandleDisableKioskAutoLaunch, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "setDisableBailoutShortcut", + base::BindRepeating(&KioskAppsHandler::HandleSetDisableBailoutShortcut, + base::Unretained(this))); } void KioskAppsHandler::GetLocalizedValues(content::WebUIDataSource* source) { diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_loader_handler.cc b/chromium/chrome/browser/ui/webui/extensions/extension_loader_handler.cc index 03e806213ea..12c132d3086 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_loader_handler.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extension_loader_handler.cc @@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/files/file_util.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/strings/string16.h" #include "base/strings/string_util.h" @@ -93,16 +92,16 @@ void ExtensionLoaderHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "extensionLoaderRetry", - base::Bind(&ExtensionLoaderHandler::HandleRetry, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&ExtensionLoaderHandler::HandleRetry, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "extensionLoaderIgnoreFailure", - base::Bind(&ExtensionLoaderHandler::HandleIgnoreFailure, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&ExtensionLoaderHandler::HandleIgnoreFailure, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "extensionLoaderDisplayFailures", - base::Bind(&ExtensionLoaderHandler::HandleDisplayFailures, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&ExtensionLoaderHandler::HandleDisplayFailures, + weak_ptr_factory_.GetWeakPtr())); } // static diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc b/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc index e18a1185bc3..450ec468bee 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc @@ -24,6 +24,7 @@ #include "content/public/test/browser_test_utils.h" #include "extensions/browser/extension_dialog_auto_confirm.h" #include "extensions/browser/extension_system.h" +#include "extensions/common/switches.h" using extensions::Extension; using extensions::TestManagementPolicyProvider; @@ -38,6 +39,14 @@ ExtensionSettingsUIBrowserTest::ExtensionSettingsUIBrowserTest() ExtensionSettingsUIBrowserTest::~ExtensionSettingsUIBrowserTest() {} +void ExtensionSettingsUIBrowserTest::SetUpCommandLine( + base::CommandLine* command_line) { + WebUIBrowserTest::SetUpCommandLine(command_line); + // TODO(devlin): Remove this. See https://crbug.com/816679. + command_line->AppendSwitch( + extensions::switches::kAllowLegacyExtensionManifests); +} + void ExtensionSettingsUIBrowserTest::InstallGoodExtension() { EXPECT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"))); } @@ -46,6 +55,8 @@ void ExtensionSettingsUIBrowserTest::InstallErrorsExtension() { EXPECT_TRUE( InstallExtension(test_data_dir_.AppendASCII("error_console") .AppendASCII("runtime_and_manifest_errors"))); + EXPECT_TRUE(InstallExtension(test_data_dir_.AppendASCII("error_console") + .AppendASCII("deep_stack_trace"))); } void ExtensionSettingsUIBrowserTest::InstallSharedModule() { diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.h b/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.h index a74021ec537..e5c2c16c5c9 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.h +++ b/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.h @@ -26,6 +26,8 @@ class ExtensionSettingsUIBrowserTest : public WebUIBrowserTest { ExtensionSettingsUIBrowserTest(); ~ExtensionSettingsUIBrowserTest() override; + void SetUpCommandLine(base::CommandLine* command_line) override; + protected: void InstallGoodExtension(); diff --git a/chromium/chrome/browser/ui/webui/extensions/install_extension_handler.cc b/chromium/chrome/browser/ui/webui/extensions/install_extension_handler.cc index 953306e2712..1782d196c68 100644 --- a/chromium/chrome/browser/ui/webui/extensions/install_extension_handler.cc +++ b/chromium/chrome/browser/ui/webui/extensions/install_extension_handler.cc @@ -20,6 +20,7 @@ #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/common/drop_data.h" +#include "content/public/common/service_manager_connection.h" #include "extensions/browser/extension_system.h" #include "extensions/common/feature_switch.h" #include "net/base/filename_util.h" @@ -43,20 +44,21 @@ void InstallExtensionHandler::GetLocalizedValues( void InstallExtensionHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "startDrag", - base::Bind(&InstallExtensionHandler::HandleStartDragMessage, - base::Unretained(this))); + base::BindRepeating(&InstallExtensionHandler::HandleStartDragMessage, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "stopDrag", - base::Bind(&InstallExtensionHandler::HandleStopDragMessage, - base::Unretained(this))); + base::BindRepeating(&InstallExtensionHandler::HandleStopDragMessage, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "installDroppedFile", - base::Bind(&InstallExtensionHandler::HandleInstallMessage, - base::Unretained(this))); + base::BindRepeating(&InstallExtensionHandler::HandleInstallMessage, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "installDroppedDirectory", - base::Bind(&InstallExtensionHandler::HandleInstallDirectoryMessage, - base::Unretained(this))); + base::BindRepeating( + &InstallExtensionHandler::HandleInstallDirectoryMessage, + base::Unretained(this))); } void InstallExtensionHandler::HandleStartDragMessage( @@ -100,6 +102,7 @@ void InstallExtensionHandler::HandleInstallMessage( if (file_display_name_.MatchesExtension(FILE_PATH_LITERAL(".zip"))) { ZipFileInstaller::Create( + content::ServiceManagerConnection::GetForProcess()->GetConnector(), MakeRegisterInExtensionServiceCallback( ExtensionSystem::Get(profile)->extension_service())) ->LoadFromZipFile(file_to_install_); diff --git a/chromium/chrome/browser/ui/webui/flags_ui.cc b/chromium/chrome/browser/ui/webui/flags_ui.cc index cf719ba468f..a692030be7a 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui.cc +++ b/chromium/chrome/browser/ui/webui/flags_ui.cc @@ -130,20 +130,21 @@ class FlagsDOMHandler : public WebUIMessageHandler { void FlagsDOMHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( flags_ui::kRequestExperimentalFeatures, - base::Bind(&FlagsDOMHandler::HandleRequestExperimentalFeatures, - base::Unretained(this))); + base::BindRepeating(&FlagsDOMHandler::HandleRequestExperimentalFeatures, + base::Unretained(this))); web_ui()->RegisterMessageCallback( flags_ui::kEnableExperimentalFeature, - base::Bind(&FlagsDOMHandler::HandleEnableExperimentalFeatureMessage, - base::Unretained(this))); + base::BindRepeating( + &FlagsDOMHandler::HandleEnableExperimentalFeatureMessage, + base::Unretained(this))); web_ui()->RegisterMessageCallback( flags_ui::kRestartBrowser, - base::Bind(&FlagsDOMHandler::HandleRestartBrowser, - base::Unretained(this))); + base::BindRepeating(&FlagsDOMHandler::HandleRestartBrowser, + base::Unretained(this))); web_ui()->RegisterMessageCallback( flags_ui::kResetAllFlags, - base::Bind(&FlagsDOMHandler::HandleResetAllFlags, - base::Unretained(this))); + base::BindRepeating(&FlagsDOMHandler::HandleResetAllFlags, + base::Unretained(this))); } void FlagsDOMHandler::Init(flags_ui::FlagsStorage* flags_storage, diff --git a/chromium/chrome/browser/ui/webui/flash_ui.cc b/chromium/chrome/browser/ui/webui/flash_ui.cc index f4352f04684..625921b65da 100644 --- a/chromium/chrome/browser/ui/webui/flash_ui.cc +++ b/chromium/chrome/browser/ui/webui/flash_ui.cc @@ -176,9 +176,10 @@ FlashDOMHandler::~FlashDOMHandler() { } void FlashDOMHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("requestFlashInfo", - base::Bind(&FlashDOMHandler::HandleRequestFlashInfo, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "requestFlashInfo", + base::BindRepeating(&FlashDOMHandler::HandleRequestFlashInfo, + base::Unretained(this))); } void FlashDOMHandler::OnUploadListAvailable() { @@ -244,9 +245,9 @@ void FlashDOMHandler::MaybeRespondToPage() { auto list = std::make_unique<base::ListValue>(); // Chrome version information. - AddPair(list.get(), l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), - version_info::GetVersionNumber() + " (" + chrome::GetChannelString() + - ")"); + AddPair( + list.get(), l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), + version_info::GetVersionNumber() + " (" + chrome::GetChannelName() + ")"); // OS version information. std::string os_label = version_info::GetOSType(); diff --git a/chromium/chrome/browser/ui/webui/foreign_session_handler.cc b/chromium/chrome/browser/ui/webui/foreign_session_handler.cc index cbae4e87be5..aa938b1a909 100644 --- a/chromium/chrome/browser/ui/webui/foreign_session_handler.cc +++ b/chromium/chrome/browser/ui/webui/foreign_session_handler.cc @@ -103,7 +103,7 @@ std::unique_ptr<base::DictionaryValue> SessionTabToValue( // Helper for initializing a boilerplate SessionWindow JSON compatible object. std::unique_ptr<base::DictionaryValue> BuildWindowData( base::Time modification_time, - SessionID::id_type window_id) { + SessionID window_id) { std::unique_ptr<base::DictionaryValue> dictionary( new base::DictionaryValue()); // The items which are to be written into |dictionary| are also described in @@ -121,7 +121,7 @@ std::unique_ptr<base::DictionaryValue> BuildWindowData( : ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED, ui::TimeFormat::LENGTH_SHORT, last_synced)); - dictionary->SetInteger("sessionId", window_id); + dictionary->SetInteger("sessionId", window_id.id()); return dictionary; } @@ -145,7 +145,7 @@ std::unique_ptr<base::DictionaryValue> SessionWindowToValue( if (tab_values->GetSize() == 0) return nullptr; std::unique_ptr<base::DictionaryValue> dictionary( - BuildWindowData(window.timestamp, window.window_id.id())); + BuildWindowData(window.timestamp, window.window_id)); dictionary->Set("tabs", std::move(tab_values)); return dictionary; } @@ -168,15 +168,15 @@ void ForeignSessionHandler::RegisterProfilePrefs( void ForeignSessionHandler::OpenForeignSessionTab( content::WebUI* web_ui, const std::string& session_string_value, - SessionID::id_type window_num, - SessionID::id_type tab_id, + int window_num, + SessionID tab_id, const WindowOpenDisposition& disposition) { sync_sessions::OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(web_ui); if (!open_tabs) return; // We don't actually care about |window_num|, this is just a sanity check. - DCHECK_LT(kInvalidId, window_num); + DCHECK_LE(0, window_num); const ::sessions::SessionTab* tab; if (!open_tabs->GetForeignTab(session_string_value, tab_id, &tab)) { LOG(ERROR) << "Failed to load foreign tab."; @@ -194,7 +194,7 @@ void ForeignSessionHandler::OpenForeignSessionTab( void ForeignSessionHandler::OpenForeignSessionWindows( content::WebUI* web_ui, const std::string& session_string_value, - SessionID::id_type window_num) { + int window_num) { sync_sessions::OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(web_ui); if (!open_tabs) return; @@ -207,11 +207,12 @@ void ForeignSessionHandler::OpenForeignSessionWindows( return; } std::vector<const ::sessions::SessionWindow*>::const_iterator iter_begin = - windows.begin() + (window_num == kInvalidId ? 0 : window_num); + windows.begin() + (window_num < 0 ? 0 : window_num); std::vector<const ::sessions::SessionWindow*>::const_iterator iter_end = - window_num == kInvalidId ? - std::vector<const ::sessions::SessionWindow*>::const_iterator( - windows.end()) : iter_begin + 1; + window_num < 0 + ? std::vector<const ::sessions::SessionWindow*>::const_iterator( + windows.end()) + : iter_begin + 1; SessionRestore::RestoreForeignSessionWindows(Profile::FromWebUI(web_ui), iter_begin, iter_end); } @@ -240,18 +241,23 @@ void ForeignSessionHandler::RegisterMessages() { if (service) scoped_observer_.Add(service); - web_ui()->RegisterMessageCallback("deleteForeignSession", - base::Bind(&ForeignSessionHandler::HandleDeleteForeignSession, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("getForeignSessions", - base::Bind(&ForeignSessionHandler::HandleGetForeignSessions, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("openForeignSession", - base::Bind(&ForeignSessionHandler::HandleOpenForeignSession, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("setForeignSessionCollapsed", - base::Bind(&ForeignSessionHandler::HandleSetForeignSessionCollapsed, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "deleteForeignSession", + base::BindRepeating(&ForeignSessionHandler::HandleDeleteForeignSession, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getForeignSessions", + base::BindRepeating(&ForeignSessionHandler::HandleGetForeignSessions, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "openForeignSession", + base::BindRepeating(&ForeignSessionHandler::HandleOpenForeignSession, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "setForeignSessionCollapsed", + base::BindRepeating( + &ForeignSessionHandler::HandleSetForeignSessionCollapsed, + base::Unretained(this))); } void ForeignSessionHandler::OnSyncConfigurationCompleted( @@ -321,37 +327,13 @@ void ForeignSessionHandler::HandleGetForeignSessions( current_collapsed_sessions->SetBoolean(session_tag, true); std::unique_ptr<base::ListValue> window_list(new base::ListValue()); - const std::string group_name = - base::FieldTrialList::FindFullName("TabSyncByRecency"); - if (group_name != "Enabled") { - // Order tabs by visual order within window. - for (const auto& window_pair : session->windows) { - std::unique_ptr<base::DictionaryValue> window_data( - SessionWindowToValue(window_pair.second->wrapped_window)); - if (window_data.get()) - window_list->Append(std::move(window_data)); - } - } else { - // Order tabs by recency. This involves creating a synthetic singleton - // window that contains all the tabs of the session. - base::Time modification_time; - std::vector<const ::sessions::SessionTab*> tabs; - open_tabs->GetForeignSessionTabs(session_tag, &tabs); - std::unique_ptr<base::ListValue> tab_values(new base::ListValue()); - for (const ::sessions::SessionTab* tab : tabs) { - std::unique_ptr<base::DictionaryValue> tab_value( - SessionTabToValue(*tab)); - if (tab_value.get()) { - modification_time = std::max(modification_time, tab->timestamp); - tab_values->Append(std::move(tab_value)); - } - } - if (tab_values->GetSize() != 0) { - std::unique_ptr<base::DictionaryValue> window_data( - BuildWindowData(modification_time, 1)); - window_data->Set("tabs", std::move(tab_values)); + + // Order tabs by visual order within window. + for (const auto& window_pair : session->windows) { + std::unique_ptr<base::DictionaryValue> window_data( + SessionWindowToValue(window_pair.second->wrapped_window)); + if (window_data) window_list->Append(std::move(window_data)); - } } session_data->Set("windows", std::move(window_list)); @@ -384,7 +366,7 @@ void ForeignSessionHandler::HandleOpenForeignSession( // Extract window number. std::string window_num_str; - int window_num = kInvalidId; + int window_num = -1; if (num_args >= 2 && (!args->GetString(1, &window_num_str) || !base::StringToInt(window_num_str, &window_num))) { LOG(ERROR) << "Failed to extract window number."; @@ -393,14 +375,15 @@ void ForeignSessionHandler::HandleOpenForeignSession( // Extract tab id. std::string tab_id_str; - SessionID::id_type tab_id = kInvalidId; + SessionID::id_type tab_id_value = 0; if (num_args >= 3 && (!args->GetString(2, &tab_id_str) || - !base::StringToInt(tab_id_str, &tab_id))) { + !base::StringToInt(tab_id_str, &tab_id_value))) { LOG(ERROR) << "Failed to extract tab SessionID."; return; } - if (tab_id != kInvalidId) { + SessionID tab_id = SessionID::FromSerializedValue(tab_id_value); + if (tab_id.is_valid()) { WindowOpenDisposition disposition = webui::GetDispositionFromClick(args, 3); OpenForeignSessionTab( web_ui(), session_string_value, window_num, tab_id, disposition); diff --git a/chromium/chrome/browser/ui/webui/foreign_session_handler.h b/chromium/chrome/browser/ui/webui/foreign_session_handler.h index d0cb2452b03..81712db1c9f 100644 --- a/chromium/chrome/browser/ui/webui/foreign_session_handler.h +++ b/chromium/chrome/browser/ui/webui/foreign_session_handler.h @@ -30,9 +30,6 @@ namespace browser_sync { class ForeignSessionHandler : public content::WebUIMessageHandler, public syncer::SyncServiceObserver { public: - // Invalid value, used to note that we don't have a tab or window number. - static const int kInvalidId = -1; - // WebUIMessageHandler implementation. void RegisterMessages() override; @@ -43,13 +40,13 @@ class ForeignSessionHandler : public content::WebUIMessageHandler, static void OpenForeignSessionTab(content::WebUI* web_ui, const std::string& session_string_value, - SessionID::id_type window_num, - SessionID::id_type tab_id, + int window_num, + SessionID tab_id, const WindowOpenDisposition& disposition); static void OpenForeignSessionWindows(content::WebUI* web_ui, const std::string& session_string_value, - SessionID::id_type window_num); + int window_num); // Returns a pointer to the current session model associator or NULL. static sync_sessions::OpenTabsUIDelegate* GetOpenTabsUIDelegate( diff --git a/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc b/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc index 80a410874af..cf281dab9ca 100644 --- a/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc @@ -145,12 +145,12 @@ void GcmInternalsUIMessageHandler::RequestGCMStatisticsFinished( void GcmInternalsUIMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( gcm_driver::kGetGcmInternalsInfo, - base::Bind(&GcmInternalsUIMessageHandler::RequestAllInfo, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&GcmInternalsUIMessageHandler::RequestAllInfo, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( gcm_driver::kSetGcmInternalsRecording, - base::Bind(&GcmInternalsUIMessageHandler::SetRecording, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&GcmInternalsUIMessageHandler::SetRecording, + weak_ptr_factory_.GetWeakPtr())); } } // namespace diff --git a/chromium/chrome/browser/ui/webui/history_login_handler.cc b/chromium/chrome/browser/ui/webui/history_login_handler.cc index 33d1b520b43..5fe265fd7ae 100644 --- a/chromium/chrome/browser/ui/webui/history_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/history_login_handler.cc @@ -28,13 +28,15 @@ void HistoryLoginHandler::RegisterMessages() { base::Bind(&HistoryLoginHandler::ProfileInfoChanged, base::Unretained(this)))); - web_ui()->RegisterMessageCallback("otherDevicesInitialized", - base::Bind(&HistoryLoginHandler::HandleOtherDevicesInitialized, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "otherDevicesInitialized", + base::BindRepeating(&HistoryLoginHandler::HandleOtherDevicesInitialized, + base::Unretained(this))); - web_ui()->RegisterMessageCallback("startSignInFlow", - base::Bind(&HistoryLoginHandler::HandleStartSignInFlow, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "startSignInFlow", + base::BindRepeating(&HistoryLoginHandler::HandleStartSignInFlow, + base::Unretained(this))); } void HistoryLoginHandler::HandleOtherDevicesInitialized( diff --git a/chromium/chrome/browser/ui/webui/identity_internals_ui.cc b/chromium/chrome/browser/ui/webui/identity_internals_ui.cc index cabffb7a4d1..ecd1b1f2407 100644 --- a/chromium/chrome/browser/ui/webui/identity_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/identity_internals_ui.cc @@ -119,7 +119,8 @@ class IdentityInternalsTokenRevoker : public GaiaAuthConsumer { const std::string& extension_id() const { return extension_id_; } // GaiaAuthConsumer implementation. - void OnOAuth2RevokeTokenCompleted() override; + void OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus status) override; private: // An object used to start a token revoke request. @@ -249,12 +250,15 @@ void IdentityInternalsUIMessageHandler::GetInfoForAllTokens( } void IdentityInternalsUIMessageHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("identityInternalsGetTokens", - base::Bind(&IdentityInternalsUIMessageHandler::GetInfoForAllTokens, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("identityInternalsRevokeToken", - base::Bind(&IdentityInternalsUIMessageHandler::RevokeToken, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "identityInternalsGetTokens", + base::BindRepeating( + &IdentityInternalsUIMessageHandler::GetInfoForAllTokens, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "identityInternalsRevokeToken", + base::BindRepeating(&IdentityInternalsUIMessageHandler::RevokeToken, + base::Unretained(this))); } void IdentityInternalsUIMessageHandler::RevokeToken( @@ -283,7 +287,8 @@ IdentityInternalsTokenRevoker::IdentityInternalsTokenRevoker( IdentityInternalsTokenRevoker::~IdentityInternalsTokenRevoker() {} -void IdentityInternalsTokenRevoker::OnOAuth2RevokeTokenCompleted() { +void IdentityInternalsTokenRevoker::OnOAuth2RevokeTokenCompleted( + GaiaAuthConsumer::TokenRevocationStatus status) { consumer_->OnTokenRevokerDone(this); } diff --git a/chromium/chrome/browser/ui/webui/inspect_ui.cc b/chromium/chrome/browser/ui/webui/inspect_ui.cc index ab19c4d204f..acad9c57e3a 100644 --- a/chromium/chrome/browser/ui/webui/inspect_ui.cc +++ b/chromium/chrome/browser/ui/webui/inspect_ui.cc @@ -110,56 +110,72 @@ class InspectMessageHandler : public WebUIMessageHandler { }; void InspectMessageHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback(kInitUICommand, - base::Bind(&InspectMessageHandler::HandleInitUICommand, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kInspectCommand, - base::Bind(&InspectMessageHandler::HandleInspectCommand, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kInitUICommand, + base::BindRepeating(&InspectMessageHandler::HandleInitUICommand, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kInspectCommand, + base::BindRepeating(&InspectMessageHandler::HandleInspectCommand, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kInspectFallbackCommand, base::BindRepeating(&InspectMessageHandler::HandleInspectFallbackCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( kInspectAdditionalCommand, - base::Bind(&InspectMessageHandler::HandleInspectAdditionalCommand, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kActivateCommand, - base::Bind(&InspectMessageHandler::HandleActivateCommand, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kCloseCommand, - base::Bind(&InspectMessageHandler::HandleCloseCommand, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kDiscoverUsbDevicesEnabledCommand, - base::Bind(&InspectMessageHandler::HandleBooleanPrefChanged, - base::Unretained(this), - &prefs::kDevToolsDiscoverUsbDevicesEnabled[0])); - web_ui()->RegisterMessageCallback(kPortForwardingEnabledCommand, - base::Bind(&InspectMessageHandler::HandleBooleanPrefChanged, - base::Unretained(this), - &prefs::kDevToolsPortForwardingEnabled[0])); - web_ui()->RegisterMessageCallback(kPortForwardingConfigCommand, - base::Bind(&InspectMessageHandler::HandlePortForwardingConfigCommand, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kDiscoverTCPTargetsEnabledCommand, - base::Bind(&InspectMessageHandler::HandleBooleanPrefChanged, - base::Unretained(this), - &prefs::kDevToolsDiscoverTCPTargetsEnabled[0])); - web_ui()->RegisterMessageCallback(kTCPDiscoveryConfigCommand, - base::Bind(&InspectMessageHandler::HandleTCPDiscoveryConfigCommand, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kOpenNodeFrontendCommand, - base::Bind(&InspectMessageHandler::HandleOpenNodeFrontendCommand, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kReloadCommand, - base::Bind(&InspectMessageHandler::HandleReloadCommand, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kOpenCommand, - base::Bind(&InspectMessageHandler::HandleOpenCommand, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kInspectBrowser, - base::Bind(&InspectMessageHandler::HandleInspectBrowserCommand, - base::Unretained(this))); + base::BindRepeating( + &InspectMessageHandler::HandleInspectAdditionalCommand, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kActivateCommand, + base::BindRepeating(&InspectMessageHandler::HandleActivateCommand, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kCloseCommand, + base::BindRepeating(&InspectMessageHandler::HandleCloseCommand, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kDiscoverUsbDevicesEnabledCommand, + base::BindRepeating(&InspectMessageHandler::HandleBooleanPrefChanged, + base::Unretained(this), + &prefs::kDevToolsDiscoverUsbDevicesEnabled[0])); + web_ui()->RegisterMessageCallback( + kPortForwardingEnabledCommand, + base::BindRepeating(&InspectMessageHandler::HandleBooleanPrefChanged, + base::Unretained(this), + &prefs::kDevToolsPortForwardingEnabled[0])); + web_ui()->RegisterMessageCallback( + kPortForwardingConfigCommand, + base::BindRepeating( + &InspectMessageHandler::HandlePortForwardingConfigCommand, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kDiscoverTCPTargetsEnabledCommand, + base::BindRepeating(&InspectMessageHandler::HandleBooleanPrefChanged, + base::Unretained(this), + &prefs::kDevToolsDiscoverTCPTargetsEnabled[0])); + web_ui()->RegisterMessageCallback( + kTCPDiscoveryConfigCommand, + base::BindRepeating( + &InspectMessageHandler::HandleTCPDiscoveryConfigCommand, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kOpenNodeFrontendCommand, + base::BindRepeating(&InspectMessageHandler::HandleOpenNodeFrontendCommand, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kReloadCommand, + base::BindRepeating(&InspectMessageHandler::HandleReloadCommand, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kOpenCommand, + base::BindRepeating(&InspectMessageHandler::HandleOpenCommand, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kInspectBrowser, + base::BindRepeating(&InspectMessageHandler::HandleInspectBrowserCommand, + base::Unretained(this))); } void InspectMessageHandler::HandleInitUICommand(const base::ListValue*) { @@ -478,7 +494,7 @@ void InspectUI::StartListeningNotifications() { PopulateAdditionalTargets(additional_targets); AddTargetUIHandler( - DevToolsTargetsUIHandler::CreateForLocal(callback)); + DevToolsTargetsUIHandler::CreateForLocal(callback, profile)); if (profile->IsOffTheRecord()) { ShowIncognitoWarning(); } else { diff --git a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.cc index 0a4eb3c584d..7acc8d01890 100644 --- a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.cc @@ -18,6 +18,7 @@ #include "components/previews/core/previews_experiments.h" #include "components/previews/core/previews_switches.h" #include "net/nqe/network_quality_estimator_params.h" +#include "services/network/public/cpp/network_switches.h" namespace { @@ -235,7 +236,7 @@ void InterventionsInternalsPageHandler::GetPreviewsFlagsDetails( ect_status->link = kEctFlagLink; std::string ect_value = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kForceEffectiveConnectionType); + network::switches::kForceEffectiveConnectionType); ect_status->value = ect_value.empty() ? GetNonFlagEctValue() : ect_value; ect_status->htmlId = kEctFlagHtmlId; flags.push_back(std::move(ect_status)); diff --git a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h index 1fe7f28dbf7..55c20dcd9a1 100644 --- a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h +++ b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h @@ -10,7 +10,6 @@ #include "base/macros.h" #include "base/time/time.h" #include "chrome/browser/ui/webui/interventions_internals/interventions_internals.mojom.h" -#include "chrome/browser/ui/webui/mojo_web_ui_handler.h" #include "components/previews/content/previews_ui_service.h" #include "components/previews/core/previews_logger.h" #include "components/previews/core/previews_logger_observer.h" @@ -23,8 +22,7 @@ class UINetworkQualityEstimatorService; class InterventionsInternalsPageHandler : public previews::PreviewsLoggerObserver, public net::EffectiveConnectionTypeObserver, - public mojom::InterventionsInternalsPageHandler, - public MojoWebUIHandler { + public mojom::InterventionsInternalsPageHandler { public: InterventionsInternalsPageHandler( mojom::InterventionsInternalsPageHandlerRequest request, diff --git a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc index d9572b773e3..da4c18dd61f 100644 --- a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc @@ -39,6 +39,7 @@ #include "mojo/public/cpp/bindings/binding.h" #include "net/nqe/effective_connection_type.h" #include "net/nqe/network_quality_estimator_params.h" +#include "services/network/public/cpp/network_switches.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -451,8 +452,8 @@ TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsForceEctValue) { base::test::ScopedCommandLine scoped_command_line; base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); for (auto expected_ect : expected_ects) { - command_line->AppendSwitchASCII(switches::kForceEffectiveConnectionType, - expected_ect); + command_line->AppendSwitchASCII( + network::switches::kForceEffectiveConnectionType, expected_ect); page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto ect_flag = passed_in_flags.find(kEctFlagHtmlId); diff --git a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.cc b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.cc index e0b8fc7be54..b6867289c53 100644 --- a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.cc @@ -45,7 +45,8 @@ content::WebUIDataSource* GetUnsupportedSource() { } // namespace InterventionsInternalsUI::InterventionsInternalsUI(content::WebUI* web_ui) - : MojoWebUIController(web_ui), previews_ui_service_(nullptr) { + : ui::MojoWebUIController<mojom::InterventionsInternalsPageHandler>(web_ui), + previews_ui_service_(nullptr) { // Set up the chrome://interventions-internals/ source. Profile* profile = Profile::FromWebUI(web_ui); diff --git a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.h b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.h index b3d115e0430..c3b79ebcc8a 100644 --- a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.h +++ b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.h @@ -8,7 +8,7 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/interventions_internals/interventions_internals.mojom.h" #include "chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h" -#include "chrome/browser/ui/webui/mojo_web_ui_controller.h" +#include "ui/webui/mojo_web_ui_controller.h" namespace previews { class PreviewsUIService; @@ -18,13 +18,13 @@ class UINetworkQualityEstimatorService; // The WebUI for chrome://interventions-internals. class InterventionsInternalsUI - : public MojoWebUIController<mojom::InterventionsInternalsPageHandler> { + : public ui::MojoWebUIController<mojom::InterventionsInternalsPageHandler> { public: explicit InterventionsInternalsUI(content::WebUI* web_ui); ~InterventionsInternalsUI() override; private: - // MojoWebUIController overrides: + // ui::MojoWebUIController overrides: void BindUIHandler( mojom::InterventionsInternalsPageHandlerRequest request) override; diff --git a/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc b/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc index 74150647fd2..388d20b037c 100644 --- a/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc @@ -33,13 +33,13 @@ InvalidationsMessageHandler::~InvalidationsMessageHandler() { void InvalidationsMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "doneLoading", - base::Bind(&InvalidationsMessageHandler::UIReady, - base::Unretained(this))); + "doneLoading", base::BindRepeating(&InvalidationsMessageHandler::UIReady, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestDetailedStatus", - base::Bind(&InvalidationsMessageHandler::HandleRequestDetailedStatus, - base::Unretained(this))); + base::BindRepeating( + &InvalidationsMessageHandler::HandleRequestDetailedStatus, + base::Unretained(this))); } void InvalidationsMessageHandler::UIReady(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui.cc b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui.cc index 2c1cb6e3567..3edcc57d67a 100644 --- a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui.cc +++ b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui.cc @@ -20,7 +20,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" -#include "printing/features/features.h" +#include "printing/buildflags/buildflags.h" namespace { diff --git a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc index 78324376cb1..1d1f4db170d 100644 --- a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc @@ -32,7 +32,7 @@ #include "components/prefs/pref_service.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "content/public/browser/web_ui.h" -#include "printing/features/features.h" +#include "printing/buildflags/buildflags.h" #include "ui/base/l10n/l10n_util.h" #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS) @@ -119,39 +119,45 @@ bool LocalDiscoveryUIHandler::GetHasVisible() { } void LocalDiscoveryUIHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("start", base::Bind( - &LocalDiscoveryUIHandler::HandleStart, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("isVisible", base::Bind( - &LocalDiscoveryUIHandler::HandleIsVisible, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("registerDevice", base::Bind( - &LocalDiscoveryUIHandler::HandleRegisterDevice, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("cancelRegistration", base::Bind( - &LocalDiscoveryUIHandler::HandleCancelRegistration, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "start", base::BindRepeating(&LocalDiscoveryUIHandler::HandleStart, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "isVisible", + base::BindRepeating(&LocalDiscoveryUIHandler::HandleIsVisible, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "registerDevice", + base::BindRepeating(&LocalDiscoveryUIHandler::HandleRegisterDevice, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "cancelRegistration", + base::BindRepeating(&LocalDiscoveryUIHandler::HandleCancelRegistration, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestDeviceList", - base::Bind(&LocalDiscoveryUIHandler::HandleRequestDeviceList, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("openCloudPrintURL", base::Bind( - &LocalDiscoveryUIHandler::HandleOpenCloudPrintURL, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("showSyncUI", base::Bind( - &LocalDiscoveryUIHandler::HandleShowSyncUI, - base::Unretained(this))); + base::BindRepeating(&LocalDiscoveryUIHandler::HandleRequestDeviceList, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "openCloudPrintURL", + base::BindRepeating(&LocalDiscoveryUIHandler::HandleOpenCloudPrintURL, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "showSyncUI", + base::BindRepeating(&LocalDiscoveryUIHandler::HandleShowSyncUI, + base::Unretained(this))); // Cloud print connector related messages #if defined(CLOUD_PRINT_CONNECTOR_UI_AVAILABLE) web_ui()->RegisterMessageCallback( "showCloudPrintSetupDialog", - base::Bind(&LocalDiscoveryUIHandler::ShowCloudPrintSetupDialog, - base::Unretained(this))); + base::BindRepeating(&LocalDiscoveryUIHandler::ShowCloudPrintSetupDialog, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "disableCloudPrintConnector", - base::Bind(&LocalDiscoveryUIHandler::HandleDisableCloudPrintConnector, - base::Unretained(this))); + base::BindRepeating( + &LocalDiscoveryUIHandler::HandleDisableCloudPrintConnector, + base::Unretained(this))); #endif // defined(CLOUD_PRINT_CONNECTOR_UI_AVAILABLE) } diff --git a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h index 80302ce897a..29baef1168a 100644 --- a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h @@ -16,7 +16,7 @@ #include "chrome/browser/printing/cloud_print/privet_http.h" #include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/web_ui_message_handler.h" -#include "printing/features/features.h" +#include "printing/buildflags/buildflags.h" #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS) #define CLOUD_PRINT_CONNECTOR_UI_AVAILABLE diff --git a/chromium/chrome/browser/ui/webui/local_state/local_state_ui.cc b/chromium/chrome/browser/ui/webui/local_state/local_state_ui.cc index df96c79a21f..818dc70e092 100644 --- a/chromium/chrome/browser/ui/webui/local_state/local_state_ui.cc +++ b/chromium/chrome/browser/ui/webui/local_state/local_state_ui.cc @@ -57,8 +57,9 @@ LocalStateUIHandler::~LocalStateUIHandler() { void LocalStateUIHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "requestJson", base::Bind(&LocalStateUIHandler::HandleRequestJson, - base::Unretained(this))); + "requestJson", + base::BindRepeating(&LocalStateUIHandler::HandleRequestJson, + base::Unretained(this))); } void LocalStateUIHandler::HandleRequestJson(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/log_web_ui_url.cc b/chromium/chrome/browser/ui/webui/log_web_ui_url.cc index 9f7abf495e6..d4d3ba99004 100644 --- a/chromium/chrome/browser/ui/webui/log_web_ui_url.cc +++ b/chromium/chrome/browser/ui/webui/log_web_ui_url.cc @@ -10,7 +10,7 @@ #include "base/metrics/histogram_functions.h" #include "chrome/common/url_constants.h" #include "content/public/common/url_constants.h" -#include "extensions/features/features.h" +#include "extensions/buildflags/buildflags.h" #include "url/gurl.h" #if BUILDFLAG(ENABLE_EXTENSIONS) diff --git a/chromium/chrome/browser/ui/webui/log_web_ui_url_unittest.cc b/chromium/chrome/browser/ui/webui/log_web_ui_url_unittest.cc index 76a735fc102..8c9bd369d07 100644 --- a/chromium/chrome/browser/ui/webui/log_web_ui_url_unittest.cc +++ b/chromium/chrome/browser/ui/webui/log_web_ui_url_unittest.cc @@ -4,7 +4,7 @@ #include "chrome/browser/ui/webui/log_web_ui_url.h" -#include "extensions/features/features.h" +#include "extensions/buildflags/buildflags.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" diff --git a/chromium/chrome/browser/ui/webui/md_bookmarks/bookmarks_message_handler.cc b/chromium/chrome/browser/ui/webui/md_bookmarks/bookmarks_message_handler.cc index 249049ae6d7..0b19140dc23 100644 --- a/chromium/chrome/browser/ui/webui/md_bookmarks/bookmarks_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/md_bookmarks/bookmarks_message_handler.cc @@ -19,12 +19,13 @@ BookmarksMessageHandler::~BookmarksMessageHandler() {} void BookmarksMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getIncognitoAvailability", - base::Bind(&BookmarksMessageHandler::HandleGetIncognitoAvailability, - base::Unretained(this))); + base::BindRepeating( + &BookmarksMessageHandler::HandleGetIncognitoAvailability, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getCanEditBookmarks", - base::Bind(&BookmarksMessageHandler::HandleGetCanEditBookmarks, - base::Unretained(this))); + base::BindRepeating(&BookmarksMessageHandler::HandleGetCanEditBookmarks, + base::Unretained(this))); } void BookmarksMessageHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_browsertest.cc b/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_browsertest.cc index 7dea1b0f145..2a1a13f088a 100644 --- a/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_browsertest.cc @@ -18,12 +18,13 @@ MdBookmarksBrowserTest::~MdBookmarksBrowserTest() {} void MdBookmarksBrowserTest::RegisterMessages() { web_ui()->RegisterMessageCallback( "testSetIncognito", - base::Bind(&MdBookmarksBrowserTest::HandleSetIncognitoAvailability, - base::Unretained(this))); + base::BindRepeating( + &MdBookmarksBrowserTest::HandleSetIncognitoAvailability, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "testSetCanEdit", - base::Bind(&MdBookmarksBrowserTest::HandleSetCanEditBookmarks, - base::Unretained(this))); + base::BindRepeating(&MdBookmarksBrowserTest::HandleSetCanEditBookmarks, + base::Unretained(this))); } void MdBookmarksBrowserTest::SetIncognitoAvailability(int availability) { diff --git a/chromium/chrome/browser/ui/webui/md_downloads/downloads_list_tracker_unittest.cc b/chromium/chrome/browser/ui/webui/md_downloads/downloads_list_tracker_unittest.cc index 8300e101409..68a121bdfb0 100644 --- a/chromium/chrome/browser/ui/webui/md_downloads/downloads_list_tracker_unittest.cc +++ b/chromium/chrome/browser/ui/webui/md_downloads/downloads_list_tracker_unittest.cc @@ -15,7 +15,7 @@ #include "base/time/time.h" #include "chrome/browser/download/download_item_model.h" #include "chrome/test/base/testing_profile.h" -#include "content/public/test/mock_download_item.h" +#include "components/download/public/common/mock_download_item.h" #include "content/public/test/mock_download_manager.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" @@ -23,7 +23,7 @@ #include "testing/gtest/include/gtest/gtest.h" using download::DownloadItem; -using content::MockDownloadItem; +using download::MockDownloadItem; using DownloadVector = std::vector<DownloadItem*>; using testing::_; using testing::Return; diff --git a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc index 4138366f5a8..990e68a08cf 100644 --- a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc +++ b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc @@ -32,7 +32,6 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" -#include "components/download/public/common/download_danger_type.h" #include "components/download/public/common/download_item.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" @@ -77,8 +76,9 @@ MdDownloadsDOMHandler::MdDownloadsDOMHandler( content::DownloadManager* download_manager, content::WebUI* web_ui) : list_tracker_(download_manager, web_ui) { // Create our fileicon data source. - profile_ = Profile::FromBrowserContext(download_manager->GetBrowserContext()); - content::URLDataSource::Add(profile_, new FileIconSource()); + Profile* profile = + Profile::FromBrowserContext(download_manager->GetBrowserContext()); + content::URLDataSource::Add(profile, new FileIconSource()); CheckForRemovedFiles(); } @@ -89,48 +89,50 @@ MdDownloadsDOMHandler::~MdDownloadsDOMHandler() { // MdDownloadsDOMHandler, public: --------------------------------------------- void MdDownloadsDOMHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("getDownloads", - base::Bind(&MdDownloadsDOMHandler::HandleGetDownloads, - weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "getDownloads", + base::BindRepeating(&MdDownloadsDOMHandler::HandleGetDownloads, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "openFileRequiringGesture", - base::Bind(&MdDownloadsDOMHandler::HandleOpenFile, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("drag", - base::Bind(&MdDownloadsDOMHandler::HandleDrag, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&MdDownloadsDOMHandler::HandleOpenFile, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "drag", base::BindRepeating(&MdDownloadsDOMHandler::HandleDrag, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "saveDangerousRequiringGesture", - base::Bind(&MdDownloadsDOMHandler::HandleSaveDangerous, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("discardDangerous", - base::Bind(&MdDownloadsDOMHandler::HandleDiscardDangerous, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("show", - base::Bind(&MdDownloadsDOMHandler::HandleShow, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("pause", - base::Bind(&MdDownloadsDOMHandler::HandlePause, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("resume", - base::Bind(&MdDownloadsDOMHandler::HandleResume, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("remove", - base::Bind(&MdDownloadsDOMHandler::HandleRemove, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("undo", - base::Bind(&MdDownloadsDOMHandler::HandleUndo, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("cancel", - base::Bind(&MdDownloadsDOMHandler::HandleCancel, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("clearAll", - base::Bind(&MdDownloadsDOMHandler::HandleClearAll, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&MdDownloadsDOMHandler::HandleSaveDangerous, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "discardDangerous", + base::BindRepeating(&MdDownloadsDOMHandler::HandleDiscardDangerous, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "show", base::BindRepeating(&MdDownloadsDOMHandler::HandleShow, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "pause", base::BindRepeating(&MdDownloadsDOMHandler::HandlePause, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "resume", base::BindRepeating(&MdDownloadsDOMHandler::HandleResume, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "remove", base::BindRepeating(&MdDownloadsDOMHandler::HandleRemove, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "undo", base::BindRepeating(&MdDownloadsDOMHandler::HandleUndo, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "cancel", base::BindRepeating(&MdDownloadsDOMHandler::HandleCancel, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "clearAll", base::BindRepeating(&MdDownloadsDOMHandler::HandleClearAll, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "openDownloadsFolderRequiringGesture", - base::Bind(&MdDownloadsDOMHandler::HandleOpenDownloadsFolder, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&MdDownloadsDOMHandler::HandleOpenDownloadsFolder, + weak_ptr_factory_.GetWeakPtr())); Observe(GetWebUIWebContents()); } @@ -196,32 +198,8 @@ void MdDownloadsDOMHandler::HandleDrag(const base::ListValue* args) { void MdDownloadsDOMHandler::HandleSaveDangerous(const base::ListValue* args) { CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS); download::DownloadItem* file = GetDownloadByValue(args); - SaveDownload(file); -} - -void MdDownloadsDOMHandler::SaveDownload(download::DownloadItem* download) { - if (!download) - return; - // If danger type is NOT DANGEROUS_FILE, chrome shows users a download danger - // prompt. - if (download->GetDangerType() != - download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE) { - ShowDangerPrompt(download); - } else { - // If danger type is DANGEROUS_FILE, chrome proceeds to keep this download - // without showing download danger prompt. - if (profile_) { - PrefService* prefs = profile_->GetPrefs(); - if (!profile_->IsOffTheRecord() && - prefs->GetBoolean(prefs::kSafeBrowsingEnabled)) { - DownloadDangerPrompt::SendSafeBrowsingDownloadReport( - safe_browsing::ClientSafeBrowsingReportRequest:: - DANGEROUS_DOWNLOAD_RECOVERY, - true, *download); - } - } - DangerPromptDone(download->GetId(), DownloadDangerPrompt::ACCEPT); - } + if (file) + ShowDangerPrompt(file); } void MdDownloadsDOMHandler::HandleDiscardDangerous( diff --git a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.h b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.h index fd401f52edb..cdfc1342bb3 100644 --- a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.h +++ b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.h @@ -31,8 +31,6 @@ namespace download { class DownloadItem; } -class Profile; - // The handler for Javascript messages related to the "downloads" view, // also observes changes to the download manager. class MdDownloadsDOMHandler : public content::WebContentsObserver, @@ -107,9 +105,6 @@ class MdDownloadsDOMHandler : public content::WebContentsObserver, // dangerous ones are immediately removed. Protected for testing. void RemoveDownloads(const DownloadVector& to_remove); - // Helper function to handle save download event. - void SaveDownload(download::DownloadItem* download); - private: using IdSet = std::set<uint32_t>; @@ -131,8 +126,7 @@ class MdDownloadsDOMHandler : public content::WebContentsObserver, // Conveys danger acceptance from the DownloadDangerPrompt to the // DownloadItem. - virtual void DangerPromptDone(int download_id, - DownloadDangerPrompt::Action action); + void DangerPromptDone(int download_id, DownloadDangerPrompt::Action action); // Returns true if the records of any downloaded items are allowed (and able) // to be deleted. @@ -155,9 +149,6 @@ class MdDownloadsDOMHandler : public content::WebContentsObserver, // IDs of downloads to remove when this handler gets deleted. std::vector<IdSet> removals_; - // User profile that corresponds to this handler. - Profile* profile_ = nullptr; - // Whether the render process has gone. bool render_process_gone_ = false; diff --git a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler_unittest.cc b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler_unittest.cc index 5b018373bd6..a2ce777f089 100644 --- a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler_unittest.cc @@ -8,7 +8,7 @@ #include "chrome/browser/download/download_item_model.h" #include "chrome/test/base/testing_profile.h" -#include "content/public/test/mock_download_item.h" +#include "components/download/public/common/mock_download_item.h" #include "content/public/test/mock_download_manager.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" @@ -21,25 +21,11 @@ class TestMdDownloadsDOMHandler : public MdDownloadsDOMHandler { public: explicit TestMdDownloadsDOMHandler(content::DownloadManager* download_manager, content::WebUI* web_ui) - : MdDownloadsDOMHandler(download_manager, web_ui), - danger_prompt_count_(0) {} + : MdDownloadsDOMHandler(download_manager, web_ui) {} using MdDownloadsDOMHandler::set_web_ui; using MdDownloadsDOMHandler::FinalizeRemovals; using MdDownloadsDOMHandler::RemoveDownloads; - using MdDownloadsDOMHandler::SaveDownload; - - int danger_prompt_count() { return danger_prompt_count_; } - - private: - void ShowDangerPrompt(download::DownloadItem* dangerous) override { - danger_prompt_count_++; - } - - void DangerPromptDone(int download_id, - DownloadDangerPrompt::Action action) override {} - - int danger_prompt_count_; }; } // namespace @@ -92,7 +78,7 @@ TEST_F(MdDownloadsDOMHandlerTest, ClearAll) { std::vector<download::DownloadItem*> downloads; // Safe, in-progress items should be passed over. - testing::StrictMock<content::MockDownloadItem> in_progress; + testing::StrictMock<download::MockDownloadItem> in_progress; EXPECT_CALL(in_progress, IsDangerous()).WillOnce(testing::Return(false)); EXPECT_CALL(in_progress, IsTransient()).WillOnce(testing::Return(false)); EXPECT_CALL(in_progress, GetState()) @@ -100,13 +86,13 @@ TEST_F(MdDownloadsDOMHandlerTest, ClearAll) { downloads.push_back(&in_progress); // Dangerous items should be removed (regardless of state). - testing::StrictMock<content::MockDownloadItem> dangerous; + testing::StrictMock<download::MockDownloadItem> dangerous; EXPECT_CALL(dangerous, IsDangerous()).WillOnce(testing::Return(true)); EXPECT_CALL(dangerous, Remove()); downloads.push_back(&dangerous); // Completed items should be marked as hidden from the shelf. - testing::StrictMock<content::MockDownloadItem> completed; + testing::StrictMock<download::MockDownloadItem> completed; EXPECT_CALL(completed, IsDangerous()).WillOnce(testing::Return(false)); EXPECT_CALL(completed, IsTransient()).WillRepeatedly(testing::Return(false)); EXPECT_CALL(completed, GetState()) @@ -128,27 +114,3 @@ TEST_F(MdDownloadsDOMHandlerTest, ClearAll) { EXPECT_CALL(completed, Remove()); handler.FinalizeRemovals(); } - -TEST_F(MdDownloadsDOMHandlerTest, HandleSaveDownload) { - // When user chooses to recover a download, download danger prompt should NOT - // be shown if download danger type is DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE. - testing::StrictMock<content::MockDownloadItem> dangerous_file_type; - EXPECT_CALL(dangerous_file_type, GetDangerType()) - .WillRepeatedly( - testing::Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); - EXPECT_CALL(dangerous_file_type, GetId()) - .WillOnce(testing::Return(uint32_t())); - TestMdDownloadsDOMHandler handler(manager(), web_ui()); - EXPECT_EQ(0, handler.danger_prompt_count()); - handler.SaveDownload(&dangerous_file_type); - EXPECT_EQ(0, handler.danger_prompt_count()); - - // For other download danger types, download danger prompt should - // be shown. - testing::StrictMock<content::MockDownloadItem> malicious_download; - EXPECT_CALL(malicious_download, GetDangerType()) - .WillRepeatedly( - testing::Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL)); - handler.SaveDownload(&malicious_download); - EXPECT_EQ(1, handler.danger_prompt_count()); -} diff --git a/chromium/chrome/browser/ui/webui/md_history_ui.cc b/chromium/chrome/browser/ui/webui/md_history_ui.cc index e59e7fa2e37..d24d3ba8eac 100644 --- a/chromium/chrome/browser/ui/webui/md_history_ui.cc +++ b/chromium/chrome/browser/ui/webui/md_history_ui.cc @@ -208,8 +208,9 @@ MdHistoryUI::MdHistoryUI(content::WebUI* web_ui) : WebUIController(web_ui) { web_ui->AddMessageHandler(std::make_unique<HistoryLoginHandler>( base::Bind(&MdHistoryUI::UpdateDataSource, base::Unretained(this)))); - web_ui->RegisterMessageCallback("menuPromoShown", - base::Bind(&MdHistoryUI::HandleMenuPromoShown, base::Unretained(this))); + web_ui->RegisterMessageCallback( + "menuPromoShown", base::BindRepeating(&MdHistoryUI::HandleMenuPromoShown, + base::Unretained(this))); } MdHistoryUI::~MdHistoryUI() {} diff --git a/chromium/chrome/browser/ui/webui/media/media_engagement_ui.cc b/chromium/chrome/browser/ui/webui/media/media_engagement_ui.cc index 9bf372c9b25..c021c705ff8 100644 --- a/chromium/chrome/browser/ui/webui/media/media_engagement_ui.cc +++ b/chromium/chrome/browser/ui/webui/media/media_engagement_ui.cc @@ -64,8 +64,8 @@ class MediaEngagementScoreDetailsProviderImpl } // namespace MediaEngagementUI::MediaEngagementUI(content::WebUI* web_ui) - : MojoWebUIController<media::mojom::MediaEngagementScoreDetailsProvider>( - web_ui) { + : ui::MojoWebUIController< + media::mojom::MediaEngagementScoreDetailsProvider>(web_ui) { // Setup the data source behind chrome://media-engagement. std::unique_ptr<content::WebUIDataSource> source( content::WebUIDataSource::Create(chrome::kChromeUIMediaEngagementHost)); diff --git a/chromium/chrome/browser/ui/webui/media/media_engagement_ui.h b/chromium/chrome/browser/ui/webui/media/media_engagement_ui.h index 6cdf939b6dd..b8a46c43b14 100644 --- a/chromium/chrome/browser/ui/webui/media/media_engagement_ui.h +++ b/chromium/chrome/browser/ui/webui/media/media_engagement_ui.h @@ -7,18 +7,18 @@ #include "base/macros.h" #include "chrome/browser/media/media_engagement_score_details.mojom.h" -#include "chrome/browser/ui/webui/mojo_web_ui_controller.h" +#include "ui/webui/mojo_web_ui_controller.h" // The UI for chrome://media-engagement/. class MediaEngagementUI - : public MojoWebUIController< + : public ui::MojoWebUIController< media::mojom::MediaEngagementScoreDetailsProvider> { public: explicit MediaEngagementUI(content::WebUI* web_ui); ~MediaEngagementUI() override; private: - // MojoWebUIController overrides: + // ui::MojoWebUIController overrides: void BindUIHandler(media::mojom::MediaEngagementScoreDetailsProviderRequest request) override; diff --git a/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc b/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc index 782ea7d2fe4..43e045c5615 100644 --- a/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc +++ b/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc @@ -126,9 +126,10 @@ void WebRtcLogsDOMHandler::RegisterMessages() { upload_list_->Load(base::BindOnce( &WebRtcLogsDOMHandler::OnUploadListAvailable, base::Unretained(this))); - web_ui()->RegisterMessageCallback("requestWebRtcLogsList", - base::Bind(&WebRtcLogsDOMHandler::HandleRequestWebRtcLogs, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "requestWebRtcLogsList", + base::BindRepeating(&WebRtcLogsDOMHandler::HandleRequestWebRtcLogs, + base::Unretained(this))); } void WebRtcLogsDOMHandler::HandleRequestWebRtcLogs( diff --git a/chromium/chrome/browser/ui/webui/media_router/cast_modes_with_media_sources.cc b/chromium/chrome/browser/ui/webui/media_router/cast_modes_with_media_sources.cc deleted file mode 100644 index 09aa90a0d7b..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/cast_modes_with_media_sources.cc +++ /dev/null @@ -1,49 +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 "base/stl_util.h" -#include "chrome/browser/ui/webui/media_router/cast_modes_with_media_sources.h" - -namespace media_router { - -CastModesWithMediaSources::CastModesWithMediaSources() {} -CastModesWithMediaSources::CastModesWithMediaSources( - CastModesWithMediaSources&& other) = default; -CastModesWithMediaSources::~CastModesWithMediaSources() {} - -void CastModesWithMediaSources::AddSource(MediaCastMode cast_mode, - const MediaSource& source) { - cast_modes_[cast_mode].insert(source); -} - -void CastModesWithMediaSources::RemoveSource(MediaCastMode cast_mode, - const MediaSource& source) { - const auto& cast_mode_it = cast_modes_.find(cast_mode); - if (cast_mode_it != cast_modes_.end()) { - auto& sources_for_cast_mode = cast_mode_it->second; - sources_for_cast_mode.erase(source); - if (sources_for_cast_mode.empty()) - cast_modes_.erase(cast_mode); - } -} - -bool CastModesWithMediaSources::HasSource(MediaCastMode cast_mode, - const MediaSource& source) const { - return base::ContainsKey(cast_modes_, cast_mode) - ? base::ContainsKey(cast_modes_.at(cast_mode), source) - : false; -} - -CastModeSet CastModesWithMediaSources::GetCastModes() const { - CastModeSet cast_mode_set; - for (const auto& cast_mode_pair : cast_modes_) - cast_mode_set.insert(cast_mode_pair.first); - return cast_mode_set; -} - -bool CastModesWithMediaSources::IsEmpty() const { - return cast_modes_.empty(); -} - -} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/cast_modes_with_media_sources.h b/chromium/chrome/browser/ui/webui/media_router/cast_modes_with_media_sources.h deleted file mode 100644 index d6fb466101f..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/cast_modes_with_media_sources.h +++ /dev/null @@ -1,49 +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 CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_CAST_MODES_WITH_MEDIA_SOURCES_H_ -#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_CAST_MODES_WITH_MEDIA_SOURCES_H_ - -#include <map> -#include <unordered_set> - -#include "chrome/browser/ui/webui/media_router/media_cast_mode.h" -#include "chrome/common/media_router/media_source.h" - -namespace media_router { - -// Contains information on cast modes and the sources associated with them. -// Each cast mode contained has at least one source. -class CastModesWithMediaSources { - public: - CastModesWithMediaSources(); - CastModesWithMediaSources(CastModesWithMediaSources&& other); - ~CastModesWithMediaSources(); - - // Adds a source for the cast mode. - void AddSource(MediaCastMode cast_mode, const MediaSource& source); - - // Removes a source from the cast mode. The cast mode will also get removed if - // it has no other sources. This is a no-op if the source is not found. - void RemoveSource(MediaCastMode cast_mode, const MediaSource& source); - - // Returns true if the source for the cast mode is contained. - bool HasSource(MediaCastMode cast_mode, const MediaSource& source) const; - - // Returns a set of all the cast modes contained. - CastModeSet GetCastModes() const; - - // Returns true if there are no cast modes contained. - bool IsEmpty() const; - - private: - std::map<MediaCastMode, std::unordered_set<MediaSource, MediaSource::Hash>> - cast_modes_; - - DISALLOW_COPY_AND_ASSIGN(CastModesWithMediaSources); -}; - -} // namespace media_router - -#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_CAST_MODES_WITH_MEDIA_SOURCES_H_ diff --git a/chromium/chrome/browser/ui/webui/media_router/cast_modes_with_media_sources_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/cast_modes_with_media_sources_unittest.cc deleted file mode 100644 index 9c428568e90..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/cast_modes_with_media_sources_unittest.cc +++ /dev/null @@ -1,89 +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 "chrome/browser/ui/webui/media_router/cast_modes_with_media_sources.h" - -#include "chrome/common/media_router/media_source_helper.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace media_router { - -TEST(MediaRouterCastModesWithMediaSourcesTest, AddAndRemoveSources) { - const MediaSource presentationSource1(MediaSourceForPresentationUrl( - GURL("http://www.example.com/presentation.html"))); - const MediaSource presentationSource2(MediaSourceForPresentationUrl( - GURL("http://www.example.net/presentation.html"))); - const MediaSource tabSourceA(MediaSourceForTab(123)); - const CastModeSet castModeSetEmpty; - const CastModeSet castModeSetPresentation({MediaCastMode::PRESENTATION}); - const CastModeSet castModeSetTab({MediaCastMode::TAB_MIRROR}); - const CastModeSet castModeSetPresentationAndTab( - {MediaCastMode::PRESENTATION, MediaCastMode::TAB_MIRROR}); - - CastModesWithMediaSources sources; - EXPECT_TRUE(sources.IsEmpty()); - EXPECT_EQ(sources.GetCastModes(), castModeSetEmpty); - - // After the below addition, |sources| should contain: - // [Presentation: 1] - sources.AddSource(MediaCastMode::PRESENTATION, presentationSource1); - EXPECT_TRUE( - sources.HasSource(MediaCastMode::PRESENTATION, presentationSource1)); - EXPECT_FALSE( - sources.HasSource(MediaCastMode::PRESENTATION, presentationSource2)); - EXPECT_FALSE( - sources.HasSource(MediaCastMode::TAB_MIRROR, presentationSource1)); - EXPECT_FALSE(sources.IsEmpty()); - EXPECT_EQ(sources.GetCastModes(), castModeSetPresentation); - - // Trying to remove non-existing sources should be no-op. - sources.RemoveSource(MediaCastMode::PRESENTATION, presentationSource2); - sources.RemoveSource(MediaCastMode::TAB_MIRROR, presentationSource1); - sources.RemoveSource(MediaCastMode::TAB_MIRROR, tabSourceA); - EXPECT_TRUE( - sources.HasSource(MediaCastMode::PRESENTATION, presentationSource1)); - EXPECT_EQ(sources.GetCastModes(), castModeSetPresentation); - - // [Presentation: 1; Tab: A] - sources.AddSource(MediaCastMode::TAB_MIRROR, tabSourceA); - EXPECT_TRUE( - sources.HasSource(MediaCastMode::PRESENTATION, presentationSource1)); - EXPECT_TRUE(sources.HasSource(MediaCastMode::TAB_MIRROR, tabSourceA)); - EXPECT_EQ(sources.GetCastModes(), castModeSetPresentationAndTab); - - // [Presentation: 1,2; Tab: A] - sources.AddSource(MediaCastMode::PRESENTATION, presentationSource2); - EXPECT_TRUE( - sources.HasSource(MediaCastMode::PRESENTATION, presentationSource2)); - EXPECT_EQ(sources.GetCastModes(), castModeSetPresentationAndTab); - - // [Presentation: 2; Tab: A] - sources.RemoveSource(MediaCastMode::PRESENTATION, presentationSource1); - EXPECT_FALSE( - sources.HasSource(MediaCastMode::PRESENTATION, presentationSource1)); - EXPECT_TRUE( - sources.HasSource(MediaCastMode::PRESENTATION, presentationSource2)); - EXPECT_EQ(sources.GetCastModes(), castModeSetPresentationAndTab); - - // [Tab: A] - sources.RemoveSource(MediaCastMode::PRESENTATION, presentationSource2); - EXPECT_FALSE( - sources.HasSource(MediaCastMode::PRESENTATION, presentationSource1)); - EXPECT_FALSE(sources.IsEmpty()); - EXPECT_EQ(sources.GetCastModes(), castModeSetTab); - - // [] - sources.RemoveSource(MediaCastMode::TAB_MIRROR, tabSourceA); - EXPECT_FALSE( - sources.HasSource(MediaCastMode::PRESENTATION, presentationSource1)); - EXPECT_FALSE( - sources.HasSource(MediaCastMode::PRESENTATION, presentationSource2)); - EXPECT_FALSE(sources.HasSource(MediaCastMode::TAB_MIRROR, tabSourceA)); - EXPECT_TRUE(sources.IsEmpty()); - EXPECT_EQ(sources.GetCastModes(), castModeSetEmpty); -} - -} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_cast_mode.cc b/chromium/chrome/browser/ui/webui/media_router/media_cast_mode.cc deleted file mode 100644 index 7a5a75a9635..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/media_cast_mode.cc +++ /dev/null @@ -1,45 +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/ui/webui/media_router/media_cast_mode.h" - -#include "base/logging.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/grit/generated_resources.h" -#include "ui/base/l10n/l10n_util.h" - -namespace media_router { - -std::string MediaCastModeToDescription(MediaCastMode mode, - const std::string& host) { - switch (mode) { - case MediaCastMode::PRESENTATION: - return l10n_util::GetStringFUTF8(IDS_MEDIA_ROUTER_PRESENTATION_CAST_MODE, - base::UTF8ToUTF16(host)); - case MediaCastMode::TAB_MIRROR: - return l10n_util::GetStringUTF8(IDS_MEDIA_ROUTER_TAB_MIRROR_CAST_MODE); - case MediaCastMode::DESKTOP_MIRROR: - return l10n_util::GetStringUTF8( - IDS_MEDIA_ROUTER_DESKTOP_MIRROR_CAST_MODE); - case MediaCastMode::LOCAL_FILE: - return l10n_util::GetStringUTF8(IDS_MEDIA_ROUTER_LOCAL_FILE_CAST_MODE); - default: - NOTREACHED(); - return ""; - } -} - -bool IsValidCastModeNum(int cast_mode_num) { - switch (cast_mode_num) { - case MediaCastMode::PRESENTATION: - case MediaCastMode::TAB_MIRROR: - case MediaCastMode::DESKTOP_MIRROR: - case MediaCastMode::LOCAL_FILE: - return true; - default: - return false; - } -} - -} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_cast_mode.h b/chromium/chrome/browser/ui/webui/media_router/media_cast_mode.h deleted file mode 100644 index 3916ab98abb..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/media_cast_mode.h +++ /dev/null @@ -1,45 +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_UI_WEBUI_MEDIA_ROUTER_MEDIA_CAST_MODE_H_ -#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_CAST_MODE_H_ - -#include <set> -#include <string> - -namespace media_router { - -// A cast mode represents one way that the current WebContents (i.e., tab) may -// be presented to a media sink. These must be declared in the priority order -// returned by GetPreferredCastMode. -enum MediaCastMode { - // PresentationRequests (and their associated URLs) provided via the - // Presentation API. A top-level browsing context can set a - // PresentationRequest as the page-level default, or any frame can use one by - // calling PresentationRequest.start(). Available when the Presentation API - // is used and there is a compatible sink. - PRESENTATION = 0x1, - // Capture the rendered WebContents and stream it to a media sink. Available - // when there is a compatible sink. - TAB_MIRROR = 0x2, - // Capture the entire desktop and stream it to a media sink. Available when - // there is a compatible sink. - DESKTOP_MIRROR = 0x4, - // Take a local media file to open in a tab and cast. - LOCAL_FILE = 0x8, -}; - -using CastModeSet = std::set<MediaCastMode>; - -// Returns a localized description string for |mode| and |host| -// (e.g. google.com). -std::string MediaCastModeToDescription(MediaCastMode mode, - const std::string& host); - -// Returns true if |cast_mode_num| is a valid MediaCastMode, false otherwise. -bool IsValidCastModeNum(int cast_mode_num); - -} // namespace media_router - -#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_CAST_MODE_H_ diff --git a/chromium/chrome/browser/ui/webui/media_router/media_cast_mode_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_cast_mode_unittest.cc deleted file mode 100644 index b7b93f0fa18..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/media_cast_mode_unittest.cc +++ /dev/null @@ -1,33 +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/ui/webui/media_router/media_cast_mode.h" - -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::Not; -using testing::HasSubstr; - -namespace media_router { - -TEST(MediaCastModeTest, MediaCastModeToDescription) { - EXPECT_FALSE( - MediaCastModeToDescription(MediaCastMode::PRESENTATION, "youtube.com") - .empty()); - EXPECT_FALSE( - MediaCastModeToDescription(MediaCastMode::TAB_MIRROR, "").empty()); - EXPECT_FALSE( - MediaCastModeToDescription(MediaCastMode::DESKTOP_MIRROR, "").empty()); -} - -TEST(MediaCastModeTest, IsValidCastModeNum) { - EXPECT_TRUE(IsValidCastModeNum(MediaCastMode::PRESENTATION)); - EXPECT_TRUE(IsValidCastModeNum(MediaCastMode::TAB_MIRROR)); - EXPECT_TRUE(IsValidCastModeNum(MediaCastMode::DESKTOP_MIRROR)); - EXPECT_FALSE(IsValidCastModeNum(-1)); - EXPECT_FALSE(IsValidCastModeNum(666)); -} - -} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.h b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.h deleted file mode 100644 index 1d21c0886b9..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.h +++ /dev/null @@ -1,92 +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_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_IMPL_H_ -#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_IMPL_H_ - -#include "base/gtest_prod_util.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/media/router/media_router_dialog_controller.h" -#include "content/public/browser/web_contents_observer.h" -#include "content/public/browser/web_contents_user_data.h" - -FORWARD_DECLARE_TEST(MediaRouterActionUnitTest, IconPressedState); - -class MediaRouterAction; -class MediaRouterActionController; - -namespace media_router { - -// A desktop implementation of MediaRouterDialogController. -// This class is not thread safe and must be called on the UI thread. -class MediaRouterDialogControllerImpl : - public content::WebContentsUserData<MediaRouterDialogControllerImpl>, - public MediaRouterDialogController { - public: - ~MediaRouterDialogControllerImpl() override; - - static MediaRouterDialogControllerImpl* GetOrCreateForWebContents( - content::WebContents* web_contents); - - // Returns the media router dialog WebContents. - // Returns nullptr if there is no dialog. - content::WebContents* GetMediaRouterDialog() const; - - // Sets the action to notify when a dialog gets shown or hidden. - void SetMediaRouterAction(const base::WeakPtr<MediaRouterAction>& action); - - // MediaRouterDialogController: - bool IsShowingMediaRouterDialog() const override; - - void UpdateMaxDialogSize(); - - MediaRouterAction* action() { return action_.get(); } - - private: - class DialogWebContentsObserver; - friend class content::WebContentsUserData<MediaRouterDialogControllerImpl>; - FRIEND_TEST_ALL_PREFIXES(::MediaRouterActionUnitTest, IconPressedState); - - // Use MediaRouterDialogControllerImpl::CreateForWebContents() to create an - // instance. - explicit MediaRouterDialogControllerImpl(content::WebContents* web_contents); - - // MediaRouterDialogController: - void CreateMediaRouterDialog() override; - void CloseMediaRouterDialog() override; - void Reset() override; - - // Invoked when the dialog WebContents has navigated. - void OnDialogNavigated(const content::LoadCommittedDetails& details); - - void PopulateDialog(content::WebContents* media_router_dialog); - - std::unique_ptr<DialogWebContentsObserver> dialog_observer_; - - // True if the controller is waiting for a new media router dialog to be - // created. - bool media_router_dialog_pending_; - - // |action_| refers to the MediaRouterAction on the toolbar, rather than - // overflow menu. A MediaRouterAction is always created for the toolbar - // first. Any subsequent creations for the overflow menu will not be set as - // |action_|. - // The lifetime of |action_| is dependent on the creation and destruction of - // a browser window. The overflow menu's MediaRouterAction is only created - // when the overflow menu is opened and destroyed when the menu is closed. - base::WeakPtr<MediaRouterAction> action_; - - // |action_controller_| is responsible for showing and hiding the toolbar - // action. It's owned by MediaRouterUIService, which outlives |this|. - MediaRouterActionController* action_controller_; - - base::WeakPtrFactory<MediaRouterDialogControllerImpl> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogControllerImpl); -}; - -} // namespace media_router - -#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_IMPL_H_ diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.cc index 18164fcace6..438bde5b358 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.cc @@ -2,27 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.h" +#include "chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h" #include <memory> #include <string> #include <utility> #include <vector> -#include "base/macros.h" #include "base/trace_event/trace_event.h" -#include "build/build_config.h" -#include "chrome/browser/media/router/presentation/presentation_service_delegate_impl.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/toolbar/media_router_action.h" #include "chrome/browser/ui/webui/constrained_web_dialog_ui.h" #include "chrome/browser/ui/webui/media_router/media_router_ui.h" -#include "chrome/browser/ui/webui/media_router/media_router_ui_service.h" #include "chrome/common/url_constants.h" #include "components/guest_view/browser/guest_view_base.h" #include "components/web_modal/web_contents_modal_dialog_host.h" +#include "content/public/browser/browser_thread.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_details.h" @@ -35,7 +32,7 @@ #include "url/gurl.h" DEFINE_WEB_CONTENTS_USER_DATA_KEY( - media_router::MediaRouterDialogControllerImpl); + media_router::MediaRouterDialogControllerWebUIImpl); using content::LoadCommittedDetails; using content::NavigationController; @@ -56,7 +53,7 @@ constexpr const int kWidth = 340; class MediaRouterDialogDelegate : public WebDialogDelegate { public: explicit MediaRouterDialogDelegate( - const base::WeakPtr<MediaRouterDialogControllerImpl>& controller) + const base::WeakPtr<MediaRouterDialogControllerWebUIImpl>& controller) : controller_(controller) {} ~MediaRouterDialogDelegate() override {} @@ -66,9 +63,7 @@ class MediaRouterDialogDelegate : public WebDialogDelegate { return ui::MODAL_TYPE_WINDOW; } - base::string16 GetDialogTitle() const override { - return base::string16(); - } + base::string16 GetDialogTitle() const override { return base::string16(); } GURL GetDialogContentURL() const override { return GURL(chrome::kChromeUIMediaRouterURL); @@ -91,9 +86,7 @@ class MediaRouterDialogDelegate : public WebDialogDelegate { controller_->UpdateMaxDialogSize(); } - std::string GetDialogArgs() const override { - return std::string(); - } + std::string GetDialogArgs() const override { return std::string(); } void OnDialogClosed(const std::string& json_retval) override { // We don't delete |this| here because this class is owned @@ -105,44 +98,35 @@ class MediaRouterDialogDelegate : public WebDialogDelegate { *out_close_dialog = true; } - bool ShouldShowDialogTitle() const override { - return false; - } + bool ShouldShowDialogTitle() const override { return false; } private: base::WeakPtr<MediaRouterAction> action_; - base::WeakPtr<MediaRouterDialogControllerImpl> controller_; + base::WeakPtr<MediaRouterDialogControllerWebUIImpl> controller_; DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogDelegate); }; -MediaRouterActionController* GetActionController(WebContents* web_contents) { - Profile* profile = - Profile::FromBrowserContext(web_contents->GetBrowserContext()); - return MediaRouterUIService::Get(profile)->action_controller(); -} - } // namespace +#if !defined(TOOLKIT_VIEWS) // static -MediaRouterDialogControllerImpl* -MediaRouterDialogControllerImpl::GetOrCreateForWebContents( - WebContents* web_contents) { - DCHECK(web_contents); - // This call does nothing if the controller already exists. - MediaRouterDialogControllerImpl::CreateForWebContents(web_contents); - return MediaRouterDialogControllerImpl::FromWebContents(web_contents); +MediaRouterDialogControllerImplBase* +MediaRouterDialogControllerImplBase::GetOrCreateForWebContents( + content::WebContents* web_contents) { + return MediaRouterDialogControllerWebUIImpl::GetOrCreateForWebContents( + web_contents); } +#endif // !defined(TOOLKIT_VIEWS) -class MediaRouterDialogControllerImpl::DialogWebContentsObserver +class MediaRouterDialogControllerWebUIImpl::DialogWebContentsObserver : public content::WebContentsObserver { public: DialogWebContentsObserver( WebContents* web_contents, - MediaRouterDialogControllerImpl* dialog_controller) + MediaRouterDialogControllerWebUIImpl* dialog_controller) : content::WebContentsObserver(web_contents), - dialog_controller_(dialog_controller) { - } + dialog_controller_(dialog_controller) {} private: void WebContentsDestroyed() override { @@ -151,8 +135,8 @@ class MediaRouterDialogControllerImpl::DialogWebContentsObserver dialog_controller_->Reset(); } - void NavigationEntryCommitted(const LoadCommittedDetails& load_details) - override { + void NavigationEntryCommitted( + const LoadCommittedDetails& load_details) override { dialog_controller_->OnDialogNavigated(load_details); } @@ -161,78 +145,32 @@ class MediaRouterDialogControllerImpl::DialogWebContentsObserver dialog_controller_->CloseMediaRouterDialog(); } - MediaRouterDialogControllerImpl* const dialog_controller_; + MediaRouterDialogControllerWebUIImpl* const dialog_controller_; }; -MediaRouterDialogControllerImpl::MediaRouterDialogControllerImpl( - WebContents* web_contents) - : MediaRouterDialogController(web_contents), - media_router_dialog_pending_(false), - action_controller_(GetActionController(web_contents)), - weak_ptr_factory_(this) { - DCHECK(action_controller_); +// static +MediaRouterDialogControllerWebUIImpl* +MediaRouterDialogControllerWebUIImpl::GetOrCreateForWebContents( + content::WebContents* web_contents) { + DCHECK(web_contents); + // This call does nothing if the controller already exists. + MediaRouterDialogControllerWebUIImpl::CreateForWebContents(web_contents); + return MediaRouterDialogControllerWebUIImpl::FromWebContents(web_contents); } -MediaRouterDialogControllerImpl::~MediaRouterDialogControllerImpl() { +MediaRouterDialogControllerWebUIImpl::~MediaRouterDialogControllerWebUIImpl() { Reset(); } -WebContents* MediaRouterDialogControllerImpl::GetMediaRouterDialog() const { +WebContents* MediaRouterDialogControllerWebUIImpl::GetMediaRouterDialog() + const { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); return dialog_observer_.get() ? dialog_observer_->web_contents() : nullptr; } -void MediaRouterDialogControllerImpl::SetMediaRouterAction( - const base::WeakPtr<MediaRouterAction>& action) { - action_ = action; -} - -bool MediaRouterDialogControllerImpl::IsShowingMediaRouterDialog() const { - return GetMediaRouterDialog() != nullptr; -} - -void MediaRouterDialogControllerImpl::UpdateMaxDialogSize() { - WebContents* media_router_dialog = GetMediaRouterDialog(); - if (!media_router_dialog) - return; +void MediaRouterDialogControllerWebUIImpl::CreateMediaRouterDialog() { + MediaRouterDialogControllerImplBase::CreateMediaRouterDialog(); - content::WebUI* web_ui = media_router_dialog->GetWebUI(); - if (web_ui) { - MediaRouterUI* media_router_ui = - static_cast<MediaRouterUI*>(web_ui->GetController()); - if (media_router_ui) { - Browser* browser = chrome::FindBrowserWithWebContents(initiator()); - web_modal::WebContentsModalDialogHost* host = nullptr; - if (browser) - host = browser->window()->GetWebContentsModalDialogHost(); - - gfx::Size maxSize = host ? - host->GetMaximumDialogSize() : - initiator()->GetContainerBounds().size(); - - // The max height of the dialog should be 90% of the browser window - // height. The width stays fixed. - maxSize.Enlarge(0, -0.1 * maxSize.height()); - media_router_ui->UpdateMaxDialogHeight(maxSize.height()); - } - } -} - -void MediaRouterDialogControllerImpl::CloseMediaRouterDialog() { - WebContents* media_router_dialog = GetMediaRouterDialog(); - if (!media_router_dialog) - return; - - content::WebUI* web_ui = media_router_dialog->GetWebUI(); - if (web_ui) { - MediaRouterUI* media_router_ui = - static_cast<MediaRouterUI*>(web_ui->GetController()); - if (media_router_ui) - media_router_ui->Close(); - } -} - -void MediaRouterDialogControllerImpl::CreateMediaRouterDialog() { DCHECK(!dialog_observer_.get()); base::Time dialog_creation_time = base::Time::Now(); @@ -256,7 +194,7 @@ void MediaRouterDialogControllerImpl::CreateMediaRouterDialog() { ConstrainedWebDialogDelegate* constrained_delegate = ShowConstrainedWebDialogWithAutoResize( profile, web_dialog_delegate, initiator(), - gfx::Size(kWidth, kMinHeight), gfx::Size(kWidth, kMaxHeight)); + gfx::Size(kWidth, kMinHeight), gfx::Size(kWidth, kMaxHeight)); WebContents* media_router_dialog = constrained_delegate->GetWebContents(); TRACE_EVENT_NESTABLE_ASYNC_INSTANT1("media_router", "UI", initiator(), @@ -282,25 +220,64 @@ void MediaRouterDialogControllerImpl::CreateMediaRouterDialog() { dialog_observer_ = std::make_unique<DialogWebContentsObserver>(media_router_dialog, this); - - // The |action_controller_| must be notified after |action_| to avoid a UI - // bug in which the drop shadow is drawn in an incorrect position. - if (action_) - action_->OnDialogShown(); - action_controller_->OnDialogShown(); } -void MediaRouterDialogControllerImpl::Reset() { - if (IsShowingMediaRouterDialog()) { - if (action_) - action_->OnDialogHidden(); - action_controller_->OnDialogHidden(); +void MediaRouterDialogControllerWebUIImpl::CloseMediaRouterDialog() { + WebContents* media_router_dialog = GetMediaRouterDialog(); + if (!media_router_dialog) + return; + + content::WebUI* web_ui = media_router_dialog->GetWebUI(); + if (web_ui) { + MediaRouterUI* media_router_ui = + static_cast<MediaRouterUI*>(web_ui->GetController()); + if (media_router_ui) + media_router_ui->Close(); } - MediaRouterDialogController::Reset(); +} + +bool MediaRouterDialogControllerWebUIImpl::IsShowingMediaRouterDialog() const { + return GetMediaRouterDialog() != nullptr; +} + +void MediaRouterDialogControllerWebUIImpl::Reset() { + MediaRouterDialogControllerImplBase::Reset(); dialog_observer_.reset(); } -void MediaRouterDialogControllerImpl::OnDialogNavigated( +void MediaRouterDialogControllerWebUIImpl::UpdateMaxDialogSize() { + WebContents* media_router_dialog = GetMediaRouterDialog(); + if (!media_router_dialog) + return; + + content::WebUI* web_ui = media_router_dialog->GetWebUI(); + if (web_ui) { + MediaRouterUI* media_router_ui = + static_cast<MediaRouterUI*>(web_ui->GetController()); + if (media_router_ui) { + Browser* browser = chrome::FindBrowserWithWebContents(initiator()); + web_modal::WebContentsModalDialogHost* host = nullptr; + if (browser) + host = browser->window()->GetWebContentsModalDialogHost(); + + gfx::Size maxSize = host ? host->GetMaximumDialogSize() + : initiator()->GetContainerBounds().size(); + + // The max height of the dialog should be 90% of the browser window + // height. The width stays fixed. + maxSize.Enlarge(0, -0.1 * maxSize.height()); + media_router_ui->UpdateMaxDialogHeight(maxSize.height()); + } + } +} + +MediaRouterDialogControllerWebUIImpl::MediaRouterDialogControllerWebUIImpl( + WebContents* web_contents) + : MediaRouterDialogControllerImplBase(web_contents), + media_router_dialog_pending_(false), + weak_ptr_factory_(this) {} + +void MediaRouterDialogControllerWebUIImpl::OnDialogNavigated( const content::LoadCommittedDetails& details) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); WebContents* media_router_dialog = GetMediaRouterDialog(); @@ -312,7 +289,7 @@ void MediaRouterDialogControllerImpl::OnDialogNavigated( DCHECK(media_router_dialog_pending_); DCHECK(ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_AUTO_TOPLEVEL) && - nav_type == content::NAVIGATION_TYPE_NEW_PAGE) + nav_type == content::NAVIGATION_TYPE_NEW_PAGE) << "transition_type: " << transition_type << ", " << "nav_type: " << nav_type; @@ -321,7 +298,7 @@ void MediaRouterDialogControllerImpl::OnDialogNavigated( PopulateDialog(media_router_dialog); } -void MediaRouterDialogControllerImpl::PopulateDialog( +void MediaRouterDialogControllerWebUIImpl::PopulateDialog( content::WebContents* media_router_dialog) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(media_router_dialog); @@ -334,15 +311,7 @@ void MediaRouterDialogControllerImpl::PopulateDialog( media_router_dialog->GetWebUI()->GetController()); DCHECK(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)); - } + InitializeMediaRouterUI(media_router_ui); } } // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h new file mode 100644 index 00000000000..13fab971ef0 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h @@ -0,0 +1,73 @@ +// 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_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_WEBUI_IMPL_H_ +#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_WEBUI_IMPL_H_ + +#include <memory> + +#include "base/gtest_prod_util.h" +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.h" +#include "content/public/browser/web_contents_observer.h" +#include "content/public/browser/web_contents_user_data.h" + +FORWARD_DECLARE_TEST(MediaRouterActionUnitTest, IconPressedState); + +namespace media_router { + +// A WebUI implementation of MediaRouterDialogController. +// This class is not thread safe and must be called on the UI thread. +class MediaRouterDialogControllerWebUIImpl + : public content::WebContentsUserData<MediaRouterDialogControllerWebUIImpl>, + public MediaRouterDialogControllerImplBase { + public: + static MediaRouterDialogControllerWebUIImpl* GetOrCreateForWebContents( + content::WebContents* web_contents); + + ~MediaRouterDialogControllerWebUIImpl() override; + + // Returns the media router dialog WebContents. + // Returns nullptr if there is no dialog. + content::WebContents* GetMediaRouterDialog() const; + + // MediaRouterDialogController: + void CreateMediaRouterDialog() override; + void CloseMediaRouterDialog() override; + bool IsShowingMediaRouterDialog() const override; + void Reset() override; + + void UpdateMaxDialogSize(); + + private: + class DialogWebContentsObserver; + friend class content::WebContentsUserData< + MediaRouterDialogControllerWebUIImpl>; + FRIEND_TEST_ALL_PREFIXES(::MediaRouterActionUnitTest, IconPressedState); + + // Use MediaRouterDialogControllerWebUIImpl::CreateForWebContents() to create + // an instance. + explicit MediaRouterDialogControllerWebUIImpl( + content::WebContents* web_contents); + + // Invoked when the dialog WebContents has navigated. + void OnDialogNavigated(const content::LoadCommittedDetails& details); + + void PopulateDialog(content::WebContents* media_router_dialog); + + std::unique_ptr<DialogWebContentsObserver> dialog_observer_; + + // True if the controller is waiting for a new media router dialog to be + // created. + bool media_router_dialog_pending_; + + base::WeakPtrFactory<MediaRouterDialogControllerWebUIImpl> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogControllerWebUIImpl); +}; + +} // namespace media_router + +#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_WEBUI_IMPL_H_ diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl_browsertest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_browsertest.cc index 202d76bfa20..85a1ce528d0 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_browsertest.cc @@ -6,7 +6,7 @@ #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.h" +#include "chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h" #include "chrome/browser/ui/webui/media_router/media_router_ui.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" @@ -19,13 +19,14 @@ using content::TestNavigationObserver; namespace media_router { -class MediaRouterDialogControllerBrowserTest : public InProcessBrowserTest { +class MediaRouterDialogControllerWebUIBrowserTest + : public InProcessBrowserTest { public: - MediaRouterDialogControllerBrowserTest() + MediaRouterDialogControllerWebUIBrowserTest() : dialog_controller_(nullptr), initiator_(nullptr), media_router_dialog_(nullptr) {} - ~MediaRouterDialogControllerBrowserTest() override {} + ~MediaRouterDialogControllerWebUIBrowserTest() override {} protected: void SetUpOnMainThread() override { @@ -35,9 +36,9 @@ class MediaRouterDialogControllerBrowserTest : public InProcessBrowserTest { initiator_ = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(initiator_); - MediaRouterDialogControllerImpl::CreateForWebContents(initiator_); + MediaRouterDialogControllerWebUIImpl::CreateForWebContents(initiator_); dialog_controller_ = - MediaRouterDialogControllerImpl::FromWebContents(initiator_); + MediaRouterDialogControllerWebUIImpl::FromWebContents(initiator_); ASSERT_TRUE(dialog_controller_); // Get the media router dialog for the initiator. @@ -46,15 +47,16 @@ class MediaRouterDialogControllerBrowserTest : public InProcessBrowserTest { ASSERT_TRUE(media_router_dialog_); } - MediaRouterDialogControllerImpl* dialog_controller_; + MediaRouterDialogControllerWebUIImpl* dialog_controller_; WebContents* initiator_; WebContents* media_router_dialog_; private: - DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogControllerBrowserTest); + DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogControllerWebUIBrowserTest); }; -IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerBrowserTest, ShowDialog) { +IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerWebUIBrowserTest, + ShowDialog) { // Waits for the dialog to initialize. TestNavigationObserver nav_observer(media_router_dialog_); nav_observer.Wait(); @@ -72,7 +74,7 @@ IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerBrowserTest, ShowDialog) { ASSERT_TRUE(media_router_ui); } -IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerBrowserTest, Navigate) { +IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerWebUIBrowserTest, Navigate) { { // Wait for the dialog to initialize. TestNavigationObserver nav_observer(media_router_dialog_); @@ -115,8 +117,8 @@ IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerBrowserTest, Navigate) { EXPECT_FALSE(dialog_controller_->GetMediaRouterDialog()); } -IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerBrowserTest, - RenderProcessHost) { +IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerWebUIBrowserTest, + RenderProcessHost) { // New media router dialog is a constrained window, so the number of // tabs is still 1. EXPECT_EQ(1, browser()->tab_strip_model()->count()); @@ -124,8 +126,8 @@ IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerBrowserTest, // Crash initiator_'s renderer process. content::WebContentsDestroyedWatcher dialog_watcher(media_router_dialog_); - content::RenderProcessHostWatcher rph_watcher(initiator_, - content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); + content::RenderProcessHostWatcher rph_watcher( + initiator_, content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); ui_test_utils::NavigateToURL(browser(), GURL(content::kChromeUICrashURL)); diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_unittest.cc index dbc60a9a569..29907ea8bf4 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl_unittest.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_unittest.cc @@ -10,7 +10,7 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/toolbar/mock_media_router_action_controller.h" -#include "chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.h" +#include "chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h" #include "chrome/browser/ui/webui/media_router/media_router_ui.h" #include "chrome/browser/ui/webui/media_router/media_router_ui_service.h" #include "chrome/browser/ui/webui/media_router/media_router_web_ui_test.h" @@ -21,10 +21,10 @@ using content::WebContents; namespace media_router { -class MediaRouterDialogControllerImplTest : public MediaRouterWebUITest { +class MediaRouterDialogControllerWebUIImplTest : public MediaRouterWebUITest { public: - MediaRouterDialogControllerImplTest() : MediaRouterWebUITest(true) {} - ~MediaRouterDialogControllerImplTest() override {} + MediaRouterDialogControllerWebUIImplTest() : MediaRouterWebUITest(true) {} + ~MediaRouterDialogControllerWebUIImplTest() override {} void OpenMediaRouterDialog(); @@ -35,14 +35,14 @@ class MediaRouterDialogControllerImplTest : public MediaRouterWebUITest { protected: WebContents* initiator_ = nullptr; - MediaRouterDialogControllerImpl* dialog_controller_ = nullptr; + MediaRouterDialogControllerWebUIImpl* dialog_controller_ = nullptr; WebContents* media_router_dialog_ = nullptr; private: - DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogControllerImplTest); + DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogControllerWebUIImplTest); }; -void MediaRouterDialogControllerImplTest::OpenMediaRouterDialog() { +void MediaRouterDialogControllerWebUIImplTest::OpenMediaRouterDialog() { // Start with one window with one tab. EXPECT_EQ(1u, chrome::GetTotalBrowserCount()); EXPECT_EQ(0, browser()->tab_strip_model()->count()); @@ -53,7 +53,8 @@ void MediaRouterDialogControllerImplTest::OpenMediaRouterDialog() { initiator_ = browser()->tab_strip_model()->GetActiveWebContents(); dialog_controller_ = - MediaRouterDialogControllerImpl::GetOrCreateForWebContents(initiator_); + MediaRouterDialogControllerWebUIImpl::GetOrCreateForWebContents( + initiator_); ASSERT_TRUE(dialog_controller_); // Get the media router dialog for the initiator. @@ -69,7 +70,7 @@ void MediaRouterDialogControllerImplTest::OpenMediaRouterDialog() { } // Create/Get a media router dialog for initiator. -TEST_F(MediaRouterDialogControllerImplTest, ShowMediaRouterDialog) { +TEST_F(MediaRouterDialogControllerWebUIImplTest, ShowMediaRouterDialog) { OpenMediaRouterDialog(); // Show media router dialog for the same initiator again. @@ -88,7 +89,7 @@ TEST_F(MediaRouterDialogControllerImplTest, ShowMediaRouterDialog) { // Tests multiple media router dialogs exist in the same browser for different // initiators. If a dialog already exists for an initiator, that initiator // gets focused. -TEST_F(MediaRouterDialogControllerImplTest, MultipleMediaRouterDialogs) { +TEST_F(MediaRouterDialogControllerWebUIImplTest, MultipleMediaRouterDialogs) { // Let's start with one window and two tabs. EXPECT_EQ(1u, chrome::GetTotalBrowserCount()); TabStripModel* tab_strip_model = browser()->tab_strip_model(); @@ -106,10 +107,9 @@ TEST_F(MediaRouterDialogControllerImplTest, MultipleMediaRouterDialogs) { ASSERT_TRUE(web_contents_2); EXPECT_EQ(2, tab_strip_model->count()); - // Create media router dialog for |web_contents_1|. - MediaRouterDialogControllerImpl* dialog_controller_1 = - MediaRouterDialogControllerImpl::GetOrCreateForWebContents( + MediaRouterDialogControllerWebUIImpl* dialog_controller_1 = + MediaRouterDialogControllerWebUIImpl::GetOrCreateForWebContents( web_contents_1); ASSERT_TRUE(dialog_controller_1); @@ -123,8 +123,8 @@ TEST_F(MediaRouterDialogControllerImplTest, MultipleMediaRouterDialogs) { EXPECT_EQ(2, tab_strip_model->count()); // Create media router dialog for |web_contents_2|. - MediaRouterDialogControllerImpl* dialog_controller_2 = - MediaRouterDialogControllerImpl::GetOrCreateForWebContents( + MediaRouterDialogControllerWebUIImpl* dialog_controller_2 = + MediaRouterDialogControllerWebUIImpl::GetOrCreateForWebContents( web_contents_2); ASSERT_TRUE(dialog_controller_2); @@ -166,7 +166,7 @@ TEST_F(MediaRouterDialogControllerImplTest, MultipleMediaRouterDialogs) { EXPECT_EQ(tab_2_index, tab_strip_model->active_index()); } -TEST_F(MediaRouterDialogControllerImplTest, CloseDialogFromWebUI) { +TEST_F(MediaRouterDialogControllerWebUIImplTest, CloseDialogFromWebUI) { OpenMediaRouterDialog(); // Close the dialog. @@ -199,7 +199,8 @@ TEST_F(MediaRouterDialogControllerImplTest, CloseDialogFromWebUI) { EXPECT_EQ(media_router_dialog_2, dialog_controller_->GetMediaRouterDialog()); } -TEST_F(MediaRouterDialogControllerImplTest, CloseDialogFromDialogController) { +TEST_F(MediaRouterDialogControllerWebUIImplTest, + CloseDialogFromDialogController) { OpenMediaRouterDialog(); // Close the dialog. @@ -217,15 +218,15 @@ TEST_F(MediaRouterDialogControllerImplTest, CloseDialogFromDialogController) { EXPECT_FALSE(dialog_controller_->GetMediaRouterDialog()); } -TEST_F(MediaRouterDialogControllerImplTest, CloseInitiator) { +TEST_F(MediaRouterDialogControllerWebUIImplTest, CloseInitiator) { OpenMediaRouterDialog(); // Close the initiator. This should also close the dialog WebContents. content::WebContentsDestroyedWatcher initiator_watcher(initiator_); content::WebContentsDestroyedWatcher dialog_watcher(media_router_dialog_); - int initiator_index = browser()->tab_strip_model() - ->GetIndexOfWebContents(initiator_); + int initiator_index = + browser()->tab_strip_model()->GetIndexOfWebContents(initiator_); EXPECT_NE(-1, initiator_index); EXPECT_TRUE(browser()->tab_strip_model()->CloseWebContentsAt( initiator_index, TabStripModel::CLOSE_NONE)); @@ -240,7 +241,7 @@ TEST_F(MediaRouterDialogControllerImplTest, CloseInitiator) { // The dialog controller is deleted when the WebContents is closed/destroyed. } -TEST_F(MediaRouterDialogControllerImplTest, NotifyActionController) { +TEST_F(MediaRouterDialogControllerWebUIImplTest, NotifyActionController) { MockMediaRouterActionController* action_controller = static_cast<MockMediaRouterActionController*>( MediaRouterUIService::Get(browser()->profile())->action_controller()); @@ -256,11 +257,11 @@ TEST_F(MediaRouterDialogControllerImplTest, NotifyActionController) { content::PresentationRequest( {1, 2}, {GURL("http://test.com"), GURL("http://test2.com")}, url::Origin::Create(GURL("http://example.com"))), - base::Bind( - &MediaRouterDialogControllerImplTest::PresentationSuccessCallback, - base::Unretained(this)), - base::Bind( - &MediaRouterDialogControllerImplTest::PresentationErrorCallback, + base::BindOnce(&MediaRouterDialogControllerWebUIImplTest:: + PresentationSuccessCallback, + base::Unretained(this)), + base::BindOnce( + &MediaRouterDialogControllerWebUIImplTest::PresentationErrorCallback, base::Unretained(this)))); // When |dialog_controller_| is destroyed with its dialog open, diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.cc deleted file mode 100644 index 2506cbba5b2..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.cc +++ /dev/null @@ -1,288 +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. - -#include "chrome/browser/ui/webui/media_router/media_router_file_dialog.h" - -#include <memory> - -#include "base/bind.h" -#include "base/task/cancelable_task_tracker.h" -#include "base/task_scheduler/post_task.h" -#include "chrome/browser/media/router/media_router_metrics.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/common/media_router/issue.h" -#include "chrome/grit/generated_resources.h" -#include "media/base/container_names.h" -#include "media/base/mime_util.h" -#include "net/base/filename_util.h" -#include "net/base/mime_util.h" -#include "ui/base/l10n/l10n_util.h" - -namespace media_router { - -namespace { - -base::string16 GetFileName(const ui::SelectedFileInfo& file_info) { - return file_info.file_path.BaseName().LossyDisplayName(); -} - -// Returns info about extensions for files we support as audio video files. -ui::SelectFileDialog::FileTypeInfo GetAudioVideoFileTypeInfo() { - ui::SelectFileDialog::FileTypeInfo file_type_info; - - file_type_info.allowed_paths = ui::SelectFileDialog::FileTypeInfo::ANY_PATH; - - std::vector<base::FilePath::StringType> extensions; - - // Add all extensions from the audio and video mime types. - net::GetExtensionsForMimeType("video/*", &extensions); - net::GetExtensionsForMimeType("audio/*", &extensions); - - // Filter based on what can be played on the media player - std::vector<base::FilePath::StringType> filtered_extensions; - std::copy_if(extensions.begin(), extensions.end(), - std::back_inserter(filtered_extensions), - [](const base::FilePath::StringType& extension) { - std::string mime_type; - net::GetWellKnownMimeTypeFromExtension(extension, &mime_type); - return media::IsSupportedMediaMimeType(mime_type); - }); - - // Add all audio and video extensions as a single type to the dialog. - file_type_info.extensions.push_back(filtered_extensions); - - // Set the description, otherwise it lists all the possible extensions which - // looks bad. - file_type_info.extension_description_overrides.push_back( - l10n_util::GetStringUTF16( - IDS_MEDIA_ROUTER_FILE_DIALOG_AUDIO_VIDEO_FILTER)); - - // Add an option for all files - file_type_info.include_all_files = true; - - return file_type_info; -} - -} // namespace - -// FileSystemDelegate default implementations -MediaRouterFileDialog::FileSystemDelegate::FileSystemDelegate() = default; -MediaRouterFileDialog::FileSystemDelegate::~FileSystemDelegate() = default; - -bool MediaRouterFileDialog::FileSystemDelegate::FileExists( - const base::FilePath& file_path) const { - // We assume if the path exists, the file exists. - return base::PathExists(file_path); -} - -bool MediaRouterFileDialog::FileSystemDelegate::IsFileReadable( - const base::FilePath& file_path) const { - char buffer[1]; - return base::ReadFile(file_path, buffer, 1) != -1; -} - -bool MediaRouterFileDialog::FileSystemDelegate::IsFileTypeSupported( - const base::FilePath& file_path) const { - std::string mime_type; - net::GetMimeTypeFromFile(file_path, &mime_type); - return media::IsSupportedMediaMimeType(mime_type); -} - -int64_t MediaRouterFileDialog::FileSystemDelegate::GetFileSize( - const base::FilePath& file_path) const { - int64_t file_size; - return base::GetFileSize(file_path, &file_size) ? file_size : -1; -} - -base::FilePath -MediaRouterFileDialog::FileSystemDelegate::GetLastSelectedDirectory( - Browser* browser) const { - return browser->profile()->last_selected_directory(); -} - -void MediaRouterFileDialog::FileSystemDelegate::OpenFileDialog( - ui::SelectFileDialog::Listener* listener, - const Browser* browser, - const base::FilePath& default_directory, - const ui::SelectFileDialog::FileTypeInfo* file_type_info) { - select_file_dialog_ = ui::SelectFileDialog::Create( - listener, std::make_unique<ChromeSelectFilePolicy>( - browser->tab_strip_model()->GetActiveWebContents())); - - gfx::NativeWindow parent_window = browser->window()->GetNativeWindow(); - - select_file_dialog_->SelectFile( - ui::SelectFileDialog::SELECT_OPEN_FILE, base::string16(), - default_directory, file_type_info, 0, base::FilePath::StringType(), - parent_window, nullptr /* |params| passed to the listener */); -} -// End of FileSystemDelegate default implementations - -MediaRouterFileDialog::MediaRouterFileDialog( - MediaRouterFileDialogDelegate* delegate) - : MediaRouterFileDialog(delegate, std::make_unique<FileSystemDelegate>()) {} - -// Used for tests -MediaRouterFileDialog::MediaRouterFileDialog( - MediaRouterFileDialogDelegate* delegate, - std::unique_ptr<FileSystemDelegate> file_system_delegate) - : task_runner_( - base::TaskScheduler::GetInstance()->CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE})), - file_system_delegate_(std::move(file_system_delegate)), - delegate_(delegate) {} - -MediaRouterFileDialog::~MediaRouterFileDialog() = default; - -GURL MediaRouterFileDialog::GetLastSelectedFileUrl() { - return selected_file_.has_value() - ? net::FilePathToFileURL(selected_file_->local_path) - : GURL(); -} - -base::string16 MediaRouterFileDialog::GetLastSelectedFileName() { - return selected_file_.has_value() ? GetFileName(selected_file_.value()) - : base::string16(); -} - -void MediaRouterFileDialog::MaybeReportLastSelectedFileInformation() { - if (selected_file_.has_value()) { - cancelable_task_tracker_.PostTask( - task_runner_.get(), FROM_HERE, - base::BindOnce(&MediaRouterFileDialog::ReportFileFormat, - base::Unretained(this), selected_file_->local_path)); - - cancelable_task_tracker_.PostTask( - task_runner_.get(), FROM_HERE, - base::BindOnce(&MediaRouterFileDialog::ReportFileSize, - base::Unretained(this), selected_file_->local_path)); - } else { - VLOG(1) << "MediaRouterFileDialog did not report file information; no file " - "to report."; - } -} - -void MediaRouterFileDialog::OpenFileDialog(Browser* browser) { - const base::FilePath directory = - file_system_delegate_->GetLastSelectedDirectory(browser); - - const ui::SelectFileDialog::FileTypeInfo file_type_info = - GetAudioVideoFileTypeInfo(); - - file_system_delegate_->OpenFileDialog(this, browser, directory, - &file_type_info); -} - -void MediaRouterFileDialog::ReportFileFormat(const base::FilePath& filename) { - // Windows implementation of ReadFile fails if file smaller than desired size, - // so use file length if file less than 8192 bytes (http://crbug.com/243885). - char buffer[8192]; - int read_size = sizeof(buffer); - int64_t actual_size; - if (base::GetFileSize(filename, &actual_size) && actual_size < read_size) - read_size = actual_size; - int read = base::ReadFile(filename, buffer, read_size); - - MediaRouterMetrics::RecordMediaRouterFileFormat( - media::container_names::DetermineContainer( - reinterpret_cast<const uint8_t*>(buffer), read)); -} - -void MediaRouterFileDialog::ReportFileSize(const base::FilePath& filename) { - int64_t size; - if (base::GetFileSize(filename, &size)) { - MediaRouterMetrics::RecordMediaRouterFileSize(size); - } else { - VLOG(1) << "Can't get file size for file: " << filename.LossyDisplayName() - << "."; - } -} - -void MediaRouterFileDialog::FileSelected(const base::FilePath& path, - int index, - void* params) { - FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params); -} - -void MediaRouterFileDialog::FileSelectedWithExtraInfo( - const ui::SelectedFileInfo& file_info, - int index, - void* params) { - cancelable_task_tracker_.PostTaskAndReplyWithResult( - task_runner_.get(), FROM_HERE, - base::BindOnce(&MediaRouterFileDialog::ValidateFile, - base::Unretained(this), file_info), - base::BindOnce(&MediaRouterFileDialog::OnValidationResults, - base::Unretained(this), file_info)); -} - -void MediaRouterFileDialog::OnValidationResults( - ui::SelectedFileInfo file_info, - MediaRouterFileDialog::ValidationResult validation_result) { - if (validation_result == MediaRouterFileDialog::FILE_OK) { - selected_file_ = file_info; - delegate_->FileDialogFileSelected(file_info); - } else { - delegate_->FileDialogSelectionFailed( - CreateIssue(file_info, validation_result)); - } -} - -void MediaRouterFileDialog::FileSelectionCanceled(void* params) { - delegate_->FileDialogSelectionCanceled(); -} - -IssueInfo MediaRouterFileDialog::CreateIssue( - const ui::SelectedFileInfo& file_info, - MediaRouterFileDialog::ValidationResult validation_result) { - std::string issue_title; - switch (validation_result) { - case MediaRouterFileDialog::FILE_MISSING: - case MediaRouterFileDialog::FILE_EMPTY: - case MediaRouterFileDialog::FILE_TYPE_NOT_SUPPORTED: - case MediaRouterFileDialog::READ_FAILURE: - issue_title = l10n_util::GetStringFUTF8( - IDS_MEDIA_ROUTER_ISSUE_FILE_CAST_ERROR, GetFileName(file_info)); - break; - case MediaRouterFileDialog::FILE_OK: - // Create issue shouldn't be called with FILE_OK, but to ensure things - // compile, fall through sets |issue_title| to the generic error. - NOTREACHED(); - FALLTHROUGH; - case MediaRouterFileDialog::UNKNOWN_FAILURE: - issue_title = l10n_util::GetStringUTF8( - IDS_MEDIA_ROUTER_ISSUE_FILE_CAST_GENERIC_ERROR); - break; - } - return IssueInfo(issue_title, IssueInfo::Action::DISMISS, - IssueInfo::Severity::WARNING); -} - -MediaRouterFileDialog::ValidationResult MediaRouterFileDialog::ValidateFile( - const ui::SelectedFileInfo& file_info) { - // Attempt to determine if file exsists. - if (!file_system_delegate_->FileExists(file_info.local_path)) - return MediaRouterFileDialog::FILE_MISSING; - - // Attempt to read the file size and verify that the file has contents. - int file_size = file_system_delegate_->GetFileSize(file_info.local_path); - if (file_size < 0) - return MediaRouterFileDialog::READ_FAILURE; - - if (file_size == 0) - return MediaRouterFileDialog::FILE_EMPTY; - - if (!file_system_delegate_->IsFileReadable(file_info.local_path)) - return MediaRouterFileDialog::READ_FAILURE; - - if (!file_system_delegate_->IsFileTypeSupported(file_info.local_path)) - return MediaRouterFileDialog::FILE_TYPE_NOT_SUPPORTED; - - return MediaRouterFileDialog::FILE_OK; -} - -} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.h b/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.h deleted file mode 100644 index 29e8bac59eb..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.h +++ /dev/null @@ -1,162 +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. - -#ifndef CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_FILE_DIALOG_H_ -#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_FILE_DIALOG_H_ - -#include "base/files/file_util.h" -#include "base/task/cancelable_task_tracker.h" -#include "chrome/browser/ui/chrome_select_file_policy.h" -#include "chrome/common/media_router/issue.h" -#include "ui/shell_dialogs/select_file_dialog.h" -#include "ui/shell_dialogs/selected_file_info.h" -#include "url/gurl.h" - -class Browser; - -namespace base { -class FilePath; -} - -namespace media_router { - -class MediaRouterFileDialog : public ui::SelectFileDialog::Listener { - public: - // The reasons that the file selection might have failed. Passed into the - // failure callback. - enum ValidationResult { - FILE_OK, - // File does not exist. - FILE_MISSING, - // The selected file is empty. - FILE_EMPTY, - // This file type is not supported by the chrome player. - FILE_TYPE_NOT_SUPPORTED, - // The selected file cannot be read. - READ_FAILURE, - // The reason for the failure is unknown. - UNKNOWN_FAILURE, - }; - - class MediaRouterFileDialogDelegate { - public: - virtual ~MediaRouterFileDialogDelegate() {} - - // Called when a file is selected by the user to store the files information - // and tell the message handler to pass along the information. - virtual void FileDialogFileSelected( - const ui::SelectedFileInfo& file_info) = 0; - - // Called when the file selection fails. - virtual void FileDialogSelectionFailed(const IssueInfo& issue) = 0; - - // Called when the file selection is canceled by the user. Optionally - // implementable. - virtual void FileDialogSelectionCanceled() {} - }; - - // A class which defines functions to interact with the file systems. - class FileSystemDelegate { - public: - FileSystemDelegate(); - virtual ~FileSystemDelegate(); - - // Checks if a file exists. - virtual bool FileExists(const base::FilePath& file_path) const; - - // Checks if a file can be read. - virtual bool IsFileReadable(const base::FilePath& file_path) const; - - // Checks if the file type is supported in this browser. - virtual bool IsFileTypeSupported(const base::FilePath& file_path) const; - - // Checks the size of a file, returns -1 if the file size cannot be read. - virtual int64_t GetFileSize(const base::FilePath& file_path) const; - - // Gets the last selected directory based on the browser. - virtual base::FilePath GetLastSelectedDirectory(Browser* browser) const; - - // Opens a dialog with |file_type_info| as the configuration, and shows - // |default_directory| as the starting place. - virtual void OpenFileDialog( - ui::SelectFileDialog::Listener* listener, - const Browser* browser, - const base::FilePath& default_directory, - const ui::SelectFileDialog::FileTypeInfo* file_type_info); - - private: - // The dialog object for the file dialog. Needs to be kept in scope while - // the dialog is open, but is not used for anything else. - scoped_refptr<ui::SelectFileDialog> select_file_dialog_; - }; - - explicit MediaRouterFileDialog(MediaRouterFileDialogDelegate* delegate); - - // Constuctor with injectable FileSystemDelegate, used for tests. - MediaRouterFileDialog( - MediaRouterFileDialogDelegate* delegate, - std::unique_ptr<FileSystemDelegate> file_system_delegate); - - ~MediaRouterFileDialog() override; - - virtual GURL GetLastSelectedFileUrl(); - virtual base::string16 GetLastSelectedFileName(); - - // Checks if a file has been recorded as being selected, then attempts to - // report interesting information about the file, such as format. - virtual void MaybeReportLastSelectedFileInformation(); - - // Opens the dialog configured to get a media file. - virtual void OpenFileDialog(Browser* browser); - - private: - // Reports the format of a file to the UMA stats. - void ReportFileFormat(const base::FilePath& filename); - - // Reports the size of a file to the UMA stats. - void ReportFileSize(const base::FilePath& filename); - - // Overridden from SelectFileDialog::Listener: - void FileSelected(const base::FilePath& path, - int index, - void* params) override; - void FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info, - int index, - void* params) override; - void FileSelectionCanceled(void* params) override; - - // Returns a reason for failure if the file is not valid, or base::nullopt if - // it passes validation. Has to be run on seperate thread. - ValidationResult ValidateFile(const ui::SelectedFileInfo& file_info); - - // Takes a file info and optionally a reason for validation failure, and calls - // the appropriate delegate function. - void OnValidationResults( - ui::SelectedFileInfo file_info, - MediaRouterFileDialog::ValidationResult validation_result); - - IssueInfo CreateIssue( - const ui::SelectedFileInfo& file_info, - MediaRouterFileDialog::ValidationResult validation_result); - - // Used to post file operations. Cleans up after itself and cancels unrun - // tasks when destructed. - base::CancelableTaskTracker cancelable_task_tracker_; - scoped_refptr<base::TaskRunner> task_runner_; - - // Pointer to the file last indicated by the system. - base::Optional<ui::SelectedFileInfo> selected_file_; - - // The object which all file system calls go through. - std::unique_ptr<FileSystemDelegate> file_system_delegate_; - - // Object which the media router file dialog callbacks get sent to. - MediaRouterFileDialogDelegate* const delegate_; - - DISALLOW_COPY_AND_ASSIGN(MediaRouterFileDialog); -}; - -} // namespace media_router - -#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_FILE_DIALOG_H_ diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog_unittest.cc deleted file mode 100644 index ea89c4b4a38..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog_unittest.cc +++ /dev/null @@ -1,194 +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. - -#include "chrome/browser/ui/webui/media_router/media_router_file_dialog.h" - -#include <memory> - -#include "base/run_loop.h" -#include "base/strings/utf_string_conversions.h" -#include "base/task_scheduler/task_scheduler.h" -#include "base/test/scoped_feature_list.h" -#include "chrome/common/media_router/issue.h" -#include "chrome/grit/generated_resources.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/base/l10n/l10n_util.h" - -using testing::_; -using testing::ContainsRegex; -using testing::Field; -using testing::InvokeWithoutArgs; -using testing::Return; -using testing::Test; - -namespace media_router { - -namespace { - -// Clears out async tasks -void FlushTasks() { - base::TaskScheduler::GetInstance()->FlushForTesting(); - base::RunLoop().RunUntilIdle(); -} - -} // namespace - -class MockDelegate - : public MediaRouterFileDialog::MediaRouterFileDialogDelegate { - public: - MOCK_METHOD1(FileDialogFileSelected, - void(const ui::SelectedFileInfo& file_info)); - MOCK_METHOD1(FileDialogSelectionFailed, void(const IssueInfo& issue)); - MOCK_METHOD0(FileDialogSelectionCanceled, void()); -}; - -class MockFileSystemDelegate - : public MediaRouterFileDialog::FileSystemDelegate { - public: - MockFileSystemDelegate() : MediaRouterFileDialog::FileSystemDelegate() {} - ~MockFileSystemDelegate() override {} - - MOCK_CONST_METHOD1(FileExists, bool(const base::FilePath& file_path)); - MOCK_CONST_METHOD1(IsFileReadable, bool(const base::FilePath& file_path)); - MOCK_CONST_METHOD1(IsFileTypeSupported, - bool(const base::FilePath& file_path)); - MOCK_CONST_METHOD1(GetFileSize, int64_t(const base::FilePath& file_path)); - MOCK_CONST_METHOD1(GetLastSelectedDirectory, - base::FilePath(Browser* browser)); - MOCK_METHOD4(OpenFileDialog, - void(ui::SelectFileDialog::Listener* listener, - const Browser* browser, - const base::FilePath& default_directory, - const ui::SelectFileDialog::FileTypeInfo* file_type_info)); -}; - -class MediaRouterFileDialogTest : public Test { - public: - MediaRouterFileDialogTest() { - fake_path = base::FilePath(FILE_PATH_LITERAL("im/a/fake_path.mp3")); - - scoped_feature_list_.InitFromCommandLine( - "EnableCastLocalMedia" /* enabled features */, - std::string() /* disabled features */); - } - - void SetUp() override { - mock_delegate_ = std::make_unique<MockDelegate>(); - - auto temp_mock = std::make_unique<MockFileSystemDelegate>(); - mock_file_system_delegate = temp_mock.get(); - - dialog_ = std::make_unique<MediaRouterFileDialog>(mock_delegate_.get(), - std::move(temp_mock)); - dialog_as_listener_ = dialog_.get(); - - // Setup default file checks to all pass - ON_CALL(*mock_file_system_delegate, FileExists(_)) - .WillByDefault(Return(true)); - ON_CALL(*mock_file_system_delegate, IsFileReadable(_)) - .WillByDefault(Return(true)); - ON_CALL(*mock_file_system_delegate, IsFileTypeSupported(_)) - .WillByDefault(Return(true)); - ON_CALL(*mock_file_system_delegate, GetFileSize(_)) - .WillByDefault(Return(1)); - } - - void FileSelectedExpectFailure(base::FilePath fake_path) { - fake_path_name = fake_path.BaseName().LossyDisplayName(); - std::string error_title = l10n_util::GetStringFUTF8( - IDS_MEDIA_ROUTER_ISSUE_FILE_CAST_ERROR, fake_path_name); - - EXPECT_CALL(*mock_delegate_, FileDialogSelectionFailed( - Field(&IssueInfo::title, error_title))); - - dialog_as_listener_->FileSelected(fake_path, 0, 0); - - // Flush out the async file validation calls - FlushTasks(); - } - - protected: - std::unique_ptr<MockDelegate> mock_delegate_; - MockFileSystemDelegate* mock_file_system_delegate = nullptr; - std::unique_ptr<MediaRouterFileDialog> dialog_; - - // Used for simulating calls from a SelectFileDialog. - ui::SelectFileDialog::Listener* dialog_as_listener_ = nullptr; - - base::FilePath fake_path; - base::string16 fake_path_name; - - base::test::ScopedFeatureList scoped_feature_list_; - content::TestBrowserThreadBundle thread_bundle_; -}; - -TEST_F(MediaRouterFileDialogTest, SelectFileSuccess) { - // File selection succeeds, success callback called with the right file info. - // Selected file URL is set properly. - - // Expect all the checks and return passes - EXPECT_CALL(*mock_file_system_delegate, FileExists(fake_path)) - .WillOnce(Return(true)); - EXPECT_CALL(*mock_file_system_delegate, IsFileReadable(fake_path)) - .WillOnce(Return(true)); - EXPECT_CALL(*mock_file_system_delegate, GetFileSize(fake_path)) - .WillOnce(Return(1)); - - EXPECT_CALL(*mock_delegate_, - FileDialogFileSelected( - Field(&ui::SelectedFileInfo::local_path, fake_path))); - - dialog_as_listener_->FileSelected(fake_path, 0, 0); - - FlushTasks(); - - ASSERT_THAT(dialog_->GetLastSelectedFileUrl().GetContent(), - ContainsRegex(base::UTF16ToUTF8(fake_path.LossyDisplayName()))); -} - -TEST_F(MediaRouterFileDialogTest, SelectFileCanceled) { - // File selection gets cancelled, failure callback called - EXPECT_CALL(*mock_delegate_, FileDialogSelectionCanceled()); - - dialog_as_listener_->FileSelectionCanceled(0); -} - -TEST_F(MediaRouterFileDialogTest, SelectFailureFileDoesNotExist) { - EXPECT_CALL(*mock_file_system_delegate, FileExists(fake_path)) - .WillOnce(Return(false)); - - FileSelectedExpectFailure(fake_path); -} - -TEST_F(MediaRouterFileDialogTest, SelectFailureFileDoesNotContainContent) { - EXPECT_CALL(*mock_file_system_delegate, GetFileSize(fake_path)) - .WillOnce(Return(0)); - - FileSelectedExpectFailure(fake_path); -} - -TEST_F(MediaRouterFileDialogTest, SelectFailureCannotReadGetFileSize) { - EXPECT_CALL(*mock_file_system_delegate, GetFileSize(fake_path)) - .WillOnce(Return(-1)); - - FileSelectedExpectFailure(fake_path); -} - -TEST_F(MediaRouterFileDialogTest, SelectFailureCannotReadFile) { - EXPECT_CALL(*mock_file_system_delegate, IsFileReadable(fake_path)) - .WillOnce(Return(false)); - - FileSelectedExpectFailure(fake_path); -} - -TEST_F(MediaRouterFileDialogTest, SelectFailureFileNotSupported) { - EXPECT_CALL(*mock_file_system_delegate, IsFileTypeSupported(fake_path)) - .WillOnce(Return(false)); - - FileSelectedExpectFailure(fake_path); -} - -} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.cc new file mode 100644 index 00000000000..1bd6fd67aa1 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.cc @@ -0,0 +1,48 @@ +// 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/webui/media_router/media_router_internals_ui.h" + +#include <memory> + +#include "chrome/browser/media/router/media_router.h" +#include "chrome/browser/media/router/media_router_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/media_router/media_router_internals_webui_message_handler.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +namespace media_router { + +MediaRouterInternalsUI::MediaRouterInternalsUI(content::WebUI* web_ui) + : content::WebUIController(web_ui) { + // Create a WebUIDataSource containing the chrome://media-router-internals + // page's content. + std::unique_ptr<content::WebUIDataSource> html_source( + content::WebUIDataSource::Create( + chrome::kChromeUIMediaRouterInternalsHost)); + html_source->AddResourcePath("media_router_internals.js", + IDR_MEDIA_ROUTER_INTERNALS_JS); + html_source->AddResourcePath("media_router_internals.css", + IDR_MEDIA_ROUTER_INTERNALS_CSS); + html_source->SetDefaultResource(IDR_MEDIA_ROUTER_INTERNALS_HTML); + // Ownership of |html_source| is transferred to the BrowserContext. + content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), + html_source.release()); + + content::WebContents* wc = web_ui->GetWebContents(); + DCHECK(wc); + content::BrowserContext* context = wc->GetBrowserContext(); + MediaRouter* router = MediaRouterFactory::GetApiForBrowserContext(context); + auto handler = + std::make_unique<MediaRouterInternalsWebUIMessageHandler>(router); + web_ui->AddMessageHandler(std::move(handler)); +} + +MediaRouterInternalsUI::~MediaRouterInternalsUI() = default; + +} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.h b/chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.h new file mode 100644 index 00000000000..40cf3f15915 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.h @@ -0,0 +1,28 @@ +// 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_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_INTERNALS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_INTERNALS_UI_H_ + +#include <string> + +#include "base/macros.h" +#include "content/public/browser/web_ui_controller.h" + +namespace media_router { + +// Implements the chrome://media-router user interface. +class MediaRouterInternalsUI : public content::WebUIController { + public: + // |web_ui| owns this object and is used to initialize the base class. + explicit MediaRouterInternalsUI(content::WebUI* web_ui); + ~MediaRouterInternalsUI() override; + + private: + DISALLOW_COPY_AND_ASSIGN(MediaRouterInternalsUI); +}; + +} // namespace media_router + +#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_INTERNALS_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_internals_webui_message_handler.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_internals_webui_message_handler.cc new file mode 100644 index 00000000000..346ac5be40f --- /dev/null +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_internals_webui_message_handler.cc @@ -0,0 +1,33 @@ +// 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/webui/media_router/media_router_internals_webui_message_handler.h" + +#include "base/values.h" +#include "chrome/browser/media/router/media_router.h" + +namespace media_router { + +MediaRouterInternalsWebUIMessageHandler:: + MediaRouterInternalsWebUIMessageHandler(const MediaRouter* router) + : router_(router) { + DCHECK(router_); +} + +void MediaRouterInternalsWebUIMessageHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "initialized", + base::BindRepeating( + &MediaRouterInternalsWebUIMessageHandler::HandleInitialized, + base::Unretained(this))); +} + +void MediaRouterInternalsWebUIMessageHandler::HandleInitialized( + const base::ListValue* args) { + AllowJavascript(); + CallJavascriptFunction("media_router_internals.setStatus", + router_->GetState()); +} + +} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_internals_webui_message_handler.h b/chromium/chrome/browser/ui/webui/media_router/media_router_internals_webui_message_handler.h new file mode 100644 index 00000000000..0f9c6fb49a8 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_internals_webui_message_handler.h @@ -0,0 +1,36 @@ +// 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_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_INTERNALS_WEBUI_MESSAGE_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_INTERNALS_WEBUI_MESSAGE_HANDLER_H_ + +#include <string> + +#include "content/public/browser/web_ui_message_handler.h" + +namespace media_router { + +class MediaRouter; + +// The handler for Javascript messages related to the media router internals +// page. +class MediaRouterInternalsWebUIMessageHandler + : public content::WebUIMessageHandler { + public: + explicit MediaRouterInternalsWebUIMessageHandler(const MediaRouter* router); + + private: + // WebUIMessageHandler implementation. + void RegisterMessages() override; + + // Handlers for JavaScript messages. + void HandleInitialized(const base::ListValue* args); + + // Pointer to the MediaRouter. + const MediaRouter* router_; +}; + +} // namespace media_router + +#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_INTERNALS_WEBUI_MESSAGE_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc index 4e10bf5fd64..e4e8a02ba28 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc @@ -55,7 +55,7 @@ #include "extensions/browser/extension_registry.h" #include "extensions/common/constants.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" -#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h" +#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/icu/source/i18n/unicode/coll.h" #include "ui/base/l10n/l10n_util.h" #include "ui/web_dialogs/web_dialog_delegate.h" @@ -467,9 +467,9 @@ void MediaRouterUI::InitCommon(content::WebContents* initiator) { } initiator_ = initiator; - SessionID::id_type tab_id = SessionTabHelper::IdForTab(initiator); - if (tab_id != -1) { - MediaSource mirroring_source(MediaSourceForTab(tab_id)); + SessionID tab_id = SessionTabHelper::IdForTab(initiator); + if (tab_id.is_valid()) { + MediaSource mirroring_source(MediaSourceForTab(tab_id.id())); query_result_manager_->SetSourcesForCastMode(MediaCastMode::TAB_MIRROR, {mirroring_source}, origin); } @@ -618,8 +618,8 @@ bool MediaRouterUI::CreateRoute(const MediaSink::Id& sink_id, GURL url = media_router_file_dialog_->GetLastSelectedFileUrl(); tab_contents = OpenTabWithUrl(url); - SessionID::id_type tab_id = SessionTabHelper::IdForTab(tab_contents); - source_id = MediaSourceForTab(tab_id).id(); + SessionID tab_id = SessionTabHelper::IdForTab(tab_contents); + source_id = MediaSourceForTab(tab_id.id()).id(); SetLocalFileRouteParameters(sink_id, &origin, url, tab_contents, &route_response_callbacks, &timeout, @@ -818,14 +818,14 @@ void MediaRouterUI::SearchSinksAndCreateRoute( bool MediaRouterUI::UserSelectedTabMirroringForCurrentOrigin() const { const base::ListValue* origins = Profile::FromWebUI(web_ui())->GetPrefs()->GetList( - prefs::kMediaRouterTabMirroringSources); + ::prefs::kMediaRouterTabMirroringSources); return origins->Find(base::Value(GetSerializedInitiatorOrigin())) != origins->end(); } void MediaRouterUI::RecordCastModeSelection(MediaCastMode cast_mode) { ListPrefUpdate update(Profile::FromWebUI(web_ui())->GetPrefs(), - prefs::kMediaRouterTabMirroringSources); + ::prefs::kMediaRouterTabMirroringSources); switch (cast_mode) { case MediaCastMode::PRESENTATION: @@ -1077,7 +1077,9 @@ void MediaRouterUI::OnUIInitialDataReceived() { } void MediaRouterUI::UpdateMaxDialogHeight(int height) { - handler_->UpdateMaxDialogHeight(height); + if (ui_initialized_) { + handler_->UpdateMaxDialogHeight(height); + } } MediaRouteController* MediaRouterUI::GetMediaRouteController() const { diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h index e8abac52f0a..3f03ed7e7a6 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h @@ -20,11 +20,11 @@ #include "chrome/browser/media/router/media_router_dialog_controller.h" #include "chrome/browser/media/router/mojo/media_route_controller.h" #include "chrome/browser/media/router/presentation/presentation_service_delegate_impl.h" +#include "chrome/browser/ui/media_router/media_cast_mode.h" +#include "chrome/browser/ui/media_router/media_router_file_dialog.h" +#include "chrome/browser/ui/media_router/media_sink_with_cast_modes.h" +#include "chrome/browser/ui/media_router/query_result_manager.h" #include "chrome/browser/ui/webui/constrained_web_dialog_ui.h" -#include "chrome/browser/ui/webui/media_router/media_cast_mode.h" -#include "chrome/browser/ui/webui/media_router/media_router_file_dialog.h" -#include "chrome/browser/ui/webui/media_router/media_sink_with_cast_modes.h" -#include "chrome/browser/ui/webui/media_router/query_result_manager.h" #include "chrome/common/media_router/issue.h" #include "chrome/common/media_router/media_source.h" #include "content/public/browser/web_ui_data_source.h" diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.cc index 98c0f0eeb07..bcd926cb963 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.cc @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h" #include "chrome/browser/media/router/media_router_factory.h" +#include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/toolbar/toolbar_actions_model_factory.h" #include "chrome/browser/ui/webui/media_router/media_router_ui_service.h" @@ -46,7 +47,9 @@ BrowserContext* MediaRouterUIServiceFactory::GetBrowserContextToUse( KeyedService* MediaRouterUIServiceFactory::BuildServiceInstanceFor( BrowserContext* context) const { - return new MediaRouterUIService(Profile::FromBrowserContext(context)); + return MediaRouterEnabled(context) + ? new MediaRouterUIService(Profile::FromBrowserContext(context)) + : nullptr; } bool MediaRouterUIServiceFactory::ServiceIsCreatedWithBrowserContext() const { diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h index 8162e6694f9..b5328f5a491 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h @@ -27,6 +27,8 @@ class MediaRouterUIServiceFactory : public BrowserContextKeyedServiceFactory { private: friend struct base::DefaultSingletonTraits<MediaRouterUIServiceFactory>; FRIEND_TEST_ALL_PREFIXES(MediaRouterUIServiceFactoryUnitTest, CreateService); + FRIEND_TEST_ALL_PREFIXES(MediaRouterUIServiceFactoryUnitTest, + DoNotCreateServiceWhenDisabled); MediaRouterUIServiceFactory(); ~MediaRouterUIServiceFactory() override; diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory_unittest.cc index 3ee9f6d215e..f66afd74352 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory_unittest.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory_unittest.cc @@ -4,6 +4,7 @@ #include <memory> +#include "base/values.h" #include "chrome/browser/media/router/media_router_factory.h" #include "chrome/browser/media/router/test/mock_media_router.h" #include "chrome/browser/profiles/profile.h" @@ -11,7 +12,9 @@ #include "chrome/browser/ui/toolbar/toolbar_actions_model_factory.h" #include "chrome/browser/ui/webui/media_router/media_router_ui_service.h" #include "chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h" +#include "chrome/common/pref_names.h" #include "chrome/test/base/testing_profile.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" @@ -41,10 +44,7 @@ class MediaRouterUIServiceFactoryUnitTest : public testing::Test { protected: content::TestBrowserThreadBundle thread_bundle_; - Profile* profile() { return profile_.get(); } - - private: - std::unique_ptr<Profile> profile_; + std::unique_ptr<TestingProfile> profile_; }; TEST_F(MediaRouterUIServiceFactoryUnitTest, CreateService) { @@ -54,9 +54,17 @@ TEST_F(MediaRouterUIServiceFactoryUnitTest, CreateService) { std::unique_ptr<MediaRouterUIService> service( static_cast<MediaRouterUIService*>( MediaRouterUIServiceFactory::GetInstance()->BuildServiceInstanceFor( - profile()))); + profile_.get()))); ASSERT_TRUE(service); ASSERT_TRUE(service->action_controller()); } +TEST_F(MediaRouterUIServiceFactoryUnitTest, DoNotCreateServiceWhenDisabled) { + profile_->GetTestingPrefService()->SetManagedPref( + prefs::kEnableMediaRouter, std::make_unique<base::Value>(false)); + EXPECT_EQ(nullptr, + MediaRouterUIServiceFactory::GetInstance()->BuildServiceInstanceFor( + profile_.get())); +} + } // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc index 6a6e17efd68..b6a7d62f329 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc @@ -462,8 +462,8 @@ TEST_F(MediaRouterUITest, FilterNonDisplayJoinableRoutes) { TEST_F(MediaRouterUITest, UIMediaRoutesObserverAssignsCurrentCastModes) { CreateMediaRouterUI(profile()); - SessionID::id_type tab_id = SessionTabHelper::IdForTab(web_contents()); - MediaSource media_source_1(MediaSourceForTab(tab_id)); + SessionID tab_id = SessionTabHelper::IdForTab(web_contents()); + MediaSource media_source_1(MediaSourceForTab(tab_id.id())); MediaSource media_source_2("mediaSource"); MediaSource media_source_3(MediaSourceForDesktop()); std::unique_ptr<MediaRouterUI::UIMediaRoutesObserver> observer( diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc index 96be58cdb9a..bcc329103d1 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc @@ -21,7 +21,6 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" -#include "chrome/browser/ui/webui/media_router/media_cast_mode.h" #include "chrome/browser/ui/webui/media_router/media_router_ui.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" @@ -270,6 +269,7 @@ void MediaRouterWebUIMessageHandler::UpdateRoutes( current_cast_modes) { std::unique_ptr<base::ListValue> routes_val( RoutesToValue(routes, joinable_route_ids, current_cast_modes)); + web_ui()->CallJavascriptFunctionUnsafe(kSetRouteList, *routes_val); } @@ -330,7 +330,6 @@ void MediaRouterWebUIMessageHandler::UpdateMediaRouteStatus( base::DictionaryValue status_value; status_value.SetString("title", status.title); - status_value.SetString("description", status.description); status_value.SetBoolean("canPlayPause", status.can_play_pause); status_value.SetBoolean("canMute", status.can_mute); status_value.SetBoolean("canSetVolume", status.can_set_volume); @@ -374,127 +373,151 @@ void MediaRouterWebUIMessageHandler::UserSelectedLocalMediaFile( void MediaRouterWebUIMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( kRequestInitialData, - base::Bind(&MediaRouterWebUIMessageHandler::OnRequestInitialData, - base::Unretained(this))); + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnRequestInitialData, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - kCreateRoute, base::Bind(&MediaRouterWebUIMessageHandler::OnCreateRoute, - base::Unretained(this))); + kCreateRoute, + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnCreateRoute, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kAcknowledgeFirstRunFlow, - base::Bind(&MediaRouterWebUIMessageHandler::OnAcknowledgeFirstRunFlow, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnAcknowledgeFirstRunFlow, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - kActOnIssue, base::Bind(&MediaRouterWebUIMessageHandler::OnActOnIssue, - base::Unretained(this))); + kActOnIssue, + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnActOnIssue, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - kCloseRoute, base::Bind(&MediaRouterWebUIMessageHandler::OnCloseRoute, - base::Unretained(this))); + kCloseRoute, + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnCloseRoute, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - kJoinRoute, base::Bind(&MediaRouterWebUIMessageHandler::OnJoinRoute, - base::Unretained(this))); + kJoinRoute, + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnJoinRoute, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - kCloseDialog, base::Bind(&MediaRouterWebUIMessageHandler::OnCloseDialog, - base::Unretained(this))); + kCloseDialog, + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnCloseDialog, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - kReportBlur, base::Bind(&MediaRouterWebUIMessageHandler::OnReportBlur, - base::Unretained(this))); + kReportBlur, + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnReportBlur, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportClickedSinkIndex, - base::Bind(&MediaRouterWebUIMessageHandler::OnReportClickedSinkIndex, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnReportClickedSinkIndex, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - kReportFilter, base::Bind(&MediaRouterWebUIMessageHandler::OnReportFilter, - base::Unretained(this))); + kReportFilter, + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnReportFilter, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportInitialState, - base::Bind(&MediaRouterWebUIMessageHandler::OnReportInitialState, - base::Unretained(this))); + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnReportInitialState, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportInitialAction, - base::Bind(&MediaRouterWebUIMessageHandler::OnReportInitialAction, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnReportInitialAction, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportRouteCreation, - base::Bind(&MediaRouterWebUIMessageHandler::OnReportRouteCreation, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnReportRouteCreation, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportRouteCreationOutcome, - base::Bind(&MediaRouterWebUIMessageHandler::OnReportRouteCreationOutcome, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnReportRouteCreationOutcome, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportSelectedCastMode, - base::Bind(&MediaRouterWebUIMessageHandler::OnReportSelectedCastMode, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnReportSelectedCastMode, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportNavigateToView, - base::Bind(&MediaRouterWebUIMessageHandler::OnReportNavigateToView, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnReportNavigateToView, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportSinkCount, - base::Bind(&MediaRouterWebUIMessageHandler::OnReportSinkCount, - base::Unretained(this))); + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnReportSinkCount, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportTimeToClickSink, - base::Bind(&MediaRouterWebUIMessageHandler::OnReportTimeToClickSink, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnReportTimeToClickSink, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportTimeToInitialActionClose, - base::Bind( + base::BindRepeating( &MediaRouterWebUIMessageHandler::OnReportTimeToInitialActionClose, base::Unretained(this))); web_ui()->RegisterMessageCallback( kReportWebUIRouteControllerLoaded, - base::Bind( + base::BindRepeating( &MediaRouterWebUIMessageHandler::OnReportWebUIRouteControllerLoaded, base::Unretained(this))); web_ui()->RegisterMessageCallback( kSearchSinksAndCreateRoute, - base::Bind(&MediaRouterWebUIMessageHandler::OnSearchSinksAndCreateRoute, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnSearchSinksAndCreateRoute, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kOnInitialDataReceived, - base::Bind(&MediaRouterWebUIMessageHandler::OnInitialDataReceived, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnInitialDataReceived, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kOnMediaControllerAvailable, - base::Bind(&MediaRouterWebUIMessageHandler::OnMediaControllerAvailable, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnMediaControllerAvailable, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kOnMediaControllerClosed, - base::Bind(&MediaRouterWebUIMessageHandler::OnMediaControllerClosed, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnMediaControllerClosed, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kPauseCurrentMedia, - base::Bind(&MediaRouterWebUIMessageHandler::OnPauseCurrentMedia, - base::Unretained(this))); + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnPauseCurrentMedia, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kPlayCurrentMedia, - base::Bind(&MediaRouterWebUIMessageHandler::OnPlayCurrentMedia, - base::Unretained(this))); + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnPlayCurrentMedia, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kSeekCurrentMedia, - base::Bind(&MediaRouterWebUIMessageHandler::OnSeekCurrentMedia, - base::Unretained(this))); + base::BindRepeating(&MediaRouterWebUIMessageHandler::OnSeekCurrentMedia, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kSelectLocalMediaFile, - base::Bind(&MediaRouterWebUIMessageHandler::OnSelectLocalMediaFile, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnSelectLocalMediaFile, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kSetCurrentMediaMute, - base::Bind(&MediaRouterWebUIMessageHandler::OnSetCurrentMediaMute, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnSetCurrentMediaMute, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kSetCurrentMediaVolume, - base::Bind(&MediaRouterWebUIMessageHandler::OnSetCurrentMediaVolume, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnSetCurrentMediaVolume, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kSetMediaRemotingEnabled, - base::Bind(&MediaRouterWebUIMessageHandler::OnSetMediaRemotingEnabled, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnSetMediaRemotingEnabled, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kHangoutsSetLocalPresent, - base::Bind(&MediaRouterWebUIMessageHandler::OnSetHangoutsLocalPresent, - base::Unretained(this))); + base::BindRepeating( + &MediaRouterWebUIMessageHandler::OnSetHangoutsLocalPresent, + base::Unretained(this))); } void MediaRouterWebUIMessageHandler::OnRequestInitialData( diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h index 8ebaa248630..85d555942c5 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h @@ -13,8 +13,8 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "base/optional.h" -#include "chrome/browser/ui/webui/media_router/media_cast_mode.h" -#include "chrome/browser/ui/webui/media_router/media_sink_with_cast_modes.h" +#include "chrome/browser/ui/media_router/media_cast_mode.h" +#include "chrome/browser/ui/media_router/media_sink_with_cast_modes.h" #include "chrome/common/media_router/issue.h" #include "chrome/common/media_router/media_status.h" #include "components/signin/core/browser/account_info.h" diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc index 69112d983ee..c5793056fc2 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc @@ -398,7 +398,6 @@ TEST_F(MediaRouterWebUIMessageHandlerTest, SetCastModesList) { TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateMediaRouteStatus) { MediaStatus status; status.title = "test title"; - status.description = "test description"; status.can_play_pause = true; status.can_set_volume = true; status.play_state = MediaStatus::PlayState::BUFFERING; @@ -414,7 +413,6 @@ TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateMediaRouteStatus) { ExtractDictFromCallArg("media_router.ui.updateRouteStatus"); EXPECT_EQ(status.title, GetStringFromDict(status_value, "title")); - EXPECT_EQ(status.description, GetStringFromDict(status_value, "description")); EXPECT_EQ(status.can_play_pause, GetBooleanFromDict(status_value, "canPlayPause")); EXPECT_EQ(status.can_mute, GetBooleanFromDict(status_value, "canMute")); diff --git a/chromium/chrome/browser/ui/webui/media_router/media_sink_with_cast_modes.cc b/chromium/chrome/browser/ui/webui/media_router/media_sink_with_cast_modes.cc deleted file mode 100644 index 0c26af3430b..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/media_sink_with_cast_modes.cc +++ /dev/null @@ -1,23 +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/ui/webui/media_router/media_sink_with_cast_modes.h" - -namespace media_router { - -MediaSinkWithCastModes::MediaSinkWithCastModes(const MediaSink& sink) - : sink(sink) { -} - -MediaSinkWithCastModes::MediaSinkWithCastModes( - const MediaSinkWithCastModes& other) = default; - -MediaSinkWithCastModes::~MediaSinkWithCastModes() { -} - -bool MediaSinkWithCastModes::Equals(const MediaSinkWithCastModes& other) const { - return sink.Equals(other.sink) && cast_modes == other.cast_modes; -} - -} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_sink_with_cast_modes.h b/chromium/chrome/browser/ui/webui/media_router/media_sink_with_cast_modes.h deleted file mode 100644 index 7006f68e34a..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/media_sink_with_cast_modes.h +++ /dev/null @@ -1,32 +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_UI_WEBUI_MEDIA_ROUTER_MEDIA_SINK_WITH_CAST_MODES_H_ -#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_SINK_WITH_CAST_MODES_H_ - -#include <set> - -#include "chrome/browser/ui/webui/media_router/media_cast_mode.h" -#include "chrome/common/media_router/media_sink.h" - -namespace media_router { - -// Contains information on a MediaSink and the set of cast modes it is -// compatible with. This should be interpreted under the context of a -// QueryResultManager which contains a mapping from MediaCastMode to -// MediaSource. -struct MediaSinkWithCastModes { - explicit MediaSinkWithCastModes(const MediaSink& sink); - MediaSinkWithCastModes(const MediaSinkWithCastModes& other); - ~MediaSinkWithCastModes(); - - MediaSink sink; - CastModeSet cast_modes; - - bool Equals(const MediaSinkWithCastModes& other) const; -}; - -} // namespace media_router - -#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_SINK_WITH_CAST_MODES_H_ diff --git a/chromium/chrome/browser/ui/webui/media_router/query_result_manager.cc b/chromium/chrome/browser/ui/webui/media_router/query_result_manager.cc deleted file mode 100644 index 701652301c5..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/query_result_manager.cc +++ /dev/null @@ -1,238 +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/ui/webui/media_router/query_result_manager.h" - -#include <utility> - -#include "base/containers/hash_tables.h" -#include "base/stl_util.h" -#include "chrome/browser/media/router/media_router.h" -#include "chrome/browser/media/router/media_sinks_observer.h" -#include "content/public/browser/browser_thread.h" -#include "url/origin.h" - -namespace media_router { - -// MediaSinkObserver that propagates results back to |result_manager|. -// An instance of this class is associated with each registered MediaSource. -class QueryResultManager::MediaSourceMediaSinksObserver - : public MediaSinksObserver { - public: - MediaSourceMediaSinksObserver(MediaCastMode cast_mode, - const MediaSource& source, - const url::Origin& origin, - MediaRouter* router, - QueryResultManager* result_manager) - : MediaSinksObserver(router, source, origin), - cast_mode_(cast_mode), - source_(source), - result_manager_(result_manager) { - DCHECK(result_manager); - } - - ~MediaSourceMediaSinksObserver() override {} - - // MediaSinksObserver - void OnSinksReceived(const std::vector<MediaSink>& result) override { - latest_sink_ids_.clear(); - for (const MediaSink& sink : result) { - latest_sink_ids_.push_back(sink.id()); - } - result_manager_->SetSinksCompatibleWithSource(cast_mode_, source_, result); - result_manager_->NotifyOnResultsUpdated(); - } - - // Returns the most recent sink IDs that were passed to |OnSinksReceived|. - void GetLatestSinkIds(std::vector<MediaSink::Id>* sink_ids) const { - DCHECK(sink_ids); - *sink_ids = latest_sink_ids_; - } - - MediaCastMode cast_mode() const { return cast_mode_; } - - private: - const MediaCastMode cast_mode_; - const MediaSource source_; - std::vector<MediaSink::Id> latest_sink_ids_; - QueryResultManager* const result_manager_; -}; - -QueryResultManager::QueryResultManager(MediaRouter* router) : router_(router) { - DCHECK(router_); -} - -QueryResultManager::~QueryResultManager() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); -} - -void QueryResultManager::AddObserver(Observer* observer) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(observer); - observers_.AddObserver(observer); -} - -void QueryResultManager::RemoveObserver(Observer* observer) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(observer); - observers_.RemoveObserver(observer); -} - -void QueryResultManager::SetSourcesForCastMode( - MediaCastMode cast_mode, - const std::vector<MediaSource>& sources, - const url::Origin& origin) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (sources.empty()) { - LOG(WARNING) << "SetSourcesForCastMode called with empty sources for " - << cast_mode; - return; - } - if (!AreSourcesValidForCastMode(cast_mode, sources)) { - LOG(WARNING) << "SetSourcesForCastMode called with invalid sources for " - << cast_mode; - return; - } - - RemoveOldSourcesForCastMode(cast_mode, sources); - AddObserversForCastMode(cast_mode, sources, origin); - cast_mode_sources_[cast_mode] = sources; - NotifyOnResultsUpdated(); -} - -void QueryResultManager::RemoveSourcesForCastMode(MediaCastMode cast_mode) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - RemoveOldSourcesForCastMode(cast_mode, std::vector<MediaSource>()); - cast_mode_sources_.erase(cast_mode); - NotifyOnResultsUpdated(); -} - -CastModeSet QueryResultManager::GetSupportedCastModes() const { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - CastModeSet modes; - for (const auto& cast_mode_pair : cast_mode_sources_) - modes.insert(cast_mode_pair.first); - - return modes; -} - -std::unique_ptr<MediaSource> QueryResultManager::GetSourceForCastModeAndSink( - MediaCastMode cast_mode, - MediaSink::Id sink_id) const { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - for (const auto& sink_pair : all_sinks_) { - if (sink_pair.first.id() == sink_id) { - return GetHighestPrioritySourceForCastModeAndSink(cast_mode, - sink_pair.second); - } - } - return std::unique_ptr<MediaSource>(); -} - -std::vector<MediaSource> QueryResultManager::GetSourcesForCastMode( - MediaCastMode cast_mode) const { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - const auto& cast_mode_it = cast_mode_sources_.find(cast_mode); - return cast_mode_it == cast_mode_sources_.end() ? std::vector<MediaSource>() - : cast_mode_it->second; -} - -void QueryResultManager::RemoveOldSourcesForCastMode( - MediaCastMode cast_mode, - const std::vector<MediaSource>& new_sources) { - const auto& cast_mode_it = cast_mode_sources_.find(cast_mode); - if (cast_mode_it == cast_mode_sources_.end()) - return; - - for (const MediaSource& source : cast_mode_it->second) { - if (!base::ContainsValue(new_sources, source)) { - sinks_observers_.erase(source); - SetSinksCompatibleWithSource(cast_mode, source, std::vector<MediaSink>()); - } - } -} - -void QueryResultManager::AddObserversForCastMode( - MediaCastMode cast_mode, - const std::vector<MediaSource>& sources, - const url::Origin& origin) { - for (const MediaSource& source : sources) { - if (!base::ContainsKey(sinks_observers_, source)) { - std::unique_ptr<MediaSourceMediaSinksObserver> observer( - new MediaSourceMediaSinksObserver(cast_mode, source, origin, router_, - this)); - observer->Init(); - sinks_observers_[source] = std::move(observer); - } - } -} - -void QueryResultManager::SetSinksCompatibleWithSource( - MediaCastMode cast_mode, - const MediaSource& source, - const std::vector<MediaSink>& new_sinks) { - base::hash_set<MediaSink::Id> new_sink_ids; - for (const MediaSink& sink : new_sinks) - new_sink_ids.insert(sink.id()); - - // (1) Iterate through current sink set, remove cast mode from those that - // do not appear in latest result. - for (auto it = all_sinks_.begin(); it != all_sinks_.end(); /*no-op*/) { - const MediaSink& sink = it->first; - CastModesWithMediaSources& sources_for_sink = it->second; - if (!base::ContainsKey(new_sink_ids, sink.id())) - sources_for_sink.RemoveSource(cast_mode, source); - if (sources_for_sink.IsEmpty()) - all_sinks_.erase(it++); - else - ++it; - } - - // (2) Add / update sinks with latest result. - for (const MediaSink& sink : new_sinks) - all_sinks_[sink].AddSource(cast_mode, source); -} - -std::unique_ptr<MediaSource> -QueryResultManager::GetHighestPrioritySourceForCastModeAndSink( - MediaCastMode cast_mode, - const CastModesWithMediaSources& sources_for_sink) const { - const auto& cast_mode_it = cast_mode_sources_.find(cast_mode); - if (cast_mode_it == cast_mode_sources_.end()) - return std::unique_ptr<MediaSource>(); - - for (const MediaSource& source : cast_mode_it->second) { - if (sources_for_sink.HasSource(cast_mode, source)) - return std::make_unique<MediaSource>(source.id()); - } - return std::unique_ptr<MediaSource>(); -} - -bool QueryResultManager::AreSourcesValidForCastMode( - MediaCastMode cast_mode, - const std::vector<MediaSource>& sources) const { - const auto& cast_mode_it = cast_mode_sources_.find(cast_mode); - bool has_cast_mode = cast_mode_it != cast_mode_sources_.end(); - // If a source has already been registered, then it must be associated with - // |cast_mode|. - return std::find_if( - sources.begin(), sources.end(), [=](const MediaSource& source) { - return base::ContainsKey(sinks_observers_, source) && - (!has_cast_mode || - !base::ContainsValue(cast_mode_it->second, source)); - }) == sources.end(); -} - -void QueryResultManager::NotifyOnResultsUpdated() { - std::vector<MediaSinkWithCastModes> sinks; - for (const auto& sink_pair : all_sinks_) { - MediaSinkWithCastModes sink_with_cast_modes(sink_pair.first); - sink_with_cast_modes.cast_modes = sink_pair.second.GetCastModes(); - sinks.push_back(sink_with_cast_modes); - } - for (QueryResultManager::Observer& observer : observers_) - observer.OnResultsUpdated(sinks); -} - -} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/query_result_manager.h b/chromium/chrome/browser/ui/webui/media_router/query_result_manager.h deleted file mode 100644 index 3e7c56db142..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/query_result_manager.h +++ /dev/null @@ -1,181 +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_UI_WEBUI_MEDIA_ROUTER_QUERY_RESULT_MANAGER_H_ -#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_QUERY_RESULT_MANAGER_H_ - -#include <map> -#include <memory> -#include <set> -#include <unordered_set> -#include <vector> - -#include "base/gtest_prod_util.h" -#include "base/macros.h" -#include "base/observer_list.h" -#include "chrome/browser/media/router/media_routes_observer.h" -#include "chrome/browser/ui/webui/media_router/cast_modes_with_media_sources.h" -#include "chrome/browser/ui/webui/media_router/media_cast_mode.h" -#include "chrome/browser/ui/webui/media_router/media_sink_with_cast_modes.h" -#include "chrome/common/media_router/media_sink.h" -#include "chrome/common/media_router/media_source.h" - -namespace url { -class Origin; -} // namespace url - -namespace media_router { - -class MediaRouter; -class MediaSinksObserver; - -// The Media Router dialog allows the user to initiate casting using one of -// several actions (each represented by a cast mode). Each cast mode is -// associated with a vector of media sources. This class allows the dialog to -// receive lists of MediaSinks compatible with the cast modes available through -// the dialog. -// -// Typical use: -// -// url::Origin origin{GURL("https://origin.com")}; -// QueryResultManager::Observer* observer = ...; -// QueryResultManager result_manager(router); -// result_manager.AddObserver(observer); -// result_manager.SetSourcesForCastMode(MediaCastMode::PRESENTATION, -// {MediaSourceForPresentationUrl("http://google.com")}, origin); -// result_manager.SetSourcesForCastMode(MediaCastMode::TAB_MIRROR, -// {MediaSourceForTab(123)}, origin); -// ... -// [Updates will be received by observer via OnResultsUpdated()] -// ... -// [When info on MediaSource is needed, i.e. when requesting route for a mode] -// CastModeSet cast_modes = result_manager.GetSupportedCastModes(); -// [Logic to select a MediaCastMode from the set] -// std::unique_ptr<MediaSource> source = -// result_manager.GetSourceForCastModeAndSink( -// MediaCastMode::TAB_MIRROR, sink_of_interest); -// if (source) { -// ... -// } -// -// Not thread-safe. Must be used on the UI thread. -class QueryResultManager { - public: - class Observer { - public: - virtual ~Observer() {} - - // Updated results have been received. - // |sinks|: List of sinks and the cast modes they are compatible with. - virtual void OnResultsUpdated( - const std::vector<MediaSinkWithCastModes>& sinks) = 0; - }; - - explicit QueryResultManager(MediaRouter* media_router); - ~QueryResultManager(); - - // Adds/removes an observer that is notified with query results. - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - // Requests a list of MediaSinks compatible with |sources| for |cast_mode| - // from |origin|. |sources| should be in descending order of priority. - // Results are sent to all observers registered with AddObserver(). - // - // Starts new queries in the Media Router for sources that we have no existing - // queries for, and stops queries for sources no longer associated with any - // cast mode. - // - // If |sources| is empty or contains a source that has already been registered - // with another cast mode, no new queries are begun. - void SetSourcesForCastMode(MediaCastMode cast_mode, - const std::vector<MediaSource>& sources, - const url::Origin& origin); - - // Stops notifying observers for |cast_mode|, and removes it from the set of - // supported cast modes. - void RemoveSourcesForCastMode(MediaCastMode cast_mode); - - // Gets the set of cast modes that are being actively queried. - CastModeSet GetSupportedCastModes() const; - - // Gets the highest-priority source for the cast mode that is supported by - // the sink. Returns an empty unique_ptr if there isn't any. - std::unique_ptr<MediaSource> GetSourceForCastModeAndSink( - MediaCastMode cast_mode, - MediaSink::Id sink_id) const; - - // Returns all the sources registered for |cast_mode|. Returns an empty - // vector if there is none. - std::vector<MediaSource> GetSourcesForCastMode(MediaCastMode cast_mode) const; - - private: - class MediaSourceMediaSinksObserver; - - FRIEND_TEST_ALL_PREFIXES(QueryResultManagerTest, Observers); - FRIEND_TEST_ALL_PREFIXES(QueryResultManagerTest, StartRoutesDiscovery); - FRIEND_TEST_ALL_PREFIXES(QueryResultManagerTest, MultipleQueries); - FRIEND_TEST_ALL_PREFIXES(QueryResultManagerTest, MultipleUrls); - FRIEND_TEST_ALL_PREFIXES(QueryResultManagerTest, AddInvalidSource); - - // Stops and destroys the MediaSinksObservers for media sources that - // |cast_mode| used to support, but isn't in |new_sources|, and disassociates - // them from sinks. - void RemoveOldSourcesForCastMode(MediaCastMode cast_mode, - const std::vector<MediaSource>& new_sources); - - // Creates observers and starts queries for each source in |sources| that - // doesn't already have an associated observer. - void AddObserversForCastMode(MediaCastMode cast_mode, - const std::vector<MediaSource>& sources, - const url::Origin& origin); - - // Modifies the set of sinks compatible with |cast_mode| and |source| - // to |new_sinks|. - void SetSinksCompatibleWithSource(MediaCastMode cast_mode, - const MediaSource& source, - const std::vector<MediaSink>& new_sinks); - - // Returns the highest-priority source for |cast_mode| contained in - // |sources_for_sink|. Returns an empty unique_ptr if none exists. - std::unique_ptr<MediaSource> GetHighestPrioritySourceForCastModeAndSink( - MediaCastMode cast_mode, - const CastModesWithMediaSources& sources_for_sink) const; - - // Returns true if every source in |sources| is either not registered yet, or - // associated with |cast_mode|. This check prevents a source from being - // associated with two cast modes. - bool AreSourcesValidForCastMode( - MediaCastMode cast_mode, - const std::vector<MediaSource>& sources) const; - - // Notifies observers that results have been updated. - void NotifyOnResultsUpdated(); - - // MediaSinksObservers that listen for compatible MediaSink updates. - // Each observer is associated with a MediaSource. Results received by - // observers are propagated back to this class. - std::unordered_map<MediaSource, - std::unique_ptr<MediaSinksObserver>, - MediaSource::Hash> - sinks_observers_; - - // Holds registrations of MediaSources for cast modes. - std::map<MediaCastMode, std::vector<MediaSource>> cast_mode_sources_; - - // Holds all known sinks along with the cast modes and sources they support. - std::map<MediaSink, CastModesWithMediaSources, MediaSink::Compare> all_sinks_; - - // Registered observers. - base::ObserverList<Observer> observers_; - - // Not owned by this object. - MediaRouter* const router_; - - DISALLOW_COPY_AND_ASSIGN(QueryResultManager); -}; - -} // namespace media_router - -#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_QUERY_RESULT_MANAGER_H_ diff --git a/chromium/chrome/browser/ui/webui/media_router/query_result_manager_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/query_result_manager_unittest.cc deleted file mode 100644 index f03f84ca9b5..00000000000 --- a/chromium/chrome/browser/ui/webui/media_router/query_result_manager_unittest.cc +++ /dev/null @@ -1,418 +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/ui/webui/media_router/query_result_manager.h" - -#include "base/bind.h" -#include "base/containers/hash_tables.h" -#include "base/json/json_writer.h" -#include "base/macros.h" -#include "chrome/browser/media/router/media_sinks_observer.h" -#include "chrome/browser/media/router/test/mock_media_router.h" -#include "chrome/common/media_router/media_source_helper.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 "url/gurl.h" - -using testing::Eq; -using testing::IsEmpty; -using testing::Eq; -using testing::Mock; -using testing::Return; -using testing::_; - -namespace media_router { - -namespace { - -const char kOrigin[] = "https://origin.com"; - -class MockObserver : public QueryResultManager::Observer { - public: - MOCK_METHOD1(OnResultsUpdated, void( - const std::vector<MediaSinkWithCastModes>& sinks)); -}; - -} // namespace - -class QueryResultManagerTest : public ::testing::Test { - public: - QueryResultManagerTest() - : mock_router_(), query_result_manager_(&mock_router_) { - } - - void DiscoverSinks(MediaCastMode cast_mode, const MediaSource& source) { - EXPECT_CALL(mock_router_, RegisterMediaSinksObserver(_)) - .WillOnce(Return(true)); - EXPECT_CALL(mock_observer_, OnResultsUpdated(_)).Times(1); - query_result_manager_.SetSourcesForCastMode( - cast_mode, {source}, url::Origin::Create(GURL(kOrigin))); - } - - bool IsDefaultSourceForSink(const MediaSource* source, - const MediaSink& sink) { - return IsPreferredSourceForSink(MediaCastMode::PRESENTATION, source, sink); - } - - bool IsTabSourceForSink(const MediaSource* source, const MediaSink& sink) { - return IsPreferredSourceForSink(MediaCastMode::TAB_MIRROR, source, sink); - } - - bool IsPreferredSourceForSink(MediaCastMode cast_mode, - const MediaSource* source, - const MediaSink& sink) { - std::unique_ptr<MediaSource> default_source = - query_result_manager_.GetSourceForCastModeAndSink(cast_mode, sink.id()); - return (!(default_source || source)) || - (default_source && source && *default_source.get() == *source); - } - - content::TestBrowserThreadBundle thread_bundle_; - MockMediaRouter mock_router_; - QueryResultManager query_result_manager_; - MockObserver mock_observer_; - - private: - DISALLOW_COPY_AND_ASSIGN(QueryResultManagerTest); -}; - -MATCHER_P(VectorEquals, expected, "") { - if (expected.size() != arg.size()) { - return false; - } - for (size_t i = 0; i < expected.size(); ++i) { - if (!expected[i].Equals(arg[i])) { - return false; - } - } - return true; -} - -TEST_F(QueryResultManagerTest, Observers) { - MockObserver ob1; - MockObserver ob2; - query_result_manager_.AddObserver(&ob1); - query_result_manager_.AddObserver(&ob2); - - EXPECT_CALL(ob1, OnResultsUpdated(_)).Times(1); - EXPECT_CALL(ob2, OnResultsUpdated(_)).Times(1); - query_result_manager_.NotifyOnResultsUpdated(); - - query_result_manager_.RemoveObserver(&ob2); - EXPECT_CALL(ob1, OnResultsUpdated(_)).Times(1); - query_result_manager_.NotifyOnResultsUpdated(); - - query_result_manager_.RemoveObserver(&ob1); - query_result_manager_.NotifyOnResultsUpdated(); -} - -TEST_F(QueryResultManagerTest, StartStopSinksQuery) { - CastModeSet cast_modes = query_result_manager_.GetSupportedCastModes(); - EXPECT_TRUE(cast_modes.empty()); - std::vector<MediaSource> actual_sources = - query_result_manager_.GetSourcesForCastMode(MediaCastMode::PRESENTATION); - EXPECT_EQ(0u, actual_sources.size()); - - MediaSource source(MediaSourceForPresentationUrl(GURL("http://foo.com"))); - EXPECT_CALL(mock_router_, RegisterMediaSinksObserver(_)) - .WillOnce(Return(true)); - query_result_manager_.SetSourcesForCastMode( - MediaCastMode::PRESENTATION, {source}, - url::Origin::Create(GURL(kOrigin))); - - cast_modes = query_result_manager_.GetSupportedCastModes(); - EXPECT_EQ(1u, cast_modes.size()); - EXPECT_TRUE(base::ContainsKey(cast_modes, MediaCastMode::PRESENTATION)); - actual_sources = - query_result_manager_.GetSourcesForCastMode(MediaCastMode::PRESENTATION); - EXPECT_EQ(1u, actual_sources.size()); - EXPECT_EQ(source, actual_sources[0]); - - // Register a different set of sources for the same cast mode. - MediaSource another_source( - MediaSourceForPresentationUrl(GURL("http://bar.com"))); - EXPECT_CALL(mock_router_, UnregisterMediaSinksObserver(_)).Times(1); - EXPECT_CALL(mock_router_, RegisterMediaSinksObserver(_)) - .WillOnce(Return(true)); - query_result_manager_.SetSourcesForCastMode( - MediaCastMode::PRESENTATION, {another_source}, - url::Origin::Create(GURL(kOrigin))); - - cast_modes = query_result_manager_.GetSupportedCastModes(); - EXPECT_EQ(1u, cast_modes.size()); - EXPECT_TRUE(base::ContainsKey(cast_modes, MediaCastMode::PRESENTATION)); - actual_sources = - query_result_manager_.GetSourcesForCastMode(MediaCastMode::PRESENTATION); - EXPECT_EQ(1u, actual_sources.size()); - EXPECT_EQ(another_source, actual_sources[0]); - - EXPECT_CALL(mock_router_, UnregisterMediaSinksObserver(_)).Times(1); - query_result_manager_.RemoveSourcesForCastMode(MediaCastMode::PRESENTATION); - - cast_modes = query_result_manager_.GetSupportedCastModes(); - EXPECT_TRUE(cast_modes.empty()); - actual_sources = - query_result_manager_.GetSourcesForCastMode(MediaCastMode::PRESENTATION); - EXPECT_EQ(0u, actual_sources.size()); -} - -TEST_F(QueryResultManagerTest, MultipleQueries) { - MediaSink sink1("sinkId1", "Sink 1", SinkIconType::CAST); - MediaSink sink2("sinkId2", "Sink 2", SinkIconType::CAST); - MediaSink sink3("sinkId3", "Sink 3", SinkIconType::CAST); - MediaSink sink4("sinkId4", "Sink 4", SinkIconType::CAST); - MediaSink sink5("sinkId5", "Sink 5", SinkIconType::CAST); - MediaSource presentation_source1 = - MediaSourceForPresentationUrl(GURL("http://bar.com")); - MediaSource presentation_source2 = - MediaSourceForPresentationUrl(GURL("http://baz.com")); - MediaSource tab_source = MediaSourceForTab(123); - - query_result_manager_.AddObserver(&mock_observer_); - DiscoverSinks(MediaCastMode::PRESENTATION, presentation_source1); - DiscoverSinks(MediaCastMode::TAB_MIRROR, tab_source); - - // Scenario (results in this order): - // Action: PRESENTATION -> [1, 2, 3] - // Expected result: - // Sinks: [1 -> {PRESENTATION}, 2 -> {PRESENTATION}, 3 -> {PRESENTATION}] - std::vector<MediaSinkWithCastModes> expected_sinks; - expected_sinks.push_back(MediaSinkWithCastModes(sink1)); - expected_sinks.back().cast_modes.insert(MediaCastMode::PRESENTATION); - expected_sinks.push_back(MediaSinkWithCastModes(sink2)); - expected_sinks.back().cast_modes.insert(MediaCastMode::PRESENTATION); - expected_sinks.push_back(MediaSinkWithCastModes(sink3)); - expected_sinks.back().cast_modes.insert(MediaCastMode::PRESENTATION); - - const auto& sinks_observers = query_result_manager_.sinks_observers_; - auto sinks_observer_it = sinks_observers.find(presentation_source1); - ASSERT_TRUE(sinks_observer_it != sinks_observers.end()); - ASSERT_TRUE(sinks_observer_it->second.get()); - - std::vector<MediaSink> sinks_query_result; - sinks_query_result.push_back(sink1); - sinks_query_result.push_back(sink2); - sinks_query_result.push_back(sink3); - EXPECT_CALL(mock_observer_, - OnResultsUpdated(VectorEquals(expected_sinks))).Times(1); - sinks_observer_it->second->OnSinksUpdated(sinks_query_result, - std::vector<url::Origin>()); - - // Action: TAB_MIRROR -> [2, 3, 4] - // Expected result: - // Sinks: [1 -> {PRESENTATION}, 2 -> {PRESENTATION, TAB_MIRROR}, - // 3 -> {PRESENTATION, TAB_MIRROR}, 4 -> {TAB_MIRROR}] - expected_sinks.clear(); - expected_sinks.push_back(MediaSinkWithCastModes(sink1)); - expected_sinks.back().cast_modes.insert(MediaCastMode::PRESENTATION); - expected_sinks.push_back(MediaSinkWithCastModes(sink2)); - expected_sinks.back().cast_modes.insert(MediaCastMode::PRESENTATION); - expected_sinks.back().cast_modes.insert(MediaCastMode::TAB_MIRROR); - expected_sinks.push_back(MediaSinkWithCastModes(sink3)); - expected_sinks.back().cast_modes.insert(MediaCastMode::PRESENTATION); - expected_sinks.back().cast_modes.insert(MediaCastMode::TAB_MIRROR); - expected_sinks.push_back(MediaSinkWithCastModes(sink4)); - expected_sinks.back().cast_modes.insert(MediaCastMode::TAB_MIRROR); - - sinks_query_result.clear(); - sinks_query_result.push_back(sink2); - sinks_query_result.push_back(sink3); - sinks_query_result.push_back(sink4); - - sinks_observer_it = sinks_observers.find(tab_source); - ASSERT_TRUE(sinks_observer_it != sinks_observers.end()); - ASSERT_TRUE(sinks_observer_it->second.get()); - EXPECT_CALL(mock_observer_, - OnResultsUpdated(VectorEquals(expected_sinks))).Times(1); - sinks_observer_it->second->OnSinksUpdated( - sinks_query_result, {url::Origin::Create(GURL(kOrigin))}); - - // Action: Update presentation URL - // Expected result: - // Sinks: [2 -> {TAB_MIRROR}, 3 -> {TAB_MIRROR}, 4 -> {TAB_MIRROR}] - expected_sinks.clear(); - expected_sinks.push_back(MediaSinkWithCastModes(sink2)); - expected_sinks.back().cast_modes.insert(MediaCastMode::TAB_MIRROR); - expected_sinks.push_back(MediaSinkWithCastModes(sink3)); - expected_sinks.back().cast_modes.insert(MediaCastMode::TAB_MIRROR); - expected_sinks.push_back(MediaSinkWithCastModes(sink4)); - expected_sinks.back().cast_modes.insert(MediaCastMode::TAB_MIRROR); - - // The observer for the old source will be unregistered. - EXPECT_CALL(mock_router_, UnregisterMediaSinksObserver(_)).Times(1); - // The observer for the new source will be registered. - EXPECT_CALL(mock_router_, RegisterMediaSinksObserver(_)) - .WillOnce(Return(true)); - EXPECT_CALL(mock_observer_, - OnResultsUpdated(VectorEquals(expected_sinks))).Times(1); - query_result_manager_.SetSourcesForCastMode( - MediaCastMode::PRESENTATION, {presentation_source2}, - url::Origin::Create(GURL(kOrigin))); - - // Action: PRESENTATION -> [1], origins don't match - // Expected result: [2 -> {TAB_MIRROR}, 3 -> {TAB_MIRROR}, 4 -> {TAB_MIRROR}] - // (No change) - sinks_query_result.clear(); - sinks_query_result.push_back(sink1); - sinks_observer_it = sinks_observers.find(presentation_source2); - ASSERT_TRUE(sinks_observer_it != sinks_observers.end()); - ASSERT_TRUE(sinks_observer_it->second.get()); - EXPECT_CALL(mock_observer_, OnResultsUpdated(VectorEquals(expected_sinks))) - .Times(1); - sinks_observer_it->second->OnSinksUpdated( - sinks_query_result, - {url::Origin::Create(GURL("https://differentOrigin.com"))}); - - // Action: Remove TAB_MIRROR observer - // Expected result: - // Sinks: [] - expected_sinks.clear(); - EXPECT_CALL(mock_observer_, - OnResultsUpdated(VectorEquals(expected_sinks))).Times(1); - EXPECT_CALL(mock_router_, UnregisterMediaSinksObserver(_)).Times(1); - query_result_manager_.RemoveSourcesForCastMode(MediaCastMode::TAB_MIRROR); - - // Remaining observers: PRESENTATION observer, which will be removed on - // destruction - EXPECT_CALL(mock_router_, UnregisterMediaSinksObserver(_)).Times(1); -} - -TEST_F(QueryResultManagerTest, MultipleUrls) { - const MediaSink sink1("sinkId1", "Sink 1", SinkIconType::CAST); - const MediaSink sink2("sinkId2", "Sink 2", SinkIconType::CAST); - const MediaSink sink3("sinkId3", "Sink 3", SinkIconType::CAST); - const MediaSink sink4("sinkId4", "Sink 4", SinkIconType::CAST); - const MediaSource source_a( - MediaSourceForPresentationUrl(GURL("http://urlA.com"))); - const MediaSource source_b( - MediaSourceForPresentationUrl(GURL("http://urlB.com"))); - const MediaSource source_c( - MediaSourceForPresentationUrl(GURL("http://urlC.com"))); - const MediaSource source_tab(MediaSourceForTab(1)); - // The sources are in decreasing order of priority. - const std::vector<MediaSource> presentation_sources = {source_a, source_b, - source_c}; - const std::vector<MediaSource> tab_sources = {source_tab}; - const auto& sinks_observers = query_result_manager_.sinks_observers_; - - // There should be one MediaSinksObserver per source. - EXPECT_CALL(mock_router_, RegisterMediaSinksObserver(_)) - .Times(4) - .WillRepeatedly(Return(true)); - query_result_manager_.SetSourcesForCastMode( - MediaCastMode::PRESENTATION, presentation_sources, - url::Origin::Create(GURL(kOrigin))); - query_result_manager_.SetSourcesForCastMode( - MediaCastMode::TAB_MIRROR, tab_sources, - url::Origin::Create(GURL(kOrigin))); - - // Scenario (results in this order): - // Action: URL_B -> [2, 4] - // Expected result: - // Sinks: [1 -> {}, - // 2 -> {URL_B}, - // 3 -> {}, - // 4 -> {URL_B}] - auto sinks_observer_it = sinks_observers.find(source_b); - ASSERT_TRUE(sinks_observer_it != sinks_observers.end()); - ASSERT_TRUE(sinks_observer_it->second.get()); - - auto& source_b_observer = sinks_observer_it->second; - source_b_observer->OnSinksUpdated({sink2, sink4}, std::vector<url::Origin>()); - EXPECT_TRUE(IsDefaultSourceForSink(nullptr, sink1)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_b, sink2)); - EXPECT_TRUE(IsDefaultSourceForSink(nullptr, sink3)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_b, sink4)); - - // Action: URL_C -> [1, 2, 3] - // Expected result: - // Sinks: [1 -> {URL_C}, - // 2 -> {URL_B, URL_C}, - // 3 -> {URL_C}, - // 4 -> {URL_B}] - sinks_observer_it = sinks_observers.find(source_c); - ASSERT_TRUE(sinks_observer_it != sinks_observers.end()); - ASSERT_TRUE(sinks_observer_it->second.get()); - - auto& source_c_observer = sinks_observer_it->second; - source_c_observer->OnSinksUpdated({sink1, sink2, sink3}, - std::vector<url::Origin>()); - EXPECT_TRUE(IsDefaultSourceForSink(&source_c, sink1)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_b, sink2)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_c, sink3)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_b, sink4)); - - // Action: URL_A -> [2, 3, 4] - // Expected result: - // Sinks: [1 -> {URL_C}, - // 2 -> {URL_A, URL_B, URL_C}, - // 3 -> {URL_A, URL_C}, - // 4 -> {URL_A, URL_B}] - sinks_observer_it = sinks_observers.find(source_a); - ASSERT_TRUE(sinks_observer_it != sinks_observers.end()); - ASSERT_TRUE(sinks_observer_it->second.get()); - - auto& source_a_observer = sinks_observer_it->second; - source_a_observer->OnSinksUpdated({sink2, sink3, sink4}, - std::vector<url::Origin>()); - EXPECT_TRUE(IsDefaultSourceForSink(&source_c, sink1)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_a, sink2)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_a, sink3)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_a, sink4)); - - // Action: TAB -> [1, 2] - // Expected result: - // Sinks: [1 -> {URL_C, TAB}, - // 2 -> {URL_A, URL_B, URL_C, TAB}, - // 3 -> {URL_A, URL_C}, - // 4 -> {URL_A, URL_B}] - sinks_observer_it = sinks_observers.find(source_tab); - ASSERT_TRUE(sinks_observer_it != sinks_observers.end()); - ASSERT_TRUE(sinks_observer_it->second.get()); - - auto& source_tab_observer = sinks_observer_it->second; - source_tab_observer->OnSinksUpdated({sink1, sink2}, - std::vector<url::Origin>()); - EXPECT_TRUE(IsDefaultSourceForSink(&source_c, sink1)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_a, sink2)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_a, sink3)); - EXPECT_TRUE(IsDefaultSourceForSink(&source_a, sink4)); - EXPECT_TRUE(IsTabSourceForSink(&source_tab, sink1)); - EXPECT_TRUE(IsTabSourceForSink(&source_tab, sink2)); - EXPECT_TRUE(IsTabSourceForSink(nullptr, sink3)); - EXPECT_TRUE(IsTabSourceForSink(nullptr, sink4)); - - // The observers for the four sources should get unregistered. - EXPECT_CALL(mock_router_, UnregisterMediaSinksObserver(_)).Times(4); - query_result_manager_.RemoveSourcesForCastMode(MediaCastMode::PRESENTATION); - query_result_manager_.RemoveSourcesForCastMode(MediaCastMode::TAB_MIRROR); -} - -TEST_F(QueryResultManagerTest, AddInvalidSource) { - const MediaSource source( - MediaSourceForPresentationUrl(GURL("http://url.com"))); - - EXPECT_CALL(mock_router_, RegisterMediaSinksObserver(_)) - .Times(1) - .WillRepeatedly(Return(true)); - query_result_manager_.SetSourcesForCastMode( - MediaCastMode::PRESENTATION, {source}, - url::Origin::Create(GURL(kOrigin))); - // |source| has already been registered with the PRESENTATION cast mode, so it - // shouldn't get registered with tab mirroring. - query_result_manager_.SetSourcesForCastMode( - MediaCastMode::TAB_MIRROR, {source}, url::Origin::Create(GURL(kOrigin))); - - const auto& cast_mode_sources = query_result_manager_.cast_mode_sources_; - const auto& presentation_sources = - cast_mode_sources.at(MediaCastMode::PRESENTATION); - EXPECT_TRUE( - base::ContainsKey(cast_mode_sources, MediaCastMode::PRESENTATION)); - EXPECT_EQ(presentation_sources.size(), 1u); - EXPECT_EQ(presentation_sources.at(0), source); - EXPECT_FALSE(base::ContainsKey(cast_mode_sources, MediaCastMode::TAB_MIRROR)); -} - -} // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc index c38eda39caa..324b4809393 100644 --- a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc @@ -25,6 +25,7 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" +#include "components/services/heap_profiling/public/cpp/settings.h" #include "content/public/browser/browser_child_process_host_iterator.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" @@ -40,7 +41,8 @@ #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/select_file_policy.h" -using profiling::ProfilingProcessHost; +using heap_profiling::Mode; +using heap_profiling::ProfilingProcessHost; namespace { @@ -48,36 +50,36 @@ namespace { std::string GetMessageString() { #if BUILDFLAG(USE_ALLOCATOR_SHIM) switch (ProfilingProcessHost::GetInstance()->GetMode()) { - case ProfilingProcessHost::Mode::kAll: + case Mode::kAll: return std::string("Memory logging is enabled for all processes."); - case ProfilingProcessHost::Mode::kAllRenderers: + case Mode::kAllRenderers: return std::string("Memory logging is enabled for all renderers."); - case ProfilingProcessHost::Mode::kBrowser: + case Mode::kBrowser: return std::string( "Memory logging is enabled for just the browser process."); - case ProfilingProcessHost::Mode::kGpu: + case Mode::kGpu: return std::string("Memory logging is enabled for just the gpu process."); - case ProfilingProcessHost::Mode::kMinimal: + case Mode::kMinimal: return std::string( "Memory logging is enabled for the browser and GPU processes."); - case ProfilingProcessHost::Mode::kRendererSampling: + case Mode::kRendererSampling: return std::string( "Memory logging is enabled for an automatic sample of renderer " "processes. This UI is disabled."); - case ProfilingProcessHost::Mode::kNone: - case ProfilingProcessHost::Mode::kManual: + case Mode::kNone: + case Mode::kManual: default: return std::string( "Memory logging must be manually enabled for each process via " "chrome://memory-internals."); } -#elif defined(ADDRESS_SANITIZER) || defined(SYZYASAN) +#elif defined(ADDRESS_SANITIZER) return "Memory logging is not available in this build because a memory " "sanitizer is running."; #else @@ -171,8 +173,8 @@ void MemoryInternalsDOMHandler::RegisterMessages() { // the WebUI. web_ui()->RegisterMessageCallback( "requestProcessList", - base::Bind(&MemoryInternalsDOMHandler::HandleRequestProcessList, - base::Unretained(this))); + base::BindRepeating(&MemoryInternalsDOMHandler::HandleRequestProcessList, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "saveDump", base::BindRepeating(&MemoryInternalsDOMHandler::HandleSaveDump, diff --git a/chromium/chrome/browser/ui/webui/metrics_handler.cc b/chromium/chrome/browser/ui/webui/metrics_handler.cc index 21fcb2cb0bb..69117325518 100644 --- a/chromium/chrome/browser/ui/webui/metrics_handler.cc +++ b/chromium/chrome/browser/ui/webui/metrics_handler.cc @@ -26,21 +26,24 @@ MetricsHandler::~MetricsHandler() {} void MetricsHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "metricsHandler:recordAction", - base::Bind(&MetricsHandler::HandleRecordAction, base::Unretained(this))); + base::BindRepeating(&MetricsHandler::HandleRecordAction, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "metricsHandler:recordInHistogram", - base::Bind(&MetricsHandler::HandleRecordInHistogram, - base::Unretained(this))); + base::BindRepeating(&MetricsHandler::HandleRecordInHistogram, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "metricsHandler:recordBooleanHistogram", - base::Bind(&MetricsHandler::HandleRecordBooleanHistogram, - base::Unretained(this))); + base::BindRepeating(&MetricsHandler::HandleRecordBooleanHistogram, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "metricsHandler:recordTime", - base::Bind(&MetricsHandler::HandleRecordTime, base::Unretained(this))); + base::BindRepeating(&MetricsHandler::HandleRecordTime, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "metricsHandler:logEventTime", - base::Bind(&MetricsHandler::HandleLogEventTime, base::Unretained(this))); + base::BindRepeating(&MetricsHandler::HandleLogEventTime, + base::Unretained(this))); } void MetricsHandler::HandleRecordAction(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/mojo_web_ui_controller.cc b/chromium/chrome/browser/ui/webui/mojo_web_ui_controller.cc deleted file mode 100644 index fc51c20e93a..00000000000 --- a/chromium/chrome/browser/ui/webui/mojo_web_ui_controller.cc +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/mojo_web_ui_controller.h" - -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/mojo_web_ui_handler.h" -#include "content/public/browser/render_process_host.h" -#include "content/public/browser/web_ui_data_source.h" -#include "content/public/common/bindings_policy.h" -#include "mojo/public/cpp/system/core.h" - -MojoWebUIControllerBase::MojoWebUIControllerBase(content::WebUI* contents) - : WebUIController(contents) {} - -MojoWebUIControllerBase::~MojoWebUIControllerBase() { -} - -void MojoWebUIControllerBase::RenderFrameCreated( - content::RenderFrameHost* render_frame_host) { - render_frame_host->AllowBindings(content::BINDINGS_POLICY_WEB_UI); -} diff --git a/chromium/chrome/browser/ui/webui/mojo_web_ui_controller.h b/chromium/chrome/browser/ui/webui/mojo_web_ui_controller.h deleted file mode 100644 index 627e5799b1b..00000000000 --- a/chromium/chrome/browser/ui/webui/mojo_web_ui_controller.h +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_MOJO_WEB_UI_CONTROLLER_H_ -#define CHROME_BROWSER_UI_WEBUI_MOJO_WEB_UI_CONTROLLER_H_ - -#include <memory> -#include <string> - -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/ui/webui/mojo_web_ui_handler.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/browser/render_view_host.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_contents_observer.h" -#include "content/public/browser/web_ui_controller.h" -#include "mojo/public/cpp/system/core.h" -#include "services/service_manager/public/cpp/binder_registry.h" - -class MojoWebUIControllerBase : public content::WebUIController { - public: - explicit MojoWebUIControllerBase(content::WebUI* contents); - ~MojoWebUIControllerBase() override; - - // WebUIController overrides: - void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override; - - private: - DISALLOW_COPY_AND_ASSIGN(MojoWebUIControllerBase); -}; - -// MojoWebUIController is intended for web ui pages that use mojo. It is -// expected that subclasses will do two things: -// . In the constructor invoke AddMojoResourcePath() to register the bindings -// files, eg: -// AddMojoResourcePath("chrome/browser/ui/webui/omnibox/omnibox.mojom", -// IDR_OMNIBOX_MOJO_JS); -// . Override BindUIHandler() to create and bind the implementation of the -// bindings. -template <typename Interface> -class MojoWebUIController : public MojoWebUIControllerBase, - public content::WebContentsObserver { - public: - explicit MojoWebUIController(content::WebUI* contents) - : MojoWebUIControllerBase(contents), - content::WebContentsObserver(contents->GetWebContents()), - weak_factory_(this) { - registry_.AddInterface<Interface>(base::Bind( - &MojoWebUIController::BindUIHandler, base::Unretained(this))); - } - ~MojoWebUIController() override {} - - // content::WebContentsObserver implementation. - void OnInterfaceRequestFromFrame( - content::RenderFrameHost* render_frame_host, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle* interface_pipe) override { - // Right now, this is expected to be called only for main frames. - DCHECK(!render_frame_host->GetParent()); - registry_.TryBindInterface(interface_name, interface_pipe); - } - - protected: - // Invoked to create the specific bindings implementation. - virtual void BindUIHandler(mojo::InterfaceRequest<Interface> request) = 0; - - private: - service_manager::BinderRegistry registry_; - - base::WeakPtrFactory<MojoWebUIController> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(MojoWebUIController); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_MOJO_WEB_UI_CONTROLLER_H_ diff --git a/chromium/chrome/browser/ui/webui/mojo_web_ui_handler.h b/chromium/chrome/browser/ui/webui/mojo_web_ui_handler.h deleted file mode 100644 index 22d2ef02c28..00000000000 --- a/chromium/chrome/browser/ui/webui/mojo_web_ui_handler.h +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_MOJO_WEB_UI_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_MOJO_WEB_UI_HANDLER_H_ - -// Bindings implementations must subclass this. Used so that MojoWebUIController -// can own the binding implementation. -class MojoWebUIHandler { - public: - MojoWebUIHandler() {} - virtual ~MojoWebUIHandler() {} -}; - -#endif // CHROME_BROWSER_UI_WEBUI_MOJO_WEB_UI_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/nacl_ui.cc b/chromium/chrome/browser/ui/webui/nacl_ui.cc index d687697c457..153107f052d 100644 --- a/chromium/chrome/browser/ui/webui/nacl_ui.cc +++ b/chromium/chrome/browser/ui/webui/nacl_ui.cc @@ -151,8 +151,8 @@ NaClDomHandler::~NaClDomHandler() { void NaClDomHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "requestNaClInfo", - base::Bind(&NaClDomHandler::HandleRequestNaClInfo, - base::Unretained(this))); + base::BindRepeating(&NaClDomHandler::HandleRequestNaClInfo, + base::Unretained(this))); } // Helper functions for collecting a list of key-value pairs that will @@ -183,10 +183,9 @@ bool NaClDomHandler::isPluginEnabled(size_t plugin_index) { void NaClDomHandler::AddOperatingSystemInfo(base::ListValue* list) { // Obtain the Chrome version info. - AddPair(list, - l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), + AddPair(list, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), ASCIIToUTF16(version_info::GetVersionNumber() + " (" + - chrome::GetChannelString() + ")")); + chrome::GetChannelName() + ")")); // OS version information. // TODO(jvoung): refactor this to share the extra windows labeling diff --git a/chromium/chrome/browser/ui/webui/net_export_ui.cc b/chromium/chrome/browser/ui/webui/net_export_ui.cc index 96b332cda49..24a70cf5093 100644 --- a/chromium/chrome/browser/ui/webui/net_export_ui.cc +++ b/chromium/chrome/browser/ui/webui/net_export_ui.cc @@ -36,7 +36,7 @@ #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/browser/web_ui_message_handler.h" -#include "extensions/features/features.h" +#include "extensions/buildflags/buildflags.h" #include "net/log/net_log_capture_mode.h" #include "net/url_request/url_request_context_getter.h" #include "ui/shell_dialogs/select_file_dialog.h" @@ -185,23 +185,24 @@ void NetExportMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( net_log::kEnableNotifyUIWithStateHandler, - base::Bind(&NetExportMessageHandler::OnEnableNotifyUIWithState, - base::Unretained(this))); + base::BindRepeating(&NetExportMessageHandler::OnEnableNotifyUIWithState, + base::Unretained(this))); web_ui()->RegisterMessageCallback( net_log::kStartNetLogHandler, - base::Bind(&NetExportMessageHandler::OnStartNetLog, - base::Unretained(this))); + base::BindRepeating(&NetExportMessageHandler::OnStartNetLog, + base::Unretained(this))); web_ui()->RegisterMessageCallback( net_log::kStopNetLogHandler, - base::Bind(&NetExportMessageHandler::OnStopNetLog, - base::Unretained(this))); + base::BindRepeating(&NetExportMessageHandler::OnStopNetLog, + base::Unretained(this))); web_ui()->RegisterMessageCallback( net_log::kSendNetLogHandler, - base::Bind(&NetExportMessageHandler::OnSendNetLog, - base::Unretained(this))); + base::BindRepeating(&NetExportMessageHandler::OnSendNetLog, + base::Unretained(this))); web_ui()->RegisterMessageCallback( net_log::kShowFile, - base::Bind(&NetExportMessageHandler::OnShowFile, base::Unretained(this))); + base::BindRepeating(&NetExportMessageHandler::OnShowFile, + base::Unretained(this))); } // The net-export UI is not notified of state changes until this function runs. @@ -333,7 +334,7 @@ void NetExportMessageHandler::StartNetLog(const base::FilePath& path) { file_writer_->StartNetLog( path, capture_mode_, max_log_file_size_, base::CommandLine::ForCurrentProcess()->GetCommandLineString(), - chrome::GetChannelString(), GetURLRequestContexts()); + chrome::GetChannelName(), GetURLRequestContexts()); } void NetExportMessageHandler::ShowFileInShell(const base::FilePath& path) { diff --git a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc index 302df0f9a2c..9a9192ba671 100644 --- a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc @@ -72,7 +72,7 @@ #include "net/log/net_log_capture_mode.h" #include "net/log/net_log_entry.h" #include "net/log/net_log_util.h" -#include "net/proxy_resolution/proxy_service.h" +#include "net/proxy_resolution/proxy_resolution_service.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" @@ -424,101 +424,102 @@ void NetInternalsMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "notifyReady", - base::Bind(&NetInternalsMessageHandler::OnRendererReady, - base::Unretained(this))); + base::BindRepeating(&NetInternalsMessageHandler::OnRendererReady, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "getNetInfo", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnGetNetInfo, proxy_)); + "getNetInfo", base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnGetNetInfo, proxy_)); web_ui()->RegisterMessageCallback( "reloadProxySettings", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnReloadProxySettings, proxy_)); + base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnReloadProxySettings, proxy_)); web_ui()->RegisterMessageCallback( "clearBadProxies", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnClearBadProxies, proxy_)); + base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnClearBadProxies, proxy_)); web_ui()->RegisterMessageCallback( "clearHostResolverCache", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnClearHostResolverCache, proxy_)); + base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnClearHostResolverCache, proxy_)); web_ui()->RegisterMessageCallback( "domainSecurityPolicyDelete", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnDomainSecurityPolicyDelete, proxy_)); + base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnDomainSecurityPolicyDelete, proxy_)); web_ui()->RegisterMessageCallback( - "hstsQuery", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnHSTSQuery, proxy_)); + "hstsQuery", base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnHSTSQuery, proxy_)); web_ui()->RegisterMessageCallback( - "hstsAdd", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnHSTSAdd, proxy_)); + "hstsAdd", base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnHSTSAdd, proxy_)); web_ui()->RegisterMessageCallback( - "expectCTQuery", base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnExpectCTQuery, proxy_)); + "expectCTQuery", + base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnExpectCTQuery, proxy_)); web_ui()->RegisterMessageCallback( - "expectCTAdd", base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnExpectCTAdd, proxy_)); + "expectCTAdd", base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnExpectCTAdd, proxy_)); web_ui()->RegisterMessageCallback( "expectCTTestReport", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnExpectCTTestReport, proxy_)); + base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnExpectCTTestReport, proxy_)); web_ui()->RegisterMessageCallback( "closeIdleSockets", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnCloseIdleSockets, proxy_)); + base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnCloseIdleSockets, proxy_)); web_ui()->RegisterMessageCallback( "flushSocketPools", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnFlushSocketPools, proxy_)); + base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnFlushSocketPools, proxy_)); #if defined(OS_WIN) web_ui()->RegisterMessageCallback( "getServiceProviders", - base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnGetServiceProviders, proxy_)); + base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnGetServiceProviders, proxy_)); #endif web_ui()->RegisterMessageCallback( - "setCaptureMode", base::Bind(&IOThreadImpl::CallbackHelper, - &IOThreadImpl::OnSetCaptureMode, proxy_)); + "setCaptureMode", + base::BindRepeating(&IOThreadImpl::CallbackHelper, + &IOThreadImpl::OnSetCaptureMode, proxy_)); web_ui()->RegisterMessageCallback( "clearBrowserCache", - base::Bind(&NetInternalsMessageHandler::OnClearBrowserCache, - base::Unretained(this))); + base::BindRepeating(&NetInternalsMessageHandler::OnClearBrowserCache, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getPrerenderInfo", - base::Bind(&NetInternalsMessageHandler::OnGetPrerenderInfo, - base::Unretained(this))); + base::BindRepeating(&NetInternalsMessageHandler::OnGetPrerenderInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getHistoricNetworkStats", - base::Bind(&NetInternalsMessageHandler::OnGetHistoricNetworkStats, - base::Unretained(this))); + base::BindRepeating( + &NetInternalsMessageHandler::OnGetHistoricNetworkStats, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getSessionNetworkStats", - base::Bind(&NetInternalsMessageHandler::OnGetSessionNetworkStats, - base::Unretained(this))); + base::BindRepeating(&NetInternalsMessageHandler::OnGetSessionNetworkStats, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getExtensionInfo", - base::Bind(&NetInternalsMessageHandler::OnGetExtensionInfo, - base::Unretained(this))); + base::BindRepeating(&NetInternalsMessageHandler::OnGetExtensionInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getDataReductionProxyInfo", - base::Bind(&NetInternalsMessageHandler::OnGetDataReductionProxyInfo, - base::Unretained(this))); + base::BindRepeating( + &NetInternalsMessageHandler::OnGetDataReductionProxyInfo, + base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( "importONCFile", - base::Bind(&NetInternalsMessageHandler::OnImportONCFile, - base::Unretained(this))); + base::BindRepeating(&NetInternalsMessageHandler::OnImportONCFile, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "storeDebugLogs", - base::Bind(&NetInternalsMessageHandler::OnStoreDebugLogs, - base::Unretained(this))); + base::BindRepeating(&NetInternalsMessageHandler::OnStoreDebugLogs, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setNetworkDebugMode", - base::Bind(&NetInternalsMessageHandler::OnSetNetworkDebugMode, - base::Unretained(this))); + base::BindRepeating(&NetInternalsMessageHandler::OnSetNetworkDebugMode, + base::Unretained(this))); #endif } @@ -663,7 +664,7 @@ void NetInternalsMessageHandler::IOThreadImpl::OnRendererReady( "receivedConstants", net_log::ChromeNetLog::GetConstants( base::CommandLine::ForCurrentProcess()->GetCommandLineString(), - chrome::GetChannelString())); + chrome::GetChannelName())); PrePopulateEventList(); diff --git a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc index 3acf04451cb..ac58f8b1ce6 100644 --- a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc @@ -31,6 +31,7 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/net_log/chrome_net_log.h" #include "components/prefs/pref_service.h" +#include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_message_handler.h" @@ -187,41 +188,53 @@ NetInternalsTest::MessageHandler::MessageHandler( } void NetInternalsTest::MessageHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("getTestServerURL", - base::Bind(&NetInternalsTest::MessageHandler::GetTestServerURL, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("addCacheEntry", - base::Bind(&NetInternalsTest::MessageHandler::AddCacheEntry, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getTestServerURL", + base::BindRepeating(&NetInternalsTest::MessageHandler::GetTestServerURL, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "addCacheEntry", + base::BindRepeating(&NetInternalsTest::MessageHandler::AddCacheEntry, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "changeNetwork", - base::Bind(&NetInternalsTest::MessageHandler::ChangeNetwork, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("loadPage", - base::Bind(&NetInternalsTest::MessageHandler::LoadPage, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("prerenderPage", - base::Bind(&NetInternalsTest::MessageHandler::PrerenderPage, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("navigateToPrerender", - base::Bind(&NetInternalsTest::MessageHandler::NavigateToPrerender, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("createIncognitoBrowser", - base::Bind(&NetInternalsTest::MessageHandler::CreateIncognitoBrowser, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("closeIncognitoBrowser", - base::Bind(&NetInternalsTest::MessageHandler::CloseIncognitoBrowser, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("getNetLogFileContents", - base::Bind( + base::BindRepeating(&NetInternalsTest::MessageHandler::ChangeNetwork, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "loadPage", + base::BindRepeating(&NetInternalsTest::MessageHandler::LoadPage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "prerenderPage", + base::BindRepeating(&NetInternalsTest::MessageHandler::PrerenderPage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "navigateToPrerender", + base::BindRepeating( + &NetInternalsTest::MessageHandler::NavigateToPrerender, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "createIncognitoBrowser", + base::BindRepeating( + &NetInternalsTest::MessageHandler::CreateIncognitoBrowser, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "closeIncognitoBrowser", + base::BindRepeating( + &NetInternalsTest::MessageHandler::CloseIncognitoBrowser, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getNetLogFileContents", + base::BindRepeating( &NetInternalsTest::MessageHandler::GetNetLogFileContents, base::Unretained(this))); web_ui()->RegisterMessageCallback( "setUpTestReportURI", - base::Bind(&NetInternalsTest::MessageHandler::SetUpTestReportURI, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("enableDataReductionProxy", - base::Bind( + base::BindRepeating(&NetInternalsTest::MessageHandler::SetUpTestReportURI, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "enableDataReductionProxy", + base::BindRepeating( &NetInternalsTest::MessageHandler::EnableDataReductionProxy, base::Unretained(this))); } @@ -330,7 +343,7 @@ void NetInternalsTest::MessageHandler::GetNetLogFileContents( std::unique_ptr<base::Value> constants(net_log::ChromeNetLog::GetConstants( base::CommandLine::ForCurrentProcess()->GetCommandLineString(), - chrome::GetChannelString())); + chrome::GetChannelName())); std::unique_ptr<net::FileNetLogObserver> net_log_logger = net::FileNetLogObserver::CreateUnbounded(state->log_path, diff --git a/chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.cc b/chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.cc index beaad4ec2c2..fe8bd9cb925 100644 --- a/chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.cc +++ b/chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.cc @@ -39,8 +39,8 @@ AppIconWebUIHandler::~AppIconWebUIHandler() {} void AppIconWebUIHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getAppIconDominantColor", - base::Bind(&AppIconWebUIHandler::HandleGetAppIconDominantColor, - base::Unretained(this))); + base::BindRepeating(&AppIconWebUIHandler::HandleGetAppIconDominantColor, + base::Unretained(this))); } void AppIconWebUIHandler::HandleGetAppIconDominantColor( diff --git a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc index 604df9e0b0c..a073ddf6153 100644 --- a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc +++ b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc @@ -223,39 +223,46 @@ void AppLauncherHandler::RegisterMessages() { registrar_.Add(this, chrome::NOTIFICATION_APP_INSTALLED_TO_NTP, content::Source<WebContents>(web_ui()->GetWebContents())); - web_ui()->RegisterMessageCallback("getApps", - base::Bind(&AppLauncherHandler::HandleGetApps, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("launchApp", - base::Bind(&AppLauncherHandler::HandleLaunchApp, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("setLaunchType", - base::Bind(&AppLauncherHandler::HandleSetLaunchType, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("uninstallApp", - base::Bind(&AppLauncherHandler::HandleUninstallApp, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("createAppShortcut", - base::Bind(&AppLauncherHandler::HandleCreateAppShortcut, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("showAppInfo", - base::Bind(&AppLauncherHandler::HandleShowAppInfo, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("reorderApps", - base::Bind(&AppLauncherHandler::HandleReorderApps, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("setPageIndex", - base::Bind(&AppLauncherHandler::HandleSetPageIndex, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("saveAppPageName", - base::Bind(&AppLauncherHandler::HandleSaveAppPageName, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("generateAppForLink", - base::Bind(&AppLauncherHandler::HandleGenerateAppForLink, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("pageSelected", - base::Bind(&AppLauncherHandler::HandlePageSelected, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getApps", base::BindRepeating(&AppLauncherHandler::HandleGetApps, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "launchApp", base::BindRepeating(&AppLauncherHandler::HandleLaunchApp, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "setLaunchType", + base::BindRepeating(&AppLauncherHandler::HandleSetLaunchType, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "uninstallApp", + base::BindRepeating(&AppLauncherHandler::HandleUninstallApp, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "createAppShortcut", + base::BindRepeating(&AppLauncherHandler::HandleCreateAppShortcut, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "showAppInfo", base::BindRepeating(&AppLauncherHandler::HandleShowAppInfo, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "reorderApps", base::BindRepeating(&AppLauncherHandler::HandleReorderApps, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "setPageIndex", + base::BindRepeating(&AppLauncherHandler::HandleSetPageIndex, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "saveAppPageName", + base::BindRepeating(&AppLauncherHandler::HandleSaveAppPageName, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "generateAppForLink", + base::BindRepeating(&AppLauncherHandler::HandleGenerateAppForLink, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "pageSelected", + base::BindRepeating(&AppLauncherHandler::HandlePageSelected, + base::Unretained(this))); } void AppLauncherHandler::Observe(int type, diff --git a/chromium/chrome/browser/ui/webui/ntp/core_app_launcher_handler.cc b/chromium/chrome/browser/ui/webui/ntp/core_app_launcher_handler.cc index 42573605dd9..da342981c09 100644 --- a/chromium/chrome/browser/ui/webui/ntp/core_app_launcher_handler.cc +++ b/chromium/chrome/browser/ui/webui/ntp/core_app_launcher_handler.cc @@ -64,7 +64,8 @@ void CoreAppLauncherHandler::RecordAppLaunchByUrl( } void CoreAppLauncherHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("recordAppLaunchByURL", - base::Bind(&CoreAppLauncherHandler::HandleRecordAppLaunchByUrl, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "recordAppLaunchByURL", + base::BindRepeating(&CoreAppLauncherHandler::HandleRecordAppLaunchByUrl, + base::Unretained(this))); } diff --git a/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc b/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc index 36cdfcfe8e4..d71fefdb9a4 100644 --- a/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc +++ b/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc @@ -21,7 +21,7 @@ #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/apps/app_info_dialog.h" -#include "chrome/browser/ui/bookmarks/bookmark_bar_constants.h" +#include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/webui/app_launcher_login_handler.h" #include "chrome/browser/ui/webui/ntp/app_launcher_handler.h" #include "chrome/common/buildflags.h" @@ -108,7 +108,7 @@ std::string GetNewTabBackgroundCSS(const ui::ThemeProvider& theme_provider, if (alignment & ThemeProperties::ALIGN_TOP) { // The bar is detached, so we must offset the background by the bar size // if it's a top-aligned bar. - int offset = chrome::kNTPBookmarkBarHeight; + int offset = GetLayoutConstant(BOOKMARK_BAR_NTP_HEIGHT); if (alignment & ThemeProperties::ALIGN_LEFT) return "left " + base::IntToString(-offset) + "px"; diff --git a/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc b/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc index 5513e2c6e93..7915180992d 100644 --- a/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc @@ -50,7 +50,8 @@ class ChromeNTPTilesInternalsMessageHandlerClient PrefService* GetPrefs() override; void RegisterMessageCallback( const std::string& message, - const base::Callback<void(const base::ListValue*)>& callback) override; + const base::RepeatingCallback<void(const base::ListValue*)>& callback) + override; void CallJavascriptFunctionVector( const std::string& name, const std::vector<const base::Value*>& values) override; @@ -101,7 +102,7 @@ PrefService* ChromeNTPTilesInternalsMessageHandlerClient::GetPrefs() { void ChromeNTPTilesInternalsMessageHandlerClient::RegisterMessageCallback( const std::string& message, - const base::Callback<void(const base::ListValue*)>& callback) { + const base::RepeatingCallback<void(const base::ListValue*)>& callback) { web_ui()->RegisterMessageCallback(message, callback); } diff --git a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc index 8053b7ab8bd..9ca918dd9d7 100644 --- a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc @@ -492,75 +492,86 @@ void OfflineInternalsUIMessageHandler::HandleSavePageLaterCallback( void OfflineInternalsUIMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "deleteSelectedPages", - base::Bind(&OfflineInternalsUIMessageHandler::HandleDeleteSelectedPages, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleDeleteSelectedPages, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "deleteSelectedRequests", - base::Bind( + base::BindRepeating( &OfflineInternalsUIMessageHandler::HandleDeleteSelectedRequests, base::Unretained(this))); web_ui()->RegisterMessageCallback( "getRequestQueue", - base::Bind(&OfflineInternalsUIMessageHandler::HandleGetRequestQueue, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleGetRequestQueue, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getStoredPages", - base::Bind(&OfflineInternalsUIMessageHandler::HandleGetStoredPages, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleGetStoredPages, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getEventLogs", - base::Bind(&OfflineInternalsUIMessageHandler::HandleGetEventLogs, - base::Unretained(this))); + base::BindRepeating(&OfflineInternalsUIMessageHandler::HandleGetEventLogs, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setRecordRequestQueue", - base::Bind(&OfflineInternalsUIMessageHandler::HandleSetRecordRequestQueue, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleSetRecordRequestQueue, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setRecordPageModel", - base::Bind(&OfflineInternalsUIMessageHandler::HandleSetRecordPageModel, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleSetRecordPageModel, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setRecordPrefetchService", - base::Bind( + base::BindRepeating( &OfflineInternalsUIMessageHandler::HandleSetRecordPrefetchService, base::Unretained(this))); web_ui()->RegisterMessageCallback( "getLoggingState", - base::Bind(&OfflineInternalsUIMessageHandler::HandleGetLoggingState, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleGetLoggingState, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "addToRequestQueue", - base::Bind(&OfflineInternalsUIMessageHandler::HandleAddToRequestQueue, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleAddToRequestQueue, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getNetworkStatus", - base::Bind(&OfflineInternalsUIMessageHandler::HandleGetNetworkStatus, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleGetNetworkStatus, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "scheduleNwake", - base::Bind(&OfflineInternalsUIMessageHandler::HandleScheduleNwake, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleScheduleNwake, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "cancelNwake", - base::Bind(&OfflineInternalsUIMessageHandler::HandleCancelNwake, - base::Unretained(this))); + base::BindRepeating(&OfflineInternalsUIMessageHandler::HandleCancelNwake, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "showPrefetchNotification", - base::Bind( + base::BindRepeating( &OfflineInternalsUIMessageHandler::HandleShowPrefetchNotification, base::Unretained(this))); web_ui()->RegisterMessageCallback( "generatePageBundle", - base::Bind(&OfflineInternalsUIMessageHandler::HandleGeneratePageBundle, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleGeneratePageBundle, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getOperation", - base::Bind(&OfflineInternalsUIMessageHandler::HandleGetOperation, - base::Unretained(this))); + base::BindRepeating(&OfflineInternalsUIMessageHandler::HandleGetOperation, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "downloadArchive", - base::Bind(&OfflineInternalsUIMessageHandler::HandleDownloadArchive, - base::Unretained(this))); + base::BindRepeating( + &OfflineInternalsUIMessageHandler::HandleDownloadArchive, + base::Unretained(this))); // Get the offline page model associated with this web ui. Profile* profile = Profile::FromWebUI(web_ui()); diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.h b/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.h index 3633baebd73..bd972c1e80a 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.h +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.h @@ -12,7 +12,6 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/time/time.h" -#include "chrome/browser/ui/webui/mojo_web_ui_handler.h" #include "chrome/browser/ui/webui/omnibox/omnibox.mojom.h" #include "components/omnibox/browser/autocomplete_controller_delegate.h" #include "components/omnibox/browser/autocomplete_input.h" @@ -27,8 +26,7 @@ class Profile; // AutocompleteController to OnResultChanged() and passes those results to // the OmniboxPage. class OmniboxPageHandler : public AutocompleteControllerDelegate, - public mojom::OmniboxPageHandler, - public MojoWebUIHandler { + public mojom::OmniboxPageHandler { public: // OmniboxPageHandler is deleted when the supplied pipe is destroyed. OmniboxPageHandler(Profile* profile, diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc index 1fcab38336d..d170f64210b 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc @@ -14,7 +14,8 @@ #include "content/public/browser/web_ui_controller.h" #include "content/public/browser/web_ui_data_source.h" -OmniboxUI::OmniboxUI(content::WebUI* web_ui) : MojoWebUIController(web_ui) { +OmniboxUI::OmniboxUI(content::WebUI* web_ui) + : ui::MojoWebUIController<mojom::OmniboxPageHandler>(web_ui) { // Set up the chrome://omnibox/ source. content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOmniboxHost); diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.h b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.h index 613dbbb78cb..473c38243d4 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.h +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.h @@ -6,19 +6,19 @@ #define CHROME_BROWSER_UI_WEBUI_OMNIBOX_OMNIBOX_UI_H_ #include "base/macros.h" -#include "chrome/browser/ui/webui/mojo_web_ui_controller.h" #include "chrome/browser/ui/webui/omnibox/omnibox.mojom.h" +#include "ui/webui/mojo_web_ui_controller.h" class OmniboxPageHandler; // The UI for chrome://omnibox/ -class OmniboxUI : public MojoWebUIController<mojom::OmniboxPageHandler> { +class OmniboxUI : public ui::MojoWebUIController<mojom::OmniboxPageHandler> { public: explicit OmniboxUI(content::WebUI* contents); ~OmniboxUI() override; private: - // MojoWebUIController overrides: + // ui::MojoWebUIController overrides: void BindUIHandler(mojom::OmniboxPageHandlerRequest request) override; std::unique_ptr<OmniboxPageHandler> omnibox_handler_; diff --git a/chromium/chrome/browser/ui/webui/plural_string_handler.cc b/chromium/chrome/browser/ui/webui/plural_string_handler.cc index 4693d198562..69cd5e22796 100644 --- a/chromium/chrome/browser/ui/webui/plural_string_handler.cc +++ b/chromium/chrome/browser/ui/webui/plural_string_handler.cc @@ -16,8 +16,9 @@ PluralStringHandler::~PluralStringHandler() {} void PluralStringHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "getPluralString", base::Bind(&PluralStringHandler::HandleGetPluralString, - base::Unretained(this))); + "getPluralString", + base::BindRepeating(&PluralStringHandler::HandleGetPluralString, + base::Unretained(this))); } void PluralStringHandler::AddLocalizedString(const std::string& name, int id) { diff --git a/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc index 5cc0cefebf9..29c17795b7b 100644 --- a/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc @@ -10,21 +10,29 @@ namespace policy_indicator { +struct LocalizedString { + const char* name; + int id; +}; + void AddLocalizedStrings(content::WebUIDataSource* html_source) { - html_source->AddLocalizedString("controlledSettingPolicy", - IDS_CONTROLLED_SETTING_POLICY); - html_source->AddLocalizedString("controlledSettingRecommendedMatches", - IDS_CONTROLLED_SETTING_RECOMMENDED); - html_source->AddLocalizedString("controlledSettingRecommendedDiffers", - IDS_CONTROLLED_SETTING_HAS_RECOMMENDATION); - html_source->AddLocalizedString("controlledSettingExtension", - IDS_CONTROLLED_SETTING_EXTENSION); + LocalizedString localized_strings[] = { + {"controlledSettingPolicy", IDS_CONTROLLED_SETTING_POLICY}, + {"controlledSettingRecommendedMatches", IDS_CONTROLLED_SETTING_RECOMMENDED}, + {"controlledSettingRecommendedDiffers", + IDS_CONTROLLED_SETTING_HAS_RECOMMENDATION}, + {"controlledSettingExtension", IDS_CONTROLLED_SETTING_EXTENSION}, + {"controlledSettingExtensionWithoutName", + IDS_CONTROLLED_SETTING_EXTENSION_WITHOUT_NAME}, #if defined(OS_CHROMEOS) - html_source->AddLocalizedString("controlledSettingShared", - IDS_CONTROLLED_SETTING_SHARED); - html_source->AddLocalizedString("controlledSettingOwner", - IDS_CONTROLLED_SETTING_OWNER); + {"controlledSettingShared", IDS_CONTROLLED_SETTING_SHARED}, + {"controlledSettingOwner", IDS_CONTROLLED_SETTING_OWNER}, #endif + }; + + for (size_t i = 0; i < arraysize(localized_strings); i++) + html_source->AddLocalizedString(localized_strings[i].name, + localized_strings[i].id); } } // namespace policy_indicator diff --git a/chromium/chrome/browser/ui/webui/policy_tool_ui.cc b/chromium/chrome/browser/ui/webui/policy_tool_ui.cc index 4152ba140dd..83c45ebffdf 100644 --- a/chromium/chrome/browser/ui/webui/policy_tool_ui.cc +++ b/chromium/chrome/browser/ui/webui/policy_tool_ui.cc @@ -26,13 +26,18 @@ content::WebUIDataSource* CreatePolicyToolUIHtmlSource() { source->AddLocalizedString("noPoliciesSet", IDS_POLICY_NO_POLICIES_SET); source->AddLocalizedString("showExpandedValue", IDS_POLICY_SHOW_EXPANDED_VALUE); + source->AddLocalizedString("exportLinux", IDS_EXPORT_POLICIES_LINUX); source->AddLocalizedString("hideExpandedValue", IDS_POLICY_HIDE_EXPANDED_VALUE); source->AddLocalizedString("loadSession", IDS_POLICY_TOOL_LOAD_SESSION); + source->AddLocalizedString("removeSession", IDS_POLICY_TOOL_REMOVE_SESSION); + source->AddLocalizedString("renameSession", IDS_POLICY_TOOL_RENAME_SESSION); source->AddLocalizedString("sessionNamePlaceholder", IDS_POLICY_TOOL_SESSION_NAME_PLACEHOLDER); source->AddLocalizedString("filterPlaceholder", IDS_POLICY_FILTER_PLACEHOLDER); + source->AddLocalizedString("cancelRename", IDS_POLICY_TOOL_CANCEL_RENAME); + source->AddLocalizedString("confirmRename", IDS_POLICY_TOOL_CONFIRM_RENAME); source->AddLocalizedString("edit", IDS_POLICY_TOOL_EDIT); source->AddLocalizedString("save", IDS_POLICY_TOOL_SAVE); source->AddLocalizedString("errorSavingDisabled", @@ -42,6 +47,12 @@ content::WebUIDataSource* CreatePolicyToolUIHtmlSource() { source->AddLocalizedString("errorFileCorrupted", IDS_POLICY_TOOL_CORRUPTED_FILE); source->AddLocalizedString("enableEditing", IDS_POLICY_TOOL_ENABLE_EDITING); + source->AddLocalizedString("errorRenameFailed", + IDS_POLICY_TOOL_RENAME_FAILED); + source->AddLocalizedString("errorSessionExist", + IDS_POLICY_TOOL_SESSION_EXIST); + source->AddLocalizedString("errorSessionNotExist", + IDS_POLICY_TOOL_SESSION_NOT_EXIST); source->AddLocalizedString("errorDeleteFailed", IDS_POLICY_TOOL_DELETE_FAILED); // Overwrite the title value added by PolicyUIHandler. diff --git a/chromium/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc index 6700b111186..de744a0e7b0 100644 --- a/chromium/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc @@ -6,7 +6,10 @@ #include "base/json/json_writer.h" #include "base/macros.h" #include "base/path_service.h" +#include "base/strings/strcat.h" #include "base/strings/utf_string_conversions.h" +#include "base/task_scheduler/post_task.h" +#include "base/task_scheduler/task_traits.h" #include "base/test/scoped_feature_list.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" @@ -22,6 +25,22 @@ #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" +#include "ui/shell_dialogs/select_file_dialog.h" +#include "ui/shell_dialogs/select_file_dialog_factory.h" +#include "ui/shell_dialogs/select_file_policy.h" + +namespace { + +const base::FilePath::CharType kPolicyToolSessionsDir[] = + FILE_PATH_LITERAL("Policy sessions"); + +const base::FilePath::CharType kPolicyToolDefaultSessionName[] = + FILE_PATH_LITERAL("policy"); + +const base::FilePath::CharType kPolicyToolSessionExtension[] = + FILE_PATH_LITERAL("json"); + +} // namespace class PolicyToolUITest : public InProcessBrowserTest { public: @@ -29,8 +48,6 @@ class PolicyToolUITest : public InProcessBrowserTest { ~PolicyToolUITest() override; protected: - // InProcessBrowserTest implementation. - void SetUpInProcessBrowserTestFixture() override; void SetUp() override; base::FilePath GetSessionsDir(); @@ -40,10 +57,13 @@ class PolicyToolUITest : public InProcessBrowserTest { void LoadSession(const std::string& session_name); void DeleteSession(const std::string& session_name); + void RenameSession(const std::string& session_name, + const std::string& new_session_name); std::unique_ptr<base::DictionaryValue> ExtractPolicyValues(bool need_status); bool IsInvalidSessionNameErrorMessageDisplayed(); + bool IsSessionRenameErrorMessageDisplayed(); std::unique_ptr<base::ListValue> ExtractSessionsList(); @@ -66,15 +86,15 @@ base::FilePath PolicyToolUITest::GetSessionsDir() { base::FilePath profile_dir; EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DATA, &profile_dir)); return profile_dir.AppendASCII(TestingProfile::kTestUserProfileDir) - .Append(PolicyToolUIHandler::kPolicyToolSessionsDir); + .Append(kPolicyToolSessionsDir); } base::FilePath::StringType PolicyToolUITest::GetDefaultSessionName() { - return PolicyToolUIHandler::kPolicyToolDefaultSessionName; + return kPolicyToolDefaultSessionName; } base::FilePath::StringType PolicyToolUITest::GetSessionExtension() { - return PolicyToolUIHandler::kPolicyToolSessionExtension; + return kPolicyToolSessionExtension; } base::FilePath PolicyToolUITest::GetSessionPath( @@ -88,8 +108,6 @@ PolicyToolUITest::PolicyToolUITest() {} PolicyToolUITest::~PolicyToolUITest() {} -void PolicyToolUITest::SetUpInProcessBrowserTestFixture() {} - void PolicyToolUITest::SetUp() { scoped_feature_list_.InitAndEnableFeature(features::kPolicyTool); InProcessBrowserTest::SetUp(); @@ -114,6 +132,18 @@ void PolicyToolUITest::DeleteSession(const std::string& session_name) { content::RunAllTasksUntilIdle(); } +void PolicyToolUITest::RenameSession(const std::string& session_name, + const std::string& new_session_name) { + const std::string javascript = + base::StrCat({"$('session-list').value = '", session_name, "';", + "$('rename-session-button').click();", + "$('new-session-name-field').value = '", new_session_name, + "';", "$('confirm-rename-button').click();"}); + EXPECT_TRUE(content::ExecuteScript( + browser()->tab_strip_model()->GetActiveWebContents(), javascript)); + content::RunAllTasksUntilIdle(); +} + std::unique_ptr<base::DictionaryValue> PolicyToolUITest::ExtractPolicyValues( bool need_status) { std::string javascript = @@ -170,6 +200,16 @@ bool PolicyToolUITest::IsInvalidSessionNameErrorMessageDisplayed() { return result; } +bool PolicyToolUITest::IsSessionRenameErrorMessageDisplayed() { + constexpr char kJavascript[] = + "domAutomationController.send($('session-rename-error').hidden == false)"; + content::WebContents* contents = + browser()->tab_strip_model()->GetActiveWebContents(); + bool result = false; + EXPECT_TRUE(ExecuteScriptAndExtractBool(contents, kJavascript, &result)); + return result; +} + void PolicyToolUITest::CreateMultipleSessionFiles(int count) { base::ScopedAllowBlockingForTesting allow_blocking; EXPECT_TRUE(base::CreateDirectory(GetSessionsDir())); @@ -222,6 +262,85 @@ std::string PolicyToolUITest::ExtractSinglePolicyValue( return value->GetString(); } +class PolicyToolUIExportTest : public PolicyToolUITest { + public: + PolicyToolUIExportTest(); + ~PolicyToolUIExportTest() override; + + protected: + // InProcessBrowserTest implementation. + void SetUpInProcessBrowserTestFixture() override; + + // The temporary directory and file path for policy saving. + base::ScopedTempDir export_policies_test_dir_; + base::FilePath export_policies_test_file_path_; +}; + +PolicyToolUIExportTest::PolicyToolUIExportTest() {} + +PolicyToolUIExportTest::~PolicyToolUIExportTest() {} + +void PolicyToolUIExportTest::SetUpInProcessBrowserTestFixture() { + ASSERT_TRUE(export_policies_test_dir_.CreateUniqueTempDir()); + const std::string filename = "policy.json"; + export_policies_test_file_path_ = + export_policies_test_dir_.GetPath().AppendASCII(filename); +} + +// An artificial SelectFileDialog that immediately returns the location of test +// file instead of showing the UI file picker. +class TestSelectFileDialogPolicyTool : public ui::SelectFileDialog { + public: + TestSelectFileDialogPolicyTool(ui::SelectFileDialog::Listener* listener, + std::unique_ptr<ui::SelectFilePolicy> policy, + const base::FilePath& default_selected_path) + : ui::SelectFileDialog(listener, std::move(policy)) { + default_path_ = default_selected_path; + } + + void SelectFileImpl(Type type, + const base::string16& title, + const base::FilePath& default_path, + const FileTypeInfo* file_types, + int file_type_index, + const base::FilePath::StringType& default_extension, + gfx::NativeWindow owning_window, + void* params) override { + listener_->FileSelected(default_path_, /*index=*/0, /*params=*/nullptr); + } + + bool IsRunning(gfx::NativeWindow owning_window) const override { + return false; + } + + void ListenerDestroyed() override {} + + bool HasMultipleFileTypeChoicesImpl() override { return false; } + + private: + ~TestSelectFileDialogPolicyTool() override {} + base::FilePath default_path_; +}; + +// A factory associated with the artificial file picker. +class TestSelectFileDialogFactoryPolicyTool + : public ui::SelectFileDialogFactory { + public: + TestSelectFileDialogFactoryPolicyTool( + const base::FilePath& default_selected_path) { + default_path_ = default_selected_path; + } + + private: + base::FilePath default_path_; + ui::SelectFileDialog* Create( + ui::SelectFileDialog::Listener* listener, + std::unique_ptr<ui::SelectFilePolicy> policy) override { + return new TestSelectFileDialogPolicyTool(listener, std::move(policy), + default_path_); + } +}; + IN_PROC_BROWSER_TEST_F(PolicyToolUITest, CreatingSessionFiles) { base::ScopedAllowBlockingForTesting allow_blocking; // Check that the directory is not created yet. @@ -327,6 +446,8 @@ IN_PROC_BROWSER_TEST_F(PolicyToolUITest, InvalidSessionName) { EXPECT_FALSE(IsInvalidSessionNameErrorMessageDisplayed()); LoadSession("../test"); EXPECT_TRUE(IsInvalidSessionNameErrorMessageDisplayed()); + LoadSession("/full_path"); + EXPECT_TRUE(IsInvalidSessionNameErrorMessageDisplayed()); LoadSession("policy"); EXPECT_FALSE(IsInvalidSessionNameErrorMessageDisplayed()); } @@ -429,3 +550,99 @@ IN_PROC_BROWSER_TEST_F(PolicyToolUITest, DeleteSession) { expected.GetList().erase(expected.GetList().begin()); EXPECT_EQ(expected, *ExtractSessionsList()); } + +IN_PROC_BROWSER_TEST_F(PolicyToolUITest, RenameSession) { + CreateMultipleSessionFiles(3); + ui_test_utils::NavigateToURL(browser(), GURL("chrome://policy-tool")); + EXPECT_EQ("2", ExtractSinglePolicyValue("SessionId")); + + // Check that a non-current session is renamed correctly. + RenameSession("0", "4"); + EXPECT_FALSE(IsSessionRenameErrorMessageDisplayed()); + base::ListValue expected; + expected.GetList().push_back(base::Value("2")); + expected.GetList().push_back(base::Value("1")); + expected.GetList().push_back(base::Value("4")); + EXPECT_EQ(expected, *ExtractSessionsList()); + + // Check that the current session can be renamed properly. + RenameSession("2", "5"); + EXPECT_FALSE(IsSessionRenameErrorMessageDisplayed()); + expected.GetList()[0] = base::Value("5"); + EXPECT_EQ(expected, *ExtractSessionsList()); +} + +IN_PROC_BROWSER_TEST_F(PolicyToolUITest, RenameSessionWithExistingSessionName) { + CreateMultipleSessionFiles(3); + ui_test_utils::NavigateToURL(browser(), GURL("chrome://policy-tool")); + EXPECT_EQ("2", ExtractSinglePolicyValue("SessionId")); + + // Check that a session can not be renamed with a name of another existing + // session. + RenameSession("2", "1"); + EXPECT_TRUE(IsSessionRenameErrorMessageDisplayed()); + base::ListValue expected; + expected.GetList().push_back(base::Value("2")); + expected.GetList().push_back(base::Value("1")); + expected.GetList().push_back(base::Value("0")); + EXPECT_EQ(expected, *ExtractSessionsList()); +} + +IN_PROC_BROWSER_TEST_F(PolicyToolUITest, RenameSessionInvalidName) { + CreateMultipleSessionFiles(3); + ui_test_utils::NavigateToURL(browser(), GURL("chrome://policy-tool")); + EXPECT_EQ("2", ExtractSinglePolicyValue("SessionId")); + + RenameSession("2", "../"); + EXPECT_TRUE(IsSessionRenameErrorMessageDisplayed()); + base::ListValue expected; + expected.GetList().push_back(base::Value("2")); + expected.GetList().push_back(base::Value("1")); + expected.GetList().push_back(base::Value("0")); + EXPECT_EQ(expected, *ExtractSessionsList()); + + // Check that full path is not allowed + RenameSession("2", "/full_path"); + EXPECT_TRUE(IsSessionRenameErrorMessageDisplayed()); + EXPECT_EQ(expected, *ExtractSessionsList()); +} + +IN_PROC_BROWSER_TEST_F(PolicyToolUIExportTest, ExportSessionPolicyToLinux) { + CreateMultipleSessionFiles(3); + + // Set SelectFileDialog to use our factory. + ui::SelectFileDialog::SetFactory(new TestSelectFileDialogFactoryPolicyTool( + export_policies_test_file_path_)); + + // Test if the current session policy is successfully exported. + ui_test_utils::NavigateToURL(browser(), GURL("chrome://policy-tool")); + std::string javascript = + "$('show-unset').click();" + "var policyEntry = document.querySelectorAll(" + " 'section.policy-table-section > * > tbody')[0];" + "policyEntry.getElementsByClassName('edit-button')[0].click();" + "policyEntry.getElementsByClassName('value-edit-field')[0].value =" + " 'test';" + "policyEntry.getElementsByClassName('save-button')[0].click();" + "$('export-policies-linux').click()"; + + content::WebContents* contents = + browser()->tab_strip_model()->GetActiveWebContents(); + EXPECT_TRUE(content::ExecuteScript(contents, javascript)); + + // Because we created 3 session policies (with paths {0, 1, 2}), the last one + // is the current active session policy. + EXPECT_TRUE(base::ContentsEqual(export_policies_test_file_path_, + GetSessionPath(FILE_PATH_LITERAL("2")))); + + // Test if after an export action, we can continue exporting. + std::string change_session_js = + "$('session-name-field').value = '1';" + "$('load-session-button').click();"; + + EXPECT_TRUE(content::ExecuteScript(contents, change_session_js + javascript)); + base::TaskScheduler::GetInstance()->FlushForTesting(); + EXPECT_TRUE(base::ContentsEqual(export_policies_test_file_path_, + GetSessionPath(FILE_PATH_LITERAL("1")))); + TestSelectFileDialogPolicyTool::SetFactory(nullptr); +} diff --git a/chromium/chrome/browser/ui/webui/policy_tool_ui_handler.cc b/chromium/chrome/browser/ui/webui/policy_tool_ui_handler.cc index fd4370040b6..c9202afefe3 100644 --- a/chromium/chrome/browser/ui/webui/policy_tool_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/policy_tool_ui_handler.cc @@ -11,62 +11,35 @@ #include "base/strings/utf_string_conversions.h" #include "base/task_scheduler/post_task.h" #include "build/build_config.h" +#include "chrome/browser/download/download_prefs.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/chrome_select_file_policy.h" +#include "components/strings/grit/components_strings.h" +#include "content/public/browser/web_contents.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/shell_dialogs/select_file_policy.h" -// static -const base::FilePath::CharType PolicyToolUIHandler::kPolicyToolSessionsDir[] = +namespace { + +const base::FilePath::CharType kPolicyToolSessionsDir[] = FILE_PATH_LITERAL("Policy sessions"); -// static -const base::FilePath::CharType - PolicyToolUIHandler::kPolicyToolDefaultSessionName[] = - FILE_PATH_LITERAL("policy"); +const base::FilePath::CharType kPolicyToolDefaultSessionName[] = + FILE_PATH_LITERAL("policy"); -// static -const base::FilePath::CharType - PolicyToolUIHandler::kPolicyToolSessionExtension[] = - FILE_PATH_LITERAL("json"); +const base::FilePath::CharType kPolicyToolSessionExtension[] = + FILE_PATH_LITERAL("json"); -PolicyToolUIHandler::PolicyToolUIHandler() : callback_weak_ptr_factory_(this) {} - -PolicyToolUIHandler::~PolicyToolUIHandler() {} +const base::FilePath::CharType kPolicyToolLinuxExtension[] = + FILE_PATH_LITERAL("json"); -void PolicyToolUIHandler::RegisterMessages() { - // Set directory for storing sessions. - sessions_dir_ = - Profile::FromWebUI(web_ui())->GetPath().Append(kPolicyToolSessionsDir); - - web_ui()->RegisterMessageCallback( - "initialized", base::Bind(&PolicyToolUIHandler::HandleInitializedAdmin, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "loadSession", base::Bind(&PolicyToolUIHandler::HandleLoadSession, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "updateSession", base::Bind(&PolicyToolUIHandler::HandleUpdateSession, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "resetSession", base::Bind(&PolicyToolUIHandler::HandleResetSession, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "deleteSession", base::Bind(&PolicyToolUIHandler::HandleDeleteSession, - base::Unretained(this))); -} - -void PolicyToolUIHandler::OnJavascriptDisallowed() { - callback_weak_ptr_factory_.InvalidateWeakPtrs(); -} - -base::FilePath PolicyToolUIHandler::GetSessionPath( - const base::FilePath::StringType& name) const { - return sessions_dir_.Append(name).AddExtension(kPolicyToolSessionExtension); -} - -base::ListValue PolicyToolUIHandler::GetSessionsList() { +// Returns the current list of all sessions sorted by last access time in +// decreasing order. +base::ListValue GetSessionsList(const base::FilePath& sessions_dir) { base::FilePath::StringType sessions_pattern = FILE_PATH_LITERAL("*.") + base::FilePath::StringType(kPolicyToolSessionExtension); - base::FileEnumerator enumerator(sessions_dir_, /*recursive=*/false, + base::FileEnumerator enumerator(sessions_dir, /*recursive=*/false, base::FileEnumerator::FILES, sessions_pattern); // A vector of session names and their last access times. @@ -89,8 +62,58 @@ base::ListValue PolicyToolUIHandler::GetSessionsList() { return session_names; } +} // namespace + +PolicyToolUIHandler::PolicyToolUIHandler() : callback_weak_ptr_factory_(this) {} + +PolicyToolUIHandler::~PolicyToolUIHandler() {} + +void PolicyToolUIHandler::RegisterMessages() { + // Set directory for storing sessions. + sessions_dir_ = + Profile::FromWebUI(web_ui())->GetPath().Append(kPolicyToolSessionsDir); + + web_ui()->RegisterMessageCallback( + "initialized", + base::BindRepeating(&PolicyToolUIHandler::HandleInitializedAdmin, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "loadSession", + base::BindRepeating(&PolicyToolUIHandler::HandleLoadSession, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "renameSession", + base::BindRepeating(&PolicyToolUIHandler::HandleRenameSession, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "updateSession", + base::BindRepeating(&PolicyToolUIHandler::HandleUpdateSession, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "resetSession", + base::BindRepeating(&PolicyToolUIHandler::HandleResetSession, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "deleteSession", + base::BindRepeating(&PolicyToolUIHandler::HandleDeleteSession, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "exportLinux", + base::BindRepeating(&PolicyToolUIHandler::HandleExportLinux, + base::Unretained(this))); +} + +void PolicyToolUIHandler::OnJavascriptDisallowed() { + callback_weak_ptr_factory_.InvalidateWeakPtrs(); +} + +base::FilePath PolicyToolUIHandler::GetSessionPath( + const base::FilePath::StringType& name) const { + return sessions_dir_.Append(name).AddExtension(kPolicyToolSessionExtension); +} + void PolicyToolUIHandler::SetDefaultSessionName() { - base::ListValue sessions = GetSessionsList(); + base::ListValue sessions = GetSessionsList(sessions_dir_); if (sessions.empty()) { // If there are no sessions, fallback to the default session name. session_name_ = kPolicyToolDefaultSessionName; @@ -165,10 +188,11 @@ void PolicyToolUIHandler::OnFileRead(const std::string& contents) { // TODO(urusant): convert the policy values so that the types are // consistent with actual policy types. CallJavascriptFunction("policy.Page.setPolicyValues", *value); + CallJavascriptFunction("policy.Page.setSessionTitle", + base::Value(session_name_)); base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::BindOnce(&PolicyToolUIHandler::GetSessionsList, - base::Unretained(this)), + base::BindOnce(&GetSessionsList, sessions_dir_), base::BindOnce(&PolicyToolUIHandler::OnSessionsListReceived, callback_weak_ptr_factory_.GetWeakPtr())); } @@ -199,8 +223,14 @@ bool PolicyToolUIHandler::IsValidSessionName( const base::FilePath::StringType& name) const { // Check if the session name is valid, which means that it doesn't use // filesystem navigation (e.g. ../ or nested folder). + + // Sanity check to avoid that GetSessionPath(|name|) crashed. + if (base::FilePath(name).IsAbsolute()) + return false; base::FilePath session_path = GetSessionPath(name); - return !session_path.empty() && session_path.DirName() == sessions_dir_; + return !session_path.empty() && session_path.DirName() == sessions_dir_ && + session_path.BaseName().RemoveExtension() == base::FilePath(name) && + !session_path.EndsWithSeparator(); } void PolicyToolUIHandler::HandleLoadSession(const base::ListValue* args) { @@ -215,6 +245,79 @@ void PolicyToolUIHandler::HandleLoadSession(const base::ListValue* args) { ImportFile(); } +// static +PolicyToolUIHandler::SessionErrors PolicyToolUIHandler::DoRenameSession( + const base::FilePath& old_session_path, + const base::FilePath& new_session_path) { + // Check if a session files with the new name exist. If |old_session_path| + // doesn't exist, it means that is not a valid session. If |new_session_path| + // exists, it means that we can't do the rename because that will cause a file + // overwrite. + if (!PathExists(old_session_path)) + return SessionErrors::kSessionNameNotExist; + if (PathExists(new_session_path)) + return SessionErrors::kSessionNameExist; + if (!base::Move(old_session_path, new_session_path)) + return SessionErrors::kRenamedSessionError; + return SessionErrors::kNone; +} + +void PolicyToolUIHandler::OnSessionRenamed( + PolicyToolUIHandler::SessionErrors result) { + if (result == SessionErrors::kNone) { + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::BindOnce(&GetSessionsList, sessions_dir_), + base::BindOnce(&PolicyToolUIHandler::OnSessionsListReceived, + callback_weak_ptr_factory_.GetWeakPtr())); + CallJavascriptFunction("policy.Page.closeRenameSessionDialog"); + return; + } + int error_message_id; + if (result == SessionErrors::kSessionNameNotExist) { + error_message_id = IDS_POLICY_TOOL_SESSION_NOT_EXIST; + } else if (result == SessionErrors::kSessionNameExist) { + error_message_id = IDS_POLICY_TOOL_SESSION_EXIST; + } else { + error_message_id = IDS_POLICY_TOOL_RENAME_FAILED; + } + + CallJavascriptFunction( + "policy.Page.showRenameSessionError", + base::Value(l10n_util::GetStringUTF16(error_message_id))); +} + +void PolicyToolUIHandler::HandleRenameSession(const base::ListValue* args) { + DCHECK_EQ(2U, args->GetSize()); + base::FilePath::StringType old_session_name, new_session_name; + old_session_name = + base::FilePath::FromUTF8Unsafe(args->GetList()[0].GetString()).value(); + new_session_name = + base::FilePath::FromUTF8Unsafe(args->GetList()[1].GetString()).value(); + + if (!IsValidSessionName(new_session_name) || + !IsValidSessionName(old_session_name)) { + CallJavascriptFunction("policy.Page.showRenameSessionError", + base::Value(l10n_util::GetStringUTF16( + IDS_POLICY_TOOL_INVALID_SESSION_NAME))); + return; + } + + // This is important in case the user renames the current active session. + // If we don't clear the current session name, after the rename, a new file + // will be created with the old name and with an empty dictionary in it. + session_name_.clear(); + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, + {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce(&PolicyToolUIHandler::DoRenameSession, + GetSessionPath(old_session_name), + GetSessionPath(new_session_name)), + base::BindOnce(&PolicyToolUIHandler::OnSessionRenamed, + callback_weak_ptr_factory_.GetWeakPtr())); +} + bool PolicyToolUIHandler::DoUpdateSession(const std::string& contents) { // Sanity check that contents is not too big. Otherwise, passing it to // WriteFile will be int overflow. @@ -285,3 +388,72 @@ void PolicyToolUIHandler::HandleDeleteSession(const base::ListValue* args) { base::BindOnce(&PolicyToolUIHandler::OnSessionDeleted, callback_weak_ptr_factory_.GetWeakPtr())); } + +void PolicyToolUIHandler::HandleExportLinux(const base::ListValue* args) { + DCHECK_EQ(1U, args->GetSize()); + + base::JSONWriter::Write(args->GetList()[0], &session_dict_for_exporting_); + ExportSessionToFile(kPolicyToolLinuxExtension); +} + +void DoWriteSessionPolicyToFile(const base::FilePath& path, + const std::string& data) { + // TODO(rodmartin): Handle when WriteFile fail. + base::WriteFile(path, data.c_str(), data.size()); +} + +void PolicyToolUIHandler::WriteSessionPolicyToFile( + const base::FilePath& path) const { + const std::string data = session_dict_for_exporting_; + base::PostTaskWithTraits( + FROM_HERE, + {base::MayBlock(), base::TaskPriority::BACKGROUND, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce(&DoWriteSessionPolicyToFile, path, data)); +} + +void PolicyToolUIHandler::FileSelected(const base::FilePath& path, + int index, + void* params) { + DCHECK(export_policies_select_file_dialog_); + WriteSessionPolicyToFile(path); + session_dict_for_exporting_.clear(); + export_policies_select_file_dialog_ = nullptr; +} + +void PolicyToolUIHandler::FileSelectionCanceled(void* params) { + DCHECK(export_policies_select_file_dialog_); + session_dict_for_exporting_.clear(); + export_policies_select_file_dialog_ = nullptr; +} + +void PolicyToolUIHandler::ExportSessionToFile( + const base::FilePath::StringType& file_extension) { + // If the "select file" dialog window is already opened, we don't want to open + // it again. + if (export_policies_select_file_dialog_) + return; + + content::WebContents* webcontents = web_ui()->GetWebContents(); + + // Building initial path based on download preferences. + base::FilePath initial_dir = + DownloadPrefs::FromBrowserContext(webcontents->GetBrowserContext()) + ->DownloadPath(); + base::FilePath initial_path = + initial_dir.Append(kPolicyToolDefaultSessionName) + .AddExtension(file_extension); + + // TODO(rodmartin): Put an error message when the user is not allowed + // to open select file dialogs. + export_policies_select_file_dialog_ = ui::SelectFileDialog::Create( + this, std::make_unique<ChromeSelectFilePolicy>(webcontents)); + ui::SelectFileDialog::FileTypeInfo file_type_info; + file_type_info.extensions = {{file_extension}}; + gfx::NativeWindow owning_window = webcontents->GetTopLevelNativeWindow(); + export_policies_select_file_dialog_->SelectFile( + ui::SelectFileDialog::SELECT_SAVEAS_FILE, /*title=*/base::string16(), + initial_path, &file_type_info, /*file_type_index=*/0, + /*default_extension=*/base::FilePath::StringType(), owning_window, + /*params=*/nullptr); +} diff --git a/chromium/chrome/browser/ui/webui/policy_tool_ui_handler.h b/chromium/chrome/browser/ui/webui/policy_tool_ui_handler.h index c520df0a85a..861fa0adefe 100644 --- a/chromium/chrome/browser/ui/webui/policy_tool_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/policy_tool_ui_handler.h @@ -20,44 +20,77 @@ class PolicyToolUIHandler : public PolicyUIHandler { private: friend class PolicyToolUITest; - static const base::FilePath::CharType kPolicyToolSessionsDir[]; - static const base::FilePath::CharType kPolicyToolDefaultSessionName[]; - static const base::FilePath::CharType kPolicyToolSessionExtension[]; + enum class SessionErrors { + kNone = 0, + kInvalidSessionName, + kSessionNameExist, + kSessionNameNotExist, + kRenamedSessionError, + }; + // Reads the current session file (based on the session_name_) and sends the // contents to the UI. void ImportFile(); void HandleInitializedAdmin(const base::ListValue* args); + void HandleLoadSession(const base::ListValue* args); + + // Rename a session if the new session name doesn't exist. + void HandleRenameSession(const base::ListValue* args); + void HandleUpdateSession(const base::ListValue* args); + void HandleResetSession(const base::ListValue* args); + void HandleDeleteSession(const base::ListValue* args); + void HandleExportLinux(const base::ListValue* args); + void OnSessionDeleted(bool is_successful); std::string ReadOrCreateFileCallback(); void OnFileRead(const std::string& contents); + static SessionErrors DoRenameSession(const base::FilePath& old_session_path, + const base::FilePath& new_session_path); + + void OnSessionRenamed(SessionErrors result); + bool DoUpdateSession(const std::string& contents); + void OnSessionUpdated(bool is_successful); bool IsValidSessionName(const base::FilePath::StringType& name) const; base::FilePath GetSessionPath(const base::FilePath::StringType& name) const; - // Returns the current list of all sessions sorted by last access time in - // decreasing order. - base::ListValue GetSessionsList(); - void OnSessionsListReceived(base::ListValue list); void SetDefaultSessionName(); + // ui::SelectFileDialog::Listener implementation. + void FileSelected(const base::FilePath& path, + int index, + void* params) override; + + void FileSelectionCanceled(void* params) override; + + void WriteSessionPolicyToFile(const base::FilePath& path) const; + + void ExportSessionToFile(const base::FilePath::StringType& file_extension); + bool is_saving_enabled_ = true; + // This string is filled when an export action occurs, it contains the current + // session dictionary in a specific format. This format will be JSON, PLIST, + // or REG; depending on the kind of export. + std::string session_dict_for_exporting_; base::FilePath sessions_dir_; base::FilePath::StringType session_name_; + scoped_refptr<ui::SelectFileDialog> export_policies_select_file_dialog_; + base::WeakPtrFactory<PolicyToolUIHandler> callback_weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(PolicyToolUIHandler); diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc index ccfafe79926..be261745a86 100644 --- a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc @@ -16,7 +16,6 @@ #include "base/json/json_writer.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/strings/string16.h" #include "base/task_scheduler/post_task.h" @@ -52,7 +51,7 @@ #include "components/policy/proto/device_management_backend.pb.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_contents.h" -#include "extensions/features/features.h" +#include "extensions/buildflags/buildflags.h" #include "google_apis/gaia/gaia_auth_util.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/time_format.h" @@ -633,16 +632,16 @@ void PolicyUIHandler::RegisterMessages() { registry->AddObserver(this); web_ui()->RegisterMessageCallback( - "initialized", - base::Bind(&PolicyUIHandler::HandleInitialized, base::Unretained(this))); + "initialized", base::BindRepeating(&PolicyUIHandler::HandleInitialized, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "reloadPolicies", - base::Bind(&PolicyUIHandler::HandleReloadPolicies, - base::Unretained(this))); + base::BindRepeating(&PolicyUIHandler::HandleReloadPolicies, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "exportPoliciesJSON", - base::Bind(&PolicyUIHandler::HandleExportPoliciesJSON, - base::Unretained(this))); + base::BindRepeating(&PolicyUIHandler::HandleExportPoliciesJSON, + base::Unretained(this))); } #if BUILDFLAG(ENABLE_EXTENSIONS) diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.h b/chromium/chrome/browser/ui/webui/policy_ui_handler.h index a3f7e8c10e7..025f7704cf8 100644 --- a/chromium/chrome/browser/ui/webui/policy_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.h @@ -20,7 +20,7 @@ #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/browser/web_ui_message_handler.h" -#include "extensions/features/features.h" +#include "extensions/buildflags/buildflags.h" #include "ui/shell_dialogs/select_file_dialog.h" #if BUILDFLAG(ENABLE_EXTENSIONS) diff --git a/chromium/chrome/browser/ui/webui/predictors/predictors_handler.cc b/chromium/chrome/browser/ui/webui/predictors/predictors_handler.cc index 7a338593fa9..50387cd2635 100644 --- a/chromium/chrome/browser/ui/webui/predictors/predictors_handler.cc +++ b/chromium/chrome/browser/ui/webui/predictors/predictors_handler.cc @@ -33,12 +33,16 @@ PredictorsHandler::PredictorsHandler(Profile* profile) { PredictorsHandler::~PredictorsHandler() { } void PredictorsHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("requestAutocompleteActionPredictorDb", - base::Bind(&PredictorsHandler::RequestAutocompleteActionPredictorDb, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("requestResourcePrefetchPredictorDb", - base::Bind(&PredictorsHandler::RequestResourcePrefetchPredictorDb, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "requestAutocompleteActionPredictorDb", + base::BindRepeating( + &PredictorsHandler::RequestAutocompleteActionPredictorDb, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "requestResourcePrefetchPredictorDb", + base::BindRepeating( + &PredictorsHandler::RequestResourcePrefetchPredictorDb, + base::Unretained(this))); } void PredictorsHandler::RequestAutocompleteActionPredictorDb( diff --git a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc index 12529779ca8..395ee71d9f4 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc @@ -19,7 +19,7 @@ #include "base/task_scheduler/post_task.h" #include "chrome/browser/printing/pwg_raster_converter.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/print_preview/printer_capabilities.h" +#include "chrome/browser/ui/webui/print_preview/print_preview_utils.h" #include "components/cloud_devices/common/cloud_device_description.h" #include "components/cloud_devices/common/printer_description.h" #include "device/base/device_client.h" @@ -185,7 +185,7 @@ void ExtensionPrinterHandler::StartPrint( const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) { auto print_job = std::make_unique<extensions::PrinterProviderPrintJob>(); print_job->printer_id = destination_id; @@ -265,13 +265,16 @@ void ExtensionPrinterHandler::ConvertToPWGRaster( const gfx::Size& page_size, std::unique_ptr<extensions::PrinterProviderPrintJob> job, PrintJobCallback callback) { - if (!pwg_raster_converter_) { + if (!pwg_raster_converter_) pwg_raster_converter_ = PwgRasterConverter::CreateDefault(); - } + + printing::PwgRasterSettings bitmap_settings = + PwgRasterConverter::GetBitmapSettings(printer_description, ticket); pwg_raster_converter_->Start( data.get(), - PwgRasterConverter::GetConversionSettings(printer_description, page_size), - PwgRasterConverter::GetBitmapSettings(printer_description, ticket), + PwgRasterConverter::GetConversionSettings(printer_description, page_size, + bitmap_settings.use_color), + bitmap_settings, base::BindOnce(&UpdateJobFileInfo, std::move(job), std::move(callback))); } @@ -370,7 +373,7 @@ void ExtensionPrinterHandler::OnUsbDevicesEnumerated( device->product_string(), base::string16(), false)) .Set("extensionId", extension->id()) .Set("extensionName", extension->name()) - .Set("provisional", true) + .SetBoolean("provisional", true) .Build()); } } diff --git a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h index 005ad93b637..ce7ab8f5ac4 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h +++ b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h @@ -18,7 +18,6 @@ namespace base { class DictionaryValue; class ListValue; -class RefCountedBytes; class RefCountedMemory; } @@ -63,7 +62,7 @@ class ExtensionPrinterHandler : public PrinterHandler { const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) override; void StartGrantPrinterAccess(const std::string& printer_id, GetPrinterInfoCallback callback) override; diff --git a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc index 2f453449b5b..0ef9c338198 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc @@ -595,7 +595,7 @@ TEST_F(ExtensionPrinterHandlerTest, GetUsbPrinters) { .Set("name", "USB Printer") .Set("extensionName", "Provider 1") .Set("extensionId", extension_1->id()) - .Set("provisional", true) + .SetBoolean("provisional", true) .Build()); std::unique_ptr<base::DictionaryValue> extension_2_entry( DictionaryBuilder() @@ -605,7 +605,7 @@ TEST_F(ExtensionPrinterHandlerTest, GetUsbPrinters) { .Set("name", "USB Printer") .Set("extensionName", "Provider 2") .Set("extensionId", extension_2->id()) - .Set("provisional", true) + .SetBoolean("provisional", true) .Build()); EXPECT_TRUE(printers->Find(*extension_1_entry) != printers->end()); EXPECT_TRUE(printers->Find(*extension_2_entry) != printers->end()); @@ -675,8 +675,8 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pdf) { bool success = false; std::string status; - auto print_data = - base::MakeRefCounted<base::RefCountedBytes>(kPrintData, kPrintDataLength); + auto print_data = base::MakeRefCounted<base::RefCountedStaticMemory>( + kPrintData, kPrintDataLength); base::string16 title = base::ASCIIToUTF16("Title"); extension_printer_handler_->StartPrint( diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.cc index b17d6ba0c5a..da909f11bbb 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.cc @@ -10,7 +10,6 @@ #include "base/bind_helpers.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/task_scheduler/post_task.h" #include "base/values.h" @@ -20,11 +19,12 @@ #include "chrome/browser/chromeos/printing/ppd_provider_factory.h" #include "chrome/browser/chromeos/printing/printer_configurer.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/print_preview/printer_capabilities.h" +#include "chrome/browser/ui/webui/print_preview/print_preview_utils.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/debug_daemon_client.h" #include "chromeos/printing/ppd_provider.h" #include "chromeos/printing/printer_configuration.h" +#include "components/printing/common/printer_capabilities.h" #include "content/public/browser/browser_thread.h" #include "printing/backend/print_backend_consts.h" @@ -66,7 +66,7 @@ void FetchCapabilities(std::unique_ptr<chromeos::Printer> printer, base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, base::BindOnce(&printing::GetSettingsOnBlockingPool, printer->id(), - basic_info), + basic_info, nullptr), std::move(cb)); } @@ -201,7 +201,7 @@ void LocalPrinterHandlerChromeos::StartPrint( const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) { printing::StartLocalPrint(ticket_json, print_data, preview_web_contents_, std::move(callback)); diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h index b22c9bc58dd..a96aa70ee77 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h +++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h @@ -41,7 +41,7 @@ class LocalPrinterHandlerChromeos : public PrinterHandler { const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) override; private: diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc index 5d3076d23dc..794a8d53a6c 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc @@ -8,11 +8,11 @@ #include <utility> #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/task_scheduler/post_task.h" #include "base/threading/thread_restrictions.h" -#include "chrome/browser/ui/webui/print_preview/printer_capabilities.h" +#include "chrome/browser/ui/webui/print_preview/print_preview_utils.h" +#include "components/printing/common/printer_capabilities.h" #include "content/public/browser/browser_thread.h" #include "printing/backend/print_backend.h" @@ -46,7 +46,8 @@ std::unique_ptr<base::DictionaryValue> FetchCapabilitiesAsync( return nullptr; } - return printing::GetSettingsOnBlockingPool(device_name, basic_info); + return printing::GetSettingsOnBlockingPool(device_name, basic_info, + print_backend); } std::string GetDefaultPrinterAsync() { @@ -106,7 +107,7 @@ void LocalPrinterHandlerDefault::StartPrint( const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) { printing::StartLocalPrint(ticket_json, print_data, preview_web_contents_, std::move(callback)); diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.h b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.h index ab07dea98dc..a9da3756d2b 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.h +++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.h @@ -36,7 +36,7 @@ class LocalPrinterHandlerDefault : public PrinterHandler { const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) override; private: diff --git a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc index 52fbb52e895..a09caf94453 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc @@ -111,7 +111,7 @@ std::unique_ptr<base::DictionaryValue> GetPdfCapabilities( } // Callback that stores a PDF file on disk. -void PrintToPdfCallback(const scoped_refptr<base::RefCountedBytes>& data, +void PrintToPdfCallback(const scoped_refptr<base::RefCountedMemory>& data, const base::FilePath& path, const base::Closure& pdf_file_saved_closure) { base::File file(path, @@ -184,7 +184,7 @@ void PdfPrinterHandler::StartPrint( const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) { print_data_ = print_data; if (!print_to_pdf_path_.empty()) { diff --git a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h index 641fb89cc83..ffa4bb4e528 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h +++ b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h @@ -17,7 +17,7 @@ #include "ui/shell_dialogs/select_file_dialog.h" namespace base { -class RefCountedBytes; +class RefCountedMemory; } namespace content { @@ -56,7 +56,7 @@ class PdfPrinterHandler : public PrinterHandler, const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) override; // SelectFileDialog::Listener implementation. @@ -108,7 +108,7 @@ class PdfPrinterHandler : public PrinterHandler, base::Closure pdf_file_saved_closure_; // The data to print - scoped_refptr<base::RefCountedBytes> print_data_; + scoped_refptr<base::RefCountedMemory> print_data_; // The callback to call when complete. PrintCallback print_callback_; diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.cc index 9bce25e7094..4a5410e4a56 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.cc @@ -71,7 +71,7 @@ #include "net/base/url_util.h" #include "printing/backend/print_backend.h" #include "printing/backend/print_backend_consts.h" -#include "printing/features/features.h" +#include "printing/buildflags/buildflags.h" #include "printing/print_settings.h" #include "third_party/icu/source/i18n/unicode/ulocdata.h" @@ -410,58 +410,70 @@ PrintPreviewHandler::~PrintPreviewHandler() { } void PrintPreviewHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("getPrinters", - base::Bind(&PrintPreviewHandler::HandleGetPrinters, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("getPreview", - base::Bind(&PrintPreviewHandler::HandleGetPreview, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("print", - base::Bind(&PrintPreviewHandler::HandlePrint, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getPrinters", + base::BindRepeating(&PrintPreviewHandler::HandleGetPrinters, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getPreview", base::BindRepeating(&PrintPreviewHandler::HandleGetPreview, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "print", base::BindRepeating(&PrintPreviewHandler::HandlePrint, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getPrinterCapabilities", - base::Bind(&PrintPreviewHandler::HandleGetPrinterCapabilities, - base::Unretained(this))); + base::BindRepeating(&PrintPreviewHandler::HandleGetPrinterCapabilities, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "setupPrinter", base::Bind(&PrintPreviewHandler::HandlePrinterSetup, - base::Unretained(this))); + "setupPrinter", + base::BindRepeating(&PrintPreviewHandler::HandlePrinterSetup, + base::Unretained(this))); #if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG) - web_ui()->RegisterMessageCallback("showSystemDialog", - base::Bind(&PrintPreviewHandler::HandleShowSystemDialog, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "showSystemDialog", + base::BindRepeating(&PrintPreviewHandler::HandleShowSystemDialog, + base::Unretained(this))); #endif - web_ui()->RegisterMessageCallback("signIn", - base::Bind(&PrintPreviewHandler::HandleSignin, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("getAccessToken", - base::Bind(&PrintPreviewHandler::HandleGetAccessToken, - base::Unretained(this))); web_ui()->RegisterMessageCallback( - "managePrinters", base::Bind(&PrintPreviewHandler::HandleManagePrinters, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("closePrintPreviewDialog", - base::Bind(&PrintPreviewHandler::HandleClosePreviewDialog, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("hidePreview", - base::Bind(&PrintPreviewHandler::HandleHidePreview, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("cancelPendingPrintRequest", - base::Bind(&PrintPreviewHandler::HandleCancelPendingPrintRequest, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("saveAppState", - base::Bind(&PrintPreviewHandler::HandleSaveAppState, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("getInitialSettings", - base::Bind(&PrintPreviewHandler::HandleGetInitialSettings, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("forceOpenNewTab", - base::Bind(&PrintPreviewHandler::HandleForceOpenNewTab, - base::Unretained(this))); + "signIn", base::BindRepeating(&PrintPreviewHandler::HandleSignin, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getAccessToken", + base::BindRepeating(&PrintPreviewHandler::HandleGetAccessToken, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "managePrinters", + base::BindRepeating(&PrintPreviewHandler::HandleManagePrinters, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "closePrintPreviewDialog", + base::BindRepeating(&PrintPreviewHandler::HandleClosePreviewDialog, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "hidePreview", + base::BindRepeating(&PrintPreviewHandler::HandleHidePreview, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "cancelPendingPrintRequest", + base::BindRepeating(&PrintPreviewHandler::HandleCancelPendingPrintRequest, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "saveAppState", + base::BindRepeating(&PrintPreviewHandler::HandleSaveAppState, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getInitialSettings", + base::BindRepeating(&PrintPreviewHandler::HandleGetInitialSettings, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "forceOpenNewTab", + base::BindRepeating(&PrintPreviewHandler::HandleForceOpenNewTab, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "grantExtensionPrinterAccess", - base::Bind(&PrintPreviewHandler::HandleGrantExtensionPrinterAccess, - base::Unretained(this))); + base::BindRepeating( + &PrintPreviewHandler::HandleGrantExtensionPrinterAccess, + base::Unretained(this))); } void PrintPreviewHandler::OnJavascriptAllowed() { @@ -708,7 +720,7 @@ void PrintPreviewHandler::HandlePrint(const base::ListValue* args) { ReportUserActionHistogram(PRINT_WITH_CLOUD_PRINT); } - scoped_refptr<base::RefCountedBytes> data; + scoped_refptr<base::RefCountedMemory> data; print_preview_ui()->GetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, &data); if (!data) { @@ -1032,11 +1044,11 @@ void PrintPreviewHandler::SendCloudPrintEnabled() { } } -void PrintPreviewHandler::SendCloudPrintJob(const std::string& callback_id, - const base::RefCountedBytes* data) { +void PrintPreviewHandler::SendCloudPrintJob( + const std::string& callback_id, + const base::RefCountedMemory* data) { // BASE64 encode the job data. - const base::StringPiece raw_data(reinterpret_cast<const char*>(data->front()), - data->size()); + const base::StringPiece raw_data(data->front_as<char>(), data->size()); std::string base64_data; base::Base64Encode(raw_data, &base64_data); @@ -1149,7 +1161,12 @@ void PrintPreviewHandler::SendPagePreviewReady(int page_index, } void PrintPreviewHandler::OnPrintPreviewCancelled() { - if (preview_callbacks_.empty() || !IsJavascriptAllowed()) { + if (!IsJavascriptAllowed()) { + BadMessageReceived(); + return; + } + + if (preview_callbacks_.empty()) { BadMessageReceived(); return; } diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.h b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.h index 8efb84708d7..27d7caa30c3 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.h +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.h @@ -19,7 +19,7 @@ #include "components/signin/core/browser/gaia_cookie_manager_service.h" #include "content/public/browser/web_ui_message_handler.h" #include "printing/backend/print_backend.h" -#include "printing/features/features.h" +#include "printing/buildflags/buildflags.h" class PdfPrinterHandler; class PrinterHandler; @@ -27,7 +27,7 @@ class PrintPreviewUI; namespace base { class DictionaryValue; -class RefCountedBytes; +class RefCountedMemory; } namespace content { @@ -246,7 +246,7 @@ class PrintPreviewHandler // Send the PDF data to the cloud to print. void SendCloudPrintJob(const std::string& callback_id, - const base::RefCountedBytes* data); + const base::RefCountedMemory* data); // Closes the preview dialog. void ClosePreviewDialog(); diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc index bc72b510408..785b773740c 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc @@ -4,14 +4,19 @@ #include "chrome/browser/ui/webui/print_preview/print_preview_handler.h" +#include <map> +#include <utility> +#include <vector> + #include "base/base64.h" #include "base/containers/flat_set.h" -#include "base/i18n/rtl.h" #include "base/json/json_writer.h" #include "base/memory/ref_counted_memory.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/icu_test_util.h" #include "base/values.h" +#include "chrome/browser/printing/print_test_utils.h" #include "chrome/browser/printing/print_view_manager.h" #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" #include "chrome/browser/ui/webui/print_preview/printer_handler.h" @@ -31,7 +36,6 @@ namespace printing { namespace { -const char kDummyPrinterName[] = "DefaultPrinter"; const char kDummyInitiatorName[] = "TestInitiator"; const char kTestData[] = "abc"; @@ -78,67 +82,6 @@ PrinterInfo GetEmptyPrinterInfo() { return empty_printer; } -// Creates a print ticket with some default values. Based on ticket creation in -// chrome/browser/resources/print_preview/native_layer.js. -base::Value GetPrintTicket(printing::PrinterType type, bool cloud) { - bool is_privet_printer = !cloud && type == printing::kPrivetPrinter; - bool is_extension_printer = !cloud && type == printing::kExtensionPrinter; - - base::Value ticket(base::Value::Type::DICTIONARY); - - // Letter - base::Value media_size(base::Value::Type::DICTIONARY); - media_size.SetKey(kSettingMediaSizeIsDefault, base::Value(true)); - media_size.SetKey(kSettingMediaSizeWidthMicrons, base::Value(215900)); - media_size.SetKey(kSettingMediaSizeHeightMicrons, base::Value(279400)); - ticket.SetKey(kSettingMediaSize, std::move(media_size)); - - ticket.SetKey(kSettingPreviewPageCount, base::Value(1)); - ticket.SetKey(kSettingLandscape, base::Value(false)); - ticket.SetKey(kSettingColor, base::Value(2)); // color printing - ticket.SetKey(kSettingHeaderFooterEnabled, base::Value(false)); - ticket.SetKey(kSettingMarginsType, base::Value(0)); // default margins - ticket.SetKey(kSettingDuplexMode, base::Value(1)); // LONG_EDGE - ticket.SetKey(kSettingCopies, base::Value(1)); - ticket.SetKey(kSettingCollate, base::Value(true)); - ticket.SetKey(kSettingShouldPrintBackgrounds, base::Value(false)); - ticket.SetKey(kSettingShouldPrintSelectionOnly, base::Value(false)); - ticket.SetKey(kSettingPreviewModifiable, base::Value(false)); - ticket.SetKey(kSettingPrintToPDF, - base::Value(!cloud && type == printing::kPdfPrinter)); - ticket.SetKey(kSettingCloudPrintDialog, base::Value(cloud)); - ticket.SetKey(kSettingPrintWithPrivet, base::Value(is_privet_printer)); - ticket.SetKey(kSettingPrintWithExtension, base::Value(is_extension_printer)); - ticket.SetKey(kSettingRasterizePdf, base::Value(false)); - ticket.SetKey(kSettingScaleFactor, base::Value(100)); - ticket.SetKey(kSettingDpiHorizontal, base::Value(600)); - ticket.SetKey(kSettingDpiVertical, base::Value(600)); - ticket.SetKey(kSettingDeviceName, base::Value(kDummyPrinterName)); - ticket.SetKey(kSettingFitToPageEnabled, base::Value(true)); - ticket.SetKey(kSettingPageWidth, base::Value(215900)); - ticket.SetKey(kSettingPageHeight, base::Value(279400)); - ticket.SetKey(kSettingShowSystemDialog, base::Value(false)); - - if (cloud) - ticket.SetKey(kSettingCloudPrintId, base::Value(kDummyPrinterName)); - - if (is_privet_printer || is_extension_printer) { - base::Value capabilities(base::Value::Type::DICTIONARY); - capabilities.SetKey("duplex", base::Value(true)); // non-empty - std::string caps_string; - base::JSONWriter::Write(capabilities, &caps_string); - ticket.SetKey(kSettingCapabilities, base::Value(caps_string)); - base::Value print_ticket(base::Value::Type::DICTIONARY); - print_ticket.SetKey("version", base::Value("1.0")); - print_ticket.SetKey("print", base::Value()); - std::string ticket_string; - base::JSONWriter::Write(print_ticket, &ticket_string); - ticket.SetKey(kSettingTicket, base::Value(ticket_string)); - } - - return ticket; -} - base::Value GetPrintPreviewTicket(bool is_pdf) { base::Value print_ticket = GetPrintTicket(kLocalPrinter, false); @@ -203,7 +146,7 @@ class TestPrinterHandler : public PrinterHandler { const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) override { std::move(callback).Run(base::Value()); } @@ -239,8 +182,8 @@ class FakePrintPreviewUI : public PrintPreviewUI { void GetPrintPreviewDataForIndex( int index, - scoped_refptr<base::RefCountedBytes>* data) const override { - *data = base::MakeRefCounted<base::RefCountedBytes>( + scoped_refptr<base::RefCountedMemory>* data) const override { + *data = base::MakeRefCounted<base::RefCountedStaticMemory>( reinterpret_cast<const unsigned char*>(kTestData), sizeof(kTestData) - 1); } @@ -342,7 +285,7 @@ class PrintPreviewHandlerTest : public testing::Test { void Initialize() { // Set locale since the delimeters we check in VerifyInitialSettings() // depend on it. - base::i18n::SetICUDefaultLocale("en"); + base::test::ScopedRestoreICUDefaultLocale scoped_locale("en"); // Sending this message will enable javascript, so it must always be called // before any other messages are sent. @@ -394,14 +337,14 @@ class PrintPreviewHandlerTest : public testing::Test { ASSERT_TRUE(settings->FindKeyOfType("isInAppKioskMode", base::Value::Type::BOOLEAN)); - const base::Value* thousandsDelimeter = settings->FindKeyOfType( + const base::Value* thousands_delimeter = settings->FindKeyOfType( "thousandsDelimeter", base::Value::Type::STRING); - ASSERT_TRUE(thousandsDelimeter); - EXPECT_EQ(",", thousandsDelimeter->GetString()); - const base::Value* decimalDelimeter = + ASSERT_TRUE(thousands_delimeter); + EXPECT_EQ(",", thousands_delimeter->GetString()); + const base::Value* decimal_delimeter = settings->FindKeyOfType("decimalDelimeter", base::Value::Type::STRING); - ASSERT_TRUE(decimalDelimeter); - EXPECT_EQ(".", decimalDelimeter->GetString()); + ASSERT_TRUE(decimal_delimeter); + EXPECT_EQ(".", decimal_delimeter->GetString()); ASSERT_TRUE( settings->FindKeyOfType("unitType", base::Value::Type::INTEGER)); diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.cc index 8c0162c47a4..c2deb06ddf2 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.cc @@ -5,7 +5,7 @@ #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" #include <map> -#include <memory> +#include <string> #include <utility> #include <vector> @@ -35,6 +35,7 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" #include "chrome/grit/chromium_strings.h" +#include "chrome/grit/component_extension_resources.h" #include "chrome/grit/generated_resources.h" #include "chrome/grit/print_preview_resources.h" #include "chrome/grit/print_preview_resources_map.h" @@ -46,7 +47,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_data_source.h" #include "extensions/common/constants.h" -#include "printing/features/features.h" +#include "printing/buildflags/buildflags.h" #include "printing/page_size_margins.h" #include "printing/print_job_constants.h" #include "ui/base/l10n/l10n_util.h" @@ -149,7 +150,7 @@ bool HandleRequestCallback( return false; // Print Preview data. - scoped_refptr<base::RefCountedBytes> data; + scoped_refptr<base::RefCountedMemory> data; std::vector<std::string> url_substr = base::SplitString( path, "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); int preview_ui_id = -1; @@ -422,13 +423,92 @@ void AddPrintPreviewFlags(content::WebUIDataSource* source, Profile* profile) { } void SetupPrintPreviewPlugin(content::WebUIDataSource* source) { - source->AddResourcePath("pdf_preview.html", - IDR_PRINT_PREVIEW_PDF_PREVIEW_HTML); + source->AddResourcePath("pdf/index.html", IDR_PDF_INDEX_HTML); + source->AddResourcePath("pdf/index.css", IDR_PDF_INDEX_CSS); + source->AddResourcePath("pdf/main.js", IDR_PDF_MAIN_JS); + source->AddResourcePath("pdf/pdf.js", IDR_PDF_PDF_JS); + source->AddResourcePath("pdf/toolbar_manager.js", IDR_PDF_UI_MANAGER_JS); + source->AddResourcePath("pdf/pdf_fitting_type.js", + IDR_PDF_PDF_FITTING_TYPE_JS); + source->AddResourcePath("pdf/viewport.js", IDR_PDF_VIEWPORT_JS); + source->AddResourcePath("pdf/open_pdf_params_parser.js", + IDR_PDF_OPEN_PDF_PARAMS_PARSER_JS); + source->AddResourcePath("pdf/navigator.js", IDR_PDF_NAVIGATOR_JS); + source->AddResourcePath("pdf/viewport_scroller.js", + IDR_PDF_VIEWPORT_SCROLLER_JS); + source->AddResourcePath("pdf/pdf_scripting_api.js", + IDR_PDF_PDF_SCRIPTING_API_JS); + source->AddResourcePath("pdf/zoom_manager.js", IDR_PDF_ZOOM_MANAGER_JS); + source->AddResourcePath("pdf/gesture_detector.js", + IDR_PDF_GESTURE_DETECTOR_JS); + source->AddResourcePath("pdf/browser_api.js", IDR_PDF_BROWSER_API_JS); + source->AddResourcePath("pdf/metrics.js", IDR_PDF_METRICS_JS); + source->AddResourcePath("pdf/coords_transformer.js", + IDR_PDF_COORDS_TRANSFORMER_JS); + + source->AddResourcePath("pdf/elements/shared-vars.html", + IDR_PDF_SHARED_VARS_HTML); + source->AddResourcePath("pdf/elements/icons.html", IDR_PDF_ICONS_HTML); + source->AddResourcePath("pdf/elements/viewer-bookmark/viewer-bookmark.html", + IDR_PDF_VIEWER_BOOKMARK_HTML); + source->AddResourcePath("pdf/elements/viewer-bookmark/viewer-bookmark.js", + IDR_PDF_VIEWER_BOOKMARK_JS); + source->AddResourcePath( + "pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.html", + IDR_PDF_VIEWER_BOOKMARKS_CONTENT_HTML); + source->AddResourcePath( + "pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js", + IDR_PDF_VIEWER_BOOKMARKS_CONTENT_JS); + source->AddResourcePath( + "pdf/elements/viewer-error-screen/viewer-error-screen.html", + IDR_PDF_VIEWER_ERROR_SCREEN_HTML); + source->AddResourcePath( + "pdf/elements/viewer-error-screen/viewer-error-screen.js", + IDR_PDF_VIEWER_ERROR_SCREEN_JS); + source->AddResourcePath( + "pdf/elements/viewer-page-indicator/viewer-page-indicator.html", + IDR_PDF_VIEWER_PAGE_INDICATOR_HTML); + source->AddResourcePath( + "pdf/elements/viewer-page-indicator/viewer-page-indicator.js", + IDR_PDF_VIEWER_PAGE_INDICATOR_JS); + source->AddResourcePath( + "pdf/elements/viewer-page-selector/viewer-page-selector.html", + IDR_PDF_VIEWER_PAGE_SELECTOR_HTML); + source->AddResourcePath( + "pdf/elements/viewer-page-selector/viewer-page-selector.js", + IDR_PDF_VIEWER_PAGE_SELECTOR_JS); + source->AddResourcePath( + "pdf/elements/viewer-password-screen/viewer-password-screen.html", + IDR_PDF_VIEWER_PASSWORD_SCREEN_HTML); + source->AddResourcePath( + "pdf/elements/viewer-password-screen/viewer-password-screen.js", + IDR_PDF_VIEWER_PASSWORD_SCREEN_JS); + source->AddResourcePath( + "pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html", + IDR_PDF_VIEWER_PDF_TOOLBAR_HTML); + source->AddResourcePath( + "pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js", + IDR_PDF_VIEWER_PDF_TOOLBAR_JS); + source->AddResourcePath( + "pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html", + IDR_PDF_VIEWER_TOOLBAR_DROPDOWN_HTML); + source->AddResourcePath( + "pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.js", + IDR_PDF_VIEWER_TOOLBAR_DROPDOWN_JS); + source->AddResourcePath( + "pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.html", + IDR_PDF_VIEWER_ZOOM_BUTTON_HTML); + source->AddResourcePath( + "pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.js", + IDR_PDF_VIEWER_ZOOM_BUTTON_JS); + source->AddResourcePath( + "pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.html", + IDR_PDF_VIEWER_ZOOM_SELECTOR_HTML); + source->AddResourcePath( + "pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js", + IDR_PDF_VIEWER_ZOOM_SELECTOR_JS); + source->SetRequestFilter(base::BindRepeating(&HandleRequestCallback)); - source->OverrideContentSecurityPolicyScriptSrc( - base::StringPrintf("script-src chrome://resources 'self' 'unsafe-eval' " - "chrome-extension://%s;", - extension_misc::kPdfExtensionId)); source->OverrideContentSecurityPolicyChildSrc("child-src 'self';"); source->DisableDenyXFrameOptions(); source->OverrideContentSecurityPolicyObjectSrc("object-src 'self';"); @@ -438,13 +518,18 @@ content::WebUIDataSource* CreateNewPrintPreviewUISource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIPrintHost); AddPrintPreviewStrings(source); + AddPrintPreviewImages(source); source->SetJsonPath("strings.js"); +#if BUILDFLAG(OPTIMIZE_WEBUI) + source->AddResourcePath("crisper.js", IDR_PRINT_PREVIEW_CRISPER_JS); + source->SetDefaultResource(IDR_PRINT_PREVIEW_VULCANIZED_HTML); +#else for (size_t i = 0; i < kPrintPreviewResourcesSize; ++i) { source->AddResourcePath(kPrintPreviewResources[i].name, kPrintPreviewResources[i].value); } - AddPrintPreviewImages(source); source->SetDefaultResource(IDR_PRINT_PREVIEW_NEW_HTML); +#endif SetupPrintPreviewPlugin(source); AddPrintPreviewFlags(source, profile); return source; @@ -521,13 +606,13 @@ PrintPreviewUI::~PrintPreviewUI() { void PrintPreviewUI::GetPrintPreviewDataForIndex( int index, - scoped_refptr<base::RefCountedBytes>* data) const { + scoped_refptr<base::RefCountedMemory>* data) const { PrintPreviewDataService::GetInstance()->GetDataEntry(id_, index, data); } void PrintPreviewUI::SetPrintPreviewDataForIndex( int index, - scoped_refptr<base::RefCountedBytes> data) { + scoped_refptr<base::RefCountedMemory> data) { PrintPreviewDataService::GetInstance()->SetDataEntry(id_, index, std::move(data)); } diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.h b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.h index d3a3d0d28f3..db9a4933bf5 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.h +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.h @@ -7,7 +7,7 @@ #include <stdint.h> -#include <string> +#include <memory> #include "base/callback_forward.h" #include "base/gtest_prod_util.h" @@ -15,7 +15,7 @@ #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "chrome/browser/ui/webui/constrained_web_dialog_ui.h" -#include "printing/features/features.h" +#include "printing/buildflags/buildflags.h" class PrintPreviewHandler; struct PrintHostMsg_DidGetPreviewPageCount_Params; @@ -25,7 +25,7 @@ struct PrintHostMsg_SetOptionsFromDocument_Params; namespace base { class DictionaryValue; class FilePath; -class RefCountedBytes; +class RefCountedMemory; } namespace gfx { @@ -47,13 +47,13 @@ class PrintPreviewUI : public ConstrainedWebDialogUI { // document. virtual void GetPrintPreviewDataForIndex( int index, - scoped_refptr<base::RefCountedBytes>* data) const; + scoped_refptr<base::RefCountedMemory>* data) const; // Sets the print preview |data|. |index| is zero-based, and can be // |printing::COMPLETE_PREVIEW_DOCUMENT_INDEX| to set the entire preview // document. void SetPrintPreviewDataForIndex(int index, - scoped_refptr<base::RefCountedBytes> data); + scoped_refptr<base::RefCountedMemory> data); // Clear the existing print preview data. void ClearAllPreviewData(); diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_browsertest.cc index 070051eb316..8d8187548ad 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_browsertest.cc @@ -21,7 +21,7 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" -#include "printing/features/features.h" +#include "printing/buildflags/buildflags.h" #include "url/url_constants.h" #if defined(OS_WIN) diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc index b374eda8358..02e979f5559 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc @@ -85,13 +85,13 @@ TEST_F(PrintPreviewUIUnitTest, PrintPreviewData) { PrintPreviewUI* preview_ui = static_cast<PrintPreviewUI*>( preview_dialog->GetWebUI()->GetController()); - ASSERT_TRUE(preview_ui != NULL); + ASSERT_TRUE(preview_ui); - scoped_refptr<base::RefCountedBytes> data; + scoped_refptr<base::RefCountedMemory> data; preview_ui->GetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, &data); - EXPECT_EQ(NULL, data.get()); + EXPECT_FALSE(data); scoped_refptr<base::RefCountedBytes> dummy_data = CreateTestData(); @@ -115,7 +115,7 @@ TEST_F(PrintPreviewUIUnitTest, PrintPreviewData) { preview_ui->GetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, &data); - EXPECT_EQ(NULL, data.get()); + EXPECT_FALSE(data); } // Set and get the individual draft pages. @@ -138,11 +138,11 @@ TEST_F(PrintPreviewUIUnitTest, PrintPreviewDraftPages) { PrintPreviewUI* preview_ui = static_cast<PrintPreviewUI*>( preview_dialog->GetWebUI()->GetController()); - ASSERT_TRUE(preview_ui != NULL); + ASSERT_TRUE(preview_ui); - scoped_refptr<base::RefCountedBytes> data; + scoped_refptr<base::RefCountedMemory> data; preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, &data); - EXPECT_EQ(NULL, data.get()); + EXPECT_FALSE(data); scoped_refptr<base::RefCountedBytes> dummy_data = CreateTestData(); @@ -163,7 +163,7 @@ TEST_F(PrintPreviewUIUnitTest, PrintPreviewDraftPages) { // Get the second page data. preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 1, &data); - EXPECT_EQ(NULL, data.get()); + EXPECT_FALSE(data); preview_ui->SetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 1, dummy_data.get()); @@ -175,7 +175,7 @@ TEST_F(PrintPreviewUIUnitTest, PrintPreviewDraftPages) { // Clear the preview data. preview_ui->ClearAllPreviewData(); preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, &data); - EXPECT_EQ(NULL, data.get()); + EXPECT_FALSE(data); } // Test the browser-side print preview cancellation functionality. @@ -198,7 +198,7 @@ TEST_F(PrintPreviewUIUnitTest, GetCurrentPrintPreviewStatus) { PrintPreviewUI* preview_ui = static_cast<PrintPreviewUI*>( preview_dialog->GetWebUI()->GetController()); - ASSERT_TRUE(preview_ui != NULL); + ASSERT_TRUE(preview_ui); // Test with invalid |preview_ui_addr|. bool cancel = false; diff --git a/chromium/chrome/browser/ui/webui/print_preview/printer_capabilities.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.cc index 918401ab811..6d8dc9b06a1 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/printer_capabilities.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_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 "chrome/browser/ui/webui/print_preview/printer_capabilities.h" +#include "chrome/browser/ui/webui/print_preview/print_preview_utils.h" #include <memory> #include <string> @@ -19,27 +19,15 @@ #include "build/build_config.h" #include "chrome/browser/printing/print_preview_dialog_controller.h" #include "chrome/browser/printing/print_view_manager.h" -#include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" #include "chrome/browser/ui/webui/print_preview/printer_handler.h" #include "components/crash/core/common/crash_keys.h" -#include "components/printing/common/cloud_print_cdd_conversion.h" +#include "components/printing/common/printer_capabilities.h" #include "content/public/browser/render_frame_host.h" -#include "printing/backend/print_backend.h" #include "printing/backend/print_backend_consts.h" #include "printing/page_range.h" -#if defined(OS_WIN) -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "components/strings/grit/components_strings.h" -#include "ui/base/l10n/l10n_util.h" -#endif - namespace printing { -const char kPrinter[] = "printer"; - // Keys for a dictionary specifying a custom vendor capability. See // settings/advanced_settings/advanced_settings_item.js in // chrome/browser/resources/print_preview. @@ -53,57 +41,6 @@ const char kVendorCapabilityKey[] = "vendor_capability"; namespace { -// Returns a dictionary representing printer capabilities as CDD. Returns -// an empty dictionary if a dictionary could not be generated. -std::unique_ptr<base::DictionaryValue> -GetPrinterCapabilitiesOnBlockingPoolThread(const std::string& device_name) { - base::AssertBlockingAllowed(); - DCHECK(!device_name.empty()); - - scoped_refptr<PrintBackend> print_backend( - PrintBackend::CreateInstance(nullptr)); - - VLOG(1) << "Get printer capabilities start for " << device_name; - crash_keys::ScopedPrinterInfo crash_key( - print_backend->GetPrinterDriverInfo(device_name)); - - auto empty_capabilities = std::make_unique<base::DictionaryValue>(); - std::unique_ptr<base::DictionaryValue> printer_info; - if (!print_backend->IsValidPrinter(device_name)) { - LOG(WARNING) << "Invalid printer " << device_name; - return empty_capabilities; - } - - PrinterSemanticCapsAndDefaults info; - if (!print_backend->GetPrinterSemanticCapsAndDefaults(device_name, &info)) { - LOG(WARNING) << "Failed to get capabilities for " << device_name; - return empty_capabilities; - } - - return cloud_print::PrinterSemanticCapsAndDefaultsToCdd(info); -} - -#if defined(OS_WIN) -std::string GetUserFriendlyName(const std::string& printer_name) { - // |printer_name| may be a UNC path like \\printserver\printername. - if (!base::StartsWith(printer_name, "\\\\", - base::CompareCase::INSENSITIVE_ASCII)) { - return printer_name; - } - - // If it is a UNC path, split the "printserver\printername" portion and - // generate a friendly name, like Windows does. - std::string printer_name_trimmed = printer_name.substr(2); - std::vector<std::string> tokens = base::SplitString( - printer_name_trimmed, "\\", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); - if (tokens.size() != 2 || tokens[0].empty() || tokens[1].empty()) - return printer_name; - return l10n_util::GetStringFUTF8( - IDS_PRINT_PREVIEW_FRIENDLY_WIN_NETWORK_PRINTER_NAME, - base::UTF8ToUTF16(tokens[1]), base::UTF8ToUTF16(tokens[0])); -} -#endif - void PrintersToValues(const PrinterList& printer_list, base::ListValue* printers) { for (const PrinterBasicInfo& printer : printer_list) { @@ -173,68 +110,6 @@ void SystemDialogDone(const base::Value& error) { } // namespace -std::pair<std::string, std::string> GetPrinterNameAndDescription( - const PrinterBasicInfo& printer) { -#if defined(OS_MACOSX) || defined(OS_CHROMEOS) - // On Mac, |printer.printer_description| specifies the printer name and - // |printer.printer_name| specifies the device name / printer queue name. - // Chrome OS emulates the Mac behavior. - const std::string& real_name = printer.printer_description; - std::string real_description; - const auto it = printer.options.find(kDriverNameTagName); - if (it != printer.options.end()) - real_description = it->second; - return std::make_pair(real_name, real_description); -#elif defined(OS_WIN) - return std::make_pair(GetUserFriendlyName(printer.printer_name), - printer.printer_description); -#else - return std::make_pair(printer.printer_name, printer.printer_description); -#endif -} - -std::unique_ptr<base::DictionaryValue> GetSettingsOnBlockingPool( - const std::string& device_name, - const PrinterBasicInfo& basic_info) { - base::AssertBlockingAllowed(); - - const auto printer_name_description = - GetPrinterNameAndDescription(basic_info); - const std::string& printer_name = printer_name_description.first; - const std::string& printer_description = printer_name_description.second; - - auto printer_info = std::make_unique<base::DictionaryValue>(); - printer_info->SetString(kSettingDeviceName, device_name); - printer_info->SetString(kSettingPrinterName, printer_name); - printer_info->SetString(kSettingPrinterDescription, printer_description); - printer_info->SetBoolean( - kCUPSEnterprisePrinter, - base::ContainsKey(basic_info.options, kCUPSEnterprisePrinter) && - basic_info.options.at(kCUPSEnterprisePrinter) == kValueTrue); - - auto printer_info_capabilities = std::make_unique<base::DictionaryValue>(); - printer_info_capabilities->SetDictionary(kPrinter, std::move(printer_info)); - printer_info_capabilities->Set( - kSettingCapabilities, - GetPrinterCapabilitiesOnBlockingPoolThread(device_name)); - - return printer_info_capabilities; -} - -void ConvertPrinterListForCallback( - const PrinterHandler::AddedPrintersCallback& callback, - PrinterHandler::GetPrintersDoneCallback done_callback, - const PrinterList& printer_list) { - base::ListValue printers; - PrintersToValues(printer_list, &printers); - - VLOG(1) << "Enumerate printers finished, found " << printers.GetSize() - << " printers"; - if (!printers.empty()) - callback.Run(printers); - std::move(done_callback).Run(); -} - std::unique_ptr<base::DictionaryValue> ValidateCddForPrintPreview( const base::DictionaryValue& cdd) { auto validated_cdd = @@ -291,8 +166,22 @@ std::unique_ptr<base::DictionaryValue> ValidateCddForPrintPreview( return validated_cdd; } +void ConvertPrinterListForCallback( + const PrinterHandler::AddedPrintersCallback& callback, + PrinterHandler::GetPrintersDoneCallback done_callback, + const PrinterList& printer_list) { + base::ListValue printers; + PrintersToValues(printer_list, &printers); + + VLOG(1) << "Enumerate printers finished, found " << printers.GetSize() + << " printers"; + if (!printers.empty()) + callback.Run(printers); + std::move(done_callback).Run(); +} + void StartLocalPrint(const std::string& ticket_json, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, content::WebContents* preview_web_contents, PrinterHandler::PrintCallback callback) { std::unique_ptr<base::DictionaryValue> job_settings = @@ -329,4 +218,5 @@ void StartLocalPrint(const std::string& ticket_json, preview_web_contents->GetMainFrame(), std::move(callback)); } + } // namespace printing diff --git a/chromium/chrome/browser/ui/webui/print_preview/printer_capabilities.h b/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.h index 04dd0fee87c..f13e2c100a3 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/printer_capabilities.h +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.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_WEBUI_PRINT_PREVIEW_PRINTER_CAPABILITIES_H_ -#define CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_PRINTER_CAPABILITIES_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_PRINT_PREVIEW_UTILS_H_ +#define CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_PRINT_PREVIEW_UTILS_H_ #include <memory> #include <string> @@ -19,29 +19,14 @@ class WebContents; namespace printing { -struct PrinterBasicInfo; - // Printer capability setting keys. extern const char kOptionKey[]; -extern const char kPrinter[]; extern const char kTypeKey[]; extern const char kSelectCapKey[]; extern const char kSelectString[]; extern const char kTypeKey[]; extern const char kVendorCapabilityKey[]; -// Extracts the printer display name and description from the -// appropriate fields in |printer| for the platform. -std::pair<std::string, std::string> GetPrinterNameAndDescription( - const PrinterBasicInfo& printer); - -// Returns the JSON representing printer capabilities for the device registered -// as |device_name| in the PrinterBackend. The returned dictionary is suitable -// for passage to the WebUI. -std::unique_ptr<base::DictionaryValue> GetSettingsOnBlockingPool( - const std::string& device_name, - const PrinterBasicInfo& basic_info); - // Converts |printer_list| to a base::ListValue form, runs |callback| with the // converted list as the argument if it is not empty, and runs |done_callback|. void ConvertPrinterListForCallback( @@ -58,9 +43,10 @@ std::unique_ptr<base::DictionaryValue> ValidateCddForPrintPreview( // Starts a local print of |print_data| with print settings dictionary // |ticket_json|. Runs |callback| on failure or success. void StartLocalPrint(const std::string& ticket_json, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, content::WebContents* preview_web_contents, PrinterHandler::PrintCallback callback); + } // namespace printing -#endif // CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_PRINTER_CAPABILITIES_H_ +#endif // CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_PRINT_PREVIEW_UTILS_H_ diff --git a/chromium/chrome/browser/ui/webui/print_preview/printer_capabilities_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils_unittest.cc index 4be22d60559..ed32d2a0736 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/printer_capabilities_unittest.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils_unittest.cc @@ -4,13 +4,9 @@ #include <memory> -#include "base/bind.h" -#include "base/memory/ref_counted.h" #include "base/stl_util.h" #include "base/test/values_test_util.h" -#include "chrome/browser/ui/webui/print_preview/printer_capabilities.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "printing/backend/test_print_backend.h" +#include "chrome/browser/ui/webui/print_preview/print_preview_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/size.h" @@ -26,6 +22,7 @@ const char kIsDefault[] = "is_default"; const char kMediaSizes[] = "media_sizes"; const char kPagesPerSheet[] = "Pages per sheet"; const char kPaperType[] = "Paper Type"; +const char kPrinter[] = "printer"; const char kValue[] = "value"; const char kVendorCapability[] = "vendor_capability"; @@ -214,87 +211,9 @@ void ValidatePrinter(const base::DictionaryValue* cdd_out, } // namespace -class PrinterCapabilitiesTest : public testing::Test { - public: - PrinterCapabilitiesTest() {} - ~PrinterCapabilitiesTest() override {} +using PrintPreviewUtilsTest = testing::Test; - protected: - void SetUp() override { - test_backend_ = base::MakeRefCounted<TestPrintBackend>(); - PrintBackend::SetPrintBackendForTesting(test_backend_.get()); - } - - void TearDown() override { test_backend_ = nullptr; } - - TestPrintBackend* print_backend() { return test_backend_.get(); } - - private: - content::TestBrowserThreadBundle test_browser_threads_; - scoped_refptr<TestPrintBackend> test_backend_; -}; - -// Verify that we don't crash for a missing printer and a nullptr is never -// returned. -TEST_F(PrinterCapabilitiesTest, NonNullForMissingPrinter) { - PrinterBasicInfo basic_info; - std::string printer_name = "missing_printer"; - - std::unique_ptr<base::DictionaryValue> settings_dictionary = - GetSettingsOnBlockingPool(printer_name, basic_info); - - ASSERT_TRUE(settings_dictionary); -} - -TEST_F(PrinterCapabilitiesTest, ProvidedCapabilitiesUsed) { - std::string printer_name = "test_printer"; - PrinterBasicInfo basic_info; - auto caps = std::make_unique<PrinterSemanticCapsAndDefaults>(); - - // set a capability - caps->dpis = {gfx::Size(600, 600)}; - - print_backend()->AddValidPrinter(printer_name, std::move(caps)); - - std::unique_ptr<base::DictionaryValue> settings_dictionary = - GetSettingsOnBlockingPool(printer_name, basic_info); - - // verify settings were created - ASSERT_TRUE(settings_dictionary); - - // verify capabilities and have one entry - base::DictionaryValue* cdd; - ASSERT_TRUE(settings_dictionary->GetDictionary(kSettingCapabilities, &cdd)); - - // read the CDD for the dpi attribute. - base::DictionaryValue* caps_dict; - ASSERT_TRUE(cdd->GetDictionary(kPrinter, &caps_dict)); - EXPECT_TRUE(caps_dict->HasKey(kDpi)); -} - -// Ensure that the capabilities dictionary is present but empty if the backend -// doesn't return capabilities. -TEST_F(PrinterCapabilitiesTest, NullCapabilitiesExcluded) { - std::string printer_name = "test_printer"; - PrinterBasicInfo basic_info; - - // return false when attempting to retrieve capabilities - print_backend()->AddValidPrinter(printer_name, nullptr); - - std::unique_ptr<base::DictionaryValue> settings_dictionary = - GetSettingsOnBlockingPool(printer_name, basic_info); - - // verify settings were created - ASSERT_TRUE(settings_dictionary); - - // verify that capabilities is an empty dictionary - base::DictionaryValue* caps_dict; - ASSERT_TRUE( - settings_dictionary->GetDictionary(kSettingCapabilities, &caps_dict)); - EXPECT_TRUE(caps_dict->empty()); -} - -TEST_F(PrinterCapabilitiesTest, FullCddPassthrough) { +TEST_F(PrintPreviewUtilsTest, FullCddPassthrough) { base::DictionaryValue printer = GetCapabilitiesFull(); base::DictionaryValue cdd; cdd.SetKey(kPrinter, printer.Clone()); @@ -302,7 +221,7 @@ TEST_F(PrinterCapabilitiesTest, FullCddPassthrough) { ValidatePrinter(cdd_out.get(), printer); } -TEST_F(PrinterCapabilitiesTest, FilterBadList) { +TEST_F(PrintPreviewUtilsTest, FilterBadList) { base::DictionaryValue printer = GetCapabilitiesFull(); printer.RemoveKey(kMediaSizes); base::Value::ListStorage list_media; @@ -315,7 +234,7 @@ TEST_F(PrinterCapabilitiesTest, FilterBadList) { ValidatePrinter(cdd_out.get(), printer); } -TEST_F(PrinterCapabilitiesTest, FilterBadOptionOneElement) { +TEST_F(PrintPreviewUtilsTest, FilterBadOptionOneElement) { base::DictionaryValue printer = GetCapabilitiesFull(); printer.RemoveKey(kDpi); base::Value options(base::Value::Type::DICTIONARY); @@ -330,7 +249,7 @@ TEST_F(PrinterCapabilitiesTest, FilterBadOptionOneElement) { ValidatePrinter(cdd_out.get(), printer); } -TEST_F(PrinterCapabilitiesTest, FilterBadOptionAllElement) { +TEST_F(PrintPreviewUtilsTest, FilterBadOptionAllElement) { base::DictionaryValue printer = GetCapabilitiesFull(); printer.RemoveKey(kDpi); base::Value options(base::Value::Type::DICTIONARY); @@ -345,7 +264,7 @@ TEST_F(PrinterCapabilitiesTest, FilterBadOptionAllElement) { ValidatePrinter(cdd_out.get(), printer); } -TEST_F(PrinterCapabilitiesTest, FilterBadVendorCapabilityAllElement) { +TEST_F(PrintPreviewUtilsTest, FilterBadVendorCapabilityAllElement) { base::DictionaryValue printer = GetCapabilitiesFull(); base::Value* select_cap_0 = printer.FindKeyOfType(kVendorCapability, base::Value::Type::LIST) @@ -362,7 +281,7 @@ TEST_F(PrinterCapabilitiesTest, FilterBadVendorCapabilityAllElement) { ValidatePrinter(cdd_out.get(), printer); } -TEST_F(PrinterCapabilitiesTest, FilterBadVendorCapabilityOneElement) { +TEST_F(PrintPreviewUtilsTest, FilterBadVendorCapabilityOneElement) { base::DictionaryValue printer = GetCapabilitiesFull(); base::Value* vendor_dictionary = printer.FindKeyOfType(kVendorCapability, base::Value::Type::LIST) diff --git a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h index 29fc3194f90..ec72a5998e3 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h +++ b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h @@ -16,7 +16,7 @@ namespace base { class DictionaryValue; class ListValue; -class RefCountedBytes; +class RefCountedMemory; class Value; } @@ -127,7 +127,7 @@ class PrinterHandler { const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) = 0; }; diff --git a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc index 6df2047be61..be5aedb2f8c 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc @@ -6,6 +6,7 @@ #include <memory> #include <string> +#include <utility> #include "base/bind.h" #include "base/callback.h" @@ -19,7 +20,7 @@ #include "chrome/browser/printing/cloud_print/privet_constants.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/signin_manager_factory.h" -#include "chrome/browser/ui/webui/print_preview/printer_capabilities.h" +#include "chrome/browser/ui/webui/print_preview/print_preview_utils.h" #include "chrome/common/chrome_switches.h" #include "components/signin/core/browser/signin_manager.h" #include "ui/gfx/geometry/size.h" @@ -85,7 +86,7 @@ void PrivetPrinterHandler::StartPrint( const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) { DCHECK(!print_callback_); print_callback_ = std::move(callback); @@ -192,7 +193,7 @@ void PrivetPrinterHandler::OnGotCapabilities( std::make_unique<base::DictionaryValue>(); FillPrinterDescription(name, *description, true, printer_info.get()); base::DictionaryValue printer_info_and_caps; - printer_info_and_caps.SetDictionary(printing::kPrinter, + printer_info_and_caps.SetDictionary(cloud_print::kPrivetTypePrinter, std::move(printer_info)); std::unique_ptr<base::DictionaryValue> capabilities_copy = capabilities->CreateDeepCopy(); @@ -205,7 +206,7 @@ void PrivetPrinterHandler::OnGotCapabilities( void PrivetPrinterHandler::PrintUpdateClient( const base::string16& job_title, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, const std::string& print_ticket, const std::string& capabilities, const gfx::Size& page_size, @@ -237,7 +238,7 @@ bool PrivetPrinterHandler::UpdateClient( void PrivetPrinterHandler::StartPrint( const base::string16& job_title, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, const std::string& print_ticket, const std::string& capabilities, const gfx::Size& page_size) { diff --git a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h index 87a3d3aa786..4a14f2a30d7 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h +++ b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h @@ -19,7 +19,7 @@ namespace base { class DictionaryValue; class OneShotTimer; -class RefCountedBytes; +class RefCountedMemory; } // namespace base namespace gfx { @@ -48,7 +48,7 @@ class PrivetPrinterHandler const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) override; // PrivetLocalPrinterLister::Delegate implementation. @@ -76,14 +76,14 @@ class PrivetPrinterHandler void OnGotCapabilities(const base::DictionaryValue* capabilities); void PrintUpdateClient( const base::string16& job_title, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, const std::string& print_ticket, const std::string& capabilities, const gfx::Size& page_size, std::unique_ptr<cloud_print::PrivetHTTPClient> http_client); bool UpdateClient(std::unique_ptr<cloud_print::PrivetHTTPClient> http_client); void StartPrint(const base::string16& job_title, - const scoped_refptr<base::RefCountedBytes>& print_data, + const scoped_refptr<base::RefCountedMemory>& print_data, const std::string& print_ticket, const std::string& capabilities, const gfx::Size& page_size); diff --git a/chromium/chrome/browser/ui/webui/profile_helper.cc b/chromium/chrome/browser/ui/webui/profile_helper.cc index e0e10904671..45e7d87e804 100644 --- a/chromium/chrome/browser/ui/webui/profile_helper.cc +++ b/chromium/chrome/browser/ui/webui/profile_helper.cc @@ -55,11 +55,7 @@ void ShowReauthDialog(const std::string& user_name, } void DeleteProfileCallback(std::unique_ptr<ScopedKeepAlive> keep_alive, - Profile* profile, - Profile::CreateStatus status) { - if (status != Profile::CREATE_STATUS_INITIALIZED) - return; - + Profile* profile) { OpenNewWindowForProfile(profile); } @@ -88,10 +84,10 @@ void DeleteProfileAtPath(base::FilePath file_path, return; g_browser_process->profile_manager()->MaybeScheduleProfileForDeletion( file_path, - base::Bind(&DeleteProfileCallback, - base::Passed(std::make_unique<ScopedKeepAlive>( - KeepAliveOrigin::PROFILE_HELPER, - KeepAliveRestartOption::DISABLED))), + base::BindOnce( + &DeleteProfileCallback, + std::make_unique<ScopedKeepAlive>(KeepAliveOrigin::PROFILE_HELPER, + KeepAliveRestartOption::DISABLED)), deletion_source); } diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.cc b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.cc index 1c632127e20..8c70d1bccbd 100644 --- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.cc +++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.cc @@ -27,9 +27,9 @@ QuotaInternalsHandler::~QuotaInternalsHandler() { } void QuotaInternalsHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("requestInfo", - base::Bind(&QuotaInternalsHandler::OnRequestInfo, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "requestInfo", base::BindRepeating(&QuotaInternalsHandler::OnRequestInfo, + base::Unretained(this))); } void QuotaInternalsHandler::ReportAvailableSpace(int64_t available_space) { diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h index 26f5bfdffcd..f5c38a3a65a 100644 --- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h +++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h @@ -18,7 +18,7 @@ #include "base/sequenced_task_runner_helpers.h" #include "content/public/browser/browser_thread.h" #include "storage/browser/quota/quota_manager.h" -#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h" +#include "third_party/blink/public/mojom/quota/quota_types.mojom.h" namespace quota_internals { diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_types.h b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_types.h index b6a1295afbb..2d99e59662f 100644 --- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_types.h +++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_types.h @@ -12,7 +12,7 @@ #include <string> #include "base/time/time.h" -#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h" +#include "third_party/blink/public/mojom/quota/quota_types.mojom.h" #include "url/gurl.h" namespace base { diff --git a/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc b/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc index 66b53a7a944..0ba9fbd6acd 100644 --- a/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc @@ -17,7 +17,7 @@ #if defined(OS_ANDROID) #include "chrome/common/sandbox_status_extension_android.mojom.h" -#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h" +#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #endif #if defined(OS_LINUX) diff --git a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc b/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc index 56f8eded426..c0977b81a9f 100644 --- a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc +++ b/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc @@ -140,8 +140,9 @@ SetAsDefaultBrowserHandler::SetAsDefaultBrowserHandler( void SetAsDefaultBrowserHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "SetAsDefaultBrowser:LaunchSetDefaultBrowserFlow", - base::Bind(&SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow, - base::Unretained(this))); + base::BindRepeating( + &SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow, + base::Unretained(this))); } void SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow( diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.cc b/chromium/chrome/browser/ui/webui/settings/about_handler.cc index 0e22bfc93e3..787f802a743 100644 --- a/chromium/chrome/browser/ui/webui/settings/about_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/about_handler.cc @@ -283,7 +283,7 @@ AboutHandler* AboutHandler::Create(content::WebUIDataSource* html_source, l10n_util::GetStringUTF16(version_info::IsOfficialBuild() ? IDS_VERSION_UI_OFFICIAL : IDS_VERSION_UI_UNOFFICIAL), - base::UTF8ToUTF16(chrome::GetChannelString()), + base::UTF8ToUTF16(chrome::GetChannelName()), #if defined(ARCH_CPU_64_BITS) l10n_util::GetStringUTF16(IDS_VERSION_UI_64BIT))); #else @@ -346,42 +346,44 @@ AboutHandler* AboutHandler::Create(content::WebUIDataSource* html_source, void AboutHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "aboutPageReady", - base::Bind(&AboutHandler::HandlePageReady, base::Unretained(this))); + "aboutPageReady", base::BindRepeating(&AboutHandler::HandlePageReady, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "refreshUpdateStatus", - base::Bind(&AboutHandler::HandleRefreshUpdateStatus, - base::Unretained(this))); + base::BindRepeating(&AboutHandler::HandleRefreshUpdateStatus, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "openFeedbackDialog", base::Bind(&AboutHandler::HandleOpenFeedbackDialog, - base::Unretained(this))); + "openFeedbackDialog", + base::BindRepeating(&AboutHandler::HandleOpenFeedbackDialog, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "openHelpPage", - base::Bind(&AboutHandler::HandleOpenHelpPage, base::Unretained(this))); + "openHelpPage", base::BindRepeating(&AboutHandler::HandleOpenHelpPage, + base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( - "setChannel", - base::Bind(&AboutHandler::HandleSetChannel, base::Unretained(this))); + "setChannel", base::BindRepeating(&AboutHandler::HandleSetChannel, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "requestUpdate", - base::Bind(&AboutHandler::HandleRequestUpdate, base::Unretained(this))); + "requestUpdate", base::BindRepeating(&AboutHandler::HandleRequestUpdate, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestUpdateOverCellular", - base::Bind(&AboutHandler::HandleRequestUpdateOverCellular, - base::Unretained(this))); + base::BindRepeating(&AboutHandler::HandleRequestUpdateOverCellular, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "getVersionInfo", - base::Bind(&AboutHandler::HandleGetVersionInfo, base::Unretained(this))); + "getVersionInfo", base::BindRepeating(&AboutHandler::HandleGetVersionInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "getRegulatoryInfo", base::Bind(&AboutHandler::HandleGetRegulatoryInfo, - base::Unretained(this))); + "getRegulatoryInfo", + base::BindRepeating(&AboutHandler::HandleGetRegulatoryInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "getChannelInfo", base::Bind(&AboutHandler::HandleGetChannelInfo, - base::Unretained(this))); + "getChannelInfo", base::BindRepeating(&AboutHandler::HandleGetChannelInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "refreshTPMFirmwareUpdateStatus", - base::Bind(&AboutHandler::HandleRefreshTPMFirmwareUpdateStatus, - base::Unretained(this))); + base::BindRepeating(&AboutHandler::HandleRefreshTPMFirmwareUpdateStatus, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getHasEndOfLife", base::BindRepeating(&AboutHandler::HandleGetHasEndOfLife, @@ -389,8 +391,8 @@ void AboutHandler::RegisterMessages() { #endif #if defined(OS_MACOSX) web_ui()->RegisterMessageCallback( - "promoteUpdater", - base::Bind(&AboutHandler::PromoteUpdater, base::Unretained(this))); + "promoteUpdater", base::BindRepeating(&AboutHandler::PromoteUpdater, + base::Unretained(this))); #endif #if defined(OS_CHROMEOS) diff --git a/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc b/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc index 3e9bb1a4d96..ae92d569046 100644 --- a/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc @@ -29,29 +29,29 @@ void AppearanceHandler::OnJavascriptDisallowed() {} void AppearanceHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "useDefaultTheme", - base::Bind(&AppearanceHandler::HandleUseDefaultTheme, - base::Unretained(this))); + base::BindRepeating(&AppearanceHandler::HandleUseDefaultTheme, + base::Unretained(this))); #if defined(OS_LINUX) && !defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( "useSystemTheme", - base::Bind(&AppearanceHandler::HandleUseSystemTheme, - base::Unretained(this))); + base::BindRepeating(&AppearanceHandler::HandleUseSystemTheme, + base::Unretained(this))); #endif #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( "openWallpaperManager", - base::Bind(&AppearanceHandler::HandleOpenWallpaperManager, - base::Unretained(this))); + base::BindRepeating(&AppearanceHandler::HandleOpenWallpaperManager, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "isWallpaperSettingVisible", - base::Bind(&AppearanceHandler::IsWallpaperSettingVisible, - base::Unretained(this))); + base::BindRepeating(&AppearanceHandler::IsWallpaperSettingVisible, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "isWallpaperPolicyControlled", - base::Bind(&AppearanceHandler::IsWallpaperPolicyControlled, - base::Unretained(this))); + base::BindRepeating(&AppearanceHandler::IsWallpaperPolicyControlled, + base::Unretained(this))); #endif } diff --git a/chromium/chrome/browser/ui/webui/settings/browser_lifetime_handler.cc b/chromium/chrome/browser/ui/webui/settings/browser_lifetime_handler.cc index 551123b58ae..c4eb7282a45 100644 --- a/chromium/chrome/browser/ui/webui/settings/browser_lifetime_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/browser_lifetime_handler.cc @@ -25,19 +25,21 @@ BrowserLifetimeHandler::BrowserLifetimeHandler() {} BrowserLifetimeHandler::~BrowserLifetimeHandler() {} void BrowserLifetimeHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("restart", - base::Bind(&BrowserLifetimeHandler::HandleRestart, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("relaunch", - base::Bind(&BrowserLifetimeHandler::HandleRelaunch, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "restart", base::BindRepeating(&BrowserLifetimeHandler::HandleRestart, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "relaunch", base::BindRepeating(&BrowserLifetimeHandler::HandleRelaunch, + base::Unretained(this))); #if defined(OS_CHROMEOS) - web_ui()->RegisterMessageCallback("signOutAndRestart", - base::Bind(&BrowserLifetimeHandler::HandleSignOutAndRestart, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("factoryReset", - base::Bind(&BrowserLifetimeHandler::HandleFactoryReset, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "signOutAndRestart", + base::BindRepeating(&BrowserLifetimeHandler::HandleSignOutAndRestart, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "factoryReset", + base::BindRepeating(&BrowserLifetimeHandler::HandleFactoryReset, + base::Unretained(this))); #endif // defined(OS_CHROMEOS) } diff --git a/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc b/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc index a077bd75bd2..6d64f7bbd08 100644 --- a/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc @@ -26,11 +26,12 @@ ChangePasswordHandler::~ChangePasswordHandler() {} void ChangePasswordHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "initializeChangePasswordHandler", - base::Bind(&ChangePasswordHandler::HandleInitialize, - base::Unretained(this))); + base::BindRepeating(&ChangePasswordHandler::HandleInitialize, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "changePassword", base::Bind(&ChangePasswordHandler::HandleChangePassword, - base::Unretained(this))); + "changePassword", + base::BindRepeating(&ChangePasswordHandler::HandleChangePassword, + base::Unretained(this))); } void ChangePasswordHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.cc index a74053c73a4..43375c860ec 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.cc @@ -25,16 +25,17 @@ AccessibilityHandler::~AccessibilityHandler() {} void AccessibilityHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "showChromeVoxSettings", - base::Bind(&AccessibilityHandler::HandleShowChromeVoxSettings, - base::Unretained(this))); + base::BindRepeating(&AccessibilityHandler::HandleShowChromeVoxSettings, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "showSelectToSpeakSettings", - base::Bind(&AccessibilityHandler::HandleShowSelectToSpeakSettings, - base::Unretained(this))); + base::BindRepeating( + &AccessibilityHandler::HandleShowSelectToSpeakSettings, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "showSwitchAccessSettings", - base::Bind(&AccessibilityHandler::HandleShowSwitchAccessSettings, - base::Unretained(this))); + base::BindRepeating(&AccessibilityHandler::HandleShowSwitchAccessSettings, + base::Unretained(this))); } void AccessibilityHandler::HandleShowChromeVoxSettings( diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.cc index 01baa407efa..1a3824cb28e 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.cc @@ -28,16 +28,16 @@ void AndroidAppsHandler::RegisterMessages() { // Note: requestAndroidAppsInfo must be called before observers will be added. web_ui()->RegisterMessageCallback( "requestAndroidAppsInfo", - base::Bind(&AndroidAppsHandler::HandleRequestAndroidAppsInfo, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&AndroidAppsHandler::HandleRequestAndroidAppsInfo, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "showAndroidAppsSettings", - base::Bind(&AndroidAppsHandler::ShowAndroidAppsSettings, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&AndroidAppsHandler::ShowAndroidAppsSettings, + weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "showAndroidManageAppLinks", - base::Bind(&AndroidAppsHandler::ShowAndroidManageAppLinks, - weak_ptr_factory_.GetWeakPtr())); + base::BindRepeating(&AndroidAppsHandler::ShowAndroidManageAppLinks, + weak_ptr_factory_.GetWeakPtr())); } void AndroidAppsHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc index 6a345261eb0..578bbdbb08e 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc @@ -100,25 +100,27 @@ ChangePictureHandler::~ChangePictureHandler() { void ChangePictureHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "chooseFile", base::Bind(&ChangePictureHandler::HandleChooseFile, - base::Unretained(this))); + "chooseFile", base::BindRepeating(&ChangePictureHandler::HandleChooseFile, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "photoTaken", base::Bind(&ChangePictureHandler::HandlePhotoTaken, - base::Unretained(this))); + "photoTaken", base::BindRepeating(&ChangePictureHandler::HandlePhotoTaken, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "discardPhoto", base::Bind(&ChangePictureHandler::HandleDiscardPhoto, - base::Unretained(this))); + "discardPhoto", + base::BindRepeating(&ChangePictureHandler::HandleDiscardPhoto, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "onChangePicturePageInitialized", - base::Bind(&ChangePictureHandler::HandlePageInitialized, - base::Unretained(this))); + base::BindRepeating(&ChangePictureHandler::HandlePageInitialized, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "selectImage", base::Bind(&ChangePictureHandler::HandleSelectImage, - base::Unretained(this))); + "selectImage", + base::BindRepeating(&ChangePictureHandler::HandleSelectImage, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestSelectedImage", - base::Bind(&ChangePictureHandler::HandleRequestSelectedImage, - base::Unretained(this))); + base::BindRepeating(&ChangePictureHandler::HandleRequestSelectedImage, + base::Unretained(this))); } void ChangePictureHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc index a535d490d14..942bd8bfbc4 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc @@ -37,6 +37,7 @@ #include "chromeos/printing/ppd_line_reader.h" #include "chromeos/printing/ppd_provider.h" #include "chromeos/printing/printer_configuration.h" +#include "chromeos/printing/printer_translator.h" #include "chromeos/printing/printing_constants.h" #include "chromeos/printing/uri_components.h" #include "content/public/browser/browser_context.h" @@ -102,84 +103,6 @@ void QueryAutoconf(const std::string& printer_uri, callback); } -// Create an empty CupsPrinterInfo dictionary value. It should be consistent -// with the fields in js side. See cups_printers_browser_proxy.js for the -// definition of CupsPrinterInfo. -std::unique_ptr<base::DictionaryValue> CreateEmptyPrinterInfo() { - std::unique_ptr<base::DictionaryValue> printer_info = - std::make_unique<base::DictionaryValue>(); - printer_info->SetString("ppdManufacturer", ""); - printer_info->SetString("ppdModel", ""); - printer_info->SetString("printerAddress", ""); - printer_info->SetBoolean("printerAutoconf", false); - printer_info->SetString("printerDescription", ""); - printer_info->SetString("printerId", ""); - printer_info->SetString("printerManufacturer", ""); - printer_info->SetString("printerModel", ""); - printer_info->SetString("printerMakeAndModel", ""); - printer_info->SetString("printerName", ""); - printer_info->SetString("printerPPDPath", ""); - printer_info->SetString("printerProtocol", "ipp"); - printer_info->SetString("printerQueue", ""); - printer_info->SetString("printerStatus", ""); - return printer_info; -} - -// Formats a host and port string. The |port| portion is omitted if -// it is unspecified or invalid. -std::string PrinterAddress(const std::string& host, int port) { - if (port != url::PORT_UNSPECIFIED && port != url::PORT_INVALID) { - return base::StringPrintf("%s:%d", host.c_str(), port); - } - - return host; -} - -// Returns a JSON representation of |printer| as a CupsPrinterInfo. If the -// printer uri cannot be parsed, the relevant fields are populated with default -// values. -std::unique_ptr<base::DictionaryValue> GetPrinterInfo(const Printer& printer) { - std::unique_ptr<base::DictionaryValue> printer_info = - CreateEmptyPrinterInfo(); - printer_info->SetString("printerId", printer.id()); - printer_info->SetString("printerName", printer.display_name()); - printer_info->SetString("printerDescription", printer.description()); - printer_info->SetString("printerManufacturer", printer.manufacturer()); - printer_info->SetString("printerModel", printer.model()); - printer_info->SetString("printerMakeAndModel", printer.make_and_model()); - - auto optional = printer.GetUriComponents(); - if (!optional.has_value()) { - // Uri is invalid so we set default values. - LOG(WARNING) << "Could not parse uri. Defaulting values"; - printer_info->SetString("printerAddress", ""); - printer_info->SetString("printerQueue", ""); - printer_info->SetString("printerProtocol", - "ipp"); // IPP is our default protocol. - return printer_info; - } - - UriComponents uri = optional.value(); - - if (base::ToLowerASCII(uri.scheme()) == "usb") { - // USB has URI path (and, maybe, query) components that aren't really - // associated with a queue -- the mapping between printing semantics and URI - // semantics breaks down a bit here. From the user's point of view, the - // entire host/path/query block is the printer address for USB. - printer_info->SetString("printerAddress", - printer.uri().substr(strlen("usb://"))); - } else { - printer_info->SetString("printerAddress", - PrinterAddress(uri.host(), uri.port())); - if (!uri.path().empty()) { - printer_info->SetString("printerQueue", uri.path().substr(1)); - } - } - printer_info->SetString("printerProtocol", base::ToLowerASCII(uri.scheme())); - - return printer_info; -} - // Extracts a sanitized value of printerQueue from |printer_dict|. Returns an // empty string if the value was not present in the dictionary. std::string GetPrinterQueue(const base::DictionaryValue& printer_dict) { @@ -265,52 +188,58 @@ CupsPrintersHandler::~CupsPrintersHandler() {} void CupsPrintersHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getCupsPrintersList", - base::Bind(&CupsPrintersHandler::HandleGetCupsPrintersList, - base::Unretained(this))); + base::BindRepeating(&CupsPrintersHandler::HandleGetCupsPrintersList, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "updateCupsPrinter", - base::Bind(&CupsPrintersHandler::HandleUpdateCupsPrinter, - base::Unretained(this))); + base::BindRepeating(&CupsPrintersHandler::HandleUpdateCupsPrinter, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "removeCupsPrinter", - base::Bind(&CupsPrintersHandler::HandleRemoveCupsPrinter, - base::Unretained(this))); + base::BindRepeating(&CupsPrintersHandler::HandleRemoveCupsPrinter, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "addCupsPrinter", base::Bind(&CupsPrintersHandler::HandleAddCupsPrinter, - base::Unretained(this))); + "addCupsPrinter", + base::BindRepeating(&CupsPrintersHandler::HandleAddCupsPrinter, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "getPrinterInfo", base::Bind(&CupsPrintersHandler::HandleGetPrinterInfo, - base::Unretained(this))); + "getPrinterInfo", + base::BindRepeating(&CupsPrintersHandler::HandleGetPrinterInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getCupsPrinterManufacturersList", - base::Bind(&CupsPrintersHandler::HandleGetCupsPrinterManufacturers, - base::Unretained(this))); + base::BindRepeating( + &CupsPrintersHandler::HandleGetCupsPrinterManufacturers, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getCupsPrinterModelsList", - base::Bind(&CupsPrintersHandler::HandleGetCupsPrinterModels, - base::Unretained(this))); + base::BindRepeating(&CupsPrintersHandler::HandleGetCupsPrinterModels, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "selectPPDFile", base::Bind(&CupsPrintersHandler::HandleSelectPPDFile, - base::Unretained(this))); + "selectPPDFile", + base::BindRepeating(&CupsPrintersHandler::HandleSelectPPDFile, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "startDiscoveringPrinters", - base::Bind(&CupsPrintersHandler::HandleStartDiscovery, - base::Unretained(this))); + base::BindRepeating(&CupsPrintersHandler::HandleStartDiscovery, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "stopDiscoveringPrinters", - base::Bind(&CupsPrintersHandler::HandleStopDiscovery, - base::Unretained(this))); + base::BindRepeating(&CupsPrintersHandler::HandleStopDiscovery, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getPrinterPpdManufacturerAndModel", - base::Bind(&CupsPrintersHandler::HandleGetPrinterPpdManufacturerAndModel, - base::Unretained(this))); + base::BindRepeating( + &CupsPrintersHandler::HandleGetPrinterPpdManufacturerAndModel, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "addDiscoveredPrinter", - base::Bind(&CupsPrintersHandler::HandleAddDiscoveredPrinter, - base::Unretained(this))); + base::BindRepeating(&CupsPrintersHandler::HandleAddDiscoveredPrinter, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "cancelPrinterSetUp", base::Bind(&CupsPrintersHandler::HandleSetUpCancel, - base::Unretained(this))); + "cancelPrinterSetUp", + base::BindRepeating(&CupsPrintersHandler::HandleSetUpCancel, + base::Unretained(this))); } void CupsPrintersHandler::OnJavascriptAllowed() { @@ -336,7 +265,7 @@ void CupsPrintersHandler::HandleGetCupsPrintersList( for (const Printer& printer : printers) { // Some of these printers could be invalid but we want to allow the user // to edit them. crbug.com/778383 - printers_list->Append(GetPrinterInfo(printer)); + printers_list->Append(GetCupsPrinterInfo(printer)); } auto response = std::make_unique<base::DictionaryValue>(); @@ -464,7 +393,7 @@ void CupsPrintersHandler::OnAutoconfQueriedDiscovered( // much information as we can about the printer, and ask the user to supply // the rest. FireWebUIListener("on-manually-add-discovered-printer", - *GetPrinterInfo(*printer)); + *GetCupsPrinterInfo(*printer)); } void CupsPrintersHandler::OnAutoconfQueried(const std::string& callback_id, @@ -810,10 +739,10 @@ void CupsPrintersHandler::OnPrintersChanged( std::unique_ptr<base::ListValue> printers_list = std::make_unique<base::ListValue>(); for (const Printer& printer : automatic_printers_) { - printers_list->Append(GetPrinterInfo(printer)); + printers_list->Append(GetCupsPrinterInfo(printer)); } for (const Printer& printer : discovered_printers_) { - printers_list->Append(GetPrinterInfo(printer)); + printers_list->Append(GetCupsPrinterInfo(printer)); } FireWebUIListener("on-printer-discovered", *printers_list); @@ -866,7 +795,7 @@ void CupsPrintersHandler::HandleAddDiscoveredPrinter( } else { // If it's not an IPP printer, the user must choose a PPD. FireWebUIListener("on-manually-add-discovered-printer", - *GetPrinterInfo(*printer)); + *GetCupsPrinterInfo(*printer)); } } diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc index ffe094e20ee..901d006207d 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc @@ -88,14 +88,16 @@ DateTimeHandler* DateTimeHandler::Create( void DateTimeHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "dateTimePageReady", base::Bind(&DateTimeHandler::HandleDateTimePageReady, - base::Unretained(this))); + "dateTimePageReady", + base::BindRepeating(&DateTimeHandler::HandleDateTimePageReady, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "getTimeZones", - base::Bind(&DateTimeHandler::HandleGetTimeZones, base::Unretained(this))); + "getTimeZones", base::BindRepeating(&DateTimeHandler::HandleGetTimeZones, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "showSetDateTimeUI", base::Bind(&DateTimeHandler::HandleShowSetDateTimeUI, - base::Unretained(this))); + "showSetDateTimeUI", + base::BindRepeating(&DateTimeHandler::HandleShowSetDateTimeUI, + base::Unretained(this))); } void DateTimeHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc index 53bf08503de..59a3f7f004d 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc @@ -46,12 +46,12 @@ KeyboardHandler::~KeyboardHandler() = default; void KeyboardHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "initializeKeyboardSettings", - base::Bind(&KeyboardHandler::HandleInitialize, - base::Unretained(this))); + base::BindRepeating(&KeyboardHandler::HandleInitialize, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "showKeyboardShortcutsOverlay", - base::Bind(&KeyboardHandler::HandleShowKeyboardShortcutsOverlay, - base::Unretained(this))); + base::BindRepeating(&KeyboardHandler::HandleShowKeyboardShortcutsOverlay, + base::Unretained(this))); } void KeyboardHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc index bbf2fa12df1..c875a4480ff 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc @@ -9,7 +9,6 @@ #include "base/command_line.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/observer_list.h" #include "chromeos/chromeos_switches.h" #include "content/public/test/test_web_ui.h" diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_pointer_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_pointer_handler.cc index 061dad6d182..0f5933cc8a8 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_pointer_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_pointer_handler.cc @@ -18,7 +18,8 @@ PointerHandler::~PointerHandler() {} void PointerHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "initializePointerSettings", - base::Bind(&PointerHandler::HandleInitialize, base::Unretained(this))); + base::BindRepeating(&PointerHandler::HandleInitialize, + base::Unretained(this))); } void PointerHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc index c07cfbf1074..38957b75449 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc @@ -7,13 +7,13 @@ #include <memory> #include <utility> +#include "ash/public/cpp/ash_pref_names.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "base/values.h" -#include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/prefs/pref_change_registrar.h" @@ -89,22 +89,24 @@ PowerHandler::~PowerHandler() {} void PowerHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "updatePowerStatus", base::Bind(&PowerHandler::HandleUpdatePowerStatus, - base::Unretained(this))); + "updatePowerStatus", + base::BindRepeating(&PowerHandler::HandleUpdatePowerStatus, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "setPowerSource", - base::Bind(&PowerHandler::HandleSetPowerSource, base::Unretained(this))); + "setPowerSource", base::BindRepeating(&PowerHandler::HandleSetPowerSource, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestPowerManagementSettings", - base::Bind(&PowerHandler::HandleRequestPowerManagementSettings, - base::Unretained(this))); + base::BindRepeating(&PowerHandler::HandleRequestPowerManagementSettings, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setLidClosedBehavior", - base::Bind(&PowerHandler::HandleSetLidClosedBehavior, - base::Unretained(this))); + base::BindRepeating(&PowerHandler::HandleSetLidClosedBehavior, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setIdleBehavior", - base::Bind(&PowerHandler::HandleSetIdleBehavior, base::Unretained(this))); + base::BindRepeating(&PowerHandler::HandleSetIdleBehavior, + base::Unretained(this))); } void PowerHandler::OnJavascriptAllowed() { @@ -121,15 +123,18 @@ void PowerHandler::OnJavascriptAllowed() { base::Unretained(this), false /* force */)); pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>(); pref_change_registrar_->Init(prefs_); - pref_change_registrar_->Add(prefs::kPowerAcIdleAction, callback); - pref_change_registrar_->Add(prefs::kPowerAcScreenDimDelayMs, callback); - pref_change_registrar_->Add(prefs::kPowerAcScreenOffDelayMs, callback); - pref_change_registrar_->Add(prefs::kPowerAcScreenLockDelayMs, callback); - pref_change_registrar_->Add(prefs::kPowerBatteryIdleAction, callback); - pref_change_registrar_->Add(prefs::kPowerBatteryScreenDimDelayMs, callback); - pref_change_registrar_->Add(prefs::kPowerBatteryScreenOffDelayMs, callback); - pref_change_registrar_->Add(prefs::kPowerBatteryScreenLockDelayMs, callback); - pref_change_registrar_->Add(prefs::kPowerLidClosedAction, callback); + pref_change_registrar_->Add(ash::prefs::kPowerAcIdleAction, callback); + pref_change_registrar_->Add(ash::prefs::kPowerAcScreenDimDelayMs, callback); + pref_change_registrar_->Add(ash::prefs::kPowerAcScreenOffDelayMs, callback); + pref_change_registrar_->Add(ash::prefs::kPowerAcScreenLockDelayMs, callback); + pref_change_registrar_->Add(ash::prefs::kPowerBatteryIdleAction, callback); + pref_change_registrar_->Add(ash::prefs::kPowerBatteryScreenDimDelayMs, + callback); + pref_change_registrar_->Add(ash::prefs::kPowerBatteryScreenOffDelayMs, + callback); + pref_change_registrar_->Add(ash::prefs::kPowerBatteryScreenLockDelayMs, + callback); + pref_change_registrar_->Add(ash::prefs::kPowerLidClosedAction, callback); } void PowerHandler::OnJavascriptDisallowed() { @@ -183,42 +188,42 @@ void PowerHandler::HandleSetIdleBehavior(const base::ListValue* args) { case IdleBehavior::DISPLAY_OFF_SLEEP: // The default behavior is to turn the display off and sleep. Clear the // prefs so we use the default delays. - prefs_->ClearPref(prefs::kPowerAcIdleAction); - prefs_->ClearPref(prefs::kPowerAcScreenDimDelayMs); - prefs_->ClearPref(prefs::kPowerAcScreenOffDelayMs); - prefs_->ClearPref(prefs::kPowerAcScreenLockDelayMs); - prefs_->ClearPref(prefs::kPowerBatteryIdleAction); - prefs_->ClearPref(prefs::kPowerBatteryScreenDimDelayMs); - prefs_->ClearPref(prefs::kPowerBatteryScreenOffDelayMs); - prefs_->ClearPref(prefs::kPowerBatteryScreenLockDelayMs); + prefs_->ClearPref(ash::prefs::kPowerAcIdleAction); + prefs_->ClearPref(ash::prefs::kPowerAcScreenDimDelayMs); + prefs_->ClearPref(ash::prefs::kPowerAcScreenOffDelayMs); + prefs_->ClearPref(ash::prefs::kPowerAcScreenLockDelayMs); + prefs_->ClearPref(ash::prefs::kPowerBatteryIdleAction); + prefs_->ClearPref(ash::prefs::kPowerBatteryScreenDimDelayMs); + prefs_->ClearPref(ash::prefs::kPowerBatteryScreenOffDelayMs); + prefs_->ClearPref(ash::prefs::kPowerBatteryScreenLockDelayMs); break; case IdleBehavior::DISPLAY_OFF: // Override idle actions to keep the system awake, but use the default // screen delays. - prefs_->SetInteger(prefs::kPowerAcIdleAction, + prefs_->SetInteger(ash::prefs::kPowerAcIdleAction, PowerPolicyController::ACTION_DO_NOTHING); - prefs_->ClearPref(prefs::kPowerAcScreenDimDelayMs); - prefs_->ClearPref(prefs::kPowerAcScreenOffDelayMs); - prefs_->ClearPref(prefs::kPowerAcScreenLockDelayMs); - prefs_->SetInteger(prefs::kPowerBatteryIdleAction, + prefs_->ClearPref(ash::prefs::kPowerAcScreenDimDelayMs); + prefs_->ClearPref(ash::prefs::kPowerAcScreenOffDelayMs); + prefs_->ClearPref(ash::prefs::kPowerAcScreenLockDelayMs); + prefs_->SetInteger(ash::prefs::kPowerBatteryIdleAction, PowerPolicyController::ACTION_DO_NOTHING); - prefs_->ClearPref(prefs::kPowerBatteryScreenDimDelayMs); - prefs_->ClearPref(prefs::kPowerBatteryScreenOffDelayMs); - prefs_->ClearPref(prefs::kPowerBatteryScreenLockDelayMs); + prefs_->ClearPref(ash::prefs::kPowerBatteryScreenDimDelayMs); + prefs_->ClearPref(ash::prefs::kPowerBatteryScreenOffDelayMs); + prefs_->ClearPref(ash::prefs::kPowerBatteryScreenLockDelayMs); break; case IdleBehavior::DISPLAY_ON: // Override idle actions and set screen delays to 0 in order to disable // them (i.e. keep the screen on). - prefs_->SetInteger(prefs::kPowerAcIdleAction, + prefs_->SetInteger(ash::prefs::kPowerAcIdleAction, PowerPolicyController::ACTION_DO_NOTHING); - prefs_->SetInteger(prefs::kPowerAcScreenDimDelayMs, 0); - prefs_->SetInteger(prefs::kPowerAcScreenOffDelayMs, 0); - prefs_->SetInteger(prefs::kPowerAcScreenLockDelayMs, 0); - prefs_->SetInteger(prefs::kPowerBatteryIdleAction, + prefs_->SetInteger(ash::prefs::kPowerAcScreenDimDelayMs, 0); + prefs_->SetInteger(ash::prefs::kPowerAcScreenOffDelayMs, 0); + prefs_->SetInteger(ash::prefs::kPowerAcScreenLockDelayMs, 0); + prefs_->SetInteger(ash::prefs::kPowerBatteryIdleAction, PowerPolicyController::ACTION_DO_NOTHING); - prefs_->SetInteger(prefs::kPowerBatteryScreenDimDelayMs, 0); - prefs_->SetInteger(prefs::kPowerBatteryScreenOffDelayMs, 0); - prefs_->SetInteger(prefs::kPowerBatteryScreenLockDelayMs, 0); + prefs_->SetInteger(ash::prefs::kPowerBatteryScreenDimDelayMs, 0); + prefs_->SetInteger(ash::prefs::kPowerBatteryScreenOffDelayMs, 0); + prefs_->SetInteger(ash::prefs::kPowerBatteryScreenLockDelayMs, 0); break; default: NOTREACHED() << "Invalid idle behavior " << value; @@ -232,10 +237,10 @@ void PowerHandler::HandleSetLidClosedBehavior(const base::ListValue* args) { CHECK(args->GetInteger(0, &value)); switch (static_cast<PowerPolicyController::Action>(value)) { case PowerPolicyController::ACTION_SUSPEND: - prefs_->ClearPref(prefs::kPowerLidClosedAction); + prefs_->ClearPref(ash::prefs::kPowerLidClosedAction); break; case PowerPolicyController::ACTION_DO_NOTHING: - prefs_->SetInteger(prefs::kPowerLidClosedAction, + prefs_->SetInteger(ash::prefs::kPowerLidClosedAction, PowerPolicyController::ACTION_DO_NOTHING); break; default: @@ -300,31 +305,32 @@ void PowerHandler::SendPowerManagementSettings(bool force) { // be able to display something meaningful in the UI in those cases anyway. const PowerPolicyController::Action idle_action = static_cast<PowerPolicyController::Action>( - prefs_->GetInteger(prefs::kPowerAcIdleAction)); + prefs_->GetInteger(ash::prefs::kPowerAcIdleAction)); IdleBehavior idle_behavior = IdleBehavior::OTHER; if (idle_action == PowerPolicyController::ACTION_SUSPEND) { idle_behavior = IdleBehavior::DISPLAY_OFF_SLEEP; } else if (idle_action == PowerPolicyController::ACTION_DO_NOTHING) { - idle_behavior = (prefs_->GetInteger(prefs::kPowerAcScreenOffDelayMs) > 0 - ? IdleBehavior::DISPLAY_OFF - : IdleBehavior::DISPLAY_ON); + idle_behavior = + (prefs_->GetInteger(ash::prefs::kPowerAcScreenOffDelayMs) > 0 + ? IdleBehavior::DISPLAY_OFF + : IdleBehavior::DISPLAY_ON); } const bool idle_controlled = - prefs_->IsManagedPreference(prefs::kPowerAcIdleAction) || - prefs_->IsManagedPreference(prefs::kPowerAcScreenDimDelayMs) || - prefs_->IsManagedPreference(prefs::kPowerAcScreenOffDelayMs) || - prefs_->IsManagedPreference(prefs::kPowerAcScreenLockDelayMs) || - prefs_->IsManagedPreference(prefs::kPowerBatteryIdleAction) || - prefs_->IsManagedPreference(prefs::kPowerBatteryScreenDimDelayMs) || - prefs_->IsManagedPreference(prefs::kPowerBatteryScreenOffDelayMs) || - prefs_->IsManagedPreference(prefs::kPowerBatteryScreenLockDelayMs); + prefs_->IsManagedPreference(ash::prefs::kPowerAcIdleAction) || + prefs_->IsManagedPreference(ash::prefs::kPowerAcScreenDimDelayMs) || + prefs_->IsManagedPreference(ash::prefs::kPowerAcScreenOffDelayMs) || + prefs_->IsManagedPreference(ash::prefs::kPowerAcScreenLockDelayMs) || + prefs_->IsManagedPreference(ash::prefs::kPowerBatteryIdleAction) || + prefs_->IsManagedPreference(ash::prefs::kPowerBatteryScreenDimDelayMs) || + prefs_->IsManagedPreference(ash::prefs::kPowerBatteryScreenOffDelayMs) || + prefs_->IsManagedPreference(ash::prefs::kPowerBatteryScreenLockDelayMs); const PowerPolicyController::Action lid_closed_behavior = static_cast<PowerPolicyController::Action>( - prefs_->GetInteger(prefs::kPowerLidClosedAction)); + prefs_->GetInteger(ash::prefs::kPowerLidClosedAction)); const bool lid_closed_controlled = - prefs_->IsManagedPreference(prefs::kPowerLidClosedAction); + prefs_->IsManagedPreference(ash::prefs::kPowerLidClosedAction); const bool has_lid = lid_state_ != PowerManagerClient::LidState::NOT_PRESENT; // Don't notify the UI if nothing changed. diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler_browsertest.cc index 149c2b74fd1..edfc117d906 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler_browsertest.cc @@ -5,25 +5,40 @@ #include "chrome/browser/ui/webui/settings/chromeos/device_power_handler.h" #include <memory> +#include <utility> -#include "ash/system/power/power_status.h" +#include "ash/public/cpp/ash_pref_names.h" #include "base/json/json_writer.h" #include "base/macros.h" #include "base/run_loop.h" -#include "base/test/scoped_task_environment.h" #include "base/values.h" -#include "chrome/browser/chromeos/power/power_prefs.h" -#include "chrome/common/pref_names.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/test/base/in_process_browser_test.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_power_manager_client.h" #include "chromeos/dbus/power_policy_controller.h" -#include "components/sync_preferences/testing_pref_service_syncable.h" +#include "components/policy/core/browser/browser_policy_connector.h" +#include "components/policy/core/common/mock_configuration_policy_provider.h" +#include "components/policy/policy_constants.h" +#include "components/prefs/pref_service.h" #include "content/public/test/test_web_ui.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +using testing::Return; +using testing::_; + namespace chromeos { namespace settings { +namespace { + +PrefService* GetPrefs() { + return ProfileManager::GetActiveUserProfile()->GetPrefs(); +} + +} // namespace + class TestPowerHandler : public PowerHandler { public: explicit TestPowerHandler(PrefService* prefs) : PowerHandler(prefs) {} @@ -32,21 +47,24 @@ class TestPowerHandler : public PowerHandler { using PowerHandler::set_web_ui; }; -class PowerHandlerTest : public testing::Test { - public: - PowerHandlerTest() { - // This initializes chromeos::DBusThreadManager. - std::unique_ptr<chromeos::DBusThreadManagerSetter> dbus_setter = - chromeos::DBusThreadManager::GetSetterForTesting(); - dbus_setter->SetPowerManagerClient( - std::make_unique<chromeos::FakePowerManagerClient>()); - power_manager_client_ = static_cast<chromeos::FakePowerManagerClient*>( - chromeos::DBusThreadManager::Get()->GetPowerManagerClient()); - ash::PowerStatus::Initialize(); - - chromeos::PowerPrefs::RegisterUserProfilePrefs(prefs_.registry()); - - handler_ = std::make_unique<TestPowerHandler>(&prefs_); +class PowerHandlerTest : public InProcessBrowserTest { + protected: + PowerHandlerTest() = default; + ~PowerHandlerTest() override = default; + + // InProcessBrowserTest: + void SetUpInProcessBrowserTestFixture() override { + power_manager_client_ = new chromeos::FakePowerManagerClient; + chromeos::DBusThreadManager::GetSetterForTesting()->SetPowerManagerClient( + base::WrapUnique(power_manager_client_)); + + // Initialize user policy. + ON_CALL(provider_, IsInitializationComplete(_)).WillByDefault(Return(true)); + policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_); + } + + void SetUpOnMainThread() override { + handler_ = std::make_unique<TestPowerHandler>(GetPrefs()); test_api_ = std::make_unique<PowerHandler::TestAPI>(handler_.get()); handler_->set_web_ui(&web_ui_); handler_->RegisterMessages(); @@ -54,13 +72,11 @@ class PowerHandlerTest : public testing::Test { base::RunLoop().RunUntilIdle(); } - ~PowerHandlerTest() override { + void TearDownOnMainThread() override { + test_api_.reset(); handler_.reset(); - ash::PowerStatus::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } - protected: // Returns a JSON representation of the contents of the last message sent to // WebUI about settings being changed. std::string GetLastSettingsChangedMessage() WARN_UNUSED_RESULT { @@ -113,13 +129,21 @@ class PowerHandlerTest : public testing::Test { // Returns the user-set value of the integer pref identified by |name| or -1 // if the pref is unset. int GetIntPref(const std::string& name) { - const base::Value* value = prefs_.GetUserPref(name); - return value ? value->GetInt() : -1; + if (!GetPrefs()->HasPrefPath(name)) + return -1; + return GetPrefs()->GetInteger(name); } - base::test::ScopedTaskEnvironment scoped_task_environment_; - sync_preferences::TestingPrefServiceSyncable prefs_; - content::TestWebUI web_ui_; + // Sets a policy update which will cause power pref managed change. + void SetPolicyForPolicyKey(policy::PolicyMap* policy_map, + const std::string& policy_key, + std::unique_ptr<base::Value> value) { + policy_map->Set(policy_key, policy::POLICY_LEVEL_MANDATORY, + policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, + std::move(value), nullptr); + provider_.UpdateChromePolicy(*policy_map); + base::RunLoop().RunUntilIdle(); + } // Owned by chromeos::DBusThreadManager. chromeos::FakePowerManagerClient* power_manager_client_; @@ -127,12 +151,16 @@ class PowerHandlerTest : public testing::Test { std::unique_ptr<TestPowerHandler> handler_; std::unique_ptr<TestPowerHandler::TestAPI> test_api_; + content::TestWebUI web_ui_; + + policy::MockConfigurationPolicyProvider provider_; + private: DISALLOW_COPY_AND_ASSIGN(PowerHandlerTest); }; // Verifies that settings are sent to WebUI when requested. -TEST_F(PowerHandlerTest, SendInitialSettings) { +IN_PROC_BROWSER_TEST_F(PowerHandlerTest, SendInitialSettings) { test_api_->RequestPowerManagementSettings(); EXPECT_EQ( CreateSettingsChangedString( @@ -143,7 +171,7 @@ TEST_F(PowerHandlerTest, SendInitialSettings) { } // Verifies that WebUI receives updated settings when the lid state changes. -TEST_F(PowerHandlerTest, SendSettingsForLidStateChanges) { +IN_PROC_BROWSER_TEST_F(PowerHandlerTest, SendSettingsForLidStateChanges) { power_manager_client_->SetLidState(PowerManagerClient::LidState::NOT_PRESENT, base::TimeTicks()); EXPECT_EQ( @@ -165,10 +193,11 @@ TEST_F(PowerHandlerTest, SendSettingsForLidStateChanges) { // Verifies that when various prefs are controlled, the corresponding settings // are reported as controlled to WebUI. -TEST_F(PowerHandlerTest, SendSettingsForControlledPrefs) { +IN_PROC_BROWSER_TEST_F(PowerHandlerTest, SendSettingsForControlledPrefs) { + policy::PolicyMap policy_map; // Making an arbitrary delay pref managed should result in the idle setting // being reported as controlled. - prefs_.SetManagedPref(prefs::kPowerAcScreenDimDelayMs, + SetPolicyForPolicyKey(&policy_map, policy::key::kScreenDimDelayAC, std::make_unique<base::Value>(10000)); EXPECT_EQ( CreateSettingsChangedString( @@ -178,8 +207,8 @@ TEST_F(PowerHandlerTest, SendSettingsForControlledPrefs) { GetLastSettingsChangedMessage()); // Ditto for making the lid action pref managed. - prefs_.SetManagedPref( - prefs::kPowerLidClosedAction, + SetPolicyForPolicyKey( + &policy_map, policy::key::kLidCloseAction, std::make_unique<base::Value>(PowerPolicyController::ACTION_SUSPEND)); EXPECT_EQ( CreateSettingsChangedString( @@ -191,13 +220,11 @@ TEST_F(PowerHandlerTest, SendSettingsForControlledPrefs) { // Verifies that idle-related prefs are distilled into the proper WebUI // settings. -TEST_F(PowerHandlerTest, SendIdleSettingForPrefChanges) { +IN_PROC_BROWSER_TEST_F(PowerHandlerTest, SendIdleSettingForPrefChanges) { // Set a do-nothing idle action and a nonzero screen-off delay. - prefs_.SetUserPref( - prefs::kPowerAcIdleAction, - std::make_unique<base::Value>(PowerPolicyController::ACTION_DO_NOTHING)); - prefs_.SetUserPref(prefs::kPowerAcScreenOffDelayMs, - std::make_unique<base::Value>(10000)); + GetPrefs()->Set(ash::prefs::kPowerAcIdleAction, + base::Value(PowerPolicyController::ACTION_DO_NOTHING)); + GetPrefs()->Set(ash::prefs::kPowerAcScreenOffDelayMs, base::Value(10000)); EXPECT_EQ(CreateSettingsChangedString(PowerHandler::IdleBehavior::DISPLAY_OFF, false /* idle_controlled */, PowerPolicyController::ACTION_SUSPEND, @@ -206,8 +233,7 @@ TEST_F(PowerHandlerTest, SendIdleSettingForPrefChanges) { GetLastSettingsChangedMessage()); // Now set the delay to zero and check that the setting goes to "display on". - prefs_.SetUserPref(prefs::kPowerAcScreenOffDelayMs, - std::make_unique<base::Value>(0)); + GetPrefs()->Set(ash::prefs::kPowerAcScreenOffDelayMs, base::Value(0)); EXPECT_EQ(CreateSettingsChangedString(PowerHandler::IdleBehavior::DISPLAY_ON, false /* idle_controlled */, PowerPolicyController::ACTION_SUSPEND, @@ -216,9 +242,8 @@ TEST_F(PowerHandlerTest, SendIdleSettingForPrefChanges) { GetLastSettingsChangedMessage()); // Other idle actions should result in an "other" setting. - prefs_.SetUserPref(prefs::kPowerAcIdleAction, - std::make_unique<base::Value>( - PowerPolicyController::ACTION_STOP_SESSION)); + GetPrefs()->Set(ash::prefs::kPowerAcIdleAction, + base::Value(PowerPolicyController::ACTION_STOP_SESSION)); EXPECT_EQ(CreateSettingsChangedString( PowerHandler::IdleBehavior::OTHER, false /* idle_controlled */, PowerPolicyController::ACTION_SUSPEND, @@ -227,10 +252,9 @@ TEST_F(PowerHandlerTest, SendIdleSettingForPrefChanges) { } // Verifies that the lid-closed pref's value is sent directly to WebUI. -TEST_F(PowerHandlerTest, SendLidSettingForPrefChanges) { - prefs_.SetUserPref( - prefs::kPowerLidClosedAction, - std::make_unique<base::Value>(PowerPolicyController::ACTION_SHUT_DOWN)); +IN_PROC_BROWSER_TEST_F(PowerHandlerTest, SendLidSettingForPrefChanges) { + GetPrefs()->Set(ash::prefs::kPowerLidClosedAction, + base::Value(PowerPolicyController::ACTION_SHUT_DOWN)); EXPECT_EQ( CreateSettingsChangedString( PowerHandler::IdleBehavior::DISPLAY_OFF_SLEEP, @@ -238,9 +262,8 @@ TEST_F(PowerHandlerTest, SendLidSettingForPrefChanges) { false /* lid_closed_controlled */, true /* has_lid */), GetLastSettingsChangedMessage()); - prefs_.SetUserPref(prefs::kPowerLidClosedAction, - std::make_unique<base::Value>( - PowerPolicyController::ACTION_STOP_SESSION)); + GetPrefs()->Set(ash::prefs::kPowerLidClosedAction, + base::Value(PowerPolicyController::ACTION_STOP_SESSION)); EXPECT_EQ(CreateSettingsChangedString( PowerHandler::IdleBehavior::DISPLAY_OFF_SLEEP, false /* idle_controlled */, @@ -251,59 +274,59 @@ TEST_F(PowerHandlerTest, SendLidSettingForPrefChanges) { // Verifies that requests from WebUI to update the idle behavior update prefs // appropriately. -TEST_F(PowerHandlerTest, SetIdleBehavior) { +IN_PROC_BROWSER_TEST_F(PowerHandlerTest, SetIdleBehavior) { // Request the "Keep display on" setting and check that prefs are set // appropriately. test_api_->SetIdleBehavior(PowerHandler::IdleBehavior::DISPLAY_ON); EXPECT_EQ(PowerPolicyController::ACTION_DO_NOTHING, - GetIntPref(prefs::kPowerAcIdleAction)); - EXPECT_EQ(0, GetIntPref(prefs::kPowerAcScreenDimDelayMs)); - EXPECT_EQ(0, GetIntPref(prefs::kPowerAcScreenOffDelayMs)); - EXPECT_EQ(0, GetIntPref(prefs::kPowerAcScreenLockDelayMs)); + GetIntPref(ash::prefs::kPowerAcIdleAction)); + EXPECT_EQ(0, GetIntPref(ash::prefs::kPowerAcScreenDimDelayMs)); + EXPECT_EQ(0, GetIntPref(ash::prefs::kPowerAcScreenOffDelayMs)); + EXPECT_EQ(0, GetIntPref(ash::prefs::kPowerAcScreenLockDelayMs)); EXPECT_EQ(PowerPolicyController::ACTION_DO_NOTHING, - GetIntPref(prefs::kPowerBatteryIdleAction)); - EXPECT_EQ(0, GetIntPref(prefs::kPowerBatteryScreenDimDelayMs)); - EXPECT_EQ(0, GetIntPref(prefs::kPowerBatteryScreenOffDelayMs)); - EXPECT_EQ(0, GetIntPref(prefs::kPowerBatteryScreenLockDelayMs)); + GetIntPref(ash::prefs::kPowerBatteryIdleAction)); + EXPECT_EQ(0, GetIntPref(ash::prefs::kPowerBatteryScreenDimDelayMs)); + EXPECT_EQ(0, GetIntPref(ash::prefs::kPowerBatteryScreenOffDelayMs)); + EXPECT_EQ(0, GetIntPref(ash::prefs::kPowerBatteryScreenLockDelayMs)); // "Turn off display" should set the idle prefs but clear the screen // delays. test_api_->SetIdleBehavior(PowerHandler::IdleBehavior::DISPLAY_OFF); EXPECT_EQ(PowerPolicyController::ACTION_DO_NOTHING, - GetIntPref(prefs::kPowerAcIdleAction)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerAcScreenDimDelayMs)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerAcScreenOffDelayMs)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerAcScreenLockDelayMs)); + GetIntPref(ash::prefs::kPowerAcIdleAction)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerAcScreenDimDelayMs)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerAcScreenOffDelayMs)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerAcScreenLockDelayMs)); EXPECT_EQ(PowerPolicyController::ACTION_DO_NOTHING, - GetIntPref(prefs::kPowerBatteryIdleAction)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerBatteryScreenDimDelayMs)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerBatteryScreenOffDelayMs)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerBatteryScreenLockDelayMs)); + GetIntPref(ash::prefs::kPowerBatteryIdleAction)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerBatteryScreenDimDelayMs)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerBatteryScreenOffDelayMs)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerBatteryScreenLockDelayMs)); // Now switch to the "Keep display on" setting (to set the prefs again) and // check that the "Turn off display and sleep" setting clears all the prefs. test_api_->SetIdleBehavior(PowerHandler::IdleBehavior::DISPLAY_ON); test_api_->SetIdleBehavior(PowerHandler::IdleBehavior::DISPLAY_OFF_SLEEP); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerAcIdleAction)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerAcScreenDimDelayMs)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerAcScreenOffDelayMs)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerAcScreenLockDelayMs)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerBatteryIdleAction)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerBatteryScreenDimDelayMs)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerBatteryScreenOffDelayMs)); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerBatteryScreenLockDelayMs)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerAcIdleAction)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerAcScreenDimDelayMs)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerAcScreenOffDelayMs)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerAcScreenLockDelayMs)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerBatteryIdleAction)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerBatteryScreenDimDelayMs)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerBatteryScreenOffDelayMs)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerBatteryScreenLockDelayMs)); } // Verifies that requests from WebUI to change the lid behavior update the pref. -TEST_F(PowerHandlerTest, SetLidBehavior) { +IN_PROC_BROWSER_TEST_F(PowerHandlerTest, SetLidBehavior) { // The "do nothing" setting should update the pref. test_api_->SetLidClosedBehavior(PowerPolicyController::ACTION_DO_NOTHING); EXPECT_EQ(PowerPolicyController::ACTION_DO_NOTHING, - GetIntPref(prefs::kPowerLidClosedAction)); + GetIntPref(ash::prefs::kPowerLidClosedAction)); // Selecting the "suspend" setting should just clear the pref. test_api_->SetLidClosedBehavior(PowerPolicyController::ACTION_SUSPEND); - EXPECT_EQ(-1, GetIntPref(prefs::kPowerLidClosedAction)); + EXPECT_EQ(-1, GetIntPref(ash::prefs::kPowerLidClosedAction)); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc index 4ff2b1c8713..04fe8449120 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc @@ -84,20 +84,19 @@ void StorageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "updateStorageInfo", - base::Bind(&StorageHandler::HandleUpdateStorageInfo, - base::Unretained(this))); + base::BindRepeating(&StorageHandler::HandleUpdateStorageInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "openDownloads", - base::Bind(&StorageHandler::HandleOpenDownloads, - base::Unretained(this))); + "openDownloads", base::BindRepeating(&StorageHandler::HandleOpenDownloads, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "openArcStorage", - base::Bind(&StorageHandler::HandleOpenArcStorage, - base::Unretained(this))); + base::BindRepeating(&StorageHandler::HandleOpenArcStorage, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "clearDriveCache", - base::Bind(&StorageHandler::HandleClearDriveCache, - base::Unretained(this))); + base::BindRepeating(&StorageHandler::HandleClearDriveCache, + base::Unretained(this))); } void StorageHandler::HandleUpdateStorageInfo(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.cc index 61283919498..e2891671dcb 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.cc @@ -40,22 +40,25 @@ void StylusHandler::RegisterMessages() { // added. web_ui()->RegisterMessageCallback( "initializeStylusSettings", - base::Bind(&StylusHandler::HandleInitialize, base::Unretained(this))); + base::BindRepeating(&StylusHandler::HandleInitialize, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestNoteTakingApps", - base::Bind(&StylusHandler::HandleRequestApps, base::Unretained(this))); + base::BindRepeating(&StylusHandler::HandleRequestApps, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setPreferredNoteTakingApp", - base::Bind(&StylusHandler::HandleSetPreferredNoteTakingApp, - base::Unretained(this))); + base::BindRepeating(&StylusHandler::HandleSetPreferredNoteTakingApp, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setPreferredNoteTakingAppEnabledOnLockScreen", - base::Bind( + base::BindRepeating( &StylusHandler::HandleSetPreferredNoteTakingAppEnabledOnLockScreen, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "showPlayStoreApps", base::Bind(&StylusHandler::HandleShowPlayStoreApps, - base::Unretained(this))); + "showPlayStoreApps", + base::BindRepeating(&StylusHandler::HandleShowPlayStoreApps, + base::Unretained(this))); } void StylusHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.cc index d19dc511e04..2735420c270 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.cc @@ -10,10 +10,10 @@ #include "base/command_line.h" #include "base/macros.h" #include "base/values.h" +#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/easy_unlock_service.h" #include "chrome/common/pref_names.h" -#include "components/proximity_auth/switches.h" +#include "chromeos/components/proximity_auth/switches.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" @@ -50,24 +50,25 @@ EasyUnlockSettingsHandler* EasyUnlockSettingsHandler::Create( void EasyUnlockSettingsHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "easyUnlockGetEnabledStatus", - base::Bind(&EasyUnlockSettingsHandler::HandleGetEnabledStatus, - base::Unretained(this))); + base::BindRepeating(&EasyUnlockSettingsHandler::HandleGetEnabledStatus, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "easyUnlockStartTurnOnFlow", - base::Bind(&EasyUnlockSettingsHandler::HandleStartTurnOnFlow, - base::Unretained(this))); + base::BindRepeating(&EasyUnlockSettingsHandler::HandleStartTurnOnFlow, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "easyUnlockGetTurnOffFlowStatus", - base::Bind(&EasyUnlockSettingsHandler::HandleGetTurnOffFlowStatus, - base::Unretained(this))); + base::BindRepeating( + &EasyUnlockSettingsHandler::HandleGetTurnOffFlowStatus, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "easyUnlockStartTurnOffFlow", - base::Bind(&EasyUnlockSettingsHandler::HandleStartTurnOffFlow, - base::Unretained(this))); + base::BindRepeating(&EasyUnlockSettingsHandler::HandleStartTurnOffFlow, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "easyUnlockCancelTurnOffFlow", - base::Bind(&EasyUnlockSettingsHandler::HandleCancelTurnOffFlow, - base::Unretained(this))); + base::BindRepeating(&EasyUnlockSettingsHandler::HandleCancelTurnOffFlow, + base::Unretained(this))); } void EasyUnlockSettingsHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.h index 3fb3706c524..e4509d75036 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.h @@ -6,7 +6,7 @@ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_EASY_UNLOCK_SETTINGS_HANDLER_H_ #include "base/macros.h" -#include "chrome/browser/signin/easy_unlock_service_observer.h" +#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_observer.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "components/prefs/pref_change_registrar.h" diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc index 862267270ce..ea6babfcfad 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc @@ -6,8 +6,8 @@ #include <memory> -#include "chrome/browser/signin/easy_unlock_service.h" -#include "chrome/browser/signin/easy_unlock_service_factory.h" +#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service.h" +#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_factory.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/test/test_browser_thread_bundle.h" @@ -56,10 +56,6 @@ class FakeEasyUnlockService : public EasyUnlockService { Type GetType() const override { return TYPE_REGULAR; } AccountId GetAccountId() const override { return EmptyAccountId(); } void LaunchSetup() override {} - const base::DictionaryValue* GetPermitAccess() const override { - return nullptr; - } - void SetPermitAccess(const base::DictionaryValue& permit) override {} void ClearPermitAccess() override {} const base::ListValue* GetRemoteDevices() const override { return nullptr; } @@ -71,8 +67,6 @@ class FakeEasyUnlockService : public EasyUnlockService { void RecordEasySignInOutcome(const AccountId& account_id, bool success) const override {} void RecordPasswordLoginEvent(const AccountId& account_id) const override {} - void StartAutoPairing(const AutoPairingResultCallback& callback) override {} - void SetAutoPairingResult(bool success, const std::string& error) override {} void InitializeInternal() override {} void ShutdownInternal() override {} diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc index a97d004c949..bd4ef59c956 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc @@ -72,40 +72,39 @@ void FingerprintHandler::RegisterMessages() { // Note: getFingerprintsList must be called before observers will be added. web_ui()->RegisterMessageCallback( "getFingerprintsList", - base::Bind(&FingerprintHandler::HandleGetFingerprintsList, - base::Unretained(this))); + base::BindRepeating(&FingerprintHandler::HandleGetFingerprintsList, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getNumFingerprints", - base::Bind(&FingerprintHandler::HandleGetNumFingerprints, - base::Unretained(this))); + base::BindRepeating(&FingerprintHandler::HandleGetNumFingerprints, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "startEnroll", - base::Bind(&FingerprintHandler::HandleStartEnroll, - base::Unretained(this))); + "startEnroll", base::BindRepeating(&FingerprintHandler::HandleStartEnroll, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "cancelCurrentEnroll", - base::Bind(&FingerprintHandler::HandleCancelCurrentEnroll, - base::Unretained(this))); + base::BindRepeating(&FingerprintHandler::HandleCancelCurrentEnroll, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getEnrollmentLabel", - base::Bind(&FingerprintHandler::HandleGetEnrollmentLabel, - base::Unretained(this))); + base::BindRepeating(&FingerprintHandler::HandleGetEnrollmentLabel, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "removeEnrollment", - base::Bind(&FingerprintHandler::HandleRemoveEnrollment, - base::Unretained(this))); + base::BindRepeating(&FingerprintHandler::HandleRemoveEnrollment, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "changeEnrollmentLabel", - base::Bind(&FingerprintHandler::HandleChangeEnrollmentLabel, - base::Unretained(this))); + base::BindRepeating(&FingerprintHandler::HandleChangeEnrollmentLabel, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "startAuthentication", - base::Bind(&FingerprintHandler::HandleStartAuthentication, - base::Unretained(this))); + base::BindRepeating(&FingerprintHandler::HandleStartAuthentication, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "endCurrentAuthentication", - base::Bind(&FingerprintHandler::HandleEndCurrentAuthentication, - base::Unretained(this))); + base::BindRepeating(&FingerprintHandler::HandleEndCurrentAuthentication, + base::Unretained(this))); } void FingerprintHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc index a6ddb49d02e..f9263067b4a 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc @@ -27,21 +27,23 @@ void GoogleAssistantHandler::OnJavascriptDisallowed() {} void GoogleAssistantHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "setGoogleAssistantEnabled", - base::Bind(&GoogleAssistantHandler::HandleSetGoogleAssistantEnabled, - base::Unretained(this))); + base::BindRepeating( + &GoogleAssistantHandler::HandleSetGoogleAssistantEnabled, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setGoogleAssistantContextEnabled", - base::Bind( + base::BindRepeating( &GoogleAssistantHandler::HandleSetGoogleAssistantContextEnabled, base::Unretained(this))); web_ui()->RegisterMessageCallback( "showGoogleAssistantSettings", - base::Bind(&GoogleAssistantHandler::HandleShowGoogleAssistantSettings, - base::Unretained(this))); + base::BindRepeating( + &GoogleAssistantHandler::HandleShowGoogleAssistantSettings, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "turnOnGoogleAssistant", - base::Bind(&GoogleAssistantHandler::HandleTurnOnGoogleAssistant, - base::Unretained(this))); + base::BindRepeating(&GoogleAssistantHandler::HandleTurnOnGoogleAssistant, + base::Unretained(this))); } void GoogleAssistantHandler::HandleSetGoogleAssistantEnabled( diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc index 38e54c5a8e3..8367559e562 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc @@ -96,18 +96,19 @@ void InternetHandler::RegisterMessages() { // TODO(stevenjb): Eliminate once network configuration UI is integrated // into settings. web_ui()->RegisterMessageCallback( - kAddNetworkMessage, - base::Bind(&InternetHandler::AddNetwork, base::Unretained(this))); + kAddNetworkMessage, base::BindRepeating(&InternetHandler::AddNetwork, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kConfigureNetworkMessage, - base::Bind(&InternetHandler::ConfigureNetwork, base::Unretained(this))); + base::BindRepeating(&InternetHandler::ConfigureNetwork, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kRequestArcVpnProviders, - base::Bind(&InternetHandler::RequestArcVpnProviders, - base::Unretained(this))); + base::BindRepeating(&InternetHandler::RequestArcVpnProviders, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kRequestGmsCoreNotificationsDisabledDeviceNames, - base::Bind( + base::BindRepeating( &InternetHandler::RequestGmsCoreNotificationsDisabledDeviceNames, base::Unretained(this))); } diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.cc new file mode 100644 index 00000000000..5c6c73a6477 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.cc @@ -0,0 +1,52 @@ +// 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/webui/settings/chromeos/smb_handler.h" + +#include <string> +#include <utility> + +#include "base/bind.h" +#include "base/values.h" +#include "chrome/browser/chromeos/file_system_provider/provided_file_system_info.h" +#include "chrome/browser/chromeos/smb_client/smb_service.h" +#include "chrome/browser/profiles/profile.h" + +namespace { +void DoNothingCallback(base::File::Error error) { + return; +} +} // namespace + +namespace chromeos { +namespace settings { + +SmbHandler::SmbHandler(Profile* profile) : profile_(profile) {} + +SmbHandler::~SmbHandler() = default; + +void SmbHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "smbMount", + base::BindRepeating(&SmbHandler::HandleSmbMount, base::Unretained(this))); +} + +void SmbHandler::HandleSmbMount(const base::ListValue* args) { + CHECK_EQ(1U, args->GetSize()); + std::string mountUrl; + CHECK(args->GetString(0, &mountUrl)); + + chromeos::smb_client::SmbService* const service = + chromeos::smb_client::SmbService::Get(profile_); + + chromeos::file_system_provider::MountOptions mo; + mo.display_name = mountUrl; + mo.writable = true; + + service->Mount(mo, base::FilePath(mountUrl), + base::BindOnce(&DoNothingCallback)); +} + +} // namespace settings +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.h new file mode 100644 index 00000000000..fc7e14637c4 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.h @@ -0,0 +1,37 @@ +// 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_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" + +class Profile; + +namespace chromeos { +namespace settings { + +class SmbHandler : public ::settings::SettingsPageUIHandler { + public: + explicit SmbHandler(Profile* profile); + ~SmbHandler() override; + + void RegisterMessages() override; + void OnJavascriptAllowed() override {} + void OnJavascriptDisallowed() override {} + + private: + // WebUI call to mount an Smb Filesystem. + void HandleSmbMount(const base::ListValue* args); + + Profile* const profile_; + + DISALLOW_COPY_AND_ASSIGN(SmbHandler); +}; + +} // namespace settings +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/downloads_handler.cc b/chromium/chrome/browser/ui/webui/settings/downloads_handler.cc index b5ab983a438..4e45994d152 100644 --- a/chromium/chrome/browser/ui/webui/settings/downloads_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/downloads_handler.cc @@ -34,15 +34,16 @@ DownloadsHandler::~DownloadsHandler() { void DownloadsHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "initializeDownloads", - base::Bind(&DownloadsHandler::HandleInitialize, base::Unretained(this))); + base::BindRepeating(&DownloadsHandler::HandleInitialize, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "resetAutoOpenFileTypes", - base::Bind(&DownloadsHandler::HandleResetAutoOpenFileTypes, - base::Unretained(this))); + base::BindRepeating(&DownloadsHandler::HandleResetAutoOpenFileTypes, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "selectDownloadLocation", - base::Bind(&DownloadsHandler::HandleSelectDownloadLocation, - base::Unretained(this))); + base::BindRepeating(&DownloadsHandler::HandleSelectDownloadLocation, + base::Unretained(this))); } void DownloadsHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc b/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc index a7c9d72622c..7f5a1b27042 100644 --- a/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc @@ -19,9 +19,10 @@ ExtensionControlHandler::ExtensionControlHandler() {} ExtensionControlHandler::~ExtensionControlHandler() {} void ExtensionControlHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("disableExtension", - base::Bind(&ExtensionControlHandler::HandleDisableExtension, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "disableExtension", + base::BindRepeating(&ExtensionControlHandler::HandleDisableExtension, + base::Unretained(this))); } void ExtensionControlHandler::HandleDisableExtension( diff --git a/chromium/chrome/browser/ui/webui/settings/font_handler.cc b/chromium/chrome/browser/ui/webui/settings/font_handler.cc index abd118e6a53..037d0a5b3a4 100644 --- a/chromium/chrome/browser/ui/webui/settings/font_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/font_handler.cc @@ -51,16 +51,17 @@ FontHandler::~FontHandler() {} void FontHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "fetchFontsData", base::Bind(&FontHandler::HandleFetchFontsData, - base::Unretained(this))); + "fetchFontsData", base::BindRepeating(&FontHandler::HandleFetchFontsData, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "observeAdvancedFontExtensionAvailable", - base::Bind(&FontHandler::HandleObserveAdvancedFontExtensionAvailable, - base::Unretained(this))); + base::BindRepeating( + &FontHandler::HandleObserveAdvancedFontExtensionAvailable, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "openAdvancedFontSettings", - base::Bind(&FontHandler::HandleOpenAdvancedFontSettings, - base::Unretained(this))); + base::BindRepeating(&FontHandler::HandleOpenAdvancedFontSettings, + base::Unretained(this))); } void FontHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/incompatible_applications_handler_win.cc b/chromium/chrome/browser/ui/webui/settings/incompatible_applications_handler_win.cc index af1646f42db..4772084b860 100644 --- a/chromium/chrome/browser/ui/webui/settings/incompatible_applications_handler_win.cc +++ b/chromium/chrome/browser/ui/webui/settings/incompatible_applications_handler_win.cc @@ -148,7 +148,7 @@ void IncompatibleApplicationsHandler::GetPluralString( const base::Value& callback_id = args->GetList()[0]; int num_applications = args->GetList()[1].GetInt(); - DCHECK_GT(0, num_applications); + DCHECK_GT(num_applications, 0); ResolveJavascriptCallback( callback_id, diff --git a/chromium/chrome/browser/ui/webui/settings/languages_handler.cc b/chromium/chrome/browser/ui/webui/settings/languages_handler.cc index 2f98827ad2d..b36e7442a2d 100644 --- a/chromium/chrome/browser/ui/webui/settings/languages_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/languages_handler.cc @@ -31,12 +31,12 @@ LanguagesHandler::~LanguagesHandler() { void LanguagesHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getProspectiveUILanguage", - base::Bind(&LanguagesHandler::HandleGetProspectiveUILanguage, - base::Unretained(this))); + base::BindRepeating(&LanguagesHandler::HandleGetProspectiveUILanguage, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setProspectiveUILanguage", - base::Bind(&LanguagesHandler::HandleSetProspectiveUILanguage, - base::Unretained(this))); + base::BindRepeating(&LanguagesHandler::HandleSetProspectiveUILanguage, + base::Unretained(this))); } void LanguagesHandler::HandleGetProspectiveUILanguage( diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index 1c76ec475ac..1d14df0f557 100644 --- a/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc @@ -29,10 +29,11 @@ #include "components/google/core/browser/google_util.h" #include "components/password_manager/core/browser/password_manager_constants.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" -#include "components/signin/core/browser/signin_features.h" +#include "components/signin/core/browser/signin_buildflags.h" #include "components/strings/grit/components_strings.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h" #include "content/public/browser/web_ui_data_source.h" +#include "content/public/common/content_features.h" #include "services/device/public/cpp/device_features.h" #include "ui/base/l10n/l10n_util.h" @@ -128,6 +129,7 @@ void AddCommonStrings(content::WebUIDataSource* html_source, Profile* profile) { {"moreActions", IDS_SETTINGS_MORE_ACTIONS}, {"ok", IDS_OK}, {"restart", IDS_SETTINGS_RESTART}, + {"retry", IDS_SETTINGS_RETRY}, {"save", IDS_SAVE}, {"settings", IDS_SETTINGS_SETTINGS}, {"toggleOn", IDS_SETTINGS_TOGGLE_ON}, @@ -151,18 +153,6 @@ void AddCommonStrings(content::WebUIDataSource* html_source, Profile* profile) { } void AddA11yStrings(content::WebUIDataSource* html_source) { -#if defined(OS_CHROMEOS) - // The content description for select to speak is dependent on a flag - // until a feature launch. - // TODO(katie): When the feature is approved, remove this variable and - // callback. The feature will be always enabled. - int selectToSpeakDescription = - (base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kEnableExperimentalAccessibilityFeatures)) - ? IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_DESCRIPTION_FLAGS - : IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_DESCRIPTION; -#endif - LocalizedString localized_strings[] = { {"a11yPageTitle", IDS_SETTINGS_ACCESSIBILITY}, {"a11yWebStore", IDS_SETTINGS_ACCESSIBILITY_WEB_STORE}, @@ -214,7 +204,8 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { {"focusHighlightLabel", IDS_SETTINGS_ACCESSIBILITY_FOCUS_HIGHLIGHT_DESCRIPTION}, {"selectToSpeakTitle", IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_TITLE}, - {"selectToSpeakDescription", selectToSpeakDescription}, + {"selectToSpeakDescription", + IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_DESCRIPTION}, {"selectToSpeakOptionsLabel", IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_OPTIONS_LABEL}, {"switchAccessLabel", IDS_SETTINGS_ACCESSIBILITY_SWITCH_ACCESS_DESCRIPTION}, @@ -244,15 +235,33 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { {"audioHeading", IDS_SETTINGS_ACCESSIBILITY_AUDIO_HEADING}, {"additionalFeaturesTitle", IDS_SETTINGS_ACCESSIBILITY_ADDITIONAL_FEATURES_TITLE}, + {"manageTtsSettings", IDS_SETTINGS_MANAGE_TTS_SETTINGS}, + {"ttsSettingsLinkDescription", IDS_SETTINGS_TTS_LINK_DESCRIPTION}, + {"textToSpeechVoices", IDS_SETTINGS_TEXT_TO_SPEECH_VOICES}, + {"textToSpeechProperties", IDS_SETTINGS_TEXT_TO_SPEECH_PROPERTIES}, + {"textToSpeechRate", IDS_SETTINGS_TEXT_TO_SPEECH_RATE}, + {"textToSpeechPitch", IDS_SETTINGS_TEXT_TO_SPEECH_PITCH}, + {"textToSpeechPreviewHeading", IDS_SETTINGS_TEXT_TO_SPEECH_PREVIEW_HEADING}, + {"textToSpeechPreviewInputLabel", + IDS_SETTINGS_TEXT_TO_SPEECH_PREVIEW_INPUT_LABEL}, + {"textToSpeechPreviewInput", IDS_SETTINGS_TEXT_TO_SPEECH_PREVIEW_INPUT}, + {"textToSpeechPreviewPlay", IDS_SETTINGS_TEXT_TO_SPEECH_PREVIEW_PLAY}, + {"textToSpeechEngines", IDS_SETTINGS_TEXT_TO_SPEECH_ENGINES}, + {"textToSpeechInstallEngines", IDS_SETTINGS_TEXT_TO_SPEECH_INSTALL_ENGINES}, + {"manageGoogleTtsEngineSettings", + IDS_SETTINGS_MANAGE_GOOGLE_TTS_ENGINE_SETTINGS}, + {"googleTtsEngineSettingsLinkDescription", + IDS_SETTINGS_GOOGLE_TTS_ENGINE_LINK_DESCRIPTION}, + {"googleTextToSpeechSettings", IDS_SETTINGS_GOOGLE_TTS_ENGINE_TITLE}, + {"enableTtsVoiceLabel", IDS_SETTINGS_ENABLE_TTS_VOICE_LABEL}, #endif }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); #if defined(OS_CHROMEOS) - html_source->AddString( - "a11yLearnMoreUrl", - GetHelpUrlWithBoard(chrome::kChromeAccessibilityHelpURL)); + html_source->AddString("a11yLearnMoreUrl", + chrome::kChromeAccessibilityHelpURL); html_source->AddBoolean( "showExperimentalA11yFeatures", @@ -466,7 +475,7 @@ void AddChangePasswordStrings(content::WebUIDataSource* html_source) { arraysize(localized_strings)); const std::string icon_id = - show_softer_warning ? "settings:security" : "cr:warning"; + show_softer_warning ? "cr:security" : "cr:warning"; html_source->AddString("changePasswordPageIcon", icon_id); #endif } @@ -672,7 +681,13 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { {"displayResolutionTextBest", IDS_SETTINGS_DISPLAY_RESOLUTION_TEXT_BEST}, {"displayResolutionTextNative", IDS_SETTINGS_DISPLAY_RESOLUTION_TEXT_NATIVE}, + {"displayResolutionSublabel", IDS_SETTINGS_DISPLAY_RESOLUTION_SUBLABEL}, + {"displayResolutionMenuItem", IDS_SETTINGS_DISPLAY_RESOLUTION_MENU_ITEM}, + {"displayZoomTitle", IDS_SETTINGS_DISPLAY_ZOOM_TITLE}, + {"displayZoomSublabel", IDS_SETTINGS_DISPLAY_ZOOM_SUBLABEL}, {"displayZoomValue", IDS_SETTINGS_DISPLAY_ZOOM_VALUE}, + {"displaySizeSliderMinLabel", IDS_SETTINGS_DISPLAY_ZOOM_SLIDER_MINIMUM}, + {"displaySizeSliderMaxLabel", IDS_SETTINGS_DISPLAY_ZOOM_SLIDER_MAXIMUM}, {"displayScreenTitle", IDS_SETTINGS_DISPLAY_SCREEN}, {"displayScreenExtended", IDS_SETTINGS_DISPLAY_SCREEN_EXTENDED}, {"displayScreenPrimary", IDS_SETTINGS_DISPLAY_SCREEN_PRIMARY}, @@ -705,8 +720,7 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { chromeos::switches::kEnableTouchCalibrationSetting)); html_source->AddBoolean("enableDisplayZoomSetting", - base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kEnableDisplayZoomSetting)); + features::IsDisplayZoomSettingEnabled()); html_source->AddBoolean("hasExternalTouchDevice", display::HasExternalTouchscreenDevice()); @@ -772,15 +786,27 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { void AddDownloadsStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { - {"downloadsPageTitle", IDS_SETTINGS_DOWNLOADS}, - {"downloadLocation", IDS_SETTINGS_DOWNLOAD_LOCATION}, - {"changeDownloadLocation", IDS_SETTINGS_CHANGE_DOWNLOAD_LOCATION}, - {"promptForDownload", IDS_SETTINGS_PROMPT_FOR_DOWNLOAD}, - {"disconnectGoogleDriveAccount", IDS_SETTINGS_DISCONNECT_GOOGLE_DRIVE}, - {"openFileTypesAutomatically", - IDS_SETTINGS_OPEN_FILE_TYPES_AUTOMATICALLY}}; + {"downloadsPageTitle", IDS_SETTINGS_DOWNLOADS}, + {"downloadLocation", IDS_SETTINGS_DOWNLOAD_LOCATION}, + {"changeDownloadLocation", IDS_SETTINGS_CHANGE_DOWNLOAD_LOCATION}, + {"promptForDownload", IDS_SETTINGS_PROMPT_FOR_DOWNLOAD}, + {"disconnectGoogleDriveAccount", IDS_SETTINGS_DISCONNECT_GOOGLE_DRIVE}, + {"openFileTypesAutomatically", IDS_SETTINGS_OPEN_FILE_TYPES_AUTOMATICALLY}, +#if defined(OS_CHROMEOS) + {"smbSharesTitle", IDS_SETTINGS_DOWNLOADS_SMB_SHARES}, + {"smbSharesLearnMoreLabel", + IDS_SETTINGS_DOWNLOADS_SMB_SHARES_LEARN_MORE_LABEL}, + {"addSmbShare", IDS_SETTINGS_DOWNLOADS_SMB_SHARES_ADD_SHARE}, + {"smbShareUrl", IDS_SETTINGS_DOWNLOADS_ADD_SHARE_URL}, +#endif + }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); + +#if defined(OS_CHROMEOS) + html_source->AddBoolean("enableNativeSmbSetting", + base::FeatureList::IsEnabled(features::kNativeSmb)); +#endif } #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) @@ -805,7 +831,11 @@ void AddChromeCleanupStrings(content::WebUIDataSource* html_source) { {"chromeCleanupExplanationPermissionsNeeded", IDS_SETTINGS_RESET_CLEANUP_EXPLANATION_PERMISSIONS_NEEDED}, {"chromeCleanupExplanationRemove", - IDS_SETTINGS_RESET_CLEANUP_EXPLANATION_REMOVE}, + // Note: removal explanation should be the same as used in the prompt + // dialog. Reusing the string to ensure they will not diverge. + IDS_CHROME_CLEANUP_PROMPT_EXPLANATION}, + {"chromeCleanupExplanationRemoving", + IDS_SETTINGS_RESET_CLEANUP_EXPLANATION_CURRENTLY_REMOVING}, {"chromeCleanupExplanationScanError", IDS_SETTINGS_RESET_CLEANUP_EXPLANATION_SCAN_ERROR}, {"chromeCleanupFindButtonLable", @@ -905,14 +935,12 @@ void AddResetStrings(content::WebUIDataSource* html_source) { #else {"resetPageTitle", IDS_SETTINGS_RESET}, #endif - {"resetTrigger", IDS_SETTINGS_RESET}, - {"resetTriggerDescription", - IDS_SETTINGS_RESET_PROFILE_SETTINGS_DESCRIPTION}, + {"resetTrigger", IDS_SETTINGS_RESET_SETTINGS_TRIGGER}, {"resetPageExplanation", IDS_RESET_PROFILE_SETTINGS_EXPLANATION}, {"triggeredResetPageExplanation", IDS_TRIGGERED_RESET_PROFILE_SETTINGS_EXPLANATION}, {"triggeredResetPageTitle", IDS_TRIGGERED_RESET_PROFILE_SETTINGS_TITLE}, - {"resetPageCommit", IDS_RESET_PROFILE_SETTINGS_COMMIT_BUTTON}, + {"resetDialogCommit", IDS_SETTINGS_RESET}, {"resetPageFeedback", IDS_SETTINGS_RESET_PROFILE_FEEDBACK}, #if defined(OS_CHROMEOS) {"powerwashTitle", IDS_SETTINGS_FACTORY_RESET}, @@ -1015,7 +1043,6 @@ void AddEasyUnlockStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_EASY_UNLOCK_TURN_OFF_ERROR_TITLE}, {"easyUnlockTurnOffErrorMessage", IDS_SETTINGS_EASY_UNLOCK_TURN_OFF_ERROR_MESSAGE}, - {"easyUnlockTurnOffRetryButton", IDS_SETTINGS_EASY_UNLOCK_TURN_OFF_RETRY}, {"easyUnlockAllowSignInLabel", IDS_SETTINGS_EASY_UNLOCK_ALLOW_SIGN_IN_LABEL}, {"easyUnlockProximityThresholdLabel", @@ -1244,6 +1271,10 @@ void AddLanguagesStrings(content::WebUIDataSource* html_source) { {"noCustomDictionaryWordsFound", IDS_SETTINGS_LANGUAGES_DICTIONARY_WORDS_NONE}, {"spellCheckDisabled", IDS_SETTINGS_LANGUAGES_SPELL_CHECK_DISABLED}, + {"languagesDictionaryDownloadError", + IDS_SETTINGS_LANGUAGES_DICTIONARY_DOWNLOAD_FAILED}, + {"languagesDictionaryDownloadErrorHelp", + IDS_SETTINGS_LANGUAGES_DICTIONARY_DOWNLOAD_FAILED_HELP}, #endif }; AddLocalizedStringsBulk(html_source, localized_strings, @@ -1361,6 +1392,9 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) { {"exportMenuItem", IDS_SETTINGS_PASSWORDS_EXPORT_MENU_ITEM}, {"undoRemovePassword", IDS_SETTINGS_PASSWORD_UNDO}, {"passwordDeleted", IDS_SETTINGS_PASSWORD_DELETED_PASSWORD}, + {"passwordRowMoreActionsButton", IDS_SETTINGS_PASSWORD_ROW_MORE_ACTIONS}, + {"passwordRowFederatedMoreActionsButton", + IDS_SETTINGS_PASSWORD_ROW_FEDERATED_MORE_ACTIONS}, {"exportPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORT_TITLE}, {"exportPasswordsDescription", IDS_SETTINGS_PASSWORDS_EXPORT_DESCRIPTION}, {"exportPasswords", IDS_SETTINGS_PASSWORDS_EXPORT}, @@ -1452,7 +1486,7 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_SETTINGS_PEOPLE_LOCK_SCREEN_FINGERPRINT_SUBPAGE_TITLE}, {"lockScreenFingerprintWarning", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_FINGERPRINT_LESS_SECURE}, - {"lockScreenOptions", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_OPTIONS}, + {"lockScreenOptions", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_OPTIONS_LOCK}, {"lockScreenPasswordOnly", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_PASSWORD_ONLY}, {"lockScreenPinOrPassword", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_PIN_OR_PASSWORD}, @@ -1460,9 +1494,9 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_SETTINGS_PEOPLE_LOCK_SCREEN_REGISTERED_FINGERPRINTS_LABEL}, {"lockScreenSetupPinButton", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_SETUP_PIN_BUTTON}, - {"lockScreenTitle", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_TITLE}, + {"lockScreenTitle", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_TITLE_LOCK}, {"passwordPromptEnterPassword", - IDS_SETTINGS_PEOPLE_PASSWORD_PROMPT_ENTER_PASSWORD}, + IDS_SETTINGS_PEOPLE_PASSWORD_PROMPT_ENTER_PASSWORD_LOCK}, {"passwordPromptInvalidPassword", IDS_SETTINGS_PEOPLE_PASSWORD_PROMPT_INVALID_PASSWORD}, {"passwordPromptPasswordLabel", @@ -1494,6 +1528,9 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"editPerson", IDS_SETTINGS_EDIT_PERSON}, {"profileNameAndPicture", IDS_SETTINGS_PROFILE_NAME_AND_PICTURE}, {"showShortcutLabel", IDS_SETTINGS_PROFILE_SHORTCUT_TOGGLE_LABEL}, + {"syncWillStart", IDS_SETTINGS_SYNC_WILL_START}, + {"syncSettingsSavedToast", IDS_SETTINGS_SYNC_SETTINGS_SAVED_TOAST_LABEL}, + {"cancelSync", IDS_SETTINGS_SYNC_SETTINGS_CANCEL_SYNC}, #endif // defined(OS_CHROMEOS) #if BUILDFLAG(ENABLE_DICE_SUPPORT) {"peopleSignIn", IDS_SETTINGS_PEOPLE_SIGN_IN}, @@ -1502,8 +1539,12 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_SETTINGS_PEOPLE_SIGN_IN_PROMPT_SECONDARY}, {"useAnotherAccount", IDS_SETTINGS_PEOPLE_SYNC_ANOTHER_ACCOUNT}, {"syncAsName", IDS_SETTINGS_PEOPLE_SYNC_AS_NAME}, - {"syncedToName", IDS_SETTINGS_PEOPLE_SYNCED_AS_NAME}, + {"syncingTo", IDS_SETTINGS_PEOPLE_SYNCING_TO_ACCOUNT}, {"turnOffSync", IDS_SETTINGS_PEOPLE_SYNC_TURN_OFF}, + {"syncNotWorking", IDS_SETTINGS_PEOPLE_SYNC_NOT_WORKING}, + {"syncPaused", IDS_SETTINGS_PEOPLE_SYNC_PAUSED}, + {"syncSignInPrompt", IDS_SETTINGS_SYNC_SIGN_IN_PROMPT}, + {"syncSignInPromptSecondary", IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_SECONDARY}, #endif {"syncOverview", IDS_SETTINGS_SYNC_OVERVIEW}, {"syncDisabledByAdministrator", @@ -1524,6 +1565,9 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"syncDisconnectExplanation", IDS_SETTINGS_SYNC_DISCONNECT_EXPLANATION}, {"syncDisconnectConfirm", IDS_SETTINGS_SYNC_DISCONNECT_CONFIRM}, {"sync", IDS_SETTINGS_SYNC}, + {"syncDescription", IDS_SETTINGS_SYNC_DESCRIPTION}, + {"syncExpandA11yLabel", IDS_SETTINGS_SYNC_SECTION_ACCESSIBILITY_LABEL}, + {"syncAndPersonalization", IDS_SETTINGS_SYNC_SYNC_AND_PERSONALIZATION}, {"syncPageTitle", IDS_SETTINGS_SYNC_PAGE_TITLE}, {"syncLoading", IDS_SETTINGS_SYNC_LOADING}, {"syncTimeout", IDS_SETTINGS_SYNC_TIMEOUT}, @@ -2041,6 +2085,11 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, {"siteSettingsMidiDevicesBlock", IDS_SETTINGS_SITE_SETTINGS_MIDI_DEVICES_BLOCK}, {"siteSettingsUsbDevices", IDS_SETTINGS_SITE_SETTINGS_USB_DEVICES}, + {"siteSettingsUsbDevicesAsk", IDS_SETTINGS_SITE_SETTINGS_USB_DEVICES_ASK}, + {"siteSettingsUsbDevicesAskRecommended", + IDS_SETTINGS_SITE_SETTINGS_USB_DEVICES_ASK_RECOMMENDED}, + {"siteSettingsUsbDevicesBlock", + IDS_SETTINGS_SITE_SETTINGS_USB_DEVICES_BLOCK}, {"siteSettingsRemoveZoomLevel", IDS_SETTINGS_SITE_SETTINGS_REMOVE_ZOOM_LEVEL}, {"siteSettingsZoomLevels", IDS_SETTINGS_SITE_SETTINGS_ZOOM_LEVELS}, @@ -2179,6 +2228,13 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, {"siteSettingsAdsBlock", IDS_SETTINGS_SITE_SETTINGS_ADS_BLOCK}, {"siteSettingsAdsBlockRecommended", IDS_SETTINGS_SITE_SETTINGS_ADS_BLOCK_RECOMMENDED}, + {"siteSettingsPaymentHandler", IDS_SETTINGS_SITE_SETTINGS_PAYMENT_HANDLER}, + {"siteSettingsPaymentHandlerAllow", + IDS_SETTINGS_SITE_SETTINGS_PAYMENT_HANDLER_ALLOW}, + {"siteSettingsPaymentHandlerAllowRecommended", + IDS_SETTINGS_SITE_SETTINGS_PAYMENT_HANDLER_ALLOW_RECOMMENDED}, + {"siteSettingsPaymentHandlerBlock", + IDS_SETTINGS_SITE_SETTINGS_PAYMENT_HANDLER_BLOCK}, }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); @@ -2203,6 +2259,10 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, "enableSensorsContentSetting", base::FeatureList::IsEnabled(features::kGenericSensorExtraClasses)); + html_source->AddBoolean( + "enablePaymentHandlerContentSetting", + base::FeatureList::IsEnabled(features::kServiceWorkerPaymentApps)); + if (PluginUtils::ShouldPreferHtmlOverPlugins( HostContentSettingsMapFactory::GetForProfile(profile))) { LocalizedString flash_strings[] = { @@ -2307,6 +2367,11 @@ void AddMultideviceStrings(content::WebUIDataSource* html_source) { } #endif +void AddExtensionsStrings(content::WebUIDataSource* html_source) { + html_source->AddLocalizedString("extensionsPageTitle", + IDS_SETTINGS_EXTENSIONS_CHECKBOX_LABEL); +} + } // namespace void AddLocalizedStrings(content::WebUIDataSource* html_source, @@ -2355,6 +2420,7 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, AddImportDataStrings(html_source); AddSystemStrings(html_source); #endif + AddExtensionsStrings(html_source); #if defined(USE_NSS_CERTS) certificate_manager::AddLocalizedStrings(html_source); diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc index c3d1a1d2812..f8e4ae44148 100644 --- a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc +++ b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc @@ -14,6 +14,7 @@ #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/signin/unified_consent_helper.h" #include "chrome/browser/ui/webui/metrics_handler.h" #include "chrome/browser/ui/webui/settings/about_handler.h" #include "chrome/browser/ui/webui/settings/appearance_handler.h" @@ -47,7 +48,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" -#include "printing/features/features.h" +#include "printing/buildflags/buildflags.h" #if defined(OS_WIN) #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_win.h" @@ -63,6 +64,7 @@ #if defined(OS_WIN) || defined(OS_CHROMEOS) #include "chrome/browser/ui/webui/settings/languages_handler.h" +#include "chrome/browser/ui/webui/settings/tts_handler.h" #endif // defined(OS_WIN) || defined(OS_CHROMEOS) #if defined(OS_CHROMEOS) @@ -84,6 +86,7 @@ #include "chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/internet_handler.h" +#include "chrome/browser/ui/webui/settings/chromeos/smb_handler.h" #include "chrome/common/chrome_switches.h" #include "chromeos/chromeos_switches.h" #include "components/arc/arc_util.h" @@ -185,11 +188,14 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) AddSettingsPageUIHandler( std::make_unique<chromeos::settings::PointerHandler>()); AddSettingsPageUIHandler( + std::make_unique<chromeos::settings::SmbHandler>(profile)); + AddSettingsPageUIHandler( std::make_unique<chromeos::settings::StorageHandler>()); AddSettingsPageUIHandler( std::make_unique<chromeos::settings::StylusHandler>()); AddSettingsPageUIHandler( std::make_unique<chromeos::settings::InternetHandler>(profile)); + AddSettingsPageUIHandler(std::make_unique<TtsHandler>()); #else AddSettingsPageUIHandler(std::make_unique<DefaultBrowserHandler>(web_ui)); AddSettingsPageUIHandler(std::make_unique<ManageProfileHandler>(profile)); @@ -302,6 +308,9 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) signin::IsDiceEnabledForProfile(profile->GetPrefs())); #endif // defined(OS_CHROMEOS) + html_source->AddBoolean("unifiedConsentEnabled", + IsUnifiedConsentEnabled(profile)); + html_source->AddBoolean("showExportPasswords", base::FeatureList::IsEnabled( password_manager::features::kPasswordExport)); diff --git a/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler.cc b/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler.cc index def21ea78e0..7d8fb6922a8 100644 --- a/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler.cc @@ -23,12 +23,15 @@ MetricsReportingHandler::MetricsReportingHandler() {} MetricsReportingHandler::~MetricsReportingHandler() {} void MetricsReportingHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("getMetricsReporting", - base::Bind(&MetricsReportingHandler::HandleGetMetricsReporting, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("setMetricsReportingEnabled", - base::Bind(&MetricsReportingHandler::HandleSetMetricsReportingEnabled, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getMetricsReporting", + base::BindRepeating(&MetricsReportingHandler::HandleGetMetricsReporting, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "setMetricsReportingEnabled", + base::BindRepeating( + &MetricsReportingHandler::HandleSetMetricsReportingEnabled, + base::Unretained(this))); } void MetricsReportingHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/native_certificates_handler.cc b/chromium/chrome/browser/ui/webui/settings/native_certificates_handler.cc index 4661e32a12a..63776d6187a 100644 --- a/chromium/chrome/browser/ui/webui/settings/native_certificates_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/native_certificates_handler.cc @@ -19,8 +19,9 @@ NativeCertificatesHandler::~NativeCertificatesHandler() {} void NativeCertificatesHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "showManageSSLCertificates", - base::Bind(&NativeCertificatesHandler::HandleShowManageSSLCertificates, - base::Unretained(this))); + base::BindRepeating( + &NativeCertificatesHandler::HandleShowManageSSLCertificates, + base::Unretained(this))); } void NativeCertificatesHandler::HandleShowManageSSLCertificates( diff --git a/chromium/chrome/browser/ui/webui/settings/on_startup_handler.cc b/chromium/chrome/browser/ui/webui/settings/on_startup_handler.cc index fe50a556468..48ae4623565 100644 --- a/chromium/chrome/browser/ui/webui/settings/on_startup_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/on_startup_handler.cc @@ -41,12 +41,13 @@ void OnStartupHandler::OnJavascriptDisallowed() { void OnStartupHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "getNtpExtension", base::Bind(&OnStartupHandler::HandleGetNtpExtension, - base::Unretained(this))); + "getNtpExtension", + base::BindRepeating(&OnStartupHandler::HandleGetNtpExtension, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "validateStartupPage", - base::Bind(&OnStartupHandler::HandleValidateStartupPage, - base::Unretained(this))); + base::BindRepeating(&OnStartupHandler::HandleValidateStartupPage, + base::Unretained(this))); } void OnStartupHandler::OnExtensionUnloaded( diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.cc b/chromium/chrome/browser/ui/webui/settings/people_handler.cc index 8c8cddf5897..23e8d1044e0 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.cc @@ -25,6 +25,7 @@ #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/signin/signin_promo.h" #include "chrome/browser/signin/signin_ui_util.h" +#include "chrome/browser/signin/unified_consent_helper.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/sync_ui_util.h" #include "chrome/browser/ui/browser_finder.h" @@ -207,7 +208,8 @@ PeopleHandler::~PeopleHandler() { if (!web_ui()) return; - // This case is hit when the user performs a back navigation. + // Note that if the user left the sync page by closing the tab, refresh, + // or via the back navigation, it would first go through OnDidClosePage(). CloseSyncSetup(); } @@ -215,35 +217,46 @@ void PeopleHandler::RegisterMessages() { InitializeSyncBlocker(); web_ui()->RegisterMessageCallback( "SyncSetupDidClosePage", - base::Bind(&PeopleHandler::OnDidClosePage, base::Unretained(this))); + base::BindRepeating(&PeopleHandler::OnDidClosePage, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "SyncSetupSetDatatypes", - base::Bind(&PeopleHandler::HandleSetDatatypes, base::Unretained(this))); + base::BindRepeating(&PeopleHandler::HandleSetDatatypes, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "SyncSetupSetSyncEverything", + base::BindRepeating(&PeopleHandler::HandleSetSyncEverything, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "SyncSetupSetEncryption", - base::Bind(&PeopleHandler::HandleSetEncryption, base::Unretained(this))); + base::BindRepeating(&PeopleHandler::HandleSetEncryption, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "SyncSetupShowSetupUI", - base::Bind(&PeopleHandler::HandleShowSetupUI, base::Unretained(this))); + base::BindRepeating(&PeopleHandler::HandleShowSetupUI, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "SyncSetupGetSyncStatus", - base::Bind(&PeopleHandler::HandleGetSyncStatus, base::Unretained(this))); + base::BindRepeating(&PeopleHandler::HandleGetSyncStatus, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "SyncSetupManageOtherPeople", - base::Bind(&PeopleHandler::HandleManageOtherPeople, - base::Unretained(this))); + base::BindRepeating(&PeopleHandler::HandleManageOtherPeople, + base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( "AttemptUserExit", - base::Bind(&PeopleHandler::HandleAttemptUserExit, - base::Unretained(this))); + base::BindRepeating(&PeopleHandler::HandleAttemptUserExit, + base::Unretained(this))); #else web_ui()->RegisterMessageCallback( "SyncSetupStopSyncing", - base::Bind(&PeopleHandler::HandleStopSyncing, base::Unretained(this))); + base::BindRepeating(&PeopleHandler::HandleStopSyncing, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "SyncSetupStartSignIn", - base::Bind(&PeopleHandler::HandleStartSignin, base::Unretained(this))); + base::BindRepeating(&PeopleHandler::HandleStartSignin, + base::Unretained(this))); #endif #if BUILDFLAG(ENABLE_DICE_SUPPORT) web_ui()->RegisterMessageCallback( @@ -269,6 +282,8 @@ void PeopleHandler::OnJavascriptAllowed() { if (signin_manager) signin_observer_.Add(signin_manager); + // This is intentionally not using GetSyncService(), to go around the + // Profile::IsSyncAllowed() check. ProfileSyncService* sync_service( ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_)); if (sync_service) @@ -376,7 +391,12 @@ void PeopleHandler::DisplayTimeout() { } void PeopleHandler::OnDidClosePage(const base::ListValue* args) { - MarkFirstSetupComplete(); + // Don't mark setup as complete if "didAbort" is true, or if authentication + // is still needed. + if (!args->GetList()[0].GetBool() && !IsProfileAuthNeededOrHasErrors()) { + MarkFirstSetupComplete(); + } + CloseSyncSetup(); } @@ -441,6 +461,30 @@ void PeopleHandler::HandleSetDatatypes(const base::ListValue* args) { ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_CHOOSE); } +// This function is different from HandleSetDatatypes, in that it only sets +// the syncAllDatatypes without overriding other prefs' on-disk values. +void PeopleHandler::HandleSetSyncEverything(const base::ListValue* args) { + DCHECK(!sync_startup_tracker_); + + CHECK_EQ(2U, args->GetSize()); + const base::Value& callback_id = args->GetList()[0]; + bool sync_everything = args->GetList()[1].GetBool(); + + ProfileSyncService* service = GetSyncService(); + // If the sync engine has shutdown for some reason, just close the sync + // dialog. + if (!service || !service->IsEngineInitialized()) { + CloseSyncSetup(); + ResolveJavascriptCallback(callback_id, base::Value(kDonePageStatus)); + return; + } + + service->OnUserChangedSyncEverythingOnly(sync_everything); + ResolveJavascriptCallback(callback_id, base::Value(kConfigurePageStatus)); + + ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_CUSTOMIZE); +} + #if BUILDFLAG(ENABLE_DICE_SUPPORT) void PeopleHandler::HandleGetStoredAccounts(const base::ListValue* args) { CHECK_EQ(1U, args->GetSize()); @@ -488,7 +532,9 @@ std::unique_ptr<base::ListValue> PeopleHandler::GetStoredAccountsList() { void PeopleHandler::HandleStartSyncingWithEmail(const base::ListValue* args) { const base::Value* email; + const base::Value* is_default_promo_account; CHECK(args->Get(0, &email)); + CHECK(args->Get(1, &is_default_promo_account)); Browser* browser = chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()); @@ -497,9 +543,9 @@ void PeopleHandler::HandleStartSyncingWithEmail(const base::ListValue* args) { AccountTrackerServiceFactory::GetForProfile(profile_); AccountInfo account = account_tracker->FindAccountInfoByEmail(email->GetString()); - - signin_ui_util::EnableSync( - browser, account, signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); + signin_ui_util::EnableSyncFromPromo( + browser, account, signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS, + is_default_promo_account->GetBool()); } #endif @@ -583,13 +629,28 @@ void PeopleHandler::HandleSetEncryption(const base::ListValue* args) { void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { AllowJavascript(); - if (!GetSyncService()) { + ProfileSyncService* service = GetSyncService(); + + // Just let the page open for now, even when the user's not signed in. + // TODO(scottchen): finish the UI for signed-out users + // (https://crbug.com/800972). + if (IsUnifiedConsentEnabled(profile_) && IsProfileAuthNeededOrHasErrors()) { + if (service && !sync_blocker_) + sync_blocker_ = service->GetSetupInProgressHandle(); + + FireWebUIListener("sync-prefs-changed", base::DictionaryValue()); + return; + } + + if (!service) { CloseUI(); return; } - SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile_); - if (!signin->IsAuthenticated()) { + // This if-statement is not using IsProfileAuthNeededOrHasErrors(), because + // in some error cases (e.g. "confirmSyncSettings") the UI still needs to + // show. + if (!SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated()) { // For web-based signin, the signin page is not displayed in an overlay // on the settings page. So if we get here, it must be due to the user // cancelling signin (by reloading the sync settings page during initial @@ -600,7 +661,38 @@ void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { return; } - OpenSyncSetup(); + // Notify services that login UI is now active. + GetLoginUIService()->SetLoginUI(this); + + if (!sync_blocker_) + sync_blocker_ = service->GetSetupInProgressHandle(); + + // Early exit if there is already a preferences push pending sync startup. + if (sync_startup_tracker_) + return; + + if (!service->IsEngineInitialized()) { + // Requesting the sync service to start may trigger call to PushSyncPrefs. + // Setting up the startup tracker beforehand correctly signals the + // re-entrant call to early exit. + sync_startup_tracker_.reset(new SyncStartupTracker(profile_, this)); + service->RequestStart(); + + // See if it's even possible to bring up the sync engine - if not + // (unrecoverable error?), don't bother displaying a spinner that will be + // immediately closed because this leads to some ugly infinite UI loop (see + // http://crbug.com/244769). + if (SyncStartupTracker::GetSyncServiceState(profile_) != + SyncStartupTracker::SYNC_STARTUP_ERROR) { + DisplaySpinner(); + } + return; + } + + // User is already logged in. They must have brought up the config wizard + // via the "Advanced..." button or through One-Click signin (cases 4-6), or + // they are re-enabling sync after having disabled it (case 7). + PushSyncPrefs(); } #if defined(OS_CHROMEOS) @@ -618,10 +710,9 @@ void PeopleHandler::HandleStartSignin(const base::ListValue* args) { // Should only be called if the user is not already signed in or has an auth // error. - DCHECK(!SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated() || - SigninErrorControllerFactory::GetForProfile(profile_)->HasError()); + DCHECK(IsProfileAuthNeededOrHasErrors()); - OpenSyncSetup(); + DisplayGaiaLogin(signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); } void PeopleHandler::HandleStopSyncing(const base::ListValue* args) { @@ -698,7 +789,6 @@ void PeopleHandler::CloseSyncSetup() { #if !defined(OS_CHROMEOS) // Sign out the user on desktop Chrome if they click cancel during // initial setup. - // TODO(rsimha): Revisit this for M30. See http://crbug.com/252049. if (sync_service->IsFirstSetupInProgress()) { SigninManagerFactory::GetForProfile(profile_) ->SignOut(signin_metrics::ABORT_SIGNIN, @@ -720,72 +810,6 @@ void PeopleHandler::CloseSyncSetup() { configuring_sync_ = false; } -void PeopleHandler::OpenSyncSetup() { - // Notify services that login UI is now active. - GetLoginUIService()->SetLoginUI(this); - - ProfileSyncService* service = GetSyncService(); - if (service && !sync_blocker_) - sync_blocker_ = service->GetSetupInProgressHandle(); - - // There are several different UI flows that can bring the user here: - // 1) Signin promo. - // 2) Normal signin through settings page (IsAuthenticated() is false). - // 3) Previously working credentials have expired. - // 4) User is signed in, but has stopped sync via the google dashboard, and - // signout is prohibited by policy so we need to force a re-auth. - // 5) User clicks [Advanced Settings] button on options page while already - // logged in. - // 6) One-click signin (credentials are already available, so should display - // sync configure UI, not login UI). - // 7) User re-enables sync after disabling it via advanced settings. -#if !defined(OS_CHROMEOS) - if (!SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated() || - SigninErrorControllerFactory::GetForProfile(profile_)->HasError()) { - // User is not logged in (cases 1-2), or login has been specially requested - // because previously working credentials have expired (case 3). Close sync - // setup including any visible overlays, and display the gaia auth page. - // Control will be returned to the sync settings page once auth is complete. - CloseUI(); - DisplayGaiaLogin(signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); - return; - } -#endif - if (!service) { - // This can happen if the user directly navigates to /settings/syncSetup. - DLOG(WARNING) << "Cannot display sync UI when sync is disabled"; - CloseUI(); - return; - } - - // Early exit if there is already a preferences push pending sync startup. - if (sync_startup_tracker_) - return; - - if (!service->IsEngineInitialized()) { - // Requesting the sync service to start may trigger call to PushSyncPrefs. - // Setting up the startup tracker beforehand correctly signals the - // re-entrant call to early exit. - sync_startup_tracker_.reset(new SyncStartupTracker(profile_, this)); - service->RequestStart(); - - // See if it's even possible to bring up the sync engine - if not - // (unrecoverable error?), don't bother displaying a spinner that will be - // immediately closed because this leads to some ugly infinite UI loop (see - // http://crbug.com/244769). - if (SyncStartupTracker::GetSyncServiceState(profile_) != - SyncStartupTracker::SYNC_STARTUP_ERROR) { - DisplaySpinner(); - } - return; - } - - // User is already logged in. They must have brought up the config wizard - // via the "Advanced..." button or through One-Click signin (cases 4-6), or - // they are re-enabling sync after having disabled it (case 7). - PushSyncPrefs(); -} - void PeopleHandler::InitializeSyncBlocker() { if (!web_ui()) return; @@ -855,13 +879,17 @@ PeopleHandler::GetSyncStatusDictionary() { } #endif + // This is intentionally not using GetSyncService(), in order to access more + // nuanced information, since GetSyncService() returns nullptr if anything + // makes Profile::IsSyncAllowed() false. ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_); sync_status->SetBoolean("signinAllowed", signin->IsSigninAllowed()); sync_status->SetBoolean("syncSystemEnabled", (service != nullptr)); - sync_status->SetBoolean( - "setupInProgress", - service && !service->IsManaged() && service->IsFirstSetupInProgress()); + sync_status->SetBoolean("setupInProgress", + service && !service->IsManaged() && + service->IsFirstSetupInProgress() && + signin->IsAuthenticated()); base::string16 status_label; base::string16 link_label; @@ -887,10 +915,8 @@ PeopleHandler::GetSyncStatusDictionary() { void PeopleHandler::PushSyncPrefs() { #if !defined(OS_CHROMEOS) // Early exit if the user has not signed in yet. - if (!SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated() || - SigninErrorControllerFactory::GetForProfile(profile_)->HasError()) { + if (IsProfileAuthNeededOrHasErrors()) return; - } #endif ProfileSyncService* service = GetSyncService(); @@ -1017,6 +1043,12 @@ void PeopleHandler::MarkFirstSetupComplete() { // start syncing. sync_blocker_.reset(); service->SetFirstSetupComplete(); + FireWebUIListener("sync-settings-saved"); +} + +bool PeopleHandler::IsProfileAuthNeededOrHasErrors() { + return !SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated() || + SigninErrorControllerFactory::GetForProfile(profile_)->HasError(); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.h b/chromium/chrome/browser/ui/webui/settings/people_handler.h index 0ea976fa175..392f0d92475 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.h @@ -19,7 +19,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_features.h" +#include "components/signin/core/browser/signin_buildflags.h" #include "components/signin/core/browser/signin_manager_base.h" #include "components/sync/driver/sync_service_observer.h" @@ -68,9 +68,6 @@ class PeopleHandler : public SettingsPageUIHandler, explicit PeopleHandler(Profile* profile); ~PeopleHandler() override; - // Initializes the sync setup flow and shows the setup UI. - void OpenSyncSetup(); - // Terminates the sync setup flow. void CloseSyncSetup(); @@ -83,9 +80,26 @@ class PeopleHandler : public SettingsPageUIHandler, DisplayConfigureWithEngineDisabledAndCancel); FRIEND_TEST_ALL_PREFIXES( PeopleHandlerTest, + DisplayConfigureWithEngineDisabledAndCancelAfterSigninSuccess); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, + DisplayConfigureWithEngineDisabledAndSigninFailed); + FRIEND_TEST_ALL_PREFIXES( + PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndSyncStartupCompleted); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, HandleSetupUIWhenSyncDisabled); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, SelectCustomEncryption); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, + ShowSetupCustomPassphraseRequired); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSetupEncryptAll); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSetupEncryptAllDisallowed); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSetupManuallySyncAll); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, + ShowSetupOldGaiaPassphraseRequired); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSetupSyncEverything); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, + ShowSetupSyncForAllTypesIndividually); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSigninOnAuthError); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSyncSetup); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSyncSetupWhenNotSignedIn); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, SuccessfullySetPassphrase); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, TestSyncEverything); @@ -153,6 +167,7 @@ class PeopleHandler : public SettingsPageUIHandler, void OnDidClosePage(const base::ListValue* args); void HandleSetDatatypes(const base::ListValue* args); void HandleSetEncryption(const base::ListValue* args); + void HandleSetSyncEverything(const base::ListValue* args); void HandleShowSetupUI(const base::ListValue* args); void HandleAttemptUserExit(const base::ListValue* args); void HandleStartSignin(const base::ListValue* args); @@ -197,6 +212,9 @@ class PeopleHandler : public SettingsPageUIHandler, // Suppresses any further signin promos, since the user has signed in once. void MarkFirstSetupComplete(); + // True if profile needs authentication before sync can run. + bool IsProfileAuthNeededOrHasErrors(); + // If we're directly loading the sync setup page, we acquire a // SetupInProgressHandle early in order to prevent a lapse in // ProfileSyncService's "SetupInProgress" status. This lapse previously diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc index 13312118858..8964c907cb6 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc @@ -358,7 +358,7 @@ TEST_F(PeopleHandlerFirstSigninTest, DisplayBasicLogin) { TEST_F(PeopleHandlerTest, ShowSyncSetupWhenNotSignedIn) { EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); - handler_->HandleShowSetupUI(NULL); + handler_->HandleShowSetupUI(nullptr); ExpectPageStatusChanged(PeopleHandler::kDonePageStatus); @@ -373,7 +373,7 @@ TEST_F(PeopleHandlerTest, ShowSyncSetupWhenNotSignedIn) { // sync is disabled. TEST_F(PeopleHandlerTest, HandleSetupUIWhenSyncDisabled) { EXPECT_CALL(*mock_pss_, IsManaged()).WillRepeatedly(Return(true)); - handler_->HandleShowSetupUI(NULL); + handler_->HandleShowSetupUI(nullptr); // Sync setup is closed when sync is disabled. EXPECT_EQ( @@ -396,7 +396,7 @@ TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndCancel) { // engine will try to download control data types (e.g encryption info), but // that won't finish for this test as we're simulating cancelling while the // spinner is showing. - handler_->HandleShowSetupUI(NULL); + handler_->HandleShowSetupUI(nullptr); EXPECT_EQ( handler_.get(), @@ -417,7 +417,7 @@ TEST_F(PeopleHandlerTest, EXPECT_CALL(*mock_pss_, RequestStart()); SetDefaultExpectationsForConfigPage(); - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); EXPECT_EQ(1U, web_ui_.call_data().size()); ExpectPageStatusChanged(PeopleHandler::kSpinnerPageStatus); @@ -454,7 +454,7 @@ TEST_F(PeopleHandlerTest, .WillRepeatedly(Return(true)); EXPECT_CALL(*mock_pss_, RequestStart()); SetDefaultExpectationsForConfigPage(); - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); // It's important to tell sync the user cancelled the setup flow before we // tell it we're through with the setup progress. @@ -475,7 +475,7 @@ TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndSigninFailed) { EXPECT_CALL(*mock_pss_, IsEngineInitialized()).WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, RequestStart()); - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); ExpectPageStatusChanged(PeopleHandler::kSpinnerPageStatus); Mock::VerifyAndClearExpectations(mock_pss_); error_ = GoogleServiceAuthError( @@ -532,7 +532,7 @@ TEST_F(PeopleHandlerNonCrosTest, HandleGaiaAuthFailure) { .WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); // Open the web UI. - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); ASSERT_FALSE(handler_->is_configuring_sync()); } @@ -542,7 +542,7 @@ TEST_F(PeopleHandlerNonCrosTest, UnrecoverableErrorInitializingSync) { EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); // Open the web UI. - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); ASSERT_FALSE(handler_->is_configuring_sync()); } @@ -551,7 +551,7 @@ TEST_F(PeopleHandlerNonCrosTest, GaiaErrorInitializingSync) { EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); // Open the web UI. - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); ASSERT_FALSE(handler_->is_configuring_sync()); } @@ -751,7 +751,7 @@ TEST_F(PeopleHandlerTest, ShowSyncSetup) { SetupInitializedProfileSyncService(); // This should display the sync setup dialog (not login). SetDefaultExpectationsForConfigPage(); - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); ExpectSyncPrefsChanged(); } @@ -787,7 +787,7 @@ TEST_F(PeopleHandlerTest, ShowSigninOnAuthError) { // On ChromeOS, this should display the spinner while we try to startup the // sync engine, and on desktop this displays the login dialog. - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); // Sync setup is closed when re-auth is in progress. EXPECT_EQ( @@ -806,7 +806,7 @@ TEST_F(PeopleHandlerTest, ShowSetupSyncEverything) { SetupInitializedProfileSyncService(); SetDefaultExpectationsForConfigPage(); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckBool(dictionary, "syncAllDataTypes", true); @@ -836,7 +836,7 @@ TEST_F(PeopleHandlerTest, ShowSetupManuallySyncAll) { sync_prefs.SetKeepEverythingSynced(false); SetDefaultExpectationsForConfigPage(); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckConfigDataTypeArguments(dictionary, CHOOSE_WHAT_TO_SYNC, GetAllTypes()); @@ -860,7 +860,7 @@ TEST_F(PeopleHandlerTest, ShowSetupSyncForAllTypesIndividually) { WillRepeatedly(Return(types)); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); // Close the config overlay. LoginUIServiceFactory::GetForProfile(profile())->LoginUIClosed( @@ -884,7 +884,7 @@ TEST_F(PeopleHandlerTest, ShowSetupOldGaiaPassphraseRequired) { SetDefaultExpectationsForConfigPage(); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckBool(dictionary, "passphraseRequired", true); @@ -900,7 +900,7 @@ TEST_F(PeopleHandlerTest, ShowSetupCustomPassphraseRequired) { SetDefaultExpectationsForConfigPage(); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckBool(dictionary, "passphraseRequired", true); @@ -918,7 +918,7 @@ TEST_F(PeopleHandlerTest, ShowSetupEncryptAll) { .WillRepeatedly(Return(true)); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckBool(dictionary, "encryptAllData", true); @@ -935,7 +935,7 @@ TEST_F(PeopleHandlerTest, ShowSetupEncryptAllDisallowed) { .WillRepeatedly(Return(false)); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckBool(dictionary, "encryptAllData", false); diff --git a/chromium/chrome/browser/ui/webui/settings/printing_handler.cc b/chromium/chrome/browser/ui/webui/settings/printing_handler.cc index 45644030eb2..8647b2daf9e 100644 --- a/chromium/chrome/browser/ui/webui/settings/printing_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/printing_handler.cc @@ -18,8 +18,8 @@ PrintingHandler::~PrintingHandler() {} void PrintingHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "openSystemPrintDialog", - base::Bind(&PrintingHandler::HandleOpenSystemPrintDialog, - base::Unretained(this))); + base::BindRepeating(&PrintingHandler::HandleOpenSystemPrintDialog, + base::Unretained(this))); } void PrintingHandler::OnJavascriptAllowed() {} diff --git a/chromium/chrome/browser/ui/webui/settings/printing_handler.h b/chromium/chrome/browser/ui/webui/settings/printing_handler.h index 5759261d684..6f993475678 100644 --- a/chromium/chrome/browser/ui/webui/settings/printing_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/printing_handler.h @@ -8,7 +8,7 @@ #include "base/macros.h" #include "build/build_config.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" -#include "printing/features/features.h" +#include "printing/buildflags/buildflags.h" #if defined(OS_CHROMEOS) #error "Not for use on ChromeOS" diff --git a/chromium/chrome/browser/ui/webui/settings/profile_info_handler.cc b/chromium/chrome/browser/ui/webui/settings/profile_info_handler.cc index 299d6fe9a8d..e7c647fe122 100644 --- a/chromium/chrome/browser/ui/webui/settings/profile_info_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/profile_info_handler.cc @@ -52,13 +52,14 @@ ProfileInfoHandler::~ProfileInfoHandler() {} void ProfileInfoHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "getProfileInfo", base::Bind(&ProfileInfoHandler::HandleGetProfileInfo, - base::Unretained(this))); + "getProfileInfo", + base::BindRepeating(&ProfileInfoHandler::HandleGetProfileInfo, + base::Unretained(this))); #if !defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( "getProfileStatsCount", - base::Bind(&ProfileInfoHandler::HandleGetProfileStats, - base::Unretained(this))); + base::BindRepeating(&ProfileInfoHandler::HandleGetProfileStats, + base::Unretained(this))); #endif } diff --git a/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc b/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc index 3b1453e6170..1f486d9b882 100644 --- a/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc @@ -40,22 +40,28 @@ void ProtocolHandlersHandler::OnJavascriptDisallowed() { } void ProtocolHandlersHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("observeProtocolHandlers", - base::Bind(&ProtocolHandlersHandler::HandleObserveProtocolHandlers, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("observeProtocolHandlersEnabledState", - base::Bind( + web_ui()->RegisterMessageCallback( + "observeProtocolHandlers", + base::BindRepeating( + &ProtocolHandlersHandler::HandleObserveProtocolHandlers, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "observeProtocolHandlersEnabledState", + base::BindRepeating( &ProtocolHandlersHandler::HandleObserveProtocolHandlersEnabledState, base::Unretained(this))); - web_ui()->RegisterMessageCallback("removeHandler", - base::Bind(&ProtocolHandlersHandler::HandleRemoveHandler, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("setHandlersEnabled", - base::Bind(&ProtocolHandlersHandler::HandleSetHandlersEnabled, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("setDefault", - base::Bind(&ProtocolHandlersHandler::HandleSetDefault, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "removeHandler", + base::BindRepeating(&ProtocolHandlersHandler::HandleRemoveHandler, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "setHandlersEnabled", + base::BindRepeating(&ProtocolHandlersHandler::HandleSetHandlersEnabled, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "setDefault", + base::BindRepeating(&ProtocolHandlersHandler::HandleSetDefault, + base::Unretained(this))); } ProtocolHandlerRegistry* ProtocolHandlersHandler::GetProtocolHandlerRegistry() { @@ -71,6 +77,8 @@ static void GetHandlersAsListValue( for (handler = handlers.begin(); handler != handlers.end(); ++handler) { std::unique_ptr<base::DictionaryValue> handler_value( new base::DictionaryValue()); + handler_value->SetString("protocol_display_name", + handler->GetProtocolDisplayName()); handler_value->SetString("protocol", handler->protocol()); handler_value->SetString("spec", handler->url().spec()); handler_value->SetString("host", handler->url().host()); @@ -83,6 +91,8 @@ void ProtocolHandlersHandler::GetHandlersForProtocol( const std::string& protocol, base::DictionaryValue* handlers_value) { ProtocolHandlerRegistry* registry = GetProtocolHandlerRegistry(); + handlers_value->SetString("protocol_display_name", + ProtocolHandler::GetProtocolDisplayName(protocol)); handlers_value->SetString("protocol", protocol); auto handlers_list = std::make_unique<base::ListValue>(); diff --git a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc index 6ecd5cc170d..4cc1ff9e229 100644 --- a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc @@ -105,30 +105,36 @@ void ResetSettingsHandler::OnJavascriptDisallowed() { } void ResetSettingsHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("performResetProfileSettings", - base::Bind(&ResetSettingsHandler::HandleResetProfileSettings, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("onShowResetProfileDialog", - base::Bind(&ResetSettingsHandler::OnShowResetProfileDialog, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("getReportedSettings", - base::Bind(&ResetSettingsHandler::HandleGetReportedSettings, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("onHideResetProfileDialog", - base::Bind(&ResetSettingsHandler::OnHideResetProfileDialog, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("onHideResetProfileBanner", - base::Bind(&ResetSettingsHandler::OnHideResetProfileBanner, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "performResetProfileSettings", + base::BindRepeating(&ResetSettingsHandler::HandleResetProfileSettings, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "onShowResetProfileDialog", + base::BindRepeating(&ResetSettingsHandler::OnShowResetProfileDialog, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getReportedSettings", + base::BindRepeating(&ResetSettingsHandler::HandleGetReportedSettings, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "onHideResetProfileDialog", + base::BindRepeating(&ResetSettingsHandler::OnHideResetProfileDialog, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "onHideResetProfileBanner", + base::BindRepeating(&ResetSettingsHandler::OnHideResetProfileBanner, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getTriggeredResetToolName", - base::Bind(&ResetSettingsHandler::HandleGetTriggeredResetToolName, - base::Unretained(this))); + base::BindRepeating( + &ResetSettingsHandler::HandleGetTriggeredResetToolName, + base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( - "onPowerwashDialogShow", - base::Bind(&ResetSettingsHandler::OnShowPowerwashDialog, - base::Unretained(this))); + "onPowerwashDialogShow", + base::BindRepeating(&ResetSettingsHandler::OnShowPowerwashDialog, + base::Unretained(this))); #endif // defined(OS_CHROMEOS) } diff --git a/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc b/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc index f017287acdf..d43930fb1e8 100644 --- a/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc @@ -13,17 +13,33 @@ namespace settings { +namespace { + +base::DictionaryValue GetSberStateDictionaryValue(const PrefService& prefs) { + base::DictionaryValue dict; + dict.SetBoolean("enabled", safe_browsing::IsExtendedReportingEnabled(prefs)); + // TODO(crbug.com/813107): SBEROIA policy is being deprecated, revisit this + // after it is removed. + dict.SetBoolean("managed", + !safe_browsing::IsExtendedReportingOptInAllowed(prefs) || + safe_browsing::IsExtendedReportingPolicyManaged(prefs)); + return dict; +} + +} // namespace + SafeBrowsingHandler::SafeBrowsingHandler(PrefService* prefs) : prefs_(prefs) {} SafeBrowsingHandler::~SafeBrowsingHandler() {} void SafeBrowsingHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getSafeBrowsingExtendedReporting", - base::Bind(&SafeBrowsingHandler::HandleGetSafeBrowsingExtendedReporting, - base::Unretained(this))); + base::BindRepeating( + &SafeBrowsingHandler::HandleGetSafeBrowsingExtendedReporting, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setSafeBrowsingExtendedReportingEnabled", - base::Bind( + base::BindRepeating( &SafeBrowsingHandler::HandleSetSafeBrowsingExtendedReportingEnabled, base::Unretained(this))); } @@ -48,16 +64,7 @@ void SafeBrowsingHandler::HandleGetSafeBrowsingExtendedReporting( const base::Value* callback_id; CHECK(args->Get(0, &callback_id)); - base::DictionaryValue dict; - dict.SetBoolean("enabled", - safe_browsing::IsExtendedReportingEnabled(*prefs_)); - // TODO(crbug.com/813107): SBEROIA policy is being deprecated, revisit this - // after it is removed. - dict.SetBoolean("managed", - !safe_browsing::IsExtendedReportingOptInAllowed(*prefs_) || - safe_browsing::IsExtendedReportingPolicyManaged(*prefs_)); - - ResolveJavascriptCallback(*callback_id, dict); + ResolveJavascriptCallback(*callback_id, GetSberStateDictionaryValue(*prefs_)); } void SafeBrowsingHandler::HandleSetSafeBrowsingExtendedReportingEnabled( @@ -72,8 +79,8 @@ void SafeBrowsingHandler::OnPrefChanged(const std::string& pref_name) { DCHECK(pref_name == prefs::kSafeBrowsingExtendedReportingEnabled || pref_name == prefs::kSafeBrowsingScoutReportingEnabled); - base::Value is_enabled(safe_browsing::IsExtendedReportingEnabled(*prefs_)); - FireWebUIListener("safe-browsing-extended-reporting-change", is_enabled); + FireWebUIListener("safe-browsing-extended-reporting-change", + GetSberStateDictionaryValue(*prefs_)); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc b/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc index 136df4229c4..bf98d178d56 100644 --- a/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc @@ -61,32 +61,35 @@ SearchEnginesHandler::~SearchEnginesHandler() { void SearchEnginesHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getSearchEnginesList", - base::Bind(&SearchEnginesHandler::HandleGetSearchEnginesList, - base::Unretained(this))); + base::BindRepeating(&SearchEnginesHandler::HandleGetSearchEnginesList, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setDefaultSearchEngine", - base::Bind(&SearchEnginesHandler::HandleSetDefaultSearchEngine, - base::Unretained(this))); + base::BindRepeating(&SearchEnginesHandler::HandleSetDefaultSearchEngine, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "removeSearchEngine", - base::Bind(&SearchEnginesHandler::HandleRemoveSearchEngine, - base::Unretained(this))); + base::BindRepeating(&SearchEnginesHandler::HandleRemoveSearchEngine, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "validateSearchEngineInput", - base::Bind(&SearchEnginesHandler::HandleValidateSearchEngineInput, - base::Unretained(this))); + base::BindRepeating( + &SearchEnginesHandler::HandleValidateSearchEngineInput, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "searchEngineEditStarted", - base::Bind(&SearchEnginesHandler::HandleSearchEngineEditStarted, - base::Unretained(this))); + base::BindRepeating(&SearchEnginesHandler::HandleSearchEngineEditStarted, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "searchEngineEditCancelled", - base::Bind(&SearchEnginesHandler::HandleSearchEngineEditCancelled, - base::Unretained(this))); + base::BindRepeating( + &SearchEnginesHandler::HandleSearchEngineEditCancelled, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "searchEngineEditCompleted", - base::Bind(&SearchEnginesHandler::HandleSearchEngineEditCompleted, - base::Unretained(this))); + base::BindRepeating( + &SearchEnginesHandler::HandleSearchEngineEditCompleted, + base::Unretained(this))); } void SearchEnginesHandler::OnJavascriptAllowed() { @@ -111,6 +114,10 @@ SearchEnginesHandler::GetSearchEnginesList() { std::make_unique<base::ListValue>(); int last_default_engine_index = list_controller_.table_model()->last_search_engine_index(); + + // Sanity check for https://crbug.com/781703. + CHECK_GE(last_default_engine_index, 0); + for (int i = 0; i < last_default_engine_index; ++i) { // Third argument is false, as the engine is not from an extension. defaults->Append(CreateDictionaryForEngine(i, i == default_index)); @@ -120,6 +127,10 @@ SearchEnginesHandler::GetSearchEnginesList() { std::unique_ptr<base::ListValue> others = std::make_unique<base::ListValue>(); int last_other_engine_index = list_controller_.table_model()->last_other_engine_index(); + + // Sanity check for https://crbug.com/781703. + CHECK_LE(last_default_engine_index, last_other_engine_index); + for (int i = std::max(last_default_engine_index, 0); i < last_other_engine_index; ++i) { others->Append(CreateDictionaryForEngine(i, i == default_index)); @@ -129,6 +140,10 @@ SearchEnginesHandler::GetSearchEnginesList() { std::unique_ptr<base::ListValue> extensions = std::make_unique<base::ListValue>(); int engine_count = list_controller_.table_model()->RowCount(); + + // Sanity check for https://crbug.com/781703. + CHECK_LE(last_other_engine_index, engine_count); + for (int i = std::max(last_other_engine_index, 0); i < engine_count; ++i) { extensions->Append(CreateDictionaryForEngine(i, i == default_index)); } @@ -163,6 +178,11 @@ SearchEnginesHandler::CreateDictionaryForEngine(int index, bool is_default) { TemplateURLTableModel* table_model = list_controller_.table_model(); const TemplateURL* template_url = list_controller_.GetTemplateURL(index); + // Sanity check for https://crbug.com/781703. + CHECK_GE(index, 0); + CHECK_LT(index, table_model->RowCount()); + CHECK(template_url); + // The items which are to be written into |dict| are also described in // chrome/browser/resources/settings/search_engines_page/ // in @typedef for SearchEngine. Please update it whenever you add or remove diff --git a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc index b4c04a907d9..f6e53a16445 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc @@ -93,18 +93,18 @@ ClearBrowsingDataHandler::~ClearBrowsingDataHandler() { void ClearBrowsingDataHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "clearBrowsingData", - base::Bind(&ClearBrowsingDataHandler::HandleClearBrowsingData, - base::Unretained(this))); + base::BindRepeating(&ClearBrowsingDataHandler::HandleClearBrowsingData, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getImportantSites", - base::Bind(&ClearBrowsingDataHandler::HandleGetImportantSites, - base::Unretained(this))); + base::BindRepeating(&ClearBrowsingDataHandler::HandleGetImportantSites, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "initializeClearBrowsingData", - base::Bind(&ClearBrowsingDataHandler::HandleInitialize, - base::Unretained(this))); + base::BindRepeating(&ClearBrowsingDataHandler::HandleInitialize, + base::Unretained(this))); } void ClearBrowsingDataHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc index b10325705f8..2017d6c1fee 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc @@ -160,28 +160,32 @@ void CookiesViewHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "localData.getDisplayList", - base::Bind(&CookiesViewHandler::HandleGetDisplayList, - base::Unretained(this))); + base::BindRepeating(&CookiesViewHandler::HandleGetDisplayList, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "localData.removeAll", - base::Bind(&CookiesViewHandler::HandleRemoveAll, base::Unretained(this))); + base::BindRepeating(&CookiesViewHandler::HandleRemoveAll, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "localData.removeShownItems", - base::Bind(&CookiesViewHandler::HandleRemoveShownItems, - base::Unretained(this))); + base::BindRepeating(&CookiesViewHandler::HandleRemoveShownItems, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "localData.removeItem", base::Bind(&CookiesViewHandler::HandleRemoveItem, - base::Unretained(this))); + "localData.removeItem", + base::BindRepeating(&CookiesViewHandler::HandleRemoveItem, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "localData.getCookieDetails", - base::Bind(&CookiesViewHandler::HandleGetCookieDetails, - base::Unretained(this))); + base::BindRepeating(&CookiesViewHandler::HandleGetCookieDetails, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "localData.removeCookie", - base::Bind(&CookiesViewHandler::HandleRemove, base::Unretained(this))); + base::BindRepeating(&CookiesViewHandler::HandleRemove, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "localData.reload", base::Bind(&CookiesViewHandler::HandleReloadCookies, - base::Unretained(this))); + "localData.reload", + base::BindRepeating(&CookiesViewHandler::HandleReloadCookies, + base::Unretained(this))); } void CookiesViewHandler::TreeNodesAdded(ui::TreeModel* model, @@ -333,6 +337,7 @@ void CookiesViewHandler::HandleReloadCookies(const base::ListValue* args) { AllowJavascript(); cookies_tree_model_.reset(); + filter_.clear(); sorted_sites_.clear(); EnsureCookiesTreeModelCreated(); } diff --git a/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.cc index 66932e563b6..bc66616f991 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.cc @@ -39,12 +39,12 @@ DefaultBrowserHandler::~DefaultBrowserHandler() {} void DefaultBrowserHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "SettingsDefaultBrowser.requestDefaultBrowserState", - base::Bind(&DefaultBrowserHandler::RequestDefaultBrowserState, - base::Unretained(this))); + base::BindRepeating(&DefaultBrowserHandler::RequestDefaultBrowserState, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "SettingsDefaultBrowser.setAsDefaultBrowser", - base::Bind(&DefaultBrowserHandler::SetAsDefaultBrowser, - base::Unretained(this))); + base::BindRepeating(&DefaultBrowserHandler::SetAsDefaultBrowser, + base::Unretained(this))); } void DefaultBrowserHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc index 4a019494a6d..32deebd14fb 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc @@ -60,14 +60,15 @@ void ImportDataHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "initializeImportDialog", - base::Bind(&ImportDataHandler::InitializeDialog, base::Unretained(this))); + base::BindRepeating(&ImportDataHandler::InitializeDialog, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "importData", - base::Bind(&ImportDataHandler::ImportData, base::Unretained(this))); + "importData", base::BindRepeating(&ImportDataHandler::ImportData, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "importFromBookmarksFile", - base::Bind(&ImportDataHandler::HandleChooseBookmarksFile, - base::Unretained(this))); + base::BindRepeating(&ImportDataHandler::HandleChooseBookmarksFile, + base::Unretained(this))); } void ImportDataHandler::OnJavascriptDisallowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc index 37fc2ac17b3..5a68d2419c3 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc @@ -58,31 +58,35 @@ ManageProfileHandler::~ManageProfileHandler() {} void ManageProfileHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getAvailableIcons", - base::Bind(&ManageProfileHandler::HandleGetAvailableIcons, - base::Unretained(this))); + base::BindRepeating(&ManageProfileHandler::HandleGetAvailableIcons, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setProfileIconToGaiaAvatar", - base::Bind(&ManageProfileHandler::HandleSetProfileIconToGaiaAvatar, - base::Unretained(this))); + base::BindRepeating( + &ManageProfileHandler::HandleSetProfileIconToGaiaAvatar, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setProfileIconToDefaultAvatar", - base::Bind(&ManageProfileHandler::HandleSetProfileIconToDefaultAvatar, - base::Unretained(this))); + base::BindRepeating( + &ManageProfileHandler::HandleSetProfileIconToDefaultAvatar, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "setProfileName", base::Bind(&ManageProfileHandler::HandleSetProfileName, - base::Unretained(this))); + "setProfileName", + base::BindRepeating(&ManageProfileHandler::HandleSetProfileName, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestProfileShortcutStatus", - base::Bind(&ManageProfileHandler::HandleRequestProfileShortcutStatus, - base::Unretained(this))); + base::BindRepeating( + &ManageProfileHandler::HandleRequestProfileShortcutStatus, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "addProfileShortcut", - base::Bind(&ManageProfileHandler::HandleAddProfileShortcut, - base::Unretained(this))); + base::BindRepeating(&ManageProfileHandler::HandleAddProfileShortcut, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "removeProfileShortcut", - base::Bind(&ManageProfileHandler::HandleRemoveProfileShortcut, - base::Unretained(this))); + base::BindRepeating(&ManageProfileHandler::HandleRemoveProfileShortcut, + base::Unretained(this))); } void ManageProfileHandler::OnJavascriptAllowed() { @@ -94,6 +98,12 @@ void ManageProfileHandler::OnJavascriptDisallowed() { observer_.RemoveAll(); } +void ManageProfileHandler::OnProfileHighResAvatarLoaded( + const base::FilePath& profile_path) { + // GAIA image is loaded asynchronously. + FireWebUIListener("available-icons-changed", *GetAvailableIcons()); +} + void ManageProfileHandler::OnProfileAvatarChanged( const base::FilePath& profile_path) { // This is necessary to send the potentially updated GAIA photo. @@ -113,9 +123,20 @@ void ManageProfileHandler::HandleGetAvailableIcons( } std::unique_ptr<base::ListValue> ManageProfileHandler::GetAvailableIcons() { - std::unique_ptr<base::ListValue> image_url_list( + std::unique_ptr<base::ListValue> avatars( profiles::GetDefaultProfileAvatarIconsAndLabels()); + PrefService* pref_service = profile_->GetPrefs(); + bool using_gaia = pref_service->GetBoolean(prefs::kProfileUsingGAIAAvatar); + + // Select the avatar from the default set. + if (!using_gaia) { + size_t index = pref_service->GetInteger(prefs::kProfileAvatarIndex); + base::DictionaryValue* avatar = nullptr; + if (avatars->GetDictionary(index, &avatar)) + avatar->SetBoolean("selected", true); + } + // Add the GAIA picture to the beginning of the list if it is available. ProfileAttributesEntry* entry; if (g_browser_process->profile_manager()->GetProfileAttributesStorage(). @@ -130,11 +151,13 @@ std::unique_ptr<base::ListValue> ManageProfileHandler::GetAvailableIcons() { "label", l10n_util::GetStringUTF16(IDS_SETTINGS_CHANGE_PICTURE_PROFILE_PHOTO)); gaia_picture_info->SetBoolean("isGaiaAvatar", true); - image_url_list->Insert(0, std::move(gaia_picture_info)); + if (using_gaia) + gaia_picture_info->SetBoolean("selected", true); + avatars->Insert(0, std::move(gaia_picture_info)); } } - return image_url_list; + return avatars; } void ManageProfileHandler::HandleSetProfileIconToGaiaAvatar( diff --git a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h index 0929d3db294..659ef79b1f8 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h @@ -32,6 +32,10 @@ class ManageProfileHandler : public settings::SettingsPageUIHandler, // ProfileAttributesStorage::Observer: void OnProfileAvatarChanged(const base::FilePath& profile_path) override; + // ProfileAttributesStorage::Observer: + void OnProfileHighResAvatarLoaded( + const base::FilePath& profile_path) override; + private: FRIEND_TEST_ALL_PREFIXES(ManageProfileHandlerTest, HandleSetProfileIconToGaiaAvatar); @@ -39,6 +43,8 @@ class ManageProfileHandler : public settings::SettingsPageUIHandler, HandleSetProfileIconToDefaultAvatar); FRIEND_TEST_ALL_PREFIXES(ManageProfileHandlerTest, HandleSetProfileName); FRIEND_TEST_ALL_PREFIXES(ManageProfileHandlerTest, HandleGetAvailableIcons); + FRIEND_TEST_ALL_PREFIXES(ManageProfileHandlerTest, + HandleGetAvailableIconsGaiaAvatarSelected); // Callback for the "getAvailableIcons" message. // Sends the array of default profile icon URLs and profile names to WebUI. diff --git a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler_unittest.cc index 5a2e216865b..d981468902e 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler_unittest.cc @@ -45,7 +45,30 @@ class ManageProfileHandlerTest : public testing::Test { web_ui()->ClearTrackedCalls(); } - void VerifyIconList(const base::Value* value) { + void VerifyIconListWithNoneSelected(const base::Value* value) { + VerifyIconList(value, 0 /* ignored */, true); + } + + void VerifyIconListWithSingleSelection(const base::Value* value, + size_t selected_index) { + VerifyIconList(value, selected_index, false); + } + + content::TestWebUI* web_ui() { return &web_ui_; } + Profile* profile() const { return profile_; } + TestManageProfileHandler* handler() const { return handler_.get(); } + + private: + content::TestBrowserThreadBundle thread_bundle_; + TestingProfileManager profile_manager_; + content::TestWebUI web_ui_; + + Profile* profile_; + std::unique_ptr<TestManageProfileHandler> handler_; + + void VerifyIconList(const base::Value* value, + size_t selected_index, + bool all_not_selected) { const base::ListValue* icons = nullptr; ASSERT_TRUE(value->GetAsList(&icons)); @@ -61,20 +84,16 @@ class ManageProfileHandlerTest : public testing::Test { std::string icon_label; EXPECT_TRUE(icon->GetString("label", &icon_label)); EXPECT_FALSE(icon_label.empty()); + bool icon_selected; + bool has_icon_selected = icon->GetBoolean("selected", &icon_selected); + if (all_not_selected) { + EXPECT_FALSE(has_icon_selected); + } else if (selected_index == i) { + EXPECT_TRUE(has_icon_selected); + EXPECT_TRUE(icon_selected); + } } } - - content::TestWebUI* web_ui() { return &web_ui_; } - Profile* profile() const { return profile_; } - TestManageProfileHandler* handler() const { return handler_.get(); } - - private: - content::TestBrowserThreadBundle thread_bundle_; - TestingProfileManager profile_manager_; - content::TestWebUI web_ui_; - - Profile* profile_; - std::unique_ptr<TestManageProfileHandler> handler_; }; TEST_F(ManageProfileHandlerTest, HandleSetProfileIconToGaiaAvatar) { @@ -106,6 +125,30 @@ TEST_F(ManageProfileHandlerTest, HandleSetProfileName) { } TEST_F(ManageProfileHandlerTest, HandleGetAvailableIcons) { + PrefService* pref_service = profile()->GetPrefs(); + pref_service->SetInteger(prefs::kProfileAvatarIndex, 7); + + base::ListValue list_args_1; + list_args_1.AppendString("get-icons-callback-id"); + handler()->HandleGetAvailableIcons(&list_args_1); + + EXPECT_EQ(1U, web_ui()->call_data().size()); + + const content::TestWebUI::CallData& data_1 = *web_ui()->call_data().back(); + EXPECT_EQ("cr.webUIResponse", data_1.function_name()); + + std::string callback_id_1; + ASSERT_TRUE(data_1.arg1()->GetAsString(&callback_id_1)); + EXPECT_EQ("get-icons-callback-id", callback_id_1); + + VerifyIconListWithSingleSelection(data_1.arg3(), 7); +} + +TEST_F(ManageProfileHandlerTest, HandleGetAvailableIconsGaiaAvatarSelected) { + PrefService* pref_service = profile()->GetPrefs(); + pref_service->SetInteger(prefs::kProfileAvatarIndex, 7); + pref_service->SetBoolean(prefs::kProfileUsingGAIAAvatar, true); + base::ListValue list_args; list_args.AppendString("get-icons-callback-id"); handler()->HandleGetAvailableIcons(&list_args); @@ -119,10 +162,13 @@ TEST_F(ManageProfileHandlerTest, HandleGetAvailableIcons) { ASSERT_TRUE(data.arg1()->GetAsString(&callback_id)); EXPECT_EQ("get-icons-callback-id", callback_id); - VerifyIconList(data.arg3()); + VerifyIconListWithNoneSelected(data.arg3()); } TEST_F(ManageProfileHandlerTest, ProfileAvatarChangedWebUIEvent) { + PrefService* pref_service = profile()->GetPrefs(); + pref_service->SetInteger(prefs::kProfileAvatarIndex, 12); + handler()->OnProfileAvatarChanged(base::FilePath()); EXPECT_EQ(1U, web_ui()->call_data().size()); @@ -133,8 +179,7 @@ TEST_F(ManageProfileHandlerTest, ProfileAvatarChangedWebUIEvent) { std::string event_id; ASSERT_TRUE(data.arg1()->GetAsString(&event_id)); EXPECT_EQ("available-icons-changed", event_id); - - VerifyIconList(data.arg2()); + VerifyIconListWithSingleSelection(data.arg2(), 12); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.cc index 17987af0a56..9c91e087592 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.cc @@ -46,12 +46,16 @@ void MediaDevicesSelectionHandler::OnJavascriptDisallowed() { } void MediaDevicesSelectionHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("getDefaultCaptureDevices", - base::Bind(&MediaDevicesSelectionHandler::GetDefaultCaptureDevices, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("setDefaultCaptureDevice", - base::Bind(&MediaDevicesSelectionHandler::SetDefaultCaptureDevice, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getDefaultCaptureDevices", + base::BindRepeating( + &MediaDevicesSelectionHandler::GetDefaultCaptureDevices, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "setDefaultCaptureDevice", + base::BindRepeating( + &MediaDevicesSelectionHandler::SetDefaultCaptureDevice, + base::Unretained(this))); } void MediaDevicesSelectionHandler::OnUpdateAudioDevices( diff --git a/chromium/chrome/browser/ui/webui/settings/settings_startup_pages_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_startup_pages_handler.cc index 4b128752b02..36037ef3dc4 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_startup_pages_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_startup_pages_handler.cc @@ -29,21 +29,27 @@ void StartupPagesHandler::RegisterMessages() { if (Profile::FromWebUI(web_ui())->IsOffTheRecord()) return; - web_ui()->RegisterMessageCallback("addStartupPage", - base::Bind(&StartupPagesHandler::HandleAddStartupPage, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("editStartupPage", - base::Bind(&StartupPagesHandler::HandleEditStartupPage, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("onStartupPrefsPageLoad", - base::Bind(&StartupPagesHandler::HandleOnStartupPrefsPageLoad, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("removeStartupPage", - base::Bind(&StartupPagesHandler::HandleRemoveStartupPage, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("setStartupPagesToCurrentPages", - base::Bind(&StartupPagesHandler::HandleSetStartupPagesToCurrentPages, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "addStartupPage", + base::BindRepeating(&StartupPagesHandler::HandleAddStartupPage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "editStartupPage", + base::BindRepeating(&StartupPagesHandler::HandleEditStartupPage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "onStartupPrefsPageLoad", + base::BindRepeating(&StartupPagesHandler::HandleOnStartupPrefsPageLoad, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "removeStartupPage", + base::BindRepeating(&StartupPagesHandler::HandleRemoveStartupPage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "setStartupPagesToCurrentPages", + base::BindRepeating( + &StartupPagesHandler::HandleSetStartupPagesToCurrentPages, + base::Unretained(this))); } void StartupPagesHandler::OnJavascriptAllowed() { diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc index c413d8569ab..10862aa2adc 100644 --- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc @@ -46,7 +46,7 @@ #include "extensions/common/permissions/api_permission.h" #include "extensions/common/permissions/permissions_data.h" #include "storage/browser/quota/quota_manager.h" -#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h" +#include "third_party/blink/public/mojom/quota/quota_types.mojom.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/text/bytes_formatting.h" @@ -125,70 +125,75 @@ SiteSettingsHandler::~SiteSettingsHandler() { void SiteSettingsHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "fetchUsageTotal", - base::Bind(&SiteSettingsHandler::HandleFetchUsageTotal, - base::Unretained(this))); + base::BindRepeating(&SiteSettingsHandler::HandleFetchUsageTotal, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "clearUsage", - base::Bind(&SiteSettingsHandler::HandleClearUsage, - base::Unretained(this))); + "clearUsage", base::BindRepeating(&SiteSettingsHandler::HandleClearUsage, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "fetchUsbDevices", - base::Bind(&SiteSettingsHandler::HandleFetchUsbDevices, - base::Unretained(this))); + base::BindRepeating(&SiteSettingsHandler::HandleFetchUsbDevices, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "removeUsbDevice", - base::Bind(&SiteSettingsHandler::HandleRemoveUsbDevice, - base::Unretained(this))); + base::BindRepeating(&SiteSettingsHandler::HandleRemoveUsbDevice, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setDefaultValueForContentType", - base::Bind(&SiteSettingsHandler::HandleSetDefaultValueForContentType, - base::Unretained(this))); + base::BindRepeating( + &SiteSettingsHandler::HandleSetDefaultValueForContentType, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getDefaultValueForContentType", - base::Bind(&SiteSettingsHandler::HandleGetDefaultValueForContentType, - base::Unretained(this))); + base::BindRepeating( + &SiteSettingsHandler::HandleGetDefaultValueForContentType, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getExceptionList", - base::Bind(&SiteSettingsHandler::HandleGetExceptionList, - base::Unretained(this))); + base::BindRepeating(&SiteSettingsHandler::HandleGetExceptionList, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getOriginPermissions", - base::Bind(&SiteSettingsHandler::HandleGetOriginPermissions, - base::Unretained(this))); + base::BindRepeating(&SiteSettingsHandler::HandleGetOriginPermissions, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setOriginPermissions", - base::Bind(&SiteSettingsHandler::HandleSetOriginPermissions, - base::Unretained(this))); + base::BindRepeating(&SiteSettingsHandler::HandleSetOriginPermissions, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "clearFlashPref", base::Bind(&SiteSettingsHandler::HandleClearFlashPref, - base::Unretained(this))); + "clearFlashPref", + base::BindRepeating(&SiteSettingsHandler::HandleClearFlashPref, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "resetCategoryPermissionForPattern", - base::Bind(&SiteSettingsHandler::HandleResetCategoryPermissionForPattern, - base::Unretained(this))); + base::BindRepeating( + &SiteSettingsHandler::HandleResetCategoryPermissionForPattern, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "setCategoryPermissionForPattern", - base::Bind(&SiteSettingsHandler::HandleSetCategoryPermissionForPattern, - base::Unretained(this))); + base::BindRepeating( + &SiteSettingsHandler::HandleSetCategoryPermissionForPattern, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "isOriginValid", base::Bind(&SiteSettingsHandler::HandleIsOriginValid, - base::Unretained(this))); + "isOriginValid", + base::BindRepeating(&SiteSettingsHandler::HandleIsOriginValid, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "isPatternValid", - base::Bind(&SiteSettingsHandler::HandleIsPatternValid, - base::Unretained(this))); + base::BindRepeating(&SiteSettingsHandler::HandleIsPatternValid, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "updateIncognitoStatus", - base::Bind(&SiteSettingsHandler::HandleUpdateIncognitoStatus, - base::Unretained(this))); + base::BindRepeating(&SiteSettingsHandler::HandleUpdateIncognitoStatus, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "fetchZoomLevels", - base::Bind(&SiteSettingsHandler::HandleFetchZoomLevels, - base::Unretained(this))); + base::BindRepeating(&SiteSettingsHandler::HandleFetchZoomLevels, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "removeZoomLevel", - base::Bind(&SiteSettingsHandler::HandleRemoveZoomLevel, - base::Unretained(this))); + base::BindRepeating(&SiteSettingsHandler::HandleRemoveZoomLevel, + base::Unretained(this))); } void SiteSettingsHandler::OnJavascriptAllowed() { @@ -780,6 +785,7 @@ void SiteSettingsHandler::HandleIsOriginValid(const base::ListValue* args) { void SiteSettingsHandler::HandleIsPatternValid( const base::ListValue* args) { + AllowJavascript(); CHECK_EQ(2U, args->GetSize()); const base::Value* callback_id; CHECK(args->Get(0, &callback_id)); diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h index 01be8c4849d..9c78d451b85 100644 --- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h @@ -16,8 +16,8 @@ #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" -#include "ppapi/features/features.h" -#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h" +#include "ppapi/buildflags/buildflags.h" +#include "third_party/blink/public/mojom/quota/quota_types.mojom.h" class HostContentSettingsMap; class Profile; diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc index 7e40e5e5081..6efafe49981 100644 --- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc @@ -31,7 +31,7 @@ #include "content/public/test/test_web_ui.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension_builder.h" -#include "ppapi/features/features.h" +#include "ppapi/buildflags/buildflags.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_CHROMEOS) diff --git a/chromium/chrome/browser/ui/webui/settings/system_handler.cc b/chromium/chrome/browser/ui/webui/settings/system_handler.cc index c87ab9fe623..7c7082779b9 100644 --- a/chromium/chrome/browser/ui/webui/settings/system_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/system_handler.cc @@ -28,8 +28,9 @@ void SystemHandler::AddLoadTimeData(content::WebUIDataSource* data_source) { void SystemHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "showProxySettings", base::Bind(&SystemHandler::HandleShowProxySettings, - base::Unretained(this))); + "showProxySettings", + base::BindRepeating(&SystemHandler::HandleShowProxySettings, + base::Unretained(this))); } void SystemHandler::HandleShowProxySettings(const base::ListValue* /*args*/) { diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc new file mode 100644 index 00000000000..fcb19846e6a --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc @@ -0,0 +1,52 @@ +// 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/webui/settings/tts_handler.h" + +#include "base/bind.h" +#include "base/values.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/speech/tts_controller_impl.h" +#include "chrome/common/extensions/extension_constants.h" +#include "content/public/browser/web_ui.h" +#include "ui/base/l10n/l10n_util.h" + +namespace settings { + +void TtsHandler::HandleGetGoogleTtsVoiceData(const base::ListValue* args) { + OnVoicesChanged(); +} + +void TtsHandler::OnVoicesChanged() { + TtsControllerImpl* impl = TtsControllerImpl::GetInstance(); + std::vector<VoiceData> voices; + impl->GetVoices(Profile::FromWebUI(web_ui()), &voices); + base::ListValue responses; + for (const auto& voice : voices) { + if (voice.extension_id != extension_misc::kSpeechSynthesisExtensionId) + continue; + + base::DictionaryValue response; + response.SetPath({"name"}, base::Value(voice.name)); + response.SetPath( + {"language"}, + base::Value(l10n_util::GetDisplayNameForLocale( + voice.lang, g_browser_process->GetApplicationLocale(), true))); + response.SetPath({"builtIn"}, base::Value(true)); + responses.GetList().push_back(std::move(response)); + } + AllowJavascript(); + CallJavascriptFunction("cr.webUIListenerCallback", + base::Value("google-voice-data-updated"), responses); +} + +void TtsHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "getGoogleTtsVoiceData", + base::BindRepeating(&TtsHandler::HandleGetGoogleTtsVoiceData, + base::Unretained(this))); +} + +} // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.h b/chromium/chrome/browser/ui/webui/settings/tts_handler.h new file mode 100644 index 00000000000..36e76c5a592 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.h @@ -0,0 +1,35 @@ +// 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_WEBUI_SETTINGS_TTS_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_TTS_HANDLER_H_ + +#include "chrome/browser/speech/tts_controller.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" + +namespace settings { + +// Chrome "/manageAccessibility/tts/*" settings page UI handler. +class TtsHandler : public SettingsPageUIHandler, public VoicesChangedDelegate { + public: + TtsHandler() = default; + ~TtsHandler() override = default; + + void HandleGetGoogleTtsVoiceData(const base::ListValue* args); + + // SettingsPageUIHandler implementation. + void RegisterMessages() override; + void OnJavascriptAllowed() override {} + void OnJavascriptDisallowed() override {} + + // VoicesChangedDelegate implementation. + void OnVoicesChanged() override; + + private: + DISALLOW_COPY_AND_ASSIGN(TtsHandler); +}; + +} // namespace settings + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_TTS_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/settings_utils_linux.cc b/chromium/chrome/browser/ui/webui/settings_utils_linux.cc index ae3ef2a5ab8..7cf91d35e41 100644 --- a/chromium/chrome/browser/ui/webui/settings_utils_linux.cc +++ b/chromium/chrome/browser/ui/webui/settings_utils_linux.cc @@ -81,7 +81,7 @@ bool StartProxyConfigUtil(const char* const command[]) { LOG(ERROR) << "StartProxyConfigUtil failed to start " << command[0]; return false; } - base::EnsureProcessGetsReaped(process.Pid()); + base::EnsureProcessGetsReaped(std::move(process)); return true; } diff --git a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc index 707c0a05630..f58263abf99 100644 --- a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc +++ b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc @@ -49,6 +49,7 @@ AccountInfo GetAccountInfo(Profile* profile, const std::string& account_id) { DiceTurnSyncOnHelper::DiceTurnSyncOnHelper( Profile* profile, signin_metrics::AccessPoint signin_access_point, + signin_metrics::PromoAction signin_promo_action, signin_metrics::Reason signin_reason, const std::string& account_id, SigninAbortedMode signin_aborted_mode, @@ -58,6 +59,7 @@ DiceTurnSyncOnHelper::DiceTurnSyncOnHelper( signin_manager_(SigninManagerFactory::GetForProfile(profile)), token_service_(ProfileOAuth2TokenServiceFactory::GetForProfile(profile)), signin_access_point_(signin_access_point), + signin_promo_action_(signin_promo_action), signin_reason_(signin_reason), signin_aborted_mode_(signin_aborted_mode), account_info_(GetAccountInfo(profile, account_id)), @@ -65,14 +67,21 @@ DiceTurnSyncOnHelper::DiceTurnSyncOnHelper( DCHECK(delegate_); DCHECK(signin::IsDicePrepareMigrationEnabled()); DCHECK(profile_); - DCHECK(!account_info_.gaia.empty()); - DCHECK(!account_info_.email.empty()); // Should not start syncing if the profile is already authenticated DCHECK(!signin_manager_->IsAuthenticated()); // Force sign-in uses the modal sign-in flow. DCHECK(!signin_util::IsForceSigninEnabled()); + if (account_info_.gaia.empty() || account_info_.email.empty()) { + LOG(ERROR) << "Cannot turn Sync On for invalid account."; + base::SequencedTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); + return; + } + + DCHECK(!account_info_.gaia.empty()); + DCHECK(!account_info_.email.empty()); + if (HasCanOfferSigninError()) { // Do not self-destruct synchronously in the constructor. base::SequencedTaskRunnerHandle::Get()->PostTask( @@ -102,12 +111,14 @@ DiceTurnSyncOnHelper::DiceTurnSyncOnHelper( Profile* profile, Browser* browser, signin_metrics::AccessPoint signin_access_point, + signin_metrics::PromoAction signin_promo_action, signin_metrics::Reason signin_reason, const std::string& account_id, SigninAbortedMode signin_aborted_mode) : DiceTurnSyncOnHelper( profile, signin_access_point, + signin_promo_action, signin_reason, account_id, signin_aborted_mode, @@ -308,7 +319,8 @@ DiceTurnSyncOnHelper::GetProfileSyncService() { void DiceTurnSyncOnHelper::SigninAndShowSyncConfirmationUI() { // Signin. signin_manager_->OnExternalSigninCompleted(account_info_.email); - signin_metrics::LogSigninAccessPointCompleted(signin_access_point_); + signin_metrics::LogSigninAccessPointCompleted(signin_access_point_, + signin_promo_action_); signin_metrics::LogSigninReason(signin_reason_); base::RecordAction(base::UserMetricsAction("Signin_Signin_Succeed")); diff --git a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h index 6641331e0fc..28af6e6555a 100644 --- a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h +++ b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h @@ -95,6 +95,7 @@ class DiceTurnSyncOnHelper : public SyncStartupTracker::Observer { // in the token service. DiceTurnSyncOnHelper(Profile* profile, signin_metrics::AccessPoint signin_access_point, + signin_metrics::PromoAction signin_promo_action, signin_metrics::Reason signin_reason, const std::string& account_id, SigninAbortedMode signin_aborted_mode, @@ -104,6 +105,7 @@ class DiceTurnSyncOnHelper : public SyncStartupTracker::Observer { DiceTurnSyncOnHelper(Profile* profile, Browser* browser, signin_metrics::AccessPoint signin_access_point, + signin_metrics::PromoAction signin_promo_action, signin_metrics::Reason signin_reason, const std::string& account_id, SigninAbortedMode signin_aborted_mode); @@ -113,6 +115,8 @@ class DiceTurnSyncOnHelper : public SyncStartupTracker::Observer { void SyncStartupFailed() override; private: + friend class base::DeleteHelper<DiceTurnSyncOnHelper>; + enum class ProfileMode { // Attempts to sign the user in |profile_|. Note that if the account to be // signed in is a managed account, then a profile confirmation dialog is @@ -187,6 +191,7 @@ class DiceTurnSyncOnHelper : public SyncStartupTracker::Observer { SigninManager* signin_manager_; ProfileOAuth2TokenService* token_service_; const signin_metrics::AccessPoint signin_access_point_; + const signin_metrics::PromoAction signin_promo_action_; const signin_metrics::Reason signin_reason_; // Whether the refresh token should be deleted if the Sync flow is aborted. diff --git a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_delegate_impl.cc b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_delegate_impl.cc index c89424c5a6c..f22399432ab 100644 --- a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_delegate_impl.cc +++ b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_delegate_impl.cc @@ -168,7 +168,8 @@ void DiceTurnSyncOnHelperDelegateImpl::ShowSigninPageInNewProfile( Browser* browser = chrome::FindTabbedBrowser(new_profile, false); browser->signin_view_controller()->ShowDiceSigninTab( profiles::BUBBLE_VIEW_MODE_GAIA_SIGNIN, browser, - signin_metrics::AccessPoint::ACCESS_POINT_START_PAGE, username); + signin_metrics::AccessPoint::ACCESS_POINT_START_PAGE, + signin_metrics::PromoAction::PROMO_ACTION_NO_SIGNIN_PROMO, username); } void DiceTurnSyncOnHelperDelegateImpl::OnSyncConfirmationUIClosed( diff --git a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc index ec518a4c526..7f134e11654 100644 --- a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc +++ b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc @@ -53,6 +53,8 @@ const char kEnterpriseGaiaID[] = "enterprise_gaia_id"; const signin_metrics::AccessPoint kAccessPoint = signin_metrics::AccessPoint::ACCESS_POINT_BOOKMARK_MANAGER; +const signin_metrics::PromoAction kSigninPromoAction = + signin_metrics::PromoAction::PROMO_ACTION_WITH_DEFAULT; const signin_metrics::Reason kSigninReason = signin_metrics::Reason::REASON_REAUTHENTICATION; @@ -224,8 +226,8 @@ class DiceTurnSyncOnHelperTest : public testing::Test { DiceTurnSyncOnHelper* CreateDiceTurnOnSyncHelper( DiceTurnSyncOnHelper::SigninAbortedMode mode) { return new DiceTurnSyncOnHelper( - profile(), kAccessPoint, kSigninReason, account_id_, mode, - std::make_unique<TestDiceTurnSyncOnHelperDelegate>(this)); + profile(), kAccessPoint, kSigninPromoAction, kSigninReason, account_id_, + mode, std::make_unique<TestDiceTurnSyncOnHelperDelegate>(this)); } void UseEnterpriseAccount() { @@ -235,6 +237,8 @@ class DiceTurnSyncOnHelperTest : public testing::Test { token_service_->UpdateCredentials(account_id_, "enterprise_refresh_token"); } + void UseInvalidAccount() { account_id_ = "invalid_account"; } + void SetExpectationsForSyncStartupCompleted() { browser_sync::ProfileSyncServiceMock* sync_service_mock = GetProfileSyncServiceMock(); @@ -431,6 +435,15 @@ void TestDiceTurnSyncOnHelperDelegate::ShowSigninPageInNewProfile( test_fixture_->OnShowSigninPageInNewProfile(new_profile, username); } +// Check that the invalid account is supported. +TEST_F(DiceTurnSyncOnHelperTest, InvalidAccount) { + UseInvalidAccount(); + CreateDiceTurnOnSyncHelper( + DiceTurnSyncOnHelper::SigninAbortedMode::REMOVE_ACCOUNT); + base::RunLoop().RunUntilIdle(); + CheckDelegateCalls(); +} + // Tests that the login error is displayed and that the account is kept. TEST_F(DiceTurnSyncOnHelperTest, CanOfferSigninErrorKeepAccount) { // Set expectations. diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc index 89c7c4320e4..6edb4d36f30 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc @@ -37,22 +37,25 @@ InlineLoginHandler::InlineLoginHandler() : weak_ptr_factory_(this) {} InlineLoginHandler::~InlineLoginHandler() {} void InlineLoginHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("initialize", - base::Bind(&InlineLoginHandler::HandleInitializeMessage, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("completeLogin", - base::Bind(&InlineLoginHandler::HandleCompleteLoginMessage, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "initialize", + base::BindRepeating(&InlineLoginHandler::HandleInitializeMessage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "completeLogin", + base::BindRepeating(&InlineLoginHandler::HandleCompleteLoginMessage, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "switchToFullTab", - base::Bind(&InlineLoginHandler::HandleSwitchToFullTabMessage, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("navigationButtonClicked", - base::Bind(&InlineLoginHandler::HandleNavigationButtonClicked, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("dialogClose", - base::Bind(&InlineLoginHandler::HandleDialogClose, - base::Unretained(this))); + base::BindRepeating(&InlineLoginHandler::HandleSwitchToFullTabMessage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "navigationButtonClicked", + base::BindRepeating(&InlineLoginHandler::HandleNavigationButtonClicked, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "dialogClose", base::BindRepeating(&InlineLoginHandler::HandleDialogClose, + base::Unretained(this))); } void InlineLoginHandler::HandleInitializeMessage(const base::ListValue* args) { @@ -105,8 +108,12 @@ void InlineLoginHandler::ContinueHandleInitializeMessage() { if (reason != signin_metrics::Reason::REASON_REAUTHENTICATION && reason != signin_metrics::Reason::REASON_UNLOCK && reason != signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT) { - signin_metrics::LogSigninAccessPointStarted(access_point); - signin_metrics::RecordSigninUserActionForAccessPoint(access_point); + signin_metrics::LogSigninAccessPointStarted( + access_point, + signin_metrics::PromoAction::PROMO_ACTION_NO_SIGNIN_PROMO); + signin_metrics::RecordSigninUserActionForAccessPoint( + access_point, + signin_metrics::PromoAction::PROMO_ACTION_NO_SIGNIN_PROMO); base::RecordAction(base::UserMetricsAction("Signin_SigninPage_Loading")); params.SetBoolean("isLoginPrimaryAccount", true); } diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc index b98fde04295..93fe4d5a4a1 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc @@ -202,10 +202,8 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( Profile::CreateStatus status) { if (is_force_sign_in_with_usermanager_) UnlockProfileAndHideLoginUI(profile_->GetPath(), handler_.get()); - content::WebContents* contents = NULL; Browser* browser = NULL; if (handler_) { - contents = handler_->web_ui()->GetWebContents(); browser = handler_->GetDesktopBrowser(); } diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_ui_browsertest.cc index 4911e8662fe..0a14718d1d8 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui_browsertest.cc @@ -340,7 +340,7 @@ IN_PROC_BROWSER_TEST_F(InlineLoginUIBrowserTest, MAYBE_DifferentStorageId) { std::set<content::WebContents*> set; GuestViewManager* manager = GuestViewManager::FromBrowserContext( info.contents->GetBrowserContext()); - manager->ForEachGuest(info.contents, base::Bind(&AddToSet, &set)); + manager->ForEachGuest(info.contents, base::BindRepeating(&AddToSet, &set)); ASSERT_EQ(1u, set.size()); content::WebContents* webview_contents = *set.begin(); content::RenderProcessHost* process = diff --git a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc index 2ce9d8cbab1..82cb431d651 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc @@ -159,27 +159,30 @@ void SigninCreateProfileHandler::RegisterMessages() { // Cancellation is only supported for supervised users. web_ui()->RegisterMessageCallback( "cancelCreateProfile", - base::Bind(&SigninCreateProfileHandler::HandleCancelProfileCreation, - base::Unretained(this))); + base::BindRepeating( + &SigninCreateProfileHandler::HandleCancelProfileCreation, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "switchToProfile", - base::Bind(&SigninCreateProfileHandler::SwitchToProfile, - base::Unretained(this))); + base::BindRepeating(&SigninCreateProfileHandler::SwitchToProfile, + base::Unretained(this))); #endif web_ui()->RegisterMessageCallback( - "createProfile", base::Bind(&SigninCreateProfileHandler::CreateProfile, - base::Unretained(this))); + "createProfile", + base::BindRepeating(&SigninCreateProfileHandler::CreateProfile, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestDefaultProfileIcons", - base::Bind(&SigninCreateProfileHandler::RequestDefaultProfileIcons, - base::Unretained(this))); + base::BindRepeating( + &SigninCreateProfileHandler::RequestDefaultProfileIcons, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestSignedInProfiles", - base::Bind(&SigninCreateProfileHandler::RequestSignedInProfiles, - base::Unretained(this))); + base::BindRepeating(&SigninCreateProfileHandler::RequestSignedInProfiles, + base::Unretained(this))); } void SigninCreateProfileHandler::RequestDefaultProfileIcons( @@ -477,10 +480,10 @@ void SigninCreateProfileHandler::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { - DCHECK_EQ(chrome::NOTIFICATION_BROWSER_WINDOW_READY, type); + DCHECK_EQ(chrome::NOTIFICATION_BROWSER_OPENED, type); - // Only respond to one Browser Window Ready event. - registrar_.Remove(this, chrome::NOTIFICATION_BROWSER_WINDOW_READY, + // Only respond to one Browser Opened event. + registrar_.Remove(this, chrome::NOTIFICATION_BROWSER_OPENED, content::NotificationService::AllSources()); UserManager::Hide(); } @@ -494,8 +497,7 @@ void SigninCreateProfileHandler::OnBrowserReadyCallback( if (browser && browser->window()) { UserManager::Hide(); } else { - registrar_.Add(this, - chrome::NOTIFICATION_BROWSER_WINDOW_READY, + registrar_.Add(this, chrome::NOTIFICATION_BROWSER_OPENED, content::NotificationService::AllSources()); } } @@ -737,9 +739,9 @@ void SigninCreateProfileHandler::RegisterSupervisedUser( supervised_user_service->RegisterAndInitSync( supervised_user_registration_utility_.get(), custodian_profile, supervised_user_id, - base::Bind(&SigninCreateProfileHandler::OnSupervisedUserRegistered, - weak_ptr_factory_.GetWeakPtr(), create_shortcut, - custodian_profile, new_profile)); + base::BindOnce(&SigninCreateProfileHandler::OnSupervisedUserRegistered, + weak_ptr_factory_.GetWeakPtr(), create_shortcut, + custodian_profile, new_profile)); } } diff --git a/chromium/chrome/browser/ui/webui/signin/signin_error_handler.cc b/chromium/chrome/browser/ui/webui/signin/signin_error_handler.cc index 6824d82f41e..8bda6fa9869 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_error_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_error_handler.cc @@ -34,21 +34,21 @@ void SigninErrorHandler::OnBrowserRemoved(Browser* browser) { void SigninErrorHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "confirm", - base::Bind(&SigninErrorHandler::HandleConfirm, base::Unretained(this))); + "confirm", base::BindRepeating(&SigninErrorHandler::HandleConfirm, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "switchToExistingProfile", - base::Bind(&SigninErrorHandler::HandleSwitchToExistingProfile, - base::Unretained(this))); + base::BindRepeating(&SigninErrorHandler::HandleSwitchToExistingProfile, + base::Unretained(this))); if (!is_system_profile_) { web_ui()->RegisterMessageCallback( - "learnMore", base::Bind(&SigninErrorHandler::HandleLearnMore, - base::Unretained(this))); + "learnMore", base::BindRepeating(&SigninErrorHandler::HandleLearnMore, + base::Unretained(this))); } web_ui()->RegisterMessageCallback( "initializedWithSize", - base::Bind(&SigninErrorHandler::HandleInitializedWithSize, - base::Unretained(this))); + base::BindRepeating(&SigninErrorHandler::HandleInitializedWithSize, + base::Unretained(this))); } void SigninErrorHandler::HandleSwitchToExistingProfile( diff --git a/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc b/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc index 7b1e9041935..3de3a5d1886 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc @@ -11,6 +11,7 @@ #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/signin/signin_ui_util.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/user_manager.h" @@ -84,9 +85,12 @@ void SigninErrorUI::Initialize(Browser* browser, bool is_system_profile) { } else if (email.empty()) { source->AddLocalizedString("signinErrorTitle", IDS_SIGNIN_ERROR_TITLE); } else { - source->AddString( - "signinErrorTitle", - l10n_util::GetStringFUTF16(IDS_SIGNIN_ERROR_EMAIL_TITLE, email)); + int title_string_id = + AccountConsistencyModeManager::IsDiceEnabledForProfile(signin_profile) + ? IDS_SIGNIN_ERROR_DICE_EMAIL_TITLE + : IDS_SIGNIN_ERROR_EMAIL_TITLE; + source->AddString("signinErrorTitle", + l10n_util::GetStringFUTF16(title_string_id, email)); } source->AddString("signinErrorMessage", base::string16()); diff --git a/chromium/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.cc b/chromium/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.cc index f7e115ff656..1de21e772db 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.cc @@ -70,20 +70,24 @@ void SigninSupervisedUserImportHandler::GetLocalizedValues( } void SigninSupervisedUserImportHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("getExistingSupervisedUsers", - base::Bind(&SigninSupervisedUserImportHandler::GetExistingSupervisedUsers, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("openUrlInLastActiveProfileBrowser", - base::Bind( + web_ui()->RegisterMessageCallback( + "getExistingSupervisedUsers", + base::BindRepeating( + &SigninSupervisedUserImportHandler::GetExistingSupervisedUsers, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "openUrlInLastActiveProfileBrowser", + base::BindRepeating( &SigninSupervisedUserImportHandler::OpenUrlInLastActiveProfileBrowser, base::Unretained(this))); web_ui()->RegisterMessageCallback( "authenticateCustodian", - base::Bind(&SigninSupervisedUserImportHandler::AuthenticateCustodian, - base::Unretained(this))); + base::BindRepeating( + &SigninSupervisedUserImportHandler::AuthenticateCustodian, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "cancelLoadingSupervisedUsers", - base::Bind( + base::BindRepeating( &SigninSupervisedUserImportHandler::HandleCancelLoadSupervisedUsers, base::Unretained(this))); } diff --git a/chromium/chrome/browser/ui/webui/signin/signin_utils.cc b/chromium/chrome/browser/ui/webui/signin/signin_utils.cc index d6d78cd206f..fe6891025e6 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_utils.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_utils.cc @@ -43,9 +43,9 @@ content::WebContents* GetAuthFrameWebContents( auto* manager = guest_view::GuestViewManager::FromBrowserContext( web_contents->GetBrowserContext()); if (manager) { - manager->ForEachGuest( - web_contents, - base::Bind(&AddWebContentsToSet, &frame_set, parent_frame_name)); + manager->ForEachGuest(web_contents, + base::BindRepeating(&AddWebContentsToSet, &frame_set, + parent_frame_name)); } DCHECK_GE(1U, frame_set.size()); if (!frame_set.empty()) diff --git a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc index e2ed758f0ee..e4718068ef1 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc @@ -59,17 +59,20 @@ void SyncConfirmationHandler::OnBrowserRemoved(Browser* browser) { } void SyncConfirmationHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("confirm", - base::Bind(&SyncConfirmationHandler::HandleConfirm, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("undo", - base::Bind(&SyncConfirmationHandler::HandleUndo, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "goToSettings", base::Bind(&SyncConfirmationHandler::HandleGoToSettings, - base::Unretained(this))); - web_ui()->RegisterMessageCallback("initializedWithSize", - base::Bind(&SyncConfirmationHandler::HandleInitializedWithSize, - base::Unretained(this))); + "confirm", base::BindRepeating(&SyncConfirmationHandler::HandleConfirm, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "undo", base::BindRepeating(&SyncConfirmationHandler::HandleUndo, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "goToSettings", + base::BindRepeating(&SyncConfirmationHandler::HandleGoToSettings, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "initializedWithSize", + base::BindRepeating(&SyncConfirmationHandler::HandleInitializedWithSize, + base::Unretained(this))); } void SyncConfirmationHandler::HandleConfirm(const base::ListValue* args) { @@ -114,6 +117,8 @@ void SyncConfirmationHandler::RecordConsent(const base::ListValue* args) { int consent_confirmation_id = iter->second; ConsentAuditorFactory::GetForProfile(profile_)->RecordGaiaConsent( + SigninManagerFactory::GetForProfile(profile_) + ->GetAuthenticatedAccountId(), consent_auditor::Feature::CHROME_SYNC, consent_text_ids, consent_confirmation_id, consent_auditor::ConsentStatus::GIVEN); } diff --git a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc index 28843bfe753..d9b4a32ca2e 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc @@ -11,6 +11,7 @@ #include "base/test/user_action_tester.h" #include "base/values.h" #include "chrome/browser/consent_auditor/consent_auditor_factory.h" +#include "chrome/browser/consent_auditor/consent_auditor_test_utils.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/signin/account_fetcher_service_factory.h" #include "chrome/browser/signin/account_tracker_service_factory.h" @@ -18,7 +19,6 @@ #include "chrome/browser/signin/fake_signin_manager_builder.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" -#include "chrome/browser/sync/user_event_service_factory.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/webui/signin/sync_confirmation_ui.h" @@ -26,7 +26,7 @@ #include "chrome/test/base/dialog_test_browser_window.h" #include "chrome/test/base/testing_profile.h" #include "components/browser_sync/profile_sync_service.h" -#include "components/consent_auditor/consent_auditor.h" +#include "components/consent_auditor/fake_consent_auditor.h" #include "components/signin/core/browser/account_fetcher_service.h" #include "components/signin/core/browser/avatar_icon_util.h" #include "components/signin/core/browser/fake_account_fetcher_service.h" @@ -40,10 +40,6 @@ const int kExpectedProfileImageSize = 128; // really matter in unit tests. const double kDefaultDialogHeight = 350.0; -const std::string kGaiaID = "gaia"; -const std::string kUsername = "foo@example.com"; -const std::string kPassword = "password"; - class TestingSyncConfirmationHandler : public SyncConfirmationHandler { public: TestingSyncConfirmationHandler( @@ -101,46 +97,13 @@ class TestingOneClickSigninSyncStarter : public OneClickSigninSyncStarter { DISALLOW_COPY_AND_ASSIGN(TestingOneClickSigninSyncStarter); }; -// TODO(msramek): Extract this into "consent_auditor_test_utils" for reusability -// and to remove unnecessary dependencies from this test. -class FakeConsentAuditor : public consent_auditor::ConsentAuditor { - public: - static std::unique_ptr<KeyedService> Build(content::BrowserContext* context) { - return std::make_unique<FakeConsentAuditor>( - Profile::FromBrowserContext(context)); - } - - FakeConsentAuditor(Profile* profile) - : ConsentAuditor( - profile->GetPrefs(), - browser_sync::UserEventServiceFactory::GetForProfile(profile), - std::string(), - std::string()) {} - ~FakeConsentAuditor() override {} - - void RecordGaiaConsent(consent_auditor::Feature feature, - const std::vector<int>& description_grd_ids, - int confirmation_grd_id, - consent_auditor::ConsentStatus status) override { - recorded_ids_ = description_grd_ids; - recorded_ids_.push_back(confirmation_grd_id); - } - - const std::vector<int>& recorded_ids() { return recorded_ids_; } - - private: - std::vector<int> recorded_ids_; - - DISALLOW_COPY_AND_ASSIGN(FakeConsentAuditor); -}; - class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest { public: - static const std::string kConsentText1; - static const std::string kConsentText2; - static const std::string kConsentText3; - static const std::string kConsentText4; - static const std::string kConsentText5; + static const char kConsentText1[]; + static const char kConsentText2[]; + static const char kConsentText3[]; + static const char kConsentText4[]; + static const char kConsentText5[]; SyncConfirmationHandlerTest() : did_user_explicitly_interact(false), web_ui_(new content::TestWebUI) {} @@ -206,8 +169,8 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest { return &user_action_tester_; } - FakeConsentAuditor* consent_auditor() { - return static_cast<FakeConsentAuditor*>( + consent_auditor::FakeConsentAuditor* consent_auditor() { + return static_cast<consent_auditor::FakeConsentAuditor*>( ConsentAuditorFactory::GetForProfile(profile())); } @@ -220,7 +183,7 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest { return {{AccountFetcherServiceFactory::GetInstance(), FakeAccountFetcherServiceBuilder::BuildForTests}, {SigninManagerFactory::GetInstance(), BuildFakeSigninManagerBase}, - {ConsentAuditorFactory::GetInstance(), FakeConsentAuditor::Build}}; + {ConsentAuditorFactory::GetInstance(), BuildFakeConsentAuditor}}; } const std::unordered_map<std::string, int>& GetStringToGrdIdMap() { @@ -247,11 +210,11 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest { DISALLOW_COPY_AND_ASSIGN(SyncConfirmationHandlerTest); }; -const std::string SyncConfirmationHandlerTest::kConsentText1 = "consentText1"; -const std::string SyncConfirmationHandlerTest::kConsentText2 = "consentText2"; -const std::string SyncConfirmationHandlerTest::kConsentText3 = "consentText3"; -const std::string SyncConfirmationHandlerTest::kConsentText4 = "consentText4"; -const std::string SyncConfirmationHandlerTest::kConsentText5 = "consentText5"; +const char SyncConfirmationHandlerTest::kConsentText1[] = "consentText1"; +const char SyncConfirmationHandlerTest::kConsentText2[] = "consentText2"; +const char SyncConfirmationHandlerTest::kConsentText3[] = "consentText3"; +const char SyncConfirmationHandlerTest::kConsentText4[] = "consentText4"; +const char SyncConfirmationHandlerTest::kConsentText5[] = "consentText5"; TEST_F(SyncConfirmationHandlerTest, TestSetImageIfPrimaryAccountReady) { account_fetcher_service()->FakeUserInfoFetchSuccess( @@ -420,8 +383,11 @@ TEST_F(SyncConfirmationHandlerTest, TestHandleConfirm) { "Signin_Signin_WithAdvancedSyncSettings")); // The corresponding string IDs get recorded. - std::vector<int> expected_ids = {1, 2, 4, 5}; - EXPECT_EQ(expected_ids, consent_auditor()->recorded_ids()); + std::vector<std::vector<int>> expected_id_vectors = {{1, 2, 4, 5}}; + EXPECT_EQ(expected_id_vectors, consent_auditor()->recorded_id_vectors()); + + EXPECT_EQ(signin_manager()->GetAuthenticatedAccountId(), + consent_auditor()->account_id()); } TEST_F(SyncConfirmationHandlerTest, TestHandleConfirmWithAdvancedSyncSettings) { @@ -459,6 +425,9 @@ TEST_F(SyncConfirmationHandlerTest, TestHandleConfirmWithAdvancedSyncSettings) { "Signin_Signin_WithAdvancedSyncSettings")); // The corresponding string IDs get recorded. - std::vector<int> expected_ids = {2, 3, 5, 2}; - EXPECT_EQ(expected_ids, consent_auditor()->recorded_ids()); + std::vector<std::vector<int>> expected_id_vectors = {{2, 3, 5, 2}}; + EXPECT_EQ(expected_id_vectors, consent_auditor()->recorded_id_vectors()); + + EXPECT_EQ(signin_manager()->GetAuthenticatedAccountId(), + consent_auditor()->account_id()); } diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc b/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc index 8642979e27a..13b02da26c2 100644 --- a/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc @@ -21,7 +21,6 @@ #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/extensions/api/screenlock_private/screenlock_private_api.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" @@ -34,7 +33,6 @@ #include "chrome/browser/profiles/profiles_state.h" #include "chrome/browser/signin/local_auth.h" #include "chrome/browser/signin/signin_util.h" -#include "chrome/browser/ui/app_list/app_list_service.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/browser_finder.h" @@ -168,8 +166,8 @@ void UrlHashHelper::OnBrowserRemoved(Browser* browser) { void UrlHashHelper::ExecuteUrlHash() { if (hash_ == profiles::kUserManagerSelectProfileAppLauncher) { - AppListService* app_list_service = AppListService::Get(); - app_list_service->ShowForProfile(profile_); + // TODO(crbug/821659): Clean up the desktop UserManager webui. + NOTIMPLEMENTED(); return; } @@ -303,83 +301,7 @@ UserManagerScreenHandler::UserManagerScreenHandler() : weak_ptr_factory_(this) { } } -UserManagerScreenHandler::~UserManagerScreenHandler() { - proximity_auth::ScreenlockBridge::Get()->SetLockHandler(NULL); -} - -void UserManagerScreenHandler::ShowBannerMessage( - const base::string16& message) { - web_ui()->CallJavascriptFunctionUnsafe( - "login.AccountPickerScreen.showBannerMessage", base::Value(message)); -} - -void UserManagerScreenHandler::ShowUserPodCustomIcon( - const AccountId& account_id, - const proximity_auth::ScreenlockBridge::UserPodCustomIconOptions& - icon_options) { - std::unique_ptr<base::DictionaryValue> icon = - icon_options.ToDictionaryValue(); - if (!icon || icon->empty()) - return; - web_ui()->CallJavascriptFunctionUnsafe( - "login.AccountPickerScreen.showUserPodCustomIcon", - base::Value(account_id.GetUserEmail()), *icon); -} - -void UserManagerScreenHandler::HideUserPodCustomIcon( - const AccountId& account_id) { - web_ui()->CallJavascriptFunctionUnsafe( - "login.AccountPickerScreen.hideUserPodCustomIcon", - base::Value(account_id.GetUserEmail())); -} - -void UserManagerScreenHandler::EnableInput() { - // Nothing here because UI is not disabled when starting to authenticate. -} - -void UserManagerScreenHandler::SetAuthType( - const AccountId& account_id, - proximity_auth::mojom::AuthType auth_type, - const base::string16& auth_value) { - if (GetAuthType(account_id) == - proximity_auth::mojom::AuthType::FORCE_OFFLINE_PASSWORD) { - return; - } - - user_auth_type_map_[account_id.GetUserEmail()] = auth_type; - web_ui()->CallJavascriptFunctionUnsafe( - "login.AccountPickerScreen.setAuthType", - base::Value(account_id.GetUserEmail()), - base::Value(static_cast<int>(auth_type)), base::Value(auth_value)); -} - -proximity_auth::mojom::AuthType UserManagerScreenHandler::GetAuthType( - const AccountId& account_id) const { - const auto it = user_auth_type_map_.find(account_id.GetUserEmail()); - if (it == user_auth_type_map_.end()) - return proximity_auth::mojom::AuthType::OFFLINE_PASSWORD; - return it->second; -} - -proximity_auth::ScreenlockBridge::LockHandler::ScreenType -UserManagerScreenHandler::GetScreenType() const { - return proximity_auth::ScreenlockBridge::LockHandler::LOCK_SCREEN; -} - -void UserManagerScreenHandler::Unlock(const AccountId& account_id) { - const base::FilePath path = profiles::GetPathOfProfileWithEmail( - g_browser_process->profile_manager(), account_id.GetUserEmail()); - if (!path.empty()) { - authenticating_profile_path_ = path; - ReportAuthenticationResult(true, ProfileMetrics::AUTH_LOCAL); - } -} - -void UserManagerScreenHandler::AttemptEasySignin(const AccountId& account_id, - const std::string& secret, - const std::string& key_label) { - NOTREACHED(); -} +UserManagerScreenHandler::~UserManagerScreenHandler() {} void UserManagerScreenHandler::HandleInitialize(const base::ListValue* args) { // If the URL has a hash parameter, store it for later. @@ -389,8 +311,6 @@ void UserManagerScreenHandler::HandleInitialize(const base::ListValue* args) { web_ui()->CallJavascriptFunctionUnsafe( "cr.ui.UserManager.showUserManagerScreen", base::Value(IsGuestModeEnabled()), base::Value(IsAddPersonEnabled())); - - proximity_auth::ScreenlockBridge::Get()->SetLockHandler(this); } void UserManagerScreenHandler::HandleAuthenticatedLaunchUser( @@ -586,10 +506,6 @@ void UserManagerScreenHandler::HandleHardlockUserPod( std::string email; CHECK(args->GetString(0, &email)); const AccountId account_id = AccountId::FromUserEmail(email); - SetAuthType(account_id, - proximity_auth::mojom::AuthType::FORCE_OFFLINE_PASSWORD, - base::string16()); - HideUserPodCustomIcon(account_id); } void UserManagerScreenHandler::HandleRemoveUserWarningLoadStats( @@ -672,30 +588,39 @@ void UserManagerScreenHandler::OnNetworkError(int response_code) { } void UserManagerScreenHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback(kJsApiUserManagerInitialize, - base::Bind(&UserManagerScreenHandler::HandleInitialize, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kJsApiUserManagerAuthLaunchUser, - base::Bind(&UserManagerScreenHandler::HandleAuthenticatedLaunchUser, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kJsApiUserManagerLaunchGuest, - base::Bind(&UserManagerScreenHandler::HandleLaunchGuest, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kJsApiUserManagerLaunchUser, - base::Bind(&UserManagerScreenHandler::HandleLaunchUser, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kJsApiUserManagerRemoveUser, - base::Bind(&UserManagerScreenHandler::HandleRemoveUser, - base::Unretained(this))); - web_ui()->RegisterMessageCallback(kJsApiUserManagerLogRemoveUserWarningShown, - base::Bind(&HandleLogRemoveUserWarningShown)); - web_ui()->RegisterMessageCallback(kJsApiUserManagerRemoveUserWarningLoadStats, - base::Bind(&UserManagerScreenHandler::HandleRemoveUserWarningLoadStats, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiUserManagerInitialize, + base::BindRepeating(&UserManagerScreenHandler::HandleInitialize, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiUserManagerAuthLaunchUser, + base::BindRepeating( + &UserManagerScreenHandler::HandleAuthenticatedLaunchUser, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiUserManagerLaunchGuest, + base::BindRepeating(&UserManagerScreenHandler::HandleLaunchGuest, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiUserManagerLaunchUser, + base::BindRepeating(&UserManagerScreenHandler::HandleLaunchUser, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiUserManagerRemoveUser, + base::BindRepeating(&UserManagerScreenHandler::HandleRemoveUser, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kJsApiUserManagerLogRemoveUserWarningShown, + base::BindRepeating(&HandleLogRemoveUserWarningShown)); + web_ui()->RegisterMessageCallback( + kJsApiUserManagerRemoveUserWarningLoadStats, + base::BindRepeating( + &UserManagerScreenHandler::HandleRemoveUserWarningLoadStats, + base::Unretained(this))); web_ui()->RegisterMessageCallback( kJsApiUserManagerAreAllProfilesLocked, - base::Bind(&UserManagerScreenHandler::HandleAreAllProfilesLocked, - base::Unretained(this))); + base::BindRepeating(&UserManagerScreenHandler::HandleAreAllProfilesLocked, + base::Unretained(this))); // Unused callbacks from screen_account_picker.js web_ui()->RegisterMessageCallback("accountPickerReady", base::DoNothing()); @@ -862,7 +787,6 @@ void UserManagerScreenHandler::SendUserList() { std::vector<ProfileAttributesEntry*> entries = g_browser_process->profile_manager()->GetProfileAttributesStorage(). GetAllProfilesAttributesSortedByName(); - user_auth_type_map_.clear(); for (const ProfileAttributesEntry* entry : entries) { // Don't show profiles still in the middle of being set up as new legacy @@ -933,7 +857,7 @@ void UserManagerScreenHandler::ReportAuthenticationResult( } } -void UserManagerScreenHandler::OnBrowserWindowReady(Browser* browser) { +void UserManagerScreenHandler::OnBrowserOpened(Browser* browser) { DCHECK(browser); DCHECK(browser->window()); @@ -967,12 +891,12 @@ void UserManagerScreenHandler::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { - DCHECK_EQ(chrome::NOTIFICATION_BROWSER_WINDOW_READY, type); + DCHECK_EQ(chrome::NOTIFICATION_BROWSER_OPENED, type); - // Only respond to one Browser Window Ready event. - registrar_.Remove(this, chrome::NOTIFICATION_BROWSER_WINDOW_READY, + // Only respond to one Browser Opened event. + registrar_.Remove(this, chrome::NOTIFICATION_BROWSER_OPENED, content::NotificationService::AllSources()); - OnBrowserWindowReady(content::Source<Browser>(source).ptr()); + OnBrowserOpened(content::Source<Browser>(source).ptr()); } // This callback is run after switching to a new profile has finished. This @@ -984,10 +908,9 @@ void UserManagerScreenHandler::OnSwitchToProfileComplete( Profile* profile, Profile::CreateStatus profile_create_status) { Browser* browser = chrome::FindAnyBrowser(profile, false); if (browser && browser->window()) { - OnBrowserWindowReady(browser); + OnBrowserOpened(browser); } else { - registrar_.Add(this, - chrome::NOTIFICATION_BROWSER_WINDOW_READY, + registrar_.Add(this, chrome::NOTIFICATION_BROWSER_OPENED, content::NotificationService::AllSources()); } } diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h b/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h index 05d91b1bda5..eac65e54b00 100644 --- a/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h @@ -17,13 +17,11 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_statistics.h" -#include "components/proximity_auth/screenlock_bridge.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/web_ui_message_handler.h" #include "google_apis/gaia/gaia_oauth_client.h" -class AccountId; class Browser; namespace base { @@ -47,7 +45,6 @@ enum AuthenticatedLaunchUserEvent { class UserManagerScreenHandler : public content::WebUIMessageHandler, - public proximity_auth::ScreenlockBridge::LockHandler, public gaia::GaiaOAuthClient::Delegate, public content::NotificationObserver { public: @@ -69,25 +66,6 @@ class UserManagerScreenHandler const content::NotificationSource& source, const content::NotificationDetails& details) override; - // proximity_auth::ScreenlockBridge::LockHandler implementation. - void ShowBannerMessage(const base::string16& message) override; - void ShowUserPodCustomIcon( - const AccountId& account_id, - const proximity_auth::ScreenlockBridge::UserPodCustomIconOptions& - icon_options) override; - void HideUserPodCustomIcon(const AccountId& account_id) override; - void EnableInput() override; - void SetAuthType(const AccountId& account_id, - proximity_auth::mojom::AuthType auth_type, - const base::string16& auth_value) override; - proximity_auth::mojom::AuthType GetAuthType( - const AccountId& account_id) const override; - ScreenType GetScreenType() const override; - void Unlock(const AccountId& account_id) override; - void AttemptEasySignin(const AccountId& account_id, - const std::string& secret, - const std::string& key_label) override; - void HandleInitialize(const base::ListValue* args); void HandleAuthenticatedLaunchUser(const base::ListValue* args); void HandleLaunchGuest(const base::ListValue* args); @@ -113,8 +91,8 @@ class UserManagerScreenHandler void OnOAuthError() override; void OnNetworkError(int response_code) override; - // Handle when Notified of a NOTIFICATION_BROWSER_WINDOW_READY event. - void OnBrowserWindowReady(Browser* browser); + // Handle when Notified of a NOTIFICATION_BROWSER_OPENED event. + void OnBrowserOpened(Browser* browser); // Sends user list to account chooser. void SendUserList(); @@ -143,10 +121,6 @@ class UserManagerScreenHandler // URL hash, used to key post-profile actions if present. std::string url_hash_; - typedef std::map<std::string, proximity_auth::mojom::AuthType> - UserAuthTypeMap; - UserAuthTypeMap user_auth_type_map_; - content::NotificationRegistrar registrar_; // The CancelableTaskTracker is currently used by GetProfileStatistics diff --git a/chromium/chrome/browser/ui/webui/site_settings_helper.cc b/chromium/chrome/browser/ui/webui/site_settings_helper.cc index cf47f689458..c6e1e92baaf 100644 --- a/chromium/chrome/browser/ui/webui/site_settings_helper.cc +++ b/chromium/chrome/browser/ui/webui/site_settings_helper.cc @@ -76,6 +76,7 @@ const ContentSettingsTypeNameEntry kContentSettingsTypeGroupNames[] = { {CONTENT_SETTINGS_TYPE_CLIPBOARD_READ, "clipboard"}, {CONTENT_SETTINGS_TYPE_SENSORS, "sensors"}, {CONTENT_SETTINGS_TYPE_PAYMENT_HANDLER, "payment-handler"}, + {CONTENT_SETTINGS_TYPE_USB_GUARD, "usb-devices"}, // Add new content settings here if a corresponding Javascript string // representation for it is not required. Note some exceptions, such as @@ -182,8 +183,7 @@ SiteSettingSource CalculateSiteSettingSource( DCHECK_NE(content_settings::SETTING_SOURCE_NONE, info.source); if (info.source == content_settings::SETTING_SOURCE_USER) { - if (result.source == PermissionStatusSource::SAFE_BROWSING_BLACKLIST || - result.source == PermissionStatusSource::MULTIPLE_DISMISSALS || + if (result.source == PermissionStatusSource::MULTIPLE_DISMISSALS || result.source == PermissionStatusSource::MULTIPLE_IGNORES) { return SiteSettingSource::kEmbargo; // Source #8. } diff --git a/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.cc b/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.cc index 52527a8d360..a65c50f7034 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.cc @@ -27,7 +27,6 @@ #include "base/values.h" #include "chrome/browser/android/chrome_feature_list.h" #include "chrome/browser/android/ntp/android_content_suggestions_notifier.h" -#include "chrome/browser/ntp_snippets/content_suggestions_service_factory.h" #include "chrome/browser/ntp_snippets/dependent_features.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_features.h" @@ -176,14 +175,10 @@ ntp_snippets::BreakingNewsListener* GetBreakingNewsListener( SnippetsInternalsMessageHandler::SnippetsInternalsMessageHandler( ntp_snippets::ContentSuggestionsService* content_suggestions_service, - ntp_snippets::ContextualContentSuggestionsService* - contextual_content_suggestions_service, PrefService* pref_service) : content_suggestions_service_observer_(this), dom_loaded_(false), content_suggestions_service_(content_suggestions_service), - contextual_content_suggestions_service_( - contextual_content_suggestions_service), remote_suggestions_provider_( content_suggestions_service_ ->remote_suggestions_provider_for_debugging()), @@ -195,62 +190,61 @@ SnippetsInternalsMessageHandler::~SnippetsInternalsMessageHandler() {} void SnippetsInternalsMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "clearCachedSuggestions", - base::Bind(&SnippetsInternalsMessageHandler::HandleClearCachedSuggestions, - base::Unretained(this))); + base::BindRepeating( + &SnippetsInternalsMessageHandler::HandleClearCachedSuggestions, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "clearClassification", - base::Bind(&SnippetsInternalsMessageHandler::HandleClearClassification, - base::Unretained(this))); + base::BindRepeating( + &SnippetsInternalsMessageHandler::HandleClearClassification, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "clearDismissedSuggestions", - base::Bind( + base::BindRepeating( &SnippetsInternalsMessageHandler::HandleClearDismissedSuggestions, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "download", base::Bind(&SnippetsInternalsMessageHandler::HandleDownload, - base::Unretained(this))); + "download", + base::BindRepeating(&SnippetsInternalsMessageHandler::HandleDownload, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "fetchRemoteSuggestionsInTheBackgroundIn2Seconds", - base::Bind(&SnippetsInternalsMessageHandler:: - HandleFetchRemoteSuggestionsInTheBackgroundIn2Seconds, - base::Unretained(this))); - - web_ui()->RegisterMessageCallback( - "fetchContextualSuggestions", - base::Bind( - &SnippetsInternalsMessageHandler::HandleFetchContextualSuggestions, + base::BindRepeating( + &SnippetsInternalsMessageHandler:: + HandleFetchRemoteSuggestionsInTheBackgroundIn2Seconds, base::Unretained(this))); web_ui()->RegisterMessageCallback( "resetNotificationsState", - base::Bind( + base::BindRepeating( &SnippetsInternalsMessageHandler::HandleResetNotificationsState, base::Unretained(this))); web_ui()->RegisterMessageCallback( "pushDummySuggestionIn10Seconds", - base::Bind(&SnippetsInternalsMessageHandler:: - HandlePushDummySuggestionIn10Seconds, - base::Unretained(this))); + base::BindRepeating(&SnippetsInternalsMessageHandler:: + HandlePushDummySuggestionIn10Seconds, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "refreshContent", - base::Bind(&SnippetsInternalsMessageHandler::HandleRefreshContent, - base::Unretained(this))); + base::BindRepeating( + &SnippetsInternalsMessageHandler::HandleRefreshContent, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "toggleDismissedSuggestions", - base::Bind( + base::BindRepeating( &SnippetsInternalsMessageHandler::HandleToggleDismissedSuggestions, base::Unretained(this))); web_ui()->RegisterMessageCallback( "initializationCompleted", - base::Bind( + base::BindRepeating( &SnippetsInternalsMessageHandler::HandleInitializationCompleted, base::Unretained(this))); @@ -404,18 +398,6 @@ void SnippetsInternalsMessageHandler:: weak_ptr_factory_.GetWeakPtr())); } -void SnippetsInternalsMessageHandler::HandleFetchContextualSuggestions( - const base::ListValue* args) { - DCHECK_EQ(1u, args->GetSize()); - std::string url_str; - args->GetString(0, &url_str); - contextual_content_suggestions_service_->FetchContextualSuggestions( - GURL(url_str), - base::BindOnce( - &SnippetsInternalsMessageHandler::OnContextualSuggestionsFetched, - weak_ptr_factory_.GetWeakPtr())); -} - void SnippetsInternalsMessageHandler::HandleResetNotificationsState( const base::ListValue* args) { pref_service_->SetInteger( @@ -427,23 +409,6 @@ void SnippetsInternalsMessageHandler::HandleResetNotificationsState( ContentSuggestionsNotificationAction::HIDE_FRONTMOST); } -void SnippetsInternalsMessageHandler::OnContextualSuggestionsFetched( - ntp_snippets::Status status, - const GURL& url, - std::vector<ntp_snippets::ContentSuggestion> suggestions) { - // Ids start in a range distinct from those created by SendContentSuggestions. - int id = 10000; - auto suggestions_list = std::make_unique<base::ListValue>(); - for (const ContentSuggestion& suggestion : suggestions) { - suggestions_list->Append(PrepareSuggestion(suggestion, id++)); - } - base::DictionaryValue result; - result.Set("list", std::move(suggestions_list)); - web_ui()->CallJavascriptFunctionUnsafe( - "chrome.SnippetsInternals.receiveContextualSuggestions", result, - base::Value(static_cast<int>(status.code))); -} - void SnippetsInternalsMessageHandler::HandlePushDummySuggestionIn10Seconds( const base::ListValue* args) { suggestion_push_timer_.Start( diff --git a/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.h b/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.h index 2f1af444c2b..bb5daac50f5 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.h +++ b/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.h @@ -27,7 +27,6 @@ class ListValue; namespace ntp_snippets { class ContentSuggestionsService; -class ContextualContentSuggestionsService; } // namespace ntp_snippets class PrefService; @@ -39,8 +38,6 @@ class SnippetsInternalsMessageHandler public: SnippetsInternalsMessageHandler( ntp_snippets::ContentSuggestionsService* content_suggestions_service, - ntp_snippets::ContextualContentSuggestionsService* - contextual_content_suggestions_service, PrefService* pref_service); ~SnippetsInternalsMessageHandler() override; @@ -69,12 +66,7 @@ class SnippetsInternalsMessageHandler void HandleClearClassification(const base::ListValue* args); void HandleFetchRemoteSuggestionsInTheBackgroundIn2Seconds( const base::ListValue* args); - void HandleFetchContextualSuggestions(const base::ListValue* args); void HandleResetNotificationsState(const base::ListValue* args); - void OnContextualSuggestionsFetched( - ntp_snippets::Status status_code, - const GURL& url, - std::vector<ntp_snippets::ContentSuggestion> suggestions); void HandlePushDummySuggestionIn10Seconds(const base::ListValue* args); void SendAllContent(); @@ -101,8 +93,8 @@ class SnippetsInternalsMessageHandler bool dom_loaded_; ntp_snippets::ContentSuggestionsService* content_suggestions_service_; - ntp_snippets::ContextualContentSuggestionsService* - contextual_content_suggestions_service_; + // TODO(pnoland): Add back contextual content suggestions service and + // handle the new data format. ntp_snippets::RemoteSuggestionsProvider* remote_suggestions_provider_; PrefService* pref_service_; diff --git a/chromium/chrome/browser/ui/webui/snippets_internals_ui.cc b/chromium/chrome/browser/ui/webui/snippets_internals_ui.cc index cbaf8fe2aaa..9700dc8eeaf 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/snippets_internals_ui.cc @@ -8,7 +8,6 @@ #include "build/build_config.h" #include "chrome/browser/ntp_snippets/content_suggestions_service_factory.h" -#include "chrome/browser/ntp_snippets/contextual_content_suggestions_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/snippets_internals_message_handler.h" #include "chrome/common/url_constants.h" @@ -26,16 +25,6 @@ content::WebUIDataSource* CreateSnippetsInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUISnippetsInternalsHost); -#if defined(OS_ANDROID) - source->AddBoolean( - "contextualSuggestionsEnabled", - base::FeatureList::IsEnabled( - chrome::android::kContextualSuggestionsCarousel) || - base::FeatureList::IsEnabled( - chrome::android::kContextualSuggestionsAboveArticles)); -#else - source->AddBoolean("contextualSuggestionsEnabled", false); -#endif source->SetJsonPath("strings.js"); source->AddResourcePath("snippets_internals.js", IDR_SNIPPETS_INTERNALS_JS); source->AddResourcePath("snippets_internals.css", IDR_SNIPPETS_INTERNALS_CSS); @@ -53,8 +42,6 @@ SnippetsInternalsUI::SnippetsInternalsUI(content::WebUI* web_ui) web_ui->AddMessageHandler(std::make_unique<SnippetsInternalsMessageHandler>( ContentSuggestionsServiceFactory::GetInstance()->GetForProfile(profile), - ContextualContentSuggestionsServiceFactory::GetInstance()->GetForProfile( - profile), profile->GetPrefs())); } diff --git a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc index a8a2f5e7486..824104454b8 100644 --- a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc @@ -126,18 +126,22 @@ SupervisedUserInternalsMessageHandler:: void SupervisedUserInternalsMessageHandler::RegisterMessages() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - web_ui()->RegisterMessageCallback("registerForEvents", - base::Bind(&SupervisedUserInternalsMessageHandler:: - HandleRegisterForEvents, - base::Unretained(this))); - - web_ui()->RegisterMessageCallback("getBasicInfo", - base::Bind(&SupervisedUserInternalsMessageHandler::HandleGetBasicInfo, - base::Unretained(this))); - - web_ui()->RegisterMessageCallback("tryURL", - base::Bind(&SupervisedUserInternalsMessageHandler::HandleTryURL, - base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "registerForEvents", + base::BindRepeating( + &SupervisedUserInternalsMessageHandler::HandleRegisterForEvents, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "getBasicInfo", + base::BindRepeating( + &SupervisedUserInternalsMessageHandler::HandleGetBasicInfo, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "tryURL", + base::BindRepeating(&SupervisedUserInternalsMessageHandler::HandleTryURL, + base::Unretained(this))); } void SupervisedUserInternalsMessageHandler::OnURLFilterChanged() { diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/dump_database_handler.cc b/chromium/chrome/browser/ui/webui/sync_file_system_internals/dump_database_handler.cc index 5d2d2dbda6e..5b6ab2d04db 100644 --- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/dump_database_handler.cc +++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/dump_database_handler.cc @@ -21,8 +21,8 @@ DumpDatabaseHandler::~DumpDatabaseHandler() {} void DumpDatabaseHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getDatabaseDump", - base::Bind(&DumpDatabaseHandler::GetDatabaseDump, - base::Unretained(this))); + base::BindRepeating(&DumpDatabaseHandler::GetDatabaseDump, + base::Unretained(this))); } void DumpDatabaseHandler::GetDatabaseDump(const base::ListValue*) { diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc b/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc index a9e8ec0244d..d6aa8fc7887 100644 --- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc +++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc @@ -70,8 +70,8 @@ ExtensionStatusesHandler::~ExtensionStatusesHandler() {} void ExtensionStatusesHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getExtensionStatuses", - base::Bind(&ExtensionStatusesHandler::GetExtensionStatuses, - base::Unretained(this))); + base::BindRepeating(&ExtensionStatusesHandler::GetExtensionStatuses, + base::Unretained(this))); } // static diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.cc b/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.cc index 19108f4f13f..4779edd6b37 100644 --- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.cc +++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.cc @@ -32,13 +32,12 @@ FileMetadataHandler::~FileMetadataHandler() {} void FileMetadataHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "getExtensions", - base::Bind(&FileMetadataHandler::GetExtensions, - base::Unretained(this))); + "getExtensions", base::BindRepeating(&FileMetadataHandler::GetExtensions, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getFileMetadata", - base::Bind(&FileMetadataHandler::GetFileMetadata, - base::Unretained(this))); + base::BindRepeating(&FileMetadataHandler::GetFileMetadata, + base::Unretained(this))); } void FileMetadataHandler::GetFileMetadata( diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_handler.cc b/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_handler.cc index a17ed60d4ef..bdbe8a704b1 100644 --- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_handler.cc +++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_handler.cc @@ -54,24 +54,24 @@ SyncFileSystemInternalsHandler::~SyncFileSystemInternalsHandler() { void SyncFileSystemInternalsHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getServiceStatus", - base::Bind(&SyncFileSystemInternalsHandler::GetServiceStatus, - base::Unretained(this))); + base::BindRepeating(&SyncFileSystemInternalsHandler::GetServiceStatus, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "getLog", - base::Bind(&SyncFileSystemInternalsHandler::GetLog, - base::Unretained(this))); + "getLog", base::BindRepeating(&SyncFileSystemInternalsHandler::GetLog, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "clearLogs", - base::Bind(&SyncFileSystemInternalsHandler::ClearLogs, - base::Unretained(this))); + base::BindRepeating(&SyncFileSystemInternalsHandler::ClearLogs, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getNotificationSource", - base::Bind(&SyncFileSystemInternalsHandler::GetNotificationSource, - base::Unretained(this))); + base::BindRepeating( + &SyncFileSystemInternalsHandler::GetNotificationSource, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "observeTaskLog", - base::Bind(&SyncFileSystemInternalsHandler::ObserveTaskLog, - base::Unretained(this))); + base::BindRepeating(&SyncFileSystemInternalsHandler::ObserveTaskLog, + base::Unretained(this))); } void SyncFileSystemInternalsHandler::OnSyncStateUpdated( diff --git a/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc b/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc index 2ed7f22ae14..4563fa61cc1 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc @@ -91,44 +91,48 @@ void SyncInternalsMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( syncer::sync_ui_util::kRegisterForEvents, - base::Bind(&SyncInternalsMessageHandler::HandleRegisterForEvents, - base::Unretained(this))); + base::BindRepeating(&SyncInternalsMessageHandler::HandleRegisterForEvents, + base::Unretained(this))); web_ui()->RegisterMessageCallback( syncer::sync_ui_util::kRegisterForPerTypeCounters, - base::Bind(&SyncInternalsMessageHandler::HandleRegisterForPerTypeCounters, - base::Unretained(this))); + base::BindRepeating( + &SyncInternalsMessageHandler::HandleRegisterForPerTypeCounters, + base::Unretained(this))); web_ui()->RegisterMessageCallback( syncer::sync_ui_util::kRequestUpdatedAboutInfo, - base::Bind(&SyncInternalsMessageHandler::HandleRequestUpdatedAboutInfo, - base::Unretained(this))); + base::BindRepeating( + &SyncInternalsMessageHandler::HandleRequestUpdatedAboutInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( syncer::sync_ui_util::kRequestListOfTypes, - base::Bind(&SyncInternalsMessageHandler::HandleRequestListOfTypes, - base::Unretained(this))); + base::BindRepeating( + &SyncInternalsMessageHandler::HandleRequestListOfTypes, + base::Unretained(this))); web_ui()->RegisterMessageCallback( syncer::sync_ui_util::kRequestUserEventsVisibility, - base::Bind( + base::BindRepeating( &SyncInternalsMessageHandler::HandleRequestUserEventsVisibility, base::Unretained(this))); web_ui()->RegisterMessageCallback( syncer::sync_ui_util::kSetIncludeSpecifics, - base::Bind(&SyncInternalsMessageHandler::HandleSetIncludeSpecifics, - base::Unretained(this))); + base::BindRepeating( + &SyncInternalsMessageHandler::HandleSetIncludeSpecifics, + base::Unretained(this))); web_ui()->RegisterMessageCallback( syncer::sync_ui_util::kWriteUserEvent, - base::Bind(&SyncInternalsMessageHandler::HandleWriteUserEvent, - base::Unretained(this))); + base::BindRepeating(&SyncInternalsMessageHandler::HandleWriteUserEvent, + base::Unretained(this))); web_ui()->RegisterMessageCallback( syncer::sync_ui_util::kGetAllNodes, - base::Bind(&SyncInternalsMessageHandler::HandleGetAllNodes, - base::Unretained(this))); + base::BindRepeating(&SyncInternalsMessageHandler::HandleGetAllNodes, + base::Unretained(this))); } void SyncInternalsMessageHandler::HandleRegisterForEvents( diff --git a/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc b/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc index 2014f38b61c..33d16953265 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc @@ -20,6 +20,7 @@ #include "components/sync/user_events/fake_user_event_service.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" +#include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -196,6 +197,10 @@ class SyncInternalsMessageHandlerTest : public ::testing::Test { void ResetHandler() { handler_.reset(); } private: + // TODO(lukasza): https://crbug.com/832100: Move the factory into + // TestingProfile, so individual tests don't need to worry about it. + content::ScopedMockRenderProcessHostFactory process_factory_; + content::TestBrowserThreadBundle thread_bundle_; TestingProfile profile_; scoped_refptr<content::SiteInstance> site_instance_; diff --git a/chromium/chrome/browser/ui/webui/task_scheduler_internals/task_scheduler_internals_ui.cc b/chromium/chrome/browser/ui/webui/task_scheduler_internals/task_scheduler_internals_ui.cc index 4c62ad6a68f..641156f4958 100644 --- a/chromium/chrome/browser/ui/webui/task_scheduler_internals/task_scheduler_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/task_scheduler_internals/task_scheduler_internals_ui.cc @@ -58,8 +58,8 @@ class TaskSchedulerDataHandler : public content::WebUIMessageHandler { void RegisterMessages() override { web_ui()->RegisterMessageCallback( "getTaskSchedulerData", - base::Bind(&TaskSchedulerDataHandler::GetTaskSchedulerData, - base::Unretained(this))); + base::BindRepeating(&TaskSchedulerDataHandler::GetTaskSchedulerData, + base::Unretained(this))); } private: diff --git a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc index 1077d815420..366846e0b5d 100644 --- a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc +++ b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc @@ -60,15 +60,17 @@ TranslateInternalsHandler::~TranslateInternalsHandler() { void TranslateInternalsHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "removePrefItem", base::Bind(&TranslateInternalsHandler::OnRemovePrefItem, - base::Unretained(this))); + "removePrefItem", + base::BindRepeating(&TranslateInternalsHandler::OnRemovePrefItem, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - "requestInfo", base::Bind(&TranslateInternalsHandler::OnRequestInfo, - base::Unretained(this))); + "requestInfo", + base::BindRepeating(&TranslateInternalsHandler::OnRequestInfo, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "overrideCountry", - base::Bind(&TranslateInternalsHandler::OnOverrideCountry, - base::Unretained(this))); + base::BindRepeating(&TranslateInternalsHandler::OnOverrideCountry, + base::Unretained(this))); } void TranslateInternalsHandler::Observe( diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.h b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.h index e3952f99cf1..22b8ea16baa 100644 --- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.h +++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.h @@ -6,12 +6,10 @@ #define CHROME_BROWSER_UI_WEBUI_USB_INTERNALS_USB_INTERNALS_PAGE_HANDLER_H_ #include "base/macros.h" -#include "chrome/browser/ui/webui/mojo_web_ui_handler.h" #include "chrome/browser/ui/webui/usb_internals/usb_internals.mojom.h" #include "mojo/public/cpp/bindings/binding.h" -class UsbInternalsPageHandler : public mojom::UsbInternalsPageHandler, - public MojoWebUIHandler { +class UsbInternalsPageHandler : public mojom::UsbInternalsPageHandler { public: explicit UsbInternalsPageHandler( mojom::UsbInternalsPageHandlerRequest request); diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.cc b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.cc index 36785e19586..28e46d02e1c 100644 --- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.cc @@ -11,7 +11,7 @@ #include "content/public/browser/web_ui_data_source.h" UsbInternalsUI::UsbInternalsUI(content::WebUI* web_ui) - : MojoWebUIController(web_ui) { + : ui::MojoWebUIController<mojom::UsbInternalsPageHandler>(web_ui) { // Set up the chrome://usb-internals source. content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIUsbInternalsHost); diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.h b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.h index 0b0a3436bb7..1665116bdc5 100644 --- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.h +++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.h @@ -6,20 +6,20 @@ #define CHROME_BROWSER_UI_WEBUI_USB_INTERNALS_USB_INTERNALS_UI_H_ #include "base/macros.h" -#include "chrome/browser/ui/webui/mojo_web_ui_controller.h" #include "chrome/browser/ui/webui/usb_internals/usb_internals.mojom.h" +#include "ui/webui/mojo_web_ui_controller.h" class UsbInternalsPageHandler; // The WebUI for chrome://usb-internals. class UsbInternalsUI - : public MojoWebUIController<mojom::UsbInternalsPageHandler> { + : public ui::MojoWebUIController<mojom::UsbInternalsPageHandler> { public: explicit UsbInternalsUI(content::WebUI* web_ui); ~UsbInternalsUI() override; private: - // MojoWebUIController overrides: + // ui::MojoWebUIController overrides: void BindUIHandler(mojom::UsbInternalsPageHandlerRequest request) override; std::unique_ptr<UsbInternalsPageHandler> page_handler_; diff --git a/chromium/chrome/browser/ui/webui/version_handler.cc b/chromium/chrome/browser/ui/webui/version_handler.cc index 9bd498db4c0..90a780dc97a 100644 --- a/chromium/chrome/browser/ui/webui/version_handler.cc +++ b/chromium/chrome/browser/ui/webui/version_handler.cc @@ -26,7 +26,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/content_constants.h" -#include "ppapi/features/features.h" +#include "ppapi/buildflags/buildflags.h" #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" @@ -62,8 +62,8 @@ VersionHandler::~VersionHandler() { void VersionHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( version_ui::kRequestVersionInfo, - base::Bind(&VersionHandler::HandleRequestVersionInfo, - base::Unretained(this))); + base::BindRepeating(&VersionHandler::HandleRequestVersionInfo, + base::Unretained(this))); } void VersionHandler::HandleRequestVersionInfo(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/version_ui.cc b/chromium/chrome/browser/ui/webui/version_ui.cc index 4d83440102f..bc9b88c1335 100644 --- a/chromium/chrome/browser/ui/webui/version_ui.cc +++ b/chromium/chrome/browser/ui/webui/version_ui.cc @@ -57,7 +57,7 @@ WebUIDataSource* CreateVersionUIDataSource() { html_source->AddString(version_ui::kVersion, version_info::GetVersionNumber()); html_source->AddString(version_ui::kVersionModifier, - chrome::GetChannelString()); + chrome::GetChannelName()); html_source->AddString(version_ui::kJSEngine, "V8"); html_source->AddString(version_ui::kJSVersion, V8_VERSION_STRING); html_source->AddLocalizedString(version_ui::kCompany, @@ -141,25 +141,7 @@ WebUIDataSource* CreateVersionUIDataSource() { #endif #if defined(OS_WIN) -#if defined(__clang__) - html_source->AddString(version_ui::kCompiler, "clang"); -#elif defined(_MSC_VER) && _MSC_VER == 1900 -#if BUILDFLAG(PGO_BUILD) - html_source->AddString(version_ui::kCompiler, "MSVC 2015 (PGO)"); -#else - html_source->AddString(version_ui::kCompiler, "MSVC 2015"); -#endif -#elif defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER < 2000 -#if BUILDFLAG(PGO_BUILD) - html_source->AddString(version_ui::kCompiler, "MSVC 2017 (PGO)"); -#else - html_source->AddString(version_ui::kCompiler, "MSVC 2017"); -#endif -#elif defined(_MSC_VER) -#error "Unsupported version of MSVC." -#else - html_source->AddString(version_ui::kCompiler, "Unknown"); -#endif + html_source->AddString("linker", CHROMIUM_LINKER_NAME); base::string16 update_cohort_name = install_static::InstallDetails::Get().update_cohort_name(); diff --git a/chromium/chrome/browser/ui/webui/web_ui_test_handler.cc b/chromium/chrome/browser/ui/webui/web_ui_test_handler.cc index 8ae8cd38394..efe8811db00 100644 --- a/chromium/chrome/browser/ui/webui/web_ui_test_handler.cc +++ b/chromium/chrome/browser/ui/webui/web_ui_test_handler.cc @@ -21,7 +21,7 @@ #include "content/public/browser/web_ui.h" #include "content/public/test/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h" +#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" using content::RenderViewHost; @@ -29,10 +29,11 @@ WebUITestHandler::WebUITestHandler() : test_done_(false), test_succeeded_(false), run_test_done_(false), - run_test_succeeded_(false), - is_waiting_(false) { + run_test_succeeded_(false) { } +WebUITestHandler::~WebUITestHandler() = default; + void WebUITestHandler::PreloadJavaScript(const base::string16& js_text, RenderViewHost* preload_host) { DCHECK(preload_host); @@ -59,15 +60,14 @@ bool WebUITestHandler::RunJavaScriptTestWithResult( } void WebUITestHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("testResult", - base::Bind(&WebUITestHandler::HandleTestResult, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "testResult", base::BindRepeating(&WebUITestHandler::HandleTestResult, + base::Unretained(this))); } void WebUITestHandler::HandleTestResult(const base::ListValue* test_result) { - // Quit the message loop if |is_waiting_| so waiting process can get result or - // error. To ensure this gets done, do this before ASSERT* calls. - if (is_waiting_) - base::RunLoop::QuitCurrentWhenIdleDeprecated(); + // To ensure this gets done, do this before ASSERT* calls. + quit_closure_.Run(); SCOPED_TRACE("WebUITestHandler::HandleTestResult"); @@ -84,10 +84,8 @@ void WebUITestHandler::HandleTestResult(const base::ListValue* test_result) { } void WebUITestHandler::JavaScriptComplete(const base::Value* result) { - // Quit the message loop if |is_waiting_| so waiting process can get result or - // error. To ensure this gets done, do this before ASSERT* calls. - if (is_waiting_) - base::RunLoop::QuitCurrentWhenIdleDeprecated(); + // To ensure this gets done, do this before ASSERT* calls. + quit_closure_.Run(); SCOPED_TRACE("WebUITestHandler::JavaScriptComplete"); @@ -102,21 +100,24 @@ bool WebUITestHandler::WaitForResult() { SCOPED_TRACE("WebUITestHandler::WaitForResult"); test_done_ = false; run_test_done_ = false; - is_waiting_ = true; // Either sync test completion or the testDone() will cause message loop // to quit. - content::RunMessageLoop(); + { + base::RunLoop run_loop; + quit_closure_ = run_loop.QuitWhenIdleClosure(); + content::RunThisRunLoop(&run_loop); + } // Run a second message loop when not |run_test_done_| so that the sync test // completes, or |run_test_succeeded_| but not |test_done_| so async tests // complete. if (!run_test_done_ || (run_test_succeeded_ && !test_done_)) { - content::RunMessageLoop(); + base::RunLoop run_loop; + quit_closure_ = run_loop.QuitWhenIdleClosure(); + content::RunThisRunLoop(&run_loop); } - is_waiting_ = false; - // To succeed the test must execute as well as pass the test. return run_test_succeeded_ && test_succeeded_; } diff --git a/chromium/chrome/browser/ui/webui/web_ui_test_handler.h b/chromium/chrome/browser/ui/webui/web_ui_test_handler.h index cb95c2f0b9a..cba7ccf76a9 100644 --- a/chromium/chrome/browser/ui/webui/web_ui_test_handler.h +++ b/chromium/chrome/browser/ui/webui/web_ui_test_handler.h @@ -23,6 +23,7 @@ class RenderViewHost; class WebUITestHandler : public content::WebUIMessageHandler { public: WebUITestHandler(); + ~WebUITestHandler() override; // Sends a message through |preload_host| with the |js_text| to preload at the // appropriate time before the onload call is made. @@ -66,8 +67,8 @@ class WebUITestHandler : public content::WebUIMessageHandler { // pass/fail. bool run_test_succeeded_; - // Waiting for a test to finish. - bool is_waiting_; + // Quits the currently running RunLoop. + base::Closure quit_closure_; DISALLOW_COPY_AND_ASSIGN(WebUITestHandler); }; diff --git a/chromium/chrome/browser/ui/webui/webapks_handler.cc b/chromium/chrome/browser/ui/webui/webapks_handler.cc index 264fe0e41be..8a4f948778b 100644 --- a/chromium/chrome/browser/ui/webui/webapks_handler.cc +++ b/chromium/chrome/browser/ui/webui/webapks_handler.cc @@ -31,8 +31,8 @@ WebApksHandler::~WebApksHandler() {} void WebApksHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "requestWebApksInfo", - base::Bind(&WebApksHandler::HandleRequestWebApksInfo, - base::Unretained(this))); + base::BindRepeating(&WebApksHandler::HandleRequestWebApksInfo, + base::Unretained(this))); } void WebApksHandler::HandleRequestWebApksInfo(const base::ListValue* args) { @@ -65,6 +65,9 @@ void WebApksHandler::OnWebApkInfoRetrieved( result->SetString("themeColor", ColorToString(webapk_info.theme_color)); result->SetString("backgroundColor", ColorToString(webapk_info.background_color)); + result->SetDouble("lastUpdateCheckTimeMs", + webapk_info.last_update_check_time.ToJsTime()); + result->SetBoolean("relaxUpdates", webapk_info.relax_updates); list.Append(std::move(result)); } diff --git a/chromium/chrome/browser/ui/webui/webui_browsertest.cc b/chromium/chrome/browser/ui/webui/webui_browsertest.cc index 95e722ad1f2..969ce238930 100644 --- a/chromium/chrome/browser/ui/webui/webui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/webui_browsertest.cc @@ -2,38 +2,123 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <utility> + +#include "base/bind.h" +#include "base/callback.h" #include "base/command_line.h" +#include "base/memory/ptr_util.h" +#include "base/memory/weak_ptr.h" +#include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" -#include "base/test/scoped_feature_list.h" +#include "base/test/simple_test_tick_clock.h" +#include "base/time/time.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h" -#include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" -#include "components/strings/grit/components_strings.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" +#include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_message_handler.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" -#include "ui/base/l10n/l10n_util.h" +#include "third_party/blink/public/platform/web_mouse_event.h" +#include "third_party/blink/public/platform/web_mouse_wheel_event.h" +#include "ui/events/base_event_utils.h" namespace { +using WebUIImplBrowserTest = InProcessBrowserTest; + class TestWebUIMessageHandler : public content::WebUIMessageHandler { public: - void RegisterMessages() override {} + void RegisterMessages() override { + web_ui()->RegisterMessageCallback( + "messageRequiringGesture", + base::BindRepeating(&TestWebUIMessageHandler::OnMessageRequiringGesture, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "notifyFinish", + base::BindRepeating(&TestWebUIMessageHandler::OnNotifyFinish, + base::Unretained(this))); + } + + void set_finish_closure(base::RepeatingClosure closure) { + finish_closure_ = std::move(closure); + } + + int message_requiring_gesture_count() const { + return message_requiring_gesture_count_; + } + + private: + void OnMessageRequiringGesture(const base::ListValue* args) { + ++message_requiring_gesture_count_; + } + + void OnNotifyFinish(const base::ListValue* args) { + if (finish_closure_) + finish_closure_.Run(); + } + + int message_requiring_gesture_count_ = 0; + base::RepeatingClosure finish_closure_; }; -} // namespace +class WebUIRequiringGestureBrowserTest : public InProcessBrowserTest { + public: + WebUIRequiringGestureBrowserTest() { + clock_.SetNowTicks(base::TimeTicks::Now()); + ui::SetEventTickClockForTesting(&clock_); + } + + ~WebUIRequiringGestureBrowserTest() override { + ui::SetEventTickClockForTesting(nullptr); + } + + void SetUpOnMainThread() override { + ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIFlagsURL)); + test_handler_ = new TestWebUIMessageHandler(); + web_contents()->GetWebUI()->AddMessageHandler( + base::WrapUnique(test_handler_)); + } + + protected: + void SendMessageAndWaitForFinish() { + main_rfh()->ExecuteJavaScriptForTests( + base::ASCIIToUTF16("chrome.send('messageRequiringGesture');" + "chrome.send('notifyFinish');")); + base::RunLoop run_loop; + test_handler()->set_finish_closure(run_loop.QuitClosure()); + run_loop.Run(); + } + + void AdvanceClock(base::TimeDelta delta) { clock_.Advance(delta); } + + content::WebContents* web_contents() { + return browser()->tab_strip_model()->GetActiveWebContents(); + } + content::RenderFrameHost* main_rfh() { + return web_contents()->GetMainFrame(); + } + + TestWebUIMessageHandler* test_handler() { return test_handler_; } + + private: + base::SimpleTestTickClock clock_; + + // Owned by the WebUI associated with the WebContents. + TestWebUIMessageHandler* test_handler_ = nullptr; +}; -using WebUIImplBrowserTest = InProcessBrowserTest; +} // namespace // Tests that navigating between WebUIs of different types results in // SiteInstance swap when running in process-per-tab process model. @@ -99,17 +184,63 @@ IN_PROC_BROWSER_TEST_F(WebUIImplBrowserTest, SameDocumentNavigationsAndReload) { EXPECT_FALSE(test_handler->IsJavascriptAllowed()); } -// Tests that navigating to chrome://connection-help displays the proper help -// page. -IN_PROC_BROWSER_TEST_F(WebUIImplBrowserTest, ConnectionHelpUI) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature(features::kBundledConnectionHelpFeature); - ui_test_utils::NavigateToURL(browser(), - GURL(chrome::kChromeUIConnectionHelpURL)); - content::WaitForLoadStop( - browser()->tab_strip_model()->GetActiveWebContents()); - base::string16 tab_title; - ui_test_utils::GetCurrentTabTitle(browser(), &tab_title); - EXPECT_EQ(base::UTF16ToUTF8(tab_title), - l10n_util::GetStringUTF8(IDS_CONNECTION_HELP_TITLE)); +// A WebUI message that should require a user gesture is ignored if there is no +// recent input event. +IN_PROC_BROWSER_TEST_F(WebUIRequiringGestureBrowserTest, + MessageRequiringGestureIgnoredIfNoGesture) { + SendMessageAndWaitForFinish(); + EXPECT_EQ(0, test_handler()->message_requiring_gesture_count()); +} + +IN_PROC_BROWSER_TEST_F(WebUIRequiringGestureBrowserTest, + MessageRequiringGestureIgnoresRendererOnlyGesture) { + // Note: this doesn't use SendMessageAndWaitForFinish() since this test needs + // to use a test-only helper to instantiate a scoped user gesture in the + // renderer. + main_rfh()->ExecuteJavaScriptWithUserGestureForTests( + base::ASCIIToUTF16("chrome.send('messageRequiringGesture');" + "chrome.send('notifyFinish');")); + base::RunLoop run_loop; + test_handler()->set_finish_closure(run_loop.QuitClosure()); + run_loop.Run(); + EXPECT_EQ(0, test_handler()->message_requiring_gesture_count()); +} + +IN_PROC_BROWSER_TEST_F(WebUIRequiringGestureBrowserTest, + MessageRequiringGestureIgnoresNonInteractiveEvents) { + // Mouse enter / mouse move / mouse leave should not be considered input + // events that interact with the page. + content::SimulateMouseEvent(web_contents(), blink::WebInputEvent::kMouseEnter, + gfx::Point(50, 50)); + content::SimulateMouseEvent(web_contents(), blink::WebInputEvent::kMouseMove, + gfx::Point(50, 50)); + content::SimulateMouseEvent(web_contents(), blink::WebInputEvent::kMouseLeave, + gfx::Point(50, 50)); + // Nor should mouse wheel. + content::SimulateMouseWheelEvent(web_contents(), gfx::Point(50, 50), + gfx::Vector2d(0, 100), + blink::WebMouseWheelEvent::kPhaseBegan); + SendMessageAndWaitForFinish(); + EXPECT_EQ(0, test_handler()->message_requiring_gesture_count()); +} + +IN_PROC_BROWSER_TEST_F(WebUIRequiringGestureBrowserTest, + MessageRequiringGestureAllowedWithInteractiveEvent) { + // Simulate a click at Now. + content::SimulateMouseClick(web_contents(), 0, + blink::WebMouseEvent::Button::kLeft); + + // Now+0 should be allowed. + SendMessageAndWaitForFinish(); + EXPECT_EQ(1, test_handler()->message_requiring_gesture_count()); + + // Now+5 seconds should be allowed. + AdvanceClock(base::TimeDelta::FromSeconds(5)); + SendMessageAndWaitForFinish(); + EXPECT_EQ(2, test_handler()->message_requiring_gesture_count()); + + // Anything after that should be disallowed though. + AdvanceClock(base::TimeDelta::FromMicroseconds(1)); + SendMessageAndWaitForFinish(); + EXPECT_EQ(2, test_handler()->message_requiring_gesture_count()); } diff --git a/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc b/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc index 0e8346fff39..1c31268e703 100644 --- a/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc @@ -39,8 +39,8 @@ class WebUIMessageListener : public base::SupportsWeakPtr<WebUIMessageListener>{ WebUIMessageListener(content::WebUI* web_ui, const std::string& message) : message_loop_(new content::MessageLoopRunner) { web_ui->RegisterMessageCallback( - message, base::Bind(&WebUIMessageListener::HandleMessage, - AsWeakPtr())); + message, + base::BindRepeating(&WebUIMessageListener::HandleMessage, AsWeakPtr())); } bool Wait() { message_loop_->Run(); diff --git a/chromium/chrome/browser/ui/webui/welcome_handler.cc b/chromium/chrome/browser/ui/webui/welcome_handler.cc index d989be56940..cf7b8341c07 100644 --- a/chromium/chrome/browser/ui/webui/welcome_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome_handler.cc @@ -32,8 +32,8 @@ WelcomeHandler::~WelcomeHandler() { // construct-time on some platforms because this page is shown immediately // after a new installation of Chrome and loads while the user is deciding // whether or not to opt in to logging. - base::RecordAction( - base::UserMetricsAction("Signin_Impression_FromStartPage")); + signin_metrics::RecordSigninImpressionUserActionForAccessPoint( + signin_metrics::AccessPoint::ACCESS_POINT_START_PAGE); UMA_HISTOGRAM_ENUMERATION("Welcome.SignInPromptResult", result_, WelcomeResult::WELCOME_RESULT_MAX); @@ -80,11 +80,13 @@ void WelcomeHandler::HandleUserDecline(const base::ListValue* args) { // Override from WebUIMessageHandler. void WelcomeHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "handleActivateSignIn", base::Bind(&WelcomeHandler::HandleActivateSignIn, - base::Unretained(this))); + "handleActivateSignIn", + base::BindRepeating(&WelcomeHandler::HandleActivateSignIn, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "handleUserDecline", - base::Bind(&WelcomeHandler::HandleUserDecline, base::Unretained(this))); + base::BindRepeating(&WelcomeHandler::HandleUserDecline, + base::Unretained(this))); } void WelcomeHandler::GoToNewTabPage() { diff --git a/chromium/chrome/browser/ui/webui/welcome_win10_handler.cc b/chromium/chrome/browser/ui/webui/welcome_win10_handler.cc index 9f345f4ab1f..fcc39583b60 100644 --- a/chromium/chrome/browser/ui/webui/welcome_win10_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome_win10_handler.cc @@ -87,15 +87,16 @@ WelcomeWin10Handler::~WelcomeWin10Handler() { void WelcomeWin10Handler::RegisterMessages() { web_ui()->RegisterMessageCallback( "handleSetDefaultBrowser", - base::Bind(&WelcomeWin10Handler::HandleSetDefaultBrowser, - base::Unretained(this))); + base::BindRepeating(&WelcomeWin10Handler::HandleSetDefaultBrowser, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "handleContinue", - base::Bind(&WelcomeWin10Handler::HandleContinue, base::Unretained(this))); + base::BindRepeating(&WelcomeWin10Handler::HandleContinue, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "getPinnedToTaskbarState", - base::Bind(&WelcomeWin10Handler::HandleGetPinnedToTaskbarState, - base::Unretained(this))); + base::BindRepeating(&WelcomeWin10Handler::HandleGetPinnedToTaskbarState, + base::Unretained(this))); } void WelcomeWin10Handler::HandleGetPinnedToTaskbarState( |