diff options
Diffstat (limited to 'chromium/chrome/browser/ui')
410 files changed, 7349 insertions, 3930 deletions
diff --git a/chromium/chrome/browser/ui/BUILD.gn b/chromium/chrome/browser/ui/BUILD.gn index 3ec0ed426c7..1826b714b2e 100644 --- a/chromium/chrome/browser/ui/BUILD.gn +++ b/chromium/chrome/browser/ui/BUILD.gn @@ -26,10 +26,6 @@ import("//third_party/protobuf/proto_library.gni") import("//ui/base/ui_features.gni") import("//ui/views/features.gni") -if (is_chromeos) { - import("//chrome/browser/chromeos/kiosk_next_home/kiosk_next.gni") -} - # Use a static library here because many test binaries depend on this but don't # require many files from it. This makes linking more efficient. jumbo_split_static_library("ui") { @@ -121,7 +117,7 @@ jumbo_split_static_library("ui") { "interventions/intervention_delegate.h", "interventions/intervention_infobar_delegate.cc", "interventions/intervention_infobar_delegate.h", - "javascript_dialogs/chrome_javascript_native_dialog_factory.h", + "javascript_dialogs/chrome_javascript_native_app_modal_dialog_factory.h", "javascript_dialogs/javascript_dialog.h", "javascript_dialogs/javascript_dialog_tab_helper.cc", "javascript_dialogs/javascript_dialog_tab_helper.h", @@ -129,6 +125,8 @@ jumbo_split_static_library("ui") { "login/login_handler.h", "login/login_interstitial_delegate.cc", "login/login_interstitial_delegate.h", + "login/login_navigation_throttle.cc", + "login/login_navigation_throttle.h", "login/login_tab_helper.cc", "login/login_tab_helper.h", "navigation_correction_tab_observer.cc", @@ -139,6 +137,8 @@ jumbo_split_static_library("ui") { "page_info/page_info_ui.h", "passwords/account_avatar_fetcher.cc", "passwords/account_avatar_fetcher.h", + "passwords/credential_leak_dialog_utils.cc", + "passwords/credential_leak_dialog_utils.h", "passwords/manage_passwords_state.cc", "passwords/manage_passwords_state.h", "passwords/manage_passwords_view_utils.cc", @@ -215,8 +215,12 @@ jumbo_split_static_library("ui") { "webauthn/authenticator_request_dialog.h", "webui/about_ui.cc", "webui/about_ui.h", - "webui/autofill_internals_ui.cc", - "webui/autofill_internals_ui.h", + "webui/autofill_and_password_manager_internals/autofill_internals_ui.cc", + "webui/autofill_and_password_manager_internals/autofill_internals_ui.h", + "webui/autofill_and_password_manager_internals/internals_ui_handler.cc", + "webui/autofill_and_password_manager_internals/internals_ui_handler.h", + "webui/autofill_and_password_manager_internals/password_manager_internals_ui.cc", + "webui/autofill_and_password_manager_internals/password_manager_internals_ui.h", "webui/chrome_web_ui_controller_factory.cc", "webui/chrome_web_ui_controller_factory.h", "webui/components_ui.cc", @@ -283,8 +287,6 @@ jumbo_split_static_library("ui") { "webui/omnibox/omnibox_page_handler.h", "webui/omnibox/omnibox_ui.cc", "webui/omnibox/omnibox_ui.h", - "webui/password_manager_internals/password_manager_internals_ui.cc", - "webui/password_manager_internals/password_manager_internals_ui.h", "webui/policy_ui.cc", "webui/policy_ui.h", "webui/policy_ui_handler.cc", @@ -375,6 +377,7 @@ jumbo_split_static_library("ui") { # browser, then we can clean up these dependencies. public_deps = [ "//components/dom_distiller/core", + "//components/safe_browsing:buildflags", "//components/sync", "//components/sync_user_events", "//components/translate/content/browser", @@ -442,7 +445,7 @@ jumbo_split_static_library("ui") { "//components/feedback", "//components/flags_ui", "//components/gcm_driver", - "//components/google/core/browser", + "//components/google/core/common", "//components/heap_profiling", "//components/history/content/browser", "//components/history/core/browser", @@ -479,12 +482,14 @@ jumbo_split_static_library("ui") { "//components/rappor", "//components/renderer_context_menu", "//components/resources", + "//components/safe_browsing:csd_proto", "//components/safe_browsing:features", "//components/safe_browsing/common", "//components/safe_browsing/common:safe_browsing_prefs", "//components/safe_browsing/db:database_manager", "//components/safe_browsing/db:util", "//components/safe_browsing/password_protection", + "//components/safe_browsing/password_protection:password_protection_metrics_util", "//components/safe_browsing/triggers:ad_popup_trigger", "//components/safe_browsing/triggers:ad_redirect_trigger", "//components/safe_browsing/web_ui", @@ -505,7 +510,6 @@ jumbo_split_static_library("ui") { "//components/strings", "//components/subresource_filter/content/browser", "//components/subresource_filter/core/browser", - "//components/supervised_user_error_page", "//components/sync", "//components/sync_preferences", "//components/sync_sessions", @@ -520,13 +524,14 @@ jumbo_split_static_library("ui") { "//components/update_client", "//components/upload_list", "//components/url_formatter", - "//components/url_formatter/top_domains:common", + "//components/url_formatter/spoof_checks/top_domains:common", "//components/user_manager", "//components/user_prefs", "//components/variations", "//components/variations/service", "//components/vector_icons", "//components/version_ui", + "//components/viz/host", "//components/web_cache/browser", "//components/web_resource", "//components/webrtc_logging/browser", @@ -683,8 +688,6 @@ jumbo_split_static_library("ui") { "android/infobars/near_oom_infobar.h", "android/infobars/near_oom_reduction_infobar.cc", "android/infobars/near_oom_reduction_infobar.h", - "android/infobars/permission_infobar.cc", - "android/infobars/permission_infobar.h", "android/infobars/previews_lite_page_infobar.cc", "android/infobars/previews_lite_page_infobar.h", "android/infobars/reader_mode_infobar.cc", @@ -717,15 +720,21 @@ jumbo_split_static_library("ui") { "android/page_info/connection_info_popup_android.h", "android/page_info/page_info_controller_android.cc", "android/page_info/page_info_controller_android.h", + "android/passwords/credential_leak_dialog_view_android.cc", + "android/passwords/credential_leak_dialog_view_android.h", "android/passwords/manual_filling_view_android.cc", "android/passwords/manual_filling_view_android.h", + "android/passwords/onboarding_dialog_view.cc", + "android/passwords/onboarding_dialog_view.h", "android/passwords/password_generation_dialog_view_android.cc", "android/passwords/password_generation_dialog_view_android.h", "android/passwords/password_generation_editing_popup_view_android.cc", "android/passwords/password_generation_editing_popup_view_android.h", "android/simple_message_box_android.cc", - "android/sms_dialog_android.cc", - "android/sms_dialog_android.h", + "android/sms/sms_infobar.cc", + "android/sms/sms_infobar.h", + "android/sms/sms_infobar_delegate.cc", + "android/sms/sms_infobar_delegate.h", "android/snackbars/auto_signin_prompt_controller.cc", "android/snackbars/auto_signin_prompt_controller.h", "android/ssl_client_certificate_request.cc", @@ -734,7 +743,6 @@ jumbo_split_static_library("ui") { "android/tab_contents/chrome_web_contents_view_delegate_android.h", "android/tab_model/android_live_tab_context.cc", "android/tab_model/android_live_tab_context.h", - "android/tab_model/single_tab_model.cc", "android/tab_model/tab_model.cc", "android/tab_model/tab_model.h", "android/tab_model/tab_model_jni_bridge.cc", @@ -779,6 +787,8 @@ jumbo_split_static_library("ui") { } deps += [ "//chrome/android:jni_headers", + "//chrome/android/features/dev_ui:buildflags", + "//chrome/browser/android/thin_webview:thin_webview", "//components/embedder_support/android:web_contents_delegate", "//components/navigation_interception", "//components/subresource_filter/core/browser", @@ -918,10 +928,8 @@ jumbo_split_static_library("ui") { "global_error/global_error_service.h", "global_error/global_error_service_factory.cc", "global_error/global_error_service_factory.h", - "global_media_controls/media_dialog_controller.cc", - "global_media_controls/media_dialog_controller.h", - "global_media_controls/media_dialog_controller_delegate.cc", - "global_media_controls/media_dialog_controller_delegate.h", + "global_media_controls/media_dialog_delegate.cc", + "global_media_controls/media_dialog_delegate.h", "global_media_controls/media_toolbar_button_controller.cc", "global_media_controls/media_toolbar_button_controller.h", "global_media_controls/media_toolbar_button_controller_delegate.cc", @@ -940,6 +948,10 @@ jumbo_split_static_library("ui") { "hung_renderer/hung_renderer_core.h", "in_product_help/active_tab_tracker.cc", "in_product_help/active_tab_tracker.h", + "in_product_help/global_media_controls_in_product_help.cc", + "in_product_help/global_media_controls_in_product_help.h", + "in_product_help/global_media_controls_in_product_help_factory.cc", + "in_product_help/global_media_controls_in_product_help_factory.h", "in_product_help/in_product_help.h", "in_product_help/reopen_tab_in_product_help.cc", "in_product_help/reopen_tab_in_product_help.h", @@ -949,8 +961,6 @@ jumbo_split_static_library("ui") { "in_product_help/reopen_tab_in_product_help_trigger.h", "intent_picker_tab_helper.cc", "intent_picker_tab_helper.h", - "javascript_dialogs/javascript_dialog_views.cc", - "javascript_dialogs/javascript_dialog_views.h", "layout_constants.cc", "layout_constants.h", "location_bar/location_bar.cc", @@ -1003,6 +1013,12 @@ jumbo_split_static_library("ui") { "page_info/page_info_infobar_delegate.h", "page_info/permission_menu_model.cc", "page_info/permission_menu_model.h", + "passwords/credential_leak_dialog_controller.h", + "passwords/credential_leak_dialog_controller_impl.cc", + "passwords/credential_leak_dialog_controller_impl.h", + "passwords/credential_manager_dialog_controller.h", + "passwords/credential_manager_dialog_controller_impl.cc", + "passwords/credential_manager_dialog_controller_impl.h", "passwords/google_password_manager_navigation_throttle.cc", "passwords/google_password_manager_navigation_throttle.h", "passwords/manage_passwords_bubble_model.cc", @@ -1010,12 +1026,11 @@ jumbo_split_static_library("ui") { "passwords/manage_passwords_icon_view.h", "passwords/manage_passwords_ui_controller.cc", "passwords/manage_passwords_ui_controller.h", - "passwords/password_dialog_controller.h", - "passwords/password_dialog_controller_impl.cc", - "passwords/password_dialog_controller_impl.h", + "passwords/password_base_dialog_controller.h", "passwords/password_dialog_prompts.h", "passwords/passwords_client_ui_delegate.cc", "passwords/passwords_client_ui_delegate.h", + "passwords/passwords_leak_dialog_delegate.h", "passwords/passwords_model_delegate.cc", "passwords/passwords_model_delegate.h", "pdf/adobe_reader_info_win.cc", @@ -1096,10 +1111,10 @@ jumbo_split_static_library("ui") { "tabs/pinned_tab_service_factory.cc", "tabs/pinned_tab_service_factory.h", "tabs/tab_change_type.h", - "tabs/tab_group_data.cc", - "tabs/tab_group_data.h", "tabs/tab_group_id.cc", "tabs/tab_group_id.h", + "tabs/tab_group_visual_data.cc", + "tabs/tab_group_visual_data.h", "tabs/tab_menu_model.cc", "tabs/tab_menu_model.h", "tabs/tab_network_state.cc", @@ -1118,6 +1133,7 @@ jumbo_split_static_library("ui") { "tabs/tab_style.h", "tabs/tab_switch_event_latency_recorder.cc", "tabs/tab_switch_event_latency_recorder.h", + "tabs/tab_types.h", "tabs/tab_utils.cc", "tabs/tab_utils.h", "task_manager/task_manager_columns.cc", @@ -1185,6 +1201,8 @@ jumbo_split_static_library("ui") { "webui/constrained_web_dialog_delegate_base.h", "webui/devtools_ui.cc", "webui/devtools_ui.h", + "webui/devtools_ui_data_source.cc", + "webui/devtools_ui_data_source.h", "webui/downloads/downloads_dom_handler.cc", "webui/downloads/downloads_dom_handler.h", "webui/downloads/downloads_list_tracker.cc", @@ -1214,6 +1232,8 @@ jumbo_split_static_library("ui") { "webui/management_ui.h", "webui/management_ui_handler.cc", "webui/management_ui_handler.h", + "webui/management_ui_handler_chromeos.cc", + "webui/management_ui_handler_chromeos.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", @@ -1241,8 +1261,6 @@ jumbo_split_static_library("ui") { "webui/policy_indicator_localized_strings_provider.h", "webui/profile_info_watcher.cc", "webui/profile_info_watcher.h", - "webui/set_as_default_browser_ui_win.cc", - "webui/set_as_default_browser_ui_win.h", "webui/settings/about_handler.cc", "webui/settings/about_handler.h", "webui/settings/accessibility_main_handler.cc", @@ -1323,6 +1341,8 @@ jumbo_split_static_library("ui") { "webui/theme_handler.h", "webui/theme_source.cc", "webui/theme_source.h", + "webui/web_footer_experiment_ui.cc", + "webui/web_footer_experiment_ui.h", "window_sizer/window_sizer.cc", "window_sizer/window_sizer.h", "zoom/chrome_zoom_level_otr_delegate.cc", @@ -1358,6 +1378,7 @@ jumbo_split_static_library("ui") { "//device/fido", "//services/device/public/mojom", "//services/metrics/public/cpp:metrics_cpp", + "//third_party/blink/public/common:headers", "//third_party/libaddressinput", "//third_party/libaddressinput:strings", "//ui/events", @@ -1388,14 +1409,6 @@ jumbo_split_static_library("ui") { } } - # TODO(crbug.com/980869): Remove the section below. - if (enable_supervised_users && !is_android && !is_chromeos) { - sources += [ - "startup/supervised_users_deprecated_infobar_delegate.cc", - "startup/supervised_users_deprecated_infobar_delegate.h", - ] - } - if (enable_supervised_users) { sources += [ "webui/supervised_user_internals_message_handler.cc", @@ -1403,6 +1416,7 @@ jumbo_split_static_library("ui") { "webui/supervised_user_internals_ui.cc", "webui/supervised_user_internals_ui.h", ] + deps += [ "//chrome/browser/supervised_user/supervised_user_error_page" ] } if (is_chromeos) { @@ -1431,6 +1445,8 @@ jumbo_split_static_library("ui") { "ash/ambient/photo_controller_impl.h", "ash/arc_chrome_actions_client.cc", "ash/arc_chrome_actions_client.h", + "ash/arc_custom_tab_modal_dialog_host.cc", + "ash/arc_custom_tab_modal_dialog_host.h", "ash/ash_shell_init.cc", "ash/ash_shell_init.h", "ash/ash_util.cc", @@ -1536,9 +1552,8 @@ jumbo_split_static_library("ui") { "ash/system_tray_client.h", "ash/tab_scrubber.cc", "ash/tab_scrubber.h", - "ash/tablet_mode_client.cc", - "ash/tablet_mode_client.h", - "ash/tablet_mode_client_observer.h", + "ash/tablet_mode_page_behavior.cc", + "ash/tablet_mode_page_behavior.h", "ash/test_ime_controller.cc", "ash/test_ime_controller.h", "ash/vpn_list_forwarder.cc", @@ -1599,6 +1614,8 @@ jumbo_split_static_library("ui") { "webui/chromeos/add_supervision/add_supervision_handler.h", "webui/chromeos/add_supervision/add_supervision_handler_utils.cc", "webui/chromeos/add_supervision/add_supervision_handler_utils.h", + "webui/chromeos/add_supervision/add_supervision_metrics_recorder.cc", + "webui/chromeos/add_supervision/add_supervision_metrics_recorder.h", "webui/chromeos/add_supervision/add_supervision_ui.cc", "webui/chromeos/add_supervision/add_supervision_ui.h", "webui/chromeos/add_supervision/confirm_signout_dialog.cc", @@ -1645,6 +1662,8 @@ jumbo_split_static_library("ui") { "webui/chromeos/image_source.h", "webui/chromeos/in_session_password_change/confirm_password_change_handler.cc", "webui/chromeos/in_session_password_change/confirm_password_change_handler.h", + "webui/chromeos/in_session_password_change/password_change_dialogs.cc", + "webui/chromeos/in_session_password_change/password_change_dialogs.h", "webui/chromeos/in_session_password_change/password_change_handler.cc", "webui/chromeos/in_session_password_change/password_change_handler.h", "webui/chromeos/in_session_password_change/password_change_ui.cc", @@ -1821,6 +1840,8 @@ jumbo_split_static_library("ui") { "webui/settings/chromeos/account_manager_handler.h", "webui/settings/chromeos/android_apps_handler.cc", "webui/settings/chromeos/android_apps_handler.h", + "webui/settings/chromeos/app_management/app_management_page_handler_factory.cc", + "webui/settings/chromeos/app_management/app_management_page_handler_factory.h", "webui/settings/chromeos/change_picture_handler.cc", "webui/settings/chromeos/change_picture_handler.h", "webui/settings/chromeos/crostini_handler.cc", @@ -1855,6 +1876,8 @@ jumbo_split_static_library("ui") { "webui/settings/chromeos/parental_controls_handler.h", "webui/settings/chromeos/plugin_vm_handler.cc", "webui/settings/chromeos/plugin_vm_handler.h", + "webui/settings/chromeos/wallpaper_handler.cc", + "webui/settings/chromeos/wallpaper_handler.h", "webui/settings/tts_handler.cc", "webui/settings/tts_handler.h", "webui/signin/inline_login_handler_chromeos.cc", @@ -1875,7 +1898,9 @@ jumbo_split_static_library("ui") { "//ash/public/cpp/resources:ash_public_unscaled_resources", "//ash/public/cpp/vector_icons", "//chrome/browser/chromeos", + "//chrome/browser/chromeos:backdrop_wallpaper_proto", "//chrome/browser/resources/chromeos:camera_resources", + "//chrome/browser/ui/webui/app_management:mojo_bindings", "//chrome/browser/ui/webui/chromeos/add_supervision:mojo_bindings", "//chrome/browser/ui/webui/chromeos/machine_learning:mojo_bindings", "//chrome/services/file_util/public/cpp", @@ -1898,6 +1923,7 @@ jumbo_split_static_library("ui") { "//chromeos/dbus/power", "//chromeos/dbus/session_manager", "//chromeos/dbus/system_clock", + "//chromeos/disks", "//chromeos/login/auth", "//chromeos/login/login_state", "//chromeos/login/session", @@ -1906,6 +1932,7 @@ jumbo_split_static_library("ui") { "//chromeos/services/assistant/public:feature_flags", "//chromeos/services/assistant/public/mojom", "//chromeos/services/assistant/public/proto:proto", + "//chromeos/services/cellular_setup", "//chromeos/services/cellular_setup/public/mojom", "//chromeos/services/machine_learning/public/cpp", "//chromeos/services/multidevice_setup/public/cpp", @@ -1949,16 +1976,17 @@ jumbo_split_static_library("ui") { if (use_cras) { defines += [ "USE_CRAS" ] } - - if (enable_kiosk_next) { - defines += [ "KIOSK_NEXT" ] - } } if (is_win || is_mac || is_desktop_linux || is_chromeos) { sources += [ + "autofill/payments/webauthn_offer_dialog.h", + "autofill/payments/webauthn_offer_dialog_controller.cc", + "autofill/payments/webauthn_offer_dialog_controller.h", "frame/window_frame_util.cc", "frame/window_frame_util.h", + "views/autofill/payments/webauthn_offer_dialog_view.cc", + "views/autofill/payments/webauthn_offer_dialog_view.h", "views/close_bubble_on_tab_activation_helper.cc", "views/close_bubble_on_tab_activation_helper.h", "views/hats/hats_bubble_view.cc", @@ -2003,14 +2031,10 @@ jumbo_split_static_library("ui") { "user_manager.h", "views/external_protocol_dialog.cc", "views/external_protocol_dialog.h", - "views/message_center/popups_only_ui_delegate.cc", - "views/message_center/popups_only_ui_delegate.h", "views/profiles/badged_profile_photo.cc", "views/profiles/badged_profile_photo.h", - "views/profiles/dice_accounts_menu.cc", - "views/profiles/dice_accounts_menu.h", - "views/profiles/profile_chooser_view.cc", - "views/profiles/profile_chooser_view.h", + "views/profiles/profile_menu_view.cc", + "views/profiles/profile_menu_view.h", "views/profiles/signin_view_controller_delegate_views.cc", "views/profiles/signin_view_controller_delegate_views.h", "views/profiles/user_manager_view.cc", @@ -2051,22 +2075,20 @@ jumbo_split_static_library("ui") { "webui/signin/user_manager_screen_handler.h", "webui/signin/user_manager_ui.cc", "webui/signin/user_manager_ui.h", - "webui/welcome/nux/bookmark_handler.cc", - "webui/welcome/nux/bookmark_handler.h", - "webui/welcome/nux/bookmark_item.cc", - "webui/welcome/nux/bookmark_item.h", - "webui/welcome/nux/constants.cc", - "webui/welcome/nux/constants.h", - "webui/welcome/nux/google_apps_handler.cc", - "webui/welcome/nux/google_apps_handler.h", - "webui/welcome/nux/ntp_background_fetcher.cc", - "webui/welcome/nux/ntp_background_fetcher.h", - "webui/welcome/nux/ntp_background_handler.cc", - "webui/welcome/nux/ntp_background_handler.h", - "webui/welcome/nux/set_as_default_handler.cc", - "webui/welcome/nux/set_as_default_handler.h", - "webui/welcome/nux_helper.cc", - "webui/welcome/nux_helper.h", + "webui/welcome/bookmark_handler.cc", + "webui/welcome/bookmark_handler.h", + "webui/welcome/bookmark_item.cc", + "webui/welcome/bookmark_item.h", + "webui/welcome/google_apps_handler.cc", + "webui/welcome/google_apps_handler.h", + "webui/welcome/helpers.cc", + "webui/welcome/helpers.h", + "webui/welcome/ntp_background_fetcher.cc", + "webui/welcome/ntp_background_fetcher.h", + "webui/welcome/ntp_background_handler.cc", + "webui/welcome/ntp_background_handler.h", + "webui/welcome/set_as_default_handler.cc", + "webui/welcome/set_as_default_handler.h", "webui/welcome/welcome_handler.cc", "webui/welcome/welcome_handler.h", "webui/welcome/welcome_ui.cc", @@ -2232,6 +2254,8 @@ jumbo_split_static_library("ui") { "cocoa/tab_contents/chrome_web_contents_view_delegate_mac.mm", "cocoa/tab_contents/web_drag_bookmark_handler_mac.h", "cocoa/tab_contents/web_drag_bookmark_handler_mac.mm", + "cocoa/tab_menu_bridge.h", + "cocoa/tab_menu_bridge.mm", "cocoa/task_manager_mac.h", "cocoa/task_manager_mac.mm", "cocoa/touchbar/browser_window_default_touch_bar.h", @@ -2294,7 +2318,6 @@ jumbo_split_static_library("ui") { "startup/credential_provider_signin_dialog_win.h", "startup/credential_provider_signin_info_fetcher_win.cc", "startup/credential_provider_signin_info_fetcher_win.h", - "startup/default_browser_prompt_win.cc", "views/certificate_viewer_win.cc", "views/chrome_cleaner_dialog_win.cc", "views/chrome_cleaner_dialog_win.h", @@ -2403,6 +2426,8 @@ jumbo_split_static_library("ui") { "views/first_run_dialog.cc", "views/first_run_dialog.h", "views/frame/browser_desktop_window_tree_host.h", + "views/frame/desktop_browser_frame_aura_linux.cc", + "views/frame/desktop_browser_frame_aura_linux.h", "views/status_icons/status_icon_linux_wrapper.cc", "views/status_icons/status_icon_linux_wrapper.h", "webui/help/version_updater_basic.cc", @@ -2432,8 +2457,6 @@ jumbo_split_static_library("ui") { sources += [ "views/frame/browser_desktop_window_tree_host_x11.cc", "views/frame/browser_desktop_window_tree_host_x11.h", - "views/frame/desktop_browser_frame_aurax11.cc", - "views/frame/desktop_browser_frame_aurax11.h", "views/frame/global_menu_bar_registrar_x11.cc", "views/frame/global_menu_bar_registrar_x11.h", "views/frame/global_menu_bar_x11.cc", @@ -2448,6 +2471,7 @@ jumbo_split_static_library("ui") { ] configs += [ "//build/config/linux:x11" ] deps += [ + "//components/dbus/menu", "//ui/events/devices", "//ui/events/devices/x11", "//ui/events/platform/x11", @@ -2459,6 +2483,7 @@ jumbo_split_static_library("ui") { "views/frame/browser_desktop_window_tree_host_platform.h", "views/frame/native_browser_frame_factory_ozone.cc", ] + deps += [ "//ui/platform_window" ] } if (use_gtk) { # This is the only component that can interact with gtk. @@ -2505,11 +2530,15 @@ jumbo_split_static_library("ui") { "autofill/payments/local_card_migration_dialog_state.h", "autofill/payments/manage_migration_ui_controller.cc", "autofill/payments/manage_migration_ui_controller.h", + "autofill/payments/save_card_bubble_controller.h", "autofill/payments/save_card_bubble_controller_impl.cc", "autofill/payments/save_card_bubble_controller_impl.h", "autofill/payments/save_card_bubble_view.h", "autofill/payments/save_card_ui.h", "bubble_anchor_util.h", + "cookie_controls/cookie_controls_controller.cc", + "cookie_controls/cookie_controls_controller.h", + "cookie_controls/cookie_controls_view.h", "manifest_web_app_browser_controller.cc", "manifest_web_app_browser_controller.h", "send_tab_to_self/send_tab_to_self_bubble_controller.cc", @@ -2631,6 +2660,8 @@ jumbo_split_static_library("ui") { "views/desktop_capture/desktop_media_tab_list.h", "views/device_chooser_content_view.cc", "views/device_chooser_content_view.h", + "views/devtools_process_observer.cc", + "views/devtools_process_observer.h", "views/download/download_danger_prompt_views.cc", "views/download/download_in_progress_dialog_view.cc", "views/download/download_in_progress_dialog_view.h", @@ -2653,6 +2684,8 @@ jumbo_split_static_library("ui") { "views/extensions/bookmark_app_confirmation_view.h", "views/extensions/chooser_dialog_view.cc", "views/extensions/chooser_dialog_view.h", + "views/extensions/extension_context_menu_controller.cc", + "views/extensions/extension_context_menu_controller.h", "views/extensions/extension_install_dialog_view.cc", "views/extensions/extension_install_dialog_view.h", "views/extensions/extension_installed_bubble_view.cc", @@ -2662,6 +2695,8 @@ jumbo_split_static_library("ui") { "views/extensions/extension_uninstall_dialog_view.cc", "views/extensions/extensions_menu_button.cc", "views/extensions/extensions_menu_button.h", + "views/extensions/extensions_menu_item_view.cc", + "views/extensions/extensions_menu_item_view.h", "views/extensions/extensions_menu_view.cc", "views/extensions/extensions_menu_view.h", "views/extensions/extensions_toolbar_button.cc", @@ -2676,6 +2711,8 @@ jumbo_split_static_library("ui") { "views/feature_promos/feature_promo_bubble_timeout.h", "views/feature_promos/feature_promo_bubble_view.cc", "views/feature_promos/feature_promo_bubble_view.h", + "views/feature_promos/global_media_controls_promo_controller.cc", + "views/feature_promos/global_media_controls_promo_controller.h", "views/feature_promos/reopen_tab_promo_controller.cc", "views/feature_promos/reopen_tab_promo_controller.h", "views/find_bar_host.cc", @@ -2725,6 +2762,8 @@ jumbo_split_static_library("ui") { "views/frame/system_menu_model_delegate.h", "views/frame/tab_strip_region_view.cc", "views/frame/tab_strip_region_view.h", + "views/frame/terminal_system_app_menu_button_chromeos.cc", + "views/frame/terminal_system_app_menu_button_chromeos.h", "views/frame/toolbar_button_provider.h", "views/frame/top_container_view.cc", "views/frame/top_container_view.h", @@ -2732,6 +2771,10 @@ jumbo_split_static_library("ui") { "views/frame/web_contents_close_handler.cc", "views/frame/web_contents_close_handler.h", "views/frame/web_contents_close_handler_delegate.h", + "views/frame/web_footer_experiment_view.cc", + "views/frame/web_footer_experiment_view.h", + "views/front_eliding_title_label.cc", + "views/front_eliding_title_label.h", "views/fullscreen_control/fullscreen_control_host.cc", "views/fullscreen_control/fullscreen_control_host.h", "views/fullscreen_control/fullscreen_control_popup.cc", @@ -2750,6 +2793,8 @@ jumbo_split_static_library("ui") { "views/global_media_controls/media_toolbar_button_view.h", "views/hover_button.cc", "views/hover_button.h", + "views/hover_button_controller.cc", + "views/hover_button_controller.h", "views/hung_renderer_view.cc", "views/hung_renderer_view.h", "views/ime/ime_warning_bubble_view.cc", @@ -2764,10 +2809,20 @@ jumbo_split_static_library("ui") { "views/infobars/infobar_container_view.h", "views/infobars/infobar_view.cc", "views/infobars/infobar_view.h", + "views/javascript_dialog_views.cc", + "views/javascript_dialog_views.h", + "views/layout/animating_layout_manager.cc", + "views/layout/animating_layout_manager.h", + "views/layout/interpolating_layout_manager.cc", + "views/layout/interpolating_layout_manager.h", "views/load_complete_listener.cc", "views/load_complete_listener.h", "views/location_bar/content_setting_image_view.cc", "views/location_bar/content_setting_image_view.h", + "views/location_bar/cookie_controls_bubble_view.cc", + "views/location_bar/cookie_controls_bubble_view.h", + "views/location_bar/cookie_controls_icon_view.cc", + "views/location_bar/cookie_controls_icon_view.h", "views/location_bar/custom_tab_bar_view.cc", "views/location_bar/custom_tab_bar_view.h", "views/location_bar/find_bar_icon.cc", @@ -2793,8 +2848,6 @@ jumbo_split_static_library("ui") { "views/login_handler_views.cc", "views/login_view.cc", "views/login_view.h", - "views/material_refresh_layout_provider.cc", - "views/material_refresh_layout_provider.h", "views/md_text_button_with_down_arrow.cc", "views/md_text_button_with_down_arrow.h", "views/media_router/cast_dialog_helper.cc", @@ -2856,8 +2909,6 @@ jumbo_split_static_library("ui") { "views/overlay/back_to_tab_image_button.h", "views/overlay/close_image_button.cc", "views/overlay/close_image_button.h", - "views/overlay/mute_image_button.cc", - "views/overlay/mute_image_button.h", "views/overlay/overlay_window_views.cc", "views/overlay/overlay_window_views.h", "views/overlay/playback_image_button.cc", @@ -2888,10 +2939,14 @@ jumbo_split_static_library("ui") { "views/page_info/permission_selector_row.cc", "views/page_info/permission_selector_row.h", "views/page_info/permission_selector_row_observer.h", + "views/page_info/safety_tip_page_info_bubble_view.cc", + "views/page_info/safety_tip_page_info_bubble_view.h", "views/passwords/account_chooser_dialog_view.cc", "views/passwords/account_chooser_dialog_view.h", "views/passwords/auto_signin_first_run_dialog_view.cc", "views/passwords/auto_signin_first_run_dialog_view.h", + "views/passwords/credential_leak_dialog_view.cc", + "views/passwords/credential_leak_dialog_view.h", "views/passwords/credentials_item_view.cc", "views/passwords/credentials_item_view.h", "views/passwords/manage_passwords_icon_views.cc", @@ -2987,10 +3042,10 @@ jumbo_split_static_library("ui") { "views/send_tab_to_self/send_tab_to_self_icon_view.h", "views/session_crashed_bubble_view.cc", "views/session_crashed_bubble_view.h", - "views/sharing/click_to_call/click_to_call_dialog_view.cc", - "views/sharing/click_to_call/click_to_call_dialog_view.h", - "views/sharing/click_to_call/click_to_call_icon_view.cc", - "views/sharing/click_to_call/click_to_call_icon_view.h", + "views/sharing/sharing_dialog_view.cc", + "views/sharing/sharing_dialog_view.h", + "views/sharing/sharing_icon_view.cc", + "views/sharing/sharing_icon_view.h", "views/simple_message_box_views.cc", "views/simple_message_box_views.h", "views/status_bubble_views.cc", @@ -3013,6 +3068,8 @@ jumbo_split_static_library("ui") { "views/tabs/alert_indicator.h", "views/tabs/browser_tab_strip_controller.cc", "views/tabs/browser_tab_strip_controller.h", + "views/tabs/color_picker_view.cc", + "views/tabs/color_picker_view.h", "views/tabs/glow_hover_controller.cc", "views/tabs/glow_hover_controller.h", "views/tabs/new_tab_button.cc", @@ -3031,6 +3088,8 @@ jumbo_split_static_library("ui") { "views/tabs/tab_drag_context.h", "views/tabs/tab_drag_controller.cc", "views/tabs/tab_drag_controller.h", + "views/tabs/tab_group_editor_bubble_view.cc", + "views/tabs/tab_group_editor_bubble_view.h", "views/tabs/tab_group_header.cc", "views/tabs/tab_group_header.h", "views/tabs/tab_hover_card_bubble_view.cc", @@ -3039,17 +3098,19 @@ jumbo_split_static_library("ui") { "views/tabs/tab_icon.h", "views/tabs/tab_renderer_data.cc", "views/tabs/tab_renderer_data.h", + "views/tabs/tab_slot_view.h", "views/tabs/tab_strip.cc", "views/tabs/tab_strip.h", - "views/tabs/tab_strip_animator.cc", - "views/tabs/tab_strip_animator.h", "views/tabs/tab_strip_controller.h", "views/tabs/tab_strip_layout.cc", "views/tabs/tab_strip_layout.h", "views/tabs/tab_strip_layout_helper.cc", "views/tabs/tab_strip_layout_helper.h", + "views/tabs/tab_strip_layout_types.h", "views/tabs/tab_style_views.cc", "views/tabs/tab_style_views.h", + "views/tabs/tab_width_constraints.cc", + "views/tabs/tab_width_constraints.h", "views/tabs/window_finder.h", "views/task_manager_view.cc", "views/task_manager_view.h", @@ -3166,8 +3227,6 @@ jumbo_split_static_library("ui") { if (is_linux) { sources += [ - "views/frame/browser_command_handler_linux.cc", - "views/frame/browser_command_handler_linux.h", "views/process_singleton_dialog_linux.cc", "views/status_icons/status_tray_linux.cc", "views/status_icons/status_tray_linux.h", @@ -3402,8 +3461,14 @@ jumbo_split_static_library("ui") { "app_list/search/arc/arc_playstore_search_result.h", "app_list/search/chrome_search_result.cc", "app_list/search/chrome_search_result.h", + "app_list/search/common/file_icon_util.cc", + "app_list/search/common/file_icon_util.h", "app_list/search/common/url_icon_source.cc", "app_list/search/common/url_icon_source.h", + "app_list/search/drive_quick_access_provider.cc", + "app_list/search/drive_quick_access_provider.h", + "app_list/search/drive_quick_access_result.cc", + "app_list/search/drive_quick_access_result.h", "app_list/search/extension_app_result.cc", "app_list/search/extension_app_result.h", "app_list/search/logging/search_ranking_event_logger.cc", @@ -3426,6 +3491,8 @@ jumbo_split_static_library("ui") { "app_list/search/search_result_ranker/app_launch_data.h", "app_list/search/search_result_ranker/app_launch_event_logger.cc", "app_list/search/search_result_ranker/app_launch_event_logger.h", + "app_list/search/search_result_ranker/app_launch_event_logger_helper.cc", + "app_list/search/search_result_ranker/app_launch_event_logger_helper.h", "app_list/search/search_result_ranker/app_launch_predictor.cc", "app_list/search/search_result_ranker/app_launch_predictor.h", "app_list/search/search_result_ranker/app_list_launch_metrics_provider.cc", @@ -3440,6 +3507,8 @@ jumbo_split_static_library("ui") { "app_list/search/search_result_ranker/frecency_store.h", "app_list/search/search_result_ranker/histogram_util.cc", "app_list/search/search_result_ranker/histogram_util.h", + "app_list/search/search_result_ranker/ml_app_rank_provider.cc", + "app_list/search/search_result_ranker/ml_app_rank_provider.h", "app_list/search/search_result_ranker/ranking_item_util.cc", "app_list/search/search_result_ranker/ranking_item_util.h", "app_list/search/search_result_ranker/recurrence_predictor.cc", @@ -3450,12 +3519,18 @@ jumbo_split_static_library("ui") { "app_list/search/search_result_ranker/recurrence_ranker_util.h", "app_list/search/search_result_ranker/search_result_ranker.cc", "app_list/search/search_result_ranker/search_result_ranker.h", + "app_list/search/search_utils/sequence_matcher.cc", + "app_list/search/search_utils/sequence_matcher.h", "app_list/search/settings_shortcut/settings_shortcut_metadata.cc", "app_list/search/settings_shortcut/settings_shortcut_metadata.h", "app_list/search/settings_shortcut/settings_shortcut_provider.cc", "app_list/search/settings_shortcut/settings_shortcut_provider.h", "app_list/search/settings_shortcut/settings_shortcut_result.cc", "app_list/search/settings_shortcut/settings_shortcut_result.h", + "app_list/search/zero_state_file_provider.cc", + "app_list/search/zero_state_file_provider.h", + "app_list/search/zero_state_file_result.cc", + "app_list/search/zero_state_file_result.h", ] deps += [ # TODO(wutao): Put new icons resources to ash/public/cpp/vector_icons/ @@ -3468,11 +3543,16 @@ jumbo_split_static_library("ui") { "//chrome/browser/ui/app_list/search/search_result_ranker:app_launch_predictor_proto", "//chrome/browser/ui/app_list/search/search_result_ranker:app_list_launch_recorder_proto", "//chrome/browser/ui/app_list/search/search_result_ranker:recurrence_ranker_proto", + "//components/assist_ranker", + "//components/assist_ranker/proto", + "//ui/file_manager:file_manager", ] if (is_chromeos) { sources += [ "app_icon_loader_delegate.h", + "app_list/app_service_app_icon_loader.cc", + "app_list/app_service_app_icon_loader.h", "app_list/app_service_app_item.cc", "app_list/app_service_app_item.h", "app_list/app_service_app_model_builder.cc", @@ -3579,6 +3659,8 @@ jumbo_split_static_library("ui") { "ash/launcher/internal_app_shelf_context_menu.h", "ash/launcher/internal_app_window_shelf_controller.cc", "ash/launcher/internal_app_window_shelf_controller.h", + "ash/launcher/launcher_app_service_app_updater.cc", + "ash/launcher/launcher_app_service_app_updater.h", "ash/launcher/launcher_arc_app_updater.cc", "ash/launcher/launcher_arc_app_updater.h", "ash/launcher/launcher_crostini_app_updater.cc", @@ -3607,6 +3689,7 @@ jumbo_split_static_library("ui") { deps += [ "//chrome/services/app_service/public/cpp:app_update", "//chrome/services/app_service/public/cpp:icon_loader", + "//components/services/app_service/public/cpp:app_file_handling", ] } } @@ -3616,6 +3699,12 @@ jumbo_split_static_library("ui") { "//ash/public/cpp", "//chromeos/services/assistant:lib", "//chromeos/services/assistant/public/mojom", + "//chromeos/services/network_config/public/mojom", + "//services/audio/public/mojom", + "//services/device/public/mojom", + "//services/identity/public/mojom", + "//services/media_session/public/mojom", + "//services/preferences/public/mojom", ] sources += [ @@ -3625,10 +3714,16 @@ jumbo_split_static_library("ui") { "ash/assistant/assistant_context_util.h", "ash/assistant/assistant_image_downloader.cc", "ash/assistant/assistant_image_downloader.h", + "ash/assistant/assistant_service_connection.cc", + "ash/assistant/assistant_service_connection.h", "ash/assistant/assistant_setup.cc", "ash/assistant/assistant_setup.h", "ash/assistant/device_actions.cc", "ash/assistant/device_actions.h", + "ash/assistant/proactive_suggestions_client_impl.cc", + "ash/assistant/proactive_suggestions_client_impl.h", + "ash/assistant/proactive_suggestions_loader.cc", + "ash/assistant/proactive_suggestions_loader.h", ] } @@ -3680,14 +3775,14 @@ jumbo_split_static_library("ui") { "extensions/extensions_container.h", "extensions/hosted_app_browser_controller.cc", "extensions/hosted_app_browser_controller.h", - "extensions/hosted_app_menu_model.cc", - "extensions/hosted_app_menu_model.h", "extensions/icon_with_badge_image_source.cc", "extensions/icon_with_badge_image_source.h", "extensions/installation_error_infobar_delegate.cc", "extensions/installation_error_infobar_delegate.h", "extensions/settings_api_bubble_helpers.cc", "extensions/settings_api_bubble_helpers.h", + "extensions/terminal_system_app_menu_model_chromeos.cc", + "extensions/terminal_system_app_menu_model_chromeos.h", "views/extensions/browser_action_drag_data.cc", "views/extensions/browser_action_drag_data.h", "views/extensions/extension_action_platform_delegate_views.cc", @@ -3706,14 +3801,20 @@ jumbo_split_static_library("ui") { "views/extensions/media_gallery_checkbox_view.h", "web_applications/app_browser_controller.cc", "web_applications/app_browser_controller.h", - "web_applications/system_web_app_ui_utils_chromeos.cc", - "web_applications/system_web_app_ui_utils_chromeos.h", + "web_applications/system_web_app_ui_utils.cc", + "web_applications/system_web_app_ui_utils.h", + "web_applications/web_app_browser_controller.cc", + "web_applications/web_app_browser_controller.h", "web_applications/web_app_dialog_manager.cc", "web_applications/web_app_dialog_manager.h", "web_applications/web_app_dialog_utils.cc", "web_applications/web_app_dialog_utils.h", "web_applications/web_app_launch_manager.cc", "web_applications/web_app_launch_manager.h", + "web_applications/web_app_launch_utils.cc", + "web_applications/web_app_launch_utils.h", + "web_applications/web_app_menu_model.cc", + "web_applications/web_app_menu_model.h", "web_applications/web_app_metrics.cc", "web_applications/web_app_metrics.h", "web_applications/web_app_metrics_factory.cc", @@ -3839,10 +3940,6 @@ jumbo_split_static_library("ui") { deps += [ "//dbus" ] } - if (use_gio) { - configs += [ "//build/linux:gio_config" ] - } - if (use_nss_certs) { sources += [ "crypto_module_delegate_nss.cc", @@ -3874,6 +3971,19 @@ jumbo_split_static_library("ui") { "//components/offline_pages/core/prefetch", ] } + + if (enable_webui_tab_strip) { + deps += [ "//chrome/browser/resources:tab_strip_resources" ] + + sources += [ + "views/frame/webui_tab_strip_container_view.cc", + "views/frame/webui_tab_strip_container_view.h", + "webui/tab_strip/tab_strip_ui.cc", + "webui/tab_strip/tab_strip_ui.h", + "webui/tab_strip/thumbnail_tracker.cc", + "webui/tab_strip/thumbnail_tracker.h", + ] + } } # In GYP this is part of test_support_common. @@ -3955,10 +4065,12 @@ static_library("test_support") { "exclusive_access/fullscreen_controller_test.h", "global_error/global_error_waiter.cc", "global_error/global_error_waiter.h", + "passwords/credential_manager_dialog_controller_mock.cc", + "passwords/credential_manager_dialog_controller_mock.h", "passwords/manage_passwords_ui_controller_mock.cc", "passwords/manage_passwords_ui_controller_mock.h", - "passwords/password_dialog_controller_mock.cc", - "passwords/password_dialog_controller_mock.h", + "passwords/passwords_leak_dialog_delegate_mock.cc", + "passwords/passwords_leak_dialog_delegate_mock.h", "passwords/passwords_model_delegate_mock.cc", "passwords/passwords_model_delegate_mock.h", "tabs/tab_ukm_test_helper.cc", @@ -3980,8 +4092,6 @@ static_library("test_support") { sources += [ "ash/ash_test_util.cc", "ash/ash_test_util.h", - "ash/fake_tablet_mode_controller.cc", - "ash/fake_tablet_mode_controller.h", "ash/test_login_screen.cc", "ash/test_login_screen.h", "ash/test_login_screen_model.cc", diff --git a/chromium/chrome/browser/ui/android/widget/BUILD.gn b/chromium/chrome/browser/ui/android/widget/BUILD.gn new file mode 100644 index 00000000000..13fa251ecb6 --- /dev/null +++ b/chromium/chrome/browser/ui/android/widget/BUILD.gn @@ -0,0 +1,102 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/android/rules.gni") + +android_library("java") { + java_files = [ + "java/src/org/chromium/chrome/browser/ui/widget/CompositeTouchDelegate.java", + "java/src/org/chromium/chrome/browser/ui/widget/FadingShadow.java", + "java/src/org/chromium/chrome/browser/ui/widget/FadingShadowView.java", + "java/src/org/chromium/chrome/browser/ui/widget/ListMenuButton.java", + "java/src/org/chromium/chrome/browser/ui/widget/text/TextViewWithCompoundDrawables.java", + ] + + deps = [ + ":ui_widget_java_resources", + "//base:base_java", + "//third_party/android_deps:android_support_v7_appcompat_java", + "//third_party/android_deps:com_android_support_design_java", + "//ui/android:ui_java", + ] +} + +android_resources("ui_widget_java_resources") { + custom_package = "org.chromium.chrome.browser.ui.widget" + resource_dirs = [ "java/res" ] + deps = [ + ":ui_widget_strings_grd", + "//ui/android:ui_java_resources", + ] +} + +java_strings_grd("ui_widget_strings_grd") { + grd_file = "java/strings/android_ui_widget_strings.grd" + outputs = [ + "values/android_ui_widget_strings.xml", + "values-am/android_ui_widget_strings.xml", + "values-ar/android_ui_widget_strings.xml", + "values-bg/android_ui_widget_strings.xml", + "values-bn/android_ui_widget_strings.xml", + "values-ca/android_ui_widget_strings.xml", + "values-cs/android_ui_widget_strings.xml", + "values-da/android_ui_widget_strings.xml", + "values-de/android_ui_widget_strings.xml", + "values-el/android_ui_widget_strings.xml", + "values-en-rGB/android_ui_widget_strings.xml", + "values-es/android_ui_widget_strings.xml", + "values-es-rUS/android_ui_widget_strings.xml", + "values-et/android_ui_widget_strings.xml", + "values-fa/android_ui_widget_strings.xml", + "values-fi/android_ui_widget_strings.xml", + "values-fr/android_ui_widget_strings.xml", + "values-gu/android_ui_widget_strings.xml", + "values-hi/android_ui_widget_strings.xml", + "values-hr/android_ui_widget_strings.xml", + "values-hu/android_ui_widget_strings.xml", + "values-in/android_ui_widget_strings.xml", + "values-it/android_ui_widget_strings.xml", + "values-iw/android_ui_widget_strings.xml", + "values-ja/android_ui_widget_strings.xml", + "values-kn/android_ui_widget_strings.xml", + "values-ko/android_ui_widget_strings.xml", + "values-lt/android_ui_widget_strings.xml", + "values-lv/android_ui_widget_strings.xml", + "values-ml/android_ui_widget_strings.xml", + "values-mr/android_ui_widget_strings.xml", + "values-ms/android_ui_widget_strings.xml", + "values-nb/android_ui_widget_strings.xml", + "values-nl/android_ui_widget_strings.xml", + "values-pl/android_ui_widget_strings.xml", + "values-pt-rBR/android_ui_widget_strings.xml", + "values-pt-rPT/android_ui_widget_strings.xml", + "values-ro/android_ui_widget_strings.xml", + "values-ru/android_ui_widget_strings.xml", + "values-sk/android_ui_widget_strings.xml", + "values-sl/android_ui_widget_strings.xml", + "values-sr/android_ui_widget_strings.xml", + "values-sv/android_ui_widget_strings.xml", + "values-sw/android_ui_widget_strings.xml", + "values-ta/android_ui_widget_strings.xml", + "values-te/android_ui_widget_strings.xml", + "values-th/android_ui_widget_strings.xml", + "values-tl/android_ui_widget_strings.xml", + "values-tr/android_ui_widget_strings.xml", + "values-uk/android_ui_widget_strings.xml", + "values-vi/android_ui_widget_strings.xml", + "values-zh-rCN/android_ui_widget_strings.xml", + "values-zh-rTW/android_ui_widget_strings.xml", + ] +} + +junit_binary("ui_widget_junit_tests") { + java_files = [ "junit/src/org/chromium/chrome//browser/ui/widget/CompositeTouchDelegateTest.java" ] + deps = [ + ":java", + "//base:base_java", + "//base:base_java_test_support", + "//base:base_junit_test_support", + "//base/test:test_support_java", + ] +} diff --git a/chromium/chrome/browser/ui/android/widget/java/strings/android_ui_widget_strings.grd b/chromium/chrome/browser/ui/android/widget/java/strings/android_ui_widget_strings.grd new file mode 100644 index 00000000000..258217f9954 --- /dev/null +++ b/chromium/chrome/browser/ui/android/widget/java/strings/android_ui_widget_strings.grd @@ -0,0 +1,119 @@ +<?xml version="1.0" encoding="UTF-8"?> +<grit latest_public_release="0" current_release="1" output_all_resource_defines="false"> + <outputs> + <output filename="values-am/android_ui_widget_strings.xml" lang="am" type="android" /> + <output filename="values-ar/android_ui_widget_strings.xml" lang="ar" type="android" /> + <output filename="values-bg/android_ui_widget_strings.xml" lang="bg" type="android" /> + <output filename="values-bn/android_ui_widget_strings.xml" lang="bn" type="android" /> + <output filename="values-ca/android_ui_widget_strings.xml" lang="ca" type="android" /> + <output filename="values-cs/android_ui_widget_strings.xml" lang="cs" type="android" /> + <output filename="values-da/android_ui_widget_strings.xml" lang="da" type="android" /> + <output filename="values-de/android_ui_widget_strings.xml" lang="de" type="android" /> + <output filename="values-el/android_ui_widget_strings.xml" lang="el" type="android" /> + <output filename="values/android_ui_widget_strings.xml" lang="en" type="android" /> + <output filename="values-en-rGB/android_ui_widget_strings.xml" lang="en-GB" type="android" /> + <output filename="values-es/android_ui_widget_strings.xml" lang="es" type="android" /> + <output filename="values-es-rUS/android_ui_widget_strings.xml" lang="es-419" type="android" /> + <output filename="values-et/android_ui_widget_strings.xml" lang="et" type="android" /> + <output filename="values-fa/android_ui_widget_strings.xml" lang="fa" type="android" /> + <output filename="values-fi/android_ui_widget_strings.xml" lang="fi" type="android" /> + <output filename="values-tl/android_ui_widget_strings.xml" lang="fil" type="android" /> + <output filename="values-fr/android_ui_widget_strings.xml" lang="fr" type="android" /> + <output filename="values-gu/android_ui_widget_strings.xml" lang="gu" type="android" /> + <output filename="values-hi/android_ui_widget_strings.xml" lang="hi" type="android" /> + <output filename="values-hr/android_ui_widget_strings.xml" lang="hr" type="android" /> + <output filename="values-hu/android_ui_widget_strings.xml" lang="hu" type="android" /> + <output filename="values-in/android_ui_widget_strings.xml" lang="id" type="android" /> + <output filename="values-it/android_ui_widget_strings.xml" lang="it" type="android" /> + <output filename="values-iw/android_ui_widget_strings.xml" lang="iw" type="android" /> + <output filename="values-ja/android_ui_widget_strings.xml" lang="ja" type="android" /> + <output filename="values-kn/android_ui_widget_strings.xml" lang="kn" type="android" /> + <output filename="values-ko/android_ui_widget_strings.xml" lang="ko" type="android" /> + <output filename="values-lt/android_ui_widget_strings.xml" lang="lt" type="android" /> + <output filename="values-lv/android_ui_widget_strings.xml" lang="lv" type="android" /> + <output filename="values-ml/android_ui_widget_strings.xml" lang="ml" type="android" /> + <output filename="values-mr/android_ui_widget_strings.xml" lang="mr" type="android" /> + <output filename="values-ms/android_ui_widget_strings.xml" lang="ms" type="android" /> + <output filename="values-nl/android_ui_widget_strings.xml" lang="nl" type="android" /> + <output filename="values-nb/android_ui_widget_strings.xml" lang="no" type="android" /> + <output filename="values-pl/android_ui_widget_strings.xml" lang="pl" type="android" /> + <output filename="values-pt-rBR/android_ui_widget_strings.xml" lang="pt-BR" type="android" /> + <output filename="values-pt-rPT/android_ui_widget_strings.xml" lang="pt-PT" type="android" /> + <output filename="values-ro/android_ui_widget_strings.xml" lang="ro" type="android" /> + <output filename="values-ru/android_ui_widget_strings.xml" lang="ru" type="android" /> + <output filename="values-sk/android_ui_widget_strings.xml" lang="sk" type="android" /> + <output filename="values-sl/android_ui_widget_strings.xml" lang="sl" type="android" /> + <output filename="values-sr/android_ui_widget_strings.xml" lang="sr" type="android" /> + <output filename="values-sv/android_ui_widget_strings.xml" lang="sv" type="android" /> + <output filename="values-sw/android_ui_widget_strings.xml" lang="sw" type="android" /> + <output filename="values-ta/android_ui_widget_strings.xml" lang="ta" type="android" /> + <output filename="values-te/android_ui_widget_strings.xml" lang="te" type="android" /> + <output filename="values-th/android_ui_widget_strings.xml" lang="th" type="android" /> + <output filename="values-tr/android_ui_widget_strings.xml" lang="tr" type="android" /> + <output filename="values-uk/android_ui_widget_strings.xml" lang="uk" type="android" /> + <output filename="values-vi/android_ui_widget_strings.xml" lang="vi" type="android" /> + <output filename="values-zh-rCN/android_ui_widget_strings.xml" lang="zh-CN" type="android" /> + <output filename="values-zh-rTW/android_ui_widget_strings.xml" lang="zh-TW" type="android" /> + </outputs> + <translations> + <file lang="am" path="translations/android_ui_widget_strings_am.xtb" /> + <file lang="ar" path="translations/android_ui_widget_strings_ar.xtb" /> + <file lang="bg" path="translations/android_ui_widget_strings_bg.xtb" /> + <file lang="bn" path="translations/android_ui_widget_strings_bn.xtb" /> + <file lang="ca" path="translations/android_ui_widget_strings_ca.xtb" /> + <file lang="cs" path="translations/android_ui_widget_strings_cs.xtb" /> + <file lang="da" path="translations/android_ui_widget_strings_da.xtb" /> + <file lang="de" path="translations/android_ui_widget_strings_de.xtb" /> + <file lang="el" path="translations/android_ui_widget_strings_el.xtb" /> + <file lang="en-GB" path="translations/android_ui_widget_strings_en-GB.xtb" /> + <file lang="es" path="translations/android_ui_widget_strings_es.xtb" /> + <file lang="es-419" path="translations/android_ui_widget_strings_es-419.xtb" /> + <file lang="et" path="translations/android_ui_widget_strings_et.xtb" /> + <file lang="fa" path="translations/android_ui_widget_strings_fa.xtb" /> + <file lang="fi" path="translations/android_ui_widget_strings_fi.xtb" /> + <file lang="fil" path="translations/android_ui_widget_strings_fil.xtb" /> + <file lang="fr" path="translations/android_ui_widget_strings_fr.xtb" /> + <file lang="gu" path="translations/android_ui_widget_strings_gu.xtb" /> + <file lang="hi" path="translations/android_ui_widget_strings_hi.xtb" /> + <file lang="hr" path="translations/android_ui_widget_strings_hr.xtb" /> + <file lang="hu" path="translations/android_ui_widget_strings_hu.xtb" /> + <file lang="id" path="translations/android_ui_widget_strings_id.xtb" /> + <file lang="it" path="translations/android_ui_widget_strings_it.xtb" /> + <file lang="iw" path="translations/android_ui_widget_strings_iw.xtb" /> + <file lang="ja" path="translations/android_ui_widget_strings_ja.xtb" /> + <file lang="ko" path="translations/android_ui_widget_strings_ko.xtb" /> + <file lang="kn" path="translations/android_ui_widget_strings_kn.xtb" /> + <file lang="lt" path="translations/android_ui_widget_strings_lt.xtb" /> + <file lang="lv" path="translations/android_ui_widget_strings_lv.xtb" /> + <file lang="ml" path="translations/android_ui_widget_strings_ml.xtb" /> + <file lang="mr" path="translations/android_ui_widget_strings_mr.xtb" /> + <file lang="ms" path="translations/android_ui_widget_strings_ms.xtb" /> + <file lang="nl" path="translations/android_ui_widget_strings_nl.xtb" /> + <file lang="no" path="translations/android_ui_widget_strings_no.xtb" /> + <file lang="pl" path="translations/android_ui_widget_strings_pl.xtb" /> + <file lang="pt-BR" path="translations/android_ui_widget_strings_pt-BR.xtb" /> + <file lang="pt-PT" path="translations/android_ui_widget_strings_pt-PT.xtb" /> + <file lang="ro" path="translations/android_ui_widget_strings_ro.xtb" /> + <file lang="ru" path="translations/android_ui_widget_strings_ru.xtb" /> + <file lang="sk" path="translations/android_ui_widget_strings_sk.xtb" /> + <file lang="sl" path="translations/android_ui_widget_strings_sl.xtb" /> + <file lang="sr" path="translations/android_ui_widget_strings_sr.xtb" /> + <file lang="sv" path="translations/android_ui_widget_strings_sv.xtb" /> + <file lang="sw" path="translations/android_ui_widget_strings_sw.xtb" /> + <file lang="ta" path="translations/android_ui_widget_strings_ta.xtb" /> + <file lang="te" path="translations/android_ui_widget_strings_te.xtb" /> + <file lang="th" path="translations/android_ui_widget_strings_th.xtb" /> + <file lang="tr" path="translations/android_ui_widget_strings_tr.xtb" /> + <file lang="uk" path="translations/android_ui_widget_strings_uk.xtb" /> + <file lang="vi" path="translations/android_ui_widget_strings_vi.xtb" /> + <file lang="zh-CN" path="translations/android_ui_widget_strings_zh-CN.xtb" /> + <file lang="zh-TW" path="translations/android_ui_widget_strings_zh-TW.xtb" /> + </translations> + <release allow_pseudo="false" seq="1"> + <messages fallback_to_english="true"> + <message name="IDS_ACCESSIBILITY_LIST_MENU_BUTTON" desc="Content description for the button that shows option menu for a list item."> + <ph name="NAME_OF_LIST_ITEM">%1$s<ex>Movie Title</ex></ph> Options + </message> + </messages> + </release> +</grit> diff --git a/chromium/chrome/browser/ui/libgtkui/BUILD.gn b/chromium/chrome/browser/ui/libgtkui/BUILD.gn index ced5ef6d9e7..7895f25952d 100644 --- a/chromium/chrome/browser/ui/libgtkui/BUILD.gn +++ b/chromium/chrome/browser/ui/libgtkui/BUILD.gn @@ -17,8 +17,6 @@ jumbo_component("libgtkui") { "app_indicator_icon_menu.h", "gtk_background_painter.cc", "gtk_background_painter.h", - "gtk_event_loop.cc", - "gtk_event_loop.h", "gtk_key_bindings_handler.cc", "gtk_key_bindings_handler.h", "gtk_ui.cc", @@ -48,8 +46,6 @@ jumbo_component("libgtkui") { "skia_utils_gtk.h", "unity_service.cc", "unity_service.h", - "x11_input_method_context_impl_gtk.cc", - "x11_input_method_context_impl_gtk.h", ] if (gtk_version <= 3) { @@ -112,10 +108,8 @@ jumbo_component("libgtkui") { "//ui/events:dom_keyboard_layout", "//ui/events:dom_keycode_converter", "//ui/events:events_base", - "//ui/events/platform/x11", "//ui/gfx", "//ui/gfx/geometry", - "//ui/gfx/x", "//ui/native_theme", "//ui/resources", "//ui/shell_dialogs", @@ -125,4 +119,18 @@ jumbo_component("libgtkui") { public_deps = [ "//chrome/browser:theme_properties", ] + + if (use_x11) { + sources += [ + "gtk_event_loop_x11.cc", + "gtk_event_loop_x11.h", + "x11_input_method_context_impl_gtk.cc", + "x11_input_method_context_impl_gtk.h", + ] + + deps += [ + "//ui/events/platform/x11", + "//ui/gfx/x", + ] + } } diff --git a/chromium/chrome/browser/ui/views/BUILD.gn b/chromium/chrome/browser/ui/views/BUILD.gn index 6862437bcc8..0241896ec54 100644 --- a/chromium/chrome/browser/ui/views/BUILD.gn +++ b/chromium/chrome/browser/ui/views/BUILD.gn @@ -27,6 +27,7 @@ component("views") { "//base", "//build:branding_buildflags", "//chrome/app:command_ids", + "//chrome/app:generated_resources", "//components/keep_alive_registry", "//components/vector_icons", "//content/public/browser", diff --git a/chromium/chrome/browser/ui/webui/about_ui.cc b/chromium/chrome/browser/ui/webui/about_ui.cc index d4cff184227..8637fe302a0 100644 --- a/chromium/chrome/browser/ui/webui/about_ui.cc +++ b/chromium/chrome/browser/ui/webui/about_ui.cc @@ -203,27 +203,35 @@ class ChromeOSTermsHandler DCHECK_CURRENTLY_ON(BrowserThread::UI); if (path_ == chrome::kOemEulaURLPath) { // Load local OEM EULA from the disk. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ChromeOSTermsHandler::LoadOemEulaFileAsync, this), base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this)); } else if (path_ == chrome::kArcTermsURLPath) { // Load ARC++ terms from the file. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ChromeOSTermsHandler::LoadArcTermsFileAsync, this), base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this)); } else if (path_ == chrome::kArcPrivacyPolicyURLPath) { // Load ARC++ privacy policy from the file. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ChromeOSTermsHandler::LoadArcPrivacyPolicyFileAsync, this), base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this)); } else { // Load local ChromeOS terms from the file. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ChromeOSTermsHandler::LoadEulaFileAsync, this), base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this)); } @@ -383,8 +391,9 @@ class ChromeOSCreditsHandler return; } // Load local Chrome OS credits from the disk. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&ChromeOSCreditsHandler::LoadCreditsFileAsync, this), base::Bind(&ChromeOSCreditsHandler::ResponseOnUIThread, this)); } @@ -450,8 +459,9 @@ class LinuxCreditsHandler return; } // Load local Linux credits from the disk. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&LinuxCreditsHandler::LoadLinuxCreditsFileAsync, this), base::Bind(&LinuxCreditsHandler::ResponseOnUIThread, this)); } @@ -586,7 +596,7 @@ std::string AboutUIHTMLSource::GetSource() { void AboutUIHTMLSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { std::string response; // Add your data source here, in alphabetical order. diff --git a/chromium/chrome/browser/ui/webui/about_ui.h b/chromium/chrome/browser/ui/webui/about_ui.h index 6860148d33b..0f2ae712871 100644 --- a/chromium/chrome/browser/ui/webui/about_ui.h +++ b/chromium/chrome/browser/ui/webui/about_ui.h @@ -26,7 +26,7 @@ class AboutUIHTMLSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; bool ShouldAddContentSecurityPolicy() override; diff --git a/chromium/chrome/browser/ui/webui/about_ui_unittest.cc b/chromium/chrome/browser/ui/webui/about_ui_unittest.cc index 301e1940431..66904b301b3 100644 --- a/chromium/chrome/browser/ui/webui/about_ui_unittest.cc +++ b/chromium/chrome/browser/ui/webui/about_ui_unittest.cc @@ -29,8 +29,7 @@ #include "chromeos/system/fake_statistics_provider.h" #include "chromeos/system/statistics_provider.h" #include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/resource_request_info.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -123,12 +122,12 @@ class ChromeOSTermsTest : public testing::Test { // Starts data request with the |request_url|. void StartRequest(const std::string& request_url, TestDataReceiver* data_receiver) { - content::ResourceRequestInfo::WebContentsGetter wc_getter; + content::WebContents::Getter wc_getter; tested_html_source_->StartDataRequest( request_url, std::move(wc_getter), base::BindRepeating(&TestDataReceiver::OnDataReceived, base::Unretained(data_receiver))); - test_browser_thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); } const base::FilePath& PreinstalledOfflineResourcesPath() { @@ -139,7 +138,7 @@ class ChromeOSTermsTest : public testing::Test { base::ScopedTempDir preinstalled_offline_resources_dir_; base::FilePath arc_tos_dir_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; chromeos::system::ScopedFakeStatisticsProvider statistics_provider_; diff --git a/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.cc b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.cc new file mode 100644 index 00000000000..9fd69a5ea1e --- /dev/null +++ b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.cc @@ -0,0 +1,85 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h" + +#include "base/bind.h" +#include "base/logging.h" +#include "base/values.h" +#include "chrome/browser/android/dev_ui/dev_ui_module_provider.h" + +DevUiLoaderMessageHandler::DevUiLoaderMessageHandler() = default; + +DevUiLoaderMessageHandler::~DevUiLoaderMessageHandler() = default; + +void DevUiLoaderMessageHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "getDevUiDfmState", + base::BindRepeating(&DevUiLoaderMessageHandler::HandleGetDevUiDfmState, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "installAndLoadDevUiDfm", + base::BindRepeating( + &DevUiLoaderMessageHandler::HandleInstallAndLoadDevUiDfm, + weak_ptr_factory_.GetWeakPtr())); +} + +void DevUiLoaderMessageHandler::HandleGetDevUiDfmState( + const base::ListValue* args) { + const base::Value* callback_id = nullptr; + CHECK(args->Get(0, &callback_id)); + const char* response = "ready"; + if (!dev_ui::DevUiModuleProvider::GetInstance().ModuleInstalled()) + response = "not-installed"; + else if (!dev_ui::DevUiModuleProvider::GetInstance().ModuleLoaded()) + response = "not-loaded"; + AllowJavascript(); + ResolveJavascriptCallback(*callback_id, base::Value(response)); +} + +void DevUiLoaderMessageHandler::ReplyToJavaScript( + const base::Value& callback_id, + const char* return_value) { + AllowJavascript(); + base::ListValue response; + response.GetList().emplace_back(base::Value(return_value)); + ResolveJavascriptCallback(callback_id, response); +} + +void DevUiLoaderMessageHandler::HandleInstallAndLoadDevUiDfm( + const base::ListValue* args) { + const base::Value* callback_id = nullptr; + CHECK(args->Get(0, &callback_id)); + + if (!dev_ui::DevUiModuleProvider::GetInstance().ModuleInstalled()) { + dev_ui::DevUiModuleProvider::GetInstance().InstallModule(base::BindOnce( + &DevUiLoaderMessageHandler::OnDevUiDfmInstallWithStatus, + weak_ptr_factory_.GetWeakPtr(), callback_id->GetString())); + + } else if (!dev_ui::DevUiModuleProvider::GetInstance().ModuleLoaded()) { + dev_ui::DevUiModuleProvider::GetInstance().LoadModule(base::BindOnce( + &DevUiLoaderMessageHandler::OnDevUiResourceLoaded, + weak_ptr_factory_.GetWeakPtr(), callback_id->GetString())); + + } else { + ReplyToJavaScript(*callback_id, "noop"); + } +} + +void DevUiLoaderMessageHandler::OnDevUiDfmInstallWithStatus( + std::string callback_id_string, + bool success) { + if (success) { + dev_ui::DevUiModuleProvider::GetInstance().LoadModule( + base::BindOnce(&DevUiLoaderMessageHandler::OnDevUiResourceLoaded, + weak_ptr_factory_.GetWeakPtr(), callback_id_string)); + } else { + ReplyToJavaScript(base::Value(callback_id_string), "failure"); + } +} + +void DevUiLoaderMessageHandler::OnDevUiResourceLoaded( + std::string callback_id_string) { + ReplyToJavaScript(base::Value(callback_id_string), "success"); +} diff --git a/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h new file mode 100644 index 00000000000..04921022d9a --- /dev/null +++ b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h @@ -0,0 +1,65 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_MESSAGE_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_MESSAGE_HANDLER_H_ + +#include <string> + +#include "base/memory/weak_ptr.h" +#include "build/build_config.h" +#include "chrome/android/features/dev_ui/buildflags.h" +#include "content/public/browser/web_ui_message_handler.h" + +#if !defined(OS_ANDROID) || !BUILDFLAG(DFMIFY_DEV_UI) +#error Unsupported platform. +#endif + +namespace base { +class ListValue; +class Value; +} // namespace base + +class DevUiLoaderMessageHandler : public content::WebUIMessageHandler { + public: + DevUiLoaderMessageHandler(); + ~DevUiLoaderMessageHandler() override; + + private: + DevUiLoaderMessageHandler(const DevUiLoaderMessageHandler&) = delete; + void operator=(const DevUiLoaderMessageHandler&) = delete; + + // WebUIMessageHandler + void RegisterMessages() override; + + // Called from JavaScript. |args| specifies id for callback, which receives + // one of the following responses: + // * "not-installed" if the DevUI DFM is not installed. + // * "not-loaded" if the DevUI DFM is installed, but not loaded. + // * "ready" if the DevUI DFM is installed and loaded. + void HandleGetDevUiDfmState(const base::ListValue* args); + + // Helper for HandleInstallAndLoadDevUiDfm(). + void ReplyToJavaScript(const base::Value& callback_id, + const char* return_value); + + // Called from JavaScript. |args| specifies id for callback, which receives + // one of the following responses: + // * "noop" if the DevUI DFM is already installed and loaded. + // * "success" if DevUI DFM install / load takes place, and succeeds. + // * "failure" if DevUI DFM install / load takes place, but fails. + void HandleInstallAndLoadDevUiDfm(const base::ListValue* args); + + // Callback for dev_ui::DevUiModuleProvider::InstallModule(). + void OnDevUiDfmInstallWithStatus(std::string callback_id_string, + bool success); + + // Callback for dev_ui::DevUiModuleProvider::LoadModule(). + void OnDevUiResourceLoaded(std::string callback_id_string); + + // Factory for creating references in callbacks. + base::WeakPtrFactory<DevUiLoaderMessageHandler> weak_ptr_factory_{this}; +}; + +#endif // CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_MESSAGE_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.cc b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.cc new file mode 100644 index 00000000000..52622ee0b68 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.cc @@ -0,0 +1,30 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h" + +#include <memory> +#include <utility> + +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h" +#include "chrome/grit/browser_resources.h" +#include "content/public/browser/web_ui_data_source.h" +#include "url/gurl.h" + +DevUiLoaderUI::DevUiLoaderUI(content::WebUI* web_ui_in, const GURL& url) + : WebUIController(web_ui_in) { + std::unique_ptr<content::WebUIDataSource> html_source; + html_source.reset(content::WebUIDataSource::Create(url.host())); + html_source->SetDefaultResource(IDR_DEV_UI_LOADER_HTML); + html_source->AddResourcePath("dev_ui_loader.html", IDR_DEV_UI_LOADER_HTML); + html_source->AddResourcePath("dev_ui_loader.js", IDR_DEV_UI_LOADER_JS); + html_source->AddResourcePath("dev_ui_loader.css", IDR_DEV_UI_LOADER_CSS); + + Profile* profile = Profile::FromWebUI(web_ui()); + content::WebUIDataSource::Add(profile, html_source.release()); + web_ui()->AddMessageHandler(std::make_unique<DevUiLoaderMessageHandler>()); +} + +DevUiLoaderUI::~DevUiLoaderUI() = default; diff --git a/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h new file mode 100644 index 00000000000..d8b70e71615 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h @@ -0,0 +1,32 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_UI_H_ + +#include "base/memory/weak_ptr.h" +#include "build/build_config.h" +#include "chrome/android/features/dev_ui/buildflags.h" +#include "content/public/browser/web_ui_controller.h" + +#if !defined(OS_ANDROID) || !BUILDFLAG(DFMIFY_DEV_UI) +#error Unsupported platform. +#endif + +class GURL; + +class DevUiLoaderUI : public content::WebUIController { + public: + DevUiLoaderUI(content::WebUI* web_ui_in, const GURL& url); + ~DevUiLoaderUI() override; + + private: + DevUiLoaderUI(const DevUiLoaderUI&) = delete; + void operator=(const DevUiLoaderUI&) = delete; + + // Factory for creating references in callbacks. + base::WeakPtrFactory<DevUiLoaderUI> weak_ptr_factory_{this}; +}; + +#endif // CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_UI_H_ 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 4b44c8cfcf5..9dfbd2f390b 100644 --- a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc @@ -80,10 +80,10 @@ AppLauncherLoginHandler::AppLauncherLoginHandler() {} AppLauncherLoginHandler::~AppLauncherLoginHandler() {} void AppLauncherLoginHandler::RegisterMessages() { - profile_info_watcher_.reset(new ProfileInfoWatcher( + profile_info_watcher_ = std::make_unique<ProfileInfoWatcher>( Profile::FromWebUI(web_ui()), base::Bind(&AppLauncherLoginHandler::UpdateLogin, - base::Unretained(this)))); + base::Unretained(this))); web_ui()->RegisterMessageCallback( "initializeSyncLogin", diff --git a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc index 7005dd6a16a..521d94e93d8 100644 --- a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc +++ b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc @@ -100,7 +100,7 @@ std::string AppLauncherPageUI::HTMLSource::GetSource() { void AppLauncherPageUI::HTMLSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); diff --git a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h index 0b632d6adb4..b5ad2e116e8 100644 --- a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h +++ b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h @@ -40,7 +40,7 @@ class AppLauncherPageUI : public content::WebUIController { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string&) override; bool ShouldReplaceExistingSource() override; diff --git a/chromium/chrome/browser/ui/webui/app_management/OWNERS b/chromium/chrome/browser/ui/webui/app_management/OWNERS index 4829e5de205..3b255369827 100644 --- a/chromium/chrome/browser/ui/webui/app_management/OWNERS +++ b/chromium/chrome/browser/ui/webui/app_management/OWNERS @@ -1,6 +1,5 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS -calamity@chromium.org dominickn@chromium.org -ericwilligers@chromium.org +jshikaram@chromium.org diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc index 8df423bb254..35c327bb3b8 100644 --- a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc @@ -22,10 +22,20 @@ #include "extensions/common/permissions/permission_message.h" #include "extensions/common/permissions/permissions_data.h" +#if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/arc/arc_util.h" +#include "components/arc/arc_prefs.h" +#endif + using apps::mojom::OptionalBool; namespace { +#if defined(OS_CHROMEOS) +constexpr char kArcFrameworkPackage[] = "android"; +constexpr int kMinAndroidFrameworkVersion = 28; // Android P +#endif + constexpr char const* kAppIdsWithHiddenMoreSettings[] = { extension_misc::kFilesManagerAppId, extensions::kWebStoreAppId, @@ -60,12 +70,13 @@ bool ShouldHidePinToShelf(const std::string app_id) { AppManagementPageHandler::AppManagementPageHandler( app_management::mojom::PageHandlerRequest request, app_management::mojom::PagePtr page, - content::WebUI* web_ui) + Profile* profile) : binding_(this, std::move(request)), page_(std::move(page)), - profile_(Profile::FromWebUI(web_ui)) + profile_(profile) #if defined(OS_CHROMEOS) , + arc_app_list_prefs_observer_(this), shelf_delegate_(this) #endif { @@ -78,6 +89,12 @@ AppManagementPageHandler::AppManagementPageHandler( return; Observe(&proxy->AppRegistryCache()); + +#if defined(OS_CHROMEOS) + if (arc::IsArcAllowedForProfile(profile_)) { + arc_app_list_prefs_observer_.Add(ArcAppListPrefs::Get(profile_)); + } +#endif // OS_CHROMEOS } AppManagementPageHandler::~AppManagementPageHandler() {} @@ -247,11 +264,36 @@ void AppManagementPageHandler::OnAppUpdate(const apps::AppUpdate& update) { } } -void AppManagementPageHandler::OnArcSupportChanged(bool supported) { - page_->OnArcSupportChanged(supported); -} - void AppManagementPageHandler::OnAppRegistryCacheWillBeDestroyed( apps::AppRegistryCache* cache) { Observe(nullptr); } + +#if defined(OS_CHROMEOS) +// static +bool AppManagementPageHandler::IsCurrentArcVersionSupported(Profile* profile) { + if (arc::IsArcAllowedForProfile(profile)) { + auto package = + ArcAppListPrefs::Get(profile)->GetPackage(kArcFrameworkPackage); + return package && (package->package_version >= kMinAndroidFrameworkVersion); + } + return false; +} + +void AppManagementPageHandler::OnArcVersionChanged(int androidVersion) { + page_->OnArcSupportChanged(androidVersion >= kMinAndroidFrameworkVersion); +} + +void AppManagementPageHandler::OnPackageInstalled( + const arc::mojom::ArcPackageInfo& package_info) { + OnPackageModified(package_info); +} + +void AppManagementPageHandler::OnPackageModified( + const arc::mojom::ArcPackageInfo& package_info) { + if (package_info.package_name != kArcFrameworkPackage) { + return; + } + OnArcVersionChanged(package_info.package_version); +} +#endif // OS_CHROMEOS diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h index 25f0a826171..baeef297ebd 100644 --- a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h @@ -6,27 +6,39 @@ #define CHROME_BROWSER_UI_WEBUI_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_H_ #include "base/macros.h" +#include "base/scoped_observer.h" #include "chrome/browser/ui/webui/app_management/app_management.mojom.h" #include "chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.h" #include "chrome/services/app_service/public/cpp/app_registry_cache.h" #include "mojo/public/cpp/bindings/binding.h" -namespace content { -class WebUI; -} +#if defined(OS_CHROMEOS) +#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" +#endif class Profile; class AppManagementPageHandler : public app_management::mojom::PageHandler, - public apps::AppRegistryCache::Observer { + public apps::AppRegistryCache::Observer +#if defined(OS_CHROMEOS) + , + public ArcAppListPrefs::Observer +#endif // OS_CHROMEOS +{ public: AppManagementPageHandler(app_management::mojom::PageHandlerRequest request, app_management::mojom::PagePtr page, - content::WebUI* web_ui); + Profile* profile); ~AppManagementPageHandler() override; +#if defined(OS_CHROMEOS) + static bool IsCurrentArcVersionSupported(Profile* profile); +#endif // OS_CHROMEOS + void OnPinnedChanged(const std::string& app_id, bool pinned); - void OnArcSupportChanged(bool supported); +#if defined(OS_CHROMEOS) + void OnArcVersionChanged(int androidVersion); +#endif // OS_CHROMEOS // app_management::mojom::PageHandler: void GetApps(GetAppsCallback callback) override; @@ -48,6 +60,14 @@ class AppManagementPageHandler : public app_management::mojom::PageHandler, void OnAppRegistryCacheWillBeDestroyed( apps::AppRegistryCache* cache) override; +#if defined(OS_CHROMEOS) + // ArcAppListPrefs::Observer: + void OnPackageInstalled( + const arc::mojom::ArcPackageInfo& package_info) override; + void OnPackageModified( + const arc::mojom::ArcPackageInfo& package_info) override; +#endif // OS_CHROMEOS + mojo::Binding<app_management::mojom::PageHandler> binding_; app_management::mojom::PagePtr page_; @@ -55,8 +75,10 @@ class AppManagementPageHandler : public app_management::mojom::PageHandler, Profile* profile_; #if defined(OS_CHROMEOS) + ScopedObserver<ArcAppListPrefs, AppManagementPageHandler> + arc_app_list_prefs_observer_; AppManagementShelfDelegate shelf_delegate_; -#endif +#endif // OS_CHROMEOS DISALLOW_COPY_AND_ASSIGN(AppManagementPageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc index d59a0bd6351..5d3ce3e4657 100644 --- a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc @@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/feature_list.h" -#include "chrome/browser/apps/app_service/app_icon_source.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/app_management/app_management_page_handler.h" #include "chrome/browser/ui/webui/localized_string.h" @@ -20,24 +19,12 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" -#include "content/public/browser/url_data_source.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "ui/base/resource/resource_bundle.h" -#if defined(OS_CHROMEOS) -#include "chrome/browser/chromeos/arc/arc_util.h" -#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" -#include "components/arc/arc_prefs.h" -#endif - namespace { -#if defined(OS_CHROMEOS) -constexpr char kArcFrameworkPackage[] = "android"; -constexpr int kMinAndroidFrameworkVersion = 28; // Android P -#endif - content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIAppManagementHost); @@ -68,14 +55,15 @@ content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) { {"storage", IDS_APP_MANAGEMENT_STORAGE}, {"thisAppCan", IDS_APP_MANAGEMENT_THIS_APP_CAN}, {"title", IDS_APP_MANAGEMENT_TITLE}, - {"uninstall", IDS_APP_MANAGEMENT_UNINSTALL}, + {"uninstall", IDS_APP_MANAGEMENT_UNINSTALL_APP}, {"version", IDS_APP_MANAGEMENT_VERSION}, }; AddLocalizedStringsBulk(source, kStrings, base::size(kStrings)); #if defined(OS_CHROMEOS) - source->AddBoolean("isSupportedArcVersion", - AppManagementUI::IsCurrentArcVersionSupported(profile)); + source->AddBoolean( + "isSupportedArcVersion", + AppManagementPageHandler::IsCurrentArcVersionSupported(profile)); #endif // OS_CHROMEOS source->AddResourcePath("app_management.mojom-lite.js", @@ -89,96 +77,15 @@ content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) { source->AddResourcePath("image_info.mojom-lite.js", IDR_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS); - source->AddResourcePath("actions.html", IDR_APP_MANAGEMENT_ACTIONS_HTML); - source->AddResourcePath("actions.js", IDR_APP_MANAGEMENT_ACTIONS_JS); - source->AddResourcePath("api_listener.html", - IDR_APP_MANAGEMENT_API_LISTENER_HTML); - source->AddResourcePath("api_listener.js", - IDR_APP_MANAGEMENT_API_LISTENER_JS); - source->AddResourcePath("app_item.html", IDR_APP_MANAGEMENT_APP_ITEM_HTML); - source->AddResourcePath("app_item.js", IDR_APP_MANAGEMENT_APP_ITEM_JS); source->AddResourcePath("app.html", IDR_APP_MANAGEMENT_APP_HTML); source->AddResourcePath("app.js", IDR_APP_MANAGEMENT_APP_JS); - source->AddResourcePath("arc_permission_view.html", - IDR_APP_MANAGEMENT_ARC_PERMISSION_VIEW_HTML); - source->AddResourcePath("arc_permission_view.js", - IDR_APP_MANAGEMENT_ARC_PERMISSION_VIEW_JS); - source->AddResourcePath("browser_proxy.html", - IDR_APP_MANAGEMENT_BROWSER_PROXY_HTML); - source->AddResourcePath("browser_proxy.js", - IDR_APP_MANAGEMENT_BROWSER_PROXY_JS); - source->AddResourcePath("chrome_app_permission_view.html", - IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_HTML); - source->AddResourcePath("chrome_app_permission_view.js", - IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_JS); - source->AddResourcePath("constants.html", IDR_APP_MANAGEMENT_CONSTANTS_HTML); - source->AddResourcePath("constants.js", IDR_APP_MANAGEMENT_CONSTANTS_JS); - source->AddResourcePath("dom_switch.html", - IDR_APP_MANAGEMENT_DOM_SWITCH_HTML); - source->AddResourcePath("dom_switch.js", IDR_APP_MANAGEMENT_DOM_SWITCH_JS); source->AddResourcePath("expandable_app_list.html", IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_HTML); source->AddResourcePath("expandable_app_list.js", IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_JS); - source->AddResourcePath("fake_page_handler.js", - IDR_APP_MANAGEMENT_FAKE_PAGE_HANDLER_JS); - source->AddResourcePath("icons.html", IDR_APP_MANAGEMENT_ICONS_HTML); - source->AddResourcePath("main_view.html", IDR_APP_MANAGEMENT_MAIN_VIEW_HTML); - source->AddResourcePath("main_view.js", IDR_APP_MANAGEMENT_MAIN_VIEW_JS); - source->AddResourcePath("metadata_view.html", - IDR_APP_MANAGEMENT_METADATA_VIEW_HTML); - source->AddResourcePath("metadata_view.js", - IDR_APP_MANAGEMENT_METADATA_VIEW_JS); - source->AddResourcePath("notifications_view.html", - IDR_APP_MANAGEMENT_NOTIFICATIONS_VIEW_HTML); - source->AddResourcePath("notifications_view.js", - IDR_APP_MANAGEMENT_NOTIFICATIONS_VIEW_JS); - source->AddResourcePath("permission_item.html", - IDR_APP_MANAGEMENT_PERMISSION_ITEM_HTML); - source->AddResourcePath("permission_item.js", - IDR_APP_MANAGEMENT_PERMISSION_ITEM_JS); - source->AddResourcePath("permission_toggle.html", - IDR_APP_MANAGEMENT_PERMISSION_TOGGLE_HTML); - source->AddResourcePath("permission_toggle.js", - IDR_APP_MANAGEMENT_PERMISSION_TOGGLE_JS); - source->AddResourcePath("permission_view_header.html", - IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_HTML); - source->AddResourcePath("permission_view_header.js", - IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_JS); - source->AddResourcePath("pin_to_shelf_item.html", - IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_HTML); - source->AddResourcePath("pin_to_shelf_item.js", - IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_JS); - source->AddResourcePath("pwa_permission_view.html", - IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_HTML); - source->AddResourcePath("pwa_permission_view.js", - IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_JS); - source->AddResourcePath("reducers.html", IDR_APP_MANAGEMENT_REDUCERS_HTML); - source->AddResourcePath("reducers.js", IDR_APP_MANAGEMENT_REDUCERS_JS); - source->AddResourcePath("router.html", IDR_APP_MANAGEMENT_ROUTER_HTML); - source->AddResourcePath("router.js", IDR_APP_MANAGEMENT_ROUTER_JS); - source->AddResourcePath("search_view.html", - IDR_APP_MANAGEMENT_SEARCH_VIEW_HTML); - source->AddResourcePath("search_view.js", IDR_APP_MANAGEMENT_SEARCH_VIEW_JS); - source->AddResourcePath("shared_style.html", - IDR_APP_MANAGEMENT_SHARED_STYLE_HTML); - source->AddResourcePath("shared_vars.html", - IDR_APP_MANAGEMENT_SHARED_VARS_HTML); - source->AddResourcePath("store_client.html", - IDR_APP_MANAGEMENT_STORE_CLIENT_HTML); - source->AddResourcePath("store_client.js", - IDR_APP_MANAGEMENT_STORE_CLIENT_JS); - source->AddResourcePath("store.html", IDR_APP_MANAGEMENT_STORE_HTML); - source->AddResourcePath("store.js", IDR_APP_MANAGEMENT_STORE_JS); - source->AddResourcePath("toggle_row.html", - IDR_APP_MANAGEMENT_TOGGLE_ROW_HTML); - source->AddResourcePath("toggle_row.js", IDR_APP_MANAGEMENT_TOGGLE_ROW_JS); - source->AddResourcePath("types.js", IDR_APP_MANAGEMENT_TYPES_JS); - source->AddResourcePath("util.html", IDR_APP_MANAGEMENT_UTIL_HTML); - source->AddResourcePath("util.js", IDR_APP_MANAGEMENT_UTIL_JS); source->SetDefaultResource(IDR_APP_MANAGEMENT_INDEX_HTML); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } @@ -202,22 +109,10 @@ AppManagementUI::AppManagementUI(content::WebUI* web_ui) AddHandlerToRegistry(base::BindRepeating( &AppManagementUI::BindPageHandlerFactory, base::Unretained(this))); - // Make the chrome://app-icon/ resource available. - if (profile) { - content::URLDataSource::Add(profile, - std::make_unique<apps::AppIconSource>(profile)); - } - auto plural_string_handler = std::make_unique<PluralStringHandler>(); plural_string_handler->AddLocalizedString( "appListPreview", IDS_APP_MANAGEMENT_APP_LIST_PREVIEW); web_ui->AddMessageHandler(std::move(plural_string_handler)); - -#if defined(OS_CHROMEOS) - if (arc::IsArcAllowedForProfile(profile)) { - ArcAppListPrefs::Get(profile)->AddObserver(this); - } -#endif } AppManagementUI::~AppManagementUI() = default; @@ -241,40 +136,5 @@ void AppManagementUI::CreatePageHandler( DCHECK(page); page_handler_ = std::make_unique<AppManagementPageHandler>( - std::move(request), std::move(page), web_ui()); + std::move(request), std::move(page), Profile::FromWebUI(web_ui())); } - -#if defined(OS_CHROMEOS) -bool AppManagementUI::IsCurrentArcVersionSupported(Profile* profile) { - if (arc::IsArcAllowedForProfile(profile)) { - auto package = - ArcAppListPrefs::Get(profile)->GetPackage(kArcFrameworkPackage); - return package && (package->package_version >= kMinAndroidFrameworkVersion); - } - return false; -} - -void AppManagementUI::NotifyAndroidVersionChange(int androidVersion) { - if (!page_handler_) { - return; - } - const bool supported = androidVersion >= kMinAndroidFrameworkVersion; - page_handler_->OnArcSupportChanged(supported); -} - -void AppManagementUI::OnPackageInstalled( - const arc::mojom::ArcPackageInfo& package_info) { - if (package_info.package_name != kArcFrameworkPackage) { - return; - } - NotifyAndroidVersionChange(package_info.package_version); -} - -void AppManagementUI::OnPackageModified( - const arc::mojom::ArcPackageInfo& package_info) { - if (package_info.package_name != kArcFrameworkPackage) { - return; - } - NotifyAndroidVersionChange(package_info.package_version); -} -#endif // OS_CHROMEOS diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h index 56caea216f0..a0187ee104e 100644 --- a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h @@ -12,31 +12,17 @@ #include "mojo/public/cpp/bindings/binding.h" #include "ui/webui/mojo_web_ui_controller.h" -#if defined(OS_CHROMEOS) -#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" -#endif - class AppManagementPageHandler; -class Profile; class AppManagementUI : public ui::MojoWebUIController, - public app_management::mojom::PageHandlerFactory -#if defined(OS_CHROMEOS) - , - public ArcAppListPrefs::Observer -#endif // OS_CHROMEOS -{ + public app_management::mojom::PageHandlerFactory { public: explicit AppManagementUI(content::WebUI* web_ui); ~AppManagementUI() override; static bool IsEnabled(); -#if defined(OS_CHROMEOS) - static bool IsCurrentArcVersionSupported(Profile* profile); -#endif // OS_CHROMEOS private: - void NotifyAndroidVersionChange(int androidVersion); void BindPageHandlerFactory( app_management::mojom::PageHandlerFactoryRequest request); @@ -49,14 +35,6 @@ class AppManagementUI : public ui::MojoWebUIController, mojo::Binding<app_management::mojom::PageHandlerFactory> page_factory_binding_; -#if defined(OS_CHROMEOS) - // ArcAppListPrefs::Observer: - void OnPackageInstalled( - const arc::mojom::ArcPackageInfo& package_info) override; - void OnPackageModified( - const arc::mojom::ArcPackageInfo& package_info) override; -#endif - DISALLOW_COPY_AND_ASSIGN(AppManagementUI); }; diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/OWNERS b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/OWNERS index 034df867c1c..85ef92a8da9 100644 --- a/chromium/chrome/browser/ui/webui/password_manager_internals/OWNERS +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/OWNERS @@ -1,3 +1,4 @@ +battre@chromium.org dvadym@chromium.org # COMPONENT: UI>Browser>Passwords diff --git a/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.cc b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.cc new file mode 100644 index 00000000000..a6231ff0fc2 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.cc @@ -0,0 +1,27 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.h" + +#include "base/bind.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.h" +#include "chrome/common/url_constants.h" +#include "components/autofill/content/browser/autofill_log_router_factory.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +AutofillInternalsUI::AutofillInternalsUI(content::WebUI* web_ui) + : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + content::WebUIDataSource::Add(profile, + autofill::CreateInternalsHTMLSource( + chrome::kChromeUIAutofillInternalsHost)); + web_ui->AddMessageHandler(std::make_unique<autofill::InternalsUIHandler>( + "setUpAutofillInternals", + base::BindRepeating( + &autofill::AutofillLogRouterFactory::GetForBrowserContext))); +} + +AutofillInternalsUI::~AutofillInternalsUI() = default; diff --git a/chromium/chrome/browser/ui/webui/autofill_internals_ui.h b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.h index 3a22afcb067..c38a6d9b7da 100644 --- a/chromium/chrome/browser/ui/webui/autofill_internals_ui.h +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.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_AUTOFILL_INTERNALS_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_AUTOFILL_INTERNALS_UI_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_AUTOFILL_INTERNALS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_AUTOFILL_INTERNALS_UI_H_ #include "base/macros.h" #include "content/public/browser/web_ui.h" @@ -18,4 +18,4 @@ class AutofillInternalsUI : public content::WebUIController { DISALLOW_COPY_AND_ASSIGN(AutofillInternalsUI); }; -#endif // CHROME_BROWSER_UI_WEBUI_AUTOFILL_INTERNALS_UI_H_ +#endif // CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_AUTOFILL_INTERNALS_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.cc b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.cc new file mode 100644 index 00000000000..1c242488832 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.cc @@ -0,0 +1,108 @@ +// 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/autofill_and_password_manager_internals/internals_ui_handler.h" + +#include "base/values.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/chrome_content_browser_client.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/common/channel_info.h" +#include "components/autofill/core/browser/logging/log_router.h" +#include "components/grit/components_resources.h" +#include "components/version_info/version_info.h" +#include "components/version_ui/version_handler_helper.h" +#include "components/version_ui/version_ui_constants.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +using autofill::LogRouter; + +namespace autofill { + +content::WebUIDataSource* CreateInternalsHTMLSource( + const std::string& source_name) { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(source_name); + source->AddResourcePath("autofill_and_password_manager_internals.js", + IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_JS); + source->AddResourcePath("autofill_and_password_manager_internals.css", + IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_CSS); + source->SetDefaultResource(IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_HTML); + // Data strings: + source->AddString(version_ui::kVersion, version_info::GetVersionNumber()); + source->AddString(version_ui::kOfficial, version_info::IsOfficialBuild() + ? "official" + : "Developer build"); + source->AddString(version_ui::kVersionModifier, chrome::GetChannelName()); + source->AddString(version_ui::kCL, version_info::GetLastChange()); + source->AddString(version_ui::kUserAgent, GetUserAgent()); + source->AddString("app_locale", g_browser_process->GetApplicationLocale()); + return source; +} + +InternalsUIHandler::InternalsUIHandler( + std::string call_on_load, + GetLogRouterFunction get_log_router_function) + : call_on_load_(std::move(call_on_load)), + get_log_router_function_(std::move(get_log_router_function)) {} + +InternalsUIHandler::~InternalsUIHandler() { + EndSubscription(); +} + +void InternalsUIHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "loaded", base::BindRepeating(&InternalsUIHandler::OnLoaded, + base::Unretained(this))); +} + +void InternalsUIHandler::OnJavascriptAllowed() { + StartSubscription(); +} + +void InternalsUIHandler::OnJavascriptDisallowed() { + EndSubscription(); +} + +void InternalsUIHandler::OnLoaded(const base::ListValue* args) { + AllowJavascript(); + CallJavascriptFunction(call_on_load_); + CallJavascriptFunction( + "notifyAboutIncognito", + base::Value(Profile::FromWebUI(web_ui())->IsIncognitoProfile())); + CallJavascriptFunction("notifyAboutVariations", + *version_ui::GetVariationsList()); +} + +void InternalsUIHandler::StartSubscription() { + LogRouter* log_router = + get_log_router_function_.Run(Profile::FromWebUI(web_ui())); + if (!log_router) + return; + + registered_with_log_router_ = true; + + const auto& past_logs = log_router->RegisterReceiver(this); + for (const auto& entry : past_logs) + LogEntry(entry); +} + +void InternalsUIHandler::EndSubscription() { + if (!registered_with_log_router_) + return; + registered_with_log_router_ = false; + LogRouter* log_router = + get_log_router_function_.Run(Profile::FromWebUI(web_ui())); + if (log_router) + log_router->UnregisterReceiver(this); +} + +void InternalsUIHandler::LogEntry(const base::Value& entry) { + if (!registered_with_log_router_ || entry.is_none()) + return; + CallJavascriptFunction("addRawLog", entry); +} + +} // namespace autofill diff --git a/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.h b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.h new file mode 100644 index 00000000000..8a6594fd352 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.h @@ -0,0 +1,70 @@ +// 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_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_INTERNALS_UI_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_INTERNALS_UI_HANDLER_H_ + +#include <string> + +#include "base/bind.h" +#include "base/macros.h" +#include "components/autofill/core/browser/logging/log_receiver.h" +#include "content/public/browser/web_ui_message_handler.h" + +namespace autofill { +class LogRouter; +} + +namespace content { +class BrowserContext; +class WebUIDataSource; +} // namespace content + +namespace autofill { +content::WebUIDataSource* CreateInternalsHTMLSource( + const std::string& source_name); + +// UI handler for chrome://password-manager-internals and +// chrome://autofill-internals that takes care of subscribing to the autofill +// logging instance. +class InternalsUIHandler : public content::WebUIMessageHandler, + public autofill::LogReceiver { + public: + using GetLogRouterFunction = + base::RepeatingCallback<autofill::LogRouter*(content::BrowserContext*)>; + + InternalsUIHandler(std::string call_on_load, + GetLogRouterFunction get_log_router_function); + ~InternalsUIHandler() override; + + private: + // content::WebUIMessageHandler: + void RegisterMessages() override; + + // Implements content::WebUIMessageHandler. + void OnJavascriptAllowed() override; + void OnJavascriptDisallowed() override; + + // LogReceiver implementation. + void LogEntry(const base::Value& entry) override; + + void StartSubscription(); + void EndSubscription(); + + // JavaScript call handler. + void OnLoaded(const base::ListValue* args); + + // JavaScript function to be called on load. + std::string call_on_load_; + GetLogRouterFunction get_log_router_function_; + + // Whether |this| is registered as a log receiver with the LogRouter. + bool registered_with_log_router_ = false; + + DISALLOW_COPY_AND_ASSIGN(InternalsUIHandler); +}; + +} // namespace autofill + +#endif // CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_INTERNALS_UI_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.cc b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.cc new file mode 100644 index 00000000000..a43a8d42ef4 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.cc @@ -0,0 +1,27 @@ +// 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/autofill_and_password_manager_internals/password_manager_internals_ui.h" + +#include "base/bind.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.h" +#include "chrome/common/url_constants.h" +#include "components/password_manager/content/browser/password_manager_log_router_factory.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +PasswordManagerInternalsUI::PasswordManagerInternalsUI(content::WebUI* web_ui) + : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + content::WebUIDataSource::Add( + profile, autofill::CreateInternalsHTMLSource( + chrome::kChromeUIPasswordManagerInternalsHost)); + web_ui->AddMessageHandler(std::make_unique<autofill::InternalsUIHandler>( + "setUpPasswordManagerInternals", + base::BindRepeating(&password_manager::PasswordManagerLogRouterFactory:: + GetForBrowserContext))); +} + +PasswordManagerInternalsUI::~PasswordManagerInternalsUI() = default; diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.h index 586ce8e2940..19d8ed9f3f2 100644 --- a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.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_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ #include "base/macros.h" #include "content/public/browser/web_ui.h" @@ -18,4 +18,4 @@ class PasswordManagerInternalsUI : public content::WebUIController { DISALLOW_COPY_AND_ASSIGN(PasswordManagerInternalsUI); }; -#endif // CHROME_BROWSER_UI_WEBUI_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ +#endif // CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui_browsertest.cc index 5d84d3044ff..0a50d409f8c 100644 --- a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui_browsertest.cc @@ -5,7 +5,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h" +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/base/web_ui_browser_test.h" @@ -31,15 +31,14 @@ class PasswordManagerInternalsWebUIBrowserTest : public WebUIBrowserTest { WindowOpenDisposition disposition); private: - PasswordManagerInternalsUI* controller_; + PasswordManagerInternalsUI* controller_ = nullptr; }; PasswordManagerInternalsWebUIBrowserTest:: - PasswordManagerInternalsWebUIBrowserTest() - : controller_(NULL) {} + PasswordManagerInternalsWebUIBrowserTest() = default; PasswordManagerInternalsWebUIBrowserTest:: - ~PasswordManagerInternalsWebUIBrowserTest() {} + ~PasswordManagerInternalsWebUIBrowserTest() = default; void PasswordManagerInternalsWebUIBrowserTest::SetUpOnMainThread() { WebUIBrowserTest::SetUpOnMainThread(); @@ -64,9 +63,7 @@ void PasswordManagerInternalsWebUIBrowserTest::OpenInternalsPageWithBrowser( std::string url_string("chrome://"); url_string += chrome::kChromeUIPasswordManagerInternalsHost; ui_test_utils::NavigateToURLWithDisposition( - browser, - GURL(url_string), - disposition, + browser, GURL(url_string), disposition, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); controller_ = static_cast<PasswordManagerInternalsUI*>( GetWebContents()->GetWebUI()->GetController()); diff --git a/chromium/chrome/browser/ui/webui/autofill_internals_ui.cc b/chromium/chrome/browser/ui/webui/autofill_internals_ui.cc deleted file mode 100644 index 489a5d65bd6..00000000000 --- a/chromium/chrome/browser/ui/webui/autofill_internals_ui.cc +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/autofill_internals_ui.h" - -#include <string> - -#include "base/bind.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/url_constants.h" -#include "chrome/grit/browser_resources.h" -#include "components/autofill/content/browser/autofill_log_router_factory.h" -#include "components/autofill/core/browser/logging/log_receiver.h" -#include "components/autofill/core/browser/logging/log_router.h" -#include "components/grit/components_resources.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" - -using autofill::AutofillLogRouterFactory; -using autofill::LogRouter; - -namespace { - -content::WebUIDataSource* CreateAutofillInternalsHTMLSource() { - content::WebUIDataSource* source = - content::WebUIDataSource::Create(chrome::kChromeUIAutofillInternalsHost); - source->AddResourcePath("autofill_and_password_manager_internals.js", - IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_JS); - source->AddResourcePath("autofill_and_password_manager_internals.css", - IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_CSS); - source->SetDefaultResource(IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_HTML); - return source; -} - -// Message handler for AutofillInternalsLoggingImpl. The purpose of this class -// is to enable safe calls to JavaScript, while the renderer is fully loaded. -class AutofillInternalsUIHandler : public content::WebUIMessageHandler, - public autofill::LogReceiver { - public: - AutofillInternalsUIHandler() = default; - ~AutofillInternalsUIHandler() override; - - private: - // content::WebUIMessageHandler: - void RegisterMessages() override; - - // Implements content::WebUIMessageHandler. - void OnJavascriptAllowed() override; - void OnJavascriptDisallowed() override; - - // LogReceiver implementation. - void LogEntry(const base::Value& entry) override; - - void StartSubscription(); - void EndSubscription(); - - // JavaScript call handler. - void OnLoaded(const base::ListValue* args); - - // Whether |this| is registered as a log receiver with the LogRouter. - bool registered_with_log_router_ = false; - - DISALLOW_COPY_AND_ASSIGN(AutofillInternalsUIHandler); -}; - -AutofillInternalsUIHandler::~AutofillInternalsUIHandler() { - EndSubscription(); -} - -void AutofillInternalsUIHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "loaded", base::BindRepeating(&AutofillInternalsUIHandler::OnLoaded, - base::Unretained(this))); -} - -void AutofillInternalsUIHandler::OnJavascriptAllowed() { - StartSubscription(); -} - -void AutofillInternalsUIHandler::OnJavascriptDisallowed() { - EndSubscription(); -} - -void AutofillInternalsUIHandler::OnLoaded(const base::ListValue* args) { - AllowJavascript(); - CallJavascriptFunction("setUpAutofillInternals"); - CallJavascriptFunction( - "notifyAboutIncognito", - base::Value(Profile::FromWebUI(web_ui())->IsIncognitoProfile())); -} - -void AutofillInternalsUIHandler::LogEntry(const base::Value& entry) { - if (!registered_with_log_router_ || entry.is_none()) - return; - CallJavascriptFunction("addRawLog", entry); -} - -void AutofillInternalsUIHandler::StartSubscription() { - LogRouter* log_router = AutofillLogRouterFactory::GetForBrowserContext( - Profile::FromWebUI(web_ui())); - - if (!log_router) - return; - - registered_with_log_router_ = true; - - const auto& past_logs = log_router->RegisterReceiver(this); - for (const auto& entry : past_logs) - LogEntry(entry); -} - -void AutofillInternalsUIHandler::EndSubscription() { - if (!registered_with_log_router_) - return; - registered_with_log_router_ = false; - LogRouter* log_router = AutofillLogRouterFactory::GetForBrowserContext( - Profile::FromWebUI(web_ui())); - if (log_router) - log_router->UnregisterReceiver(this); -} - -} // namespace - -AutofillInternalsUI::AutofillInternalsUI(content::WebUI* web_ui) - : WebUIController(web_ui) { - Profile* profile = Profile::FromWebUI(web_ui); - content::WebUIDataSource::Add(profile, CreateAutofillInternalsHTMLSource()); - web_ui->AddMessageHandler(std::make_unique<AutofillInternalsUIHandler>()); -} - -AutofillInternalsUI::~AutofillInternalsUI() = default; diff --git a/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn index c50c38a1ffc..0f0f0aaad80 100644 --- a/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn @@ -18,6 +18,7 @@ source_set("bluetooth_internals") { deps = [ ":mojo_bindings", + "//chrome/browser/resources/bluetooth_internals:resources", "//chrome/common", "//content/public/browser", "//device/bluetooth", @@ -33,7 +34,4 @@ mojom("mojo_bindings") { deps = [ "//device/bluetooth/public/mojom:deprecated_experimental_interfaces", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } 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 513a4d8208a..d51387baaee 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 @@ -8,7 +8,8 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h" #include "chrome/common/url_constants.h" -#include "chrome/grit/browser_resources.h" +#include "chrome/grit/bluetooth_internals_resources.h" +#include "chrome/grit/bluetooth_internals_resources_map.h" #include "content/public/browser/web_ui_data_source.h" BluetoothInternalsUI::BluetoothInternalsUI(content::WebUI* web_ui) @@ -19,48 +20,17 @@ BluetoothInternalsUI::BluetoothInternalsUI(content::WebUI* web_ui) // Add required resources. html_source->AddResourcePath("adapter.mojom-lite.js", - IDR_BLUETOOTH_ADAPTER_MOJO_JS); - html_source->AddResourcePath("adapter_broker.js", - IDR_BLUETOOTH_INTERNALS_ADAPTER_BROKER_JS); - html_source->AddResourcePath("adapter_page.js", - IDR_BLUETOOTH_INTERNALS_ADAPTER_PAGE_JS); - html_source->AddResourcePath("bluetooth_internals.css", - IDR_BLUETOOTH_INTERNALS_CSS); - html_source->AddResourcePath("bluetooth_internals.js", - IDR_BLUETOOTH_INTERNALS_JS); + IDR_BLUETOOTH_INTERNALS_ADAPTER_MOJO_JS); + html_source->AddResourcePath("device.mojom-lite.js", + IDR_BLUETOOTH_INTERNALS_DEVICE_MOJO_JS); html_source->AddResourcePath("bluetooth_internals.mojom-lite.js", IDR_BLUETOOTH_INTERNALS_MOJO_JS); - html_source->AddResourcePath("characteristic_list.js", - IDR_BLUETOOTH_INTERNALS_CHARACTERISTIC_LIST_JS); - html_source->AddResourcePath("descriptor_list.js", - IDR_BLUETOOTH_INTERNALS_DESCRIPTOR_LIST_JS); - html_source->AddResourcePath("device.mojom-lite.js", - IDR_BLUETOOTH_DEVICE_MOJO_JS); - html_source->AddResourcePath("device_broker.js", - IDR_BLUETOOTH_INTERNALS_DEVICE_BROKER_JS); - html_source->AddResourcePath("device_collection.js", - IDR_BLUETOOTH_INTERNALS_DEVICE_COLLECTION_JS); - html_source->AddResourcePath("device_details_page.js", - IDR_BLUETOOTH_INTERNALS_DEVICE_DETAILS_PAGE_JS); - html_source->AddResourcePath("device_table.js", - IDR_BLUETOOTH_INTERNALS_DEVICE_TABLE_JS); - html_source->AddResourcePath("devices_page.js", - IDR_BLUETOOTH_INTERNALS_DEVICES_PAGE_JS); - html_source->AddResourcePath("expandable_list.js", - IDR_BLUETOOTH_INTERNALS_EXPANDABLE_LIST_JS); - html_source->AddResourcePath("object_fieldset.js", - IDR_BLUETOOTH_INTERNALS_OBJECT_FIELDSET_JS); - html_source->AddResourcePath("service_list.js", - IDR_BLUETOOTH_INTERNALS_SERVICE_LIST_JS); - html_source->AddResourcePath("sidebar.js", - IDR_BLUETOOTH_INTERNALS_SIDEBAR_JS); - html_source->AddResourcePath("snackbar.js", - IDR_BLUETOOTH_INTERNALS_SNACKBAR_JS); html_source->AddResourcePath("uuid.mojom-lite.js", - IDR_BLUETOOTH_UUID_MOJO_JS); - html_source->AddResourcePath("value_control.js", - IDR_BLUETOOTH_INTERNALS_VALUE_CONTROL_JS); - + IDR_BLUETOOTH_INTERNALS_UUID_MOJO_JS); + for (size_t i = 0; i < kBluetoothInternalsResourcesSize; i++) { + html_source->AddResourcePath(kBluetoothInternalsResources[i].name, + kBluetoothInternalsResources[i].value); + } html_source->SetDefaultResource(IDR_BLUETOOTH_INTERNALS_HTML); Profile* profile = Profile::FromWebUI(web_ui); @@ -74,5 +44,6 @@ BluetoothInternalsUI::~BluetoothInternalsUI() {} void BluetoothInternalsUI::BindBluetoothInternalsHandler( mojom::BluetoothInternalsHandlerRequest request) { - page_handler_.reset(new BluetoothInternalsHandler(std::move(request))); + page_handler_ = + std::make_unique<BluetoothInternalsHandler>(std::move(request)); } diff --git a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc index 483ef599b63..2e4f5d89ed3 100644 --- a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc @@ -60,7 +60,7 @@ void BookmarksBrowserTest::SetupExtensionAPITest() { node->SetString("name", "Managed Bookmark"); node->SetString("url", "http://www.chromium.org"); list.Append(std::move(node)); - node.reset(new base::DictionaryValue()); + node = std::make_unique<base::DictionaryValue>(); node->SetString("name", "Managed Folder"); node->Set("children", std::make_unique<base::ListValue>()); list.Append(std::move(node)); diff --git a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc index dc7678bab36..094a943ac95 100644 --- a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc +++ b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc @@ -52,7 +52,7 @@ content::WebUIDataSource* CreateBookmarksUIHTMLSource(Profile* profile) { // definitions from JS to C++. ui::Accelerator undoAccelerator(ui::VKEY_Z, ui::EF_PLATFORM_ACCELERATOR); source->AddString("undoDescription", l10n_util::GetStringFUTF16( - IDS_BOOKMARK_BAR_UNDO_DESCRIPTION, + IDS_UNDO_DESCRIPTION, undoAccelerator.GetShortcutText())); // Localized strings (alphabetical order). @@ -73,7 +73,10 @@ content::WebUIDataSource* CreateBookmarksUIHTMLSource(Profile* profile) { {"listAxLabel", IDS_BOOKMARK_MANAGER_LIST_AX_LABEL}, {"menuAddBookmark", IDS_BOOKMARK_MANAGER_MENU_ADD_BOOKMARK}, {"menuAddFolder", IDS_BOOKMARK_MANAGER_MENU_ADD_FOLDER}, + {"menuCut", IDS_BOOKMARK_MANAGER_MENU_CUT}, + {"menuCopy", IDS_BOOKMARK_MANAGER_MENU_COPY}, {"menuCopyURL", IDS_BOOKMARK_MANAGER_MENU_COPY_URL}, + {"menuPaste", IDS_BOOKMARK_MANAGER_MENU_PASTE}, {"menuDelete", IDS_DELETE}, {"menuEdit", IDS_EDIT}, {"menuExport", IDS_BOOKMARK_MANAGER_MENU_EXPORT}, @@ -90,6 +93,8 @@ content::WebUIDataSource* CreateBookmarksUIHTMLSource(Profile* profile) { {"menuSort", IDS_BOOKMARK_MANAGER_MENU_SORT}, {"moreActionsButtonTitle", IDS_BOOKMARK_MANAGER_MORE_ACTIONS}, {"moreActionsButtonAxLabel", IDS_BOOKMARK_MANAGER_MORE_ACTIONS_AX_LABEL}, + {"moreActionsMultiButtonAxLabel", + IDS_BOOKMARK_MANAGER_MORE_ACTIONS_MULTI_AX_LABEL}, {"noSearchResults", IDS_SEARCH_NO_RESULTS}, {"openDialogBody", IDS_BOOKMARK_BAR_SHOULD_OPEN_ALL}, {"openDialogConfirm", IDS_BOOKMARK_MANAGER_OPEN_DIALOG_CONFIRM}, @@ -167,7 +172,7 @@ content::WebUIDataSource* CreateBookmarksUIHTMLSource(Profile* profile) { source->SetDefaultResource(IDR_BOOKMARKS_BOOKMARKS_HTML); #endif - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } diff --git a/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc b/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc index 89a24827fde..f21dc8923c5 100644 --- a/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc +++ b/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc @@ -148,7 +148,7 @@ content::WebUIDataSource* CreateBrowserSwitchUIHTMLSource( source->AddResourcePath("internals/", IDR_BROWSER_SWITCH_INTERNALS_HTML); source->AddResourcePath("internals", IDR_BROWSER_SWITCH_INTERNALS_HTML); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } diff --git a/chromium/chrome/browser/ui/webui/browsing_history_handler.cc b/chromium/chrome/browser/ui/webui/browsing_history_handler.cc index 389bc5d5767..95e30eecb7c 100644 --- a/chromium/chrome/browser/ui/webui/browsing_history_handler.cc +++ b/chromium/chrome/browser/ui/webui/browsing_history_handler.cc @@ -245,6 +245,8 @@ std::unique_ptr<base::DictionaryValue> HistoryEntryToValue( result->SetInteger("hostFilteringBehavior", host_filtering_behavior); result->SetBoolean("blockedVisit", is_blocked_visit); result->SetBoolean("isUrlInRemoteUserData", IsEntryInRemoteUserData(entry)); + result->SetString("remoteIconUrlForUma", + entry.remote_icon_url_for_uma.spec()); return result; } 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 0eb7e9de200..f65dda6c020 100644 --- a/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc @@ -80,7 +80,7 @@ class BrowsingHistoryHandlerTest : public ChromeRenderViewHostTestHarness { WebHistoryServiceFactory::GetForProfile(profile())); ASSERT_TRUE(web_history_service_); - web_ui_.reset(new content::TestWebUI); + web_ui_ = std::make_unique<content::TestWebUI>(); web_ui_->set_web_contents(web_contents()); } @@ -89,14 +89,15 @@ class BrowsingHistoryHandlerTest : public ChromeRenderViewHostTestHarness { ChromeRenderViewHostTestHarness::TearDown(); } - content::BrowserContext* CreateBrowserContext() override { - TestingProfile::Builder builder; - builder.AddTestingFactory(ProfileSyncServiceFactory::GetInstance(), - base::BindRepeating(&BuildTestSyncService)); - builder.AddTestingFactory(WebHistoryServiceFactory::GetInstance(), - base::BindRepeating(&BuildFakeWebHistoryService)); - return builder.Build().release(); + TestingProfile::TestingFactories GetTestingFactories() const override { + return { + {ProfileSyncServiceFactory::GetInstance(), + base::BindRepeating(&BuildTestSyncService)}, + {WebHistoryServiceFactory::GetInstance(), + base::BindRepeating(&BuildFakeWebHistoryService)}, + }; } + syncer::TestSyncService* sync_service() { return sync_service_; } history::WebHistoryService* web_history_service() { return web_history_service_; diff --git a/chromium/chrome/browser/ui/webui/cast/OWNERS b/chromium/chrome/browser/ui/webui/cast/OWNERS index 5b34f4712ed..1de9e6bb6d7 100644 --- a/chromium/chrome/browser/ui/webui/cast/OWNERS +++ b/chromium/chrome/browser/ui/webui/cast/OWNERS @@ -1 +1 @@ -sheretov@chromium.org +# Component: Chromecast diff --git a/chromium/chrome/browser/ui/webui/cast/cast_ui.cc b/chromium/chrome/browser/ui/webui/cast/cast_ui.cc index 68f113bf2ae..1c27f5122b3 100644 --- a/chromium/chrome/browser/ui/webui/cast/cast_ui.cc +++ b/chromium/chrome/browser/ui/webui/cast/cast_ui.cc @@ -13,6 +13,8 @@ #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" +// TODO: Figure out a way to self-navigate the WebUI in C++ on instantiation, +// and replace the navigation in cast.js with that. CastUI::CastUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { // Retrieve the ID of the component extension. @@ -26,13 +28,10 @@ CastUI::CastUI(content::WebUI* web_ui) content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUICastHost); - html_source->AddResourcePath("cast.css", IDR_CAST_CSS); html_source->AddResourcePath("cast.js", IDR_CAST_JS); - html_source->AddResourcePath("cast_favicon.ico", IDR_CAST_FAVICON); html_source->AddString("extensionId", extension_id); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->SetDefaultResource(IDR_CAST_HTML); - html_source->OverrideContentSecurityPolicyObjectSrc("object-src * chrome:;"); content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), html_source); } diff --git a/chromium/chrome/browser/ui/webui/certificate_viewer_ui.cc b/chromium/chrome/browser/ui/webui/certificate_viewer_ui.cc index 468aaacacb4..995c3fefa64 100644 --- a/chromium/chrome/browser/ui/webui/certificate_viewer_ui.cc +++ b/chromium/chrome/browser/ui/webui/certificate_viewer_ui.cc @@ -46,7 +46,7 @@ content::WebUIDataSource* GetWebUIDataSource(const std::string& host) { }; AddLocalizedStringsBulk(html_source, kStrings, base::size(kStrings)); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); // Add required resources. html_source->AddResourcePath("certificate_viewer.js", diff --git a/chromium/chrome/browser/ui/webui/certificates_handler.cc b/chromium/chrome/browser/ui/webui/certificates_handler.cc index 78dd1df58d1..02077494954 100644 --- a/chromium/chrome/browser/ui/webui/certificates_handler.cc +++ b/chromium/chrome/browser/ui/webui/certificates_handler.cc @@ -57,6 +57,7 @@ static const char kCertificatesHandlerObjSignField[] = "objSign"; static const char kCertificatesHandlerPolicyInstalledField[] = "policy"; static const char kCertificatesHandlerWebTrustAnchorField[] = "webTrustAnchor"; static const char kCertificatesHandlerCanBeDeletedField[] = "canBeDeleted"; +static const char kCertificatesHandlerCanBeEditedField[] = "canBeEdited"; static const char kCertificatesHandlerSslField[] = "ssl"; static const char kCertificatesHandlerSubnodesField[] = "subnodes"; static const char kCertificatesHandlerContainsPolicyCertsField[] = @@ -78,19 +79,6 @@ enum { IMPORT_CA_FILE_SELECTED, }; -#if defined(OS_CHROMEOS) -// Enumeration of certificate management permissions which corresponds to -// values of policy ClientCertificateManagementAllowed. -enum class CertificateManagementPermission : int { - // Allow users to manage all certificates - kAll = 0, - // Allow users to manage user certificates - kUserOnly = 1, - // Disallow users from managing certificates - kNone = 2 -}; -#endif - std::string OrgNameToId(const std::string& org) { return "org-" + org; } @@ -236,8 +224,8 @@ base::CancelableTaskTracker::TaskId FileAccessProvider::StartRead( std::string* data = new std::string(); // Post task to a background sequence to read file. - auto task_runner = base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); + auto task_runner = base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}); return tracker->PostTaskAndReply( task_runner.get(), FROM_HERE, base::BindOnce(&FileAccessProvider::DoRead, this, path, saved_errno, @@ -255,8 +243,8 @@ base::CancelableTaskTracker::TaskId FileAccessProvider::StartWrite( int* bytes_written = new int(0); // This task blocks shutdown because it saves critical user data. - auto task_runner = base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + auto task_runner = base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); return tracker->PostTaskAndReply( task_runner.get(), FROM_HERE, @@ -457,6 +445,15 @@ void CertificatesHandler::HandleEditCATrust(const base::ListValue* args) { if (!cert_info) return; + if (!CanEditCertificate(cert_info)) { + RejectCallbackWithError( + l10n_util::GetStringUTF8( + IDS_SETTINGS_CERTIFICATE_MANAGER_SET_TRUST_ERROR_TITLE), + l10n_util::GetStringUTF8( + IDS_SETTINGS_CERTIFICATE_MANAGER_ERROR_NOT_ALLOWED)); + return; + } + bool trust_ssl = false; bool trust_email = false; bool trust_obj_sign = false; @@ -571,15 +568,19 @@ void CertificatesHandler::ExportPersonalFileWritten(const int* write_errno, } void CertificatesHandler::HandleImportPersonal(const base::ListValue* args) { +#if defined(OS_CHROMEOS) + // When policy changes while user on the certificate manager page, the UI + // doesn't update without page refresh and user can still see and use import + // button. Because of this 'return' the button will do nothing. + if (!IsClientCertificateManagementAllowedPolicy(Slot::kUser)) { + return; + } +#endif + CHECK_EQ(2U, args->GetSize()); AssignWebUICallbackId(args); CHECK(args->GetBoolean(1, &use_hardware_backed_)); -#if defined(OS_CHROMEOS) - CHECK(IsClientCertificateManagementAllowedPolicy(Slot::kUser)) - << "Importing certificates not allowed by policy"; -#endif - ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.resize(1); file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("p12")); @@ -740,11 +741,6 @@ void CertificatesHandler::HandleImportServer(const base::ListValue* args) { CHECK_EQ(1U, args->GetSize()); AssignWebUICallbackId(args); -#if defined(OS_CHROMEOS) - CHECK(IsClientCertificateManagementAllowedPolicy(Slot::kUser)) - << "Importing certificates not allowed by policy"; -#endif - select_file_dialog_ = ui::SelectFileDialog::Create( this, std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents())); @@ -809,6 +805,15 @@ void CertificatesHandler::ImportServerFileRead(const int* read_errno, } void CertificatesHandler::HandleImportCA(const base::ListValue* args) { +#if defined(OS_CHROMEOS) + // When policy changes while user on the certificate manager page, the UI + // doesn't update without page refresh and user can still see and use import + // button. Because of this 'return' the button will do nothing. + if (!IsCACertificateManagementAllowedPolicy(CertificateSource::kImported)) { + return; + } +#endif // defined(OS_CHROMEOS) + CHECK_EQ(1U, args->GetSize()); AssignWebUICallbackId(args); @@ -924,6 +929,15 @@ void CertificatesHandler::HandleDeleteCertificate(const base::ListValue* args) { if (!cert_info) return; + if (!CanDeleteCertificate(cert_info)) { + RejectCallbackWithError( + l10n_util::GetStringUTF8( + IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_CERT_ERROR_TITLE), + l10n_util::GetStringUTF8( + IDS_SETTINGS_CERTIFICATE_MANAGER_ERROR_NOT_ALLOWED)); + return; + } + bool result = certificate_manager_model_->Delete(cert_info->cert()); if (!result) { // TODO(mattm): better error messages? @@ -945,13 +959,18 @@ void CertificatesHandler::OnCertificateManagerModelCreated( void CertificatesHandler::CertificateManagerModelReady() { bool client_import_allowed = true; + bool ca_import_allowed = true; #if defined(OS_CHROMEOS) client_import_allowed = IsClientCertificateManagementAllowedPolicy(Slot::kUser); -#endif + ca_import_allowed = + IsCACertificateManagementAllowedPolicy(CertificateSource::kImported); +#endif // defined(OS_CHROMEOS) if (IsJavascriptAllowed()) { - FireWebUIListener("certificates-model-ready", + FireWebUIListener("client-import-allowed-changed", base::Value(client_import_allowed)); + FireWebUIListener("ca-import-allowed-changed", + base::Value(ca_import_allowed)); } certificate_manager_model_->Refresh(); } @@ -1019,6 +1038,8 @@ void CertificatesHandler::PopulateTree(const std::string& tab_name, base::Value(cert_info->name())); cert_dict.SetKey(kCertificatesHandlerCanBeDeletedField, base::Value(CanDeleteCertificate(cert_info))); + cert_dict.SetKey(kCertificatesHandlerCanBeEditedField, + base::Value(CanEditCertificate(cert_info))); cert_dict.SetKey(kCertificatesHandlerUntrustedField, base::Value(cert_info->untrusted())); cert_dict.SetKey( @@ -1136,18 +1157,33 @@ bool CertificatesHandler::IsClientCertificateManagementAllowedPolicy( Slot slot) const { Profile* profile = Profile::FromWebUI(web_ui()); PrefService* prefs = profile->GetPrefs(); - auto policy_value = static_cast<CertificateManagementPermission>( + auto policy_value = static_cast<ClientCertificateManagementPermission>( prefs->GetInteger(prefs::kClientCertificateManagementAllowed)); if (slot == Slot::kUser) { - return policy_value != CertificateManagementPermission::kNone; + return policy_value != ClientCertificateManagementPermission::kNone; + } + return policy_value == ClientCertificateManagementPermission::kAll; +} + +bool CertificatesHandler::IsCACertificateManagementAllowedPolicy( + CertificateSource source) const { + Profile* profile = Profile::FromWebUI(web_ui()); + PrefService* prefs = profile->GetPrefs(); + auto policy_value = static_cast<CACertificateManagementPermission>( + prefs->GetInteger(prefs::kCACertificateManagementAllowed)); + + switch (source) { + case CertificateSource::kBuiltIn: + return policy_value == CACertificateManagementPermission::kAll; + case CertificateSource::kImported: + return policy_value != CACertificateManagementPermission::kNone; } - return policy_value == CertificateManagementPermission::kAll; } #endif // defined(OS_CHROMEOS) bool CertificatesHandler::CanDeleteCertificate( - const CertificateManagerModel::CertInfo* cert_info) { + const CertificateManagerModel::CertInfo* cert_info) const { if (!cert_info->can_be_deleted() || cert_info->source() == CertificateManagerModel::CertInfo::Source::kPolicy) { @@ -1155,22 +1191,50 @@ bool CertificatesHandler::CanDeleteCertificate( } #if defined(OS_CHROMEOS) - return cert_info->type() == net::CertType::USER_CERT && - IsClientCertificateManagementAllowedPolicy( - cert_info->device_wide() ? Slot::kSystem : Slot::kUser); -#else + if (cert_info->type() == net::CertType::USER_CERT) { + return IsClientCertificateManagementAllowedPolicy( + cert_info->device_wide() ? Slot::kSystem : Slot::kUser); + } + if (cert_info->type() == net::CertType::CA_CERT) { + CertificateSource source = cert_info->can_be_deleted() + ? CertificateSource::kImported + : CertificateSource::kBuiltIn; + return IsCACertificateManagementAllowedPolicy(source); + } +#endif // defined(OS_CHROMEOS) + return true; +} + +bool CertificatesHandler::CanEditCertificate( + const CertificateManagerModel::CertInfo* cert_info) const { + if ((cert_info->type() != net::CertType::CA_CERT) || + (cert_info->source() == + CertificateManagerModel::CertInfo::Source::kPolicy)) { + return false; + } +#if defined(OS_CHROMEOS) + CertificateSource source = cert_info->can_be_deleted() + ? CertificateSource::kImported + : CertificateSource::kBuiltIn; + return IsCACertificateManagementAllowedPolicy(source); +#endif // defined(OS_CHROMEOS) return true; -#endif } #if defined(OS_CHROMEOS) void CertificatesHandler::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { - // Allow users to manage all certificates by default. This can be overridden - // by enterprise policy. + // Allow users to manage all client certificates by default. This can be + // overridden by enterprise policy. registry->RegisterIntegerPref( prefs::kClientCertificateManagementAllowed, - static_cast<int>(CertificateManagementPermission::kAll)); + static_cast<int>(ClientCertificateManagementPermission::kAll)); + + // Allow users to manage all CA certificates by default. This can be + // overridden by enterprise policy. + registry->RegisterIntegerPref( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kAll)); } #endif // defined(OS_CHROMEOS) diff --git a/chromium/chrome/browser/ui/webui/certificates_handler.h b/chromium/chrome/browser/ui/webui/certificates_handler.h index 76ff163b1e7..e346efa177e 100644 --- a/chromium/chrome/browser/ui/webui/certificates_handler.h +++ b/chromium/chrome/browser/ui/webui/certificates_handler.h @@ -25,7 +25,32 @@ class PrefRegistrySyncable; #if defined(OS_CHROMEOS) enum class Slot { kUser, kSystem }; -#endif +enum class CertificateSource { kBuiltIn, kImported }; + +// Enumeration of certificate management permissions which corresponds to +// values of policy ClientCertificateManagementAllowed. +// Underlying type is int because values are casting to/from prefs values. +enum class ClientCertificateManagementPermission : int { + // Allow users to manage all certificates + kAll = 0, + // Allow users to manage user certificates + kUserOnly = 1, + // Disallow users from managing certificates + kNone = 2 +}; + +// Enumeration of certificate management permissions which corresponds to +// values of policy CACertificateManagementAllowed. +// Underlying type is int because values are casting to/from prefs values. +enum class CACertificateManagementPermission : int { + // Allow users to manage all certificates + kAll = 0, + // Allow users to manage user certificates + kUserOnly = 1, + // Disallow users from managing certificates + kNone = 2 +}; +#endif // defined(OS_CHROMEOS) namespace certificate_manager { @@ -178,14 +203,21 @@ class CertificatesHandler : public content::WebUIMessageHandler, #if defined(OS_CHROMEOS) // Returns true if the user may manage certificates on |slot| according - // ClientCertificateManagementAllowed to policy. + // to ClientCertificateManagementAllowed policy. bool IsClientCertificateManagementAllowedPolicy(Slot slot) const; -#endif + + // Returns true if the user may manage certificates according + // to CACertificateManagementAllowed policy. + bool IsCACertificateManagementAllowedPolicy(CertificateSource source) const; +#endif // defined(OS_CHROMEOS) // Returns true if the certificate represented by |cert_info| can be deleted. - // Evaluates the certificate attributes and, on Chrome OS devices, the - // enterprise policy ClientCertificateManagementAllowed. - bool CanDeleteCertificate(const CertificateManagerModel::CertInfo* cert_info); + bool CanDeleteCertificate( + const CertificateManagerModel::CertInfo* cert_info) const; + + // Returns true if the certificate represented by |cert_info| can be edited. + bool CanEditCertificate( + const CertificateManagerModel::CertInfo* cert_info) const; // The Certificates Manager model bool requested_certificate_manager_model_; @@ -215,6 +247,7 @@ class CertificatesHandler : public content::WebUIMessageHandler, base::WeakPtrFactory<CertificatesHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CertificatesHandler); + friend class ::CertificateHandlerTest; }; } // namespace certificate_manager diff --git a/chromium/chrome/browser/ui/webui/certificates_handler_unittest.cc b/chromium/chrome/browser/ui/webui/certificates_handler_unittest.cc new file mode 100644 index 00000000000..6977fd0295c --- /dev/null +++ b/chromium/chrome/browser/ui/webui/certificates_handler_unittest.cc @@ -0,0 +1,354 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/certificates_handler.h" + +#include "base/logging.h" +#include "chrome/common/pref_names.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "chrome/test/base/testing_profile.h" +#include "components/sync_preferences/testing_pref_service_syncable.h" +#include "content/public/test/test_web_ui.h" +#include "testing/gtest/include/gtest/gtest.h" + +class CertificateHandlerTest : public ChromeRenderViewHostTestHarness { + public: + void SetUp() override { + ChromeRenderViewHostTestHarness::SetUp(); + + web_ui_.set_web_contents(web_contents()); + cert_handler_.set_web_ui(&web_ui_); + pref_service_ = profile()->GetTestingPrefService(); + } + +#if defined(OS_CHROMEOS) + bool IsCACertificateManagementAllowedPolicy(CertificateSource source) const { + return cert_handler_.IsCACertificateManagementAllowedPolicy(source); + } +#endif // defined(OS_CHROMEOS) + + bool CanDeleteCertificate( + const CertificateManagerModel::CertInfo* cert_info) const { + return cert_handler_.CanDeleteCertificate(cert_info); + } + + bool CanEditCertificate( + const CertificateManagerModel::CertInfo* cert_info) const { + return cert_handler_.CanEditCertificate(cert_info); + } + + protected: + content::TestWebUI web_ui_; + certificate_manager::CertificatesHandler cert_handler_; + sync_preferences::TestingPrefServiceSyncable* pref_service_ = nullptr; +}; + +#if defined(OS_CHROMEOS) +TEST_F(CertificateHandlerTest, IsCACertificateManagementAllowedPolicyTest) { + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kAll)); + + EXPECT_TRUE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kImported)); + EXPECT_TRUE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kBuiltIn)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kUserOnly)); + + EXPECT_TRUE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kImported)); + EXPECT_FALSE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kBuiltIn)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kNone)); + + EXPECT_FALSE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kImported)); + EXPECT_FALSE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kBuiltIn)); + } +} +#endif // defined(OS_CHROMEOS) + +TEST_F(CertificateHandlerTest, CanDeleteCertificateCommonTest) { + CertificateManagerModel::CertInfo default_cert_info( + {} /* cert */, net::CertType::USER_CERT, {} /* cert_name */, + false /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kPolicy, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + + { + auto cert_info = + CertificateManagerModel::CertInfo::Clone(&default_cert_info); + cert_info->type_ = net::CertType::USER_CERT; + cert_info->can_be_deleted_ = false; + cert_info->source_ = CertificateManagerModel::CertInfo::Source::kExtension; + + // Deletion of |!can_be_deleted_| certificates is not allowed. + EXPECT_FALSE(CanDeleteCertificate(cert_info.get())); + } + + { + auto cert_info = + CertificateManagerModel::CertInfo::Clone(&default_cert_info); + cert_info->type_ = net::CertType::USER_CERT; + cert_info->can_be_deleted_ = true; + cert_info->source_ = CertificateManagerModel::CertInfo::Source::kPolicy; + + // Deletion of policy certificates is not allowed. + EXPECT_FALSE(CanDeleteCertificate(cert_info.get())); + } +} + +TEST_F(CertificateHandlerTest, CanDeleteUserCertificateTest) { + CertificateManagerModel::CertInfo cert_info( + {} /* cert */, net::CertType::USER_CERT, {} /* cert_name */, + true /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kExtension, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + { + cert_info.device_wide_ = false; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + } + +#if defined(OS_CHROMEOS) + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kAll)); + + cert_info.device_wide_ = false; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kUserOnly)); + + cert_info.device_wide_ = false; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kNone)); + + cert_info.device_wide_ = false; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + } +#endif // defined(OS_CHROMEOS) +} + +TEST_F(CertificateHandlerTest, CanDeleteCACertificateTest) { + CertificateManagerModel::CertInfo cert_info( + {} /* cert */, net::CertType::CA_CERT, {} /* cert_name */, + true /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kExtension, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + { + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + } + +#if defined(OS_CHROMEOS) + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kAll)); + + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kUserOnly)); + + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kNone)); + + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + cert_info.can_be_deleted_ = true; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + } +#endif // defined(OS_CHROMEOS) +} + +TEST_F(CertificateHandlerTest, CanEditCertificateCommonTest) { + CertificateManagerModel::CertInfo cert_info( + {} /* cert */, net::CertType::USER_CERT, {} /* cert_name */, + true /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kExtension, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + + cert_info.source_ = CertificateManagerModel::CertInfo::Source::kExtension; + cert_info.type_ = net::CertType::USER_CERT; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.source_ = CertificateManagerModel::CertInfo::Source::kExtension; + cert_info.type_ = net::CertType::SERVER_CERT; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.source_ = CertificateManagerModel::CertInfo::Source::kExtension; + cert_info.type_ = net::CertType::OTHER_CERT; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.source_ = CertificateManagerModel::CertInfo::Source::kPolicy; + cert_info.type_ = net::CertType::CA_CERT; + EXPECT_FALSE(CanEditCertificate(&cert_info)); +} + +// Edit of user certificates is not allowed in any case. +TEST_F(CertificateHandlerTest, CanEditUserCertificateTest) { + CertificateManagerModel::CertInfo cert_info( + {} /* cert */, net::CertType::USER_CERT, {} /* cert_name */, + true /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kExtension, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + { + cert_info.device_wide_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + } + +#if defined(OS_CHROMEOS) + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kAll)); + + cert_info.device_wide_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kUserOnly)); + + cert_info.device_wide_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kNone)); + + cert_info.device_wide_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + } +#endif // defined(OS_CHROMEOS) +} + +TEST_F(CertificateHandlerTest, CanEditCACertificateTest) { + CertificateManagerModel::CertInfo cert_info( + {} /* cert */, net::CertType::CA_CERT, {} /* cert_name */, + false /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kExtension, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + { + cert_info.can_be_deleted_ = false; + EXPECT_TRUE(CanEditCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanEditCertificate(&cert_info)); + } + +#if defined(OS_CHROMEOS) + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kAll)); + + cert_info.can_be_deleted_ = false; + EXPECT_TRUE(CanEditCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanEditCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kUserOnly)); + + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanEditCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kNone)); + + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + } +#endif // defined(OS_CHROMEOS) +} diff --git a/chromium/chrome/browser/ui/webui/chrome_web_contents_handler.cc b/chromium/chrome/browser/ui/webui/chrome_web_contents_handler.cc index 8d2a5e65217..1b97ae66d5b 100644 --- a/chromium/chrome/browser/ui/webui/chrome_web_contents_handler.cc +++ b/chromium/chrome/browser/ui/webui/chrome_web_contents_handler.cc @@ -43,7 +43,7 @@ WebContents* ChromeWebContentsHandler::OpenURLFromTab( // TODO(erg): OpenURLParams should pass a user_gesture flag, pass it to // CreateParams, and pass the real value to nav_params below. browser = - new Browser(Browser::CreateParams(Browser::TYPE_TABBED, profile, true)); + new Browser(Browser::CreateParams(Browser::TYPE_NORMAL, profile, true)); } NavigateParams nav_params(browser, params.url, params.transition); nav_params.referrer = params.referrer; @@ -88,7 +88,7 @@ void ChromeWebContentsHandler::AddNewContents( const bool browser_created = !browser; if (!browser) { browser = new Browser( - Browser::CreateParams(Browser::TYPE_TABBED, profile, user_gesture)); + Browser::CreateParams(Browser::TYPE_NORMAL, profile, user_gesture)); } NavigateParams params(browser, std::move(new_contents)); params.source_contents = source; 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 8f6d49bfdb3..afb648955a1 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 @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h" #include <stddef.h> +#include <utility> #include "base/bind.h" #include "base/feature_list.h" @@ -22,7 +23,8 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/search/suggestions/suggestions_ui.h" #include "chrome/browser/ui/webui/about_ui.h" -#include "chrome/browser/ui/webui/autofill_internals_ui.h" +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.h" +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h" #include "chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h" #include "chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h" @@ -51,7 +53,6 @@ #include "chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.h" #include "chrome/browser/ui/webui/ntp_tiles_internals_ui.h" #include "chrome/browser/ui/webui/omnibox/omnibox_ui.h" -#include "chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h" #include "chrome/browser/ui/webui/policy_ui.h" #include "chrome/browser/ui/webui/predictors/predictors_ui.h" #include "chrome/browser/ui/webui/quota_internals/quota_internals_ui.h" @@ -81,6 +82,7 @@ #include "components/history/core/browser/history_types.h" #include "components/nacl/common/buildflags.h" #include "components/prefs/pref_service.h" +#include "components/safe_browsing/buildflags.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" @@ -106,17 +108,23 @@ #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" #endif +#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) +#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui.h" +#endif + #if !defined(OS_ANDROID) #include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/ui/webui/app_management/app_management_ui.h" #include "chrome/browser/ui/webui/management_ui.h" #include "chrome/browser/ui/webui/media_router/media_router_internals_ui.h" +#include "chrome/browser/ui/webui/web_footer_experiment_ui.h" #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS) #include "chrome/browser/ui/webui/cast/cast_ui.h" #endif #if defined(OS_ANDROID) +#include "chrome/android/features/dev_ui/buildflags.h" #include "chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.h" #include "chrome/browser/ui/webui/offline/offline_internals_ui.h" #include "chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.h" @@ -126,7 +134,10 @@ #if BUILDFLAG(ENABLE_FEED_IN_CHROME) #include "chrome/browser/ui/webui/feed_internals/feed_internals_ui.h" #endif // BUILDFLAG(ENABLE_FEED_IN_CHROME) -#else +#if BUILDFLAG(DFMIFY_DEV_UI) +#include "chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h" +#endif // BUILDFLAG(DFMIFY_DEV_UI) +#else // defined(OS_ANDROID) #include "chrome/browser/ui/webui/bookmarks/bookmarks_ui.h" #include "chrome/browser/ui/webui/devtools_ui.h" #include "chrome/browser/ui/webui/downloads/downloads_ui.h" @@ -137,7 +148,7 @@ #include "chrome/browser/ui/webui/page_not_available_for_guest/page_not_available_for_guest_ui.h" #include "chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.h" #include "chrome/browser/ui/webui/system_info_ui.h" -#endif +#endif // defined(OS_ANDROID) #if defined(OS_CHROMEOS) #include "base/system/sys_info.h" @@ -175,7 +186,6 @@ #include "chromeos/components/multidevice/debug_webui/url_constants.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/constants/chromeos_switches.h" -#include "components/arc/arc_features.h" #endif #if defined(OS_CHROMEOS) && !defined(OFFICIAL_BUILD) @@ -194,13 +204,12 @@ #include "chrome/browser/ui/webui/signin/signin_error_ui.h" #include "chrome/browser/ui/webui/signin/sync_confirmation_ui.h" #include "chrome/browser/ui/webui/signin/user_manager_ui.h" -#include "chrome/browser/ui/webui/welcome/nux_helper.h" +#include "chrome/browser/ui/webui/welcome/helpers.h" #include "chrome/browser/ui/webui/welcome/welcome_ui.h" #endif #if defined(OS_WIN) #include "chrome/browser/ui/webui/conflicts/conflicts_ui.h" -#include "chrome/browser/ui/webui/set_as_default_browser_ui_win.h" #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) @@ -231,7 +240,7 @@ #include "extensions/common/manifest.h" #endif -#if defined(FULL_SAFE_BROWSING) +#if BUILDFLAG(FULL_SAFE_BROWSING) #include "chrome/browser/ui/webui/reset_password/reset_password_ui.h" #endif @@ -246,16 +255,25 @@ using ui::WebDialogUI; namespace { // A function for creating a new WebUI. The caller owns the return value, which -// may be NULL (for example, if the URL refers to an non-existent extension). +// may be nullptr (for example, if the URL refers to an non-existent extension). typedef WebUIController* (*WebUIFactoryFunction)(WebUI* web_ui, const GURL& url); // Template for defining WebUIFactoryFunction. -template<class T> +template <class T> WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { return new T(web_ui); } +#if defined(OS_ANDROID) +#if BUILDFLAG(DFMIFY_DEV_UI) +template <> +WebUIController* NewWebUI<DevUiLoaderUI>(WebUI* web_ui, const GURL& url) { + return new DevUiLoaderUI(web_ui, url); +} +#endif // BUILDFLAG(DFMIFY_DEV_UI) +#endif // defined(OS_ANDROID) + #if !defined(OS_ANDROID) template <> WebUIController* NewWebUI<PageNotAvailableForGuestUI>(WebUI* web_ui, @@ -265,13 +283,13 @@ WebUIController* NewWebUI<PageNotAvailableForGuestUI>(WebUI* web_ui, #endif // Special case for older about: handlers. -template<> +template <> WebUIController* NewWebUI<AboutUI>(WebUI* web_ui, const GURL& url) { return new AboutUI(web_ui, url.host()); } #if defined(OS_CHROMEOS) -template<> +template <> WebUIController* NewWebUI<chromeos::OobeUI>(WebUI* web_ui, const GURL& url) { return new chromeos::OobeUI(web_ui, url); } @@ -293,7 +311,7 @@ WebUIController* NewWebUI<chromeos::multidevice::ProximityAuthUI>( #endif // Special cases for DOM distiller. -template<> +template <> WebUIController* NewWebUI<dom_distiller::DomDistillerUi>(WebUI* web_ui, const GURL& url) { // The DomDistillerUi can not depend on components/dom_distiller/content, @@ -303,8 +321,8 @@ WebUIController* NewWebUI<dom_distiller::DomDistillerUi>(WebUI* web_ui, dom_distiller::DomDistillerService* service = dom_distiller::DomDistillerServiceFactory::GetForBrowserContext( browser_context); - return new dom_distiller::DomDistillerUi( - web_ui, service, dom_distiller::kDomDistillerScheme); + return new dom_distiller::DomDistillerUi(web_ui, service, + dom_distiller::kDomDistillerScheme); } #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) @@ -327,12 +345,12 @@ bool IsAboutUI(const GURL& url) { || url.host_piece() == chrome::kChromeUIOSCreditsHost || url.host_piece() == chrome::kChromeUILinuxCreditsHost #endif - ); // NOLINT + ); // NOLINT } // Returns a function that can be used to create the right type of WebUI for a -// tab, based on its URL. Returns NULL if the URL doesn't have WebUI associated -// with it. +// tab, based on its URL. Returns nullptr if the URL doesn't have WebUI +// associated with it. WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, Profile* profile, const GURL& url) { @@ -340,13 +358,19 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, // schemes to filter out most URLs. if (!url.SchemeIs(content::kChromeDevToolsScheme) && !url.SchemeIs(content::kChromeUIScheme)) { - return NULL; + return nullptr; } - /**************************************************************************** - * Please keep this in alphabetical order. If #ifs or special logics are - * required, add it below in the appropriate section. - ***************************************************************************/ +#if defined(OS_ANDROID) +#if BUILDFLAG(DFMIFY_DEV_UI) + if (url.host_piece() == chrome::kChromeUIDevUiLoaderHost) + return &NewWebUI<DevUiLoaderUI>; +#endif // BUILDFLAG(DFMIFY_DEV_UI) +#endif // defined(OS_ANDROID) + + // Please keep this in alphabetical order. If #ifs or special logics are + // required, add it below in the appropriate section. + // // We must compare hosts only since some of the Web UIs append extra stuff // after the host name. // All platform builds of Chrome will need to have a cloud printing @@ -370,6 +394,9 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<DomainReliabilityInternalsUI>; if (url.host_piece() == chrome::kChromeUIDownloadInternalsHost) return &NewWebUI<DownloadInternalsUI>; + if (url.host_piece() == chrome::kChromeUIFlagsHost && + FlagsDeprecatedUI::IsDeprecatedUrl(url)) + return &NewWebUI<FlagsDeprecatedUI>; if (url.host_piece() == chrome::kChromeUIFlagsHost) return &NewWebUI<FlagsUI>; if (url.host_piece() == chrome::kChromeUIGCMInternalsHost) @@ -421,9 +448,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, if (url.host_piece() == chrome::kChromeUIVersionHost) return &NewWebUI<VersionUI>; - /**************************************************************************** - * OS Specific #defines - ***************************************************************************/ #if !defined(OS_ANDROID) if (AppManagementUI::IsEnabled() && url.host_piece() == chrome::kChromeUIAppManagementHost && profile && @@ -469,6 +493,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<SyncFileSystemInternalsUI>; if (url.host_piece() == chrome::kChromeUISystemInfoHost) return &NewWebUI<SystemInfoUI>; + if (url.host_piece() == chrome::kChromeUIWebFooterExperimentHost) + return &NewWebUI<WebFooterExperimentUI>; // Inline login UI is available on all platforms except Android. if (url.host_piece() == chrome::kChromeUIChromeSigninHost) return &NewWebUI<InlineLoginUI>; @@ -476,8 +502,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, #if defined(OS_WIN) if (url.host_piece() == chrome::kChromeUIConflictsHost) return &NewWebUI<ConflictsUI>; - if (url.host_piece() == chrome::kChromeUIMetroFlowHost) - return &NewWebUI<SetAsDefaultBrowserUI>; #endif #if defined(OS_CHROMEOS) if (url.host_piece() == chrome::kChromeUIPasswordChangeHost) { @@ -506,7 +530,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<chromeos::AccountManagerWelcomeUI>; if (url.host_piece() == chrome::kChromeUIAccountMigrationWelcomeHost) return &NewWebUI<chromeos::AccountMigrationWelcomeUI>; - if (chromeos::switches::IsParentalControlsSettingsEnabled()) { + if (chromeos::features::IsParentalControlsSettingsEnabled()) { if (url.host_piece() == chrome::kChromeUIAddSupervisionHost) return &NewWebUI<chromeos::AddSupervisionUI>; } @@ -566,11 +590,9 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<chromeos::CameraUI>; } - if (url.host_piece() == chrome::kChromeUIArcGraphicsTracingHost) { - if (!base::FeatureList::IsEnabled(arc::kGraphicBuffersVisualizationTool)) - return nullptr; + if (url.host_piece() == chrome::kChromeUIArcGraphicsTracingHost) return &NewWebUI<chromeos::ArcGraphicsTracingUI>; - } + #if !defined(OFFICIAL_BUILD) if (!base::SysInfo::IsRunningOnChromeOS()) { if (url.host_piece() == chrome::kChromeUIDeviceEmulatorHost) @@ -624,13 +646,10 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, !profile->IsOffTheRecord()) return &NewWebUI<SigninEmailConfirmationUI>; if (url.host_piece() == chrome::kChromeUIWelcomeHost && - nux::IsNuxOnboardingEnabled(profile)) + welcome::IsEnabled(profile)) return &NewWebUI<WelcomeUI>; #endif - /**************************************************************************** - * Other #defines and special logics. - ***************************************************************************/ #if BUILDFLAG(ENABLE_NACL) if (url.host_piece() == chrome::kChromeUINaClHost) return &NewWebUI<NaClUI>; @@ -662,6 +681,13 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<LocalDiscoveryUI>; } #endif + +#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) + if (url.host_piece() == chrome::kChromeUITabStripHost) { + return &NewWebUI<TabStripUI>; + } +#endif + if (url.host_piece() == chrome::kChromeUIWebRtcLogsHost) return &NewWebUI<WebRtcLogsUI>; #if !defined(OS_ANDROID) @@ -698,7 +724,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<security_interstitials::ConnectionHelpUI>; } - if (dom_distiller::IsEnableDomDistillerSet() && + if (dom_distiller::IsDomDistillerEnabled() && url.host_piece() == dom_distiller::kChromeUIDomDistillerHost) { return &NewWebUI<dom_distiller::DomDistillerUi>; } @@ -713,7 +739,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<MediaEngagementUI>; } -#if defined(FULL_SAFE_BROWSING) +#if BUILDFLAG(FULL_SAFE_BROWSING) if (url.host_piece() == chrome::kChromeUIResetPasswordHost) { return &NewWebUI<ResetPasswordUI>; } @@ -724,7 +750,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<SupervisedUserInternalsUI>; #endif - return NULL; + return nullptr; } } // namespace @@ -733,7 +759,8 @@ WebUI::TypeID ChromeWebUIControllerFactory::GetWebUIType( content::BrowserContext* browser_context, const GURL& url) { Profile* profile = Profile::FromBrowserContext(browser_context); - WebUIFactoryFunction function = GetWebUIFactoryFunction(NULL, profile, url); + WebUIFactoryFunction function = + GetWebUIFactoryFunction(nullptr, profile, url); return function ? reinterpret_cast<WebUI::TypeID>(function) : WebUI::kNoWebUI; } @@ -801,8 +828,8 @@ void ChromeWebUIControllerFactory::GetFaviconForURL( gfx::Size(candidate_edge_size, candidate_edge_size)); } std::vector<size_t> selected_indices; - SelectFaviconFrameIndices( - candidate_sizes, desired_sizes_in_pixel, &selected_indices, NULL); + SelectFaviconFrameIndices(candidate_sizes, desired_sizes_in_pixel, + &selected_indices, nullptr); for (size_t i = 0; i < selected_indices.size(); ++i) { size_t selected_index = selected_indices[i]; ui::ScaleFactor selected_resource_scale = @@ -850,24 +877,23 @@ bool ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests( origin.host() == chrome::kChromeUIDownloadsHost; } -ChromeWebUIControllerFactory::ChromeWebUIControllerFactory() { -} +ChromeWebUIControllerFactory::ChromeWebUIControllerFactory() {} -ChromeWebUIControllerFactory::~ChromeWebUIControllerFactory() { -} +ChromeWebUIControllerFactory::~ChromeWebUIControllerFactory() {} base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( - const GURL& page_url, ui::ScaleFactor scale_factor) const { + const GURL& page_url, + ui::ScaleFactor scale_factor) const { #if !defined(OS_ANDROID) // The extension scheme is handled in GetFaviconForURL. if (page_url.SchemeIs(extensions::kExtensionScheme)) { NOTREACHED(); - return NULL; + return nullptr; } #endif if (!content::HasWebUIScheme(page_url)) - return NULL; + return nullptr; if (page_url.host_piece() == chrome::kChromeUIComponentsHost) return ComponentsUI::GetFaviconResourceBytes(scale_factor); @@ -921,5 +947,10 @@ base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( #endif // BUILDFLAG(ENABLE_EXTENSIONS) #endif // !defined(OS_ANDROID) - return NULL; +#if defined(OS_CHROMEOS) + if (page_url.host_piece() == chrome::kChromeUIOSSettingsHost) + return settings_utils::GetFaviconResourceBytes(scale_factor); +#endif // defined(OS_CHROMEOS) + + return nullptr; } diff --git a/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h b/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h index 92245af05e9..ada994e360c 100644 --- a/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h +++ b/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h @@ -67,7 +67,8 @@ class ChromeWebUIControllerFactory : public content::WebUIControllerFactory { // |gfx::kFaviconSize| x |gfx::kFaviconSize| DIP. GetFaviconForURL() should // be updated if this changes. base::RefCountedMemory* GetFaviconResourceBytes( - const GURL& page_url, ui::ScaleFactor scale_factor) const; + const GURL& page_url, + ui::ScaleFactor scale_factor) const; DISALLOW_COPY_AND_ASSIGN(ChromeWebUIControllerFactory); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc index d678bfe3343..0ffa1c7c75a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc @@ -67,7 +67,6 @@ bool AccountManagerWelcomeDialog::ShowIfRequired() { void AccountManagerWelcomeDialog::AdjustWidgetInitParams( views::Widget::InitParams* params) { params->z_order = ui::ZOrderLevel::kNormal; - params->type = views::Widget::InitParams::Type::TYPE_WINDOW_FRAMELESS; params->shadow_type = views::Widget::InitParams::ShadowType::SHADOW_TYPE_DROP; params->shadow_elevation = wm::kShadowElevationActiveWindow; } @@ -92,4 +91,8 @@ bool AccountManagerWelcomeDialog::ShouldShowDialogTitle() const { return false; } +bool AccountManagerWelcomeDialog::ShouldShowCloseButton() const { + return false; +} + } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h index efed08c5331..67fea954e98 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h +++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h @@ -29,6 +29,7 @@ class AccountManagerWelcomeDialog : public SystemWebDialogDelegate { void GetDialogSize(gfx::Size* size) const override; std::string GetDialogArgs() const override; bool ShouldShowDialogTitle() const override; + bool ShouldShowCloseButton() const override; private: DISALLOW_COPY_AND_ASSIGN(AccountManagerWelcomeDialog); diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc index 67d228af18c..16a69c1d232 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc @@ -6,6 +6,7 @@ #include "base/bind.h" #include "base/strings/utf_string_conversions.h" +#include "build/branding_buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "chrome/common/webui_url_constants.h" @@ -18,7 +19,7 @@ namespace chromeos { AccountManagerWelcomeUI::AccountManagerWelcomeUI(content::WebUI* web_ui) - : ui::WebDialogUI(web_ui), weak_factory_(this) { + : ui::WebDialogUI(web_ui) { content::WebUIDataSource* html_source = content::WebUIDataSource::Create( chrome::kChromeUIAccountManagerWelcomeHost); @@ -26,7 +27,7 @@ AccountManagerWelcomeUI::AccountManagerWelcomeUI(content::WebUI* web_ui) "closeDialog", base::BindRepeating(&WebDialogUI::CloseDialog, weak_factory_.GetWeakPtr())); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); // Add localized strings. html_source->AddLocalizedString("welcomeTitle", @@ -44,7 +45,7 @@ AccountManagerWelcomeUI::AccountManagerWelcomeUI(content::WebUI* web_ui) IDR_ACCOUNT_MANAGER_SHARED_CSS); html_source->AddResourcePath("account_manager_welcome.js", IDR_ACCOUNT_MANAGER_WELCOME_JS); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) html_source->AddResourcePath("account_manager_welcome_1x.png", IDR_ACCOUNT_MANAGER_WELCOME_1X_PNG); html_source->AddResourcePath("account_manager_welcome_2x.png", diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h index 6f66e183f84..ded176fe6df 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h @@ -18,7 +18,7 @@ class AccountManagerWelcomeUI : public ui::WebDialogUI { ~AccountManagerWelcomeUI() override; private: - base::WeakPtrFactory<AccountManagerWelcomeUI> weak_factory_; + base::WeakPtrFactory<AccountManagerWelcomeUI> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AccountManagerWelcomeUI); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc index 33407733834..5144af68c27 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc @@ -64,7 +64,6 @@ AccountMigrationWelcomeDialog* AccountMigrationWelcomeDialog::Show( void AccountMigrationWelcomeDialog::AdjustWidgetInitParams( views::Widget::InitParams* params) { params->z_order = ui::ZOrderLevel::kNormal; - params->type = views::Widget::InitParams::Type::TYPE_WINDOW_FRAMELESS; params->shadow_type = views::Widget::InitParams::ShadowType::SHADOW_TYPE_DROP; params->shadow_elevation = wm::kShadowElevationActiveWindow; } @@ -89,6 +88,10 @@ bool AccountMigrationWelcomeDialog::ShouldShowDialogTitle() const { return false; } +bool AccountMigrationWelcomeDialog::ShouldShowCloseButton() const { + return false; +} + const std::string& AccountMigrationWelcomeDialog::Id() { return id_; } diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h index c12c22906fc..96670974836 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h +++ b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h @@ -28,6 +28,7 @@ class AccountMigrationWelcomeDialog : public SystemWebDialogDelegate { void GetDialogSize(gfx::Size* size) const override; std::string GetDialogArgs() const override; bool ShouldShowDialogTitle() const override; + bool ShouldShowCloseButton() const override; const std::string& Id() override; std::string GetUserEmail() const; diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc index 78f338045ea..3c486f344a0 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc @@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/strings/utf_string_conversions.h" +#include "build/branding_buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h" #include "chrome/common/url_constants.h" @@ -71,11 +72,11 @@ class MigrationMessageHandler : public content::WebUIMessageHandler { } // namespace AccountMigrationWelcomeUI::AccountMigrationWelcomeUI(content::WebUI* web_ui) - : ui::WebDialogUI(web_ui), weak_factory_(this) { + : ui::WebDialogUI(web_ui) { content::WebUIDataSource* html_source = content::WebUIDataSource::Create( chrome::kChromeUIAccountMigrationWelcomeHost); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); // Add localized strings. html_source->AddLocalizedString("welcomePageTitle", @@ -99,7 +100,7 @@ AccountMigrationWelcomeUI::AccountMigrationWelcomeUI(content::WebUI* web_ui) IDR_ACCOUNT_MIGRATION_BROWSER_PROXY_HTML); html_source->AddResourcePath("account_migration_browser_proxy.js", IDR_ACCOUNT_MIGRATION_BROWSER_PROXY_JS); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) html_source->AddResourcePath("account_manager_welcome_1x.png", IDR_ACCOUNT_MANAGER_WELCOME_1X_PNG); html_source->AddResourcePath("account_manager_welcome_2x.png", diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h index 90dee7f3a6f..24a0c7dd8be 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h @@ -19,7 +19,7 @@ class AccountMigrationWelcomeUI : public ui::WebDialogUI { ~AccountMigrationWelcomeUI() override; private: - base::WeakPtrFactory<AccountMigrationWelcomeUI> weak_factory_; + base::WeakPtrFactory<AccountMigrationWelcomeUI> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AccountMigrationWelcomeUI); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn index 2829e6d376d..54b63f6b00a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn @@ -8,7 +8,4 @@ mojom("mojo_bindings") { sources = [ "add_supervision.mojom", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc index 0acab1a5249..e418a046414 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc @@ -11,17 +11,19 @@ #include "base/stl_util.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" -#include "chrome/browser/lifetime/application_lifetime.h" +#include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/supervised_user/supervised_user_service.h" #include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h" #include "chrome/services/app_service/public/cpp/app_registry_cache.h" #include "components/signin/public/identity_manager/access_token_fetcher.h" #include "components/signin/public/identity_manager/access_token_info.h" #include "components/signin/public/identity_manager/identity_manager.h" +#include "components/user_manager/user_manager.h" #include "content/public/browser/web_ui.h" #include "google_apis/gaia/gaia_constants.h" @@ -50,6 +52,18 @@ void AddSupervisionHandler::GetInstalledArcApps( apps::AppServiceProxy* proxy = apps::AppServiceProxyFactory::GetForProfile(profile); + if (arc::ArcSessionManager::Get() == nullptr) { + DLOG(WARNING) << "No ArcSessionManager available"; + std::move(callback).Run({}); + return; + } + if (arc::ArcSessionManager::Get()->state() != + arc::ArcSessionManager::State::ACTIVE) { + DLOG(WARNING) << "ArcSessionManager is not active"; + std::move(callback).Run({}); + return; + } + std::vector<std::string> installed_arc_apps; proxy->AppRegistryCache().ForEachApp( @@ -75,6 +89,8 @@ void AddSupervisionHandler::GetOAuthToken(GetOAuthTokenCallback callback) { scopes.insert(GaiaConstants::kKidsSupervisionSetupChildOAuth2Scope); scopes.insert(GaiaConstants::kPeopleApiReadOnlyOAuth2Scope); scopes.insert(GaiaConstants::kAccountsReauthOAuth2Scope); + scopes.insert(GaiaConstants::kAuditRecordingOAuth2Scope); + scopes.insert(GaiaConstants::kClearCutOAuth2Scope); oauth2_access_token_fetcher_ = identity_manager_->CreateAccessTokenFetcherForAccount( @@ -85,14 +101,23 @@ void AddSupervisionHandler::GetOAuthToken(GetOAuthTokenCallback callback) { } void AddSupervisionHandler::LogOut() { - chrome::AttemptUserExit(); + LogOutHelper(); } void AddSupervisionHandler::NotifySupervisionEnabled() { SupervisedUserService* service = SupervisedUserServiceFactory::GetForProfile(Profile::FromWebUI(web_ui_)); - service->set_signout_required_after_supervision_enabled(); + + // Force full sign-in the next time the user is at the login screen. + // Gellerization can only be triggered by the primary user. + user_manager::UserManager* manager = user_manager::UserManager::Get(); + manager->SaveForceOnlineSignin(manager->GetPrimaryUser()->GetAccountId(), + true /* force signin */); + + // Record UMA metric that user has completed Add Supervision process. + AddSupervisionMetricsRecorder::GetInstance()->RecordAddSupervisionEnrollment( + AddSupervisionMetricsRecorder::EnrollmentState::kCompleted); } void AddSupervisionHandler::OnAccessTokenFetchComplete( diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc index c5775d23ff0..0c7a610df3e 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc @@ -4,6 +4,11 @@ #include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" +#include "chrome/browser/lifetime/application_lifetime.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/supervised_user/supervised_user_service.h" +#include "chrome/browser/supervised_user/supervised_user_service_factory.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h" #include "chrome/services/app_service/public/cpp/app_update.h" #include "chrome/services/app_service/public/mojom/types.mojom.h" @@ -13,3 +18,23 @@ bool ShouldIncludeAppUpdate(const apps::AppUpdate& app_update) { return app_update.AppType() == apps::mojom::AppType::kArc; } + +void LogOutHelper() { + // Record UMA metric that the user clicked "Sign out". + if (EnrollmentCompleted()) { + AddSupervisionMetricsRecorder::GetInstance() + ->RecordAddSupervisionEnrollment( + AddSupervisionMetricsRecorder::EnrollmentState::kSignedOut); + } else { + AddSupervisionMetricsRecorder::GetInstance() + ->RecordAddSupervisionEnrollment( + AddSupervisionMetricsRecorder::EnrollmentState::kSwitchedAccounts); + } + chrome::AttemptUserExit(); +} + +bool EnrollmentCompleted() { + SupervisedUserService* service = SupervisedUserServiceFactory::GetForProfile( + ProfileManager::GetPrimaryUserProfile()); + return service->signout_required_after_supervision_enabled(); +} diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h index 9f8c8383fc8..6cb4741673d 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h @@ -17,4 +17,10 @@ class AppUpdate; // returned to clients or uninstalled. bool ShouldIncludeAppUpdate(const apps::AppUpdate& app_update); +// Records UMA metric and signs out the user. +void LogOutHelper(); + +// Checks if the user has completed enrollment in supervision. +bool EnrollmentCompleted(); + #endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_ADD_SUPERVISION_HANDLER_UTILS_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.cc new file mode 100644 index 00000000000..3681eee93fe --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.cc @@ -0,0 +1,79 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h" + +#include "base/logging.h" +#include "base/metrics/histogram_functions.h" +#include "base/metrics/user_metrics.h" +#include "base/time/default_tick_clock.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" + +// static +AddSupervisionMetricsRecorder* AddSupervisionMetricsRecorder::GetInstance() { + static base::NoDestructor<AddSupervisionMetricsRecorder> instance_; + return instance_.get(); +} + +void AddSupervisionMetricsRecorder::RecordAddSupervisionEnrollment( + EnrollmentState action) { + base::UmaHistogramEnumeration("AddSupervisionDialog.Enrollment", action); + switch (action) { + case EnrollmentState::kInitiated: + DCHECK(!EnrollmentCompleted()) + << "The user should not be enrolled in supervision at the start of " + "the Add Supervision process."; + base::RecordAction( + base::UserMetricsAction("AddSupervisionDialog_Launched")); + start_time_ = clock_->NowTicks(); + break; + case EnrollmentState::kCompleted: + DCHECK(EnrollmentCompleted()) + << "Add Supervision enrollment should be completed before recording " + "kCompleted UMA metric."; + RecordUserTime("AddSupervisionDialog.EnrollmentCompletedUserTime"); + base::RecordAction( + base::UserMetricsAction("AddSupervisionDialog_EnrollmentCompleted")); + break; + case EnrollmentState::kSignedOut: + DCHECK(EnrollmentCompleted()) + << "There should be no way for the user to attempt sign out from " + "within the Add Supervision dialog without completing supervision " + "enrollment."; + RecordUserTime("AddSupervisionDialog.SignoutCompletedUserTime"); + base::RecordAction(base::UserMetricsAction( + "AddSupervisionDialog_AttemptedSignoutAfterEnrollment")); + break; + case EnrollmentState::kClosed: + DCHECK(!EnrollmentCompleted()) + << "There should be no way to close the Add Supervision dialog " + "without signing out after supervision enrollment has completed."; + RecordUserTime("AddSupervisionDialog.EnrollmentNotCompletedUserTime"); + base::RecordAction( + base::UserMetricsAction("AddSupervisionDialog_Closed")); + break; + case EnrollmentState::kSwitchedAccounts: + DCHECK(!EnrollmentCompleted()) << "The only way for the user to switch " + "accounts is before enrollment"; + RecordUserTime("AddSupervisionDialog.EnrollmentNotCompletedUserTime"); + base::RecordAction( + base::UserMetricsAction("AddSupervisionDialog_SwitchedAccounts")); + break; + } +} + +void AddSupervisionMetricsRecorder::SetClockForTesting( + const base::TickClock* tick_clock) { + clock_ = tick_clock; +} + +AddSupervisionMetricsRecorder::AddSupervisionMetricsRecorder() + : clock_(base::DefaultTickClock::GetInstance()) {} + +void AddSupervisionMetricsRecorder::RecordUserTime( + const char* metric_name) const { + DCHECK(!start_time_.is_null()) << "start_time_ has not been initialized."; + base::TimeDelta duration = clock_->NowTicks() - start_time_; + base::UmaHistogramLongTimes(metric_name, duration); +} diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h new file mode 100644 index 00000000000..600f4b87324 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h @@ -0,0 +1,66 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_ADD_SUPERVISION_METRICS_RECORDER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_ADD_SUPERVISION_METRICS_RECORDER_H_ + +#include "base/no_destructor.h" +#include "base/time/time.h" + +namespace base { +class TickClock; +} + +// Records UMA metrics for users going through the Add Supervision process. +class AddSupervisionMetricsRecorder { + public: + // These enum values represent the state that the user has attained while + // going through the Add Supervision dialog. + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. + enum class EnrollmentState { + // Recorded when user opens Add Supervision dialog. + kInitiated = 0, + // Recorded when user successfully enrolls in supervision. + kCompleted = 1, + // Recorded when user clicks "Sign out" after enrollment in the dialog. + kSignedOut = 2, + // Recorded when user closes the dialog without enrollment, excluding sign + // out. + kClosed = 3, + // Recorded when user signs out to switch accounts. + kSwitchedAccounts = 4, + // Add future entries above this comment, in sync with enums.xml. + // Update kMaxValue to the last value. + kMaxValue = kSwitchedAccounts + }; + + static AddSupervisionMetricsRecorder* GetInstance(); + + // Records UMA metrics for users going through the Add Supervision process. + void RecordAddSupervisionEnrollment(EnrollmentState action); + + // Method intended for testing purposes only. + // Set clock used for timing to enable manipulation during tests. + void SetClockForTesting(const base::TickClock* tick_clock); + + private: + friend class base::NoDestructor<AddSupervisionMetricsRecorder>; + + AddSupervisionMetricsRecorder(); + + // Records UMA metric of how long the user spends in the Add Supervision + // process in milliseconds. + void RecordUserTime(const char* metric_name) const; + + // Points to the base::DefaultTickClock by default. + const base::TickClock* clock_; + + // Records when the user initiates the Add Supervision process. + base::TimeTicks start_time_; + + DISALLOW_COPY_AND_ASSIGN(AddSupervisionMetricsRecorder); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_ADD_SUPERVISION_METRICS_RECORDER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder_browsertest.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder_browsertest.cc new file mode 100644 index 00000000000..3071dacac19 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder_browsertest.cc @@ -0,0 +1,294 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/test/metrics/histogram_tester.h" +#include "base/test/metrics/user_action_tester.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/test_mock_time_task_runner.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision.mojom.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chromeos/constants/chromeos_features.h" +#include "content/public/test/test_web_ui.h" + +namespace chromeos { + +// This browser test class is for the Add Supervision metrics recorder. +class AddSupervisionMetricsRecorderTest : public InProcessBrowserTest { + public: + AddSupervisionMetricsRecorderTest() = default; + ~AddSupervisionMetricsRecorderTest() override = default; + + void SetUp() override { + feature_list_.InitAndEnableFeature( + chromeos::features::kParentalControlsSettings); + InProcessBrowserTest::SetUp(); + } + + void SetUpOnMainThread() override { + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + test_web_ui_.set_web_contents(web_contents); + } + + void ShowAddSupervisionDialog() { + content::WebContents* web_contents = test_web_ui_.GetWebContents(); + AddSupervisionDialog::Show(web_contents->GetTopLevelNativeWindow()); + } + + void CloseNowForTesting() { + AddSupervisionDialog* instance = + static_cast<AddSupervisionDialog*>(AddSupervisionDialog::GetInstance()); + instance->CloseNowForTesting(); + } + + void CloseAddSupervisionDialog() { + bool out_close_dialog = + AddSupervisionDialog::GetInstance()->OnDialogCloseRequested(); + EXPECT_TRUE(out_close_dialog); + CloseNowForTesting(); + } + + void NotifySupervisionEnabled() { + add_supervision::mojom::AddSupervisionHandlerRequest request; + AddSupervisionUI add_supervision_ui(&test_web_ui_); + AddSupervisionHandler add_supervision_handler( + std::move(request), &test_web_ui_, &add_supervision_ui); + add_supervision_handler.NotifySupervisionEnabled(); + } + + void LogOutAndClose() { + LogOutHelper(); + CloseNowForTesting(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(AddSupervisionMetricsRecorderTest); + + base::test::ScopedFeatureList feature_list_; + content::TestWebUI test_web_ui_; +}; + +IN_PROC_BROWSER_TEST_F(AddSupervisionMetricsRecorderTest, HistogramTest) { + base::HistogramTester histogram_tester; + + // Should see 0 Add Supervision enrollment metrics at first. + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 0); + + // Simulate the user opening the Add Supervision dialog and closing it. + ShowAddSupervisionDialog(); + + // Should see 1 Add Supervision process initiated. + histogram_tester.ExpectUniqueSample( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kInitiated, 1); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 1); + + CloseAddSupervisionDialog(); + + // Should see 1 Add Supervision process closed. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kClosed, 1); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 2); + + // Simulate the user opening the Add Supervision dialog and signing out to + // switch accounts. + ShowAddSupervisionDialog(); + + // Should see 2 Add Supervision processes initiated. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kInitiated, 2); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 3); + + LogOutAndClose(); + + // Should see 1 switch accounts attempt. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kSwitchedAccounts, 1); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 4); + + // Simulate the user opening the Add Supervision dialog, enrolling in + // supervision and signing out. + ShowAddSupervisionDialog(); + + // Should see 3 Add Supervision processes initiated. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kInitiated, 3); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 5); + + NotifySupervisionEnabled(); + + // Should see 1 Add Supervision process completed. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kCompleted, 1); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 6); + + LogOutAndClose(); + + // Should see 1 sign out attempt. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kSignedOut, 1); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 7); +} + +IN_PROC_BROWSER_TEST_F(AddSupervisionMetricsRecorderTest, UserActionTest) { + base::UserActionTester user_action_tester; + // Should see 0 user actions at first. + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Launched"), + 0); + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Closed"), + 0); + EXPECT_EQ(user_action_tester.GetActionCount( + "AddSupervisionDialog_AttemptedSignoutAfterEnrollment"), + 0); + EXPECT_EQ(user_action_tester.GetActionCount( + "AddSupervisionDialog_EnrollmentCompleted"), + 0); + + // Simulate the user opening the Add Supervision dialog and closing it. + ShowAddSupervisionDialog(); + + // Should see 1 Launched action. + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Launched"), + 1); + + CloseAddSupervisionDialog(); + + // Should see 1 Closed action. + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Closed"), + 1); + + // Simulate the user opening the Add Supervision dialog and signing out to + // switch accounts. + ShowAddSupervisionDialog(); + + // Should see 2 Launched actions. + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Launched"), + 2); + + LogOutAndClose(); + + // Should see 1 switch accounts attempt. + EXPECT_EQ(user_action_tester.GetActionCount( + "AddSupervisionDialog_SwitchedAccounts"), + 1); + + // Simulate the user opening the Add Supervision dialog, enrolling in + // supervision and signing out. + ShowAddSupervisionDialog(); + + // Should see 3 Launched actions. + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Launched"), + 3); + + NotifySupervisionEnabled(); + + // Should see 1 EnrollmentCompleted action. + EXPECT_EQ(user_action_tester.GetActionCount( + "AddSupervisionDialog_EnrollmentCompleted"), + 1); + + LogOutAndClose(); + + // Should see 1 AttemptedSignoutAfterEnrollment action. + EXPECT_EQ(user_action_tester.GetActionCount( + "AddSupervisionDialog_AttemptedSignoutAfterEnrollment"), + 1); +} + +// This browser test class is for the Add Supervision timing metrics. +class AddSupervisionMetricsRecorderTimeTest + : public AddSupervisionMetricsRecorderTest, + public testing::WithParamInterface<int> {}; + +INSTANTIATE_TEST_SUITE_P(AddSupervisionDialogUserTimeInSeconds, + AddSupervisionMetricsRecorderTimeTest, + ::testing::Values(0, 11, 120, 1800)); + +IN_PROC_BROWSER_TEST_P(AddSupervisionMetricsRecorderTimeTest, UserTimingTest) { + base::HistogramTester histogram_tester; + + // Should see 0 Add Supervision timing metrics at first. + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", 0); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentCompletedUserTime", 0); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.SignoutCompletedUserTime", 0); + + // Simulate the user opening the Add Supervision dialog and closing it + // after GetParam() seconds. + scoped_refptr<base::TestMockTimeTaskRunner> task_runner_ = + base::MakeRefCounted<base::TestMockTimeTaskRunner>(); + AddSupervisionMetricsRecorder::GetInstance()->SetClockForTesting( + task_runner_->GetMockTickClock()); + base::TimeDelta duration(base::TimeDelta::FromSeconds(GetParam())); + + // We need to start at some non-zero point in time or else + // DCHECK(!start_time_.is_null()) throws. + task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(1)); + ShowAddSupervisionDialog(); + task_runner_->FastForwardBy(duration); + CloseAddSupervisionDialog(); + + // Should see 1 new EnrollmentNotCompletedUserTime timing. + histogram_tester.ExpectTimeBucketCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", duration, 1); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", 1); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentCompletedUserTime", 0); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.SignoutCompletedUserTime", 0); + + // Simulate the user opening the Add Supervision dialog and signing out to + // switch accounts after GetParam() seconds. + ShowAddSupervisionDialog(); + task_runner_->FastForwardBy(duration); + LogOutAndClose(); + + // Should see 1 new EnrollmentNotCompletedUserTime timing. + histogram_tester.ExpectTimeBucketCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", duration, 2); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", 2); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentCompletedUserTime", 0); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.SignoutCompletedUserTime", 0); + + // Simulate the user opening the Add Supervision dialog, enrolling in + // supervision after GetParam() seconds and signing out after GetParam() + // seconds. + ShowAddSupervisionDialog(); + task_runner_->FastForwardBy(duration); + NotifySupervisionEnabled(); + task_runner_->FastForwardBy(duration); + LogOutAndClose(); + + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", 2); + // Should see 1 new EnrollmentCompletedUserTime timing. + histogram_tester.ExpectTimeBucketCount( + "AddSupervisionDialog.EnrollmentCompletedUserTime", duration, 1); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentCompletedUserTime", 1); + // Should see 1 new SignoutCompletedUserTime timing. + histogram_tester.ExpectTimeBucketCount( + "AddSupervisionDialog.SignoutCompletedUserTime", 2 * duration, 1); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.SignoutCompletedUserTime", 1); +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc index b0dcfb1cfef..c0c3fb9b98f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc @@ -8,14 +8,13 @@ #include <utility> #include "base/bind.h" -#include "base/no_destructor.h" #include "base/system/sys_info.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/supervised_user/supervised_user_service.h" -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/views/chrome_web_dialog_view.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h" #include "chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/browser_resources.h" @@ -34,19 +33,12 @@ namespace { constexpr int kDialogHeightPx = 608; constexpr int kDialogWidthPx = 768; -// Id of System Dialog used to show the Add Supervision flow. -std::string& GetDialogId() { - static base::NoDestructor<std::string> dialog_id; - return *dialog_id; -} // Shows the dialog indicating that user has to sign out if supervision has been // enabled for their account. Returns a boolean indicating whether the // ConfirmSignoutDialog is being shown. bool MaybeShowConfirmSignoutDialog() { - SupervisedUserService* service = SupervisedUserServiceFactory::GetForProfile( - ProfileManager::GetPrimaryUserProfile()); - if (service->signout_required_after_supervision_enabled()) { + if (EnrollmentCompleted()) { ConfirmSignoutDialog::Show(); return true; } @@ -94,10 +86,18 @@ void AddSupervisionDialog::Show(gfx::NativeView parent) { // SystemWebDialogDelegate::OnDialogClosed() is called. current_instance = new AddSupervisionDialog(); - GetDialogId() = current_instance->Id(); - current_instance->ShowSystemDialogForBrowserContext( ProfileManager::GetPrimaryUserProfile(), parent); + + // Record UMA metric that user has initiated the Add Supervision process. + AddSupervisionMetricsRecorder::GetInstance()->RecordAddSupervisionEnrollment( + AddSupervisionMetricsRecorder::EnrollmentState::kInitiated); +} + +// static +SystemWebDialogDelegate* AddSupervisionDialog::GetInstance() { + return SystemWebDialogDelegate::FindInstance( + chrome::kChromeUIAddSupervisionURL); } // static @@ -105,7 +105,14 @@ void AddSupervisionDialog::Close() { SystemWebDialogDelegate* current_instance = GetInstance(); if (current_instance) { current_instance->Close(); - GetDialogId() = std::string(); + } +} + +void AddSupervisionDialog::CloseNowForTesting() { + SystemWebDialogDelegate* current_instance = GetInstance(); + if (current_instance) { + DCHECK(dialog_window()) << "No dialog window instance currently set."; + views::Widget::GetWidgetForNativeWindow(dialog_window())->CloseNow(); } } @@ -117,20 +124,16 @@ void AddSupervisionDialog::GetDialogSize(gfx::Size* size) const { size->SetSize(kDialogWidthPx, kDialogHeightPx); } -bool AddSupervisionDialog::OnDialogCloseRequested() { +bool AddSupervisionDialog::CanCloseDialog() const { bool showing_confirm_dialog = MaybeShowConfirmSignoutDialog(); return !showing_confirm_dialog; } -void AddSupervisionDialog::OnCloseContents(content::WebContents* source, - bool* out_close_dialog) { - // This code gets called by a different path that OnDialogCloseRequested(), - // and actually masks the call to OnDialogCloseRequested() the first time the - // user clicks on the [x]. Because the first [x] click comes here, we need to - // show the confirmation dialog here and signal the caller to possibly close - // the dialog. Subsequent clicks on [x] during the lifetime of the dialog - // will result in calls to OnDialogCloseRequested(). - *out_close_dialog = OnDialogCloseRequested(); +bool AddSupervisionDialog::OnDialogCloseRequested() { + // Record UMA metric that user has closed the Add Supervision dialog. + AddSupervisionMetricsRecorder::GetInstance()->RecordAddSupervisionEnrollment( + AddSupervisionMetricsRecorder::EnrollmentState::kClosed); + return true; } AddSupervisionDialog::AddSupervisionDialog() @@ -139,11 +142,6 @@ AddSupervisionDialog::AddSupervisionDialog() AddSupervisionDialog::~AddSupervisionDialog() = default; -// static -SystemWebDialogDelegate* AddSupervisionDialog::GetInstance() { - return SystemWebDialogDelegate::FindInstance(GetDialogId()); -} - // AddSupervisionUI implementations. AddSupervisionUI::AddSupervisionUI(content::WebUI* web_ui) @@ -188,7 +186,7 @@ void AddSupervisionUI::SetupResources() { "add_supervision.mojom-lite.js", IDR_ADD_SUPERVISION_MOJOM_LITE_JS); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_ADD_SUPERVISION_HTML); source->AddString("webviewUrl", supervision_url_.spec()); source->AddString("eventOriginFilter", supervision_url_.GetOrigin().spec()); diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h index 25a2c1b2068..02afc8e1d8e 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h @@ -27,24 +27,30 @@ class AddSupervisionDialog : public SystemWebDialogDelegate { // no-op. static void Show(gfx::NativeView parent); - // Closes the dialog, if the dialog doesn't exist, this function is a + static SystemWebDialogDelegate* GetInstance(); + + // Closes the dialog; if the dialog doesn't exist, this function is a // no-op. + // This is only called when the user clicks "Cancel", not the "x" in the top + // right. static void Close(); + // Deletes this dialog window. + // Currently only used by AddSupervisionMetricsRecorderTest browser test to + // simulate closing the dialog cleanly. + void CloseNowForTesting(); + // ui::WebDialogDelegate: ui::ModalType GetDialogModalType() const override; void GetDialogSize(gfx::Size* size) const override; + bool CanCloseDialog() const override; bool OnDialogCloseRequested() override; - void OnCloseContents(content::WebContents* source, - bool* out_close_dialog) override; protected: AddSupervisionDialog(); ~AddSupervisionDialog() override; private: - static SystemWebDialogDelegate* GetInstance(); - DISALLOW_COPY_AND_ASSIGN(AddSupervisionDialog); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc index 9ee08568e9b..b0754f4a57b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc @@ -7,11 +7,10 @@ #include <memory> #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/ui/browser_dialogs.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" #include "chrome/grit/generated_resources.h" #include "components/constrained_window/constrained_window_views.h" -#include "components/user_manager/user_manager.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/resources/grit/ui_resources.h" @@ -35,15 +34,12 @@ ConfirmSignoutDialog::ConfirmSignoutDialog() { views::LayoutProvider::Get()->GetDialogInsetsForContentType( views::DialogContentType::TEXT, views::DialogContentType::TEXT))); - base::string16 given_name = - user_manager::UserManager::Get()->GetPrimaryUser()->GetGivenName(); - - // |body_| will be owned by the views system. + // |body| will be owned by the views system. views::Label* body = new views::Label; body->SetHorizontalAlignment(gfx::ALIGN_LEFT); body->SetMultiLine(true); - body->SetText(l10n_util::GetStringFUTF16(IDS_ADD_SUPERVISION_EXIT_DIALOG_BODY, - given_name)); + body->SetText( + l10n_util::GetStringUTF16(IDS_ADD_SUPERVISION_EXIT_DIALOG_BODY)); body->SizeToFit(kDialogBodyTextWidth); AddChildView(body); } @@ -59,7 +55,7 @@ base::string16 ConfirmSignoutDialog::GetWindowTitle() const { } bool ConfirmSignoutDialog::Accept() { - chrome::AttemptUserExit(); + LogOutHelper(); return true; } diff --git a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc index de20b5eedd0..3c918789930 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc @@ -16,6 +16,7 @@ #include "base/json/json_writer.h" #include "base/linux_util.h" #include "base/memory/ref_counted_memory.h" +#include "base/metrics/histogram_macros.h" #include "base/process/process_iterator.h" #include "base/strings/string_split.h" #include "base/strings/string_tokenizer.h" @@ -55,9 +56,24 @@ constexpr char kKeyTasks[] = "tasks"; constexpr char kLastTracingModelName[] = "last_tracing_model.json"; +enum class Action { + kShown = 0, + kBuildSucceeded = 1, + kBuildFailed = 2, + kInitialLoadSucceeded = 3, + kInitialLoadFailed = 4, + kLoadSucceeded = 5, + kLoadFailed = 6, + kMaxValue = kLoadFailed, +}; + +void UpdateStatistics(Action action) { + UMA_HISTOGRAM_ENUMERATION("Arc.Tracing.Tool", action); +} + // Maximum interval to display. constexpr base::TimeDelta kMaxIntervalToDisplay = - base::TimeDelta::FromSecondsD(3.0); + base::TimeDelta::FromSecondsD(5.0); base::FilePath GetLastTracingModelPath(Profile* profile) { DCHECK(profile); @@ -78,9 +94,12 @@ std::pair<base::Value, std::string> MaybeLoadLastGraphicsModel( arc::ArcTracingGraphicsModel graphics_model; base::DictionaryValue* dictionary = nullptr; model->GetAsDictionary(&dictionary); - if (!graphics_model.LoadFromValue(*dictionary)) + if (!graphics_model.LoadFromValue(*dictionary)) { + UpdateStatistics(Action::kInitialLoadFailed); return std::make_pair(base::Value(), "Failed to load last tracing model"); + } + UpdateStatistics(Action::kInitialLoadSucceeded); return std::make_pair(std::move(*model), "Loaded last tracing model"); } @@ -168,15 +187,19 @@ std::pair<base::Value, std::string> BuildGraphicsModel( (time_min_clamped - base::TimeTicks()).InMicroseconds(), (time_max - base::TimeTicks()).InMicroseconds()); - if (!common_model.Build(data)) + if (!common_model.Build(data)) { + UpdateStatistics(Action::kBuildFailed); return std::make_pair(base::Value(), "Failed to process tracing data"); + } system_stat_collector->Flush(time_min, time_max, &common_model.system_model()); arc::ArcTracingGraphicsModel graphics_model; - if (!graphics_model.Build(common_model)) + if (!graphics_model.Build(common_model)) { + UpdateStatistics(Action::kBuildFailed); return std::make_pair(base::Value(), "Failed to build tracing model"); + } UpdateThreads(&graphics_model.system_model().thread_map()); @@ -194,16 +217,20 @@ std::pair<base::Value, std::string> BuildGraphicsModel( << "."; } + UpdateStatistics(Action::kBuildSucceeded); return std::make_pair(std::move(*model), "Tracing model is ready"); } std::pair<base::Value, std::string> LoadGraphicsModel( const std::string& json_text) { arc::ArcTracingGraphicsModel graphics_model; - if (!graphics_model.LoadFromJson(json_text)) + if (!graphics_model.LoadFromJson(json_text)) { + UpdateStatistics(Action::kLoadFailed); return std::make_pair(base::Value(), "Failed to load tracing model"); + } std::unique_ptr<base::DictionaryValue> model = graphics_model.Serialize(); + UpdateStatistics(Action::kLoadSucceeded); return std::make_pair(std::move(*model), "Tracing model is loaded"); } @@ -211,8 +238,7 @@ std::pair<base::Value, std::string> LoadGraphicsModel( ArcGraphicsTracingHandler::ArcGraphicsTracingHandler() : wm_helper_(exo::WMHelper::HasInstance() ? exo::WMHelper::GetInstance() - : nullptr), - weak_ptr_factory_(this) { + : nullptr) { DCHECK(wm_helper_); aura::Window* const current_active = wm_helper_->GetActiveWindow(); @@ -221,6 +247,8 @@ ArcGraphicsTracingHandler::ArcGraphicsTracingHandler() current_active, nullptr); } wm_helper_->AddActivationObserver(this); + + UpdateStatistics(Action::kShown); } ArcGraphicsTracingHandler::~ArcGraphicsTracingHandler() { @@ -428,8 +456,9 @@ void ArcGraphicsTracingHandler::OnTracingStopped( base::RefCountedString* trace_data) { std::string string_data; string_data.swap(trace_data->data()); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&BuildGraphicsModel, std::move(string_data), std::move(tasks_info_), std::move(system_stat_colletor_), tracing_time_min_, tracing_time_max_, @@ -450,8 +479,9 @@ void ArcGraphicsTracingHandler::OnGraphicsModelReady( } void ArcGraphicsTracingHandler::HandleReady(const base::ListValue* args) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&MaybeLoadLastGraphicsModel, GetLastTracingModelPath(Profile::FromWebUI(web_ui()))), base::BindOnce(&ArcGraphicsTracingHandler::OnGraphicsModelReady, @@ -476,8 +506,9 @@ void ArcGraphicsTracingHandler::HandleLoadFromText( return; } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&LoadGraphicsModel, std::move(args->GetList()[0].GetString())), base::BindOnce(&ArcGraphicsTracingHandler::OnGraphicsModelReady, diff --git a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.h b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.h index 4f613c1a1a7..bd774e39149 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.h @@ -119,7 +119,7 @@ class ArcGraphicsTracingHandler : public content::WebUIMessageHandler, // Information about tasks, title and icon. base::DictionaryValue tasks_info_; - base::WeakPtrFactory<ArcGraphicsTracingHandler> weak_ptr_factory_; + base::WeakPtrFactory<ArcGraphicsTracingHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ArcGraphicsTracingHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc index f144257e56f..9610dee0f41 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc @@ -25,7 +25,7 @@ constexpr char kArcGraphicsTracingCssPath[] = "arc_graphics_tracing.css"; content::WebUIDataSource* CreateDataSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIArcGraphicsTracingHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_ARC_GRAPHICS_TRACING_HTML); source->AddResourcePath(kArcGraphicsTracingJsPath, IDR_ARC_GRAPHICS_TRACING_JS); 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 index 2e65bdfe483..03a052c6863 100644 --- 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 @@ -8,7 +8,7 @@ #include <string> #include <utility> -#include "ash/public/interfaces/voice_interaction_controller.mojom.h" +#include "ash/public/mojom/voice_interaction_controller.mojom.h" #include "base/bind.h" #include "base/macros.h" #include "base/strings/string_number_conversions.h" @@ -20,7 +20,6 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" #include "chromeos/services/assistant/public/cpp/assistant_prefs.h" -#include "components/arc/arc_prefs.h" #include "components/prefs/pref_service.h" #include "components/session_manager/core/session_manager.h" #include "content/public/browser/host_zoom_map.h" @@ -29,7 +28,9 @@ #include "content/public/browser/web_ui_data_source.h" #include "content/public/common/content_features.h" #include "net/base/url_util.h" +#include "ui/chromeos/resources/grit/ui_chromeos_resources.h" #include "ui/views/widget/widget.h" +#include "ui/wm/core/window_animations.h" namespace chromeos { @@ -76,11 +77,14 @@ AssistantOptInUI::AssistantOptInUI(content::WebUI* web_ui) base::DictionaryValue localized_strings; assistant_handler_ptr_->GetLocalizedStrings(&localized_strings); source->AddLocalizedStrings(localized_strings); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("assistant_optin.js", IDR_ASSISTANT_OPTIN_JS); source->AddResourcePath("assistant_logo.png", IDR_ASSISTANT_LOGO_PNG); source->AddBoolean("hotwordDspAvailable", chromeos::IsHotwordDspAvailable()); source->SetDefaultResource(IDR_ASSISTANT_OPTIN_HTML); + source->AddResourcePath("voice_match_animation.json", + IDR_ASSISTANT_VOICE_MATCH_ANIMATION); + source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';"); content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); // Do not zoom for Assistant opt-in web contents. @@ -135,6 +139,17 @@ void AssistantOptInDialog::Show( g_dialog->ShowSystemDialog(); } +// static +bool AssistantOptInDialog::BounceIfActive() { + if (!g_dialog) + return false; + + g_dialog->Focus(); + wm::AnimateWindow(g_dialog->dialog_window(), + wm::WINDOW_ANIMATION_TYPE_BOUNCE); + return true; +} + AssistantOptInDialog::AssistantOptInDialog( ash::FlowType type, ash::AssistantSetup::StartAssistantOptInFlowCallback callback) @@ -172,7 +187,7 @@ void AssistantOptInDialog::OnDialogClosed(const std::string& json_retval) { PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); const bool completed = - prefs->GetBoolean(arc::prefs::kVoiceInteractionEnabled) && + prefs->GetBoolean(chromeos::assistant::prefs::kAssistantEnabled) && (prefs->GetInteger(assistant::prefs::kAssistantConsentStatus) == assistant::prefs::ConsentStatus::kActivityControlAccepted); std::move(callback_).Run(completed); 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 index d4b7b6b90e0..a93c2483e26 100644 --- 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 @@ -48,6 +48,9 @@ class AssistantOptInDialog : public SystemWebDialogDelegate { ash::AssistantSetup::StartAssistantOptInFlowCallback callback = base::DoNothing()); + // Returns true and bounces the window if the dialog is active. + static bool BounceIfActive(); + protected: AssistantOptInDialog( ash::FlowType type, diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc index 4287e686189..96f8106a00d 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc @@ -13,6 +13,7 @@ #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" #include "chromeos/audio/cras_audio_handler.h" +#include "chromeos/services/assistant/public/cpp/assistant_prefs.h" #include "chromeos/services/assistant/public/features.h" #include "components/arc/arc_prefs.h" #include "components/consent_auditor/consent_auditor.h" @@ -39,12 +40,12 @@ bool IsPreferenceDefaultEnabled(const PrefService* prefs, bool IsScreenContextDefaultEnabled(PrefService* prefs) { return IsPreferenceDefaultEnabled( - prefs, arc::prefs::kVoiceInteractionContextEnabled); + prefs, chromeos::assistant::prefs::kAssistantContextEnabled); } bool IsScreenContextToggleDisabled(PrefService* prefs) { return prefs->IsManagedPreference( - arc::prefs::kVoiceInteractionContextEnabled); + chromeos::assistant::prefs::kAssistantContextEnabled); } } // namespace @@ -244,8 +245,8 @@ bool IsVoiceMatchEnforcedOff(const PrefService* prefs) { // If the hotword preference is managed to always disabled, then we should not // show Voice Match flow. return prefs->IsManagedPreference( - arc::prefs::kVoiceInteractionHotwordEnabled) && - !prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled); + assistant::prefs::kAssistantHotwordEnabled) && + !prefs->GetBoolean(assistant::prefs::kAssistantHotwordEnabled); } } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc index 326632a3125..b65490702e4 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc @@ -103,7 +103,7 @@ BluetoothPairingDialogUI::BluetoothPairingDialogUI(content::WebUI* web_ui) AddBluetoothStrings(source); source->AddLocalizedString("title", IDS_SETTINGS_BLUETOOTH_PAIR_DEVICE_TITLE); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); #if BUILDFLAG(OPTIMIZE_WEBUI) source->SetDefaultResource(IDR_BLUETOOTH_PAIRING_DIALOG_VULCANIZED_HTML); source->AddResourcePath("crisper.js", diff --git a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog_browsertest-inl.h b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog_browsertest-inl.h index 3fd8630b818..3a39cb5c7ab 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog_browsertest-inl.h +++ b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog_browsertest-inl.h @@ -54,9 +54,10 @@ void BluetoothPairingDialogTest::ShowDialog() { const bool kNotPaired = false; const bool kNotConnected = false; - mock_device_.reset(new testing::NiceMock<device::MockBluetoothDevice>( - nullptr, 0, "Bluetooth 2.0 Mouse", "28:CF:DA:00:00:00", kNotPaired, - kNotConnected)); + mock_device_ = + std::make_unique<testing::NiceMock<device::MockBluetoothDevice>>( + nullptr, 0, "Bluetooth 2.0 Mouse", "28:CF:DA:00:00:00", kNotPaired, + kNotConnected); EXPECT_CALL(*mock_adapter_, GetDevice(testing::_)) .WillRepeatedly(testing::Return(mock_device_.get())); diff --git a/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc index c6110b2fde4..8a40f0cbdba 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc @@ -45,15 +45,15 @@ content::WebUIDataSource* CreateCameraUIHTMLSource() { IDR_CAMERA_CAMERA_METADATA_MOJOM_LITE_JS); source->AddResourcePath("src/js/mojo/camera_metadata_tags.mojom-lite.js", IDR_CAMERA_CAMERA_METADATA_TAGS_MOJOM_LITE_JS); - source->AddResourcePath("src/js/mojo/cros_image_capture.mojom-lite.js", - IDR_CAMERA_CROS_IMAGE_CAPTURE_MOJOM_LITE_JS); + source->AddResourcePath("src/js/mojo/camera_app.mojom-lite.js", + IDR_CAMERA_APP_MOJOM_LITE_JS); source->AddResourcePath("src/js/mojo/mojo_bindings_lite.js", IDR_MOJO_MOJO_BINDINGS_LITE_JS); // Add System Web App resources. source->AddResourcePath("pwa.html", IDR_PWA_HTML); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } diff --git a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/DEPS b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/DEPS new file mode 100644 index 00000000000..55ca2bd3041 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/DEPS @@ -0,0 +1,3 @@ +include_rules = [ + "+chromeos/services/cellular_setup", +] diff --git a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog.cc index 4243362e1fc..60d1b64de38 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog.cc @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog.h" #include "base/bind.h" +#include "base/supports_user_data.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_dialogs.h" @@ -12,9 +13,10 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/cellular_setup_resources.h" #include "chrome/grit/cellular_setup_resources_map.h" -#include "chromeos/services/cellular_setup/public/mojom/constants.mojom.h" +#include "chromeos/services/cellular_setup/cellular_setup_base.h" +#include "chromeos/services/cellular_setup/cellular_setup_impl.h" #include "content/public/browser/web_ui_data_source.h" -#include "services/service_manager/public/cpp/connector.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "ui/aura/window.h" namespace chromeos { @@ -30,6 +32,37 @@ constexpr int kDialogWidthPx = 650; CellularSetupDialog* dialog_instance = nullptr; +// Used to attach an instance of the CellularSetup service to a BrowserContext. +class CellularSetupServiceHolder : public base::SupportsUserData::Data { + public: + CellularSetupServiceHolder() = default; + ~CellularSetupServiceHolder() override = default; + + void BindReceiver(mojo::PendingReceiver<mojom::CellularSetup> receiver) { + service_.BindRequest(std::move(receiver)); + } + + private: + CellularSetupImpl service_; + + DISALLOW_COPY_AND_ASSIGN(CellularSetupServiceHolder); +}; + +const char kCellularSetupServiceHolderKey[] = "cellular_setup_service_holder"; + +CellularSetupServiceHolder* GetOrCreateServiceHolder( + content::BrowserContext* browser_context) { + auto* holder = static_cast<CellularSetupServiceHolder*>( + browser_context->GetUserData(kCellularSetupServiceHolderKey)); + if (!holder) { + auto new_holder = std::make_unique<CellularSetupServiceHolder>(); + holder = new_holder.get(); + browser_context->SetUserData(kCellularSetupServiceHolderKey, + std::move(new_holder)); + } + return holder; +} + } // namespace // static @@ -78,7 +111,7 @@ CellularSetupDialogUI::CellularSetupDialogUI(content::WebUI* web_ui) content::WebUIDataSource::Create(chrome::kChromeUICellularSetupHost); chromeos::cellular_setup::AddLocalizedStrings(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_CELLULAR_SETUP_CELLULAR_SETUP_DIALOG_HTML); // Note: The |kCellularSetupResourcesSize| and |kCellularSetupResources| @@ -100,10 +133,8 @@ CellularSetupDialogUI::~CellularSetupDialogUI() = default; void CellularSetupDialogUI::BindCellularSetup( mojom::CellularSetupRequest request) { - service_manager::Connector* connector = - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()); - connector->BindInterface(mojom::kServiceName, std::move(request)); + GetOrCreateServiceHolder(web_ui()->GetWebContents()->GetBrowserContext()) + ->BindReceiver(std::move(request)); } } // namespace cellular_setup diff --git a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc index 981076b2c11..994d31c045b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc @@ -23,7 +23,17 @@ constexpr LocalizedString kLocalizedStringsWithoutPlaceholders[] = { {"finish", IDS_CELLULAR_SETUP_FINISH_LABEL}, {"tryAgain", IDS_CELLULAR_SETUP_TRY_AGAIN_LABEL}, {"simDetectPageTitle", IDS_CELLULAR_SETUP_SIM_DETECT_PAGE_TITLE}, - {"provisioningPageTitle", IDS_CELLULAR_SETUP_PROVISIONING_PAGE_TITLE}, + {"simDetectPageErrorTitle", IDS_CELLULAR_SETUP_SIM_DETECT_PAGE_ERROR_TITLE}, + {"simDetectPageErrorMessage", + IDS_CELLULAR_SETUP_SIM_DETECT_PAGE_ERROR_MESSAGE}, + {"provisioningPageLoadingTitle", + IDS_CELLULAR_SETUP_PROVISIONING_PAGE_LOADING_TITLE}, + {"provisioningPageActiveTitle", + IDS_CELLULAR_SETUP_PROVISIONING_PAGE_ACTIVE_TITLE}, + {"provisioningPageErrorTitle", + IDS_CELLULAR_SETUP_PROVISIONING_PAGE_ERROR_TITLE}, + {"provisioningPageErrorMessage", + IDS_CELLULAR_SETUP_PROVISIONING_PAGE_ERROR_MESSAGE}, {"finalPageTitle", IDS_CELLULAR_SETUP_FINAL_PAGE_TITLE}, {"finalPageMessage", IDS_CELLULAR_SETUP_FINAL_PAGE_MESSAGE}, {"finalPageErrorTitle", IDS_CELLULAR_SETUP_FINAL_PAGE_ERROR_TITLE}, diff --git a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc index 5eaf0f3a48c..6ac7d19882b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc @@ -178,7 +178,7 @@ class MobileSetupUIHTMLSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string&) override { return "text/html"; } bool ShouldAddContentSecurityPolicy() override { return false; } @@ -189,7 +189,7 @@ class MobileSetupUIHTMLSource : public content::URLDataSource { } private: - base::WeakPtrFactory<MobileSetupUIHTMLSource> weak_ptr_factory_; + base::WeakPtrFactory<MobileSetupUIHTMLSource> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MobileSetupUIHTMLSource); }; @@ -251,7 +251,7 @@ class MobileSetupHandler : public content::WebUIMessageHandler, // connection state. This value is reflected in portal webui for lte networks. // Initial value is true. bool lte_portal_reachable_; - base::WeakPtrFactory<MobileSetupHandler> weak_ptr_factory_; + base::WeakPtrFactory<MobileSetupHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MobileSetupHandler); }; @@ -262,7 +262,7 @@ class MobileSetupHandler : public content::WebUIMessageHandler, // //////////////////////////////////////////////////////////////////////////////// -MobileSetupUIHTMLSource::MobileSetupUIHTMLSource() : weak_ptr_factory_(this) {} +MobileSetupUIHTMLSource::MobileSetupUIHTMLSource() {} std::string MobileSetupUIHTMLSource::GetSource() { return chrome::kChromeUIMobileSetupHost; @@ -270,7 +270,7 @@ std::string MobileSetupUIHTMLSource::GetSource() { void MobileSetupUIHTMLSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { // Sanity checks that activation was requested for an appropriate network. const NetworkState* network = @@ -362,10 +362,7 @@ void MobileSetupUIHTMLSource::StartDataRequest( // //////////////////////////////////////////////////////////////////////////////// MobileSetupHandler::MobileSetupHandler() - : type_(TYPE_UNDETERMINED), - active_(false), - lte_portal_reachable_(true), - weak_ptr_factory_(this) {} + : type_(TYPE_UNDETERMINED), active_(false), lte_portal_reachable_(true) {} MobileSetupHandler::~MobileSetupHandler() { Reset(); diff --git a/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.cc index e3c74610424..36919052a60 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.cc @@ -55,7 +55,7 @@ CertificateManagerDialogUI::CertificateManagerDialogUI(content::WebUI* web_ui) user_manager::UserManager::Get()->IsLoggedInAsKioskApp() || user_manager::UserManager::Get()->IsLoggedInAsArcKioskApp()); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_CERT_MANAGER_DIALOG_HTML); source->DisableContentSecurityPolicy(); 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 a2b95c06332..52894b68f0e 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 @@ -18,7 +18,7 @@ using content::BrowserThread; namespace chromeos { -CryptohomeWebUIHandler::CryptohomeWebUIHandler() : weak_ptr_factory_(this) {} +CryptohomeWebUIHandler::CryptohomeWebUIHandler() {} CryptohomeWebUIHandler::~CryptohomeWebUIHandler() {} @@ -40,7 +40,7 @@ void CryptohomeWebUIHandler::OnPageLoaded(const base::ListValue* args) { cryptohome_client->Pkcs11IsTpmTokenReady( GetCryptohomeBoolCallback("pkcs11-is-tpm-token-ready")); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::IO}, base::Bind(&crypto::IsTPMTokenReady, base::Closure()), base::Bind(&CryptohomeWebUIHandler::DidGetNSSUtilInfoOnUIThread, diff --git a/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.h b/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.h index b470724610c..890066643bb 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.h @@ -49,7 +49,7 @@ class CryptohomeWebUIHandler : public content::WebUIMessageHandler { void SetCryptohomeProperty(const std::string& destination_id, const base::Value& value); - base::WeakPtrFactory<CryptohomeWebUIHandler> weak_ptr_factory_; + base::WeakPtrFactory<CryptohomeWebUIHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CryptohomeWebUIHandler); }; 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 cce737b51cf..686d55faf55 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc @@ -34,6 +34,7 @@ #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/file_manager/path_util.h" #include "chrome/browser/drive/drive_notification_manager_factory.h" +#include "chrome/browser/file_util_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" @@ -53,7 +54,6 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_controller.h" -#include "content/public/browser/system_connector.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" @@ -297,8 +297,7 @@ void ZipLogs(Profile* profile, // Class to handle messages from chrome://drive-internals. class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { public: - DriveInternalsWebUIHandler() - : last_sent_event_id_(-1), weak_ptr_factory_(this) {} + DriveInternalsWebUIHandler() : last_sent_event_id_(-1) {} ~DriveInternalsWebUIHandler() override {} @@ -694,8 +693,10 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { // Propagate the amount of local free space in bytes. base::FilePath home_path; if (base::PathService::Get(base::DIR_HOME, &home_path)) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&base::SysInfo::AmountOfFreeDiskSpace, home_path), base::BindOnce(&DriveInternalsWebUIHandler::OnGetFreeDiskSpace, weak_ptr_factory_.GetWeakPtr())); @@ -793,8 +794,10 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { "updateOtherServiceLogsUrl", base::Value(net::FilePathToFileURL(log_path.DirName()).spec())); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&GetServiceLogContents, log_path, service_log_file_inode_, last_sent_line_number_), base::BindOnce(&DriveInternalsWebUIHandler::OnServiceLogRead, @@ -852,8 +855,10 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { const base::FilePath root_path = drive::util::GetCacheRootPath(profile()).DirName(); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&GetGCacheContents, root_path), base::BindOnce(&DriveInternalsWebUIHandler::OnGetGCacheContents, weak_ptr_factory_.GetWeakPtr())); @@ -966,7 +971,7 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { // Service log file is being parsed. bool service_log_file_is_processing_ = false; - base::WeakPtrFactory<DriveInternalsWebUIHandler> weak_ptr_factory_; + base::WeakPtrFactory<DriveInternalsWebUIHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DriveInternalsWebUIHandler); }; @@ -983,8 +988,10 @@ class LogsZipper : public download::AllDownloadItemNotifier::Observer { drive_internals_(std::move(drive_internals)) {} void Start() { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&LogsZipper::EnumerateLogFiles, logs_directory_, zip_path_), base::BindOnce(&LogsZipper::ZipLogFiles, base::Unretained(this))); @@ -997,7 +1004,7 @@ class LogsZipper : public download::AllDownloadItemNotifier::Observer { (new ZipFileCreator( base::BindRepeating(&LogsZipper::OnZipDone, base::Unretained(this)), logs_directory_, files, zip_path_)) - ->Start(content::GetSystemConnector()); + ->Start(LaunchFileUtilService()); } static std::vector<base::FilePath> EnumerateLogFiles( @@ -1040,8 +1047,9 @@ class LogsZipper : public download::AllDownloadItemNotifier::Observer { } void CleanUp() { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), zip_path_, false)); download_notifier_.reset(); 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 85c54f11143..1c6ecadb2f3 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 @@ -198,8 +198,7 @@ DeviceEmulatorMessageHandler::DeviceEmulatorMessageHandler() : fake_bluetooth_device_client_( static_cast<bluez::FakeBluetoothDeviceClient*>( bluez::BluezDBusManager::Get()->GetBluetoothDeviceClient())), - fake_power_manager_client_(chromeos::FakePowerManagerClient::Get()), - weak_ptr_factory_(this) { + fake_power_manager_client_(chromeos::FakePowerManagerClient::Get()) { device::BluetoothAdapterFactory::GetAdapter( base::BindOnce(&DeviceEmulatorMessageHandler::BluetoothDeviceAdapterReady, weak_ptr_factory_.GetWeakPtr())); @@ -553,9 +552,9 @@ void DeviceEmulatorMessageHandler::RegisterMessages() { } void DeviceEmulatorMessageHandler::OnJavascriptAllowed() { - bluetooth_observer_.reset(new BluetoothObserver(this)); - cras_audio_observer_.reset(new CrasAudioObserver(this)); - power_observer_.reset(new PowerObserver(this)); + bluetooth_observer_ = std::make_unique<BluetoothObserver>(this); + cras_audio_observer_ = std::make_unique<CrasAudioObserver>(this); + power_observer_ = std::make_unique<PowerObserver>(this); system::InputDeviceSettings::Get()->TouchpadExists( base::BindOnce(&DeviceEmulatorMessageHandler::TouchpadExists, diff --git a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h index 0aca35bab32..3afd435d960 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h @@ -137,7 +137,7 @@ class DeviceEmulatorMessageHandler : scoped_refptr<device::BluetoothAdapter> bluetooth_adapter_; - base::WeakPtrFactory<DeviceEmulatorMessageHandler> weak_ptr_factory_; + base::WeakPtrFactory<DeviceEmulatorMessageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DeviceEmulatorMessageHandler); }; 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 d05e0369f39..46afde2fa0d 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 @@ -6,7 +6,7 @@ #include <utility> -#include "ash/public/interfaces/voice_interaction_controller.mojom.h" +#include "ash/public/mojom/voice_interaction_controller.mojom.h" #include "base/bind.h" #include "base/values.h" #include "chrome/browser/chromeos/assistant/assistant_util.h" diff --git a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc index 912347ea86e..a58bf9524c5 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc @@ -86,7 +86,7 @@ void SetLocalizedStrings(Profile* profile, content::WebUIDataSource* CreateDataSource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIFirstRunHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_FIRST_RUN_HTML); source->AddResourcePath(kFirstRunJSPath, IDR_FIRST_RUN_JS); base::DictionaryValue localized_strings; diff --git a/chromium/chrome/browser/ui/webui/chromeos/image_source.cc b/chromium/chrome/browser/ui/webui/chromeos/image_source.cc index d5942fc36e6..1a9ff112dda 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/image_source.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/image_source.cc @@ -16,7 +16,7 @@ #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/task/post_task.h" -#include "base/task/thread_pool/thread_pool.h" +#include "base/task/thread_pool/thread_pool_instance.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/chromeos/login/users/avatar/user_image_loader.h" #include "chrome/common/url_constants.h" @@ -40,9 +40,9 @@ void ImageLoaded( } // namespace -ImageSource::ImageSource() : weak_factory_(this) { - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, +ImageSource::ImageSource() { + task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); } @@ -55,7 +55,7 @@ std::string ImageSource::GetSource() { void ImageSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& got_data_callback) { if (!IsWhitelisted(path)) { got_data_callback.Run(nullptr); @@ -64,8 +64,9 @@ void ImageSource::StartDataRequest( const base::FilePath asset_dir(chrome::kChromeOSAssetPath); const base::FilePath image_path = asset_dir.AppendASCII(path); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&base::PathExists, image_path), base::Bind(&ImageSource::StartDataRequestAfterPathExists, weak_factory_.GetWeakPtr(), image_path, got_data_callback)); diff --git a/chromium/chrome/browser/ui/webui/chromeos/image_source.h b/chromium/chrome/browser/ui/webui/chromeos/image_source.h index 5d7a5afcec0..4bf09ea101a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/image_source.h +++ b/chromium/chrome/browser/ui/webui/chromeos/image_source.h @@ -27,11 +27,10 @@ class ImageSource : public content::URLDataSource { // content::URLDataSource implementation. std::string GetSource() override; - void StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const content::URLDataSource::GotDataCallback& got_data_callback) - override; + void StartDataRequest(const std::string& path, + const content::WebContents::Getter& wc_getter, + const content::URLDataSource::GotDataCallback& + got_data_callback) override; std::string GetMimeType(const std::string& path) override; @@ -48,7 +47,7 @@ class ImageSource : public content::URLDataSource { // The background task runner on which file I/O and image decoding are done. scoped_refptr<base::SequencedTaskRunner> task_runner_; - base::WeakPtrFactory<ImageSource> weak_factory_; + base::WeakPtrFactory<ImageSource> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ImageSource); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc index e46a6eabfa8..b95907fe477 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc @@ -19,7 +19,29 @@ namespace chromeos { -ConfirmPasswordChangeHandler::ConfirmPasswordChangeHandler() { +namespace { + +const InSessionPasswordChangeManager::Event kIncorrectPasswordEvent = + InSessionPasswordChangeManager::Event::CRYPTOHOME_PASSWORD_CHANGE_FAILURE; + +const InSessionPasswordChangeManager::PasswordSource kPasswordSource = + InSessionPasswordChangeManager::PasswordSource::PASSWORDS_RETYPED; + +// Returns one if it is non-empty, otherwise returns two. +const std::string& FirstNonEmpty(const std::string& one, + const std::string& two) { + return !one.empty() ? one : two; +} + +} // namespace + +ConfirmPasswordChangeHandler::ConfirmPasswordChangeHandler( + const std::string& scraped_old_password, + const std::string& scraped_new_password, + const bool show_spinner_initially) + : scraped_old_password_(scraped_old_password), + scraped_new_password_(scraped_new_password), + show_spinner_initially_(show_spinner_initially) { if (InSessionPasswordChangeManager::IsInitialized()) { InSessionPasswordChangeManager::Get()->AddObserver(this); } @@ -31,25 +53,52 @@ ConfirmPasswordChangeHandler::~ConfirmPasswordChangeHandler() { } } -void ConfirmPasswordChangeHandler::OnEvent( - InSessionPasswordChangeManager::Event event) { - if (event == - InSessionPasswordChangeManager::CRYPTOHOME_PASSWORD_CHANGE_FAILURE) { - AllowJavascript(); - FireWebUIListener("incorrect-old-password"); - } +void ConfirmPasswordChangeHandler::HandleGetInitialState( + const base::ListValue* params) { + const std::string callback_id = params->GetList()[0].GetString(); + + base::Value state(base::Value::Type::DICTIONARY); + state.SetBoolKey("showOldPasswordPrompt", scraped_old_password_.empty()); + state.SetBoolKey("showNewPasswordPrompt", scraped_new_password_.empty()); + state.SetBoolKey("showSpinner", show_spinner_initially_); + + AllowJavascript(); + ResolveJavascriptCallback(base::Value(callback_id), state); } void ConfirmPasswordChangeHandler::HandleChangePassword( const base::ListValue* params) { - const std::string old_password = params->GetList()[0].GetString(); - const std::string new_password = params->GetList()[1].GetString(); - InSessionPasswordChangeManager::Get()->ChangePassword(old_password, - new_password); + const std::string old_password = + FirstNonEmpty(params->GetList()[0].GetString(), scraped_old_password_); + const std::string new_password = + FirstNonEmpty(params->GetList()[1].GetString(), scraped_new_password_); + DCHECK(!old_password.empty() && !new_password.empty()); + + InSessionPasswordChangeManager::Get()->ChangePassword( + old_password, new_password, kPasswordSource); +} + +void ConfirmPasswordChangeHandler::OnEvent( + InSessionPasswordChangeManager::Event event) { + if (event == kIncorrectPasswordEvent) { + // If this event comes before getInitialState, then don't show the spinner + // initially after all - the initial password change attempt using scraped + // passwords already failed before the dialog finished loading. + show_spinner_initially_ = false; + // Discard the scraped old password and ask the user what it really is. + scraped_old_password_.clear(); + if (IsJavascriptAllowed()) { + FireWebUIListener("incorrect-old-password"); + } + } } void ConfirmPasswordChangeHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( + "getInitialState", + base::BindRepeating(&ConfirmPasswordChangeHandler::HandleGetInitialState, + weak_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( "changePassword", base::BindRepeating(&ConfirmPasswordChangeHandler::HandleChangePassword, weak_factory_.GetWeakPtr())); diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h index 7a69e7c624e..f3104499174 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h @@ -16,9 +16,14 @@ class ConfirmPasswordChangeHandler : public content::WebUIMessageHandler, public InSessionPasswordChangeManager::Observer { public: - ConfirmPasswordChangeHandler(); + ConfirmPasswordChangeHandler(const std::string& scraped_old_password, + const std::string& scraped_new_password, + const bool show_spinner_initially); ~ConfirmPasswordChangeHandler() override; + // Called by the JS UI to find out what to show and what size to be. + void HandleGetInitialState(const base::ListValue* params); + // Tries to change the cryptohome password once the confirm-password-change // dialog is filled in and the password change is confirmed. void HandleChangePassword(const base::ListValue* passwords); @@ -30,6 +35,10 @@ class ConfirmPasswordChangeHandler void RegisterMessages() override; private: + std::string scraped_old_password_; + std::string scraped_new_password_; + bool show_spinner_initially_ = false; + base::WeakPtrFactory<ConfirmPasswordChangeHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.cc b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.cc new file mode 100644 index 00000000000..bba646a609d --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.cc @@ -0,0 +1,201 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.h" + +#include <memory> + +#include "base/bind.h" +#include "base/json/json_writer.h" +#include "chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "chrome/grit/generated_resources.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/web_ui_data_source.h" +#include "ui/display/display.h" +#include "ui/display/screen.h" +#include "ui/strings/grit/ui_strings.h" + +namespace chromeos { + +namespace { + +PasswordChangeDialog* g_dialog = nullptr; + +ConfirmPasswordChangeDialog* g_confirm_dialog = nullptr; + +UrgentPasswordExpiryNotificationDialog* g_notification_dialog = nullptr; + +constexpr gfx::Size kPasswordChangeSize(768, 640); + +constexpr gfx::Size kUrgentPasswordExpiryNotificationSize = kPasswordChangeSize; + +// The size of the confirm password change UI depends on which passwords were +// scraped and which ones we need to prompt for: +constexpr int kConfirmPasswordsWidth = 520; +constexpr int kConfirmOldPasswordHeight = 230; +constexpr int kConfirmNewPasswordHeight = 310; +constexpr int kConfirmBothPasswordsHeight = 380; + +// Given a desired size, returns the same size if it fits on screen, +// or the closest possible size that will fit on the screen. +gfx::Size FitSizeToDisplay(const gfx::Size& desired) { + const display::Display display = + display::Screen::GetScreen()->GetPrimaryDisplay(); + + gfx::Size display_size = display.size(); + + if (display.rotation() == display::Display::ROTATE_90 || + display.rotation() == display::Display::ROTATE_270) { + display_size = gfx::Size(display_size.height(), display_size.width()); + } + + return gfx::Size(std::min(desired.width(), display_size.width()), + std::min(desired.height(), display_size.height())); +} + +} // namespace + +BasePasswordDialog::BasePasswordDialog(GURL url, gfx::Size desired_size) + : SystemWebDialogDelegate(url, /*title=*/base::string16()), + desired_size_(desired_size) {} + +BasePasswordDialog::~BasePasswordDialog() {} + +void BasePasswordDialog::GetDialogSize(gfx::Size* size) const { + *size = FitSizeToDisplay(desired_size_); +} + +void BasePasswordDialog::AdjustWidgetInitParams( + views::Widget::InitParams* params) { + params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; +} + +ui::ModalType BasePasswordDialog::GetDialogModalType() const { + return ui::ModalType::MODAL_TYPE_SYSTEM; +} + +// static +void PasswordChangeDialog::Show() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_dialog) { + g_dialog->Focus(); + return; + } + g_dialog = new PasswordChangeDialog(); + g_dialog->ShowSystemDialog(); +} + +// static +void PasswordChangeDialog::Dismiss() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_dialog) + g_dialog->Close(); +} + +PasswordChangeDialog::PasswordChangeDialog() + : BasePasswordDialog(GURL(chrome::kChromeUIPasswordChangeUrl), + kPasswordChangeSize) {} + +PasswordChangeDialog::~PasswordChangeDialog() { + DCHECK_EQ(this, g_dialog); + g_dialog = nullptr; +} + +// static +void ConfirmPasswordChangeDialog::Show(const std::string& scraped_old_password, + const std::string& scraped_new_password, + bool show_spinner_initially) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_confirm_dialog) { + g_confirm_dialog->Focus(); + return; + } + g_confirm_dialog = new ConfirmPasswordChangeDialog( + scraped_old_password, scraped_new_password, show_spinner_initially); + g_confirm_dialog->ShowSystemDialog(); +} + +// static +void ConfirmPasswordChangeDialog::Dismiss() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_confirm_dialog) + g_confirm_dialog->Close(); +} + +ConfirmPasswordChangeDialog::ConfirmPasswordChangeDialog( + const std::string& scraped_old_password, + const std::string& scraped_new_password, + bool show_spinner_initially) + : BasePasswordDialog( + GURL(chrome::kChromeUIConfirmPasswordChangeUrl), + GetSize(scraped_old_password.empty(), scraped_new_password.empty())), + scraped_old_password_(scraped_old_password), + scraped_new_password_(scraped_new_password), + show_spinner_initially_(show_spinner_initially) {} + +ConfirmPasswordChangeDialog::~ConfirmPasswordChangeDialog() { + DCHECK_EQ(this, g_confirm_dialog); + g_confirm_dialog = nullptr; +} + +// static +gfx::Size ConfirmPasswordChangeDialog::GetSize( + const bool show_old_password_prompt, + const bool show_new_password_prompt) { + const int desired_width = kConfirmPasswordsWidth; + if (show_old_password_prompt && show_new_password_prompt) { + return gfx::Size(desired_width, kConfirmBothPasswordsHeight); + } + if (show_new_password_prompt) { + return gfx::Size(desired_width, kConfirmNewPasswordHeight); + } + // Use the same size for these two cases: + // 1) We scraped new password, but not old, so we need to prompt for that. + // 2) We scraped both passwords, so we don't need to prompt for anything. + + // In case 2, we need to show a spinner. That spinner could be any size, so + // we size it the same as in case 1, because there is a chance that the + // scraped password will be wrong and so we will need to show the old password + // prompt. So it looks best if the dialog is already the right size. + return gfx::Size(desired_width, kConfirmOldPasswordHeight); +} + +void ConfirmPasswordChangeDialog::GetWebUIMessageHandlers( + std::vector<content::WebUIMessageHandler*>* handlers) const { + handlers->push_back(new ConfirmPasswordChangeHandler( + scraped_old_password_, scraped_new_password_, show_spinner_initially_)); +} + +// static +void UrgentPasswordExpiryNotificationDialog::Show() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_notification_dialog) { + g_notification_dialog->Focus(); + return; + } + g_notification_dialog = new UrgentPasswordExpiryNotificationDialog(); + g_notification_dialog->ShowSystemDialog(); +} + +// static +void UrgentPasswordExpiryNotificationDialog::Dismiss() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_notification_dialog) + g_notification_dialog->Close(); +} + +UrgentPasswordExpiryNotificationDialog::UrgentPasswordExpiryNotificationDialog() + : BasePasswordDialog( + GURL(chrome::kChromeUIUrgentPasswordExpiryNotificationUrl), + kUrgentPasswordExpiryNotificationSize) {} + +UrgentPasswordExpiryNotificationDialog:: + ~UrgentPasswordExpiryNotificationDialog() { + DCHECK_EQ(this, g_notification_dialog); + g_notification_dialog = nullptr; +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.h b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.h new file mode 100644 index 00000000000..d8c2b144e2c --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.h @@ -0,0 +1,92 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_DIALOGS_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_DIALOGS_H_ + +#include "base/macros.h" +#include "base/strings/string16.h" +#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" +#include "ui/web_dialogs/web_dialog_ui.h" + +namespace chromeos { + +// A modal system dialog without any frame decorating it. +class BasePasswordDialog : public SystemWebDialogDelegate { + protected: + BasePasswordDialog(GURL url, gfx::Size desired_size); + ~BasePasswordDialog() override; + + // ui::WebDialogDelegate: + void GetDialogSize(gfx::Size* size) const override; + void AdjustWidgetInitParams(views::Widget::InitParams* params) override; + ui::ModalType GetDialogModalType() const override; + + private: + gfx::Size desired_size_; + + DISALLOW_COPY_AND_ASSIGN(BasePasswordDialog); +}; + +// System dialog wrapping chrome:://password-change +class PasswordChangeDialog : public BasePasswordDialog { + public: + static void Show(); + static void Dismiss(); + + protected: + PasswordChangeDialog(); + ~PasswordChangeDialog() override; + + private: + DISALLOW_COPY_AND_ASSIGN(PasswordChangeDialog); +}; + +// System dialog wrapping chrome://confirm-password-change +class ConfirmPasswordChangeDialog : public BasePasswordDialog { + public: + static void Show(const std::string& scraped_old_password, + const std::string& scraped_new_password, + bool show_spinner_initially); + static void Dismiss(); + + // How big does this dialog need to be to show these prompts: + static gfx::Size GetSize(bool show_old_password_prompt, + bool show_new_password_prompt); + + protected: + ConfirmPasswordChangeDialog(const std::string& scraped_old_password, + const std::string& scraped_new_password, + bool show_spinner_initially); + ~ConfirmPasswordChangeDialog() override; + + // ui::WebDialogDelegate: + void GetWebUIMessageHandlers( + std::vector<content::WebUIMessageHandler*>* handlers) const override; + + private: + std::string scraped_old_password_; + std::string scraped_new_password_; + bool show_spinner_initially_ = false; + + DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeDialog); +}; + +// System dialog wrapping chrome://urgent-password-expiry-notification +class UrgentPasswordExpiryNotificationDialog : public BasePasswordDialog { + public: + static void Show(); + static void Dismiss(); + + protected: + UrgentPasswordExpiryNotificationDialog(); + ~UrgentPasswordExpiryNotificationDialog() override; + + private: + DISALLOW_COPY_AND_ASSIGN(UrgentPasswordExpiryNotificationDialog); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_DIALOGS_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc index 8b85995d13c..04a7c285025 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc @@ -13,7 +13,7 @@ #include "chrome/browser/chromeos/login/saml/password_expiry_notification.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h" +#include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.h" #include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.h" #include "chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.h" #include "chrome/browser/ui/webui/localized_string.h" @@ -38,12 +38,6 @@ namespace chromeos { namespace { -PasswordChangeDialog* g_dialog = nullptr; - -ConfirmPasswordChangeDialog* g_confirm_dialog = nullptr; - -UrgentPasswordExpiryNotificationDialog* g_notification_dialog = nullptr; - std::string GetPasswordChangeUrl(Profile* profile) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSamlPasswordChangeUrl)) { @@ -73,79 +67,15 @@ base::string16 GetHostedHeaderText(const std::string& password_change_url) { host); } -constexpr int kMaxPasswordChangeDialogWidth = 768; -constexpr int kMaxPasswordChangeDialogHeight = 640; - -// TODO(https://crbug.com/930109): Change these numbers depending on what is -// shown in the dialog. -constexpr int kMaxConfirmPasswordChangeDialogWidth = 520; -constexpr int kMaxConfirmPasswordChangeDialogHeight = 380; - -constexpr int kMaxNotificationDialogWidth = 768; -constexpr int kMaxNotificationDialogHeight = 640; - -// Given a desired width and height, returns the same size if it fits on screen, -// or the closest possible size that will fit on the screen. -gfx::Size FitSizeToDisplay(int max_width, int max_height) { - const display::Display display = - display::Screen::GetScreen()->GetPrimaryDisplay(); - - gfx::Size display_size = display.size(); - - if (display.rotation() == display::Display::ROTATE_90 || - display.rotation() == display::Display::ROTATE_270) { - display_size = gfx::Size(display_size.height(), display_size.width()); - } - - display_size = gfx::Size(std::min(display_size.width(), max_width), - std::min(display_size.height(), max_height)); - - return display_size; +void AddSize(content::WebUIDataSource* source, + const std::string& suffix, + const gfx::Size& size) { + source->AddInteger("width" + suffix, size.width()); + source->AddInteger("height" + suffix, size.height()); } } // namespace -PasswordChangeDialog::PasswordChangeDialog() - : SystemWebDialogDelegate(GURL(chrome::kChromeUIPasswordChangeUrl), - /*title=*/base::string16()) {} - -PasswordChangeDialog::~PasswordChangeDialog() { - DCHECK_EQ(this, g_dialog); - g_dialog = nullptr; -} - -void PasswordChangeDialog::GetDialogSize(gfx::Size* size) const { - *size = FitSizeToDisplay(kMaxPasswordChangeDialogWidth, - kMaxPasswordChangeDialogHeight); -} - -void PasswordChangeDialog::AdjustWidgetInitParams( - views::Widget::InitParams* params) { - params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; -} - -ui::ModalType PasswordChangeDialog::GetDialogModalType() const { - return ui::ModalType::MODAL_TYPE_SYSTEM; -} - -// static -void PasswordChangeDialog::Show() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_dialog) { - g_dialog->Focus(); - return; - } - g_dialog = new PasswordChangeDialog(); - g_dialog->ShowSystemDialog(); -} - -// static -void PasswordChangeDialog::Dismiss() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_dialog) - g_dialog->Close(); -} - PasswordChangeUI::PasswordChangeUI(content::WebUI* web_ui) : ui::WebDialogUI(web_ui) { Profile* profile = Profile::FromWebUI(web_ui); @@ -159,7 +89,7 @@ PasswordChangeUI::PasswordChangeUI(content::WebUI* web_ui) std::make_unique<PasswordChangeHandler>(password_change_url)); source->AddString("hostedHeader", GetHostedHeaderText(password_change_url)); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_PASSWORD_CHANGE_HTML); @@ -173,66 +103,6 @@ PasswordChangeUI::PasswordChangeUI(content::WebUI* web_ui) PasswordChangeUI::~PasswordChangeUI() = default; -// static -void ConfirmPasswordChangeDialog::Show(const std::string& scraped_old_password, - const std::string& scraped_new_password, - bool show_spinner_initially) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_confirm_dialog) { - g_confirm_dialog->Focus(); - return; - } - g_confirm_dialog = new ConfirmPasswordChangeDialog( - scraped_old_password, scraped_new_password, show_spinner_initially); - g_confirm_dialog->ShowSystemDialog(); -} - -// static -void ConfirmPasswordChangeDialog::Dismiss() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_confirm_dialog) - g_confirm_dialog->Close(); -} - -ConfirmPasswordChangeDialog::ConfirmPasswordChangeDialog( - const std::string& scraped_old_password, - const std::string& scraped_new_password, - bool show_spinner_initially) - : SystemWebDialogDelegate(GURL(chrome::kChromeUIConfirmPasswordChangeUrl), - /*title=*/base::string16()), - scraped_old_password_(scraped_old_password), - scraped_new_password_(scraped_new_password), - show_spinner_initially_(show_spinner_initially) {} - -ConfirmPasswordChangeDialog::~ConfirmPasswordChangeDialog() { - DCHECK_EQ(this, g_confirm_dialog); - g_confirm_dialog = nullptr; -} - -void ConfirmPasswordChangeDialog::GetDialogSize(gfx::Size* size) const { - *size = FitSizeToDisplay(kMaxConfirmPasswordChangeDialogWidth, - kMaxConfirmPasswordChangeDialogHeight); -} - -std::string ConfirmPasswordChangeDialog::GetDialogArgs() const { - // TODO(https://crbug.com/930109): Configure the embedded UI to only display - // prompts for the passwords that were not scraped. - std::string data; - base::DictionaryValue dialog_args; - dialog_args.SetBoolean("showSpinnerInitially", show_spinner_initially_); - base::JSONWriter::Write(dialog_args, &data); - return data; -} - -void ConfirmPasswordChangeDialog::AdjustWidgetInitParams( - views::Widget::InitParams* params) { - params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; -} - -ui::ModalType ConfirmPasswordChangeDialog::GetDialogModalType() const { - return ui::ModalType::MODAL_TYPE_SYSTEM; -} - ConfirmPasswordChangeUI::ConfirmPasswordChangeUI(content::WebUI* web_ui) : ui::WebDialogUI(web_ui) { Profile* profile = Profile::FromWebUI(web_ui); @@ -252,69 +122,31 @@ ConfirmPasswordChangeUI::ConfirmPasswordChangeUI(content::WebUI* web_ui) {"oldPassword", IDS_PASSWORD_CHANGE_OLD_PASSWORD_LABEL}, {"newPassword", IDS_PASSWORD_CHANGE_NEW_PASSWORD_LABEL}, {"confirmNewPassword", IDS_PASSWORD_CHANGE_CONFIRM_NEW_PASSWORD_LABEL}, + {"incorrectPassword", IDS_LOGIN_CONFIRM_PASSWORD_INCORRECT_PASSWORD}, {"matchError", IDS_PASSWORD_CHANGE_PASSWORDS_DONT_MATCH}, {"save", IDS_PASSWORD_CHANGE_CONFIRM_SAVE_BUTTON}}; AddLocalizedStringsBulk(source, kLocalizedStrings, base::size(kLocalizedStrings)); - source->SetJsonPath("strings.js"); + AddSize(source, "", ConfirmPasswordChangeDialog::GetSize(false, false)); + AddSize(source, "Old", ConfirmPasswordChangeDialog::GetSize(true, false)); + AddSize(source, "New", ConfirmPasswordChangeDialog::GetSize(false, true)); + AddSize(source, "OldNew", ConfirmPasswordChangeDialog::GetSize(true, true)); + + source->UseStringsJs(); source->SetDefaultResource(IDR_CONFIRM_PASSWORD_CHANGE_HTML); source->AddResourcePath("confirm_password_change.js", IDR_CONFIRM_PASSWORD_CHANGE_JS); - web_ui->AddMessageHandler(std::make_unique<ConfirmPasswordChangeHandler>()); + // The ConfirmPasswordChangeHandler is added by the dialog, so no need to add + // it here. content::WebUIDataSource::Add(profile, source); } ConfirmPasswordChangeUI::~ConfirmPasswordChangeUI() = default; -UrgentPasswordExpiryNotificationDialog::UrgentPasswordExpiryNotificationDialog() - : SystemWebDialogDelegate( - GURL(chrome::kChromeUIUrgentPasswordExpiryNotificationUrl), - /*title=*/base::string16()) {} - -UrgentPasswordExpiryNotificationDialog:: - ~UrgentPasswordExpiryNotificationDialog() { - DCHECK_EQ(this, g_notification_dialog); - g_notification_dialog = nullptr; -} - -void UrgentPasswordExpiryNotificationDialog::GetDialogSize( - gfx::Size* size) const { - *size = FitSizeToDisplay(kMaxNotificationDialogWidth, - kMaxNotificationDialogHeight); -} - -void UrgentPasswordExpiryNotificationDialog::AdjustWidgetInitParams( - views::Widget::InitParams* params) { - params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; -} - -ui::ModalType UrgentPasswordExpiryNotificationDialog::GetDialogModalType() - const { - return ui::ModalType::MODAL_TYPE_SYSTEM; -} - -// static -void UrgentPasswordExpiryNotificationDialog::Show() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_notification_dialog) { - g_notification_dialog->Focus(); - return; - } - g_notification_dialog = new UrgentPasswordExpiryNotificationDialog(); - g_notification_dialog->ShowSystemDialog(); -} - -// static -void UrgentPasswordExpiryNotificationDialog::Dismiss() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_notification_dialog) - g_notification_dialog->Close(); -} - UrgentPasswordExpiryNotificationUI::UrgentPasswordExpiryNotificationUI( content::WebUI* web_ui) : ui::WebDialogUI(web_ui) { @@ -340,7 +172,7 @@ UrgentPasswordExpiryNotificationUI::UrgentPasswordExpiryNotificationUI( AddLocalizedStringsBulk(source, kLocalizedStrings, base::size(kLocalizedStrings)); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_URGENT_PASSWORD_EXPIRY_NOTIFICATION_HTML); source->AddResourcePath("urgent_password_expiry_notification.js", IDR_URGENT_PASSWORD_EXPIRY_NOTIFICATION_JS); diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h index d1b2cb7e877..b8d19af17e1 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h @@ -12,25 +12,6 @@ namespace chromeos { -// System dialog wrapping chrome:://password-change -class PasswordChangeDialog : public SystemWebDialogDelegate { - public: - static void Show(); - static void Dismiss(); - - protected: - PasswordChangeDialog(); - ~PasswordChangeDialog() override; - - // ui::WebDialogDelegate: - void GetDialogSize(gfx::Size* size) const override; - void AdjustWidgetInitParams(views::Widget::InitParams* params) override; - ui::ModalType GetDialogModalType() const override; - - private: - DISALLOW_COPY_AND_ASSIGN(PasswordChangeDialog); -}; - // For chrome:://password-change class PasswordChangeUI : public ui::WebDialogUI { public: @@ -41,34 +22,6 @@ class PasswordChangeUI : public ui::WebDialogUI { DISALLOW_COPY_AND_ASSIGN(PasswordChangeUI); }; -// System dialog wrapping chrome://confirm-password-change -class ConfirmPasswordChangeDialog : public SystemWebDialogDelegate { - public: - static void Show(const std::string& scraped_old_password, - const std::string& scraped_new_password, - bool show_spinner_initially); - static void Dismiss(); - - protected: - ConfirmPasswordChangeDialog(const std::string& scraped_old_password, - const std::string& scraped_new_password, - bool show_spinner_initially); - ~ConfirmPasswordChangeDialog() override; - - // ui::WebDialogDelegate: - void GetDialogSize(gfx::Size* size) const override; - std::string GetDialogArgs() const override; - void AdjustWidgetInitParams(views::Widget::InitParams* params) override; - ui::ModalType GetDialogModalType() const override; - - private: - std::string scraped_old_password_; - std::string scraped_new_password_; - bool show_spinner_initially_ = false; - - DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeDialog); -}; - // For chrome:://confirm-password-change class ConfirmPasswordChangeUI : public ui::WebDialogUI { public: @@ -79,25 +32,6 @@ class ConfirmPasswordChangeUI : public ui::WebDialogUI { DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeUI); }; -// System dialog wrapping chrome://urgent-password-expiry-notification -class UrgentPasswordExpiryNotificationDialog : public SystemWebDialogDelegate { - public: - static void Show(); - static void Dismiss(); - - protected: - UrgentPasswordExpiryNotificationDialog(); - ~UrgentPasswordExpiryNotificationDialog() override; - - // ui::WebDialogDelegate: - void GetDialogSize(gfx::Size* size) const override; - void AdjustWidgetInitParams(views::Widget::InitParams* params) override; - ui::ModalType GetDialogModalType() const override; - - private: - DISALLOW_COPY_AND_ASSIGN(UrgentPasswordExpiryNotificationDialog); -}; - // For chrome:://urgent-password-expiry-notification class UrgentPasswordExpiryNotificationUI : public ui::WebDialogUI { public: diff --git a/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc index 24c46c4c6c8..4d8cca34874 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc @@ -142,7 +142,7 @@ InternetConfigDialogUI::InternetConfigDialogUI(content::WebUI* web_ui) AddInternetStrings(source); source->AddLocalizedString("title", IDS_SETTINGS_INTERNET_CONFIG); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); #if BUILDFLAG(OPTIMIZE_WEBUI) source->SetDefaultResource(IDR_INTERNET_CONFIG_DIALOG_VULCANIZED_HTML); source->AddResourcePath("crisper.js", IDR_INTERNET_CONFIG_DIALOG_CRISPER_JS); 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 b1faef7f2de..2489cb2e124 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/chromeos/internet_detail_dialog.h" #include "ash/public/cpp/ash_features.h" +#include "ash/public/cpp/network_config_service.h" #include "base/json/json_writer.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" @@ -16,11 +17,9 @@ #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/network_util.h" -#include "chromeos/services/network_config/public/mojom/constants.mojom.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 "services/service_manager/public/cpp/connector.h" #include "ui/base/l10n/l10n_util.h" namespace chromeos { @@ -142,7 +141,7 @@ InternetDetailDialogUI::InternetDetailDialogUI(content::WebUI* web_ui) !ash::features::IsSeparateNetworkIconsEnabled()); AddInternetStrings(source); source->AddLocalizedString("title", IDS_SETTINGS_INTERNET_DETAIL); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); #if BUILDFLAG(OPTIMIZE_WEBUI) source->SetDefaultResource(IDR_INTERNET_DETAIL_DIALOG_VULCANIZED_HTML); source->AddResourcePath("crisper.js", IDR_INTERNET_DETAIL_DIALOG_CRISPER_JS); @@ -162,10 +161,7 @@ InternetDetailDialogUI::~InternetDetailDialogUI() {} void InternetDetailDialogUI::BindCrosNetworkConfig( chromeos::network_config::mojom::CrosNetworkConfigRequest request) { - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()) - ->BindInterface(chromeos::network_config::mojom::kServiceName, - std::move(request)); + ash::GetNetworkConfigService(std::move(request)); } } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc index a31ce2c2566..f2882ee9ec6 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc @@ -42,9 +42,7 @@ ActiveDirectoryPasswordChangeScreenHandler:: : BaseScreenHandler(OobeScreen::SCREEN_ACTIVE_DIRECTORY_PASSWORD_CHANGE, js_calls_container), authpolicy_login_helper_(std::make_unique<AuthPolicyHelper>()), - core_oobe_view_(core_oobe_view), - weak_factory_(this) { -} + core_oobe_view_(core_oobe_view) {} ActiveDirectoryPasswordChangeScreenHandler:: ~ActiveDirectoryPasswordChangeScreenHandler() {} diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h index 74b41552268..8768175e503 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h @@ -65,7 +65,7 @@ class ActiveDirectoryPasswordChangeScreenHandler : public BaseScreenHandler { CoreOobeView* core_oobe_view_ = nullptr; base::WeakPtrFactory<ActiveDirectoryPasswordChangeScreenHandler> - weak_factory_; + weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ActiveDirectoryPasswordChangeScreenHandler); }; 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 29601c934c8..e6b65a80a77 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 @@ -294,8 +294,8 @@ void ArcTermsOfServiceScreenHandler::DoShow() { MaybeLoadPlayStoreToS(true); StartNetworkAndTimeZoneObserving(); - pref_handler_.reset(new arc::ArcOptInPreferenceHandler( - this, profile->GetPrefs())); + pref_handler_ = std::make_unique<arc::ArcOptInPreferenceHandler>( + this, profile->GetPrefs()); pref_handler_->Start(); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc index 622537cfdff..f53cede13a4 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc @@ -15,17 +15,16 @@ #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/ash/assistant/assistant_service_connection.h" #include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h" #include "chrome/grit/generated_resources.h" #include "chromeos/services/assistant/public/cpp/assistant_prefs.h" #include "chromeos/services/assistant/public/features.h" -#include "chromeos/services/assistant/public/mojom/constants.mojom.h" #include "chromeos/services/assistant/public/proto/settings_ui.pb.h" -#include "components/arc/arc_prefs.h" #include "components/login/localized_values_builder.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user_manager.h" -#include "services/service_manager/public/cpp/connector.h" +#include "ui/chromeos/devicetype_utils.h" namespace chromeos { @@ -50,13 +49,13 @@ constexpr StaticOobeScreenId AssistantOptInFlowScreenView::kScreenId; AssistantOptInFlowScreenHandler::AssistantOptInFlowScreenHandler( JSCallsContainer* js_calls_container) - : BaseScreenHandler(kScreenId, js_calls_container), - client_binding_(this), - weak_factory_(this) { + : BaseScreenHandler(kScreenId, js_calls_container), client_binding_(this) { set_user_acted_method_path("login.AssistantOptInFlowScreen.userActed"); } AssistantOptInFlowScreenHandler::~AssistantOptInFlowScreenHandler() { + if (client_binding_) + StopSpeakerIdEnrollment(); if (arc::VoiceInteractionControllerClient::Get()) { arc::VoiceInteractionControllerClient::Get()->RemoveObserver(this); } @@ -113,10 +112,13 @@ void AssistantOptInFlowScreenHandler::DeclareLocalizedValues( builder->Add("assistantOptinSaveButton", IDS_ASSISTANT_SAVE_BUTTON); builder->Add("assistantOptinWaitMessage", IDS_ASSISTANT_WAIT_MESSAGE); builder->Add("assistantReadyTitle", IDS_ASSISTANT_READY_SCREEN_TITLE); - builder->Add("assistantReadyMessage", IDS_ASSISTANT_READY_SCREEN_MESSAGE); + builder->AddF("assistantReadyMessage", IDS_ASSISTANT_READY_SCREEN_MESSAGE, + ui::GetChromeOSDeviceName()); builder->Add("assistantReadyButton", IDS_ASSISTANT_DONE_BUTTON); builder->Add("back", IDS_EULA_BACK_BUTTON); builder->Add("next", IDS_EULA_NEXT_BUTTON); + builder->Add("assistantOobePopupOverlayLoading", + IDS_ASSISTANT_OOBE_POPUP_OVERLAY_LOADING); } void AssistantOptInFlowScreenHandler::RegisterMessages() { @@ -214,7 +216,7 @@ void AssistantOptInFlowScreenHandler::SetupAssistantConnection() { } // Make sure enable Assistant service since we need it during the flow. - prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, true); + prefs->SetBoolean(chromeos::assistant::prefs::kAssistantEnabled, true); if (arc::VoiceInteractionControllerClient::Get()->voice_interaction_state() == ash::mojom::VoiceInteractionState::NOT_READY) { @@ -266,7 +268,7 @@ void AssistantOptInFlowScreenHandler::OnDialogClosed() { if (!voice_match_enrollment_done_ && flow_type_ == ash::FlowType::kSpeakerIdEnrollment) { ProfileManager::GetActiveUserProfile()->GetPrefs()->SetBoolean( - arc::prefs::kVoiceInteractionHotwordEnabled, false); + assistant::prefs::kAssistantHotwordEnabled, false); } } @@ -283,11 +285,10 @@ void AssistantOptInFlowScreenHandler::BindAssistantSettingsManager() { return; // Set up settings mojom. - service_manager::Connector* connector = - content::BrowserContext::GetConnectorFor( - ProfileManager::GetActiveUserProfile()); - connector->BindInterface(assistant::mojom::kServiceName, - mojo::MakeRequest(&settings_manager_)); + AssistantServiceConnection::GetForProfile( + ProfileManager::GetActiveUserProfile()) + ->service() + ->BindSettingsManager(mojo::MakeRequest(&settings_manager_)); if (initialized_) { SendGetSettingsRequest(); @@ -339,7 +340,7 @@ void AssistantOptInFlowScreenHandler::OnGetSettingsResponse( "opt-in flow."; PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); prefs->SetBoolean(assistant::prefs::kAssistantDisabledByPolicy, true); - prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, false); + prefs->SetBoolean(chromeos::assistant::prefs::kAssistantEnabled, false); HandleFlowFinished(); return; } @@ -508,13 +509,13 @@ void AssistantOptInFlowScreenHandler::HandleVoiceMatchScreenUserAction( RecordAssistantOptInStatus(VOICE_MATCH_ENROLLMENT_SKIPPED); if (flow_type_ != ash::FlowType::kSpeakerIdRetrain) { // No need to disable hotword for retrain flow since user has a model. - prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, false); + prefs->SetBoolean(assistant::prefs::kAssistantHotwordEnabled, false); } StopSpeakerIdEnrollment(); ShowNextScreen(); } else if (action == kRecordPressed) { - if (!prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled)) { - prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, true); + if (!prefs->GetBoolean(assistant::prefs::kAssistantHotwordEnabled)) { + prefs->SetBoolean(assistant::prefs::kAssistantHotwordEnabled, true); } assistant::mojom::SpeakerIdEnrollmentClientPtr client_ptr; @@ -529,8 +530,7 @@ void AssistantOptInFlowScreenHandler::HandleGetMoreScreenUserAction( const bool email_opted_in) { RecordAssistantOptInStatus(GET_MORE_CONTINUED); PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); - prefs->SetBoolean(arc::prefs::kVoiceInteractionContextEnabled, - screen_context); + prefs->SetBoolean(assistant::prefs::kAssistantContextEnabled, screen_context); OnEmailOptInResult(email_opted_in); } @@ -576,7 +576,7 @@ void AssistantOptInFlowScreenHandler::HandleFlowFinished() { void AssistantOptInFlowScreenHandler::HandleFlowInitialized( const int flow_type) { auto* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); - if (!prefs->GetBoolean(arc::prefs::kVoiceInteractionEnabled)) { + if (!prefs->GetBoolean(chromeos::assistant::prefs::kAssistantEnabled)) { HandleFlowFinished(); return; } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h index 8a24e879ca3..9810c088aea 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h @@ -163,7 +163,7 @@ class AssistantOptInFlowScreenHandler mojo::Binding<assistant::mojom::SpeakerIdEnrollmentClient> client_binding_; assistant::mojom::AssistantSettingsManagerPtr settings_manager_; - base::WeakPtrFactory<AssistantOptInFlowScreenHandler> weak_factory_; + base::WeakPtrFactory<AssistantOptInFlowScreenHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AssistantOptInFlowScreenHandler); }; 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 5326b0b1233..5474107730b 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 @@ -8,7 +8,8 @@ #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/event_rewriter_controller.h" -#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/cpp/tablet_mode.h" +#include "ash/public/mojom/constants.mojom.h" #include "ash/shell.h" #include "base/bind.h" #include "base/command_line.h" @@ -32,7 +33,6 @@ #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/ui/ash/ash_util.h" #include "chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.h" -#include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" @@ -88,9 +88,7 @@ void LaunchResetScreen() { // Note that show_oobe_ui_ defaults to false because WizardController assumes // OOBE UI is not visible by default. CoreOobeHandler::CoreOobeHandler(JSCallsContainer* js_calls_container) - : BaseWebUIHandler(js_calls_container), - version_info_updater_(this), - weak_ptr_factory_(this) { + : BaseWebUIHandler(js_calls_container), version_info_updater_(this) { DCHECK(js_calls_container); AccessibilityManager* accessibility_manager = AccessibilityManager::Get(); CHECK(accessibility_manager); @@ -98,8 +96,7 @@ CoreOobeHandler::CoreOobeHandler(JSCallsContainer* js_calls_container) base::Bind(&CoreOobeHandler::OnAccessibilityStatusChanged, base::Unretained(this))); - TabletModeClient* tablet_mode_client = TabletModeClient::Get(); - tablet_mode_client->AddObserver(this); + ash::TabletMode::Get()->AddObserver(this); // |connector| may be null in tests. auto* connector = content::GetSystemConnector(); @@ -112,7 +109,10 @@ CoreOobeHandler::CoreOobeHandler(JSCallsContainer* js_calls_container) CoreOobeHandler::~CoreOobeHandler() { OobeConfiguration::Get()->RemoveObserver(this); - TabletModeClient::Get()->RemoveObserver(this); + + // Ash may be released before us. + if (ash::TabletMode::Get()) + ash::TabletMode::Get()->RemoveObserver(this); } void CoreOobeHandler::DeclareLocalizedValues( @@ -178,7 +178,7 @@ void CoreOobeHandler::Initialize() { void CoreOobeHandler::GetAdditionalParameters(base::DictionaryValue* dict) { dict->SetKey("isInTabletMode", - base::Value(TabletModeClient::Get()->tablet_mode_enabled())); + base::Value(ash::TabletMode::Get()->InTabletMode())); dict->SetKey("isDemoModeEnabled", base::Value(DemoSetupController::IsDemoModeAllowed())); dict->SetKey("showTechnologyBadge", @@ -534,8 +534,12 @@ void CoreOobeHandler::UpdateKeyboardState() { SetVirtualKeyboardShown(is_keyboard_shown); } -void CoreOobeHandler::OnTabletModeToggled(bool enabled) { - CallJS("cr.ui.Oobe.setTabletModeState", enabled); +void CoreOobeHandler::OnTabletModeStarted() { + CallJS("cr.ui.Oobe.setTabletModeState", true); +} + +void CoreOobeHandler::OnTabletModeEnded() { + CallJS("cr.ui.Oobe.setTabletModeState", false); } void CoreOobeHandler::UpdateClientAreaSize() { 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 cb7db18c545..8e30d2b5363 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 @@ -9,7 +9,8 @@ #include <string> #include <vector> -#include "ash/public/interfaces/cros_display_config.mojom.h" +#include "ash/public/cpp/tablet_mode_observer.h" +#include "ash/public/mojom/cros_display_config.mojom.h" #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -21,7 +22,6 @@ #include "chrome/browser/chromeos/login/oobe_configuration.h" #include "chrome/browser/chromeos/login/version_info_updater.h" #include "chrome/browser/chromeos/tpm_firmware_update.h" -#include "chrome/browser/ui/ash/tablet_mode_client_observer.h" #include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" #include "ui/events/event_source.h" @@ -72,7 +72,7 @@ class CoreOobeHandler : public BaseWebUIHandler, public VersionInfoUpdater::Delegate, public CoreOobeView, public ui::EventSource, - public TabletModeClientObserver, + public ash::TabletModeObserver, public OobeConfiguration::Observer { public: explicit CoreOobeHandler(JSCallsContainer* js_calls_container); @@ -146,8 +146,9 @@ class CoreOobeHandler : public BaseWebUIHandler, void StopDemoModeDetection() override; void UpdateKeyboardState() override; - // TabletModeClientObserver: - void OnTabletModeToggled(bool enabled) override; + // ash::TabletModeObserver: + void OnTabletModeStarted() override; + void OnTabletModeEnded() override; // OobeConfiguration::Observer: void OnOobeConfigurationChanged() override; @@ -223,7 +224,7 @@ class CoreOobeHandler : public BaseWebUIHandler, ash::mojom::CrosDisplayConfigControllerPtr cros_display_config_ptr_; - base::WeakPtrFactory<CoreOobeHandler> weak_ptr_factory_; + base::WeakPtrFactory<CoreOobeHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CoreOobeHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc b/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc index b43a2040cf9..c6fce1fdcd0 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc @@ -43,16 +43,14 @@ class DiscoverModulePinSetupHandler : public DiscoverHandler { base::WeakPtr<DiscoverModulePinSetup> module_; - base::WeakPtrFactory<DiscoverModulePinSetupHandler> weak_factory_; + base::WeakPtrFactory<DiscoverModulePinSetupHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DiscoverModulePinSetupHandler); }; DiscoverModulePinSetupHandler::DiscoverModulePinSetupHandler( base::WeakPtr<DiscoverModulePinSetup> module, JSCallsContainer* js_calls_container) - : DiscoverHandler(js_calls_container), - module_(module), - weak_factory_(this) {} + : DiscoverHandler(js_calls_container), module_(module) {} void DiscoverModulePinSetupHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc index a8d27784548..35e15951f2a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc @@ -36,9 +36,7 @@ constexpr StaticOobeScreenId EnableDebuggingScreenView::kScreenId; EnableDebuggingScreenHandler::EnableDebuggingScreenHandler( JSCallsContainer* js_calls_container) - : BaseScreenHandler(kScreenId, js_calls_container), - weak_ptr_factory_(this) { -} + : BaseScreenHandler(kScreenId, js_calls_container) {} EnableDebuggingScreenHandler::~EnableDebuggingScreenHandler() { if (screen_) diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.h index aaa881d0bbf..88dfc9a0a19 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.h @@ -97,7 +97,7 @@ class EnableDebuggingScreenHandler : public EnableDebuggingScreenView, // Keeps whether screen should be shown right after initialization. bool show_on_init_ = false; - base::WeakPtrFactory<EnableDebuggingScreenHandler> weak_ptr_factory_; + base::WeakPtrFactory<EnableDebuggingScreenHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(EnableDebuggingScreenHandler); }; 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 ed23aaa3cda..b75aaa8b7cf 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 @@ -40,7 +40,7 @@ #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/system_connector.h" -#include "mojo/public/cpp/bindings/interface_request.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "services/device/public/mojom/constants.mojom.h" #include "services/device/public/mojom/wake_lock_provider.mojom.h" #include "services/service_manager/public/cpp/connector.h" @@ -258,8 +258,7 @@ constexpr StaticOobeScreenId EncryptionMigrationScreenView::kScreenId; EncryptionMigrationScreenHandler::EncryptionMigrationScreenHandler( JSCallsContainer* js_calls_container) : BaseScreenHandler(kScreenId, js_calls_container), - tick_clock_(base::DefaultTickClock::GetInstance()), - weak_ptr_factory_(this) { + tick_clock_(base::DefaultTickClock::GetInstance()) { free_disk_space_fetcher_ = base::Bind(&base::SysInfo::AmountOfFreeDiskSpace, base::FilePath(kCheckStoragePath)); } @@ -482,7 +481,8 @@ void EncryptionMigrationScreenHandler::HandleOpenFeedbackDialog() { "Auto generated feedback for http://crbug.com/719266.\n" "(uniquifier:%s)", base::NumberToString(base::Time::Now().ToInternalValue()).c_str()); - login_feedback_.reset(new LoginFeedback(Profile::FromWebUI(web_ui()))); + login_feedback_ = + std::make_unique<LoginFeedback>(Profile::FromWebUI(web_ui())); login_feedback_->Request(description, base::Closure()); } @@ -520,8 +520,9 @@ void EncryptionMigrationScreenHandler::UpdateUIState(UIState state) { } void EncryptionMigrationScreenHandler::CheckAvailableStorage() { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, free_disk_space_fetcher_, base::Bind(&EncryptionMigrationScreenHandler::OnGetAvailableStorage, weak_ptr_factory_.GetWeakPtr())); @@ -620,7 +621,8 @@ device::mojom::WakeLock* EncryptionMigrationScreenHandler::GetWakeLock() { if (wake_lock_) return wake_lock_.get(); - device::mojom::WakeLockRequest request = mojo::MakeRequest(&wake_lock_); + mojo::PendingReceiver<device::mojom::WakeLock> receiver = + wake_lock_.BindNewPipeAndPassReceiver(); // Service manager connection might be not initialized in some testing // contexts. @@ -629,13 +631,14 @@ device::mojom::WakeLock* EncryptionMigrationScreenHandler::GetWakeLock() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - device::mojom::WakeLockProviderPtr wake_lock_provider; - content::GetSystemConnector()->BindInterface( - device::mojom::kServiceName, mojo::MakeRequest(&wake_lock_provider)); + mojo::Remote<device::mojom::WakeLockProvider> wake_lock_provider; + content::GetSystemConnector()->Connect( + device::mojom::kServiceName, + wake_lock_provider.BindNewPipeAndPassReceiver()); wake_lock_provider->GetWakeLockWithoutContext( device::mojom::WakeLockType::kPreventAppSuspension, device::mojom::WakeLockReason::kOther, - "Encryption migration is in progress...", std::move(request)); + "Encryption migration is in progress...", std::move(receiver)); return wake_lock_.get(); } 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 4661fce4ee1..23dd21fc6bb 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 @@ -18,6 +18,7 @@ #include "chromeos/dbus/cryptohome/rpc.pb.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/login/auth/user_context.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/wake_lock.mojom.h" #include "third_party/cros_system_api/dbus/cryptohome/dbus-constants.h" @@ -201,7 +202,7 @@ class EncryptionMigrationScreenHandler : public EncryptionMigrationScreenView, // Point in time when minimal migration started, as reported by |tick_clock_|. base::TimeTicks minimal_migration_start_; - device::mojom::WakeLockPtr wake_lock_; + mojo::Remote<device::mojom::WakeLock> wake_lock_; std::unique_ptr<LoginFeedback> login_feedback_; @@ -210,7 +211,8 @@ class EncryptionMigrationScreenHandler : public EncryptionMigrationScreenView, FreeDiskSpaceFetcher free_disk_space_fetcher_; - base::WeakPtrFactory<EncryptionMigrationScreenHandler> weak_ptr_factory_; + base::WeakPtrFactory<EncryptionMigrationScreenHandler> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(EncryptionMigrationScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc index 081fdff1bfb..bca31b6289f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc @@ -7,8 +7,8 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" -#include "base/test/scoped_task_environment.h" #include "base/test/simple_test_tick_clock.h" +#include "base/test/task_environment.h" #include "chrome/browser/chromeos/arc/arc_migration_constants.h" #include "chrome/browser/chromeos/login/screens/encryption_migration_mode.h" #include "chrome/browser/chromeos/login/users/mock_user_manager.h" @@ -26,6 +26,7 @@ #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user_names.h" #include "content/public/test/test_web_ui.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -47,7 +48,8 @@ class FakeWakeLock : public device::mojom::WakeLock { // Implement device::mojom::WakeLock: void RequestWakeLock() override { has_wakelock_ = true; } void CancelWakeLock() override { has_wakelock_ = false; } - void AddClient(device::mojom::WakeLockRequest request) override {} + void AddClient( + mojo::PendingReceiver<device::mojom::WakeLock> receiver) override {} void ChangeType(device::mojom::WakeLockType type, ChangeTypeCallback callback) override { NOTIMPLEMENTED(); @@ -167,7 +169,7 @@ class EncryptionMigrationScreenHandlerTest : public testing::Test { protected: // Must be the first member. - base::test::ScopedTaskEnvironment scoped_task_environment_; + base::test::TaskEnvironment task_environment_; std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager_enabler_; FakeCryptohomeClient* fake_cryptohome_client_ = nullptr; // unowned @@ -218,7 +220,7 @@ TEST_F(EncryptionMigrationScreenHandlerTest, MinimalMigration) { EncryptionMigrationMode::START_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); - scoped_task_environment_.RunUntilIdle(); + task_environment_.RunUntilIdle(); EXPECT_TRUE( encryption_migration_screen_handler_->fake_wake_lock()->HasWakeLock()); @@ -247,7 +249,7 @@ TEST_F(EncryptionMigrationScreenHandlerTest, ResumeMinimalMigration) { EncryptionMigrationMode::RESUME_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); - scoped_task_environment_.RunUntilIdle(); + task_environment_.RunUntilIdle(); fake_cryptohome_client_->NotifyDircryptoMigrationProgress( cryptohome::DircryptoMigrationStatus::DIRCRYPTO_MIGRATION_SUCCESS, @@ -272,7 +274,7 @@ TEST_F(EncryptionMigrationScreenHandlerTest, MinimalMigrationSlow) { EncryptionMigrationMode::START_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); - scoped_task_environment_.RunUntilIdle(); + task_environment_.RunUntilIdle(); encryption_migration_screen_handler_->testing_tick_clock()->Advance( base::TimeDelta::FromMinutes(1)); @@ -297,7 +299,7 @@ TEST_F(EncryptionMigrationScreenHandlerTest, MinimalMigrationFails) { EncryptionMigrationMode::START_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); - scoped_task_environment_.RunUntilIdle(); + task_environment_.RunUntilIdle(); encryption_migration_screen_handler_->testing_tick_clock()->Advance( base::TimeDelta::FromMinutes(1)); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc index 5c9688e360d..d0fa17ef808 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc @@ -182,8 +182,7 @@ EnrollmentScreenHandler::EnrollmentScreenHandler( : BaseScreenHandler(kScreenId, js_calls_container), network_state_informer_(network_state_informer), error_screen_(error_screen), - histogram_helper_(new ErrorScreensHistogramHelper("Enrollment")), - weak_ptr_factory_(this) { + histogram_helper_(new ErrorScreensHistogramHelper("Enrollment")) { DCHECK(network_state_informer_.get()); DCHECK(error_screen_); network_state_informer_->AddObserver(this); @@ -800,12 +799,12 @@ void EnrollmentScreenHandler::HandleCompleteLogin(const std::string& user) { void EnrollmentScreenHandler::OnGetCookiesForCompleteLogin( const std::string& user, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies) { std::string auth_code; - for (const auto& cookie : cookies) { - if (cookie.Name() == "oauth_code") { - auth_code = cookie.Value(); + for (const auto& cookie_with_status : cookies) { + if (cookie_with_status.cookie.Name() == "oauth_code") { + auth_code = cookie_with_status.cookie.Value(); break; } } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h index 0d4ff94c225..2580ce653f0 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h @@ -17,10 +17,7 @@ #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h" #include "net/base/net_errors.h" - -namespace net { -class CanonicalCookie; -} +#include "net/cookies/canonical_cookie.h" namespace chromeos { @@ -107,7 +104,7 @@ class EnrollmentScreenHandler void HandleCompleteLogin(const std::string& user); void OnGetCookiesForCompleteLogin( const std::string& user, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies); void HandleAdCompleteLogin(const std::string& machine_name, const std::string& distinguished_name, @@ -191,8 +188,7 @@ class EnrollmentScreenHandler // Help application used for help dialogs. scoped_refptr<HelpAppLauncher> help_app_; - - base::WeakPtrFactory<EnrollmentScreenHandler> weak_ptr_factory_; + base::WeakPtrFactory<EnrollmentScreenHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(EnrollmentScreenHandler); }; 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 e0638ca7a4a..b61b4f7bb1f 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 @@ -32,8 +32,7 @@ constexpr StaticOobeScreenId EulaView::kScreenId; EulaScreenHandler::EulaScreenHandler(JSCallsContainer* js_calls_container, CoreOobeView* core_oobe_view) : BaseScreenHandler(kScreenId, js_calls_container), - core_oobe_view_(core_oobe_view), - weak_factory_(this) { + core_oobe_view_(core_oobe_view) { set_user_acted_method_path("login.EulaScreen.userActed"); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h index 395a459a27a..c6ace1d9492 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h @@ -79,7 +79,7 @@ class EulaScreenHandler : public EulaView, public BaseScreenHandler { // Keeps whether screen should be shown right after initialization. bool show_on_init_ = false; - base::WeakPtrFactory<EulaScreenHandler> weak_factory_; + base::WeakPtrFactory<EulaScreenHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(EulaScreenHandler); }; 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 7ea94468de3..ee389c1f193 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 @@ -18,6 +18,7 @@ #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/metrics/histogram_macros.h" +#include "base/optional.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -26,6 +27,9 @@ #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/authpolicy/authpolicy_helper.h" +#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h" +#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" +#include "chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h" #include "chrome/browser/chromeos/language_preferences.h" #include "chrome/browser/chromeos/login/lock_screen_utils.h" #include "chrome/browser/chromeos/login/reauth_stats.h" @@ -58,11 +62,13 @@ #include "chromeos/constants/chromeos_features.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/constants/devicetype.h" +#include "chromeos/constants/security_token_pin_types.h" #include "chromeos/dbus/util/version_loader.h" #include "chromeos/login/auth/challenge_response/cert_utils.h" #include "chromeos/login/auth/cryptohome_key_constants.h" #include "chromeos/login/auth/saml_password_attributes.h" #include "chromeos/login/auth/user_context.h" +#include "chromeos/network/onc/certificate_scope.h" #include "chromeos/settings/cros_settings_names.h" #include "components/login/localized_values_builder.h" #include "components/policy/proto/chrome_device_policy.pb.h" @@ -77,6 +83,7 @@ #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/gaia_urls.h" #include "mojo/public/cpp/bindings/callback_helpers.h" +#include "net/base/net_errors.h" #include "net/cert/x509_certificate.h" #include "services/network/nss_temp_certs_cache_chromeos.h" #include "services/network/public/mojom/network_context.mojom.h" @@ -253,6 +260,27 @@ bool GaiaActionButtonsEnabled() { return base::FeatureList::IsEnabled(chromeos::features::kGaiaActionButtons); } +PinDialogManager* GetLoginScreenPinDialogManager() { + DCHECK(ProfileHelper::IsSigninProfileInitialized()); + CertificateProviderService* certificate_provider_service = + CertificateProviderServiceFactory::GetForBrowserContext( + ProfileHelper::GetSigninProfile()); + return certificate_provider_service->pin_dialog_manager(); +} + +base::Value MakeSecurityTokenPinDialogParameters( + SecurityTokenPinCodeType code_type, + bool enable_user_input, + SecurityTokenPinErrorLabel error_label, + int attempts_left) { + base::Value params(base::Value::Type::DICTIONARY); + params.SetIntKey("codeType", static_cast<int>(code_type)); + params.SetBoolKey("enableUserInput", enable_user_input); + params.SetIntKey("errorLabel", static_cast<int>(error_label)); + params.SetIntKey("attemptsLeft", attempts_left); + return params; +} + } // namespace constexpr StaticOobeScreenId GaiaView::kScreenId; @@ -289,14 +317,15 @@ GaiaScreenHandler::GaiaScreenHandler( network_state_informer_(network_state_informer), core_oobe_view_(core_oobe_view), active_directory_password_change_screen_handler_( - active_directory_password_change_screen_handler), - weak_factory_(this) { + active_directory_password_change_screen_handler) { DCHECK(network_state_informer_.get()); } GaiaScreenHandler::~GaiaScreenHandler() { if (network_portal_detector_) network_portal_detector_->RemoveObserver(this); + if (is_security_token_pin_enabled_) + GetLoginScreenPinDialogManager()->RemovePinDialogHost(this); } void GaiaScreenHandler::MaybePreloadAuthExtension() { @@ -349,8 +378,7 @@ void GaiaScreenHandler::LoadGaiaWithPartition( base::BindOnce(&GaiaScreenHandler::OnSetCookieForLoadGaiaWithPartition, weak_factory_.GetWeakPtr(), context, partition_name); if (context.gaps_cookie.empty()) { - std::move(callback).Run( - net::CanonicalCookie::CookieInclusionStatus::INCLUDE); + std::move(callback).Run(net::CanonicalCookie::CookieInclusionStatus()); return; } @@ -367,15 +395,15 @@ void GaiaScreenHandler::LoadGaiaWithPartition( std::string gaps_cookie_value(kGAPSCookie); gaps_cookie_value += "=" + context.gaps_cookie; + std::unique_ptr<net::CanonicalCookie> cc(net::CanonicalCookie::Create( + GaiaUrls::GetInstance()->gaia_url(), gaps_cookie_value, base::Time::Now(), + base::nullopt /* server_time */)); + net::CookieOptions options; options.set_include_httponly(); // Permit it to set a SameSite cookie if it wants to. options.set_same_site_cookie_context( net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); - std::unique_ptr<net::CanonicalCookie> cc(net::CanonicalCookie::Create( - GaiaUrls::GetInstance()->gaia_url(), gaps_cookie_value, base::Time::Now(), - options)); - partition->GetCookieManagerForBrowserProcess()->SetCanonicalCookie( *cc.get(), "https", options, std::move(callback)); } @@ -393,8 +421,9 @@ void GaiaScreenHandler::OnSetCookieForLoadGaiaWithPartition( &GaiaScreenHandler::LoadGaiaWithPartitionAndVersionAndConsent, weak_factory_.GetWeakPtr(), context, partition_name, base::Owned(version.release()), base::Owned(consent.release())); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, std::move(get_version_and_consent), std::move(load_gaia)); } @@ -415,6 +444,30 @@ void GaiaScreenHandler::LoadGaiaWithPartitionAndVersionAndConsent( screen_mode_ = GetGaiaScreenMode(context.email, context.use_offline); params.SetInteger("screenMode", screen_mode_); + if (!context.email.empty()) { + const AccountId account_id = GetAccountId( + context.email, std::string() /* id */, AccountType::UNKNOWN); + const user_manager::User* const user = + user_manager::UserManager::Get()->FindUser(account_id); + if (user && user->using_saml() && + user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT && + base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kPublicAccountsSamlUrl)) { + std::string saml_url = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kPublicAccountsSamlUrl); + params.SetBoolean("startsOnSamlPage", true); + params.SetString("frameUrl", saml_url); + params.SetString("email", account_id.GetUserEmail()); + CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kPublicAccountsSamlAclUrl)); + std::string saml_acl_url = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kPublicAccountsSamlAclUrl); + params.SetString("samlAclUrl", saml_acl_url); + } + } + if (screen_mode_ == GAIA_SCREEN_MODE_AD && !authpolicy_login_helper_) authpolicy_login_helper_ = std::make_unique<AuthPolicyHelper>(); @@ -573,6 +626,23 @@ void GaiaScreenHandler::DeclareLocalizedValues( IDS_AD_PASSWORD_CHANGE_NEW_PASSWORD_REJECTED_SHORT_ERROR); builder->Add("adPassChangePasswordsMismatch", IDS_AD_PASSWORD_CHANGE_PASSWORDS_MISMATCH_ERROR); + + builder->Add("securityTokenPinDialogTitle", + IDS_SAML_SECURITY_TOKEN_PIN_DIALOG_TITLE); + builder->Add("securityTokenPinDialogSubtitle", + IDS_SAML_SECURITY_TOKEN_PIN_DIALOG_SUBTITLE); + builder->Add("securityTokenPinDialogTryAgain", + IDS_SAML_SECURITY_TOKEN_PIN_DIALOG_TRY_AGAIN); + builder->Add("securityTokenPinDialogAttemptsLeft", + IDS_REQUEST_PIN_DIALOG_ATTEMPTS_LEFT); + builder->Add("securityTokenPinDialogUnknownError", + IDS_REQUEST_PIN_DIALOG_UNKNOWN_ERROR); + builder->Add("securityTokenPinDialogUnknownInvalidPin", + IDS_REQUEST_PIN_DIALOG_INVALID_PIN_ERROR); + builder->Add("securityTokenPinDialogUnknownInvalidPuk", + IDS_REQUEST_PIN_DIALOG_INVALID_PUK_ERROR); + builder->Add("securityTokenPinDialogUnknownMaxAttemptsExceeded", + IDS_REQUEST_PIN_DIALOG_MAX_ATTEMPTS_EXCEEDED_ERROR); } void GaiaScreenHandler::Initialize() { @@ -612,6 +682,9 @@ void GaiaScreenHandler::RegisterMessages() { AddCallback("updateSigninUIState", &GaiaScreenHandler::HandleUpdateSigninUIState); AddCallback("showGuestInOobe", &GaiaScreenHandler::HandleShowGuestInOobe); + AddCallback("samlStateChanged", &GaiaScreenHandler::HandleSamlStateChanged); + AddCallback("securityTokenPinEntered", + &GaiaScreenHandler::HandleSecurityTokenPinEntered); // Allow UMA metrics collection from JS. web_ui()->AddMessageHandler(std::make_unique<MetricsHandler>()); @@ -653,34 +726,15 @@ void GaiaScreenHandler::HandleAuthExtensionLoaded() { std::make_unique<LoginClientCertUsageObserver>(); } -void GaiaScreenHandler::HandleWebviewLoadAborted( - const std::string& error_reason_str) { - // TODO(nkostylev): Switch to int code once webview supports that. - // http://crbug.com/470483 - if (error_reason_str == "ERR_ABORTED") { - LOG(WARNING) << "Ignoring Gaia webview error: " << error_reason_str; +void GaiaScreenHandler::HandleWebviewLoadAborted(int error_code) { + if (error_code == net::ERR_ABORTED) { + LOG(WARNING) << "Ignoring Gaia webview error: " + << net::ErrorToShortString(error_code); return; } - // TODO(nkostylev): Switch to int code once webview supports that. - // http://crbug.com/470483 - // Extract some common codes used by SigninScreenHandler for now. - if (error_reason_str == "ERR_NAME_NOT_RESOLVED") - frame_error_ = net::ERR_NAME_NOT_RESOLVED; - else if (error_reason_str == "ERR_INTERNET_DISCONNECTED") - frame_error_ = net::ERR_INTERNET_DISCONNECTED; - else if (error_reason_str == "ERR_NETWORK_CHANGED") - frame_error_ = net::ERR_NETWORK_CHANGED; - else if (error_reason_str == "ERR_INTERNET_DISCONNECTED") - frame_error_ = net::ERR_INTERNET_DISCONNECTED; - else if (error_reason_str == "ERR_PROXY_CONNECTION_FAILED") - frame_error_ = net::ERR_PROXY_CONNECTION_FAILED; - else if (error_reason_str == "ERR_TUNNEL_CONNECTION_FAILED") - frame_error_ = net::ERR_TUNNEL_CONNECTION_FAILED; - else - frame_error_ = net::ERR_INTERNET_DISCONNECTED; - - LOG(ERROR) << "Gaia webview error: " << error_reason_str; + frame_error_ = static_cast<net::Error>(error_code); + LOG(ERROR) << "Gaia webview error: " << net::ErrorToShortString(error_code); NetworkError::ErrorReason error_reason = NetworkError::ERROR_REASON_FRAME_ERROR; frame_state_ = FRAME_STATE_ERROR; @@ -812,10 +866,11 @@ void GaiaScreenHandler::OnGetCookiesForCompleteAuthentication( bool using_saml, const ::login::StringList& services, const SamlPasswordAttributes& password_attributes, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies) { std::string auth_code, gaps_cookie; - for (const auto& cookie : cookies) { + for (const auto& cookie_with_status : cookies) { + const auto& cookie = cookie_with_status.cookie; if (cookie.Name() == kOAUTHCodeCookie) auth_code = cookie.Value(); else if (cookie.Name() == kGAPSCookie) @@ -948,6 +1003,48 @@ void GaiaScreenHandler::HandleShowGuestInOobe(bool show) { ash::LoginScreen::Get()->ShowGuestButtonInOobe(show); } +void GaiaScreenHandler::HandleSamlStateChanged(bool is_saml) { + if (is_saml == is_security_token_pin_enabled_) { + // We're already in the needed |is_security_token_pin_enabled_| state. + return; + } + // Enable ourselves as a security token PIN dialog host during the SAML + // sign-in, so that when the SAML page requires client authentication (e.g., + // against a smart card), this PIN request is embedded into the SAML login UI. + if (is_saml) { + GetLoginScreenPinDialogManager()->AddPinDialogHost(this); + } else { + security_token_pin_entered_callback_.Reset(); + security_token_pin_dialog_closed_callback_.Reset(); + GetLoginScreenPinDialogManager()->RemovePinDialogHost(this); + } + is_security_token_pin_enabled_ = is_saml; +} + +void GaiaScreenHandler::HandleSecurityTokenPinEntered( + const std::string& user_input) { + // Invariant: when the pin_entered_callback is present, the closed_callback + // must be present as well. + DCHECK(!security_token_pin_entered_callback_ || + security_token_pin_dialog_closed_callback_); + + if (!security_token_pin_dialog_closed_callback_) { + // The PIN request has already been canceled on the handler side. + return; + } + + if (user_input.empty()) { + security_token_pin_entered_callback_.Reset(); + std::move(security_token_pin_dialog_closed_callback_).Run(); + } else { + // The callback must be non-null, since the UI implementation should not + // send multiple non-empty results. + std::move(security_token_pin_entered_callback_).Run(user_input); + // Keep |security_token_pin_dialog_closed_callback_|, in order to be able to + // notify about the dialog closing afterwards. + } +} + void GaiaScreenHandler::OnShowAddUser() { signin_screen_handler_->is_account_picker_showing_first_time_ = false; lock_screen_utils::EnforcePolicyInputMethods(std::string()); @@ -1123,6 +1220,49 @@ void GaiaScreenHandler::ShowSigninScreenForTest(const std::string& username, } } +void GaiaScreenHandler::ShowSecurityTokenPinDialog( + const std::string& /*caller_extension_name*/, + SecurityTokenPinCodeType code_type, + bool enable_user_input, + SecurityTokenPinErrorLabel error_label, + int attempts_left, + const base::Optional<AccountId>& /*authenticating_user_account_id*/, + SecurityTokenPinEnteredCallback pin_entered_callback, + SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback) { + DCHECK(is_security_token_pin_enabled_); + // There must be either no active PIN dialog, or the active dialog for which + // the PIN has already been entered. + DCHECK(!security_token_pin_entered_callback_); + + security_token_pin_entered_callback_ = std::move(pin_entered_callback); + // Note that this overwrites the previous closed_callback in the case where + // the dialog was already shown. This is intended, since the closing callback + // should only be used to notify that the dialog got canceled, which imposes a + // stricter quota on the PIN request caller. + security_token_pin_dialog_closed_callback_ = + std::move(pin_dialog_closed_callback); + + CallJS("login.GaiaSigninScreen.showPinDialog", + MakeSecurityTokenPinDialogParameters(code_type, enable_user_input, + error_label, attempts_left)); +} + +void GaiaScreenHandler::CloseSecurityTokenPinDialog() { + DCHECK(is_security_token_pin_enabled_); + // Invariant: when the pin_entered_callback is present, the closed_callback + // must be present as well. + DCHECK(!security_token_pin_entered_callback_ || + security_token_pin_dialog_closed_callback_); + + security_token_pin_entered_callback_.Reset(); + security_token_pin_dialog_closed_callback_.Reset(); + + // Notify the page, unless it's already being shut down (which may happen if + // we're called from the destructor). + if (IsJavascriptAllowed()) + CallJS("login.GaiaSigninScreen.closePinDialog"); +} + bool GaiaScreenHandler::IsOfflineLoginActive() const { return (screen_mode_ == GAIA_SCREEN_MODE_OFFLINE) || offline_login_is_active_; } @@ -1207,7 +1347,8 @@ void GaiaScreenHandler::ShowGaiaScreenIfReady() { g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->GetDeviceNetworkConfigurationUpdater() - ->GetAllAuthorityCertificates()); + ->GetAllAuthorityCertificates( + chromeos::onc::CertificateScope::Default())); } LoadAuthExtension(!gaia_silent_load_ /* force */, false /* offline */); @@ -1296,7 +1437,6 @@ bool GaiaScreenHandler::BuildUserContextForGaiaSignIn( const SamlPasswordAttributes& password_attributes, UserContext* user_context, std::string* error_message) { - // TODO(emaxx,https://crbug.com/826417): Localize the error messages. *user_context = UserContext(user_type, account_id); if (using_saml && extension_provided_client_cert_usage_observer_ && extension_provided_client_cert_usage_observer_->ClientCertsWereUsed()) { @@ -1304,13 +1444,15 @@ bool GaiaScreenHandler::BuildUserContextForGaiaSignIn( std::vector<ChallengeResponseKey::SignatureAlgorithm> signature_algorithms; if (!extension_provided_client_cert_usage_observer_->GetOnlyUsedClientCert( &saml_client_cert, &signature_algorithms)) { - *error_message = "Multiple client certificates are not supported"; + *error_message = l10n_util::GetStringUTF8( + IDS_CHALLENGE_RESPONSE_AUTH_MULTIPLE_CLIENT_CERTS_ERROR); return false; } ChallengeResponseKey challenge_response_key; if (!ExtractChallengeResponseKeyFromCert( *saml_client_cert, signature_algorithms, &challenge_response_key)) { - *error_message = "Internal error"; + *error_message = l10n_util::GetStringUTF8( + IDS_CHALLENGE_RESPONSE_AUTH_INVALID_CLIENT_CERT_ERROR); return false; } user_context->GetMutableChallengeResponseKeys()->push_back( diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h index 1b1dd70e282..9cba09d99ff 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h @@ -12,6 +12,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "chrome/browser/chromeos/authpolicy/authpolicy_helper.h" +#include "chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host.h" #include "chrome/browser/chromeos/login/login_client_cert_usage_observer.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h" @@ -19,6 +20,7 @@ #include "chromeos/network/portal_detector/network_portal_detector.h" #include "components/user_manager/user_type.h" #include "net/base/net_errors.h" +#include "net/cookies/canonical_cookie.h" class AccountId; @@ -26,10 +28,6 @@ namespace base { class DictionaryValue; } // namespace base -namespace net { -class CanonicalCookie; -} - namespace network { class NSSTempCertsCacheChromeOS; } @@ -75,7 +73,8 @@ class GaiaView { // A class that handles WebUI hooks in Gaia screen. class GaiaScreenHandler : public BaseScreenHandler, public GaiaView, - public NetworkPortalDetector::Observer { + public NetworkPortalDetector::Observer, + public SecurityTokenPinDialogHost { public: using TView = GaiaView; @@ -117,6 +116,18 @@ class GaiaScreenHandler : public BaseScreenHandler, const std::string& password, const std::string& services) override; + // SecurityTokenPinDialogHost: + void ShowSecurityTokenPinDialog( + const std::string& caller_extension_name, + SecurityTokenPinCodeType code_type, + bool enable_user_input, + SecurityTokenPinErrorLabel error_label, + int attempts_left, + const base::Optional<AccountId>& authenticating_user_account_id, + SecurityTokenPinEnteredCallback pin_entered_callback, + SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback) override; + void CloseSecurityTokenPinDialog() override; + // Returns true if offline login mode was either required, or reported by the // WebUI (i.e. WebUI mignt not have completed transition to the new mode). bool IsOfflineLoginActive() const; @@ -174,7 +185,7 @@ class GaiaScreenHandler : public BaseScreenHandler, const NetworkPortalDetector::CaptivePortalState& state) override; // WebUI message handlers. - void HandleWebviewLoadAborted(const std::string& error_reason_str); + void HandleWebviewLoadAborted(int error_code); void HandleCompleteAuthentication( const std::string& gaia_id, const std::string& email, @@ -189,7 +200,7 @@ class GaiaScreenHandler : public BaseScreenHandler, bool using_saml, const ::login::StringList& services, const SamlPasswordAttributes& password_attributes, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies); void HandleCompleteLogin(const std::string& gaia_id, const std::string& typed_email, @@ -222,6 +233,12 @@ class GaiaScreenHandler : public BaseScreenHandler, // OOBE. void HandleShowGuestInOobe(bool show); + // Called to notify whether the SAML sign-in is currently happening. + void HandleSamlStateChanged(bool is_saml); + // Called to deliver the result of the security token PIN request. Called with + // an empty string when the request is canceled. + void HandleSecurityTokenPinEntered(const std::string& user_input); + void OnShowAddUser(); // Really handles the complete login message. @@ -397,7 +414,23 @@ class GaiaScreenHandler : public BaseScreenHandler, std::unique_ptr<LoginClientCertUsageObserver> extension_provided_client_cert_usage_observer_; - base::WeakPtrFactory<GaiaScreenHandler> weak_factory_; + // State of the security token PIN dialogs: + + // Whether this instance is currently registered as a host for showing the + // security token PIN dialogs. (See PinDialogManager for the default host.) + bool is_security_token_pin_enabled_ = false; + // The callback to run when the user submits a non-empty input to the security + // token PIN dialog. + // Is non-empty iff the dialog is active and the input wasn't sent yet. + SecurityTokenPinEnteredCallback security_token_pin_entered_callback_; + // The callback to run when the security token PIN dialog gets closed - either + // due to the user canceling the dialog or the whole sign-in attempt being + // aborted. + // Is non-empty iff the dialog is active. + SecurityTokenPinDialogClosedCallback + security_token_pin_dialog_closed_callback_; + + base::WeakPtrFactory<GaiaScreenHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(GaiaScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc index 476a82cbb5b..cc9f15d605b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc @@ -24,9 +24,7 @@ constexpr StaticOobeScreenId KioskEnableScreenView::kScreenId; KioskEnableScreenHandler::KioskEnableScreenHandler( JSCallsContainer* js_calls_container) - : BaseScreenHandler(kScreenId, js_calls_container), - weak_ptr_factory_(this) { -} + : BaseScreenHandler(kScreenId, js_calls_container) {} KioskEnableScreenHandler::~KioskEnableScreenHandler() { if (delegate_) diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h index 7e7a8de528d..c6aa06760f7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h @@ -68,7 +68,7 @@ class KioskEnableScreenHandler : public KioskEnableScreenView, // True if machine's consumer kiosk mode is in a configurable state. bool is_configurable_ = false; - base::WeakPtrFactory<KioskEnableScreenHandler> weak_ptr_factory_; + base::WeakPtrFactory<KioskEnableScreenHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(KioskEnableScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc index c3dbe6c9ffb..8ec89e865c7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc @@ -426,8 +426,8 @@ void ResolveUILanguageList( const UILanguageListResolvedCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, + base::PostTask( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ResolveLanguageListInThreadPool, base::Passed(&language_switch_result), base::SequencedTaskRunnerHandle::Get(), callback)); @@ -581,9 +581,10 @@ void GetKeyboardLayoutsForLocale( // thread. std::string (*get_application_locale)(const std::string&, bool) = &l10n_util::GetApplicationLocale; - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(get_application_locale, locale, false /* set_icu_locale */), base::BindOnce(&GetKeyboardLayoutsForResolvedLocale, locale, callback)); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util_unittest.cc index 7449e5194ca..25586cf34dd 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util_unittest.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util_unittest.cc @@ -11,7 +11,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/run_loop.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "base/values.h" #include "chrome/browser/chromeos/customization/customization_document.h" #include "chrome/browser/chromeos/input_method/input_method_configuration.h" @@ -58,7 +58,7 @@ class L10nUtilTest : public testing::Test { void SetInputMethods2(); private: - base::test::ScopedTaskEnvironment scoped_task_environment_; + base::test::TaskEnvironment task_environment_; system::ScopedFakeStatisticsProvider scoped_fake_statistics_provider_; MockInputMethodManagerWithInputMethods* input_manager_; @@ -107,10 +107,10 @@ TEST_F(L10nUtilTest, FindMostRelevantLocale) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); dict->SetString("value", "de"); available_locales.Append(std::move(dict)); - dict.reset(new base::DictionaryValue); + dict = std::make_unique<base::DictionaryValue>(); dict->SetString("value", "fr"); available_locales.Append(std::move(dict)); - dict.reset(new base::DictionaryValue); + dict = std::make_unique<base::DictionaryValue>(); dict->SetString("value", "en-GB"); available_locales.Append(std::move(dict)); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.cc b/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.cc index 564cfbe0f74..e990f0f0868 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.cc @@ -7,7 +7,6 @@ #include "base/bind.h" #include "base/logging.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/login/screens/network_error.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chromeos/network/network_state.h" @@ -89,10 +88,7 @@ NetworkStateInformer::State GetStateForDefaultNetwork() { } // namespace -NetworkStateInformer::NetworkStateInformer() - : state_(OFFLINE), - weak_ptr_factory_(this) { -} +NetworkStateInformer::NetworkStateInformer() : state_(OFFLINE) {} NetworkStateInformer::~NetworkStateInformer() { if (NetworkHandler::IsInitialized()) { @@ -108,10 +104,6 @@ void NetworkStateInformer::Init() { this, FROM_HERE); network_portal_detector::GetInstance()->AddAndFireObserver(this); - - registrar_.Add(this, - chrome::NOTIFICATION_SESSION_STARTED, - content::NotificationService::AllSources()); } void NetworkStateInformer::AddObserver(NetworkStateInformerObserver* observer) { @@ -134,16 +126,6 @@ void NetworkStateInformer::OnPortalDetectionCompleted( UpdateStateAndNotify(); } -void NetworkStateInformer::Observe( - int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - if (type == chrome::NOTIFICATION_SESSION_STARTED) - registrar_.RemoveAll(); - else - NOTREACHED() << "Unknown notification: " << type; -} - void NetworkStateInformer::OnPortalDetected() { UpdateStateAndNotify(); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.h b/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.h index df2306eb8ec..32d79f0dc48 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.h @@ -18,9 +18,6 @@ #include "chrome/browser/chromeos/login/ui/captive_portal_window_proxy.h" #include "chromeos/network/network_state_handler_observer.h" #include "chromeos/network/portal_detector/network_portal_detector.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" -#include "content/public/browser/notification_service.h" namespace base { class Value; @@ -34,7 +31,6 @@ namespace chromeos { class NetworkStateInformer : public chromeos::NetworkStateHandlerObserver, public chromeos::NetworkPortalDetector::Observer, - public content::NotificationObserver, public CaptivePortalWindowProxyDelegate, public base::RefCounted<NetworkStateInformer> { public: @@ -74,11 +70,6 @@ class NetworkStateInformer const NetworkState* network, const NetworkPortalDetector::CaptivePortalState& state) override; - // content::NotificationObserver implementation. - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; - // CaptivePortalWindowProxyDelegate implementation: void OnPortalDetected() override; @@ -102,9 +93,8 @@ class NetworkStateInformer std::unique_ptr<base::Value> proxy_config_; base::ObserverList<NetworkStateInformerObserver>::Unchecked observers_; - content::NotificationRegistrar registrar_; - base::WeakPtrFactory<NetworkStateInformer> weak_ptr_factory_; + base::WeakPtrFactory<NetworkStateInformer> weak_ptr_factory_{this}; }; } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc index 57c06c6fd28..0b45e2d2f8f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc @@ -6,7 +6,7 @@ #include <stdint.h> -#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/mojom/constants.mojom.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/strings/string_number_conversions.h" @@ -42,8 +42,7 @@ bool IsWhiteListedVendorId(uint16_t vendor_id) { } // namespace -OobeDisplayChooser::OobeDisplayChooser() - : scoped_observer_(this), weak_ptr_factory_(this) { +OobeDisplayChooser::OobeDisplayChooser() : scoped_observer_(this) { // |connector| may be null in tests. auto* connector = content::GetSystemConnector(); if (connector) { @@ -66,10 +65,9 @@ void OobeDisplayChooser::TryToPlaceUiOnTouchDisplay() { display::Screen::GetScreen()->GetPrimaryDisplay(); if (primary_display.is_valid() && !TouchSupportAvailable(primary_display)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&OobeDisplayChooser::MaybeMoveToTouchDisplay, - weak_ptr_factory_.GetWeakPtr())); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&OobeDisplayChooser::MaybeMoveToTouchDisplay, + weak_ptr_factory_.GetWeakPtr())); } } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h index 5f2c67645d4..555050c7f87 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h @@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_OOBE_DISPLAY_CHOOSER_H_ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_OOBE_DISPLAY_CHOOSER_H_ -#include "ash/public/interfaces/cros_display_config.mojom.h" +#include "ash/public/mojom/cros_display_config.mojom.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" @@ -47,7 +47,7 @@ class OobeDisplayChooser : public ui::InputDeviceEventObserver { scoped_observer_; ash::mojom::CrosDisplayConfigControllerPtr cros_display_config_ptr_; - base::WeakPtrFactory<OobeDisplayChooser> weak_ptr_factory_; + base::WeakPtrFactory<OobeDisplayChooser> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(OobeDisplayChooser); }; 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 b780e5acb2d..67f444cbacd 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc @@ -12,6 +12,7 @@ #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_switches.h" +#include "ash/public/cpp/network_config_service.h" #include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" #include "base/bind.h" #include "base/command_line.h" @@ -20,6 +21,7 @@ #include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" +#include "build/branding_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chromeos/login/enrollment/auto_enrollment_check_screen_view.h" @@ -88,7 +90,6 @@ #include "chrome/grit/component_extension_resources.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/services/multidevice_setup/public/mojom/constants.mojom.h" -#include "chromeos/services/network_config/public/mojom/constants.mojom.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" @@ -133,9 +134,8 @@ constexpr char kOobeJSPath[] = "oobe.js"; constexpr char kProductLogoPath[] = "product-logo.png"; constexpr char kRecommendAppListViewHTMLPath[] = "recommend_app_list_view.html"; constexpr char kRecommendAppListViewJSPath[] = "recommend_app_list_view.js"; -constexpr char kStringsJSPath[] = "strings.js"; -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) constexpr char kLogo24PX1XSvgPath[] = "logo_24px-1x.svg"; constexpr char kLogo24PX2XSvgPath[] = "logo_24px-2x.svg"; constexpr char kSyncConsentIcons[] = "sync-consent-icons.html"; @@ -147,7 +147,7 @@ void AddProductLogoResources(content::WebUIDataSource* source) { source->AddResourcePath(kArcAssistantLogoPath, IDR_ASSISTANT_LOGO_PNG); source->AddResourcePath(kArcSupervisionIconPath, IDR_SUPERVISION_ICON_PNG); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) source->AddResourcePath(kLogo24PX1XSvgPath, IDR_PRODUCT_LOGO_24PX_1X); source->AddResourcePath(kLogo24PX2XSvgPath, IDR_PRODUCT_LOGO_24PX_2X); #endif @@ -157,7 +157,7 @@ void AddProductLogoResources(content::WebUIDataSource* source) { } void AddSyncConsentResources(content::WebUIDataSource* source) { -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) source->AddResourcePath(kSyncConsentIcons, IDR_PRODUCT_CHROMEOS_SYNC_CONSENT_SCREEN_ICONS); // No #else section here as Sync Settings screen is Chrome-specific. @@ -179,12 +179,19 @@ void AddArcScreensResources(content::WebUIDataSource* source) { IDR_ARC_SUPPORT_RECOMMEND_APP_LIST_VIEW_HTML); } +void AddAssistantScreensResources(content::WebUIDataSource* source) { + source->AddResourcePath("voice_match_animation.json", + IDR_ASSISTANT_VOICE_MATCH_ANIMATION); + source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';"); +} + void AddFingerprintResources(content::WebUIDataSource* source) { int animation_id; + bool is_lottie_animation = false; switch (quick_unlock::GetFingerprintLocation()) { case quick_unlock::FingerprintLocation::TABLET_POWER_BUTTON: - animation_id = - IDR_LOGIN_FINGERPRINT_SCANNER_TABLET_POWER_BUTTON_ANIMATION; + is_lottie_animation = true; + animation_id = IDR_LOGIN_FINGER_PRINT_TABLET_ANIMATION; break; case quick_unlock::FingerprintLocation::KEYBOARD_BOTTOM_RIGHT: animation_id = @@ -194,7 +201,20 @@ void AddFingerprintResources(content::WebUIDataSource* source) { animation_id = IDR_LOGIN_FINGERPRINT_SCANNER_LAPTOP_TOP_RIGHT_ANIMATION; break; } - source->AddResourcePath("fingerprint_scanner_animation.png", animation_id); + if (is_lottie_animation) { + source->AddResourcePath("fingerprint_scanner_animation.json", animation_id); + + // To use lottie, the worker-src CSP needs to be updated for the web ui that + // is using it. Since as of now there are only a couple of webuis using + // lottie animations, this update has to be performed manually. As the usage + // increases, set this as the default so manual override is no longer + // required. + source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';"); + } else { + source->AddResourcePath("fingerprint_scanner_animation.png", animation_id); + } + + source->AddBoolean("useLottieAnimationForFingerprint", is_lottie_animation); } // Default and non-shared resource definition for kOobeDisplay display type. @@ -235,7 +255,7 @@ content::WebUIDataSource* CreateOobeUIDataSource( content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOobeHost); source->AddLocalizedStrings(localized_strings); - source->SetJsonPath(kStringsJSPath); + source->UseStringsJs(); // First, configure default and non-shared resources for the current display // type. @@ -255,6 +275,7 @@ content::WebUIDataSource* CreateOobeUIDataSource( AddFingerprintResources(source); AddSyncConsentResources(source); AddArcScreensResources(source); + AddAssistantScreensResources(source); source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS); source->OverrideContentSecurityPolicyObjectSrc( @@ -482,10 +503,7 @@ void OobeUI::BindPrivilegedHostDeviceSetter( void OobeUI::BindCrosNetworkConfig( chromeos::network_config::mojom::CrosNetworkConfigRequest request) { - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()) - ->BindInterface(chromeos::network_config::mojom::kServiceName, - std::move(request)); + ash::GetNetworkConfigService(std::move(request)); } OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url) @@ -552,7 +570,7 @@ void OobeUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) { const std::string& app_locale = g_browser_process->GetApplicationLocale(); webui::SetLoadTimeDataDefaults(app_locale, localized_strings); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) localized_strings->SetString("buildType", "chrome"); #else localized_strings->SetString("buildType", "chromium"); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.cc b/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.cc index 01aed9f684e..e86ea5107dc 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.cc @@ -35,7 +35,7 @@ std::string ScreenlockIconSource::GetSource() const { void ScreenlockIconSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { if (!icon_provider_) { callback.Run(GetDefaultIcon().As1xPNGBytes().get()); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.h b/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.h index d6715f1afa8..44b13c43bd5 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.h @@ -24,7 +24,7 @@ class ScreenlockIconSource : public content::URLDataSource { std::string GetSource() const override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) const override; 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 eca0146a80f..aa0e6206df5 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 @@ -11,8 +11,9 @@ #include <vector> #include "ash/public/cpp/login_constants.h" +#include "ash/public/cpp/tablet_mode.h" #include "ash/public/cpp/wallpaper_types.h" -#include "ash/public/interfaces/tray_action.mojom.h" +#include "ash/public/mojom/tray_action.mojom.h" #include "base/bind.h" #include "base/i18n/number_formatting.h" #include "base/location.h" @@ -64,7 +65,6 @@ #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/ui/ash/ime_controller_client.h" #include "chrome/browser/ui/ash/session_controller_client_impl.h" -#include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chrome/browser/ui/ash/wallpaper_controller_client.h" #include "chrome/browser/ui/webui/chromeos/internet_detail_dialog.h" #include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h" @@ -97,6 +97,8 @@ #include "components/user_manager/user_manager.h" #include "components/user_manager/user_type.h" #include "components/version_info/version_info.h" +#include "content/public/browser/notification_service.h" +#include "content/public/browser/notification_source.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "google_apis/gaia/gaia_auth_util.h" @@ -235,8 +237,7 @@ SigninScreenHandler::SigninScreenHandler( ->CapsLockIsEnabled()), proxy_auth_dialog_reload_times_(kMaxGaiaReloadForProxyAuthDialog), gaia_screen_handler_(gaia_screen_handler), - histogram_helper_(new ErrorScreensHistogramHelper("Signin")), - weak_factory_(this) { + histogram_helper_(new ErrorScreensHistogramHelper("Signin")) { DCHECK(network_state_informer_.get()); DCHECK(error_screen_); DCHECK(core_oobe_view_); @@ -266,9 +267,9 @@ SigninScreenHandler::SigninScreenHandler( base::Bind(&SigninScreenHandler::OnAllowedInputMethodsChanged, base::Unretained(this))); - TabletModeClient* tablet_mode_client = TabletModeClient::Get(); - tablet_mode_client->AddObserver(this); - OnTabletModeToggled(tablet_mode_client->tablet_mode_enabled()); + ash::TabletMode* tablet_mode = ash::TabletMode::Get(); + tablet_mode->AddObserver(this); + OnTabletModeToggled(tablet_mode->InTabletMode()); WallpaperControllerClient::Get()->AddObserver(this); } @@ -276,7 +277,9 @@ SigninScreenHandler::SigninScreenHandler( SigninScreenHandler::~SigninScreenHandler() { if (auto* wallpaper_controller_client = WallpaperControllerClient::Get()) wallpaper_controller_client->RemoveObserver(this); - TabletModeClient::Get()->RemoveObserver(this); + // Ash maybe released before us. + if (ash::TabletMode::Get()) + ash::TabletMode::Get()->RemoveObserver(this); OobeUI* oobe_ui = GetOobeUI(); if (oobe_ui && oobe_ui_observer_added_) oobe_ui->RemoveObserver(this); @@ -439,6 +442,8 @@ void SigninScreenHandler::RegisterMessages() { AddCallback("launchIncognito", &SigninScreenHandler::HandleLaunchIncognito); AddCallback("launchPublicSession", &SigninScreenHandler::HandleLaunchPublicSession); + AddCallback("launchSAMLPublicSession", + &SigninScreenHandler::HandleLaunchSAMLPublicSession); AddRawCallback("offlineLogin", &SigninScreenHandler::HandleOfflineLogin); AddCallback("rebootSystem", &SigninScreenHandler::HandleRebootSystem); AddCallback("removeUser", &SigninScreenHandler::HandleRemoveUser); @@ -1016,6 +1021,14 @@ void SigninScreenHandler::SuspendDone(const base::TimeDelta& sleep_duration) { } } +void SigninScreenHandler::OnTabletModeStarted() { + OnTabletModeToggled(true); +} + +void SigninScreenHandler::OnTabletModeEnded() { + OnTabletModeToggled(false); +} + void SigninScreenHandler::OnTabletModeToggled(bool enabled) { CallJS("login.AccountPickerScreen.setTabletModeState", enabled); } @@ -1102,6 +1115,14 @@ void SigninScreenHandler::HandleLaunchIncognito() { delegate_->Login(context, SigninSpecifics()); } +void SigninScreenHandler::HandleLaunchSAMLPublicSession( + const std::string& email) { + const AccountId account_id = user_manager::known_user::GetAccountId( + email, std::string() /* id */, AccountType::UNKNOWN); + SigninScreenHandler::HandleLaunchPublicSession(account_id, std::string(), + std::string()); +} + void SigninScreenHandler::HandleLaunchPublicSession( const AccountId& account_id, const std::string& locale, @@ -1367,7 +1388,7 @@ void SigninScreenHandler::SendPublicSessionKeyboardLayouts( void SigninScreenHandler::HandleGetTabletModeState() { CallJS("login.AccountPickerScreen.setTabletModeState", - TabletModeClient::Get()->tablet_mode_enabled()); + ash::TabletMode::Get()->InTabletMode()); } void SigninScreenHandler::HandleGetDemoModeState() { 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 48988d3b853..6195aa7c0d3 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/public/cpp/tablet_mode_observer.h" #include "ash/public/cpp/wallpaper_controller_observer.h" #include "base/callback.h" #include "base/compiler_specific.h" @@ -21,7 +22,6 @@ #include "chrome/browser/chromeos/login/signin_specifics.h" #include "chrome/browser/chromeos/login/ui/login_display.h" #include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chrome/browser/ui/ash/tablet_mode_client_observer.h" #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" @@ -183,7 +183,7 @@ class SigninScreenHandler public NetworkStateInformer::NetworkStateInformerObserver, public PowerManagerClient::Observer, public input_method::ImeKeyboard::Observer, - public TabletModeClientObserver, + public ash::TabletModeObserver, public OobeUI::Observer, public ash::WallpaperControllerObserver { public: @@ -302,8 +302,11 @@ class SigninScreenHandler // PowerManagerClient::Observer implementation: void SuspendDone(const base::TimeDelta& sleep_duration) override; - // TabletModeClientObserver: - void OnTabletModeToggled(bool enabled) override; + // ash::TabletModeObserver: + void OnTabletModeStarted() override; + void OnTabletModeEnded() override; + + void OnTabletModeToggled(bool enabled); // Restore input focus to current user pod. void RefocusCurrentPod(); @@ -324,6 +327,7 @@ class SigninScreenHandler const std::string& password); void HandleAttemptUnlock(const std::string& username); void HandleLaunchIncognito(); + void HandleLaunchSAMLPublicSession(const std::string& email); void HandleLaunchPublicSession(const AccountId& account_id, const std::string& locale, const std::string& input_method); @@ -503,7 +507,7 @@ class SigninScreenHandler std::unique_ptr<AccountId> focused_pod_account_id_; - base::WeakPtrFactory<SigninScreenHandler> weak_factory_; + base::WeakPtrFactory<SigninScreenHandler> weak_factory_{this}; 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 a235cccacbf..205688cf91b 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 @@ -18,7 +18,7 @@ #include "components/account_id/account_id.h" #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -52,8 +52,8 @@ class SigninPrepareUserListTest : public testing::Test, profile_manager_.reset( new TestingProfileManager(TestingBrowserProcess::GetGlobal())); ASSERT_TRUE(profile_manager_->SetUp()); - controller_.reset(new MultiProfileUserController( - this, TestingBrowserProcess::GetGlobal()->local_state())); + controller_ = std::make_unique<MultiProfileUserController>( + this, TestingBrowserProcess::GetGlobal()->local_state()); fake_user_manager_->set_multi_profile_user_controller(controller_.get()); for (size_t i = 0; i < base::size(kUsersPublic); ++i) @@ -78,7 +78,7 @@ class SigninPrepareUserListTest : public testing::Test, FakeChromeUserManager* user_manager() { return fake_user_manager_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; ScopedCrosSettingsTestHelper cros_settings_test_helper_; FakeChromeUserManager* fake_user_manager_; user_manager::ScopedUserManager user_manager_enabler_; 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 bea38eec2ff..e4b7d641ffc 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 @@ -13,7 +13,7 @@ constexpr StaticOobeScreenId UserBoardView::kScreenId; UserBoardScreenHandler::UserBoardScreenHandler( JSCallsContainer* js_calls_container) - : BaseScreenHandler(kScreenId, js_calls_container), weak_factory_(this) {} + : BaseScreenHandler(kScreenId, js_calls_container) {} UserBoardScreenHandler::~UserBoardScreenHandler() { } 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 ada66bdbba9..8aadb916d4d 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 @@ -63,7 +63,7 @@ class UserBoardScreenHandler : public BaseScreenHandler, public UserBoardView { base::WeakPtr<UserBoardView> GetWeakPtr() override; UserSelectionScreen* screen_ = nullptr; - base::WeakPtrFactory<UserBoardScreenHandler> weak_factory_; + base::WeakPtrFactory<UserBoardScreenHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(UserBoardScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn b/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn index f6ccee9ab2e..3adbd9c1354 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn @@ -12,7 +12,4 @@ mojom("mojo_bindings") { deps = [ "//chromeos/services/machine_learning/public/mojom", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } 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 index a436b2ad466..dc4915027ca 100644 --- 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 @@ -91,7 +91,7 @@ MultiDeviceSetupDialogUI::MultiDeviceSetupDialogUI(content::WebUI* web_ui) content::WebUIDataSource::Create(chrome::kChromeUIMultiDeviceSetupHost); chromeos::multidevice_setup::AddLocalizedStrings(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource( IDR_MULTIDEVICE_SETUP_MULTIDEVICE_SETUP_DIALOG_HTML); diff --git a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc index 7a95459f913..9314ef72f38 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc @@ -25,6 +25,7 @@ #include "content/public/browser/web_ui_data_source.h" #include "services/service_manager/public/cpp/connector.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/chromeos/devicetype_utils.h" namespace chromeos { @@ -47,8 +48,6 @@ constexpr LocalizedString kLocalizedStringsWithoutPlaceholders[] = { IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_MULTIPLE_DEVICE_HEADER}, {"startSetupPageSingleDeviceHeader", IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_SINGLE_DEVICE_HEADER}, - {"startSetupPageFeatureListHeader", - IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_FEATURE_LIST_HEADER}, {"startSetupPageFeatureListInstallApps", IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_INSTALL_APPS_DESCRIPTION}, {"startSetupPageFeatureListAddFeatures", @@ -83,6 +82,7 @@ GetLocalizedStringsWithPlaceholders() { "startSetupPageMessage", l10n_util::GetStringFUTF16( IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_MESSAGE, + ui::GetChromeOSDeviceName(), base::ASCIIToUTF16(kFootnoteMarker), base::UTF8ToUTF16( chromeos::multidevice_setup:: @@ -96,6 +96,12 @@ GetLocalizedStringsWithPlaceholders() { base::ASCIIToUTF16(kFootnoteMarker))); localized_strings.emplace_back( + "startSetupPageFeatureListHeader", + l10n_util::GetStringFUTF16( + IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_FEATURE_LIST_HEADER, + ui::GetChromeOSDeviceName())); + + localized_strings.emplace_back( "startSetupPageFeatureListAwm", l10n_util::GetStringFUTF16( IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_AWM_DESCRIPTION, @@ -128,11 +134,15 @@ void AddLocalizedValuesToBuilder(::login::LocalizedValuesBuilder* builder) { // localization calls separately. builder->AddF( "startSetupPageMessage", IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_MESSAGE, - base::ASCIIToUTF16(kFootnoteMarker), + ui::GetChromeOSDeviceName(), base::ASCIIToUTF16(kFootnoteMarker), base::UTF8ToUTF16(chromeos::multidevice_setup:: GetBoardSpecificBetterTogetherSuiteLearnMoreUrl() .spec())); + builder->AddF("startSetupPageFeatureListHeader", + IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_FEATURE_LIST_HEADER, + ui::GetChromeOSDeviceName()); + builder->AddF("startSetupPageFootnote", IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_FOOTNOTE, base::ASCIIToUTF16(kFootnoteMarker)); 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 34e2447eafb..2bea1501801 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 @@ -32,7 +32,6 @@ constexpr LocalizedString kElementLocalizedStrings[] = { {"OncTypeTether", IDS_NETWORK_TYPE_TETHER}, {"OncTypeVPN", IDS_NETWORK_TYPE_VPN}, {"OncTypeWiFi", IDS_NETWORK_TYPE_WIFI}, - {"OncTypeWiMAX", IDS_NETWORK_TYPE_WIMAX}, {"networkListItemConnected", IDS_STATUSBAR_NETWORK_DEVICE_CONNECTED}, {"networkListItemConnecting", IDS_STATUSBAR_NETWORK_DEVICE_CONNECTING}, {"networkListItemConnectingTo", IDS_NETWORK_LIST_CONNECTING_TO}, @@ -76,6 +75,8 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { IDS_ONC_CELLULAR_ACTIVATION_STATE_NOT_ACTIVATED}, {"OncCellular-ActivationState_PartiallyActivated", IDS_ONC_CELLULAR_ACTIVATION_STATE_PARTIALLY_ACTIVATED}, + {"OncCellular-ActivationState_NoService", + IDS_ONC_CELLULAR_ACTIVATION_STATE_NO_SERVICE}, {"OncCellular-Family", IDS_ONC_CELLULAR_FAMILY}, {"OncCellular-FirmwareRevision", IDS_ONC_CELLULAR_FIRMWARE_REVISION}, {"OncCellular-HardwareRevision", IDS_ONC_CELLULAR_HARDWARE_REVISION}, @@ -86,7 +87,6 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { {"OncCellular-Manufacturer", IDS_ONC_CELLULAR_MANUFACTURER}, {"OncCellular-ModelID", IDS_ONC_CELLULAR_MODEL_ID}, {"OncCellular-NetworkTechnology", IDS_ONC_CELLULAR_NETWORK_TECHNOLOGY}, - {"OncCellular-PRLVersion", IDS_ONC_CELLULAR_PRL_VERSION}, {"OncCellular-RoamingState", IDS_ONC_CELLULAR_ROAMING_STATE}, {"OncCellular-RoamingState_Home", IDS_ONC_CELLULAR_ROAMING_STATE_HOME}, {"OncCellular-RoamingState_Roaming", @@ -138,11 +138,11 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { {"OncVPN-IPsec-PSK", IDS_ONC_VPN_IPSEC_PSK}, {"OncVPN-L2TP-Password", IDS_ONC_VPN_PASSWORD}, {"OncVPN-L2TP-Username", IDS_ONC_VPN_USERNAME}, + {"OncVPN-OpenVPN-ExtraHosts", IDS_ONC_VPN_OPENVPN_EXTRA_HOSTS}, {"OncVPN-OpenVPN-OTP", IDS_ONC_VPN_OPENVPN_OTP}, {"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-ProviderName", IDS_ONC_VPN_THIRD_PARTY_VPN_PROVIDER_NAME}, {"OncVPN-Type", IDS_ONC_VPN_TYPE}, {"OncVPN-Type_L2TP_IPsec", IDS_ONC_VPN_TYPE_L2TP_IPSEC}, {"OncVPN-Type_L2TP_IPsec_PSK", IDS_ONC_VPN_TYPE_L2TP_IPSEC_PSK}, @@ -159,7 +159,6 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { {"OncWiFi-Security_WPA-PSK", IDS_ONC_WIFI_SECURITY_PSK}, {"OncWiFi-Security_WEP-8021X", IDS_ONC_WIFI_SECURITY_EAP}, {"OncWiFi-SignalStrength", IDS_ONC_WIFI_SIGNAL_STRENGTH}, - {"OncWiMAX-EAP-Identity", IDS_ONC_WIMAX_EAP_IDENTITY}, {"Oncipv4-Gateway", IDS_ONC_IPV4_GATEWAY}, {"Oncipv4-IPAddress", IDS_ONC_IPV4_ADDRESS}, {"Oncipv4-RoutingPrefix", IDS_ONC_IPV4_ROUTING_PREFIX}, diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc index 4c767fef5ea..6e1c9d1f886 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc @@ -8,6 +8,7 @@ #include <string> #include <utility> +#include "ash/public/cpp/network_config_service.h" #include "base/bind.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -27,14 +28,12 @@ #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/onc/onc_utils.h" -#include "chromeos/services/network_config/public/mojom/constants.mojom.h" #include "components/device_event_log/device_event_log.h" #include "content/public/browser/browser_context.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" -#include "services/service_manager/public/cpp/connector.h" #include "third_party/cros_system_api/dbus/service_constants.h" #include "ui/base/l10n/l10n_util.h" @@ -88,7 +87,7 @@ void SetDeviceProperties(base::DictionaryValue* dictionary) { class NetworkConfigMessageHandler : public content::WebUIMessageHandler { public: - NetworkConfigMessageHandler() : weak_ptr_factory_(this) {} + NetworkConfigMessageHandler() {} ~NetworkConfigMessageHandler() override {} // WebUIMessageHandler implementation. @@ -273,7 +272,7 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler { InternetConfigDialog::ShowDialogForNetworkType(onc_type); } - base::WeakPtrFactory<NetworkConfigMessageHandler> weak_ptr_factory_; + base::WeakPtrFactory<NetworkConfigMessageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(NetworkConfigMessageHandler); }; @@ -363,7 +362,7 @@ NetworkUI::NetworkUI(content::WebUI* web_ui) network_element::AddLocalizedStrings(html); - html->SetJsonPath("strings.js"); + html->UseStringsJs(); html->AddResourcePath("network_ui.css", IDR_NETWORK_UI_CSS); html->AddResourcePath("network_ui.js", IDR_NETWORK_UI_JS); html->SetDefaultResource(IDR_NETWORK_UI_HTML); @@ -378,9 +377,7 @@ NetworkUI::~NetworkUI() {} void NetworkUI::BindCrosNetworkConfig( network_config::mojom::CrosNetworkConfigRequest request) { - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()) - ->BindInterface(network_config::mojom::kServiceName, std::move(request)); + ash::GetNetworkConfigService(std::move(request)); } } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc index dd93475bca4..b77f4d2f921 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc @@ -33,8 +33,6 @@ namespace chromeos { namespace { -const char kStringsJsFile[] = "strings.js"; - const char kRequestBatteryChargeDataCallback[] = "requestBatteryChargeData"; const char kOnRequestBatteryChargeDataFunction[] = "powerUI.showBatteryChargeData"; @@ -260,7 +258,7 @@ PowerUI::PowerUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { }; AddLocalizedStringsBulk(html, kStrings, base::size(kStrings)); - html->SetJsonPath(kStringsJsFile); + html->UseStringsJs(); html->AddResourcePath("power.css", IDR_ABOUT_POWER_CSS); html->AddResourcePath("power.js", IDR_ABOUT_POWER_JS); 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 7c2890f0231..1376878c1d8 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc @@ -128,6 +128,12 @@ class SetTimeMessageHandler : public content::WebUIMessageHandler, return; } + double seconds; + if (!args->GetDouble(0, &seconds)) { + NOTREACHED(); + return; + } + AccountId account_id; bool is_user_logged_in = user_manager::UserManager::Get()->IsUserLoggedIn(); if (is_user_logged_in) { @@ -139,7 +145,8 @@ class SetTimeMessageHandler : public content::WebUIMessageHandler, base::BindRepeating(&SetTimeMessageHandler::OnParentAccessValidation, weak_factory_.GetWeakPtr()), ash::ParentAccessRequestReason::kChangeTime, - !is_user_logged_in /* extra_dimmer */); + !is_user_logged_in /* extra_dimmer */, + base::Time::FromDoubleT(seconds)); } void OnParentAccessValidation(bool success) { @@ -188,7 +195,7 @@ SetTimeUI::SetTimeUI(content::WebUI* web_ui) : WebDialogUI(web_ui) { values.SetDouble("buildTime", base::GetBuildTime().ToJsTime()); source->AddLocalizedStrings(values); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("set_time_browser_proxy.html", IDR_SET_TIME_BROWSER_PROXY_HTML); diff --git a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc index 07d906c1abd..c5c1b2cba55 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc @@ -34,7 +34,7 @@ std::string SlowTraceSource::GetSource() { void SlowTraceSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { int trace_id = 0; size_t pos = path.find('#'); diff --git a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h index 77a04463b1d..8d0007981f7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h @@ -32,7 +32,7 @@ class SlowTraceSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; bool AllowCaching() override; diff --git a/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc index 4e199978350..1020d867f72 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc @@ -101,7 +101,7 @@ void SlowHandler::RegisterMessages() { kJsApiLoadComplete, base::BindRepeating(&SlowHandler::LoadComplete, base::Unretained(this))); - user_pref_registrar_.reset(new PrefChangeRegistrar); + user_pref_registrar_ = std::make_unique<PrefChangeRegistrar>(); user_pref_registrar_->Init(profile_->GetPrefs()); user_pref_registrar_->Add(prefs::kPerformanceTracingEnabled, base::Bind(&SlowHandler::UpdatePage, diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc index d20bb682266..4b31716cbeb 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc @@ -87,7 +87,7 @@ SmbCredentialsDialogUI::SmbCredentialsDialogUI(content::WebUI* web_ui) AddSmbCredentialsDialogStrings(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_SMB_CREDENTIALS_DIALOG_CONTAINER_HTML); source->AddResourcePath("smb_credentials_dialog.html", IDR_SMB_CREDENTIALS_DIALOG_HTML); diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc index 4b224daa69c..819e4fb6cf7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc @@ -32,8 +32,7 @@ base::Value BuildShareList(const std::vector<smb_client::SmbUrl>& shares) { } // namespace -SmbHandler::SmbHandler(Profile* profile) - : profile_(profile), weak_ptr_factory_(this) {} +SmbHandler::SmbHandler(Profile* profile) : profile_(profile) {} SmbHandler::~SmbHandler() = default; diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h index 38354b5e168..ef94923201b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h @@ -6,7 +6,6 @@ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_SMB_SHARES_SMB_HANDLER_H_ #include "base/callback_forward.h" -#include "base/files/file.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/smb_client/smb_service.h" @@ -52,7 +51,7 @@ class SmbHandler : public content::WebUIMessageHandler { bool host_discovery_done_ = false; base::OnceClosure stored_mount_call_; Profile* const profile_; - base::WeakPtrFactory<SmbHandler> weak_ptr_factory_; + base::WeakPtrFactory<SmbHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SmbHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc index ac5be07201d..5bbece77c06 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc @@ -70,7 +70,7 @@ SmbShareDialogUI::SmbShareDialogUI(content::WebUI* web_ui) source->AddBoolean("isActiveDirectoryUser", user && user->IsActiveDirectoryUser()); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_SMB_SHARES_DIALOG_CONTAINER_HTML); source->AddResourcePath("smb_share_dialog.html", IDR_SMB_SHARES_DIALOG_HTML); source->AddResourcePath("smb_share_dialog.js", IDR_SMB_SHARES_DIALOG_JS); 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 d84d732aa42..23d28d7e47f 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 @@ -198,8 +198,7 @@ base::Value GetSysInfo() { } // namespace -SysInternalsMessageHandler::SysInternalsMessageHandler() - : weak_ptr_factory_(this) {} +SysInternalsMessageHandler::SysInternalsMessageHandler() {} SysInternalsMessageHandler::~SysInternalsMessageHandler() {} @@ -222,8 +221,9 @@ void SysInternalsMessageHandler::HandleGetSysInfo(const base::ListValue* args) { } base::Value callback_id = list[0].Clone(); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, base::MayBlock(), base::BindOnce(&GetSysInfo), + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(&GetSysInfo), base::BindOnce(&SysInternalsMessageHandler::ReplySysInfo, weak_ptr_factory_.GetWeakPtr(), std::move(callback_id))); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.h b/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.h index 4a21bbabe73..6e84b36f0b2 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.h @@ -59,7 +59,7 @@ class SysInternalsMessageHandler : public content::WebUIMessageHandler { // void ReplySysInfo(base::Value callback_id, base::Value result); - base::WeakPtrFactory<SysInternalsMessageHandler> weak_ptr_factory_; + base::WeakPtrFactory<SysInternalsMessageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SysInternalsMessageHandler); }; 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 6fcd5cd124a..ce6790a8ec3 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 @@ -162,8 +162,9 @@ void SystemWebDialogDelegate::ShowSystemDialogForBrowserContext( if (!parent && GetDialogModalType() == ui::MODAL_TYPE_NONE) extra_params.z_order = ui::ZOrderLevel::kFloatingWindow; AdjustWidgetInitParams(&extra_params); - dialog_window_ = chrome::ShowWebDialogWithParams(parent, browser_context, - this, &extra_params); + dialog_window_ = chrome::ShowWebDialogWithParams( + parent, browser_context, this, + base::make_optional<views::Widget::InitParams>(std::move(extra_params))); } void SystemWebDialogDelegate::ShowSystemDialog(gfx::NativeWindow parent) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc index 889a692e022..2609acbbbde 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc @@ -26,7 +26,8 @@ constexpr char kDefaultMime[] = "text/html"; void ReadFile(const base::FilePath& path, const content::URLDataSource::GotDataCallback& callback) { std::string content; - CHECK(base::ReadFileToString(path, &content)) << path; + bool result = base::ReadFileToString(path, &content); + DCHECK(result) << path; scoped_refptr<base::RefCountedString> response = base::RefCountedString::TakeString(&content); callback.Run(response.get()); @@ -39,16 +40,17 @@ std::string TerminalSource::GetSource() { void TerminalSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { - base::FilePath file_path(kTerminalRoot); - if (path.empty()) { - file_path = file_path.Append(kDefaultFile); - } else { - file_path = file_path.Append(path); - } - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + // Reparse path to strip any query or fragment, skip first '/' in path. + std::string reparsed = + GURL(chrome::kChromeUITerminalURL + path).path().substr(1); + if (reparsed.empty()) + reparsed = kDefaultFile; + base::FilePath file_path = base::FilePath(kTerminalRoot).Append(reparsed); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&ReadFile, file_path, callback)); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h index dc922840e02..b5acfdeb435 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h +++ b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h @@ -8,8 +8,8 @@ #include <string> #include "base/macros.h" -#include "content/public/browser/resource_request_info.h" #include "content/public/browser/url_data_source.h" +#include "content/public/browser/web_contents.h" class TerminalSource : public content::URLDataSource { public: @@ -21,7 +21,7 @@ class TerminalSource : public content::URLDataSource { void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; diff --git a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc index 63c867618b6..e8ca63d7cbf 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc @@ -179,7 +179,7 @@ std::string UserImageSource::GetSource() { void UserImageSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { std::string email; int frame = -1; diff --git a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h index 1e73aed0637..f20af23e762 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h +++ b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h @@ -33,7 +33,7 @@ class UserImageSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; diff --git a/chromium/chrome/browser/ui/webui/chromeos/video_source.cc b/chromium/chrome/browser/ui/webui/chromeos/video_source.cc index 4db1b33388d..4b56024a718 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/video_source.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/video_source.cc @@ -14,7 +14,7 @@ #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/task/post_task.h" -#include "base/task/thread_pool/thread_pool.h" +#include "base/task/thread_pool/thread_pool_instance.h" #include "base/task_runner_util.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/common/url_constants.h" @@ -54,9 +54,9 @@ void VideoLoaded( } // namespace -VideoSource::VideoSource() : weak_factory_(this) { - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, +VideoSource::VideoSource() { + task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); } @@ -68,7 +68,7 @@ std::string VideoSource::GetSource() { void VideoSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& got_data_callback) { if (!IsWhitelisted(path)) { got_data_callback.Run(nullptr); @@ -77,8 +77,9 @@ void VideoSource::StartDataRequest( const base::FilePath asset_dir(chrome::kChromeOSAssetPath); const base::FilePath video_path = asset_dir.AppendASCII(path); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&base::PathExists, video_path), base::BindOnce(&VideoSource::StartDataRequestAfterPathExists, weak_factory_.GetWeakPtr(), video_path, diff --git a/chromium/chrome/browser/ui/webui/chromeos/video_source.h b/chromium/chrome/browser/ui/webui/chromeos/video_source.h index 316509a93ec..c8f6cae1d3a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/video_source.h +++ b/chromium/chrome/browser/ui/webui/chromeos/video_source.h @@ -29,11 +29,10 @@ class VideoSource : public content::URLDataSource { // content::URLDataSource: std::string GetSource() override; - void StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const content::URLDataSource::GotDataCallback& got_data_callback) - override; + void StartDataRequest(const std::string& path, + const content::WebContents::Getter& wc_getter, + const content::URLDataSource::GotDataCallback& + got_data_callback) override; std::string GetMimeType(const std::string& path) override; private: @@ -46,7 +45,7 @@ class VideoSource : public content::URLDataSource { // The background task runner on which file I/O is performed. scoped_refptr<base::SequencedTaskRunner> task_runner_; - base::WeakPtrFactory<VideoSource> weak_factory_; + base::WeakPtrFactory<VideoSource> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VideoSource); }; diff --git a/chromium/chrome/browser/ui/webui/components_ui.cc b/chromium/chrome/browser/ui/webui/components_ui.cc index 8ae8e72db64..e4686db9b66 100644 --- a/chromium/chrome/browser/ui/webui/components_ui.cc +++ b/chromium/chrome/browser/ui/webui/components_ui.cc @@ -67,7 +67,7 @@ content::WebUIDataSource* CreateComponentsUIHTMLSource(Profile* profile) { profile->IsOffTheRecord() #endif ); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("components.js", IDR_COMPONENTS_JS); source->SetDefaultResource(IDR_COMPONENTS_HTML); return source; diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc b/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc index 0b218719771..caf0202c54d 100644 --- a/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc +++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc @@ -495,17 +495,16 @@ void ConflictsDataFetcher::OnModuleDatabaseIdle() { #if defined(GOOGLE_CHROME_BUILD) // The state of third-party features must be determined on the UI thread. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( OnModuleDataFetched, std::move(on_conflicts_data_fetched_callback_), std::move(results), std::move(third_party_conflicts_manager_state_))); #else // The third-party features are always disabled on Chromium builds. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(OnConflictsDataFetched, - std::move(on_conflicts_data_fetched_callback_), - std::move(results), kNonGoogleChromeBuild)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(OnConflictsDataFetched, + std::move(on_conflicts_data_fetched_callback_), + std::move(results), kNonGoogleChromeBuild)); #endif } diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc index 55b5fc5ef3e..013e61657b4 100644 --- a/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc +++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc @@ -13,8 +13,7 @@ #include "content/public/browser/web_ui.h" ConflictsHandler::ConflictsHandler() - : conflicts_data_fetcher_(nullptr, base::OnTaskRunnerDeleter(nullptr)), - weak_ptr_factory_(this) {} + : conflicts_data_fetcher_(nullptr, base::OnTaskRunnerDeleter(nullptr)) {} ConflictsHandler::~ConflictsHandler() = default; diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h index 35f4dcc7d36..e10db79f2a0 100644 --- a/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h +++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h @@ -40,7 +40,7 @@ class ConflictsHandler : public content::WebUIMessageHandler { // lives on a different sequence. ConflictsDataFetcher::UniquePtr conflicts_data_fetcher_; - base::WeakPtrFactory<ConflictsHandler> weak_ptr_factory_; + base::WeakPtrFactory<ConflictsHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ConflictsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/crashes_ui.cc b/chromium/chrome/browser/ui/webui/crashes_ui.cc index 9dbca7c9102..d150c2cc8d5 100644 --- a/chromium/chrome/browser/ui/webui/crashes_ui.cc +++ b/chromium/chrome/browser/ui/webui/crashes_ui.cc @@ -46,16 +46,17 @@ content::WebUIDataSource* CreateCrashesUIHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUICrashesHost); - for (size_t i = 0; i < crash::kCrashesUILocalizedStringsCount; ++i) { + for (size_t i = 0; i < crash_reporter::kCrashesUILocalizedStringsCount; ++i) { source->AddLocalizedString( - crash::kCrashesUILocalizedStrings[i].name, - crash::kCrashesUILocalizedStrings[i].resource_id); + crash_reporter::kCrashesUILocalizedStrings[i].name, + crash_reporter::kCrashesUILocalizedStrings[i].resource_id); } - source->AddLocalizedString(crash::kCrashesUIShortProductName, + source->AddLocalizedString(crash_reporter::kCrashesUIShortProductName, IDS_SHORT_PRODUCT_NAME); - source->SetJsonPath("strings.js"); - source->AddResourcePath(crash::kCrashesUICrashesJS, IDR_CRASH_CRASHES_JS); + source->UseStringsJs(); + source->AddResourcePath(crash_reporter::kCrashesUICrashesJS, + IDR_CRASH_CRASHES_JS); source->SetDefaultResource(IDR_CRASH_CRASHES_HTML); return source; } @@ -112,19 +113,19 @@ void CrashesDOMHandler::RegisterMessages() { upload_list_->Load(base::BindOnce(&CrashesDOMHandler::OnUploadListAvailable, base::Unretained(this))); web_ui()->RegisterMessageCallback( - crash::kCrashesUIRequestCrashList, + crash_reporter::kCrashesUIRequestCrashList, base::BindRepeating(&CrashesDOMHandler::HandleRequestCrashes, base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( - crash::kCrashesUIRequestCrashUpload, + crash_reporter::kCrashesUIRequestCrashUpload, base::BindRepeating(&CrashesDOMHandler::HandleRequestUploads, base::Unretained(this))); #endif web_ui()->RegisterMessageCallback( - crash::kCrashesUIRequestSingleCrashUpload, + crash_reporter::kCrashesUIRequestSingleCrashUpload, base::BindRepeating(&CrashesDOMHandler::HandleRequestSingleCrashUpload, base::Unretained(this))); } @@ -183,7 +184,7 @@ void CrashesDOMHandler::UpdateUI() { base::ListValue crash_list; if (upload_list) - crash::UploadListToValue(upload_list_.get(), &crash_list); + crash_reporter::UploadListToValue(upload_list_.get(), &crash_list); base::Value enabled(crash_reporting_enabled); base::Value dynamic_backend(system_crash_reporter); @@ -199,8 +200,8 @@ void CrashesDOMHandler::UpdateUI() { args.push_back(&crash_list); args.push_back(&version); args.push_back(&os_string); - web_ui()->CallJavascriptFunctionUnsafe(crash::kCrashesUIUpdateCrashList, - args); + web_ui()->CallJavascriptFunctionUnsafe( + crash_reporter::kCrashesUIUpdateCrashList, args); } void CrashesDOMHandler::HandleRequestSingleCrashUpload( diff --git a/chromium/chrome/browser/ui/webui/device_log_ui.cc b/chromium/chrome/browser/ui/webui/device_log_ui.cc index 1eb85455185..f30a8f8c9ae 100644 --- a/chromium/chrome/browser/ui/webui/device_log_ui.cc +++ b/chromium/chrome/browser/ui/webui/device_log_ui.cc @@ -91,7 +91,7 @@ DeviceLogUI::DeviceLogUI(content::WebUI* web_ui) }; AddLocalizedStringsBulk(html, kStrings, base::size(kStrings)); - html->SetJsonPath("strings.js"); + html->UseStringsJs(); html->AddResourcePath("device_log_ui.css", IDR_DEVICE_LOG_UI_CSS); html->AddResourcePath("device_log_ui.js", IDR_DEVICE_LOG_UI_JS); html->SetDefaultResource(IDR_DEVICE_LOG_UI_HTML); diff --git a/chromium/chrome/browser/ui/webui/devtools_ui.cc b/chromium/chrome/browser/ui/webui/devtools_ui.cc index a9cc1d845e7..5217a31c8d6 100644 --- a/chromium/chrome/browser/ui/webui/devtools_ui.cc +++ b/chromium/chrome/browser/ui/webui/devtools_ui.cc @@ -4,407 +4,16 @@ #include "chrome/browser/ui/webui/devtools_ui.h" -#include <list> -#include <utility> - -#include "base/bind.h" -#include "base/command_line.h" -#include "base/files/file_util.h" -#include "base/macros.h" -#include "base/memory/ref_counted_memory.h" -#include "base/path_service.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/task/post_task.h" #include "chrome/browser/devtools/url_constants.h" -#include "chrome/common/chrome_paths.h" +#include "chrome/browser/ui/webui/devtools_ui_data_source.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/devtools_frontend_host.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/user_agent.h" -#include "net/base/filename_util.h" #include "net/base/load_flags.h" -#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/blink/public/public_buildflags.h" - -using content::BrowserThread; -using content::WebContents; - -namespace { - -std::string PathWithoutParams(const std::string& path) { - return GURL(std::string("devtools://devtools/") + path).path().substr(1); -} - -scoped_refptr<base::RefCountedMemory> CreateNotFoundResponse() { - const char kHttpNotFound[] = "HTTP/1.1 404 Not Found\n\n"; - return base::MakeRefCounted<base::RefCountedStaticMemory>( - kHttpNotFound, strlen(kHttpNotFound)); -} - -// DevToolsDataSource --------------------------------------------------------- - -std::string GetMimeTypeForPath(const std::string& path) { - std::string filename = PathWithoutParams(path); - if (base::EndsWith(filename, ".html", base::CompareCase::INSENSITIVE_ASCII)) { - return "text/html"; - } else if (base::EndsWith(filename, ".css", - base::CompareCase::INSENSITIVE_ASCII)) { - return "text/css"; - } else if (base::EndsWith(filename, ".js", - base::CompareCase::INSENSITIVE_ASCII)) { - return "application/javascript"; - } else if (base::EndsWith(filename, ".png", - base::CompareCase::INSENSITIVE_ASCII)) { - return "image/png"; - } else if (base::EndsWith(filename, ".gif", - base::CompareCase::INSENSITIVE_ASCII)) { - return "image/gif"; - } else if (base::EndsWith(filename, ".svg", - base::CompareCase::INSENSITIVE_ASCII)) { - return "image/svg+xml"; - } else if (base::EndsWith(filename, ".manifest", - base::CompareCase::INSENSITIVE_ASCII)) { - return "text/cache-manifest"; - } - return "text/html"; -} - -// An URLDataSource implementation that handles devtools://devtools/ -// requests. Three types of requests could be handled based on the URL path: -// 1. /bundled/: bundled DevTools frontend is served. -// 2. /remote/: remote DevTools frontend is served from App Engine. -// 3. /custom/: custom DevTools frontend is served from the server as specified -// by the --custom-devtools-frontend flag. -class DevToolsDataSource : public content::URLDataSource { - public: - using GotDataCallback = content::URLDataSource::GotDataCallback; - - explicit DevToolsDataSource( - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) - : url_loader_factory_(std::move(url_loader_factory)) {} - ~DevToolsDataSource() override = default; - - // content::URLDataSource implementation. - std::string GetSource() override; - - void StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const GotDataCallback& callback) override; - - private: - struct PendingRequest; - - // content::URLDataSource overrides. - std::string GetMimeType(const std::string& path) override; - bool ShouldAddContentSecurityPolicy() override; - bool ShouldDenyXFrameOptions() override; - bool ShouldServeMimeTypeAsContentTypeHeader() override; - - void OnLoadComplete(std::list<PendingRequest>::iterator request_iter, - std::unique_ptr<std::string> response_body); - - // Serves bundled DevTools frontend from ResourceBundle. - void StartBundledDataRequest(const std::string& path, - const GotDataCallback& callback); - - // Serves remote DevTools frontend from hard-coded App Engine domain. - void StartRemoteDataRequest(const GURL& url, const GotDataCallback& callback); - - // Serves remote DevTools frontend from any endpoint, passed through - // command-line flag. - void StartCustomDataRequest(const GURL& url, - const GotDataCallback& callback); - - void StartNetworkRequest( - const GURL& url, - const net::NetworkTrafficAnnotationTag& traffic_annotation, - int load_flags, - const GotDataCallback& callback); - -#if BUILDFLAG(DEBUG_DEVTOOLS) - void StartFileRequestForDebugDevtools(const std::string& path, - const GotDataCallback& callback); -#endif - - struct PendingRequest { - PendingRequest() = default; - PendingRequest(PendingRequest&& other) = default; - PendingRequest& operator=(PendingRequest&& other) = default; - - ~PendingRequest() { - if (callback) - callback.Run(CreateNotFoundResponse()); - } - - GotDataCallback callback; - std::unique_ptr<network::SimpleURLLoader> loader; - - DISALLOW_COPY_AND_ASSIGN(PendingRequest); - }; - - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - std::list<PendingRequest> pending_requests_; - - DISALLOW_COPY_AND_ASSIGN(DevToolsDataSource); -}; - -std::string DevToolsDataSource::GetSource() { - return chrome::kChromeUIDevToolsHost; -} - -void DevToolsDataSource::StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const content::URLDataSource::GotDataCallback& callback) { - // Serve request from local bundle. - std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath); - bundled_path_prefix += "/"; - if (base::StartsWith(path, bundled_path_prefix, - base::CompareCase::INSENSITIVE_ASCII)) { - std::string path_without_params = PathWithoutParams(path); - - DCHECK(base::StartsWith(path_without_params, bundled_path_prefix, - base::CompareCase::INSENSITIVE_ASCII)); - std::string path_under_bundled = - path_without_params.substr(bundled_path_prefix.length()); -#if BUILDFLAG(DEBUG_DEVTOOLS) - StartFileRequestForDebugDevtools(path_under_bundled, callback); -#else - StartBundledDataRequest(path_under_bundled, callback); -#endif - return; - } - - // Serve empty page. - std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath); - if (base::StartsWith(path, empty_path_prefix, - base::CompareCase::INSENSITIVE_ASCII)) { - callback.Run(new base::RefCountedStaticMemory()); - return; - } - - // Serve request from remote location. - std::string remote_path_prefix(chrome::kChromeUIDevToolsRemotePath); - remote_path_prefix += "/"; - if (base::StartsWith(path, remote_path_prefix, - base::CompareCase::INSENSITIVE_ASCII)) { - GURL url(kRemoteFrontendBase + path.substr(remote_path_prefix.length())); - - CHECK_EQ(url.host(), kRemoteFrontendDomain); - if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) { - StartRemoteDataRequest(url, callback); - } else { - DLOG(ERROR) << "Refusing to load invalid remote front-end URL"; - callback.Run(CreateNotFoundResponse()); - } - return; - } - - std::string custom_frontend_url = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kCustomDevtoolsFrontend); - - if (custom_frontend_url.empty()) { - callback.Run(NULL); - return; - } - - // Serve request from custom location. - std::string custom_path_prefix(chrome::kChromeUIDevToolsCustomPath); - custom_path_prefix += "/"; - - if (base::StartsWith(path, custom_path_prefix, - base::CompareCase::INSENSITIVE_ASCII)) { - GURL url = GURL(custom_frontend_url + - path.substr(custom_path_prefix.length())); - DCHECK(url.is_valid()); - StartCustomDataRequest(url, callback); - return; - } - - callback.Run(NULL); -} - -std::string DevToolsDataSource::GetMimeType(const std::string& path) { - return GetMimeTypeForPath(path); -} - -bool DevToolsDataSource::ShouldAddContentSecurityPolicy() { - return false; -} - -bool DevToolsDataSource::ShouldDenyXFrameOptions() { - return false; -} - -bool DevToolsDataSource::ShouldServeMimeTypeAsContentTypeHeader() { - return true; -} - -void DevToolsDataSource::StartBundledDataRequest( - const std::string& path, - const content::URLDataSource::GotDataCallback& callback) { - base::StringPiece resource = - content::DevToolsFrontendHost::GetFrontendResource(path); - - DLOG_IF(WARNING, resource.empty()) - << "Unable to find dev tool resource: " << path - << ". If you compiled with debug_devtools=1, try running with " - "--debug-devtools."; - scoped_refptr<base::RefCountedStaticMemory> bytes( - new base::RefCountedStaticMemory(resource.data(), resource.length())); - callback.Run(bytes.get()); -} - -void DevToolsDataSource::StartRemoteDataRequest( - const GURL& url, - const content::URLDataSource::GotDataCallback& callback) { - CHECK(url.is_valid()); - net::NetworkTrafficAnnotationTag traffic_annotation = - net::DefineNetworkTrafficAnnotation("devtools_hard_coded_data_source", R"( - semantics { - sender: "Developer Tools Remote Data Request From Google" - description: - "This service fetches Chromium DevTools front-end files from the " - "cloud for the remote debugging scenario." - trigger: - "When user attaches to mobile phone for debugging." - data: "None" - destination: GOOGLE_OWNED_SERVICE - } - policy { - cookies_allowed: YES - cookies_store: "user" - setting: "This feature cannot be disabled by settings." - chrome_policy { - DeveloperToolsAvailability { - policy_options {mode: MANDATORY} - DeveloperToolsAvailability: 2 - } - } - })"); - - StartNetworkRequest(url, traffic_annotation, net::LOAD_NORMAL, callback); -} - -void DevToolsDataSource::StartCustomDataRequest( - const GURL& url, - const content::URLDataSource::GotDataCallback& callback) { - if (!url.is_valid()) { - callback.Run(CreateNotFoundResponse()); - return; - } - net::NetworkTrafficAnnotationTag traffic_annotation = - net::DefineNetworkTrafficAnnotation("devtools_free_data_source", R"( - semantics { - sender: "Developer Tools Remote Data Request" - description: - "This service fetches Chromium DevTools front-end files from the " - "cloud for the remote debugging scenario. This can only happen if " - "a URL was passed on the commandline via flag " - "'--custom-devtools-frontend'. This URL overrides the default " - "fetching from a Google website, see " - "devtools_hard_coded_data_source." - trigger: - "When command line flag --custom-devtools-frontend is specified " - "and DevTools is opened." - data: "None" - destination: WEBSITE - } - policy { - cookies_allowed: YES - cookies_store: "user" - setting: "This feature cannot be disabled by settings." - chrome_policy { - DeveloperToolsAvailability { - policy_options {mode: MANDATORY} - DeveloperToolsAvailability: 2 - } - } - })"); - - StartNetworkRequest(url, traffic_annotation, net::LOAD_DISABLE_CACHE, - callback); -} - -void DevToolsDataSource::StartNetworkRequest( - const GURL& url, - const net::NetworkTrafficAnnotationTag& traffic_annotation, - int load_flags, - const GotDataCallback& callback) { - auto request = std::make_unique<network::ResourceRequest>(); - request->url = url; - request->load_flags = load_flags; - - auto request_iter = pending_requests_.emplace(pending_requests_.begin()); - request_iter->callback = callback; - request_iter->loader = - network::SimpleURLLoader::Create(std::move(request), traffic_annotation); - request_iter->loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( - url_loader_factory_.get(), - base::BindOnce(&DevToolsDataSource::OnLoadComplete, - base::Unretained(this), request_iter)); -} - -#if BUILDFLAG(DEBUG_DEVTOOLS) -scoped_refptr<base::RefCountedMemory> ReadFile(const base::FilePath& path) { - std::string buffer; - if (!base::ReadFileToString(path, &buffer)) { - LOG(ERROR) << "Failed to read " << path; - return CreateNotFoundResponse(); - } - return base::RefCountedString::TakeString(&buffer); -} - -void DevToolsDataSource::StartFileRequestForDebugDevtools( - const std::string& path, - const GotDataCallback& callback) { - base::FilePath inspector_debug_dir; - if (!base::PathService::Get(chrome::DIR_INSPECTOR_DEBUG, - &inspector_debug_dir)) { - callback.Run(CreateNotFoundResponse()); - return; - } - - DCHECK(!inspector_debug_dir.empty()); - - base::FilePath full_path = inspector_debug_dir.AppendASCII(path); - - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, - base::TaskPriority::USER_VISIBLE}, - // The usage of BindRepeating below is only because the type of - // task callback needs to match that of response callback, which - // is currently a repeating callback. - base::BindRepeating(ReadFile, std::move(full_path)), callback); -} - -#endif // BUILDFLAG(DEBUG_DEVTOOLS) - -void DevToolsDataSource::OnLoadComplete( - std::list<PendingRequest>::iterator request_iter, - std::unique_ptr<std::string> response_body) { - std::move(request_iter->callback) - .Run(response_body - ? base::RefCountedString::TakeString(response_body.get()) - : CreateNotFoundResponse()); - pending_requests_.erase(request_iter); -} - -} // namespace - -// DevToolsUI ----------------------------------------------------------------- // static GURL DevToolsUI::GetProxyURL(const std::string& frontend_url) { diff --git a/chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc b/chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc new file mode 100644 index 00000000000..95e73c57300 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc @@ -0,0 +1,348 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/devtools_ui_data_source.h" + +#include <list> +#include <utility> + +#include "base/bind.h" +#include "base/command_line.h" +#include "base/files/file_util.h" +#include "base/memory/ref_counted_memory.h" +#include "base/path_service.h" +#include "base/strings/strcat.h" +#include "base/task/post_task.h" +#include "chrome/browser/devtools/devtools_ui_bindings.h" +#include "chrome/browser/devtools/url_constants.h" +#include "chrome/common/chrome_paths.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/url_constants.h" +#include "chrome/common/webui_url_constants.h" +#include "content/public/browser/devtools_frontend_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/url_constants.h" +#include "net/base/load_flags.h" +#include "net/traffic_annotation/network_traffic_annotation.h" +#include "services/network/public/cpp/resource_request.h" +#include "url/url_constants.h" + +namespace { + +std::string PathWithoutParams(const std::string& path) { + return GURL(base::StrCat({content::kChromeDevToolsScheme, + url::kStandardSchemeSeparator, + chrome::kChromeUIDevToolsHost})) + .Resolve(path) + .path() + .substr(1); +} + +scoped_refptr<base::RefCountedMemory> CreateNotFoundResponse() { + const char kHttpNotFound[] = "HTTP/1.1 404 Not Found\n\n"; + return base::MakeRefCounted<base::RefCountedStaticMemory>( + kHttpNotFound, strlen(kHttpNotFound)); +} + +// DevToolsDataSource --------------------------------------------------------- + +std::string GetMimeTypeForPath(const std::string& path) { + std::string filename = PathWithoutParams(path); + if (base::EndsWith(filename, ".html", base::CompareCase::INSENSITIVE_ASCII)) { + return "text/html"; + } else if (base::EndsWith(filename, ".css", + base::CompareCase::INSENSITIVE_ASCII)) { + return "text/css"; + } else if (base::EndsWith(filename, ".js", + base::CompareCase::INSENSITIVE_ASCII)) { + return "application/javascript"; + } else if (base::EndsWith(filename, ".png", + base::CompareCase::INSENSITIVE_ASCII)) { + return "image/png"; + } else if (base::EndsWith(filename, ".gif", + base::CompareCase::INSENSITIVE_ASCII)) { + return "image/gif"; + } else if (base::EndsWith(filename, ".svg", + base::CompareCase::INSENSITIVE_ASCII)) { + return "image/svg+xml"; + } else if (base::EndsWith(filename, ".manifest", + base::CompareCase::INSENSITIVE_ASCII)) { + return "text/cache-manifest"; + } + return "text/html"; +} +} // namespace + +DevToolsDataSource::DevToolsDataSource( + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) + : url_loader_factory_(std::move(url_loader_factory)) {} + +DevToolsDataSource::~DevToolsDataSource() {} + +std::string DevToolsDataSource::GetSource() { + return chrome::kChromeUIDevToolsHost; +} + +void DevToolsDataSource::StartDataRequest( + const std::string& path, + const content::WebContents::Getter& wc_getter, + const GotDataCallback& callback) { + // Serve request from local bundle. + std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath); + bundled_path_prefix += "/"; + if (base::StartsWith(path, bundled_path_prefix, + base::CompareCase::INSENSITIVE_ASCII)) { + std::string path_without_params = PathWithoutParams(path); + + DCHECK(base::StartsWith(path_without_params, bundled_path_prefix, + base::CompareCase::INSENSITIVE_ASCII)); + std::string path_under_bundled = + path_without_params.substr(bundled_path_prefix.length()); +#if BUILDFLAG(DEBUG_DEVTOOLS) + StartFileRequestForDebugDevtools(path_under_bundled, callback); +#else + StartBundledDataRequest(path_under_bundled, callback); +#endif + return; + } + + // Serve empty page. + std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath); + if (base::StartsWith(path, empty_path_prefix, + base::CompareCase::INSENSITIVE_ASCII)) { + callback.Run(new base::RefCountedStaticMemory()); + return; + } + + // Serve request from remote location. + std::string remote_path_prefix(chrome::kChromeUIDevToolsRemotePath); + remote_path_prefix += "/"; + if (base::StartsWith(path, remote_path_prefix, + base::CompareCase::INSENSITIVE_ASCII)) { + GURL url(kRemoteFrontendBase + path.substr(remote_path_prefix.length())); + + CHECK_EQ(url.host(), kRemoteFrontendDomain); + if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) { + StartRemoteDataRequest(url, callback); + } else { + DLOG(ERROR) << "Refusing to load invalid remote front-end URL"; + callback.Run(CreateNotFoundResponse()); + } + return; + } + + std::string custom_frontend_url = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kCustomDevtoolsFrontend); + + if (custom_frontend_url.empty()) { + callback.Run(nullptr); + return; + } + + // Serve request from custom location. + std::string custom_path_prefix(chrome::kChromeUIDevToolsCustomPath); + custom_path_prefix += "/"; + + if (base::StartsWith(path, custom_path_prefix, + base::CompareCase::INSENSITIVE_ASCII)) { + GURL url = + GURL(custom_frontend_url + path.substr(custom_path_prefix.length())); + DCHECK(url.is_valid()); + StartCustomDataRequest(url, callback); + return; + } + + callback.Run(nullptr); +} + +std::string DevToolsDataSource::GetMimeType(const std::string& path) { + return GetMimeTypeForPath(path); +} + +bool DevToolsDataSource::ShouldAddContentSecurityPolicy() { + return false; +} + +bool DevToolsDataSource::ShouldDenyXFrameOptions() { + return false; +} + +bool DevToolsDataSource::ShouldServeMimeTypeAsContentTypeHeader() { + return true; +} + +void DevToolsDataSource::StartBundledDataRequest( + const std::string& path, + const content::URLDataSource::GotDataCallback& callback) { + base::StringPiece resource = + content::DevToolsFrontendHost::GetFrontendResource(path); + + DLOG_IF(WARNING, resource.empty()) + << "Unable to find dev tool resource: " << path + << ". If you compiled with debug_devtools=1, try running with " + "--debug-devtools."; + scoped_refptr<base::RefCountedStaticMemory> bytes( + new base::RefCountedStaticMemory(resource.data(), resource.length())); + callback.Run(bytes.get()); +} + +void DevToolsDataSource::StartRemoteDataRequest( + const GURL& url, + const content::URLDataSource::GotDataCallback& callback) { + CHECK(url.is_valid()); + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("devtools_hard_coded_data_source", + R"( + semantics { + sender: "Developer Tools Remote Data Request From Google" + description: + "This service fetches Chromium DevTools front-end files from the " + "cloud for the remote debugging scenario." + trigger: + "When user attaches to mobile phone for debugging." + data: "None" + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: YES + cookies_store: "user" + setting: "This feature cannot be disabled by settings." + chrome_policy { + DeveloperToolsAvailability { + policy_options {mode: MANDATORY} + DeveloperToolsAvailability: 2 + } + } + })"); + + StartNetworkRequest(url, traffic_annotation, net::LOAD_NORMAL, callback); +} + +void DevToolsDataSource::StartCustomDataRequest( + const GURL& url, + const content::URLDataSource::GotDataCallback& callback) { + if (!url.is_valid()) { + callback.Run(CreateNotFoundResponse()); + return; + } + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("devtools_free_data_source", R"( + semantics { + sender: "Developer Tools Remote Data Request" + description: + "This service fetches Chromium DevTools front-end files from the " + "cloud for the remote debugging scenario. This can only happen if " + "a URL was passed on the commandline via flag " + "'--custom-devtools-frontend'. This URL overrides the default " + "fetching from a Google website, see " + "devtools_hard_coded_data_source." + trigger: + "When command line flag --custom-devtools-frontend is specified " + "and DevTools is opened." + data: "None" + destination: WEBSITE + } + policy { + cookies_allowed: YES + cookies_store: "user" + setting: "This feature cannot be disabled by settings." + chrome_policy { + DeveloperToolsAvailability { + policy_options {mode: MANDATORY} + DeveloperToolsAvailability: 2 + } + } + })"); + + StartNetworkRequest(url, traffic_annotation, net::LOAD_DISABLE_CACHE, + callback); +} + +void DevToolsDataSource::StartNetworkRequest( + const GURL& url, + const net::NetworkTrafficAnnotationTag& traffic_annotation, + int load_flags, + const GotDataCallback& callback) { + auto request = std::make_unique<network::ResourceRequest>(); + request->url = url; + request->load_flags = load_flags; + + auto request_iter = pending_requests_.emplace(pending_requests_.begin()); + request_iter->callback = callback; + request_iter->loader = + network::SimpleURLLoader::Create(std::move(request), traffic_annotation); + request_iter->loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( + url_loader_factory_.get(), + base::BindOnce(&DevToolsDataSource::OnLoadComplete, + base::Unretained(this), request_iter)); +} + +#if BUILDFLAG(DEBUG_DEVTOOLS) +scoped_refptr<base::RefCountedMemory> ReadFileForDebugDevTools( + const base::FilePath& path) { + std::string buffer; + if (!base::ReadFileToString(path, &buffer)) { + LOG(ERROR) << "Failed to read " << path; + return CreateNotFoundResponse(); + } + return base::RefCountedString::TakeString(&buffer); +} + +void DevToolsDataSource::StartFileRequestForDebugDevtools( + const std::string& path, + const GotDataCallback& callback) { + base::FilePath inspector_debug_dir; + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kCustomDevtoolsFrontend)) { + inspector_debug_dir = + command_line->GetSwitchValuePath(switches::kCustomDevtoolsFrontend); + // --custom-devtools-frontend may already be used to specify an URL. + // In that case, fall back to the default debug-devtools bundle. + if (!base::PathExists(inspector_debug_dir)) + inspector_debug_dir.clear(); + } + if (inspector_debug_dir.empty() && + !base::PathService::Get(chrome::DIR_INSPECTOR_DEBUG, + &inspector_debug_dir)) { + callback.Run(CreateNotFoundResponse()); + return; + } + + DCHECK(!inspector_debug_dir.empty()); + + base::FilePath full_path = inspector_debug_dir.AppendASCII(path); + + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::MayBlock(), base::ThreadPool(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, + base::TaskPriority::USER_VISIBLE}, + // The usage of BindRepeating below is only because the type of + // task callback needs to match that of response callback, which + // is currently a repeating callback. + base::BindRepeating(ReadFileForDebugDevTools, std::move(full_path)), + callback); +} +#endif // BUILDFLAG(DEBUG_DEVTOOLS) + +void DevToolsDataSource::OnLoadComplete( + std::list<PendingRequest>::iterator request_iter, + std::unique_ptr<std::string> response_body) { + std::move(request_iter->callback) + .Run(response_body + ? base::RefCountedString::TakeString(response_body.get()) + : CreateNotFoundResponse()); + pending_requests_.erase(request_iter); +} + +DevToolsDataSource::PendingRequest::PendingRequest() = default; + +DevToolsDataSource::PendingRequest::PendingRequest(PendingRequest&& other) = + default; + +DevToolsDataSource::PendingRequest::~PendingRequest() { + if (callback) + callback.Run(CreateNotFoundResponse()); +} diff --git a/chromium/chrome/browser/ui/webui/devtools_ui_data_source.h b/chromium/chrome/browser/ui/webui/devtools_ui_data_source.h new file mode 100644 index 00000000000..dddecbcd1ba --- /dev/null +++ b/chromium/chrome/browser/ui/webui/devtools_ui_data_source.h @@ -0,0 +1,101 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_DATA_SOURCE_H_ +#define CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_DATA_SOURCE_H_ + +#include <list> +#include <memory> + +#include "content/public/browser/url_data_source.h" + +#include "base/macros.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "services/network/public/cpp/simple_url_loader.h" +#include "third_party/blink/public/public_buildflags.h" + +class GURL; + +namespace net { +struct NetworkTrafficAnnotationTag; +} + +// An URLDataSource implementation that handles devtools://devtools/ +// requests. Three types of requests could be handled based on the URL path: +// 1. /bundled/: bundled DevTools frontend is served. +// when built with debug_devtools=true, the path can be provided via +// --custom-devtools-frontend. +// 2. /remote/: remote DevTools frontend is served from App Engine. +// 3. /custom/: custom DevTools frontend is served from the server as specified +// by the --custom-devtools-frontend flag. +class DevToolsDataSource : public content::URLDataSource { + public: + using GotDataCallback = content::URLDataSource::GotDataCallback; + + explicit DevToolsDataSource( + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); + ~DevToolsDataSource() override; + + // content::URLDataSource implementation. + std::string GetSource() override; + + void StartDataRequest(const std::string& path, + const content::WebContents::Getter& wc_getter, + const GotDataCallback& callback) override; + + private: + friend class DevToolsUIDataSourceTest; + + struct PendingRequest; + + // content::URLDataSource overrides. + std::string GetMimeType(const std::string& path) override; + bool ShouldAddContentSecurityPolicy() override; + bool ShouldDenyXFrameOptions() override; + bool ShouldServeMimeTypeAsContentTypeHeader() override; + + void OnLoadComplete(std::list<PendingRequest>::iterator request_iter, + std::unique_ptr<std::string> response_body); + + // Serves bundled DevTools frontend from ResourceBundle. + void StartBundledDataRequest(const std::string& path, + const GotDataCallback& callback); + + // Serves remote DevTools frontend from hard-coded App Engine domain. + void StartRemoteDataRequest(const GURL& url, const GotDataCallback& callback); + + // Serves remote DevTools frontend from any endpoint, passed through + // command-line flag. + void StartCustomDataRequest(const GURL& url, const GotDataCallback& callback); + + virtual void StartNetworkRequest( + const GURL& url, + const net::NetworkTrafficAnnotationTag& traffic_annotation, + int load_flags, + const GotDataCallback& callback); + +#if BUILDFLAG(DEBUG_DEVTOOLS) + void StartFileRequestForDebugDevtools(const std::string& path, + const GotDataCallback& callback); +#endif + + struct PendingRequest { + PendingRequest(); + PendingRequest(PendingRequest&& other); + PendingRequest& operator=(PendingRequest&& other) = default; + ~PendingRequest(); + + GotDataCallback callback; + std::unique_ptr<network::SimpleURLLoader> loader; + + DISALLOW_COPY_AND_ASSIGN(PendingRequest); + }; + + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; + std::list<PendingRequest> pending_requests_; + + DISALLOW_COPY_AND_ASSIGN(DevToolsDataSource); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_DATA_SOURCE_H_ diff --git a/chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc b/chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc new file mode 100644 index 00000000000..323ce84efc3 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc @@ -0,0 +1,235 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/devtools_ui_data_source.h" + +#include <memory> + +#include "base/bind.h" +#include "base/memory/ref_counted_memory.h" +#include "base/strings/strcat.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/url_constants.h" +#include "content/public/browser/url_data_source.h" +#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +constexpr char kDevToolsUITestFrontEndUrl[] = "/devtools_app.html"; +constexpr char kDevToolsUITest404Response[] = "HTTP/1.1 404 Not Found"; + +GURL DevToolsUrl() { + return GURL(base::StrCat({content::kChromeDevToolsScheme, + url::kStandardSchemeSeparator, + chrome::kChromeUIDevToolsHost})); +} + +std::string DevToolsBundledPath(const std::string& path) { + return base::StrCat({chrome::kChromeUIDevToolsBundledPath, path}); +} + +std::string DevToolsRemotePath(const std::string& path) { + return base::StrCat({chrome::kChromeUIDevToolsRemotePath, path}); +} + +std::string DevToolsCustomPath(const std::string& path) { + return base::StrCat({chrome::kChromeUIDevToolsCustomPath, path}); +} + +} // namespace + +class TestDevToolsDataSource : public DevToolsDataSource { + public: + TestDevToolsDataSource() : DevToolsDataSource(nullptr) {} + ~TestDevToolsDataSource() override {} + + void StartNetworkRequest( + const GURL& url, + const net::NetworkTrafficAnnotationTag& traffic_annotation, + int load_flags, + const GotDataCallback& callback) override { + std::string copy_of_url = url.spec(); + callback.Run(base::RefCountedString::TakeString(©_of_url)); + } +}; + +class DevToolsUIDataSourceTest : public testing::Test { + protected: + DevToolsUIDataSourceTest() {} + ~DevToolsUIDataSourceTest() override = default; + + void SetUp() override { + devtools_data_source_ = std::make_unique<TestDevToolsDataSource>(); + } + + void TearDown() override { devtools_data_source_.reset(); } + + TestDevToolsDataSource* data_source() const { + return devtools_data_source_.get(); + } + + bool data_received() const { return data_received_; } + + std::string data() const { return data_; } + + void StartRequest(const std::string& path) { + data_received_ = false; + data_.clear(); + std::string trimmed_path = path.substr(1); + content::WebContents::Getter wc_getter; + data_source()->StartDataRequest( + trimmed_path, std::move(wc_getter), + base::BindRepeating(&DevToolsUIDataSourceTest::OnDataReceived, + base::Unretained(this))); + } + + private: + void OnDataReceived(scoped_refptr<base::RefCountedMemory> bytes) { + data_received_ = true; + if (bytes.get() != nullptr) { + data_ = base::StringPiece(reinterpret_cast<const char*>(bytes->front()), + bytes->size()) + .as_string(); + } + } + + std::unique_ptr<TestDevToolsDataSource> devtools_data_source_; + bool data_received_ = false; + std::string data_; + + DISALLOW_COPY_AND_ASSIGN(DevToolsUIDataSourceTest); +}; + +// devtools/bundled path. + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsBundledURL) { + const GURL path = + DevToolsUrl().Resolve(DevToolsBundledPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_FALSE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsBundledURLWithQueryParam) { + const GURL path = + DevToolsUrl().Resolve(DevToolsBundledPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path() + "?foo"); + EXPECT_TRUE(data_received()); + EXPECT_FALSE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsInvalidBundledURL) { + const GURL path = + DevToolsUrl().Resolve(DevToolsBundledPath("invalid_devtools_app.html")); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsInvalidBundledURLWithQueryParam) { + const GURL path = + DevToolsUrl().Resolve(DevToolsBundledPath("invalid_devtools_app.html")); + StartRequest(path.path() + "?foo"); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +// devtools/blank path + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsBlankURL) { + const GURL path = DevToolsUrl().Resolve(chrome::kChromeUIDevToolsBlankPath); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsBlankURLWithQueryParam) { + const GURL path = DevToolsUrl().Resolve(chrome::kChromeUIDevToolsBlankPath); + StartRequest(path.path() + "?foo"); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +// devtools/remote path + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsRemoteURL) { + const GURL path = + DevToolsUrl().Resolve(DevToolsRemotePath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_EQ(data(), + "https://chrome-devtools-frontend.appspot.com/devtools_app.html"); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsRemoteURLWithQueryParam) { + const GURL path = + DevToolsUrl().Resolve(DevToolsRemotePath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path() + "?foo"); + EXPECT_TRUE(data_received()); + ASSERT_TRUE(base::StartsWith(data(), kDevToolsUITest404Response, + base::CompareCase::SENSITIVE)); +} + +// devtools/custom path. + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsCustomURLWithNoSwitch) { + const GURL path = + DevToolsUrl().Resolve(DevToolsCustomPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsCustomURLWithSwitch) { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kCustomDevtoolsFrontend, "http://localhost:8090/front_end/"); + const GURL path = + DevToolsUrl().Resolve(DevToolsCustomPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_EQ(data(), "http://localhost:8090/front_end/devtools_app.html"); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsCustomURLWithSwitchAndQueryParam) { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kCustomDevtoolsFrontend, "http://localhost:8090/front_end/"); + const GURL path = + DevToolsUrl().Resolve(DevToolsCustomPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path() + "?foo"); + EXPECT_TRUE(data_received()); + EXPECT_EQ(data(), "http://localhost:8090/front_end/devtools_app.html?foo"); +} + +#if !DCHECK_IS_ON() +TEST_F(DevToolsUIDataSourceTest, + TestDevToolsCustomURLWithSwitchAndInvalidServerURL) { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kCustomDevtoolsFrontend, "invalid-server-url"); + const GURL path = + DevToolsUrl().Resolve(DevToolsCustomPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + ASSERT_TRUE(base::StartsWith(data(), kDevToolsUITest404Response, + base::CompareCase::SENSITIVE)); +} +#endif + +// devtools path (i.e. no route specified). + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsNoRoute) { + const GURL path = DevToolsUrl().Resolve(kDevToolsUITestFrontEndUrl); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsNoRouteWithSwitch) { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kCustomDevtoolsFrontend, "invalid-server-url"); + const GURL path = DevToolsUrl().Resolve(kDevToolsUITestFrontEndUrl); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} diff --git a/chromium/chrome/browser/ui/webui/discards/DEPS b/chromium/chrome/browser/ui/webui/discards/DEPS index f452a3a9db6..b6e5e564456 100644 --- a/chromium/chrome/browser/ui/webui/discards/DEPS +++ b/chromium/chrome/browser/ui/webui/discards/DEPS @@ -1,5 +1,10 @@ specific_include_rules = { + # TODO(siggi): Move WebUIGraphDumpImpl into this directory and kill these + # include rules. "discards_ui.h": [ "+chrome/browser/performance_manager/webui_graph_dump.mojom.h", ], + "discards_ui.cc": [ + "+chrome/browser/performance_manager/webui_graph_dump_impl.h", + ], } diff --git a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc index 597f062d388..04bc887b3d3 100644 --- a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc +++ b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc @@ -15,6 +15,7 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/performance_manager/performance_manager.h" +#include "chrome/browser/performance_manager/webui_graph_dump_impl.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/resource_coordinator/lifecycle_unit.h" #include "chrome/browser/resource_coordinator/lifecycle_unit_state.mojom.h" @@ -464,6 +465,9 @@ void DiscardsUI::BindWebUIGraphDumpProvider( performance_manager::PerformanceManager::GetInstance(); if (performance_manager) { // Forward the interface request directly to the service. - performance_manager->BindInterface(std::move(request)); + performance_manager->CallOnGraph( + FROM_HERE, + base::BindOnce(&performance_manager::WebUIGraphDumpImpl::CreateAndBind, + std::move(request))); } } diff --git a/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc b/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc index f8ba443b977..10c8baf3813 100644 --- a/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc @@ -23,7 +23,7 @@ DownloadInternalsUI::DownloadInternalsUI(content::WebUI* web_ui) "script-src chrome://resources 'self' 'unsafe-eval';"); // Required resources. - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->AddResourcePath("download_internals.css", IDR_DOWNLOAD_INTERNALS_CSS); html_source->AddResourcePath("download_internals.js", diff --git a/chromium/chrome/browser/ui/webui/downloads/downloads_dom_handler_unittest.cc b/chromium/chrome/browser/ui/webui/downloads/downloads_dom_handler_unittest.cc index 31e1659b50c..c4935b9397d 100644 --- a/chromium/chrome/browser/ui/webui/downloads/downloads_dom_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/downloads/downloads_dom_handler_unittest.cc @@ -4,16 +4,16 @@ #include "chrome/browser/ui/webui/downloads/downloads_dom_handler.h" -#include <vector> #include <utility> +#include <vector> #include "chrome/browser/download/download_item_model.h" #include "chrome/browser/ui/webui/downloads/downloads.mojom.h" #include "chrome/browser/ui/webui/downloads/mock_downloads_page.h" #include "chrome/test/base/testing_profile.h" #include "components/download/public/common/mock_download_item.h" +#include "content/public/test/browser_task_environment.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" #include "mojo/public/cpp/bindings/binding.h" #include "testing/gmock/include/gmock/gmock.h" @@ -57,7 +57,7 @@ class DownloadsDOMHandlerTest : public testing::Test { private: // NOTE: The initialization order of these members matters. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; testing::NiceMock<content::MockDownloadManager> manager_; diff --git a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc index 8b51693ecd6..4c9e7443170 100644 --- a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc +++ b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc @@ -21,14 +21,13 @@ #include "chrome/browser/download/download_item_model.h" #include "chrome/browser/download/download_query.h" #include "chrome/browser/extensions/api/downloads/downloads_api.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "components/download/public/common/download_danger_type.h" #include "components/download/public/common/download_item.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager.h" -#include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_registry.h" #include "net/base/filename_util.h" #include "third_party/icu/source/i18n/unicode/datefmt.h" #include "ui/base/l10n/time_format.h" @@ -224,13 +223,11 @@ downloads::mojom::DataPtr DownloadsListTracker::CreateDownloadData( // Lookup the extension's current name() in case the user changed their // language. This won't work if the extension was uninstalled, so the name // might be the wrong language. - bool include_disabled = true; auto* profile = Profile::FromBrowserContext( content::DownloadItemUtils::GetBrowserContext(download_item)); - auto* service = - extensions::ExtensionSystem::Get(profile)->extension_service(); - const extensions::Extension* extension = - service->GetExtensionById(by_ext->id(), include_disabled); + auto* registry = extensions::ExtensionRegistry::Get(profile); + const extensions::Extension* extension = registry->GetExtensionById( + by_ext->id(), extensions::ExtensionRegistry::COMPATIBILITY); if (extension) by_ext_name = extension->name(); } @@ -338,8 +335,12 @@ void DownloadsListTracker::SetChunkSizeForTesting(size_t chunk_size) { } bool DownloadsListTracker::ShouldShow(const DownloadItem& item) const { - return !download_crx_util::IsExtensionDownload(item) && !item.IsTemporary() && - !item.IsTransient() && !item.GetFileNameToReportUser().empty() && + return !download_crx_util::IsTrustedExtensionDownload( + Profile::FromBrowserContext( + GetMainNotifierManager()->GetBrowserContext()), + item) && + !item.IsTemporary() && !item.IsTransient() && + !item.GetFileNameToReportUser().empty() && !item.GetTargetFilePath().empty() && !item.GetURL().is_empty() && DownloadItemModel(const_cast<DownloadItem*>(&item)) .ShouldShowInShelf() && @@ -357,8 +358,8 @@ void DownloadsListTracker::Init() { GetMainNotifierManager()->GetBrowserContext()); if (profile->IsOffTheRecord()) { Profile* original_profile = profile->GetOriginalProfile(); - original_notifier_.reset(new download::AllDownloadItemNotifier( - BrowserContext::GetDownloadManager(original_profile), this)); + original_notifier_ = std::make_unique<download::AllDownloadItemNotifier>( + BrowserContext::GetDownloadManager(original_profile), this); } RebuildSortedItems(); diff --git a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker_unittest.cc b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker_unittest.cc index e56ac40279a..00ab6f9573c 100644 --- a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker_unittest.cc +++ b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker_unittest.cc @@ -19,8 +19,8 @@ #include "chrome/browser/ui/webui/downloads/mock_downloads_page.h" #include "chrome/test/base/testing_profile.h" #include "components/download/public/common/mock_download_item.h" +#include "content/public/test/browser_task_environment.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" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -115,7 +115,7 @@ class DownloadsListTrackerTest : public testing::Test { } // NOTE: The initialization order of these members matters. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; testing::NiceMock<content::MockDownloadManager> manager_; diff --git a/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc b/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc index b2b55ef537a..e1c53488cb0 100644 --- a/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc +++ b/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc @@ -16,6 +16,7 @@ #include "chrome/browser/defaults.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/advanced_protection_status_manager.h" +#include "chrome/browser/safe_browsing/advanced_protection_status_manager_factory.h" #include "chrome/browser/ui/webui/downloads/downloads_dom_handler.h" #include "chrome/browser/ui/webui/localized_string.h" #include "chrome/browser/ui/webui/managed_ui_handler.h" @@ -51,8 +52,10 @@ content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIDownloadsHost); - bool requests_ap_verdicts = safe_browsing::AdvancedProtectionStatusManager:: - RequestsAdvancedProtectionVerdicts(profile); + bool requests_ap_verdicts = + safe_browsing::AdvancedProtectionStatusManagerFactory::GetForProfile( + profile) + ->RequestsAdvancedProtectionVerdicts(); source->AddBoolean("requestsApVerdicts", requests_ap_verdicts); static constexpr LocalizedString kStrings[] = { @@ -114,7 +117,7 @@ content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) { // definitions from JS to C++. ui::Accelerator undoAccelerator(ui::VKEY_Z, ui::EF_PLATFORM_ACCELERATOR); source->AddString("undoDescription", l10n_util::GetStringFUTF16( - IDS_DOWNLOAD_UNDO_DESCRIPTION, + IDS_UNDO_DESCRIPTION, undoAccelerator.GetShortcutText())); PrefService* prefs = profile->GetPrefs(); @@ -146,7 +149,7 @@ content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) { source->SetDefaultResource(IDR_DOWNLOADS_DOWNLOADS_HTML); #endif - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } @@ -198,6 +201,6 @@ void DownloadsUI::CreatePageHandler( Profile* profile = Profile::FromWebUI(web_ui()); DownloadManager* dlm = BrowserContext::GetDownloadManager(profile); - page_handler_.reset(new DownloadsDOMHandler(std::move(request), - std::move(page), dlm, web_ui())); + page_handler_ = std::make_unique<DownloadsDOMHandler>( + std::move(request), std::move(page), dlm, web_ui()); } 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 d21545e7601..2c97430d0dc 100644 --- a/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc +++ b/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc @@ -98,6 +98,6 @@ SiteEngagementUI::~SiteEngagementUI() {} void SiteEngagementUI::BindSiteEngagementDetailsProvider( mojom::SiteEngagementDetailsProviderRequest request) { - ui_handler_.reset(new SiteEngagementDetailsProviderImpl( - Profile::FromWebUI(web_ui()), std::move(request))); + ui_handler_ = std::make_unique<SiteEngagementDetailsProviderImpl>( + Profile::FromWebUI(web_ui()), std::move(request)); } diff --git a/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.cc b/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.cc index 255326cda96..661ba823499 100644 --- a/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.cc @@ -45,9 +45,8 @@ ExploreSitesInternalsUI::~ExploreSitesInternalsUI() {} void ExploreSitesInternalsUI::BindExploreSitesInternalsPageHandler( explore_sites_internals::mojom::PageHandlerRequest request) { - page_handler_.reset(new ExploreSitesInternalsPageHandler( - std::move(request), explore_sites_service_, - Profile::FromWebUI(web_ui()))); + page_handler_ = std::make_unique<ExploreSitesInternalsPageHandler>( + std::move(request), explore_sites_service_, Profile::FromWebUI(web_ui())); } } // namespace explore_sites 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 22fee225778..d8295f8e69b 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 @@ -107,8 +107,7 @@ KioskAppsHandler::KioskAppsHandler(OwnerSettingsServiceChromeOS* service) initialized_(false), is_kiosk_enabled_(false), is_auto_launch_enabled_(false), - owner_settings_service_(service), - weak_ptr_factory_(this) {} + owner_settings_service_(service) {} KioskAppsHandler::~KioskAppsHandler() { // TODO(tommycli): This is needed because OnJavascriptDisallowed only called diff --git a/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.h b/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.h index a7d38504888..aeb28325109 100644 --- a/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.h +++ b/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.h @@ -68,7 +68,7 @@ class KioskAppsHandler : public content::WebUIMessageHandler, bool is_kiosk_enabled_; bool is_auto_launch_enabled_; OwnerSettingsServiceChromeOS* const owner_settings_service_; // not owned - base::WeakPtrFactory<KioskAppsHandler> weak_ptr_factory_; + base::WeakPtrFactory<KioskAppsHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(KioskAppsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc index 618914d559b..76e1be57c95 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc @@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/memory/ref_counted_memory.h" +#include "base/memory/scoped_refptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" @@ -45,7 +46,7 @@ namespace extensions { namespace { scoped_refptr<base::RefCountedMemory> BitmapToMemory(const SkBitmap* image) { - base::RefCountedBytes* image_bytes = new base::RefCountedBytes; + auto image_bytes = base::MakeRefCounted<base::RefCountedBytes>(); gfx::PNGCodec::EncodeBGRASkBitmap(*image, false, &image_bytes->data()); return image_bytes; } @@ -114,7 +115,7 @@ std::string ExtensionIconSource::GetMimeType(const std::string&) { void ExtensionIconSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { // This is where everything gets started. First, parse the request and make // the request data available for later. diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h index c7be8dc828f..0737257d85b 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h +++ b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h @@ -72,7 +72,7 @@ class ExtensionIconSource : public content::URLDataSource, std::string GetMimeType(const std::string&) override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; bool AllowCaching() override; 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 7d66742b077..93a7af977c7 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc @@ -91,13 +91,15 @@ void ExtensionSettingsUIBrowserTest::AddManagedPolicyProvider() { } void ExtensionSettingsUIBrowserTest::SetAutoConfirmUninstall() { - uninstall_auto_confirm_.reset(new extensions::ScopedTestDialogAutoConfirm( - extensions::ScopedTestDialogAutoConfirm::ACCEPT)); + uninstall_auto_confirm_ = + std::make_unique<extensions::ScopedTestDialogAutoConfirm>( + extensions::ScopedTestDialogAutoConfirm::ACCEPT); } void ExtensionSettingsUIBrowserTest::EnableErrorConsole() { - error_console_override_.reset(new extensions::FeatureSwitch::ScopedOverride( - extensions::FeatureSwitch::error_console(), true)); + error_console_override_ = + std::make_unique<extensions::FeatureSwitch::ScopedOverride>( + extensions::FeatureSwitch::error_console(), true); } void ExtensionSettingsUIBrowserTest::SetDevModeEnabled(bool enabled) { diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc index 9c1963ef46f..69157d3f489 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc @@ -435,7 +435,7 @@ std::string ExtensionsInternalsSource::GetMimeType(const std::string& path) { void ExtensionsInternalsSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { std::string json = WriteToString(); callback.Run(base::RefCountedString::TakeString(&json)); diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h index 4a8a6cabeaf..0b2840aec47 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h +++ b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h @@ -22,7 +22,7 @@ class ExtensionsInternalsSource : public content::URLDataSource { std::string GetMimeType(const std::string& path) override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; // Simpler interface to generate string output, without needing to diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc index b08cee7d5bd..645cf9d7c67 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc @@ -59,7 +59,7 @@ content::WebUIDataSource* CreateMdExtensionsSource(Profile* profile, bool in_dev_mode) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIExtensionsHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); static constexpr LocalizedString kLocalizedStrings[] = { // Add common strings. @@ -178,6 +178,8 @@ content::WebUIDataSource* CreateMdExtensionsSource(Profile* profile, {"itemSourceUnpacked", IDS_EXTENSIONS_ITEM_SOURCE_UNPACKED}, {"itemSourceWebstore", IDS_EXTENSIONS_ITEM_SOURCE_WEBSTORE}, {"itemVersion", IDS_EXTENSIONS_ITEM_VERSION}, + {"itemReloaded", IDS_EXTENSIONS_ITEM_RELOADED}, + {"itemReloading", IDS_EXTENSIONS_ITEM_RELOADING}, // TODO(dpapad): Replace this with an Extensions specific string. {"itemSize", IDS_DIRECTORY_LISTING_SIZE}, {"itemAllowOnFileUrls", IDS_EXTENSIONS_ALLOW_FILE_ACCESS}, diff --git a/chromium/chrome/browser/ui/webui/favicon_source.cc b/chromium/chrome/browser/ui/webui/favicon_source.cc index 5175c36ac4d..498c9de6242 100644 --- a/chromium/chrome/browser/ui/webui/favicon_source.cc +++ b/chromium/chrome/browser/ui/webui/favicon_source.cc @@ -15,14 +15,11 @@ #include "chrome/browser/history/top_sites_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/instant_io_context.h" -#include "chrome/browser/sync/session_sync_service_factory.h" #include "chrome/common/url_constants.h" #include "chrome/common/webui_url_constants.h" #include "components/favicon/core/history_ui_favicon_request_handler.h" #include "components/favicon_base/favicon_url_parser.h" #include "components/history/core/browser/top_sites.h" -#include "components/sync_sessions/open_tabs_ui_delegate.h" -#include "components/sync_sessions/session_sync_service.h" #include "content/public/browser/web_contents.h" #include "net/url_request/url_request.h" #include "ui/base/layout.h" @@ -38,8 +35,7 @@ namespace { // original URL that started the request, but we're only interested in verifying // if it was issued by a history page, for whom this is the case. If it is not // possible to obtain the URL, we return the empty GURL. -GURL GetUnsafeRequestOrigin( - const content::ResourceRequestInfo::WebContentsGetter& wc_getter) { +GURL GetUnsafeRequestOrigin(const content::WebContents::Getter& wc_getter) { content::WebContents* web_contents = wc_getter.Run(); return web_contents ? web_contents->GetLastCommittedURL() : GURL(); } @@ -80,7 +76,7 @@ std::string FaviconSource::GetSource() { void FaviconSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { favicon::FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(profile_, @@ -97,8 +93,9 @@ void FaviconSource::StartDataRequest( return; } - GURL url(parsed.url); - if (!url.is_valid()) { + GURL page_url(parsed.page_url); + GURL icon_url(parsed.icon_url); + if (!page_url.is_valid() && !icon_url.is_valid()) { SendDefaultResponse(callback); return; } @@ -106,11 +103,13 @@ void FaviconSource::StartDataRequest( int desired_size_in_pixel = std::ceil(parsed.size_in_dip * parsed.device_scale_factor); - if (parsed.is_icon_url) { + if (parsed.page_url.empty()) { + // Request by icon url. + // TODO(michaelbai): Change GetRawFavicon to support combination of // IconType. favicon_service->GetRawFavicon( - url, favicon_base::IconType::kFavicon, desired_size_in_pixel, + icon_url, favicon_base::IconType::kFavicon, desired_size_in_pixel, base::BindRepeating(&FaviconSource::OnFaviconDataAvailable, base::Unretained(this), callback, parsed.size_in_dip, parsed.device_scale_factor), @@ -121,7 +120,7 @@ void FaviconSource::StartDataRequest( TopSitesFactory::GetForProfile(profile_); if (top_sites) { for (const auto& prepopulated_page : top_sites->GetPrepopulatedPages()) { - if (url == prepopulated_page.most_visited.url) { + if (page_url == prepopulated_page.most_visited.url) { ui::ScaleFactor resource_scale_factor = ui::GetSupportedScaleFactor(parsed.device_scale_factor); callback.Run( @@ -142,7 +141,7 @@ void FaviconSource::StartDataRequest( // API and move the explanatory comment for |fallback_to_host| here. const bool fallback_to_host = true; favicon_service->GetRawFaviconForPageURL( - url, {favicon_base::IconType::kFavicon}, desired_size_in_pixel, + page_url, {favicon_base::IconType::kFavicon}, desired_size_in_pixel, fallback_to_host, base::Bind(&FaviconSource::OnFaviconDataAvailable, base::Unretained(this), callback, parsed.size_in_dip, @@ -161,19 +160,14 @@ void FaviconSource::StartDataRequest( SendDefaultResponse(callback); return; } - sync_sessions::SessionSyncService* session_sync_service = - SessionSyncServiceFactory::GetInstance()->GetForProfile(profile_); - sync_sessions::OpenTabsUIDelegate* open_tabs = - session_sync_service->GetOpenTabsUIDelegate(); history_ui_favicon_request_handler->GetRawFaviconForPageURL( - url, desired_size_in_pixel, + page_url, desired_size_in_pixel, base::BindOnce(&FaviconSource::OnFaviconDataAvailable, base::Unretained(this), callback, parsed.size_in_dip, parsed.device_scale_factor), favicon::FaviconRequestPlatform::kDesktop, parsed_history_ui_origin, /*icon_url_for_uma=*/ - open_tabs ? open_tabs->GetIconUrlForPageUrl(url) : GURL(), - &cancelable_task_tracker_); + GURL(parsed.icon_url), &cancelable_task_tracker_); } } @@ -231,7 +225,7 @@ void FaviconSource::SendDefaultResponse( const content::URLDataSource::GotDataCallback& callback, int size_in_dip, float scale_factor) { - const bool dark = GetNativeTheme()->SystemDarkModeEnabled(); + const bool dark = GetNativeTheme()->ShouldUseDarkColors(); int resource_id; switch (size_in_dip) { case 64: diff --git a/chromium/chrome/browser/ui/webui/favicon_source.h b/chromium/chrome/browser/ui/webui/favicon_source.h index d07df2fed51..35e52bab808 100644 --- a/chromium/chrome/browser/ui/webui/favicon_source.h +++ b/chromium/chrome/browser/ui/webui/favicon_source.h @@ -45,7 +45,7 @@ class FaviconSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string&) override; bool AllowCaching() override; diff --git a/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc b/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc index 5639be31fb3..95b83fcd6bc 100644 --- a/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc +++ b/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc @@ -17,9 +17,8 @@ #include "components/favicon/core/test/mock_favicon_service.h" #include "components/favicon_base/favicon_url_parser.h" #include "content/public/browser/browser_context.h" -#include "content/public/browser/resource_request_info.h" #include "content/public/browser/web_contents.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/web_contents_tester.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -27,7 +26,7 @@ #include "ui/resources/grit/ui_resources.h" using GotDataCallback = content::URLDataSource::GotDataCallback; -using WebContentsGetter = content::ResourceRequestInfo::WebContentsGetter; +using WebContentsGetter = content::WebContents::Getter; using testing::_; using testing::Return; using testing::ReturnArg; @@ -141,7 +140,7 @@ class FaviconSourceTestBase : public testing::Test { protected: const scoped_refptr<base::RefCountedBytes> kDummyIconBytes; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; ui::TestNativeTheme theme_; TestingProfile profile_; MockHistoryUiFaviconRequestHandler* mock_history_ui_favicon_request_handler_; @@ -215,7 +214,7 @@ TEST_F(FaviconSourceTestWithFavicon2Format, .Times(0); source()->StartDataRequest( - "?size=16&scale_factor=1x&url_type=page_url&url=https%3A%2F%2Fwww.google." + "?size=16&scale_factor=1x&page_url=https%3A%2F%2Fwww.google." "com&allow_google_server_fallback=0", test_web_contents_getter_, base::BindRepeating(&Noop)); } @@ -230,7 +229,7 @@ TEST_F(FaviconSourceTestWithFavicon2Format, .Times(0); source()->StartDataRequest( - "?size=16&scale_factor=1x&url_type=page_url&url=https%3A%2F%2Fwww.google." + "?size=16&scale_factor=1x&page_url=https%3A%2F%2Fwww.google." "com&allow_google_server_fallback=1", test_web_contents_getter_, base::BindRepeating(&Noop)); } @@ -247,7 +246,7 @@ TEST_F( .Times(1); source()->StartDataRequest( - "?size=16&scale_factor=1x&url_type=page_url&url=https%3A%2F%2Fwww.google." + "?size=16&scale_factor=1x&page_url=https%3A%2F%2Fwww.google." "com&allow_google_server_fallback=1", test_web_contents_getter_, base::BindRepeating(&Noop)); } diff --git a/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc index 77f5faedee6..cbc85825f30 100644 --- a/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc @@ -53,8 +53,7 @@ FeedInternalsPageHandler::FeedInternalsPageHandler( : binding_(this, std::move(request)), feed_scheduler_host_(feed_host_service->GetSchedulerHost()), feed_offline_host_(feed_host_service->GetOfflineHost()), - pref_service_(pref_service), - weak_ptr_factory_(this) {} + pref_service_(pref_service) {} FeedInternalsPageHandler::~FeedInternalsPageHandler() = default; diff --git a/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h b/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h index 67f1327fe9a..2d0352747a4 100644 --- a/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h +++ b/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h @@ -59,7 +59,7 @@ class FeedInternalsPageHandler : public feed_internals::mojom::PageHandler { feed::FeedOfflineHost* feed_offline_host_; PrefService* pref_service_; - base::WeakPtrFactory<FeedInternalsPageHandler> weak_ptr_factory_; + base::WeakPtrFactory<FeedInternalsPageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FeedInternalsPageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/fileicon_source.cc b/chromium/chrome/browser/ui/webui/fileicon_source.cc index 7706c0fffd1..a9e963a94da 100644 --- a/chromium/chrome/browser/ui/webui/fileicon_source.cc +++ b/chromium/chrome/browser/ui/webui/fileicon_source.cc @@ -114,7 +114,7 @@ std::string FileIconSource::GetSource() { void FileIconSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { base::FilePath file_path; IconLoader::IconSize icon_size = IconLoader::NORMAL; diff --git a/chromium/chrome/browser/ui/webui/fileicon_source.h b/chromium/chrome/browser/ui/webui/fileicon_source.h index 38fd7797a60..d607cf1b49b 100644 --- a/chromium/chrome/browser/ui/webui/fileicon_source.h +++ b/chromium/chrome/browser/ui/webui/fileicon_source.h @@ -28,7 +28,7 @@ class FileIconSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string&) override; bool AllowCaching() override; diff --git a/chromium/chrome/browser/ui/webui/fileicon_source_unittest.cc b/chromium/chrome/browser/ui/webui/fileicon_source_unittest.cc index 42dd71a64ce..549f17167eb 100644 --- a/chromium/chrome/browser/ui/webui/fileicon_source_unittest.cc +++ b/chromium/chrome/browser/ui/webui/fileicon_source_unittest.cc @@ -10,7 +10,7 @@ #include "chrome/browser/icon_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/test/base/testing_profile.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,7 +34,7 @@ class FileIconSourceTest : public testing::Test { FileIconSourceTest() = default; private: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; const struct FetchFileIconExpectation { @@ -118,9 +118,7 @@ TEST_F(FileIconSourceTest, FileIconSource_Parse) { base::FilePath(kBasicExpectations[i].unescaped_path), kBasicExpectations[i].scale_factor, kBasicExpectations[i].size, CallbackIsNull())); - source->StartDataRequest( - kBasicExpectations[i].request_path, - content::ResourceRequestInfo::WebContentsGetter(), - callback); + source->StartDataRequest(kBasicExpectations[i].request_path, + content::WebContents::Getter(), callback); } } diff --git a/chromium/chrome/browser/ui/webui/flags_ui.cc b/chromium/chrome/browser/ui/webui/flags_ui.cc index cdf598ea4d3..70df1a343d1 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui.cc +++ b/chromium/chrome/browser/ui/webui/flags_ui.cc @@ -58,9 +58,6 @@ content::WebUIDataSource* CreateFlagsUIHTMLSource() { content::WebUIDataSource::Create(chrome::kChromeUIFlagsHost); source->OverrideContentSecurityPolicyScriptSrc( "script-src chrome://resources 'self' 'unsafe-eval';"); - - source->AddLocalizedString(flags_ui::kFlagsRestartNotice, - IDS_FLAGS_UI_RELAUNCH_NOTICE); source->AddString(flags_ui::kVersion, version_info::GetVersionNumber()); #if defined(OS_CHROMEOS) @@ -69,11 +66,11 @@ content::WebUIDataSource* CreateFlagsUIHTMLSource() { // Set the string to show which user can actually change the flags. std::string owner; chromeos::CrosSettings::Get()->GetString(chromeos::kDeviceOwner, &owner); - source->AddString(flags_ui::kOwnerEmail, base::UTF8ToUTF16(owner)); + source->AddString("owner-warning", + l10n_util::GetStringFUTF16(IDS_FLAGS_UI_OWNER_WARNING, + base::UTF8ToUTF16(owner))); } else { - // The warning will be only shown on ChromeOS, when the current user is not - // the owner. - source->AddString(flags_ui::kOwnerEmail, base::string16()); + source->AddString("owner-warning", base::string16()); } #endif @@ -87,7 +84,8 @@ content::WebUIDataSource* CreateFlagsUIHTMLSource() { // after finishing it the UI can be properly populated. This function is the // callback for whether the owner is signed in. It will respectively pick the // proper PrefService for the flags interface. -void FinishInitialization(base::WeakPtr<FlagsUI> flags_ui, +template <class T> +void FinishInitialization(base::WeakPtr<T> flags_ui, Profile* profile, FlagsUIHandler* dom_handler, bool current_user_is_owner) { @@ -117,9 +115,69 @@ void FinishInitialization(base::WeakPtr<FlagsUI> flags_ui, } // namespace -FlagsUI::FlagsUI(content::WebUI* web_ui) : WebUIController(web_ui) { - Profile* profile = Profile::FromWebUI(web_ui); +// static +void FlagsUI::AddStrings(content::WebUIDataSource* source) { + // Strings added here are all marked a non-translatable, so they are not + // actually localized. + source->AddLocalizedString(flags_ui::kFlagsRestartNotice, + IDS_FLAGS_UI_RELAUNCH_NOTICE); + source->AddLocalizedString("available", IDS_FLAGS_UI_AVAILABLE_FEATURE); + source->AddLocalizedString("clear-search", IDS_FLAGS_UI_CLEAR_SEARCH); + source->AddLocalizedString("disabled", IDS_FLAGS_UI_DISABLED_FEATURE); + source->AddLocalizedString("enabled", IDS_FLAGS_UI_ENABLED_FEATURE); + source->AddLocalizedString("experiment-enabled", + IDS_FLAGS_UI_EXPERIMENT_ENABLED); + source->AddLocalizedString("no-results", IDS_FLAGS_UI_NO_RESULTS); + source->AddLocalizedString("not-available-platform", + IDS_FLAGS_UI_NOT_AVAILABLE_ON_PLATFORM); + source->AddLocalizedString("page-warning", IDS_FLAGS_UI_PAGE_WARNING); + source->AddLocalizedString("page-warning-explanation", + IDS_FLAGS_UI_PAGE_WARNING_EXPLANATION); + source->AddLocalizedString("relaunch", IDS_FLAGS_UI_RELAUNCH); + source->AddLocalizedString("reset", IDS_FLAGS_UI_PAGE_RESET); + source->AddLocalizedString("reset-acknowledged", + IDS_FLAGS_UI_RESET_ACKNOWLEDGED); + source->AddLocalizedString("search-placeholder", + IDS_FLAGS_UI_SEARCH_PLACEHOLDER); + source->AddLocalizedString("title", IDS_FLAGS_UI_TITLE); + source->AddLocalizedString("unavailable", IDS_FLAGS_UI_UNAVAILABLE_FEATURE); +} + +// static +void FlagsDeprecatedUI::AddStrings(content::WebUIDataSource* source) { + source->AddLocalizedString(flags_ui::kFlagsRestartNotice, + IDS_DEPRECATED_FEATURES_RELAUNCH_NOTICE); + source->AddLocalizedString("available", + IDS_DEPRECATED_FEATURES_AVAILABLE_FEATURE); + source->AddLocalizedString("clear-search", IDS_DEPRECATED_UI_CLEAR_SEARCH); + source->AddLocalizedString("disabled", + IDS_DEPRECATED_FEATURES_DISABLED_FEATURE); + source->AddLocalizedString("enabled", + IDS_DEPRECATED_FEATURES_ENABLED_FEATURE); + source->AddLocalizedString("experiment-enabled", + IDS_DEPRECATED_UI_EXPERIMENT_ENABLED); + source->AddLocalizedString("no-results", IDS_DEPRECATED_FEATURES_NO_RESULTS); + source->AddLocalizedString("not-available-platform", + IDS_DEPRECATED_FEATURES_NOT_AVAILABLE_ON_PLATFORM); + source->AddLocalizedString("page-warning", + IDS_DEPRECATED_FEATURES_PAGE_WARNING); + source->AddLocalizedString("page-warning-explanation", + IDS_DEPRECATED_FEATURES_PAGE_WARNING_EXPLANATION); + source->AddLocalizedString("relaunch", IDS_DEPRECATED_FEATURES_RELAUNCH); + source->AddLocalizedString("reset", IDS_DEPRECATED_FEATURES_PAGE_RESET); + source->AddLocalizedString("reset-acknowledged", + IDS_DEPRECATED_UI_RESET_ACKNOWLEDGED); + source->AddLocalizedString("search-placeholder", + IDS_DEPRECATED_FEATURES_SEARCH_PLACEHOLDER); + source->AddLocalizedString("title", IDS_DEPRECATED_FEATURES_TITLE); + source->AddLocalizedString("unavailable", + IDS_DEPRECATED_FEATURES_UNAVAILABLE_FEATURE); +} +template <class T> +FlagsUIHandler* InitializeHandler(content::WebUI* web_ui, + Profile* profile, + base::WeakPtrFactory<T>& weak_factory) { auto handler_owner = std::make_unique<FlagsUIHandler>(); FlagsUIHandler* handler = handler_owner.get(); web_ui->AddMessageHandler(std::move(handler_owner)); @@ -133,11 +191,11 @@ FlagsUI::FlagsUI(content::WebUI* web_ui) : WebUIController(web_ui) { chromeos::OwnerSettingsServiceChromeOS* service = chromeos::OwnerSettingsServiceChromeOSFactory::GetForBrowserContext( original_profile); - service->IsOwnerAsync(base::Bind(&FinishInitialization, - weak_factory_.GetWeakPtr(), + service->IsOwnerAsync(base::Bind(&FinishInitialization<T>, + weak_factory.GetWeakPtr(), original_profile, handler)); } else { - FinishInitialization(weak_factory_.GetWeakPtr(), original_profile, handler, + FinishInitialization(weak_factory.GetWeakPtr(), original_profile, handler, false /* current_user_is_owner */); } #else @@ -145,9 +203,20 @@ FlagsUI::FlagsUI(content::WebUI* web_ui) : WebUIController(web_ui) { new flags_ui::PrefServiceFlagsStorage(g_browser_process->local_state()), flags_ui::kOwnerAccessToFlags); #endif + return handler; +} + +FlagsUI::FlagsUI(content::WebUI* web_ui) + : WebUIController(web_ui), weak_factory_(this) { + Profile* profile = Profile::FromWebUI(web_ui); + auto* handler = InitializeHandler(web_ui, profile, weak_factory_); + DCHECK(handler); + handler->set_deprecated_features_only(false); // Set up the about:flags source. - content::WebUIDataSource::Add(profile, CreateFlagsUIHTMLSource()); + auto* source = CreateFlagsUIHTMLSource(); + AddStrings(source); + content::WebUIDataSource::Add(profile, source); } FlagsUI::~FlagsUI() { @@ -159,3 +228,23 @@ base::RefCountedMemory* FlagsUI::GetFaviconResourceBytes( return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( IDR_FLAGS_FAVICON, scale_factor); } + +FlagsDeprecatedUI::FlagsDeprecatedUI(content::WebUI* web_ui) + : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + auto* handler = InitializeHandler(web_ui, profile, weak_factory_); + DCHECK(handler); + handler->set_deprecated_features_only(true); + + // Set up the about:flags/deprecated source. + auto* source = CreateFlagsUIHTMLSource(); + AddStrings(source); + content::WebUIDataSource::Add(profile, source); +} + +FlagsDeprecatedUI::~FlagsDeprecatedUI() {} + +// static +bool FlagsDeprecatedUI::IsDeprecatedUrl(const GURL& url) { + return url.path() == "/deprecated" || url.path() == "/deprecated/"; +} diff --git a/chromium/chrome/browser/ui/webui/flags_ui.h b/chromium/chrome/browser/ui/webui/flags_ui.h index c41991b2f88..3809b15190d 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui.h +++ b/chromium/chrome/browser/ui/webui/flags_ui.h @@ -19,11 +19,16 @@ namespace base { class RefCountedMemory; } +namespace content { +class WebUIDataSource; +} + class FlagsUI : public content::WebUIController { public: explicit FlagsUI(content::WebUI* web_ui); ~FlagsUI() override; + static void AddStrings(content::WebUIDataSource* source); static base::RefCountedMemory* GetFaviconResourceBytes( ui::ScaleFactor scale_factor); @@ -33,4 +38,17 @@ class FlagsUI : public content::WebUIController { DISALLOW_COPY_AND_ASSIGN(FlagsUI); }; +class FlagsDeprecatedUI : public content::WebUIController { + public: + explicit FlagsDeprecatedUI(content::WebUI* web_ui); + ~FlagsDeprecatedUI() override; + + static void AddStrings(content::WebUIDataSource* source); + static bool IsDeprecatedUrl(const GURL& url); + + private: + base::WeakPtrFactory<FlagsDeprecatedUI> weak_factory_{this}; + + DISALLOW_COPY_AND_ASSIGN(FlagsDeprecatedUI); +}; #endif // CHROME_BROWSER_UI_WEBUI_FLAGS_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/flags_ui_handler.cc b/chromium/chrome/browser/ui/webui/flags_ui_handler.cc index 0c03c7a56fa..3661f832926 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/flags_ui_handler.cc @@ -22,7 +22,8 @@ FlagsUIHandler::FlagsUIHandler() : access_(flags_ui::kGeneralAccessFlagsOnly), - experimental_features_requested_(false) {} + experimental_features_requested_(false), + deprecated_features_only_(false) {} FlagsUIHandler::~FlagsUIHandler() {} @@ -72,9 +73,15 @@ void FlagsUIHandler::HandleRequestExperimentalFeatures( std::unique_ptr<base::ListValue> supported_features(new base::ListValue); std::unique_ptr<base::ListValue> unsupported_features(new base::ListValue); - about_flags::GetFlagFeatureEntries(flags_storage_.get(), access_, - supported_features.get(), - unsupported_features.get()); + if (deprecated_features_only_) { + about_flags::GetFlagFeatureEntriesForDeprecatedPage( + flags_storage_.get(), access_, supported_features.get(), + unsupported_features.get()); + } else { + about_flags::GetFlagFeatureEntries(flags_storage_.get(), access_, + supported_features.get(), + unsupported_features.get()); + } results.Set(flags_ui::kSupportedFeatures, std::move(supported_features)); results.Set(flags_ui::kUnsupportedFeatures, std::move(unsupported_features)); @@ -85,10 +92,12 @@ void FlagsUIHandler::HandleRequestExperimentalFeatures( #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS) version_info::Channel channel = chrome::GetChannel(); - results.SetBoolean(flags_ui::kShowBetaChannelPromotion, - channel == version_info::Channel::STABLE); - results.SetBoolean(flags_ui::kShowDevChannelPromotion, - channel == version_info::Channel::BETA); + results.SetBoolean( + flags_ui::kShowBetaChannelPromotion, + channel == version_info::Channel::STABLE && !deprecated_features_only_); + results.SetBoolean( + flags_ui::kShowDevChannelPromotion, + channel == version_info::Channel::BETA && !deprecated_features_only_); #else results.SetBoolean(flags_ui::kShowBetaChannelPromotion, false); results.SetBoolean(flags_ui::kShowDevChannelPromotion, false); diff --git a/chromium/chrome/browser/ui/webui/flags_ui_handler.h b/chromium/chrome/browser/ui/webui/flags_ui_handler.h index 05c6bfd343b..f76e2847a3e 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/flags_ui_handler.h @@ -26,6 +26,12 @@ class FlagsUIHandler : public content::WebUIMessageHandler { // this was called, it calls |HandleRequestExperimentalFeatures| again. void Init(flags_ui::FlagsStorage* flags_storage, flags_ui::FlagAccess access); + // Configures the handler to return either all features or deprecated + // features only. + void set_deprecated_features_only(bool deprecatedFeaturesOnly) { + deprecated_features_only_ = deprecatedFeaturesOnly; + } + // WebUIMessageHandler implementation. void RegisterMessages() override; @@ -48,6 +54,7 @@ class FlagsUIHandler : public content::WebUIMessageHandler { std::unique_ptr<flags_ui::FlagsStorage> flags_storage_; flags_ui::FlagAccess access_; bool experimental_features_requested_; + bool deprecated_features_only_; DISALLOW_COPY_AND_ASSIGN(FlagsUIHandler); }; diff --git a/chromium/chrome/browser/ui/webui/flags_ui_unittest.cc b/chromium/chrome/browser/ui/webui/flags_ui_unittest.cc new file mode 100644 index 00000000000..e5f5a49a5ad --- /dev/null +++ b/chromium/chrome/browser/ui/webui/flags_ui_unittest.cc @@ -0,0 +1,50 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/flags_ui.h" + +#include "base/values.h" +#include "content/public/test/browser_task_environment.h" +#include "content/public/test/test_web_ui_data_source.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +class FlagsUITest : public testing::Test { + public: + FlagsUITest() = default; + + private: + content::TestBrowserThreadBundle bundle_; +}; + +TEST_F(FlagsUITest, IsDeprecatedUrl) { + const struct { + std::string url; + bool is_deprecated; + } expectations[] = { + {"chrome://flags", false}, + {"chrome://flags/no/deprecated", false}, + {"chrome://deprecated", false}, + {"chrome://flags/deprecated", true}, + {"chrome://flags/deprecated/", true}, + {"chrome://flags//deprecated/yes?no", false}, + }; + + for (const auto& expectation : expectations) { + EXPECT_EQ(expectation.is_deprecated, + FlagsDeprecatedUI::IsDeprecatedUrl(GURL(expectation.url))); + } +} + +TEST_F(FlagsUITest, FlagsAndDeprecatedSources) { + std::unique_ptr<content::TestWebUIDataSource> flags_strings = + content::TestWebUIDataSource::Create("A"); + std::unique_ptr<content::TestWebUIDataSource> deprecated_strings = + content::TestWebUIDataSource::Create("B"); + FlagsUI::AddStrings(flags_strings->GetWebUIDataSource()); + FlagsDeprecatedUI::AddStrings(deprecated_strings->GetWebUIDataSource()); + EXPECT_EQ(flags_strings->GetLocalizedStrings()->size(), + deprecated_strings->GetLocalizedStrings()->size()); +} diff --git a/chromium/chrome/browser/ui/webui/foreign_session_handler.cc b/chromium/chrome/browser/ui/webui/foreign_session_handler.cc index 48900ea2404..dc148f71d72 100644 --- a/chromium/chrome/browser/ui/webui/foreign_session_handler.cc +++ b/chromium/chrome/browser/ui/webui/foreign_session_handler.cc @@ -89,6 +89,8 @@ std::unique_ptr<base::DictionaryValue> SessionTabToValue( new base::DictionaryValue()); NewTabUI::SetUrlTitleAndDirection(dictionary.get(), current_navigation.title(), tab_url); + dictionary->SetString("remoteIconUrlForUma", + current_navigation.favicon_url().spec()); dictionary->SetString("type", "tab"); dictionary->SetDouble("timestamp", static_cast<double>(tab.timestamp.ToInternalValue())); diff --git a/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc b/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc index b1e16e87001..6fcce1ae41a 100644 --- a/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc @@ -160,7 +160,7 @@ GCMInternalsUI::GCMInternalsUI(content::WebUI* web_ui) content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUIGCMInternalsHost); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); // Add required resources. html_source->AddResourcePath(gcm_driver::kGcmInternalsCSS, diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc index fd278d7d6c2..55b745814a2 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc +++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc @@ -88,8 +88,6 @@ base::string16 GetConnectionTypeAsUTF16(const chromeos::NetworkState* network) { } if (chromeos::NetworkTypePattern::Ethernet().MatchesType(type)) return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_ETHERNET); - if (chromeos::NetworkTypePattern::Wimax().MatchesType(type)) - return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_WIMAX); if (chromeos::NetworkTypePattern::Mobile().MatchesType(type)) return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_MOBILE_DATA); if (chromeos::NetworkTypePattern::VPN().MatchesType(type)) @@ -252,17 +250,17 @@ void VersionUpdaterCros::GetEolStatus(EolStatusCallback cb) { weak_ptr_factory_.GetWeakPtr(), std::move(cb))); } -void VersionUpdaterCros::OnGetEolStatus(EolStatusCallback cb, - update_engine::EndOfLifeStatus status) { +void VersionUpdaterCros::OnGetEolStatus( + EolStatusCallback cb, + update_engine::EndOfLifeStatus status, + base::Optional<int32_t> number_of_milestones) { std::move(cb).Run(status); } VersionUpdaterCros::VersionUpdaterCros(content::WebContents* web_contents) : context_(web_contents ? web_contents->GetBrowserContext() : nullptr), last_operation_(UpdateEngineClient::UPDATE_STATUS_IDLE), - check_for_update_when_idle_(false), - weak_ptr_factory_(this) { -} + check_for_update_when_idle_(false) {} VersionUpdaterCros::~VersionUpdaterCros() { UpdateEngineClient* update_engine_client = diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h index ec6ea7da17e..3ec09168b97 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h +++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h @@ -59,7 +59,8 @@ class VersionUpdaterCros : public VersionUpdater, // Callback from UpdateEngineClient::GetEolStatus(). void OnGetEolStatus(EolStatusCallback cb, - update_engine::EndOfLifeStatus status); + update_engine::EndOfLifeStatus status, + base::Optional<int32_t> number_of_milestones); // BrowserContext in which the class was instantiated. content::BrowserContext* context_; @@ -73,7 +74,7 @@ class VersionUpdaterCros : public VersionUpdater, // True if an update check should be scheduled when the update engine is idle. bool check_for_update_when_idle_; - base::WeakPtrFactory<VersionUpdaterCros> weak_ptr_factory_; + base::WeakPtrFactory<VersionUpdaterCros> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VersionUpdaterCros); }; diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos_unittest.cc b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos_unittest.cc index a19b61e6e61..850f225d3e7 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos_unittest.cc +++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos_unittest.cc @@ -18,7 +18,7 @@ #include "chromeos/dbus/shill/shill_service_client.h" #include "chromeos/network/network_handler.h" #include "components/user_manager/scoped_user_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/cros_system_api/dbus/service_constants.h" @@ -90,7 +90,7 @@ class VersionUpdaterCrosTest : public ::testing::Test { NetworkHandler::Shutdown(); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<VersionUpdater> version_updater_; FakeUpdateEngineClient* fake_update_engine_client_; // Not owned. diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_win.cc b/chromium/chrome/browser/ui/webui/help/version_updater_win.cc index 7eb104ff796..6467d6e1dca 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_win.cc +++ b/chromium/chrome/browser/ui/webui/help/version_updater_win.cc @@ -40,8 +40,10 @@ void VersionUpdaterWin::OnUpdateCheckComplete( if (new_version.empty()) { // Google Update says that no new version is available. Check to see if a // restart is needed for a previously-applied update to take effect. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::Bind(&upgrade_util::IsUpdatePendingRestart), base::Bind(&VersionUpdaterWin::OnPendingRestartCheck, weak_factory_.GetWeakPtr())); diff --git a/chromium/chrome/browser/ui/webui/history_login_handler.cc b/chromium/chrome/browser/ui/webui/history_login_handler.cc index f8db85e08e6..0c3eb1a4047 100644 --- a/chromium/chrome/browser/ui/webui/history_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/history_login_handler.cc @@ -23,10 +23,10 @@ HistoryLoginHandler::HistoryLoginHandler(const base::Closure& signin_callback) HistoryLoginHandler::~HistoryLoginHandler() {} void HistoryLoginHandler::RegisterMessages() { - profile_info_watcher_.reset(new ProfileInfoWatcher( + profile_info_watcher_ = std::make_unique<ProfileInfoWatcher>( Profile::FromWebUI(web_ui()), base::Bind(&HistoryLoginHandler::ProfileInfoChanged, - base::Unretained(this)))); + base::Unretained(this))); web_ui()->RegisterMessageCallback( "otherDevicesInitialized", @@ -59,6 +59,6 @@ void HistoryLoginHandler::HandleStartSignInFlow( Browser* browser = chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()); browser->window()->ShowAvatarBubbleFromAvatarButton( - BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, signin::ManageAccountsParams(), + BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, signin_metrics::AccessPoint::ACCESS_POINT_RECENT_TABS, false); } diff --git a/chromium/chrome/browser/ui/webui/history_ui.cc b/chromium/chrome/browser/ui/webui/history_ui.cc index 368b995af9a..5f900c0829b 100644 --- a/chromium/chrome/browser/ui/webui/history_ui.cc +++ b/chromium/chrome/browser/ui/webui/history_ui.cc @@ -167,7 +167,7 @@ content::WebUIDataSource* CreateHistoryUIHTMLSource(Profile* profile) { #endif source->SetDefaultResource(IDR_HISTORY_HISTORY_HTML); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } diff --git a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc index 1a5607b50c2..51016ebb1a9 100644 --- a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc +++ b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc @@ -27,7 +27,6 @@ #include "components/safe_browsing/db/database_manager.h" #include "components/security_interstitials/content/origin_policy_ui.h" #include "components/security_interstitials/core/ssl_error_ui.h" -#include "components/supervised_user_error_page/supervised_user_error_page.h" #include "content/public/browser/interstitial_page_delegate.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" @@ -49,6 +48,11 @@ #include "chrome/browser/ssl/captive_portal_blocking_page.h" #endif +#if BUILDFLAG(ENABLE_SUPERVISED_USERS) +#include "chrome/browser/supervised_user/supervised_user_error_page/supervised_user_error_page.h" +#include "chrome/browser/supervised_user/supervised_user_interstitial.h" +#endif + using security_interstitials::TestSafeBrowsingBlockingPageQuiet; namespace { @@ -89,11 +93,13 @@ class InterstitialHTMLSource : public content::URLDataSource { std::string GetContentSecurityPolicyImgSrc() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; private: +#if BUILDFLAG(ENABLE_SUPERVISED_USERS) std::string GetSupervisedUserInterstitialHTML(const std::string& path); +#endif DISALLOW_COPY_AND_ASSIGN(InterstitialHTMLSource); }; @@ -462,7 +468,7 @@ std::string InterstitialHTMLSource::GetContentSecurityPolicyImgSrc() { void InterstitialHTMLSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { content::WebContents* web_contents = wc_getter.Run(); if (!web_contents) { @@ -496,13 +502,15 @@ void InterstitialHTMLSource::StartDataRequest( CreateOriginPolicyInterstitialPage(web_contents)); } - if (path_without_query == "/supervised_user") { - html = GetSupervisedUserInterstitialHTML(path); - } else if (path_without_query == "/quietsafebrowsing") { + if (path_without_query == "/quietsafebrowsing") { TestSafeBrowsingBlockingPageQuiet* blocking_page = CreateSafeBrowsingQuietBlockingPage(web_contents); interstitial_delegate.reset(blocking_page); html = blocking_page->GetHTML(); +#if BUILDFLAG(ENABLE_SUPERVISED_USERS) + } else if (path_without_query == "/supervised_user") { + html = GetSupervisedUserInterstitialHTML(path); +#endif } else if (interstitial_delegate.get()) { html = interstitial_delegate.get()->GetHTMLContents(); } else { @@ -514,6 +522,7 @@ void InterstitialHTMLSource::StartDataRequest( callback.Run(html_bytes.get()); } +#if BUILDFLAG(ENABLE_SUPERVISED_USERS) std::string InterstitialHTMLSource::GetSupervisedUserInterstitialHTML( const std::string& path) { GURL url("https://localhost/" + path); @@ -571,3 +580,4 @@ std::string InterstitialHTMLSource::GetSupervisedUserInterstitialHTML( is_child_account, is_deprecated, reason, g_browser_process->GetApplicationLocale()); } +#endif diff --git a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc index de85f80c7d1..867c83d78ca 100644 --- a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc @@ -150,7 +150,7 @@ IN_PROC_BROWSER_TEST_F(InterstitialUITest, UnwantedSoftwareInterstitialQuiet) { IN_PROC_BROWSER_TEST_F(InterstitialUITest, BillingInterstitialQuiet) { TestInterstitial( GURL("chrome://interstitials/quietsafebrowsing?type=billing"), - "Security error", IDS_BILLING_WEBVIEW_HEADING); + "Page may charge money", IDS_BILLING_WEBVIEW_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, ClientsideMalwareInterstitial) { @@ -167,7 +167,7 @@ IN_PROC_BROWSER_TEST_F(InterstitialUITest, ClientsidePhishingInterstitial) { IN_PROC_BROWSER_TEST_F(InterstitialUITest, BillingInterstitial) { TestInterstitial(GURL("chrome://interstitials/safebrowsing?type=billing"), - "Security error", IDS_BILLING_HEADING); + "Page may charge money", IDS_BILLING_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, CaptivePortalInterstitial) { 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 3f8998adb52..c4b5994f991 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 @@ -19,7 +19,7 @@ #include "base/run_loop.h" #include "base/test/scoped_command_line.h" #include "base/test/scoped_feature_list.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "base/time/default_clock.h" #include "build/build_config.h" #include "chrome/browser/flag_descriptions.h" @@ -38,7 +38,7 @@ #include "components/previews/core/previews_logger.h" #include "components/previews/core/previews_logger_observer.h" #include "components/previews/core/previews_switches.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "mojo/public/cpp/bindings/binding.h" #include "net/base/features.h" #include "net/nqe/effective_connection_type.h" @@ -310,7 +310,7 @@ class InterventionsInternalsPageHandlerTest : public testing::Test { page_.reset(); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; protected: TestingProfileManager profile_manager_; diff --git a/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc b/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc index 858391be7b1..27b07ff974c 100644 --- a/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc @@ -7,7 +7,6 @@ #include <utility> #include "base/bind.h" -#include "chrome/browser/invalidation/deprecated_profile_invalidation_provider_factory.h" #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/invalidation/impl/invalidation_logger.h" @@ -29,13 +28,8 @@ namespace { invalidation::ProfileInvalidationProvider* GetInvalidationProvider( Profile* profile) { - if (base::FeatureList::IsEnabled(invalidation::switches::kFCMInvalidations)) { - return invalidation::ProfileInvalidationProviderFactory::GetForProfile( - profile); - } else { - return invalidation::DeprecatedProfileInvalidationProviderFactory:: - GetForProfile(profile); - } + return invalidation::ProfileInvalidationProviderFactory::GetForProfile( + profile); } } // namespace 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 f422bff9918..4b2a6a713f2 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 @@ -81,7 +81,7 @@ content::WebUIDataSource* CreateLocalDiscoveryHTMLSource() { }; AddLocalizedStringsBulk(source, kStrings, base::size(kStrings)); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->DisableDenyXFrameOptions(); diff --git a/chromium/chrome/browser/ui/webui/managed_ui_handler.cc b/chromium/chrome/browser/ui/webui/managed_ui_handler.cc index 5fd6841ecd7..3d4e6125bbe 100644 --- a/chromium/chrome/browser/ui/webui/managed_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/managed_ui_handler.cc @@ -110,8 +110,12 @@ void ManagedUIHandler::RemoveObservers() { std::unique_ptr<base::DictionaryValue> ManagedUIHandler::GetDataSourceUpdate() const { auto update = std::make_unique<base::DictionaryValue>(); - update->SetKey("managedByOrg", + update->SetKey("browserManagedByOrg", base::Value(chrome::GetManagedUiWebUILabel(profile_))); +#if defined(OS_CHROMEOS) + update->SetKey("deviceManagedByOrg", + base::Value(chrome::GetDeviceManagedUiWebUILabel(profile_))); +#endif update->SetKey("isManaged", base::Value(managed_)); return update; } diff --git a/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc b/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc index f9a4b1b0c37..c165d33a633 100644 --- a/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc @@ -13,7 +13,7 @@ #include "components/policy/core/common/policy_service_impl.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_data_source.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "content/public/test/test_web_ui_data_source.h" #include "testing/gmock/include/gmock/gmock.h" @@ -75,7 +75,7 @@ class ManagedUIHandlerTest : public testing::Test { } private: - content::TestBrowserThreadBundle bundle_; + content::BrowserTaskEnvironment task_environment_; testing::NiceMock<policy::MockConfigurationPolicyProvider> policy_provider_; std::unique_ptr<TestingProfile> profile_; diff --git a/chromium/chrome/browser/ui/webui/management_ui.cc b/chromium/chrome/browser/ui/webui/management_ui.cc index fd0d3cbdde4..cf98a0cd441 100644 --- a/chromium/chrome/browser/ui/webui/management_ui.cc +++ b/chromium/chrome/browser/ui/webui/management_ui.cc @@ -86,6 +86,18 @@ content::WebUIDataSource* CreateManagementUIHtmlSource(Profile* profile) { IDS_MANAGEMENT_EXTENSION_REPORT_PERF_CRASH}, {kManagementExtensionReportUserBrowsingData, IDS_MANAGEMENT_EXTENSION_REPORT_USER_BROWSING_DATA}, + {kThreatProtectionTitle, IDS_MANAGEMENT_THREAT_PROTECTION}, + {kManagementDataLossPreventionName, + IDS_MANAGEMENT_DATA_LOSS_PREVENTION_NAME}, + {kManagementDataLossPreventionPermissions, + IDS_MANAGEMENT_DATA_LOSS_PREVENTION_PERMISSIONS}, + {kManagementMalwareScanningName, IDS_MANAGEMENT_MALWARE_SCANNING_NAME}, + {kManagementMalwareScanningPermissions, + IDS_MANAGEMENT_MALWARE_SCANNING_PERMISSIONS}, + {kManagementEnterpriseReportingName, + IDS_MANAGEMENT_ENTERPRISE_REPORTING_NAME}, + {kManagementEnterpriseReportingPermissions, + IDS_MANAGEMENT_ENTERPRISE_REPORTING_PERMISSIONS}, }; AddLocalizedStringsBulk(source, kLocalizedStrings, @@ -102,7 +114,7 @@ content::WebUIDataSource* CreateManagementUIHtmlSource(Profile* profile) { chrome::kManagedUiLearnMoreUrl); #endif // defined(OS_CHROMEOS) - source->SetJsonPath("strings.js"); + source->UseStringsJs(); // Add required resources. source->AddResourcePath("management_browser_proxy.html", IDR_MANAGEMENT_BROWSER_PROXY_HTML); diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler.cc b/chromium/chrome/browser/ui/webui/management_ui_handler.cc index 329d86573be..6b9e20b4ac9 100644 --- a/chromium/chrome/browser/ui/webui/management_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/management_ui_handler.cc @@ -25,6 +25,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" +#include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" @@ -45,6 +46,7 @@ #include "chrome/browser/chromeos/policy/status_uploader.h" #include "chrome/browser/chromeos/policy/system_log_uploader.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/ui/webui/management_ui_handler_chromeos.h" #include "chrome/grit/chromium_strings.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user_manager.h" @@ -56,6 +58,7 @@ #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" #include "components/policy/core/common/policy_service.h" +#include "components/policy/policy_constants.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension.h" #include "extensions/common/extension_set.h" @@ -95,6 +98,19 @@ const char kManagementExtensionReportPerfCrash[] = const char kManagementExtensionReportUserBrowsingData[] = "managementExtensionReportUserBrowsingData"; +const char kThreatProtectionTitle[] = "threatProtectionTitle"; +const char kManagementDataLossPreventionName[] = + "managementDataLossPreventionName"; +const char kManagementDataLossPreventionPermissions[] = + "managementDataLossPreventionPermissions"; +const char kManagementMalwareScanningName[] = "managementMalwareScanningName"; +const char kManagementMalwareScanningPermissions[] = + "managementMalwareScanningPermissions"; +const char kManagementEnterpriseReportingName[] = + "managementEnterpriseReportingName"; +const char kManagementEnterpriseReportingPermissions[] = + "managementEnterpriseReportingPermissions"; + const char kReportingTypeDevice[] = "device"; const char kReportingTypeExtensions[] = "extensions"; const char kReportingTypeSecurity[] = "security"; @@ -377,6 +393,10 @@ void ManagementUIHandler::RegisterMessages() { base::Unretained(this))); #endif // defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( + "getThreatProtectionInfo", + base::BindRepeating(&ManagementUIHandler::HandleGetThreatProtectionInfo, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "initBrowserReportingInfo", base::BindRepeating(&ManagementUIHandler::HandleInitBrowserReportingInfo, base::Unretained(this))); @@ -560,6 +580,70 @@ base::DictionaryValue ManagementUIHandler::GetContextualManagedData( return response; } +base::Value ManagementUIHandler::GetThreatProtectionInfo( + Profile* profile) const { + base::Value info(base::Value::Type::LIST); + const policy::PolicyService* policy_service = GetPolicyService(); + const auto& chrome_policies = policy_service->GetPolicies( + policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())); + // CheckContentCompliance is a int-enum policy. The accepted values are + // defined in the enum CheckContentComplianceValues. + auto* check_content_compliance_value = + chrome_policies.GetValue(policy::key::kCheckContentCompliance); + if (check_content_compliance_value && + check_content_compliance_value->GetInt() > safe_browsing::CHECK_NONE && + check_content_compliance_value->GetInt() <= + safe_browsing::CHECK_CONTENT_COMPLIANCE_MAX) { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementDataLossPreventionName); + value.SetStringKey("permission", kManagementDataLossPreventionPermissions); + info.GetList().push_back(std::move(value)); + } + + // SendFilesForMalwareCheck is a int-enum policy. The accepted values are + // defined in the enum SendFilesForMalwareCheckValues. + auto* send_files_for_malware_check_value = + chrome_policies.GetValue(policy::key::kSendFilesForMalwareCheck); + if (send_files_for_malware_check_value && + send_files_for_malware_check_value->GetInt() > + safe_browsing::SEND_FILES_DISABLED && + send_files_for_malware_check_value->GetInt() <= + safe_browsing::SEND_FILES_FOR_MALWARE_CHECK_MAX) { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementMalwareScanningName); + value.SetStringKey("permission", kManagementMalwareScanningPermissions); + info.GetList().push_back(std::move(value)); + } + + auto* unsafe_event_reporting_value = + chrome_policies.GetValue(policy::key::kUnsafeEventsReportingEnabled); + if (unsafe_event_reporting_value && unsafe_event_reporting_value->GetBool()) { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementEnterpriseReportingName); + value.SetStringKey("permission", kManagementEnterpriseReportingPermissions); + info.GetList().push_back(std::move(value)); + } + +#if defined(OS_CHROMEOS) + std::string management_domain = GetDeviceDomain(); + if (management_domain.empty()) + management_domain = GetAccountDomain(profile); +#else + std::string management_domain = GetAccountDomain(profile); +#endif // defined(OS_CHROMEOS) + + base::Value result(base::Value::Type::DICTIONARY); + result.SetStringKey("description", + management_domain.empty() + ? l10n_util::GetStringUTF16( + IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION) + : l10n_util::GetStringFUTF16( + IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION_BY, + base::UTF8ToUTF16(management_domain))); + result.SetKey("info", std::move(info)); + return result; +} + policy::PolicyService* ManagementUIHandler::GetPolicyService() const { return Profile::FromWebUI(web_ui()) ->GetProfilePolicyConnector() @@ -579,29 +663,8 @@ void ManagementUIHandler::AsyncUpdateLogo() { g_browser_process->platform_part()->browser_policy_connector_chromeos(); const auto url = connector->GetCustomerLogoURL(); if (!url.empty() && GURL(url) != logo_url_) { - net::NetworkTrafficAnnotationTag traffic_annotation = - net::DefineNetworkTrafficAnnotation("management_ui_customer_logo", R"( - semantics { - sender: "Management UI Handler" - description: - "Download organization logo for visualization on the " - "chrome://management page." - trigger: - "The user managed by organization that provides a company logo " - "in their GSuites account loads the chrome://management page." - data: - "Organization uploaded image URL." - destination: GOOGLE_OWNED_SERVICE - } - policy { - cookies_allowed: NO - setting: - "This feature cannot be disabled by settings, but it is only " - "triggered by a user action." - policy_exception_justification: "Not implemented." - })"); - icon_fetcher_ = - std::make_unique<BitmapFetcher>(GURL(url), this, traffic_annotation); + icon_fetcher_ = std::make_unique<BitmapFetcher>( + GURL(url), this, GetManagementUICustomerLogoAnnotation()); icon_fetcher_->Init( std::string(), net::URLRequest::NEVER_CLEAR_REFERRER, net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES); @@ -750,6 +813,14 @@ void ManagementUIHandler::HandleGetContextualManagedData( std::move(result)); } +void ManagementUIHandler::HandleGetThreatProtectionInfo( + const base::ListValue* args) { + AllowJavascript(); + ResolveJavascriptCallback( + args->GetList()[0] /* callback_id */, + GetThreatProtectionInfo(Profile::FromWebUI(web_ui()))); +} + void ManagementUIHandler::HandleInitBrowserReportingInfo( const base::ListValue* args) { base::Value report_sources(base::Value::Type::LIST); @@ -765,6 +836,11 @@ void ManagementUIHandler::NotifyBrowserReportingInfoUpdated() { FireWebUIListener("browser-reporting-info-updated", report_sources); } +void ManagementUIHandler::NotifyThreatProtectionInfoUpdated() { + FireWebUIListener("threat-protection-info-updated", + GetThreatProtectionInfo(Profile::FromWebUI(web_ui()))); +} + void ManagementUIHandler::OnExtensionLoaded( content::BrowserContext* /*browser_context*/, const extensions::Extension* extension) { @@ -808,6 +884,7 @@ void ManagementUIHandler::OnPolicyUpdated( const policy::PolicyMap& /*current*/) { UpdateManagedState(); NotifyBrowserReportingInfoUpdated(); + NotifyThreatProtectionInfoUpdated(); } void ManagementUIHandler::AddObservers() { diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler.h b/chromium/chrome/browser/ui/webui/management_ui_handler.h index 1d40707ca7c..f06e8d6e58a 100644 --- a/chromium/chrome/browser/ui/webui/management_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/management_ui_handler.h @@ -48,6 +48,14 @@ extern const char kManagementExtensionReportSafeBrowsingWarnings[]; extern const char kManagementExtensionReportPerfCrash[]; extern const char kManagementExtensionReportUserBrowsingData[]; +extern const char kThreatProtectionTitle[]; +extern const char kManagementDataLossPreventionName[]; +extern const char kManagementDataLossPreventionPermissions[]; +extern const char kManagementMalwareScanningName[]; +extern const char kManagementMalwareScanningPermissions[]; +extern const char kManagementEnterpriseReportingName[]; +extern const char kManagementEnterpriseReportingPermissions[]; + extern const char kPolicyKeyReportMachineIdData[]; extern const char kPolicyKeyReportUserIdData[]; extern const char kPolicyKeyReportVersionData[]; @@ -108,6 +116,7 @@ class ManagementUIHandler : public content::WebUIMessageHandler, void AddExtensionReportingInfo(base::Value* report_sources); base::DictionaryValue GetContextualManagedData(Profile* profile); + base::Value GetThreatProtectionInfo(Profile* profile) const; virtual policy::PolicyService* GetPolicyService() const; virtual const extensions::Extension* GetEnabledExtension( const std::string& extensionId) const; @@ -130,6 +139,7 @@ class ManagementUIHandler : public content::WebUIMessageHandler, #endif // defined(OS_CHROMEOS) void HandleGetContextualManagedData(const base::ListValue* args); + void HandleGetThreatProtectionInfo(const base::ListValue* args); void HandleInitBrowserReportingInfo(const base::ListValue* args); void AsyncUpdateLogo(); @@ -138,6 +148,7 @@ class ManagementUIHandler : public content::WebUIMessageHandler, void OnFetchComplete(const GURL& url, const SkBitmap* bitmap) override; void NotifyBrowserReportingInfoUpdated(); + void NotifyThreatProtectionInfoUpdated(); // extensions::ExtensionRegistryObserver implementation. void OnExtensionLoaded(content::BrowserContext* browser_context, diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.cc new file mode 100644 index 00000000000..2702f506396 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.cc @@ -0,0 +1,28 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/management_ui_handler_chromeos.h" + +net::NetworkTrafficAnnotationTag GetManagementUICustomerLogoAnnotation() { + return net::DefineNetworkTrafficAnnotation("management_ui_customer_logo", R"( + semantics { + sender: "Management UI Handler" + description: + "Download organization logo for visualization on the " + "chrome://management page." + trigger: + "The user managed by organization that provides a company logo " + "in their GSuites account loads the chrome://management page." + data: + "Organization uploaded image URL." + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: NO + setting: + "This feature cannot be disabled by settings, but it is only " + "triggered by a user action." + policy_exception_justification: "Not implemented." + })"); +} diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.h b/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.h new file mode 100644 index 00000000000..b2deb928e03 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.h @@ -0,0 +1,12 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_MANAGEMENT_UI_HANDLER_CHROMEOS_H_ +#define CHROME_BROWSER_UI_WEBUI_MANAGEMENT_UI_HANDLER_CHROMEOS_H_ + +#include "net/traffic_annotation/network_traffic_annotation.h" + +net::NetworkTrafficAnnotationTag GetManagementUICustomerLogoAnnotation(); + +#endif // CHROME_BROWSER_UI_WEBUI_MANAGEMENT_UI_HANDLER_CHROMEOS_H_ diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc b/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc index c118fd35680..8541fce2c79 100644 --- a/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc @@ -15,8 +15,9 @@ #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" #include "components/policy/core/common/policy_service.h" +#include "components/policy/policy_constants.h" #include "components/strings/grit/components_strings.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "testing/gmock/include/gmock/gmock.h" @@ -64,6 +65,10 @@ class TestManagementUIHandler : public ManagementUIHandler { return report_sources; } + base::Value GetThreatProtectionInfo(Profile* profile) { + return ManagementUIHandler::GetThreatProtectionInfo(profile); + } + policy::PolicyService* GetPolicyService() const override { return policy_service_; } @@ -101,6 +106,20 @@ class ManagementUIHandlerTests : public testing::Test { policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD, std::make_unique<base::Value>(true), nullptr); } + void SetPolicyValue(const char* policy_key, + policy::PolicyMap& policies, + int value) { + policies.Set(policy_key, policy::POLICY_LEVEL_MANDATORY, + policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD, + std::make_unique<base::Value>(value), nullptr); + } + void SetPolicyValue(const char* policy_key, + policy::PolicyMap& policies, + bool value) { + policies.Set(policy_key, policy::POLICY_LEVEL_MANDATORY, + policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD, + std::make_unique<base::Value>(value), nullptr); + } void ExtractContextualSourceUpdate( const base::DictionaryValue& data, @@ -119,7 +138,7 @@ class ManagementUIHandlerTests : public testing::Test { protected: TestManagementUIHandler handler_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; policy::MockPolicyService policy_service_; policy::PolicyMap empty_policy_map_; base::string16 device_domain_; @@ -606,3 +625,81 @@ TEST_F(ManagementUIHandlerTests, ExtensionReportingInfoPoliciesMerge) { } EXPECT_EQ(reporting_info.GetList().size(), expected_messages.size()); } + +TEST_F(ManagementUIHandlerTests, ThreatReportingInfo) { + policy::PolicyMap chrome_policies; + const policy::PolicyNamespace chrome_policies_namespace = + policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string()); + + TestingProfile::Builder builder_no_domain; + auto profile_no_domain = builder_no_domain.Build(); + + TestingProfile::Builder builder_known_domain; + builder_known_domain.SetProfileName("managed@manager.com"); + auto profile_known_domain = builder_known_domain.Build(); + +#if defined(OS_CHROMEOS) + handler_.SetDeviceDomain(""); +#endif // !defined(OS_CHROMEOS) + + EXPECT_CALL(policy_service_, GetPolicies(chrome_policies_namespace)) + .WillRepeatedly(ReturnRef(chrome_policies)); + + base::DictionaryValue* threat_protection_info = nullptr; + + // When no policies are set, nothing to report. + auto info = handler_.GetThreatProtectionInfo(profile_no_domain.get()); + info.GetAsDictionary(&threat_protection_info); + EXPECT_TRUE(threat_protection_info->FindListKey("info")->GetList().empty()); + EXPECT_EQ( + l10n_util::GetStringUTF16(IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION), + base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description"))); + + // When policies are set to uninteresting values, nothing to report. + SetPolicyValue(policy::key::kCheckContentCompliance, chrome_policies, 0); + SetPolicyValue(policy::key::kSendFilesForMalwareCheck, chrome_policies, 0); + SetPolicyValue(policy::key::kUnsafeEventsReportingEnabled, chrome_policies, + false); + info = handler_.GetThreatProtectionInfo(profile_known_domain.get()); + info.GetAsDictionary(&threat_protection_info); + EXPECT_TRUE(threat_protection_info->FindListKey("info")->GetList().empty()); + EXPECT_EQ( + l10n_util::GetStringFUTF16( + IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION_BY, + base::UTF8ToUTF16("manager.com")), + base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description"))); + + // When policies are set to values that enable the feature, report it. + SetPolicyValue(policy::key::kCheckContentCompliance, chrome_policies, 1); + SetPolicyValue(policy::key::kSendFilesForMalwareCheck, chrome_policies, 2); + SetPolicyValue(policy::key::kUnsafeEventsReportingEnabled, chrome_policies, + true); + info = handler_.GetThreatProtectionInfo(profile_no_domain.get()); + info.GetAsDictionary(&threat_protection_info); + EXPECT_EQ(3u, threat_protection_info->FindListKey("info")->GetList().size()); + EXPECT_EQ( + l10n_util::GetStringUTF16(IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION), + base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description"))); + + base::Value expected_info(base::Value::Type::LIST); + { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementDataLossPreventionName); + value.SetStringKey("permission", kManagementDataLossPreventionPermissions); + expected_info.GetList().push_back(std::move(value)); + } + { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementMalwareScanningName); + value.SetStringKey("permission", kManagementMalwareScanningPermissions); + expected_info.GetList().push_back(std::move(value)); + } + { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementEnterpriseReportingName); + value.SetStringKey("permission", kManagementEnterpriseReportingPermissions); + expected_info.GetList().push_back(std::move(value)); + } + + EXPECT_EQ(expected_info, *threat_protection_info->FindListKey("info")); +} 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 c4172e96053..e6899c4fcc4 100644 --- a/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc +++ b/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc @@ -75,7 +75,7 @@ content::WebUIDataSource* CreateWebRtcLogsUIHTMLSource() { }; AddLocalizedStringsBulk(source, kStrings, base::size(kStrings)); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("webrtc_logs.js", IDR_WEBRTC_LOGS_JS); source->SetDefaultResource(IDR_WEBRTC_LOGS_HTML); return source; diff --git a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc index 30482e50366..6ce8d49549e 100644 --- a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc @@ -205,7 +205,7 @@ void MemoryInternalsDOMHandler::HandleRequestProcessList( const base::ListValue* args) { // This is called on the UI thread, the child process iterator must run on // the IO thread, while the render process iterator must run on the UI thread. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&MemoryInternalsDOMHandler::GetChildProcessesOnIOThread, weak_factory_.GetWeakPtr())); @@ -292,10 +292,9 @@ void MemoryInternalsDOMHandler::GetChildProcessesOnIOThread( } } - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&MemoryInternalsDOMHandler::GetProfiledPids, dom_handler, - std::move(result))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&MemoryInternalsDOMHandler::GetProfiledPids, + dom_handler, std::move(result))); } void MemoryInternalsDOMHandler::GetProfiledPids( @@ -306,7 +305,7 @@ void MemoryInternalsDOMHandler::GetProfiledPids( // The supervisor hasn't started, so return an empty list. if (!supervisor->HasStarted()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&MemoryInternalsDOMHandler::ReturnProcessListOnUIThread, weak_factory_.GetWeakPtr(), std::move(children), diff --git a/chromium/chrome/browser/ui/webui/nacl_ui.cc b/chromium/chrome/browser/ui/webui/nacl_ui.cc index 89228f3b232..1fea3ce2ecc 100644 --- a/chromium/chrome/browser/ui/webui/nacl_ui.cc +++ b/chromium/chrome/browser/ui/webui/nacl_ui.cc @@ -63,7 +63,7 @@ content::WebUIDataSource* CreateNaClUIHTMLSource() { content::WebUIDataSource::Create(chrome::kChromeUINaClHost); source->OverrideContentSecurityPolicyScriptSrc( "script-src chrome://resources 'self' 'unsafe-eval';"); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("about_nacl.css", IDR_ABOUT_NACL_CSS); source->AddResourcePath("about_nacl.js", IDR_ABOUT_NACL_JS); source->SetDefaultResource(IDR_ABOUT_NACL_HTML); @@ -364,8 +364,9 @@ void NaClDomHandler::MaybeRespondToPage() { if (!pnacl_path_validated_) { std::string* version_string = new std::string; - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&CheckPathAndVersion, version_string), base::Bind(&NaClDomHandler::DidCheckPathAndVersion, weak_ptr_factory_.GetWeakPtr(), diff --git a/chromium/chrome/browser/ui/webui/net_export_ui.cc b/chromium/chrome/browser/ui/webui/net_export_ui.cc index c50cd8b8f77..081ef17bf0d 100644 --- a/chromium/chrome/browser/ui/webui/net_export_ui.cc +++ b/chromium/chrome/browser/ui/webui/net_export_ui.cc @@ -61,7 +61,7 @@ content::WebUIDataSource* CreateNetExportHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUINetExportHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath(net_log::kNetExportUIJS, IDR_NET_LOG_NET_EXPORT_JS); source->SetDefaultResource(IDR_NET_LOG_NET_EXPORT_HTML); return source; 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 5cc53f9c7d0..8c5bfd5d3fc 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 @@ -62,7 +62,7 @@ content::WebUIDataSource* CreateNetInternalsHTMLSource() { source->SetDefaultResource(IDR_NET_INTERNALS_INDEX_HTML); source->AddResourcePath("index.js", IDR_NET_INTERNALS_INDEX_JS); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } @@ -381,7 +381,7 @@ void NetInternalsMessageHandler::ImportONCFileToNSSDB( error += network_error; chromeos::onc::CertificateImporterImpl cert_importer( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}), nssdb); + base::CreateSingleThreadTaskRunner({BrowserThread::IO}), nssdb); auto certs = std::make_unique<chromeos::onc::OncParsedCertificates>(certificates); if (certs->has_error()) @@ -435,13 +435,13 @@ void NetInternalsMessageHandler::OnStoreDebugLogs(bool combined, if (file_manager::util::IsUnderNonNativeLocalPath(profile, path)) path = prefs->GetDefaultDownloadDirectoryForProfile(); base::FilePath policies_path = path.Append("policies.json"); - std::string json_policies = policy::GetAllPolicyValuesAsJSON( - web_ui()->GetWebContents()->GetBrowserContext(), - true /* with_user_policies */, false /* with_device_data */, - true /* is_pretty_print */); - base::PostTaskWithTraitsAndReply( + std::string json_policies = + policy::DictionaryPolicyConversions() + .WithBrowserContext(web_ui()->GetWebContents()->GetBrowserContext()) + .ToJSON(); + base::PostTaskAndReply( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::BindOnce(DumpPolicyLogs, policies_path, json_policies), base::BindOnce(&NetInternalsMessageHandler::OnDumpPolicyLogsCompleted, 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 4b93e834575..eab07796c00 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 @@ -231,7 +231,7 @@ void NetInternalsTest::MessageHandler::DnsLookup( NetInternalsTest::NetInternalsTest() : test_server_started_(false) { - message_handler_.reset(new MessageHandler(this)); + message_handler_ = std::make_unique<MessageHandler>(this); } NetInternalsTest::~NetInternalsTest() { diff --git a/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc index 9cca6cc57da..cd4c3f51c07 100644 --- a/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc @@ -37,6 +37,9 @@ void NotificationsInternalsUIMessageHandler::HandleScheduleNotification( const base::ListValue* args) { CHECK_EQ(args->GetList().size(), 4u); notifications::ScheduleParams schedule_params; + schedule_params.deliver_time_start = base::Time::Now(); + schedule_params.deliver_time_end = + base::Time::Now() + base::TimeDelta::FromMinutes(5); notifications::NotificationData data; data.custom_data.emplace("url", args->GetList()[1].GetString()); data.title = base::UTF8ToUTF16(args->GetList()[2].GetString()); 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 eb64fce1c92..abeeef88687 100644 --- a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc +++ b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc @@ -20,9 +20,9 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "chrome/browser/apps/launch_service/launch_service.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/extensions/bookmark_app_extension_util.h" #include "chrome/browser/extensions/crx_installer.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_ui_util.h" @@ -37,12 +37,12 @@ #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/extensions/app_launch_params.h" -#include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/browser/ui/extensions/extension_enable_flow.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/webui/extensions/extension_basic_info.h" #include "chrome/browser/ui/webui/extensions/extension_icon_source.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" +#include "chrome/browser/web_applications/extensions/bookmark_app_finalizer_utils.h" #include "chrome/browser/web_applications/extensions/bookmark_app_util.h" #include "chrome/common/buildflags.h" #include "chrome/common/chrome_switches.h" @@ -488,8 +488,11 @@ void AppLauncherHandler::HandleLaunchApp(const base::ListValue* args) { CHECK(launch_bucket >= 0 && launch_bucket < extension_misc::APP_LAUNCH_BUCKET_BOUNDARY); + Profile* profile = extension_service_->profile(); + const Extension* extension = - extension_service_->GetExtensionById(extension_id, false); + extensions::ExtensionRegistry::Get(profile)->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); // Prompt the user to re-enable the application if disabled. if (!extension) { @@ -497,8 +500,6 @@ void AppLauncherHandler::HandleLaunchApp(const base::ListValue* args) { return; } - Profile* profile = extension_service_->profile(); - WindowOpenDisposition disposition = args->GetSize() > 3 ? webui::GetDispositionFromClick(args, 3) : WindowOpenDisposition::CURRENT_TAB; @@ -526,11 +527,11 @@ void AppLauncherHandler::HandleLaunchApp(const base::ListValue* args) { AppLaunchParams params( profile, extension_id, disposition == WindowOpenDisposition::NEW_WINDOW - ? extensions::LaunchContainer::kLaunchContainerWindow - : extensions::LaunchContainer::kLaunchContainerTab, - disposition, extensions::AppLaunchSource::kSourceNewTabPage); + ? apps::mojom::LaunchContainer::kLaunchContainerWindow + : apps::mojom::LaunchContainer::kLaunchContainerTab, + disposition, apps::mojom::AppLaunchSource::kSourceNewTabPage); params.override_url = override_url; - OpenApplication(params); + apps::LaunchService::Get(profile)->OpenApplication(params); } else { // To give a more "launchy" experience when using the NTP launcher, we close // it automatically. @@ -546,7 +547,8 @@ void AppLauncherHandler::HandleLaunchApp(const base::ListValue* args) { : WindowOpenDisposition::NEW_FOREGROUND_TAB, extensions::AppLaunchSource::kSourceNewTabPage); params.override_url = override_url; - WebContents* new_contents = OpenApplication(params); + WebContents* new_contents = + apps::LaunchService::Get(profile)->OpenApplication(params); // This will also destroy the handler, so do not perform any actions after. if (new_contents != old_contents && browser && @@ -563,7 +565,9 @@ void AppLauncherHandler::HandleSetLaunchType(const base::ListValue* args) { CHECK(args->GetDouble(1, &launch_type)); const Extension* extension = - extension_service_->GetExtensionById(extension_id, true); + extensions::ExtensionRegistry::Get(extension_service_->profile()) + ->GetExtensionById(extension_id, + extensions::ExtensionRegistry::COMPATIBILITY); if (!extension) return; @@ -615,7 +619,9 @@ void AppLauncherHandler::HandleCreateAppShortcut(const base::ListValue* args) { CHECK(args->GetString(0, &extension_id)); const Extension* extension = - extension_service_->GetExtensionById(extension_id, true); + extensions::ExtensionRegistry::Get(extension_service_->profile()) + ->GetExtensionById(extension_id, + extensions::ExtensionRegistry::COMPATIBILITY); if (!extension) return; @@ -631,7 +637,9 @@ void AppLauncherHandler::HandleInstallAppLocally(const base::ListValue* args) { CHECK(args->GetString(0, &extension_id)); const Extension* extension = - extension_service_->GetExtensionById(extension_id, true); + extensions::ExtensionRegistry::Get(extension_service_->profile()) + ->GetExtensionById(extension_id, + extensions::ExtensionRegistry::COMPATIBILITY); if (!extension) return; @@ -654,7 +662,9 @@ void AppLauncherHandler::HandleShowAppInfo(const base::ListValue* args) { CHECK(args->GetString(0, &extension_id)); const Extension* extension = - extension_service_->GetExtensionById(extension_id, true); + extensions::ExtensionRegistry::Get(extension_service_->profile()) + ->GetExtensionById(extension_id, + extensions::ExtensionRegistry::COMPATIBILITY); if (!extension) return; @@ -831,8 +841,8 @@ void AppLauncherHandler::PromptToEnableApp(const std::string& extension_id) { return; // Only one prompt at a time. extension_id_prompting_ = extension_id; - extension_enable_flow_.reset(new ExtensionEnableFlow( - Profile::FromWebUI(web_ui()), extension_id, this)); + extension_enable_flow_ = std::make_unique<ExtensionEnableFlow>( + Profile::FromWebUI(web_ui()), extension_id, this); extension_enable_flow_->StartForWebContents(web_ui()->GetWebContents()); } @@ -862,7 +872,9 @@ void AppLauncherHandler::ExtensionEnableFlowAborted(bool user_initiated) { // We record the histograms here because ExtensionUninstallCanceled is also // called when the extension uninstall dialog is canceled. const Extension* extension = - extension_service_->GetExtensionById(extension_id_prompting_, true); + extensions::ExtensionRegistry::Get(extension_service_->profile()) + ->GetExtensionById(extension_id_prompting_, + extensions::ExtensionRegistry::COMPATIBILITY); std::string histogram_name = user_initiated ? "ReEnableCancel" : "ReEnableAbort"; extensions::ExtensionService::RecordPermissionMessagesHistogram( diff --git a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc index 9102ea06af4..48f2a16a42c 100644 --- a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc +++ b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc @@ -150,7 +150,7 @@ std::string NewTabUI::NewTabHTMLSource::GetSource() { void NewTabUI::NewTabHTMLSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); diff --git a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h index 61e2451c3db..01d668a40d7 100644 --- a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h +++ b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h @@ -57,7 +57,7 @@ class NewTabUI : public content::WebUIController { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string&) override; bool ShouldReplaceExistingSource() override; diff --git a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui.cc b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui.cc index 6b89090bf8a..fd62303ce45 100644 --- a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui.cc @@ -22,7 +22,7 @@ OfflineInternalsUI::OfflineInternalsUI(content::WebUI* web_ui) content::WebUIDataSource::Create(chrome::kChromeUIOfflineInternalsHost); // Required resources. - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->AddResourcePath("offline_internals.css", IDR_OFFLINE_INTERNALS_CSS); html_source->AddResourcePath("offline_internals.js", 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 d8eadc545f5..b1ad92cf59c 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 @@ -82,8 +82,7 @@ std::string GetStringFromSavePageStatus() { OfflineInternalsUIMessageHandler::OfflineInternalsUIMessageHandler() : offline_page_model_(nullptr), request_coordinator_(nullptr), - prefetch_service_(nullptr), - weak_ptr_factory_(this) {} + prefetch_service_(nullptr) {} OfflineInternalsUIMessageHandler::~OfflineInternalsUIMessageHandler() {} diff --git a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h index 09a718680fa..01c291664fe 100644 --- a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h +++ b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h @@ -134,7 +134,8 @@ class OfflineInternalsUIMessageHandler : public content::WebUIMessageHandler { offline_pages::PrefetchService* prefetch_service_; // Factory for creating references in callbacks. - base::WeakPtrFactory<OfflineInternalsUIMessageHandler> weak_ptr_factory_; + base::WeakPtrFactory<OfflineInternalsUIMessageHandler> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(OfflineInternalsUIMessageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom b/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom index de8253d461c..7ffa3971673 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom @@ -31,6 +31,7 @@ struct AutocompleteMatch { array<ACMatchClassification> contents_class; string description; array<ACMatchClassification> description_class; + bool swap_contents_and_description; string answer; string transition; bool allowed_to_be_default_match; @@ -59,12 +60,15 @@ struct OmniboxResponse { string type; string host; bool is_typed_host; + string input_text; array<AutocompleteMatch> combined_results; array<AutocompleteResultsForProvider> results_by_provider; }; interface OmniboxPageHandler { + // Registers the webui page. SetClientPage(OmniboxPage page); + // Prompts a autocopmlete controller to process an omnibox query. StartOmniboxQuery(string input_string, bool reset_autocomplete_controller, int32 cursor_position, @@ -76,8 +80,15 @@ interface OmniboxPageHandler { }; interface OmniboxPage { - handleNewAutocompleteResponse(OmniboxResponse response, - bool isPageController); - HandleNewAutocompleteQuery(bool isPageController, string input_text); + // Notifies the page of an omnibox response from a autocomplete + // controller. |is_page_controller| indicates wether the response + // originates from a query initiated from the page via + // |StartOmniboxQuery| or from the browser omnibox. + HandleNewAutocompleteResponse(OmniboxResponse response, + bool is_page_controller); + // Notifies the page a new omnibox query has begun. + HandleNewAutocompleteQuery(bool is_page_controller, string input_text); + // Asyncronously notifies the page of the image data URLs for previous omnibox + // responses. HandleAnswerImageData(string image_url, string image_data); }; diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc b/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc index 97def4ae86d..3c90ef1508e 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc @@ -174,6 +174,7 @@ struct TypeConverter<mojom::AutocompleteMatchPtr, AutocompleteMatch> { result->description_class = mojo::ConvertTo<std::vector<mojom::ACMatchClassificationPtr>>( input.description_class); + result->swap_contents_and_description = input.swap_contents_and_description; if (input.answer) { result->answer = SuggestionAnswerImageLineToString(input.answer->first_line()) + @@ -254,6 +255,7 @@ void OmniboxPageHandler::OnOmniboxResultChanged( if (!LookupIsTypedHost(host, &is_typed_host)) is_typed_host = false; response->is_typed_host = is_typed_host; + response->input_text = base::UTF16ToUTF8(input_.text()); { // Copy to an ACMatches to make conversion easier. Since this isn't @@ -295,7 +297,7 @@ void OmniboxPageHandler::OnOmniboxResultChanged( image_urls.push_back(result_by_provider.results[j]->image); } - page_->handleNewAutocompleteResponse(std::move(response), + page_->HandleNewAutocompleteResponse(std::move(response), controller == controller_.get()); // Fill in image data @@ -417,7 +419,7 @@ void OmniboxPageHandler::StartOmniboxQuery(const std::string& input_string, } void OmniboxPageHandler::ResetController() { - controller_.reset(new AutocompleteController( + controller_ = std::make_unique<AutocompleteController>( std::make_unique<ChromeAutocompleteProviderClient>(profile_), this, - AutocompleteClassifier::DefaultOmniboxProviders())); + AutocompleteClassifier::DefaultOmniboxProviders()); } diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc index af3ee72c3cd..4e95206d915 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc @@ -9,6 +9,7 @@ #include "base/bind.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/omnibox/omnibox_page_handler.h" +#include "chrome/browser/ui/webui/version_handler.h" #include "chrome/browser/ui/webui/version_ui.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" @@ -16,14 +17,15 @@ #include "content/public/browser/web_ui_controller.h" #include "content/public/browser/web_ui_data_source.h" -OmniboxUI::OmniboxUI(content::WebUI* web_ui) : ui::MojoWebUIController(web_ui) { +OmniboxUI::OmniboxUI(content::WebUI* web_ui) + : ui::MojoWebUIController(web_ui, /*enable_chrome_send=*/true) { // Set up the chrome://omnibox/ source. content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOmniboxHost); // Expose version information to client because it is useful in output. VersionUI::AddVersionDetailStrings(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("omnibox.css", IDR_OMNIBOX_CSS); source->AddResourcePath("omnibox_input.css", IDR_OMNIBOX_INPUT_CSS); @@ -43,6 +45,7 @@ OmniboxUI::OmniboxUI(content::WebUI* web_ui) : ui::MojoWebUIController(web_ui) { content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); AddHandlerToRegistry(base::BindRepeating(&OmniboxUI::BindOmniboxPageHandler, base::Unretained(this))); + web_ui->AddMessageHandler(std::make_unique<VersionHandler>()); } OmniboxUI::~OmniboxUI() {} diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc b/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc deleted file mode 100644 index 5e92515c354..00000000000 --- a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc +++ /dev/null @@ -1,134 +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/password_manager_internals/password_manager_internals_ui.h" - -#include "base/values.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/url_constants.h" -#include "components/autofill/core/browser/logging/log_receiver.h" -#include "components/autofill/core/browser/logging/log_router.h" -#include "components/grit/components_resources.h" -#include "components/password_manager/content/browser/password_manager_log_router_factory.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" -#include "net/base/escape.h" - -using autofill::LogRouter; -using password_manager::PasswordManagerLogRouterFactory; - -namespace { - -content::WebUIDataSource* CreatePasswordManagerInternalsHTMLSource() { - content::WebUIDataSource* source = content::WebUIDataSource::Create( - chrome::kChromeUIPasswordManagerInternalsHost); - source->AddResourcePath("autofill_and_password_manager_internals.js", - IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_JS); - source->AddResourcePath("autofill_and_password_manager_internals.css", - IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_CSS); - source->SetDefaultResource(IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_HTML); - return source; -} - -// chrome://password-manager-internals specific UI handler that takes care of -// subscribing to the autofill logging instance. -class PasswordManagerInternalsUIHandler : public content::WebUIMessageHandler, - public autofill::LogReceiver { - public: - PasswordManagerInternalsUIHandler() = default; - ~PasswordManagerInternalsUIHandler() override; - - private: - // content::WebUIMessageHandler: - void RegisterMessages() override; - - // Implements content::WebUIMessageHandler. - void OnJavascriptAllowed() override; - void OnJavascriptDisallowed() override; - - // LogReceiver implementation. - void LogEntry(const base::Value& entry) override; - - void StartSubscription(); - void EndSubscription(); - - // JavaScript call handler. - void OnLoaded(const base::ListValue* args); - - // Whether |this| is registered as a log receiver with the LogRouter. - bool registered_with_log_router_ = false; - - DISALLOW_COPY_AND_ASSIGN(PasswordManagerInternalsUIHandler); -}; - -PasswordManagerInternalsUIHandler::~PasswordManagerInternalsUIHandler() { - EndSubscription(); -} - -void PasswordManagerInternalsUIHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "loaded", - base::BindRepeating(&PasswordManagerInternalsUIHandler::OnLoaded, - base::Unretained(this))); -} - -void PasswordManagerInternalsUIHandler::OnJavascriptAllowed() { - StartSubscription(); -} - -void PasswordManagerInternalsUIHandler::OnJavascriptDisallowed() { - EndSubscription(); -} - -void PasswordManagerInternalsUIHandler::OnLoaded(const base::ListValue* args) { - AllowJavascript(); - CallJavascriptFunction("setUpPasswordManagerInternals"); - CallJavascriptFunction( - "notifyAboutIncognito", - base::Value(Profile::FromWebUI(web_ui())->IsIncognitoProfile())); -} - -void PasswordManagerInternalsUIHandler::StartSubscription() { - LogRouter* log_router = PasswordManagerLogRouterFactory::GetForBrowserContext( - Profile::FromWebUI(web_ui())); - if (!log_router) - return; - - registered_with_log_router_ = true; - - const auto& past_logs = log_router->RegisterReceiver(this); - for (const auto& entry : past_logs) - LogEntry(entry); -} - -void PasswordManagerInternalsUIHandler::EndSubscription() { - if (!registered_with_log_router_) - return; - registered_with_log_router_ = false; - LogRouter* log_router = PasswordManagerLogRouterFactory::GetForBrowserContext( - Profile::FromWebUI(web_ui())); - if (log_router) - log_router->UnregisterReceiver(this); -} - -void PasswordManagerInternalsUIHandler::LogEntry(const base::Value& entry) { - if (!registered_with_log_router_ || entry.is_none()) - return; - CallJavascriptFunction("addRawLog", entry); -} - -} // namespace - -PasswordManagerInternalsUI::PasswordManagerInternalsUI(content::WebUI* web_ui) - : WebUIController(web_ui) { - Profile* profile = Profile::FromWebUI(web_ui); - content::WebUIDataSource::Add(profile, - CreatePasswordManagerInternalsHTMLSource()); - web_ui->AddMessageHandler( - std::make_unique<PasswordManagerInternalsUIHandler>()); -} - -PasswordManagerInternalsUI::~PasswordManagerInternalsUI() = default; diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc index 85b71b8f5ea..22075e1d920 100644 --- a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc @@ -739,7 +739,7 @@ void PolicyUIHandler::AddCommonLocalizedStringsToSource( }; AddLocalizedStringsBulk(source, kStrings, base::size(kStrings)); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); } void PolicyUIHandler::RegisterMessages() { @@ -923,11 +923,10 @@ base::Value PolicyUIHandler::GetPolicyNames() const { } base::Value PolicyUIHandler::GetPolicyValues() const { - return policy::GetAllPolicyValuesAsArray( - web_ui()->GetWebContents()->GetBrowserContext(), - true /* with_user_policies */, true /* convert_values */, - false /* with_device_data */, true /* is_pretty_print */, - true /* convert_types */); + return policy::ArrayPolicyConversions() + .WithBrowserContext(web_ui()->GetWebContents()->GetBrowserContext()) + .EnableConvertValues(true) + .ToValue(); } void PolicyUIHandler::SendStatus() { @@ -1030,11 +1029,10 @@ void DoWritePoliciesToJSONFile(const base::FilePath& path, void PolicyUIHandler::WritePoliciesToJSONFile( const base::FilePath& path) const { - constexpr bool is_pretty_print = true; - base::Value dict = policy::GetAllPolicyValuesAsDictionary( - web_ui()->GetWebContents()->GetBrowserContext(), - true /* with_user_policies */, false /* convert_values */, - false /* with_device_data */, is_pretty_print, true /* convert_types */); + base::Value dict = + policy::DictionaryPolicyConversions() + .WithBrowserContext(web_ui()->GetWebContents()->GetBrowserContext()) + .ToValue(); base::Value chrome_metadata(base::Value::Type::DICTIONARY); @@ -1085,12 +1083,11 @@ void PolicyUIHandler::WritePoliciesToJSONFile( std::string json_policies; base::JSONWriter::WriteWithOptions( - dict, (is_pretty_print ? base::JSONWriter::OPTIONS_PRETTY_PRINT : 0), - &json_policies); + dict, base::JSONWriter::OPTIONS_PRETTY_PRINT, &json_policies); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::BindOnce(&DoWritePoliciesToJSONFile, path, json_policies)); } diff --git a/chromium/chrome/browser/ui/webui/prefs_internals_source.cc b/chromium/chrome/browser/ui/webui/prefs_internals_source.cc index 382f02f3391..152af756c8d 100644 --- a/chromium/chrome/browser/ui/webui/prefs_internals_source.cc +++ b/chromium/chrome/browser/ui/webui/prefs_internals_source.cc @@ -29,7 +29,7 @@ std::string PrefsInternalsSource::GetMimeType(const std::string& path) { void PrefsInternalsSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string json; diff --git a/chromium/chrome/browser/ui/webui/prefs_internals_source.h b/chromium/chrome/browser/ui/webui/prefs_internals_source.h index d20af558b90..922302643d7 100644 --- a/chromium/chrome/browser/ui/webui/prefs_internals_source.h +++ b/chromium/chrome/browser/ui/webui/prefs_internals_source.h @@ -21,7 +21,7 @@ class PrefsInternalsSource : public content::URLDataSource { std::string GetMimeType(const std::string& path) override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; private: 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 13276fa5968..f1efaf51d10 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 @@ -35,6 +35,7 @@ #include "extensions/browser/api/usb/usb_device_manager.h" #include "extensions/common/extension.h" #include "extensions/common/value_builder.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "printing/pdf_render_settings.h" #include "printing/print_job_constants.h" #include "printing/pwg_raster_settings.h" @@ -507,10 +508,10 @@ class ExtensionPrinterHandlerTest : public testing::Test { std::move(pwg_raster_converter)); // Set fake USB device manager for extensions::UsbDeviceManager. - device::mojom::UsbDeviceManagerPtr usb_manager_ptr; - fake_usb_manager_.AddBinding(mojo::MakeRequest(&usb_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> usb_manager; + fake_usb_manager_.AddReceiver(usb_manager.InitWithNewPipeAndPassReceiver()); extensions::UsbDeviceManager::Get(env_.profile()) - ->SetDeviceManagerForTesting(std::move(usb_manager_ptr)); + ->SetDeviceManagerForTesting(std::move(usb_manager)); base::RunLoop().RunUntilIdle(); } 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 9534da45d8d..9b926a8b629 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 @@ -19,7 +19,6 @@ #include "chrome/browser/chromeos/printing/cups_print_job_manager_factory.h" #include "chrome/browser/chromeos/printing/cups_printers_manager.h" #include "chrome/browser/chromeos/printing/cups_printers_manager_factory.h" -#include "chrome/browser/chromeos/printing/ppd_provider_factory.h" #include "chrome/browser/chromeos/printing/printer_configurer.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" @@ -27,7 +26,6 @@ #include "chrome/common/pref_names.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/prefs/pref_service.h" #include "components/printing/browser/printer_capabilities.h" @@ -83,8 +81,9 @@ void FetchCapabilities(const chromeos::Printer& printer, printer.GetProtocol() == chromeos::Printer::kIpps; // USER_VISIBLE because the result is displayed in the print preview dialog. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&GetSettingsOnBlockingPool, printer.id(), basic_info, PrinterSemanticCapsAndDefaults::Papers(), has_secure_protocol, nullptr), @@ -101,8 +100,7 @@ LocalPrinterHandlerChromeos::LocalPrinterHandlerChromeos( : profile_(profile), preview_web_contents_(preview_web_contents), printers_manager_(printers_manager), - printer_configurer_(std::move(printer_configurer)), - weak_factory_(this) { + printer_configurer_(std::move(printer_configurer)) { // Construct the CupsPrintJobManager to listen for printing events. chromeos::CupsPrintJobManagerFactory::GetForBrowserContext(profile); } @@ -147,8 +145,8 @@ void LocalPrinterHandlerChromeos::GetDefaultPrinter(DefaultPrinterCallback cb) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // TODO(crbug.com/660898): Add default printers to ChromeOS. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(cb), "")); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(cb), "")); } void LocalPrinterHandlerChromeos::StartGetPrinters( @@ -158,11 +156,8 @@ void LocalPrinterHandlerChromeos::StartGetPrinters( // thread. DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // TODO(crbug.com/971823): Re-enable printing from OOBE. - if (chromeos::ProfileHelper::IsSigninProfile(profile_)) { - std::move(done_callback).Run(); - return; - } + // Printing is not allowed during OOBE. + CHECK(!chromeos::ProfileHelper::IsSigninProfile(profile_)); PrinterList printer_list; AddPrintersToList(printers_manager_->GetPrinters(PrinterClass::kSaved), @@ -185,8 +180,8 @@ void LocalPrinterHandlerChromeos::StartGetCapability( printers_manager_->GetPrinter(printer_name); if (!printer) { // If the printer was removed, the lookup will fail. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(cb), base::Value())); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(cb), base::Value())); return; } @@ -215,7 +210,9 @@ void LocalPrinterHandlerChromeos::OnPrinterInstalled( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (result == chromeos::PrinterSetupResult::kSuccess) { - printers_manager_->PrinterInstalled(printer, true /*is_automatic*/); + printers_manager_->PrinterInstalled( + printer, /*is_automatic=*/true, + chromeos::PrinterSetupSource::kPrintPreview); } HandlePrinterSetup(printer, std::move(cb), printer.IsUsbProtocol(), result); 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 7136f4e03a9..609eafc64f0 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 @@ -77,9 +77,8 @@ class LocalPrinterHandlerChromeos : public PrinterHandler { Profile* const profile_; content::WebContents* const preview_web_contents_; chromeos::CupsPrintersManager* printers_manager_; - scoped_refptr<chromeos::PpdProvider> ppd_provider_; std::unique_ptr<chromeos::PrinterConfigurer> printer_configurer_; - base::WeakPtrFactory<LocalPrinterHandlerChromeos> weak_factory_; + base::WeakPtrFactory<LocalPrinterHandlerChromeos> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LocalPrinterHandlerChromeos); }; diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos_unittest.cc index e968ba221e5..756f3b374ea 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos_unittest.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos_unittest.cc @@ -21,7 +21,7 @@ #include "chrome/test/base/testing_profile.h" #include "components/printing/browser/printer_capabilities.h" #include "components/sync_preferences/testing_pref_service_syncable.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "printing/backend/print_backend.h" #include "printing/backend/printing_restrictions.h" #include "printing/backend/test_print_backend.h" @@ -140,7 +140,7 @@ class LocalPrinterHandlerChromeosTest : public testing::Test { protected: // Must outlive |profile_|. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; // Must outlive |printers_manager_|. TestingProfile profile_; scoped_refptr<TestPrintBackend> test_backend_; @@ -230,7 +230,7 @@ TEST_F(LocalPrinterHandlerChromeosTest, StartGetCapabilityValidPrinter) { local_printer_handler_->StartGetCapability( "printer1", base::BindOnce(&RecordGetCapability, &fetched_caps)); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ASSERT_TRUE(fetched_caps); base::DictionaryValue* dict; @@ -257,7 +257,7 @@ TEST_F(LocalPrinterHandlerChromeosTest, StartGetCapabilityPrinterNotInstalled) { local_printer_handler_->StartGetCapability( "printer1", base::BindOnce(&RecordGetCapability, &fetched_caps)); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ASSERT_TRUE(fetched_caps); base::DictionaryValue* dict; @@ -273,7 +273,7 @@ TEST_F(LocalPrinterHandlerChromeosTest, StartGetCapabilityInvalidPrinter) { local_printer_handler_->StartGetCapability( "invalid printer", base::BindOnce(&RecordGetCapability, &fetched_caps)); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ASSERT_TRUE(fetched_caps); EXPECT_TRUE(fetched_caps->is_none()); 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 0074a2f8b68..84ecb34377b 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 @@ -31,14 +31,17 @@ namespace { scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. static constexpr base::TaskTraits kTraits = { - base::MayBlock(), base::TaskPriority::USER_VISIBLE}; + base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}; -#if defined(OS_WIN) - // Windows drivers are likely not thread-safe. - return base::CreateSingleThreadTaskRunnerWithTraits(kTraits); -#elif defined(USE_CUPS) +#if defined(USE_CUPS) // CUPS is thread safe. - return base::CreateTaskRunnerWithTraits(kTraits); + return base::CreateTaskRunner(kTraits); +#elif defined(OS_WIN) + // Windows drivers are likely not thread-safe. + return base::CreateSingleThreadTaskRunner(kTraits); +#else + // Be conservative on unsupported platforms. + return base::CreateSingleThreadTaskRunner(kTraits); #endif } @@ -67,15 +70,12 @@ base::Value FetchCapabilitiesAsync(const std::string& device_name) { VLOG(1) << "Get printer capabilities start for " << device_name; - if (!print_backend->IsValidPrinter(device_name)) { + PrinterBasicInfo basic_info; + if (!print_backend->GetPrinterBasicInfo(device_name, &basic_info)) { LOG(WARNING) << "Invalid printer " << device_name; return base::Value(); } - PrinterBasicInfo basic_info; - if (!print_backend->GetPrinterBasicInfo(device_name, &basic_info)) - return base::Value(); - return GetSettingsOnBlockingPool(device_name, basic_info, additional_papers, /* has_secure_protocol */ false, print_backend); 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 6147b07f6da..00cf10991ed 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 @@ -312,8 +312,9 @@ void PdfPrinterHandler::SelectFile(const base::FilePath& default_filename, // Handle the no prompting case. Like the dialog prompt, this function // returns and eventually FileSelected() gets called. if (!prompt_user) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&base::GetUniquePath, path.Append(default_filename)), base::BindOnce(&PdfPrinterHandler::OnGotUniqueFileName, weak_ptr_factory_.GetWeakPtr())); @@ -330,16 +331,18 @@ void PdfPrinterHandler::SelectFile(const base::FilePath& default_filename, // Get default download directory. This will be used as a fallback if the // save directory does not exist. base::FilePath default_path = download_prefs->DownloadPath(); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&SelectSaveDirectory, path, default_path), base::BindOnce(&PdfPrinterHandler::OnDirectorySelected, weak_ptr_factory_.GetWeakPtr(), default_filename)); } void PdfPrinterHandler::PostPrintToPdfTask() { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&PrintToPdfCallback, print_data_, print_to_pdf_path_, std::move(pdf_file_saved_closure_))); print_to_pdf_path_.clear(); 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 e3d7c5f14cd..977fa0091ff 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 @@ -79,9 +79,11 @@ #include "third_party/icu/source/i18n/unicode/ulocdata.h" #if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/account_manager/account_manager_util.h" #include "chrome/browser/chromeos/settings/device_oauth2_token_service.h" #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" +#include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h" #include "chromeos/printing/printer_configuration.h" #include "services/identity/public/cpp/scope_set.h" #endif @@ -221,12 +223,12 @@ const char kIsInKioskAutoPrintMode[] = "isInKioskAutoPrintMode"; const char kIsInAppKioskMode[] = "isInAppKioskMode"; // Name of a dictionary field holding the UI locale. const char kUiLocale[] = "uiLocale"; -// Name of a dictionary field holding the thousands delimeter according to the +// Name of a dictionary field holding the thousands delimiter according to the // locale. -const char kThousandsDelimeter[] = "thousandsDelimeter"; -// Name of a dictionary field holding the decimal delimeter according to the +const char kThousandsDelimiter[] = "thousandsDelimiter"; +// Name of a dictionary field holding the decimal delimiter according to the // locale. -const char kDecimalDelimeter[] = "decimalDelimeter"; +const char kDecimalDelimiter[] = "decimalDelimiter"; // Name of a dictionary field holding the measurement system according to the // locale. const char kUnitType[] = "unitType"; @@ -830,7 +832,25 @@ void PrintPreviewHandler::HandleSignin(const base::ListValue* args) { bool add_account = false; CHECK(args->GetBoolean(0, &add_account)); - chrome::ScopedTabbedBrowserDisplayer displayer(Profile::FromWebUI(web_ui())); + Profile* profile = Profile::FromWebUI(web_ui()); + DCHECK(profile); + +#if defined(OS_CHROMEOS) + if (chromeos::IsAccountManagerAvailable(profile)) { + // Chrome OS Account Manager is enabled on this Profile and hence, all + // account management flows will go through native UIs and not through a + // tabbed browser window. + if (add_account) { + chromeos::InlineLoginHandlerDialogChromeOS::Show(); + } else { + chrome::SettingsWindowManager::GetInstance()->ShowOSSettings( + profile, chrome::kAccountManagerSubPage); + } + return; + } +#endif + + chrome::ScopedTabbedBrowserDisplayer displayer(profile); print_dialog_cloud::CreateCloudPrintSigninTab( displayer.browser(), add_account, base::BindOnce(&PrintPreviewHandler::OnSignInTabClosed, @@ -894,7 +914,7 @@ void PrintPreviewHandler::HandleClosePreviewDialog( void PrintPreviewHandler::HandleOpenPrinterSettings( const base::ListValue* args) { chrome::SettingsWindowManager::GetInstance()->ShowOSSettings( - Profile::FromWebUI(web_ui()), chrome::kPrintingSettingsSubPage); + Profile::FromWebUI(web_ui()), chrome::kNativePrintingSettingsSubPage); } #endif @@ -913,8 +933,15 @@ void PrintPreviewHandler::GetLocaleInformation(base::Value* settings) { // Getting the number formatting based on the locale and writing to // dictionary. base::string16 number_format = base::FormatDouble(123456.78, 2); - settings->SetStringKey(kDecimalDelimeter, number_format.substr(7, 1)); - settings->SetStringKey(kThousandsDelimeter, number_format.substr(3, 1)); + size_t thousands_pos = number_format.find('3') + 1; + base::string16 thousands_delimiter = number_format.substr(thousands_pos, 1); + if (number_format[thousands_pos] == '4') + thousands_delimiter.clear(); + size_t decimal_pos = number_format.find('6') + 1; + DCHECK_NE(number_format[decimal_pos], '7'); + base::string16 decimal_delimiter = number_format.substr(decimal_pos, 1); + settings->SetStringKey(kDecimalDelimiter, decimal_delimiter); + settings->SetStringKey(kThousandsDelimiter, thousands_delimiter); settings->SetIntKey(kUnitType, system); } 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 305ba9357f5..bdccac1a8a4 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 @@ -144,11 +144,6 @@ class PrintPreviewHandler : public content::WebUIMessageHandler, FRIEND_TEST_ALL_PREFIXES(PrintPreviewPdfGeneratedBrowserTest, MANUAL_DummyTest); friend class PrintPreviewHandlerTest; - FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, InitialSettingsSimple); - FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, - InitialSettingsEnableHeaderFooter); - FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, - InitialSettingsDisableHeaderFooter); FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, GetPrinters); FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, GetPrinterCapabilities); FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, Print); 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 004dec28a15..e56a96a4703 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 @@ -10,6 +10,7 @@ #include "base/base64.h" #include "base/containers/flat_set.h" +#include "base/i18n/number_formatting.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/memory/ref_counted_memory.h" @@ -25,6 +26,7 @@ #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" #include "chrome/browser/ui/webui/print_preview/printer_handler.h" #include "chrome/common/pref_names.h" +#include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "components/prefs/pref_service.h" #include "components/printing/common/print_messages.h" @@ -32,8 +34,8 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_controller.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/mock_render_process_host.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_renderer_host.h" #include "content/public/test/test_web_ui.h" #include "ipc/ipc_test_sink.h" @@ -284,18 +286,30 @@ class PrintPreviewHandlerTest : public testing::Test { return std::make_unique<TestPrinterHandler>(printers); } - void Initialize() { - // Set locale since the delimeters we check in VerifyInitialSettings() - // depend on it. - base::test::ScopedRestoreICUDefaultLocale scoped_locale("en"); + void Initialize() { InitializeWithLocale("en"); } + void InitializeWithLocale(const std::string& locale) { // Sending this message will enable javascript, so it must always be called // before any other messages are sent. base::Value args(base::Value::Type::LIST); args.GetList().emplace_back("test-callback-id-0"); std::unique_ptr<base::ListValue> list_args = base::ListValue::From(base::Value::ToUniquePtrValue(std::move(args))); - handler()->HandleGetInitialSettings(list_args.get()); + + auto* browser_process = TestingBrowserProcess::GetGlobal(); + std::string original_locale = browser_process->GetApplicationLocale(); + { + // Set locale since the delimiters checked in VerifyInitialSettings() + // depend on it. This has to be done in several ways to make various + // locale code sync up correctly. + browser_process->SetApplicationLocale(locale); + base::test::ScopedRestoreICUDefaultLocale scoped_locale(locale); + base::testing::ResetFormatters(); + handler()->HandleGetInitialSettings(list_args.get()); + } + // Reset again now that |scoped_locale| has been destroyed. + browser_process->SetApplicationLocale(original_locale); + base::testing::ResetFormatters(); // In response to get initial settings, the initial settings are sent back. ASSERT_EQ(1u, web_ui()->call_data().size()); @@ -321,18 +335,33 @@ class PrintPreviewHandlerTest : public testing::Test { EXPECT_EQ(expect_success, success); } + void ValidateInitialSettings(const content::TestWebUI::CallData& data, + const std::string& default_printer_name, + const std::string& initiator_title, + base::Optional<bool> expected_header_footer) { + ValidateInitialSettingsForLocale(data, default_printer_name, + initiator_title, "en", ",", ".", + expected_header_footer); + } + // Validates the initial settings structure in the response matches the // print_preview.NativeInitialSettings type in // chrome/browser/resources/print_preview/native_layer.js. Checks that: // - |default_printer_name| is the printer name returned // - |initiator_title| is the initiator title returned // - |expected_header_footer| is the header/footer state returned, if any - // Also validates that delimeters are correct for "en" locale (set in - // Initialize()). Assumes "test-callback-id-0" was used as the callback id. - void ValidateInitialSettings(const content::TestWebUI::CallData& data, - const std::string& default_printer_name, - const std::string& initiator_title, - base::Optional<bool> expected_header_footer) { + // Also validates that delimiters are correct for |locale| (set in + // InitializeWithLocale()) with the associated |thousands_delimiter| and + // |decimal_delimiter|. + // Assumes "test-callback-id-0" was used as the callback id. + void ValidateInitialSettingsForLocale( + const content::TestWebUI::CallData& data, + const std::string& default_printer_name, + const std::string& initiator_title, + const std::string& locale, + const std::string& thousands_delimiter, + const std::string& decimal_delimiter, + base::Optional<bool> expected_header_footer) { CheckWebUIResponse(data, "test-callback-id-0", true); const base::Value* settings = data.arg3(); ASSERT_TRUE(settings->FindKeyOfType("isInKioskAutoPrintMode", @@ -340,18 +369,17 @@ class PrintPreviewHandlerTest : public testing::Test { ASSERT_TRUE(settings->FindKeyOfType("isInAppKioskMode", base::Value::Type::BOOLEAN)); - const base::Value* locale = - settings->FindKeyOfType("uiLocale", base::Value::Type::STRING); - ASSERT_TRUE(locale); - EXPECT_EQ("en", locale->GetString()); - const base::Value* thousands_delimeter = settings->FindKeyOfType( - "thousandsDelimeter", base::Value::Type::STRING); - ASSERT_TRUE(thousands_delimeter); - EXPECT_EQ(",", thousands_delimeter->GetString()); - const base::Value* decimal_delimeter = - settings->FindKeyOfType("decimalDelimeter", base::Value::Type::STRING); - ASSERT_TRUE(decimal_delimeter); - EXPECT_EQ(".", decimal_delimeter->GetString()); + const std::string* actual_locale = settings->FindStringKey("uiLocale"); + ASSERT_TRUE(actual_locale); + EXPECT_EQ(locale, *actual_locale); + const std::string* actual_thousands_delimiter = + settings->FindStringKey("thousandsDelimiter"); + ASSERT_TRUE(actual_thousands_delimiter); + EXPECT_EQ(thousands_delimiter, *actual_thousands_delimiter); + const std::string* actual_decimal_delimiter = + settings->FindStringKey("decimalDelimiter"); + ASSERT_TRUE(actual_decimal_delimiter); + EXPECT_EQ(decimal_delimiter, *actual_decimal_delimiter); ASSERT_TRUE( settings->FindKeyOfType("unitType", base::Value::Type::INTEGER)); @@ -416,7 +444,7 @@ class PrintPreviewHandlerTest : public testing::Test { std::vector<PrinterInfo>& printers() { return printers_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<TestingProfile> profile_; std::unique_ptr<content::TestWebUI> web_ui_; content::RenderViewHostTestEnabler rvh_test_enabler_; @@ -437,6 +465,24 @@ TEST_F(PrintPreviewHandlerTest, InitialSettingsSimple) { kDummyInitiatorName, {}); } +TEST_F(PrintPreviewHandlerTest, InitialSettingsHiLocale) { + InitializeWithLocale("hi"); + + // Verify initial settings were sent for Hindi. + ValidateInitialSettingsForLocale(*web_ui()->call_data().back(), + kDummyPrinterName, kDummyInitiatorName, "hi", + ",", ".", {}); +} + +TEST_F(PrintPreviewHandlerTest, InitialSettingsRuLocale) { + InitializeWithLocale("ru"); + + // Verify initial settings were sent for Russian. + ValidateInitialSettingsForLocale(*web_ui()->call_data().back(), + kDummyPrinterName, kDummyInitiatorName, "ru", + "\xC2\xA0", ",", {}); +} + TEST_F(PrintPreviewHandlerTest, InitialSettingsEnableHeaderFooter) { // Set a pref that should take priority over StickySettings. prefs()->SetBoolean(prefs::kPrintHeaderFooter, true); 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 2dfc91469b8..a855e2f1d97 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 @@ -345,10 +345,6 @@ void SetupPrintPreviewPlugin(content::WebUIDataSource* source) { {"pdf/browser_api.js", IDR_PDF_BROWSER_API_JS}, {"pdf/elements/icons.html", IDR_PDF_ICONS_HTML}, {"pdf/elements/shared-vars.html", IDR_PDF_SHARED_VARS_HTML}, - {"pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.html", - IDR_PDF_VIEWER_BOOKMARKS_CONTENT_HTML}, - {"pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js", - IDR_PDF_VIEWER_BOOKMARKS_CONTENT_JS}, {"pdf/elements/viewer-bookmark/viewer-bookmark.html", IDR_PDF_VIEWER_BOOKMARK_HTML}, {"pdf/elements/viewer-bookmark/viewer-bookmark.js", @@ -412,7 +408,6 @@ void SetupPrintPreviewPlugin(content::WebUIDataSource* source) { {"pdf/pdf_scripting_api.js", IDR_PDF_PDF_SCRIPTING_API_JS}, {"pdf/pdf_viewer.js", IDR_PDF_PDF_VIEWER_JS}, {"pdf/toolbar_manager.js", IDR_PDF_TOOLBAR_MANAGER_JS}, - {"pdf/viewport_interface.js", IDR_PDF_VIEWPORT_INTERFACE_JS}, {"pdf/viewport.js", IDR_PDF_VIEWPORT_JS}, {"pdf/viewport_scroller.js", IDR_PDF_VIEWPORT_SCROLLER_JS}, {"pdf/zoom_manager.js", IDR_PDF_ZOOM_MANAGER_JS}, @@ -432,7 +427,7 @@ content::WebUIDataSource* CreatePrintPreviewUISource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIPrintHost); AddPrintPreviewStrings(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); #if BUILDFLAG(OPTIMIZE_WEBUI) source->AddResourcePath("crisper.js", IDR_PRINT_PREVIEW_CRISPER_JS); source->SetDefaultResource(IDR_PRINT_PREVIEW_VULCANIZED_HTML); diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc index fd564930748..daefcc3f6ca 100644 --- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc +++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc @@ -27,7 +27,7 @@ void QuotaInternalsProxy::RequestInfo( scoped_refptr<storage::QuotaManager> quota_manager) { DCHECK(quota_manager.get()); if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&QuotaInternalsProxy::RequestInfo, this, quota_manager)); return; @@ -69,18 +69,17 @@ void QuotaInternalsProxy::RequestInfo( QuotaInternalsProxy::~QuotaInternalsProxy() {} -#define RELAY_TO_HANDLER(func, arg_t) \ - void QuotaInternalsProxy::func(arg_t arg) { \ - if (!handler_) \ - return; \ - if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { \ - base::PostTaskWithTraits( \ - FROM_HERE, {BrowserThread::UI}, \ - base::BindOnce(&QuotaInternalsProxy::func, this, arg)); \ - return; \ - } \ - \ - handler_->func(arg); \ +#define RELAY_TO_HANDLER(func, arg_t) \ + void QuotaInternalsProxy::func(arg_t arg) { \ + if (!handler_) \ + return; \ + if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { \ + base::PostTask(FROM_HERE, {BrowserThread::UI}, \ + base::BindOnce(&QuotaInternalsProxy::func, this, arg)); \ + return; \ + } \ + \ + handler_->func(arg); \ } RELAY_TO_HANDLER(ReportAvailableSpace, int64_t) diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_ui.cc b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_ui.cc index 61b1ba55e9e..c119a8f17f8 100644 --- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_ui.cc @@ -23,7 +23,7 @@ content::WebUIDataSource* CreateQuotaInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIQuotaInternalsHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath( "event_handler.js", IDR_QUOTA_INTERNALS_EVENT_HANDLER_JS); source->AddResourcePath( diff --git a/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn b/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn index bf4768bf16e..46529aa8ccb 100644 --- a/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn @@ -8,7 +8,4 @@ mojom("mojo_bindings") { sources = [ "reset_password.mojom", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } diff --git a/chromium/chrome/browser/ui/webui/reset_password/OWNERS b/chromium/chrome/browser/ui/webui/reset_password/OWNERS index 310210ec249..c30ee078ee0 100644 --- a/chromium/chrome/browser/ui/webui/reset_password/OWNERS +++ b/chromium/chrome/browser/ui/webui/reset_password/OWNERS @@ -1,6 +1,7 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS +drubery@chromium.org nparker@chromium.org vakh@chromium.org diff --git a/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc b/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc index 739a6f401c3..b4b7b46f2c6 100644 --- a/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc +++ b/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc @@ -10,9 +10,10 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" -#include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" +#include "components/safe_browsing/password_protection/metrics_util.h" #include "components/safe_browsing/password_protection/password_protection_service.h" +#include "components/safe_browsing/proto/csd.pb.h" #include "components/strings/grit/components_strings.h" #include "components/url_formatter/url_formatter.h" #include "components/user_prefs/user_prefs.h" @@ -23,6 +24,9 @@ #include "mojo/public/cpp/bindings/binding.h" #include "ui/base/l10n/l10n_util.h" +using safe_browsing::LoginReputationClientResponse; +using safe_browsing::RequestOutcome; + namespace { constexpr char kStringTypeUMAName[] = "PasswordProtection.InterstitialString"; @@ -42,10 +46,8 @@ class ResetPasswordHandlerImpl : public mojom::ResetPasswordHandler { public: ResetPasswordHandlerImpl( content::WebContents* web_contents, - PasswordType password_type, mojo::InterfaceRequest<mojom::ResetPasswordHandler> request) : web_contents_(web_contents), - password_type_(password_type), binding_(this, std::move(request)) { DCHECK(web_contents); } @@ -59,15 +61,18 @@ class ResetPasswordHandlerImpl : public mojom::ResetPasswordHandler { safe_browsing::ChromePasswordProtectionService* service = safe_browsing:: ChromePasswordProtectionService::GetPasswordProtectionService(profile); if (service) { - service->OnUserAction(web_contents_, password_type_, - safe_browsing::WarningUIType::INTERSTITIAL, - safe_browsing::WarningAction::CHANGE_PASSWORD); + service->OnUserAction( + web_contents_, + service->reused_password_account_type_for_last_shown_warning(), + RequestOutcome::UNKNOWN, + LoginReputationClientResponse::VERDICT_TYPE_UNSPECIFIED, + /*verdict_token=*/"", safe_browsing::WarningUIType::INTERSTITIAL, + safe_browsing::WarningAction::CHANGE_PASSWORD); } } private: content::WebContents* web_contents_; - PasswordType password_type_; mojo::Binding<mojom::ResetPasswordHandler> binding_; DISALLOW_COPY_AND_ASSIGN(ResetPasswordHandlerImpl); @@ -123,14 +128,14 @@ ResetPasswordUI::~ResetPasswordUI() {} void ResetPasswordUI::BindResetPasswordHandler( mojom::ResetPasswordHandlerRequest request) { ui_handler_ = std::make_unique<ResetPasswordHandlerImpl>( - web_ui()->GetWebContents(), password_type_, std::move(request)); + web_ui()->GetWebContents(), std::move(request)); } base::DictionaryValue ResetPasswordUI::PopulateStrings() const { - std::string org_name = - safe_browsing::ChromePasswordProtectionService:: - GetPasswordProtectionService(Profile::FromWebUI(web_ui())) - ->GetOrganizationName(password_type_); + auto* service = safe_browsing::ChromePasswordProtectionService:: + GetPasswordProtectionService(Profile::FromWebUI(web_ui())); + std::string org_name = service->GetOrganizationName( + service->reused_password_account_type_for_last_shown_warning()); bool known_password_type = password_type_ != PasswordType::PASSWORD_TYPE_UNKNOWN; diff --git a/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc b/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc index 200baa9c15f..e09f9d4a1e9 100644 --- a/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc @@ -69,7 +69,7 @@ content::WebUIDataSource* CreateDataSource() { #if defined(OS_LINUX) SetSandboxStatusData(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); #endif return source; diff --git a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_browsertest_win.cc b/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_browsertest_win.cc deleted file mode 100644 index ec06882aeab..00000000000 --- a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_browsertest_win.cc +++ /dev/null @@ -1,59 +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/set_as_default_browser_ui_win.h" - -#include "base/command_line.h" -#include "base/win/windows_version.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "ui/views/widget/widget.h" - -namespace { - -bool IsBrowserVisible(Browser* browser) { - return views::Widget::GetWidgetForNativeWindow( - browser->window()->GetNativeWindow()) - ->IsVisible(); -} - -} // namespace - -using SetAsDefaultBrowserUIBrowserTestWithoutFirstRun = InProcessBrowserTest; - -class SetAsDefaultBrowserUIBrowserTestWithFirstRun - : public InProcessBrowserTest { - public: - void SetUpCommandLine(base::CommandLine* command_line) override { - command_line->AppendSwitch(switches::kForceFirstRun); - } - - protected: - void TearDownInProcessBrowserTestFixture() override { - ASSERT_FALSE(SetAsDefaultBrowserUI::GetDialogWidgetForTesting()); - } -}; - -IN_PROC_BROWSER_TEST_F(SetAsDefaultBrowserUIBrowserTestWithFirstRun, Test) { - // Windows 8 only test case. - if (base::win::GetVersion() != base::win::Version::WIN8 && - base::win::GetVersion() != base::win::Version::WIN8_1) { - return; - } - ASSERT_FALSE(IsBrowserVisible(browser())); - views::Widget* dialog_widget = - SetAsDefaultBrowserUI::GetDialogWidgetForTesting(); - ASSERT_TRUE(dialog_widget); - ASSERT_TRUE(dialog_widget->IsVisible()); - dialog_widget->CloseNow(); - ASSERT_TRUE(IsBrowserVisible(browser())); -} - -IN_PROC_BROWSER_TEST_F(SetAsDefaultBrowserUIBrowserTestWithoutFirstRun, - TestWithoutFirstRun) { - ASSERT_TRUE(IsBrowserVisible(browser())); - EXPECT_EQ(nullptr, SetAsDefaultBrowserUI::GetDialogWidgetForTesting()); -} 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 deleted file mode 100644 index c72f92b4a6c..00000000000 --- a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc +++ /dev/null @@ -1,396 +0,0 @@ -// Copyright (c) 2012 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/set_as_default_browser_ui_win.h" - -#include <string> -#include <vector> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/metrics/histogram_macros.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/shell_integration.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_dialogs.h" -#include "chrome/browser/ui/browser_finder.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/browser/ui/browser_list_observer.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/chrome_pages.h" -#include "chrome/browser/ui/singleton_tabs.h" -#include "chrome/browser/ui/startup/default_browser_prompt.h" -#include "chrome/browser/ui/sync/sync_promo_ui.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/webui/localized_string.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/url_constants.h" -#include "chrome/grit/browser_resources.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "chrome/grit/locale_settings.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_contents_delegate.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" -#include "ui/base/l10n/l10n_font_util.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/gfx/font.h" -#include "ui/views/widget/widget.h" -#include "ui/web_dialogs/web_dialog_delegate.h" - -using content::BrowserThread; -using content::WebContents; -using content::WebUIMessageHandler; - -namespace { - -const char kSetAsDefaultBrowserHistogram[] = "DefaultBrowser.InteractionResult"; - -// The enum permits registering in UMA the four possible outcomes (do not -// reorder these). -// ACCEPTED: user pressed Next and made Chrome default. -// DECLINED: user simply closed the dialog without making Chrome default. -// REGRETTED: user pressed Next but then selected a different default browser. -// ACCEPTED_OTHER_MODE: user selected a different side-by-side install of -// Chrome. -enum MakeChromeDefaultResult { - MAKE_CHROME_DEFAULT_ACCEPTED = 0, - MAKE_CHROME_DEFAULT_DECLINED = 1, - MAKE_CHROME_DEFAULT_REGRETTED = 2, - // MAKE_CHROME_DEFAULT_ACCEPTED_IMMERSE = 3, // Deprecated. - MAKE_CHROME_DEFAULT_ACCEPTED_OTHER_MODE = 4, - MAKE_CHROME_DEFAULT_MAX -}; - -content::WebUIDataSource* CreateSetAsDefaultBrowserUIHTMLSource() { - content::WebUIDataSource* data_source = - content::WebUIDataSource::Create(chrome::kChromeUIMetroFlowHost); - - static constexpr LocalizedString kStrings[] = { - {"pageTitle", IDS_METRO_FLOW_TAB_TITLE}, - {"flowTitle", IDS_METRO_FLOW_TITLE_SHORT}, - {"flowDescription", IDS_METRO_FLOW_DESCRIPTION}, - {"flowNext", IDS_METRO_FLOW_SET_DEFAULT}, - {"chromeLogoString", IDS_SHORT_PRODUCT_LOGO_ALT_TEXT}, - }; - AddLocalizedStringsBulk(data_source, kStrings, base::size(kStrings)); - - data_source->SetJsonPath("strings.js"); - data_source->AddResourcePath("set_as_default_browser.js", - IDR_SET_AS_DEFAULT_BROWSER_JS); - data_source->SetDefaultResource(IDR_SET_AS_DEFAULT_BROWSER_HTML); - return data_source; -} - -// A simple class serving as a delegate for passing down the result of the -// interaction. -class ResponseDelegate { - public: - virtual void SetDialogInteractionResult(MakeChromeDefaultResult result) = 0; - - protected: - virtual ~ResponseDelegate() {} -}; - -// Event handler for SetAsDefaultBrowserUI. Capable of setting Chrome as the -// default browser on button click, closing itself and triggering Chrome -// restart. -class SetAsDefaultBrowserHandler : public WebUIMessageHandler { - public: - explicit SetAsDefaultBrowserHandler( - const base::WeakPtr<ResponseDelegate>& response_delegate); - - // WebUIMessageHandler implementation. - void RegisterMessages() override; - - private: - // Handler for the 'Next' (or 'make Chrome the Metro browser') button. - void HandleLaunchSetDefaultBrowserFlow(const base::ListValue* args); - - // Close this web ui. - void ConcludeInteraction(MakeChromeDefaultResult interaction_result); - - void OnDefaultBrowserWorkerFinished( - shell_integration::DefaultWebClientState state); - - // The worker pointer is reference counted. While it is running, the - // message loops of the FILE and UI thread will hold references to it - // and it will be automatically freed once all its tasks have finished. - scoped_refptr<shell_integration::DefaultBrowserWorker> - default_browser_worker_; - base::WeakPtr<ResponseDelegate> response_delegate_; - - // Used to invalidate the DefaultBrowserWorker callback. - base::WeakPtrFactory<SetAsDefaultBrowserHandler> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(SetAsDefaultBrowserHandler); -}; - -SetAsDefaultBrowserHandler::SetAsDefaultBrowserHandler( - const base::WeakPtr<ResponseDelegate>& response_delegate) - : response_delegate_(response_delegate), weak_ptr_factory_(this) { - default_browser_worker_ = new shell_integration::DefaultBrowserWorker( - base::Bind(&SetAsDefaultBrowserHandler::OnDefaultBrowserWorkerFinished, - weak_ptr_factory_.GetWeakPtr())); -} - -void SetAsDefaultBrowserHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "SetAsDefaultBrowser:LaunchSetDefaultBrowserFlow", - base::BindRepeating( - &SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow, - base::Unretained(this))); -} - -void SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow( - const base::ListValue* args) { - default_browser_worker_->StartSetAsDefault(); -} - -void SetAsDefaultBrowserHandler::ConcludeInteraction( - MakeChromeDefaultResult interaction_result) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (response_delegate_) - response_delegate_->SetDialogInteractionResult(interaction_result); - - WebContents* contents = web_ui()->GetWebContents(); - - if (contents) { - content::WebContentsDelegate* delegate = contents->GetDelegate(); - if (delegate) - delegate->CloseContents(contents); - } -} - -void SetAsDefaultBrowserHandler::OnDefaultBrowserWorkerFinished( - shell_integration::DefaultWebClientState state) { - // The callback is expected to be invoked once the procedure has completed. - DCHECK_CURRENTLY_ON(BrowserThread::UI); - switch (state) { - case shell_integration::NOT_DEFAULT: - // The operation concluded, but Chrome is still not the default. This - // suggests the user has decided not to make Chrome the default. - ConcludeInteraction(MAKE_CHROME_DEFAULT_REGRETTED); - break; - case shell_integration::IS_DEFAULT: - ConcludeInteraction(MAKE_CHROME_DEFAULT_ACCEPTED); - break; - case shell_integration::UNKNOWN_DEFAULT: - break; - case shell_integration::OTHER_MODE_IS_DEFAULT: - // Interestingly, the user picked a different install mode of this browser - // (e.g., stable Chrome rather than Chrome Beta). - ConcludeInteraction(MAKE_CHROME_DEFAULT_ACCEPTED_OTHER_MODE); - break; - case shell_integration::NUM_DEFAULT_STATES: - NOTREACHED(); - break; - } - - // Otherwise, keep the dialog open since the user probably didn't make a - // choice. -} - -// A web dialog delegate implementation for when 'Make Chrome Metro' UI -// is displayed on a dialog. -class SetAsDefaultBrowserDialogImpl : public ui::WebDialogDelegate, - public ResponseDelegate, - public BrowserListObserver { - public: - explicit SetAsDefaultBrowserDialogImpl(Profile* profile); - ~SetAsDefaultBrowserDialogImpl() override; - // Show a modal web dialog with kChromeUIMetroFlowURL page. - void ShowDialog(); - static views::Widget* dialog_widget() { return dialog_widget_; } - - protected: - // Overridden from WebDialogDelegate: - ui::ModalType GetDialogModalType() const override; - base::string16 GetDialogTitle() const override; - GURL GetDialogContentURL() const override; - void GetWebUIMessageHandlers( - std::vector<WebUIMessageHandler*>* handlers) const override; - void GetDialogSize(gfx::Size* size) const override; - std::string GetDialogArgs() const override; - void OnDialogClosed(const std::string& json_retval) override; - void OnCloseContents(WebContents* source, bool* out_close_dialog) override; - bool ShouldShowDialogTitle() const override; - bool HandleContextMenu(content::RenderFrameHost* render_frame_host, - const content::ContextMenuParams& params) override; - - // Overridden from ResponseDelegate: - void SetDialogInteractionResult(MakeChromeDefaultResult result) override; - - // Overridden from BrowserListObserver: - void OnBrowserAdded(Browser* browser) override; - void OnBrowserRemoved(Browser* browser) override; - - private: - Profile* profile_; - Browser* browser_; - mutable bool owns_handler_; - base::WeakPtrFactory<ResponseDelegate> response_delegate_ptr_factory_; - SetAsDefaultBrowserHandler* handler_; - MakeChromeDefaultResult dialog_interaction_result_; - - static views::Widget* dialog_widget_; - - DISALLOW_COPY_AND_ASSIGN(SetAsDefaultBrowserDialogImpl); -}; - -// static -views::Widget* SetAsDefaultBrowserDialogImpl::dialog_widget_ = nullptr; - -SetAsDefaultBrowserDialogImpl::SetAsDefaultBrowserDialogImpl(Profile* profile) - : profile_(profile), - browser_(nullptr), - owns_handler_(true), - response_delegate_ptr_factory_(this), - handler_(new SetAsDefaultBrowserHandler( - response_delegate_ptr_factory_.GetWeakPtr())), - dialog_interaction_result_(MAKE_CHROME_DEFAULT_DECLINED) { - BrowserList::AddObserver(this); -} - -SetAsDefaultBrowserDialogImpl::~SetAsDefaultBrowserDialogImpl() { - if (browser_) - BrowserList::RemoveObserver(this); - if (owns_handler_) - delete handler_; -} - -void SetAsDefaultBrowserDialogImpl::ShowDialog() { - // Use a NULL parent window to make sure that the dialog will have an item - // in the Windows task bar. The code below will make it highlight if the - // dialog is not in the foreground. - gfx::NativeWindow native_window = chrome::ShowWebDialog(NULL, profile_, this); - DCHECK(!dialog_widget_); - dialog_widget_ = views::Widget::GetWidgetForNativeWindow(native_window); - dialog_widget_->FlashFrame(true); -} - -ui::ModalType SetAsDefaultBrowserDialogImpl::GetDialogModalType() const { - return ui::MODAL_TYPE_SYSTEM; -} - -base::string16 SetAsDefaultBrowserDialogImpl::GetDialogTitle() const { - return l10n_util::GetStringUTF16(IDS_METRO_FLOW_TAB_TITLE); -} - -GURL SetAsDefaultBrowserDialogImpl::GetDialogContentURL() const { - std::string url_string(chrome::kChromeUIMetroFlowURL); - return GURL(url_string); -} - -void SetAsDefaultBrowserDialogImpl::GetWebUIMessageHandlers( - std::vector<WebUIMessageHandler*>* handlers) const { - handlers->push_back(handler_); - owns_handler_ = false; -} - -void SetAsDefaultBrowserDialogImpl::GetDialogSize(gfx::Size* size) const { - PrefService* prefs = profile_->GetPrefs(); - gfx::Font approximate_web_font( - prefs->GetString(prefs::kWebKitSansSerifFontFamily), - prefs->GetInteger(prefs::kWebKitDefaultFontSize)); - - *size = ui::GetLocalizedContentsSizeForFont(IDS_METRO_FLOW_WIDTH_CHARS, - IDS_METRO_FLOW_HEIGHT_LINES, - approximate_web_font); -} - -std::string SetAsDefaultBrowserDialogImpl::GetDialogArgs() const { - return "[]"; -} - -void SetAsDefaultBrowserDialogImpl::OnDialogClosed( - const std::string& json_retval) { - // Register the user's response in UMA. - UMA_HISTOGRAM_ENUMERATION(kSetAsDefaultBrowserHistogram, - dialog_interaction_result_, - MAKE_CHROME_DEFAULT_MAX); - - // Suppress showing the default browser infobar if the user explicitly elected - // *not to* make Chrome default. - if (dialog_interaction_result_ == MAKE_CHROME_DEFAULT_REGRETTED || - dialog_interaction_result_ == MAKE_CHROME_DEFAULT_ACCEPTED_OTHER_MODE) { - DefaultBrowserPromptDeclined(profile_); - } - - // Carry on with a normal chrome session. For the purpose of surfacing this - // dialog the actual browser window had to remain hidden. Now it's time to - // show it. - if (browser_) { - BrowserWindow* window = browser_->window(); - WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents(); - window->Show(); - if (contents) - contents->SetInitialFocus(); - } - - DCHECK(dialog_widget_); - dialog_widget_ = nullptr; - - delete this; -} - -void SetAsDefaultBrowserDialogImpl::OnCloseContents(WebContents* source, - bool* out_close_dialog) { - *out_close_dialog = true; -} - -bool SetAsDefaultBrowserDialogImpl::ShouldShowDialogTitle() const { - return true; -} - -bool SetAsDefaultBrowserDialogImpl::HandleContextMenu( - content::RenderFrameHost* render_frame_host, - const content::ContextMenuParams& params) { - return true; -} - -void SetAsDefaultBrowserDialogImpl::SetDialogInteractionResult( - MakeChromeDefaultResult result) { - dialog_interaction_result_ = result; -} - -void SetAsDefaultBrowserDialogImpl::OnBrowserAdded(Browser* browser) { - if (browser_ || !browser || !browser->is_type_tabbed()) - return; - browser_ = browser; - ShowDialog(); -} - -void SetAsDefaultBrowserDialogImpl::OnBrowserRemoved(Browser* browser) { - if (browser_ == browser) { - browser_ = NULL; - BrowserList::RemoveObserver(this); - } -} - -} // namespace - -SetAsDefaultBrowserUI::SetAsDefaultBrowserUI(content::WebUI* web_ui) - : ui::WebDialogUI(web_ui) { - content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), - CreateSetAsDefaultBrowserUIHTMLSource()); -} - -// static -void SetAsDefaultBrowserUI::Show(Profile* profile) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - new SetAsDefaultBrowserDialogImpl(profile); -} - -// static -views::Widget* SetAsDefaultBrowserUI::GetDialogWidgetForTesting() { - return SetAsDefaultBrowserDialogImpl::dialog_widget(); -} diff --git a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.h b/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.h deleted file mode 100644 index 308200d435f..00000000000 --- a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.h +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2012 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_SET_AS_DEFAULT_BROWSER_UI_WIN_H_ -#define CHROME_BROWSER_UI_WEBUI_SET_AS_DEFAULT_BROWSER_UI_WIN_H_ - -#include "base/macros.h" -#include "ui/web_dialogs/web_dialog_ui.h" - -class Profile; - -namespace views { -class Widget; -} - -// The UI used in first-run flow to prompt the user to set Chrome as the -// default Windows browser and *the browser* of Metro mode. Intended for -// Windows 8 only. -class SetAsDefaultBrowserUI : public ui::WebDialogUI { - public: - explicit SetAsDefaultBrowserUI(content::WebUI* web_ui); - - // Present metroizer UI either in a new singleton tab or in a dialog window. - static void Show(Profile* profile); - - // Returns the web dialog widget for testing. - static views::Widget* GetDialogWidgetForTesting(); - - private: - DISALLOW_COPY_AND_ASSIGN(SetAsDefaultBrowserUI); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_SET_AS_DEFAULT_BROWSER_UI_WIN_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.cc b/chromium/chrome/browser/ui/webui/settings/about_handler.cc index 517f2c413cb..7245f9a91e3 100644 --- a/chromium/chrome/browser/ui/webui/settings/about_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/about_handler.cc @@ -25,6 +25,7 @@ #include "base/task/post_task.h" #include "base/time/time.h" #include "base/values.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_content_browser_client.h" @@ -325,7 +326,7 @@ AboutHandler* AboutHandler::Create(content::WebUIDataSource* html_source, html_source->AddString("aboutObsoleteSystemURL", ObsoleteSystem::GetLinkURL()); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) base::string16 tos = l10n_util::GetStringFUTF16( IDS_ABOUT_TERMS_OF_SERVICE, base::UTF8ToUTF16(chrome::kChromeUITermsURL)); html_source->AddString("aboutProductTos", tos); @@ -334,7 +335,7 @@ AboutHandler* AboutHandler::Create(content::WebUIDataSource* html_source, #if defined(OS_CHROMEOS) std::string safetyInfoLink = GetSafetyInfoLink(); html_source->AddBoolean("shouldShowSafetyInfo", !safetyInfoLink.empty()); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) html_source->AddString( "aboutProductSafety", l10n_util::GetStringUTF16(IDS_ABOUT_SAFETY_INFORMATION)); @@ -450,9 +451,9 @@ void AboutHandler::RegisterMessages() { void AboutHandler::OnJavascriptAllowed() { apply_changes_from_upgrade_observer_ = true; version_updater_.reset(VersionUpdater::Create(web_ui()->GetWebContents())); - policy_registrar_.reset(new policy::PolicyChangeRegistrar( + policy_registrar_ = std::make_unique<policy::PolicyChangeRegistrar>( g_browser_process->policy_service(), - policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string()))); + policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())); policy_registrar_->Observe( policy::key::kDeviceAutoUpdateDisabled, base::Bind(&AboutHandler::OnDeviceAutoUpdatePolicyChanged, @@ -604,8 +605,9 @@ void AboutHandler::HandleGetVersionInfo(const base::ListValue* args) { std::string callback_id; CHECK(args->GetString(0, &callback_id)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&GetVersionInfo), base::Bind(&AboutHandler::OnGetVersionInfoReady, weak_factory_.GetWeakPtr(), callback_id)); @@ -622,8 +624,9 @@ void AboutHandler::HandleGetRegulatoryInfo(const base::ListValue* args) { std::string callback_id; CHECK(args->GetString(0, &callback_id)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&FindRegulatoryLabelDir), base::Bind(&AboutHandler::OnRegulatoryLabelDirFound, weak_factory_.GetWeakPtr(), callback_id)); @@ -801,8 +804,9 @@ void AboutHandler::OnRegulatoryLabelDirFound( return; } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&ReadRegulatoryLabelText, label_dir_path), base::Bind(&AboutHandler::OnRegulatoryLabelTextRead, weak_factory_.GetWeakPtr(), callback_id, label_dir_path)); diff --git a/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc b/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc index 86695044727..4fceb887f1c 100644 --- a/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc @@ -12,10 +12,6 @@ #include "chrome/browser/themes/theme_service_factory.h" #include "content/public/browser/web_ui.h" -#if defined(OS_CHROMEOS) -#include "chrome/browser/ui/ash/wallpaper_controller_client.h" -#endif - namespace settings { AppearanceHandler::AppearanceHandler(content::WebUI* webui) @@ -37,22 +33,6 @@ void AppearanceHandler::RegisterMessages() { base::BindRepeating(&AppearanceHandler::HandleUseSystemTheme, base::Unretained(this))); #endif -#if defined(OS_CHROMEOS) - web_ui()->RegisterMessageCallback( - "openWallpaperManager", - base::BindRepeating(&AppearanceHandler::HandleOpenWallpaperManager, - base::Unretained(this))); - - web_ui()->RegisterMessageCallback( - "isWallpaperSettingVisible", - base::BindRepeating(&AppearanceHandler::IsWallpaperSettingVisible, - base::Unretained(this))); - - web_ui()->RegisterMessageCallback( - "isWallpaperPolicyControlled", - base::BindRepeating(&AppearanceHandler::IsWallpaperPolicyControlled, - base::Unretained(this))); -#endif } void AppearanceHandler::HandleUseDefaultTheme(const base::ListValue* args) { @@ -68,31 +48,4 @@ void AppearanceHandler::HandleUseSystemTheme(const base::ListValue* args) { } #endif -#if defined(OS_CHROMEOS) -void AppearanceHandler::IsWallpaperSettingVisible(const base::ListValue* args) { - CHECK_EQ(args->GetSize(), 1U); - bool result = WallpaperControllerClient::Get()->ShouldShowWallpaperSetting(); - ResolveCallback(args->GetList()[0], result); -} - -void AppearanceHandler::IsWallpaperPolicyControlled( - const base::ListValue* args) { - CHECK_EQ(args->GetSize(), 1U); - bool result = WallpaperControllerClient::Get() - ->IsActiveUserWallpaperControlledByPolicy(); - ResolveCallback(args->GetList()[0], result); -} - -void AppearanceHandler::HandleOpenWallpaperManager( - const base::ListValue* args) { - WallpaperControllerClient::Get()->OpenWallpaperPickerIfAllowed(); -} - -void AppearanceHandler::ResolveCallback(const base::Value& callback_id, - bool result) { - AllowJavascript(); - ResolveJavascriptCallback(callback_id, base::Value(result)); -} -#endif - } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/appearance_handler.h b/chromium/chrome/browser/ui/webui/settings/appearance_handler.h index dabbd53601d..961e16eec2d 100644 --- a/chromium/chrome/browser/ui/webui/settings/appearance_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/appearance_handler.h @@ -41,20 +41,6 @@ class AppearanceHandler : public SettingsPageUIHandler { void HandleUseSystemTheme(const base::ListValue* args); #endif -#if defined(OS_CHROMEOS) - // Whether the wallpaper setting should be shown. - void IsWallpaperSettingVisible(const base::ListValue* args); - - // Whether the wallpaper is policy controlled. - void IsWallpaperPolicyControlled(const base::ListValue* args); - - // Open the wallpaper manager app. - void HandleOpenWallpaperManager(const base::ListValue* args); - - // Helper function to resolve the Javascript callback. - void ResolveCallback(const base::Value& callback_id, bool result); -#endif - Profile* profile_; // Weak pointer. base::WeakPtrFactory<AppearanceHandler> weak_ptr_factory_{this}; 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 7047d2983da..b34815f9c76 100644 --- a/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc @@ -7,8 +7,9 @@ #include "base/bind.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/chrome_password_protection_service.h" -#include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/prefs/pref_service.h" +#include "components/safe_browsing/password_protection/metrics_util.h" +#include "components/safe_browsing/proto/csd.pb.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -16,6 +17,8 @@ namespace settings { using password_manager::metrics_util::PasswordType; using safe_browsing::ChromePasswordProtectionService; +using safe_browsing::LoginReputationClientResponse; +using safe_browsing::RequestOutcome; ChangePasswordHandler::ChangePasswordHandler( Profile* profile, @@ -40,7 +43,7 @@ void ChangePasswordHandler::RegisterMessages() { void ChangePasswordHandler::OnJavascriptAllowed() { pref_registrar_.Init(profile_->GetPrefs()); pref_registrar_.Add( - prefs::kSafeBrowsingUnhandledSyncPasswordReuses, + prefs::kSafeBrowsingUnhandledGaiaPasswordReuses, base::Bind(&ChangePasswordHandler::UpdateChangePasswordCardVisibility, base::Unretained(this))); } @@ -55,18 +58,24 @@ void ChangePasswordHandler::HandleInitialize(const base::ListValue* args) { } void ChangePasswordHandler::HandleChangePassword(const base::ListValue* args) { - service_->OnUserAction(web_ui()->GetWebContents(), - PasswordType::PRIMARY_ACCOUNT_PASSWORD, - safe_browsing::WarningUIType::CHROME_SETTINGS, - safe_browsing::WarningAction::CHANGE_PASSWORD); + service_->OnUserAction( + web_ui()->GetWebContents(), + service_->reused_password_account_type_for_last_shown_warning(), + RequestOutcome::UNKNOWN, + LoginReputationClientResponse::VERDICT_TYPE_UNSPECIFIED, "unused_token", + safe_browsing::WarningUIType::CHROME_SETTINGS, + safe_browsing::WarningAction::CHANGE_PASSWORD); } void ChangePasswordHandler::UpdateChangePasswordCardVisibility() { FireWebUIListener( "change-password-visibility", - base::Value(service_->IsWarningEnabled() && - safe_browsing::ChromePasswordProtectionService:: - ShouldShowChangePasswordSettingUI(profile_))); + base::Value( + service_->IsWarningEnabled( + service_ + ->reused_password_account_type_for_last_shown_warning()) && + safe_browsing::ChromePasswordProtectionService:: + ShouldShowChangePasswordSettingUI(profile_))); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc index d7a9cd51101..37f8b056c86 100644 --- a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc +++ b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc @@ -18,6 +18,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" #include "base/values.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_service.h" @@ -119,7 +120,7 @@ void ChromeCleanupHandler::GetExtensionNamesFromIds( Profile* profile, const std::set<base::string16>& extension_ids, std::set<base::string16>* extension_names) { -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) extensions::ExtensionRegistry* extension_registry = extensions::ExtensionRegistry::Get(profile); for (const base::string16& extension_id : extension_ids) { @@ -303,16 +304,16 @@ void ChromeCleanupHandler::HandleNotifyChromeCleanupLearnMoreClicked( void ChromeCleanupHandler::HandleGetMoreItemsPluralString( const base::ListValue* args) { -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) GetPluralString(IDS_SETTINGS_RESET_CLEANUP_DETAILS_MORE, args); -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#endif // defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) } void ChromeCleanupHandler::HandleGetItemsToRemovePluralString( const base::ListValue* args) { -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) GetPluralString(IDS_SETTINGS_RESET_CLEANUP_DETAILS_ITEMS_TO_BE_REMOVED, args); -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#endif // defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) } void ChromeCleanupHandler::GetPluralString(int id, diff --git a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc index a9fb0bb1553..cff17fb6870 100644 --- a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc @@ -4,12 +4,13 @@ #include "chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.h" +#include "build/branding_buildflags.h" #include "chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" @@ -19,7 +20,7 @@ namespace settings { using safe_browsing::MockChromeCleanerProcess; TEST(ChromeCleanupHandlerTest, GetExtensionsNamesFromIds) { - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_(TestingBrowserProcess::GetGlobal()); // Set up the testing profile to get the extensions registry from it. @@ -35,7 +36,7 @@ TEST(ChromeCleanupHandlerTest, GetExtensionsNamesFromIds) { }; std::set<base::string16> expected_names = { -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) // Extension names are only available in Google-branded builds. MockChromeCleanerProcess::kInstalledExtensionName1, MockChromeCleanerProcess::kInstalledExtensionName2, 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 56f573121d0..34dbb5b6fac 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.cc @@ -35,10 +35,6 @@ void AccessibilityHandler::RegisterMessages() { &AccessibilityHandler::HandleShowSelectToSpeakSettings, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "showSwitchAccessSettings", - base::BindRepeating(&AccessibilityHandler::HandleShowSwitchAccessSettings, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( "getStartupSoundEnabled", base::BindRepeating(&AccessibilityHandler::HandleGetStartupSoundEnabled, base::Unretained(this))); @@ -58,11 +54,6 @@ void AccessibilityHandler::HandleShowSelectToSpeakSettings( OpenExtensionOptionsPage(extension_misc::kSelectToSpeakExtensionId); } -void AccessibilityHandler::HandleShowSwitchAccessSettings( - const base::ListValue* args) { - OpenExtensionOptionsPage(extension_misc::kSwitchAccessExtensionId); -} - void AccessibilityHandler::HandleGetStartupSoundEnabled( const base::ListValue* args) { AllowJavascript(); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h index 26f284ad260..80d735832cb 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h @@ -32,11 +32,10 @@ class AccessibilityHandler : public ::settings::SettingsPageUIHandler { void OnJavascriptDisallowed() override {} private: - // Callback for the messages to show settings for ChromeVox, - // Select To Speak, or Switch Access. + // Callback for the messages to show settings for ChromeVox or + // Select To Speak. void HandleShowChromeVoxSettings(const base::ListValue* args); void HandleShowSelectToSpeakSettings(const base::ListValue* args); - void HandleShowSwitchAccessSettings(const base::ListValue* args); void HandleGetStartupSoundEnabled(const base::ListValue* args); void HandleSetStartupSoundEnabled(const base::ListValue* args); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc index e06d7205e11..3978c28d325 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc @@ -101,8 +101,7 @@ AccountManagerUIHandler::AccountManagerUIHandler( : account_manager_(account_manager), identity_manager_(identity_manager), account_manager_observer_(this), - identity_manager_observer_(this), - weak_factory_(this) { + identity_manager_observer_(this) { DCHECK(account_manager_); DCHECK(identity_manager_); } @@ -141,21 +140,18 @@ void AccountManagerUIHandler::HandleGetAccounts(const base::ListValue* args) { AllowJavascript(); const auto& args_list = args->GetList(); - CHECK_EQ(args_list.size(), 2u); + CHECK_EQ(args_list.size(), 1u); CHECK(args_list[0].is_string()); - CHECK(args_list[1].is_bool()); base::Value callback_id = args_list[0].Clone(); - bool include_images = args_list[1].GetBool(); - account_manager_->GetAccounts(base::BindOnce( - &AccountManagerUIHandler::OnGetAccounts, weak_factory_.GetWeakPtr(), - std::move(callback_id), include_images)); + account_manager_->GetAccounts( + base::BindOnce(&AccountManagerUIHandler::OnGetAccounts, + weak_factory_.GetWeakPtr(), std::move(callback_id))); } void AccountManagerUIHandler::OnGetAccounts( base::Value callback_id, - bool include_images, const std::vector<AccountManager::Account>& stored_accounts) { base::ListValue accounts; @@ -179,8 +175,9 @@ void AccountManagerUIHandler::OnGetAccounts( account.SetBoolean("isDeviceAccount", false); base::Optional<AccountInfo> maybe_account_info = - identity_manager_->FindAccountInfoForAccountWithRefreshTokenByGaiaId( - account_key.id); + identity_manager_ + ->FindExtendedAccountInfoForAccountWithRefreshTokenByGaiaId( + account_key.id); DCHECK(maybe_account_info.has_value()); account.SetBoolean( @@ -189,20 +186,17 @@ void AccountManagerUIHandler::OnGetAccounts( maybe_account_info->account_id)); account.SetString("fullName", maybe_account_info->full_name); account.SetString("email", stored_account.raw_email); - // Images can be large, so only send them if requested. - if (include_images) { - if (!maybe_account_info->account_image.IsEmpty()) { - account.SetString("pic", - webui::GetBitmapDataUrl( - maybe_account_info->account_image.AsBitmap())); - } else { - gfx::ImageSkia default_icon = - *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( - IDR_LOGIN_DEFAULT_USER); - account.SetString( - "pic", webui::GetBitmapDataUrl( - default_icon.GetRepresentation(1.0f).GetBitmap())); - } + if (!maybe_account_info->account_image.IsEmpty()) { + account.SetString("pic", + webui::GetBitmapDataUrl( + maybe_account_info->account_image.AsBitmap())); + } else { + gfx::ImageSkia default_icon = + *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( + IDR_LOGIN_DEFAULT_USER); + account.SetString("pic", + webui::GetBitmapDataUrl( + default_icon.GetRepresentation(1.0f).GetBitmap())); } account.SetBoolean("unmigrated", account_manager_->HasDummyGaiaToken(account_key)); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h index 071c7cf9b22..c915a10cfa6 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h @@ -64,7 +64,6 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler, // |AccountManager::GetAccounts| callback. void OnGetAccounts( base::Value callback_id, - bool include_images, const std::vector<AccountManager::Account>& stored_accounts); // Refreshes the UI. @@ -86,7 +85,7 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler, ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> identity_manager_observer_; - base::WeakPtrFactory<AccountManagerUIHandler> weak_factory_; + base::WeakPtrFactory<AccountManagerUIHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AccountManagerUIHandler); }; 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 4cf92f5fcda..df482d3555e 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 @@ -20,8 +20,7 @@ namespace settings { AndroidAppsHandler::AndroidAppsHandler(Profile* profile) : arc_prefs_observer_(this), arc_session_manager_observer_(this), - profile_(profile), - weak_ptr_factory_(this) {} + profile_(profile) {} AndroidAppsHandler::~AndroidAppsHandler() {} diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h index cb89bc38224..3a7d0549e7d 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h @@ -60,7 +60,7 @@ class AndroidAppsHandler : public ::settings::SettingsPageUIHandler, ScopedObserver<arc::ArcSessionManager, arc::ArcSessionManager::Observer> arc_session_manager_observer_; Profile* profile_; // unowned - base::WeakPtrFactory<AndroidAppsHandler> weak_ptr_factory_; + base::WeakPtrFactory<AndroidAppsHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AndroidAppsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/OWNERS b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/OWNERS new file mode 100644 index 00000000000..94b2e07d850 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/OWNERS @@ -0,0 +1,4 @@ +dominickn@chromium.org +jshikaram@chromium.org + +# COMPONENT: Platform>Apps>Foundation diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc new file mode 100644 index 00000000000..8b3abcc9b50 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc @@ -0,0 +1,55 @@ +// 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/app_management/app_management_page_handler_factory.h" + +#include <memory> +#include <utility> + +#include "base/bind.h" +#include "base/feature_list.h" +#include "chrome/browser/apps/app_service/app_icon_source.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/app_management/app_management_page_handler.h" +#include "chrome/grit/browser_resources.h" +#include "chrome/grit/chromium_strings.h" +#include "chrome/grit/generated_resources.h" +#include "components/prefs/pref_service.h" +#include "content/public/browser/url_data_source.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" +#include "ui/base/resource/resource_bundle.h" + +AppManagementPageHandlerFactory::AppManagementPageHandlerFactory( + Profile* profile) + : page_factory_binding_(this), profile_(profile) {} + +AppManagementPageHandlerFactory::~AppManagementPageHandlerFactory() = default; + +void AppManagementPageHandlerFactory::Bind( + app_management::mojom::PageHandlerFactoryRequest request) { + if (page_factory_binding_.is_bound()) { + page_factory_binding_.Unbind(); + } + + page_factory_binding_.Bind(std::move(request)); +} + +void AppManagementPageHandlerFactory::BindPageHandlerFactory( + app_management::mojom::PageHandlerFactoryRequest request) { + if (page_factory_binding_.is_bound()) { + page_factory_binding_.Unbind(); + } + + page_factory_binding_.Bind(std::move(request)); +} + +void AppManagementPageHandlerFactory::CreatePageHandler( + app_management::mojom::PagePtr page, + app_management::mojom::PageHandlerRequest request) { + DCHECK(page); + + page_handler_ = std::make_unique<AppManagementPageHandler>( + std::move(request), std::move(page), profile_); +} diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h new file mode 100644 index 00000000000..3779071f093 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h @@ -0,0 +1,45 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ + +#include <memory> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/app_management/app_management.mojom.h" +#include "mojo/public/cpp/bindings/binding.h" + +class Profile; + +class AppManagementPageHandler; + +class AppManagementPageHandlerFactory + : public app_management::mojom::PageHandlerFactory { + public: + explicit AppManagementPageHandlerFactory(Profile* profile); + ~AppManagementPageHandlerFactory() override; + + void Bind(app_management::mojom::PageHandlerFactoryRequest request); + + private: + void BindPageHandlerFactory( + app_management::mojom::PageHandlerFactoryRequest request); + + // app_management::mojom::PageHandlerFactory: + void CreatePageHandler( + app_management::mojom::PagePtr page, + app_management::mojom::PageHandlerRequest request) override; + + std::unique_ptr<AppManagementPageHandler> page_handler_; + + mojo::Binding<app_management::mojom::PageHandlerFactory> + page_factory_binding_; + + Profile* profile_; + + DISALLOW_COPY_AND_ASSIGN(AppManagementPageHandlerFactory); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc index 3a2b3bc5b12..c548d8996f3 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc @@ -6,12 +6,9 @@ #include <string> #include <utility> -#include <vector> #include "base/bind.h" #include "base/bind_helpers.h" -#include "chrome/browser/chromeos/crostini/crostini_export_import.h" -#include "chrome/browser/chromeos/crostini/crostini_manager.h" #include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/chromeos/file_manager/path_util.h" #include "chrome/browser/chromeos/guest_os/guest_os_share_path.h" @@ -21,8 +18,7 @@ namespace chromeos { namespace settings { -CrostiniHandler::CrostiniHandler(Profile* profile) - : profile_(profile), weak_ptr_factory_(this) {} +CrostiniHandler::CrostiniHandler(Profile* profile) : profile_(profile) {} CrostiniHandler::~CrostiniHandler() { DisallowJavascript(); @@ -67,6 +63,11 @@ void CrostiniHandler::RegisterMessages() { base::BindRepeating( &CrostiniHandler::HandleCrostiniInstallerStatusRequest, weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "requestCrostiniExportImportOperationStatus", + base::BindRepeating( + &CrostiniHandler::HandleCrostiniExportImportOperationStatusRequest, + weak_ptr_factory_.GetWeakPtr())); } void CrostiniHandler::OnJavascriptAllowed() { @@ -75,6 +76,7 @@ void CrostiniHandler::OnJavascriptAllowed() { if (chromeos::CrosUsbDetector::Get()) { chromeos::CrosUsbDetector::Get()->AddUsbDeviceObserver(this); } + crostini::CrostiniExportImport::GetForProfile(profile_)->AddObserver(this); } void CrostiniHandler::OnJavascriptDisallowed() { @@ -86,6 +88,7 @@ void CrostiniHandler::OnJavascriptDisallowed() { if (chromeos::CrosUsbDetector::Get()) { chromeos::CrosUsbDetector::Get()->RemoveUsbDeviceObserver(this); } + crostini::CrostiniExportImport::GetForProfile(profile_)->RemoveObserver(this); } void CrostiniHandler::HandleRequestCrostiniInstallerView( @@ -130,7 +133,8 @@ void CrostiniHandler::HandleRemoveCrostiniSharedPath( vm_name, base::FilePath(path), /*unpersist=*/true, base::BindOnce( - [](const std::string& path, bool result, std::string failure_reason) { + [](const std::string& path, bool result, + const std::string& failure_reason) { if (!result) { LOG(ERROR) << "Error unsharing " << path << ": " << failure_reason; @@ -225,6 +229,15 @@ void CrostiniHandler::HandleCrostiniInstallerStatusRequest( OnCrostiniInstallerViewStatusChanged(status); } +void CrostiniHandler::HandleCrostiniExportImportOperationStatusRequest( + const base::ListValue* args) { + AllowJavascript(); + CHECK_EQ(0U, args->GetSize()); + bool in_progress = crostini::CrostiniExportImport::GetForProfile(profile_) + ->GetExportImportOperationStatus(); + OnCrostiniExportImportOperationStatusChanged(in_progress); +} + void CrostiniHandler::OnCrostiniInstallerViewStatusChanged(bool status) { // It's technically possible for this to be called before Javascript is // enabled, in which case we must not call FireWebUIListener @@ -234,5 +247,12 @@ void CrostiniHandler::OnCrostiniInstallerViewStatusChanged(bool status) { } } +void CrostiniHandler::OnCrostiniExportImportOperationStatusChanged( + bool in_progress) { + // Other side listens with cr.addWebUIListener + FireWebUIListener("crostini-export-import-operation-status-changed", + base::Value(in_progress)); +} + } // namespace settings } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h index 97f4605f475..c5d4a353f6e 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h @@ -8,6 +8,7 @@ #include <vector> #include "base/memory/weak_ptr.h" +#include "chrome/browser/chromeos/crostini/crostini_export_import.h" #include "chrome/browser/chromeos/crostini/crostini_manager.h" #include "chrome/browser/chromeos/usb/cros_usb_detector.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" @@ -23,6 +24,7 @@ namespace settings { class CrostiniHandler : public ::settings::SettingsPageUIHandler, public crostini::InstallerViewStatusObserver, + public crostini::CrostiniExportImport::Observer, public chromeos::CrosUsbDeviceObserver { public: explicit CrostiniHandler(Profile* profile); @@ -56,10 +58,15 @@ class CrostiniHandler : public ::settings::SettingsPageUIHandler, void HandleCrostiniInstallerStatusRequest(const base::ListValue* args); // Handle the CrostiniInstallerView opening/closing. void OnCrostiniInstallerViewStatusChanged(bool open) override; + // Handle a request for the CrostiniExportImport operation status. + void HandleCrostiniExportImportOperationStatusRequest( + const base::ListValue* args); + // CrostiniExportImport::Observer: + void OnCrostiniExportImportOperationStatusChanged(bool in_progress) override; Profile* profile_; // weak_ptr_factory_ should always be last member. - base::WeakPtrFactory<CrostiniHandler> weak_ptr_factory_; + base::WeakPtrFactory<CrostiniHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CrostiniHandler); }; 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 b6021b75156..2f4c1749e9a 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 @@ -260,8 +260,7 @@ CupsPrintersHandler::CupsPrintersHandler( printer_configurer_(std::move(printer_configurer)), printers_manager_(printers_manager), endpoint_resolver_(std::make_unique<local_discovery::EndpointResolver>()), - printers_manager_observer_(this), - weak_factory_(this) {} + printers_manager_observer_(this) {} // static std::unique_ptr<CupsPrintersHandler> CupsPrintersHandler::Create( @@ -745,7 +744,8 @@ void CupsPrintersHandler::OnAddedOrEditedPrinterCommon( UMA_HISTOGRAM_ENUMERATION("Printing.CUPS.PrinterAdded", printer.GetProtocol(), Printer::kProtocolMax); PRINTER_LOG(USER) << "Performing printer setup"; - printers_manager_->PrinterInstalled(printer, is_automatic); + printers_manager_->PrinterInstalled(printer, is_automatic, + PrinterSetupSource::kSettings); printers_manager_->SavePrinter(printer); if (printer.IsUsbProtocol()) { // Record UMA for USB printer setup source. @@ -945,8 +945,9 @@ void CupsPrintersHandler::FileSelected(const base::FilePath& path, // VerifyPpdContents() in order to determine whether the file appears to be a // PPD file. The task's priority is USER_BLOCKING because the this task // updates the UI as a result of a direct user action. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&ReadFileToStringWithMaxSize, path, kPpdMaxLineLength), base::BindOnce(&CupsPrintersHandler::VerifyPpdContents, weak_factory_.GetWeakPtr(), path)); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h index d2b16b0ec44..3fe1146c725 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h @@ -232,7 +232,7 @@ class CupsPrintersHandler : public ::settings::SettingsPageUIHandler, ScopedObserver<CupsPrintersManager, CupsPrintersManager::Observer> printers_manager_observer_; - base::WeakPtrFactory<CupsPrintersHandler> weak_factory_; + base::WeakPtrFactory<CupsPrintersHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CupsPrintersHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc index 3a0aa798540..c9c52df5e53 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc @@ -13,7 +13,7 @@ #include "chrome/test/base/testing_profile.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/debug_daemon_client.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -78,7 +78,7 @@ class FakePpdProvider : public PpdProvider { class CupsPrintersHandlerTest : public testing::Test { public: CupsPrintersHandlerTest() - : thread_bundle_(content::TestBrowserThreadBundle::REAL_IO_THREAD), + : task_environment_(content::BrowserTaskEnvironment::REAL_IO_THREAD), profile_(), web_ui_(), printers_handler_() {} @@ -94,7 +94,7 @@ class CupsPrintersHandlerTest : public testing::Test { protected: // Must outlive |profile_|. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; content::TestWebUI web_ui_; std::unique_ptr<CupsPrintersHandler> printers_handler_; 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 812cffcf10f..e2de1a94c72 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 @@ -9,12 +9,14 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/logging.h" +#include "base/time/time.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/child_accounts/parent_access_code/parent_access_service.h" #include "chrome/browser/chromeos/set_time_dialog.h" #include "chrome/browser/chromeos/system/timezone_resolver_manager.h" #include "chrome/browser/chromeos/system/timezone_util.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/dbus/system_clock/system_clock_client.h" @@ -64,8 +66,7 @@ bool IsTimezoneAutomaticDetectionUserEditable() { } // namespace -DateTimeHandler::DateTimeHandler() - : scoped_observer_(this), weak_ptr_factory_(this) {} +DateTimeHandler::DateTimeHandler() : scoped_observer_(this) {} DateTimeHandler::~DateTimeHandler() = default; @@ -76,6 +77,9 @@ DateTimeHandler* DateTimeHandler::Create( html_source->AddString( "timeZoneID", system::TimezoneSettings::GetInstance()->GetCurrentTimezoneID()); + html_source->AddBoolean( + "timeActionsProtectedForChild", + base::FeatureList::IsEnabled(features::kParentAccessCodeForTimeChange)); return new DateTimeHandler; } @@ -165,7 +169,8 @@ void DateTimeHandler::HandleShowParentAccessForTimeZone( user_manager::UserManager::Get()->GetActiveUser()->GetAccountId(), base::BindRepeating(&DateTimeHandler::OnParentAccessValidation, weak_ptr_factory_.GetWeakPtr()), - ash::ParentAccessRequestReason::kChangeTimezone); + ash::ParentAccessRequestReason::kChangeTimezone, false /* extra_dimmer */, + base::Time()); } void DateTimeHandler::OnParentAccessValidation(bool success) { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h index bd69d936bc8..2a3c44a9b29 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h @@ -75,7 +75,7 @@ class DateTimeHandler : public ::settings::SettingsPageUIHandler, ScopedObserver<SystemClockClient, SystemClockClient::Observer> scoped_observer_; - base::WeakPtrFactory<DateTimeHandler> weak_ptr_factory_; + base::WeakPtrFactory<DateTimeHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DateTimeHandler); }; 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 de342d5a55e..c38687e6415 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 @@ -5,11 +5,11 @@ #include "chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h" #include "ash/public/cpp/keyboard_shortcut_viewer.h" -#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/cpp/tablet_mode.h" +#include "ash/public/mojom/constants.mojom.h" #include "base/bind.h" #include "base/command_line.h" #include "base/values.h" -#include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chromeos/constants/chromeos_switches.h" #include "content/public/browser/web_ui.h" #include "content/public/common/service_manager_connection.h" @@ -114,8 +114,7 @@ void KeyboardHandler::HandleKeyboardChange(const base::ListValue* args) { void KeyboardHandler::UpdateKeyboards() { bool physical_keyboard = false; // In tablet mode, physical keybards are disabled / ignored. - if (!TabletModeClient::Get() || - !TabletModeClient::Get()->tablet_mode_enabled()) { + if (!ash::TabletMode::Get() || !ash::TabletMode::Get()->InTabletMode()) { physical_keyboard = true; } if (!physical_keyboard) { 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 0f5933cc8a8..f9ac3140904 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 @@ -24,7 +24,8 @@ void PointerHandler::RegisterMessages() { void PointerHandler::OnJavascriptAllowed() { if (!pointer_device_observer_) { - pointer_device_observer_.reset(new system::PointerDeviceObserver()); + pointer_device_observer_ = + std::make_unique<system::PointerDeviceObserver>(); pointer_device_observer_->Init(); } 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 ca32d32706f..79feea807e9 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 @@ -110,9 +110,7 @@ void PowerHandler::TestAPI::SetLidClosedBehavior( } PowerHandler::PowerHandler(PrefService* prefs) - : prefs_(prefs), - power_manager_client_observer_(this), - weak_ptr_factory_(this) {} + : prefs_(prefs), power_manager_client_observer_(this) {} PowerHandler::~PowerHandler() {} diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.h index 78869c7978e..a362dcd45be 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.h @@ -130,7 +130,7 @@ class PowerHandler : public ::settings::SettingsPageUIHandler, bool last_lid_closed_controlled_ = false; bool last_has_lid_ = true; - base::WeakPtrFactory<PowerHandler> weak_ptr_factory_; + base::WeakPtrFactory<PowerHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PowerHandler); }; 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 cf9b1c9342e..b9737dc9919 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 @@ -35,6 +35,7 @@ #include "chromeos/cryptohome/cryptohome_util.h" #include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/disks/disk.h" #include "components/arc/arc_features.h" #include "components/arc/arc_prefs.h" #include "components/arc/arc_service_manager.h" @@ -49,6 +50,9 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/text/bytes_formatting.h" +using chromeos::disks::Disk; +using chromeos::disks::DiskMountManager; + namespace chromeos { namespace settings { namespace { @@ -90,7 +94,7 @@ StorageHandler::StorageHandler(Profile* profile, profile_(profile), source_name_(html_source->GetSource()), arc_observer_(this), - weak_ptr_factory_(this) { + special_volume_path_pattern_("[a-z]+://.*") { html_source->AddBoolean( kAndroidEnabled, base::FeatureList::IsEnabled(arc::kUsbStorageUIFeature) && @@ -98,6 +102,7 @@ StorageHandler::StorageHandler(Profile* profile, } StorageHandler::~StorageHandler() { + DiskMountManager::GetInstance()->RemoveObserver(this); arc::ArcServiceManager::Get() ->arc_bridge_service() ->storage_manager() @@ -126,6 +131,10 @@ void StorageHandler::RegisterMessages() { "clearDriveCache", base::BindRepeating(&StorageHandler::HandleClearDriveCache, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "updateExternalStorages", + base::BindRepeating(&StorageHandler::HandleUpdateExternalStorages, + base::Unretained(this))); } void StorageHandler::OnJavascriptAllowed() { @@ -139,12 +148,18 @@ void StorageHandler::OnJavascriptAllowed() { ->arc_bridge_service() ->storage_manager() ->AddObserver(this); + + // Start observing mount/unmount events to update the connected device list. + DiskMountManager::GetInstance()->AddObserver(this); } void StorageHandler::OnJavascriptDisallowed() { // Ensure that pending callbacks do not complete and cause JS to be evaluated. weak_ptr_factory_.InvalidateWeakPtrs(); + // Stop observing mount/unmount events to update the connected device list. + DiskMountManager::GetInstance()->RemoveObserver(this); + // Stop observing the mojo connection so that OnConnectionReady() and // OnConnectionClosed() that use FireWebUIListener() won't be called while JS // is disabled. @@ -202,6 +217,11 @@ void StorageHandler::HandleClearDriveCache( weak_ptr_factory_.GetWeakPtr())); } +void StorageHandler::HandleUpdateExternalStorages( + const base::ListValue* unused_args) { + UpdateExternalStorages(); +} + void StorageHandler::OnClearDriveCacheDone(bool /*success*/) { UpdateDriveCacheSize(); } @@ -212,8 +232,9 @@ void StorageHandler::UpdateSizeStat() { int64_t* total_size = new int64_t(0); int64_t* available_size = new int64_t(0); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&GetSizeStatBlocking, downloads_path, total_size, available_size), base::Bind(&StorageHandler::OnGetSizeStat, weak_ptr_factory_.GetWeakPtr(), @@ -247,8 +268,9 @@ void StorageHandler::UpdateDownloadsSize() { const base::FilePath downloads_path = file_manager::util::GetDownloadsFolderForProfile(profile_); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&base::ComputeDirectorySize, downloads_path), base::Bind(&StorageHandler::OnGetDownloadsSize, weak_ptr_factory_.GetWeakPtr())); @@ -300,7 +322,7 @@ void StorageHandler::UpdateBrowsingDataSize() { if (!site_data_size_collector_.get()) { content::StoragePartition* storage_partition = content::BrowserContext::GetDefaultStoragePartition(profile_); - site_data_size_collector_.reset(new SiteDataSizeCollector( + site_data_size_collector_ = std::make_unique<SiteDataSizeCollector>( storage_partition->GetPath(), new BrowsingDataCookieHelper(storage_partition), new BrowsingDataDatabaseHelper(profile_), @@ -314,7 +336,7 @@ void StorageHandler::UpdateBrowsingDataSize() { storage_partition->GetServiceWorkerContext()), new BrowsingDataCacheStorageHelper( storage_partition->GetCacheStorageContext()), - BrowsingDataFlashLSOHelper::Create(profile_))); + BrowsingDataFlashLSOHelper::Create(profile_)); } site_data_size_collector_->Fetch( base::Bind(&StorageHandler::OnGetBrowsingDataSize, @@ -453,6 +475,36 @@ void StorageHandler::OnGetOtherUserSize( } } +void StorageHandler::UpdateExternalStorages() { + base::Value devices(base::Value::Type::LIST); + for (const auto& itr : DiskMountManager::GetInstance()->mount_points()) { + const DiskMountManager::MountPointInfo& mount_info = itr.second; + if (!IsEligibleForAndroidStorage(mount_info.source_path)) + continue; + + const chromeos::disks::Disk* disk = + DiskMountManager::GetInstance()->FindDiskBySourcePath( + mount_info.source_path); + if (!disk) + continue; + + std::string label = disk->device_label(); + if (label.empty()) { + // To make volume labels consistent with Files app, we follow how Files + // generates a volume label when the volume doesn't have specific label. + // That is, we use the base name of mount path instead in such cases. + // TODO(fukino): Share the implementation to compute the volume name with + // Files app. crbug.com/1002535. + label = base::FilePath(mount_info.mount_path).BaseName().AsUTF8Unsafe(); + } + base::Value device(base::Value::Type::DICTIONARY); + device.SetKey("uuid", base::Value(disk->fs_uuid())); + device.SetKey("label", base::Value(label)); + devices.GetList().push_back(std::move(device)); + } + FireWebUIListener("onExternalStoragesUpdated", devices); +} + void StorageHandler::OnConnectionReady() { is_android_running_ = true; UpdateAndroidRunning(); @@ -471,5 +523,25 @@ void StorageHandler::OnArcPlayStoreEnabledChanged(bool enabled) { content::WebUIDataSource::Update(profile_, source_name_, std::move(update)); } +void StorageHandler::OnMountEvent( + DiskMountManager::MountEvent event, + chromeos::MountError error_code, + const DiskMountManager::MountPointInfo& mount_info) { + if (error_code != chromeos::MountError::MOUNT_ERROR_NONE) + return; + + if (!IsEligibleForAndroidStorage(mount_info.source_path)) + return; + + UpdateExternalStorages(); +} + +bool StorageHandler::IsEligibleForAndroidStorage(std::string source_path) { + // Android's StorageManager volume concept relies on assumption that it is + // local filesystem. Hence, special volumes like DriveFS should not be + // listed on the Settings. + return !RE2::FullMatch(source_path, special_volume_path_pattern_); +} + } // namespace settings } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h index cefa5753f66..32078b3aa56 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h @@ -19,10 +19,12 @@ #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "components/arc/common/storage_manager.mojom.h" +#include "chromeos/disks/disk_mount_manager.h" +#include "components/arc/mojom/storage_manager.mojom.h" #include "components/arc/session/connection_observer.h" #include "components/arc/storage_manager/arc_storage_manager.h" #include "components/user_manager/user.h" +#include "third_party/re2/src/re2/re2.h" class Profile; @@ -40,7 +42,8 @@ namespace settings { class StorageHandler : public ::settings::SettingsPageUIHandler, public arc::ConnectionObserver<arc::mojom::StorageManagerInstance>, - public arc::ArcSessionManager::Observer { + public arc::ArcSessionManager::Observer, + public chromeos::disks::DiskMountManager::Observer { public: // Enumeration for device state about remaining space. These values must be // kept in sync with settings.StorageSpaceState in JS code. @@ -65,6 +68,12 @@ class StorageHandler // arc::ArcSessionManager::Observer: void OnArcPlayStoreEnabledChanged(bool enabled) override; + // chromeos::disks::DiskMountManager::Observer: + void OnMountEvent(chromeos::disks::DiskMountManager::MountEvent event, + chromeos::MountError error_code, + const chromeos::disks::DiskMountManager::MountPointInfo& + mount_info) override; + private: // Handlers of JS messages. void HandleUpdateAndroidEnabled(const base::ListValue* unused_args); @@ -72,6 +81,7 @@ class StorageHandler void HandleOpenDownloads(const base::ListValue* unused_args); void HandleOpenArcStorage(const base::ListValue* unused_args); void HandleClearDriveCache(const base::ListValue* unused_args); + void HandleUpdateExternalStorages(const base::ListValue* unused_args); // Callback called when clearing Drive cache is done. void OnClearDriveCacheDone(bool success); @@ -125,6 +135,13 @@ class StorageHandler // Callback to save the fetched user sizes and update the UI. void OnGetOtherUserSize(base::Optional<cryptohome::BaseReply> reply); + // Updates list of external storages. + void UpdateExternalStorages(); + + // Returns true if the volume from |source_path| can be used as Android + // storage. + bool IsEligibleForAndroidStorage(std::string source_path); + // Total size of cache data in browsing data. int64_t browser_cache_size_; @@ -163,8 +180,9 @@ class StorageHandler const std::string source_name_; ScopedObserver<arc::ArcSessionManager, arc::ArcSessionManager::Observer> arc_observer_; + const re2::RE2 special_volume_path_pattern_; - base::WeakPtrFactory<StorageHandler> weak_ptr_factory_; + base::WeakPtrFactory<StorageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(StorageHandler); }; 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 8af7cb25dac..577dc77a406 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc @@ -58,10 +58,7 @@ std::unique_ptr<base::DictionaryValue> GetFingerprintsInfo( } // namespace FingerprintHandler::FingerprintHandler(Profile* profile) - : profile_(profile), - binding_(this), - session_observer_(this), - weak_ptr_factory_(this) { + : profile_(profile), binding_(this), session_observer_(this) { content::GetSystemConnector()->BindInterface(device::mojom::kServiceName, &fp_service_); user_id_ = ProfileHelper::Get()->GetUserIdHashFromProfile(profile); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h index e4d6c7e1fad..766d8842ee6 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h @@ -85,7 +85,7 @@ class FingerprintHandler : public ::settings::SettingsPageUIHandler, session_manager::SessionManagerObserver> session_observer_; - base::WeakPtrFactory<FingerprintHandler> weak_ptr_factory_; + base::WeakPtrFactory<FingerprintHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FingerprintHandler); }; 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 25814f623e6..a734cd0dc87 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 @@ -12,21 +12,20 @@ #include "base/bind_helpers.h" #include "base/values.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/ash/assistant/assistant_service_connection.h" #include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h" #include "chromeos/audio/cras_audio_handler.h" -#include "chromeos/constants/chromeos_switches.h" -#include "chromeos/services/assistant/public/mojom/constants.mojom.h" +#include "chromeos/constants/chromeos_features.h" #include "components/arc/arc_prefs.h" #include "components/arc/arc_service_manager.h" #include "content/public/browser/browser_context.h" -#include "services/service_manager/public/cpp/connector.h" #include "ui/gfx/geometry/rect.h" namespace chromeos { namespace settings { GoogleAssistantHandler::GoogleAssistantHandler(Profile* profile) - : profile_(profile), weak_factory_(this) { + : profile_(profile) { chromeos::CrasAudioHandler::Get()->AddAudioObserver(this); } @@ -77,8 +76,7 @@ void GoogleAssistantHandler::RegisterMessages() { void GoogleAssistantHandler::HandleShowGoogleAssistantSettings( const base::ListValue* args) { CHECK_EQ(0U, args->GetSize()); - if (chromeos::switches::IsAssistantEnabled()) - ash::OpenAssistantSettings(); + ash::OpenAssistantSettings(); } void GoogleAssistantHandler::HandleRetrainVoiceModel( @@ -106,9 +104,9 @@ void GoogleAssistantHandler::BindAssistantSettingsManager() { DCHECK(!settings_manager_.is_bound()); // Set up settings mojom. - service_manager::Connector* connector = - content::BrowserContext::GetConnectorFor(profile_); - connector->BindInterface(assistant::mojom::kServiceName, &settings_manager_); + AssistantServiceConnection::GetForProfile(profile_) + ->service() + ->BindSettingsManager(mojo::MakeRequest(&settings_manager_)); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h index 8891f4e53d7..067eae00af2 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h @@ -49,7 +49,7 @@ class GoogleAssistantHandler : public ::settings::SettingsPageUIHandler, bool pending_hotword_update_ = false; - base::WeakPtrFactory<GoogleAssistantHandler> weak_factory_; + base::WeakPtrFactory<GoogleAssistantHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(GoogleAssistantHandler); }; 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 6d0b2214df2..883457370ee 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc @@ -14,14 +14,13 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" +#include "chromeos/network/network_connect.h" #include "chromeos/network/network_event_log.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "components/arc/arc_service_manager.h" -#include "components/arc/common/net.mojom.h" -#include "components/arc/metrics/arc_metrics_constants.h" +#include "components/arc/mojom/net.mojom.h" #include "components/arc/session/arc_bridge_service.h" -#include "components/arc/session/connection_holder.h" #include "components/onc/onc_constants.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -36,8 +35,7 @@ namespace { const char kAddThirdPartyVpnMessage[] = "addThirdPartyVpn"; const char kConfigureThirdPartyVpnMessage[] = "configureThirdPartyVpn"; -const char kRequestArcVpnProviders[] = "requestArcVpnProviders"; -const char kSendArcVpnProviders[] = "sendArcVpnProviders"; +const char kShowCellularSetupUI[] = "showCellularSetupUI"; const char kRequestGmsCoreNotificationsDisabledDeviceNames[] = "requestGmsCoreNotificationsDisabledDeviceNames"; const char kSendGmsCoreNotificationsDisabledDeviceNames[] = @@ -48,18 +46,6 @@ Profile* GetProfileForPrimaryUser() { user_manager::UserManager::Get()->GetPrimaryUser()); } -std::unique_ptr<base::DictionaryValue> ArcVpnProviderToValue( - const app_list::ArcVpnProviderManager::ArcVpnProvider* arc_vpn_provider) { - std::unique_ptr<base::DictionaryValue> serialized_entry = - std::make_unique<base::DictionaryValue>(); - serialized_entry->SetString("PackageName", arc_vpn_provider->package_name); - serialized_entry->SetString("ProviderName", arc_vpn_provider->app_name); - serialized_entry->SetString("AppID", arc_vpn_provider->app_id); - serialized_entry->SetDouble("LastLaunchTime", - arc_vpn_provider->last_launch_time.ToDoubleT()); - return serialized_entry; -} - } // namespace namespace settings { @@ -67,10 +53,6 @@ namespace settings { InternetHandler::InternetHandler(Profile* profile) : profile_(profile) { DCHECK(profile_); - arc_vpn_provider_manager_ = app_list::ArcVpnProviderManager::Get(profile_); - if (arc_vpn_provider_manager_) - arc_vpn_provider_manager_->AddObserver(this); - TetherService* tether_service = TetherService::Get(profile); gms_core_notifications_state_tracker_ = tether_service ? tether_service->GetGmsCoreNotificationsStateTracker() @@ -80,8 +62,6 @@ InternetHandler::InternetHandler(Profile* profile) : profile_(profile) { } InternetHandler::~InternetHandler() { - if (arc_vpn_provider_manager_) - arc_vpn_provider_manager_->RemoveObserver(this); if (gms_core_notifications_state_tracker_) gms_core_notifications_state_tracker_->RemoveObserver(this); } @@ -96,41 +76,20 @@ void InternetHandler::RegisterMessages() { base::BindRepeating(&InternetHandler::ConfigureThirdPartyVpn, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kRequestArcVpnProviders, - base::BindRepeating(&InternetHandler::RequestArcVpnProviders, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( kRequestGmsCoreNotificationsDisabledDeviceNames, base::BindRepeating( &InternetHandler::RequestGmsCoreNotificationsDisabledDeviceNames, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kShowCellularSetupUI, + base::BindRepeating(&InternetHandler::ShowCellularSetupUI, + base::Unretained(this))); } void InternetHandler::OnJavascriptAllowed() {} void InternetHandler::OnJavascriptDisallowed() {} -void InternetHandler::OnArcVpnProviderRemoved(const std::string& package_name) { - if (arc_vpn_providers_.find(package_name) == arc_vpn_providers_.end()) - return; - arc_vpn_providers_.erase(package_name); - SendArcVpnProviders(); -} - -void InternetHandler::OnArcVpnProvidersRefreshed( - const std::vector< - std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& - arc_vpn_providers) { - SetArcVpnProviders(arc_vpn_providers); -} - -void InternetHandler::OnArcVpnProviderUpdated( - app_list::ArcVpnProviderManager::ArcVpnProvider* arc_vpn_provider) { - arc_vpn_providers_[arc_vpn_provider->package_name] = - ArcVpnProviderToValue(arc_vpn_provider); - SendArcVpnProviders(); -} - void InternetHandler::OnGmsCoreNotificationStateChanged() { SetGmsCoreNotificationsDisabledDeviceNames(); } @@ -213,41 +172,19 @@ void InternetHandler::ConfigureThirdPartyVpn(const base::ListValue* args) { << network->GetVpnProviderType() << " For: " << guid; } -void InternetHandler::RequestArcVpnProviders(const base::ListValue* args) { - if (!arc_vpn_provider_manager_) - return; - - AllowJavascript(); - SetArcVpnProviders(arc_vpn_provider_manager_->GetArcVpnProviders()); -} - void InternetHandler::RequestGmsCoreNotificationsDisabledDeviceNames( const base::ListValue* args) { AllowJavascript(); SetGmsCoreNotificationsDisabledDeviceNames(); } -void InternetHandler::SetArcVpnProviders( - const std::vector< - std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& - arc_vpn_providers) { - arc_vpn_providers_.clear(); - for (const auto& arc_vpn_provider : arc_vpn_providers) { - arc_vpn_providers_[arc_vpn_provider->package_name] = - ArcVpnProviderToValue(arc_vpn_provider.get()); - } - SendArcVpnProviders(); -} - -void InternetHandler::SendArcVpnProviders() { - if (!IsJavascriptAllowed()) +void InternetHandler::ShowCellularSetupUI(const base::ListValue* args) { + std::string guid; + if (args->GetSize() < 1 || !args->GetString(0, &guid)) { + NOTREACHED() << "Invalid args for: " << kConfigureThirdPartyVpnMessage; return; - - base::ListValue arc_vpn_providers_value; - for (const auto& iter : arc_vpn_providers_) { - arc_vpn_providers_value.GetList().push_back(iter.second->Clone()); } - FireWebUIListener(kSendArcVpnProviders, arc_vpn_providers_value); + chromeos::NetworkConnect::Get()->ShowMobileSetup(guid); } void InternetHandler::SetGmsCoreNotificationsDisabledDeviceNames() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.h index 31ed7c90e43..89f10828b9a 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.h @@ -8,7 +8,6 @@ #include <memory> #include "base/macros.h" -#include "chrome/browser/ui/app_list/arc/arc_vpn_provider_manager.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "chromeos/components/tether/gms_core_notifications_state_tracker.h" #include "ui/gfx/native_widget_types.h" @@ -25,8 +24,7 @@ namespace settings { // Chrome OS Internet settings page UI handler. class InternetHandler - : public app_list::ArcVpnProviderManager::Observer, - public chromeos::tether::GmsCoreNotificationsStateTracker::Observer, + : public chromeos::tether::GmsCoreNotificationsStateTracker::Observer, public ::settings::SettingsPageUIHandler { public: explicit InternetHandler(Profile* profile); @@ -37,15 +35,6 @@ class InternetHandler void OnJavascriptAllowed() override; void OnJavascriptDisallowed() override; - // app_list::ArcVpnProviderManager::Observer: - void OnArcVpnProvidersRefreshed( - const std::vector< - std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& - arc_vpn_providers) override; - void OnArcVpnProviderRemoved(const std::string& package_name) override; - void OnArcVpnProviderUpdated(app_list::ArcVpnProviderManager::ArcVpnProvider* - arc_vpn_provider) override; - // chromeos::tether::GmsCoreNotificationsStateTracker::Observer: void OnGmsCoreNotificationStateChanged() override; @@ -55,18 +44,9 @@ class InternetHandler // Settings JS handlers. void AddThirdPartyVpn(const base::ListValue* args); void ConfigureThirdPartyVpn(const base::ListValue* args); - void RequestArcVpnProviders(const base::ListValue* args); void RequestGmsCoreNotificationsDisabledDeviceNames( const base::ListValue* args); - - // Sets list of Arc Vpn providers. - void SetArcVpnProviders( - const std::vector< - std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& - arc_vpn_providers); - - // Sends list of Arc Vpn providers to Chrome://settings. - void SendArcVpnProviders(); + void ShowCellularSetupUI(const base::ListValue* args); // Sets list of names of devices whose "Google Play Services" notifications // are disabled. @@ -81,17 +61,10 @@ class InternetHandler chromeos::tether::GmsCoreNotificationsStateTracker* gms_core_notifications_state_tracker); - std::map<std::string, std::unique_ptr<base::DictionaryValue>> - arc_vpn_providers_; - std::vector<std::unique_ptr<base::Value>> device_names_without_notifications_; Profile* const profile_; - // |arc_vpn_provider_manager_| and |gms_core_notifications_state_tracker_| are - // provided by BrowserContextKeyedServices which are guaranteed to outlive - // WebUIMessageHandlers. - app_list::ArcVpnProviderManager* arc_vpn_provider_manager_; chromeos::tether::GmsCoreNotificationsStateTracker* gms_core_notifications_state_tracker_; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc index fdf98ee2cf5..d6125af737b 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc @@ -22,7 +22,7 @@ namespace chromeos { namespace settings { KerberosAccountsHandler::KerberosAccountsHandler() - : credentials_manager_observer_(this), weak_factory_(this) {} + : credentials_manager_observer_(this) {} KerberosAccountsHandler::~KerberosAccountsHandler() = default; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h index 78493fb26a9..296cf45bb46 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h @@ -79,7 +79,7 @@ class KerberosAccountsHandler : public ::settings::SettingsPageUIHandler, KerberosCredentialsManager::Observer> credentials_manager_observer_; - base::WeakPtrFactory<KerberosAccountsHandler> weak_factory_; + base::WeakPtrFactory<KerberosAccountsHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(KerberosAccountsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc index 8d03f47642a..19977ff73a7 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc @@ -62,9 +62,8 @@ MultideviceHandler::MultideviceHandler( android_sms_app_manager_(android_sms_app_manager), multidevice_setup_observer_(this), android_sms_pairing_state_tracker_observer_(this), - android_sms_app_manager_observer_(this), - callback_weak_ptr_factory_(this) { - RegisterPrefChangeListeners(); + android_sms_app_manager_observer_(this) { + pref_change_registrar_.Init(prefs_); } MultideviceHandler::~MultideviceHandler() {} @@ -123,9 +122,22 @@ void MultideviceHandler::OnJavascriptAllowed() { if (android_sms_app_manager_) android_sms_app_manager_observer_.Add(android_sms_app_manager_); + + pref_change_registrar_.Add( + proximity_auth::prefs::kProximityAuthIsChromeOSLoginEnabled, + base::BindRepeating( + &MultideviceHandler::NotifySmartLockSignInEnabledChanged, + base::Unretained(this))); + pref_change_registrar_.Add( + multidevice_setup::kSmartLockSigninAllowedPrefName, + base::BindRepeating( + &MultideviceHandler::NotifySmartLockSignInAllowedChanged, + base::Unretained(this))); } void MultideviceHandler::OnJavascriptDisallowed() { + pref_change_registrar_.RemoveAll(); + if (multidevice_setup_client_) multidevice_setup_observer_.Remove(multidevice_setup_client_); @@ -377,23 +389,7 @@ MultideviceHandler::GeneratePageContentDataDictionary() { return page_content_dictionary; } -void MultideviceHandler::RegisterPrefChangeListeners() { - pref_change_registrar_.Init(prefs_); - pref_change_registrar_.Add( - proximity_auth::prefs::kProximityAuthIsChromeOSLoginEnabled, - base::BindRepeating( - &MultideviceHandler::NotifySmartLockSignInEnabledChanged, - base::Unretained(this))); - pref_change_registrar_.Add( - multidevice_setup::kSmartLockSigninAllowedPrefName, - base::BindRepeating( - &MultideviceHandler::NotifySmartLockSignInAllowedChanged, - base::Unretained(this))); -} - void MultideviceHandler::NotifySmartLockSignInEnabledChanged() { - AllowJavascript(); - bool sign_in_enabled = prefs_->GetBoolean( proximity_auth::prefs::kProximityAuthIsChromeOSLoginEnabled); FireWebUIListener("smart-lock-signin-enabled-changed", diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h index efb5ac7c6e9..8ee0b692ac1 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h @@ -82,7 +82,6 @@ class MultideviceHandler void OnSetFeatureStateEnabledResult(const std::string& js_callback_id, bool success); - void RegisterPrefChangeListeners(); void NotifySmartLockSignInEnabledChanged(); void NotifySmartLockSignInAllowedChanged(); // Generate android sms info dictionary containing the messages for web @@ -126,7 +125,7 @@ class MultideviceHandler android_sms_app_manager_observer_; // Used to cancel callbacks when JavaScript becomes disallowed. - base::WeakPtrFactory<MultideviceHandler> callback_weak_ptr_factory_; + base::WeakPtrFactory<MultideviceHandler> callback_weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MultideviceHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc index 8af51c05725..e0efafd8f75 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc @@ -124,7 +124,7 @@ class MultideviceHandlerTest : public testing::Test { fake_android_sms_app_manager_ = std::make_unique<android_sms::FakeAndroidSmsAppManager>(); - prefs_.reset(new TestingPrefServiceSimple()); + prefs_ = std::make_unique<TestingPrefServiceSimple>(); handler_ = std::make_unique<TestMultideviceHandler>( prefs_.get(), fake_multidevice_setup_client_.get(), diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc index d01be34282e..a0fd1fe87ff 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc @@ -11,15 +11,21 @@ #include <utility> #include <vector> +#include "ash/public/cpp/network_config_service.h" #include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" +#include "base/bind.h" +#include "base/feature_list.h" #include "build/build_config.h" +#include "chrome/browser/ui/webui/app_management/app_management.mojom.h" +#include "chrome/browser/ui/webui/app_management/app_management_page_handler.h" #include "chrome/browser/ui/webui/managed_ui_handler.h" #include "chrome/browser/ui/webui/metrics_handler.h" #include "chrome/browser/ui/webui/plural_string_handler.h" #include "chrome/browser/ui/webui/settings/about_handler.h" #include "chrome/browser/ui/webui/settings/accessibility_main_handler.h" -#include "chrome/browser/ui/webui/settings/appearance_handler.h" #include "chrome/browser/ui/webui/settings/browser_lifetime_handler.h" +#include "chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h" +#include "chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h" #include "chrome/browser/ui/webui/settings/downloads_handler.h" #include "chrome/browser/ui/webui/settings/extension_control_handler.h" #include "chrome/browser/ui/webui/settings/languages_handler.h" @@ -33,22 +39,25 @@ #include "chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.h" #include "chrome/browser/ui/webui/settings/settings_ui.h" #include "chrome/browser/web_applications/system_web_app_manager.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" #include "chrome/grit/os_settings_resources.h" #include "chrome/grit/os_settings_resources_map.h" -#include "chromeos/services/network_config/public/mojom/constants.mojom.h" +#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/unified_consent/feature.h" #include "content/public/browser/web_ui_data_source.h" -#include "services/service_manager/public/cpp/connector.h" namespace chromeos { namespace settings { OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) - : ui::MojoWebUIController(web_ui, /*enable_chrome_send =*/true) { + : ui::MojoWebUIController(web_ui, /*enable_chrome_send=*/true), + webui_load_timer_(web_ui->GetWebContents(), + "ChromeOS.Settings.LoadDocumentTime", + "ChromeOS.Settings.LoadCompletedTime") { Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUIOSSettingsHost); @@ -62,8 +71,9 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) // page_visibility.js). html_source->AddBoolean("showOSSettings", true); - AddSettingsPageUIHandler( - std::make_unique<::settings::AppearanceHandler>(web_ui)); + html_source->AddBoolean( + "showParentalControls", + chromeos::settings::ShouldShowParentalControls(profile)); AddSettingsPageUIHandler( std::make_unique<::settings::AccessibilityMainHandler>()); @@ -86,10 +96,21 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) std::make_unique<::settings::ProtocolHandlersHandler>()); AddSettingsPageUIHandler( std::make_unique<::settings::SearchEnginesHandler>(profile)); + AddSettingsPageUIHandler( + std::make_unique<chromeos::settings::WallpaperHandler>(web_ui)); html_source->AddBoolean("unifiedConsentEnabled", unified_consent::IsUnifiedConsentFeatureEnabled()); + html_source->AddBoolean( + "showApps", base::FeatureList::IsEnabled(features::kAppManagement)); + +#if defined(OS_CHROMEOS) + html_source->AddBoolean( + "isSupportedArcVersion", + AppManagementPageHandler::IsCurrentArcVersionSupported(profile)); +#endif // OS_CHROMEOS + AddSettingsPageUIHandler( base::WrapUnique(::settings::AboutHandler::Create(html_source, profile))); AddSettingsPageUIHandler(base::WrapUnique( @@ -122,6 +143,17 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) html_source->SetDefaultResource(IDR_OS_SETTINGS_SETTINGS_HTML); #endif + html_source->AddResourcePath("app-management/app_management.mojom-lite.js", + IDR_APP_MANAGEMENT_MOJO_LITE_JS); + html_source->AddResourcePath("app-management/types.mojom-lite.js", + IDR_APP_MANAGEMENT_TYPES_MOJO_LITE_JS); + html_source->AddResourcePath("app-management/bitmap.mojom-lite.js", + IDR_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS); + html_source->AddResourcePath("app-management/image.mojom-lite.js", + IDR_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS); + html_source->AddResourcePath("app-management/image_info.mojom-lite.js", + IDR_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS); + ::settings::AddLocalizedStrings(html_source, profile); auto plural_string_handler = std::make_unique<PluralStringHandler>(); @@ -136,6 +168,10 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) AddHandlerToRegistry(base::BindRepeating(&OSSettingsUI::BindCrosNetworkConfig, base::Unretained(this))); + + AddHandlerToRegistry( + base::BindRepeating(&OSSettingsUI::BindAppManagementPageHandlerFactory, + base::Unretained(this))); } OSSettingsUI::~OSSettingsUI() = default; @@ -148,9 +184,17 @@ void OSSettingsUI::AddSettingsPageUIHandler( void OSSettingsUI::BindCrosNetworkConfig( network_config::mojom::CrosNetworkConfigRequest request) { - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()) - ->BindInterface(network_config::mojom::kServiceName, std::move(request)); + ash::GetNetworkConfigService(std::move(request)); +} + +void OSSettingsUI::BindAppManagementPageHandlerFactory( + app_management::mojom::PageHandlerFactoryRequest request) { + if (!app_management_page_handler_factory_) { + app_management_page_handler_factory_ = + std::make_unique<AppManagementPageHandlerFactory>( + Profile::FromWebUI(web_ui())); + } + app_management_page_handler_factory_->Bind(std::move(request)); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h index 4e600afc38b..63131cfb6f6 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h @@ -8,8 +8,10 @@ #include <memory> #include "base/macros.h" -#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" -#include "content/public/browser/web_ui_controller.h" +#include "chrome/browser/ui/webui/app_management/app_management.mojom-forward.h" +#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h" +#include "chrome/browser/ui/webui/webui_load_timer.h" +#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom-forward.h" #include "ui/webui/mojo_web_ui_controller.h" namespace content { @@ -30,8 +32,13 @@ class OSSettingsUI : public ui::MojoWebUIController { std::unique_ptr<content::WebUIMessageHandler> handler); void BindCrosNetworkConfig( network_config::mojom::CrosNetworkConfigRequest request); + void BindAppManagementPageHandlerFactory( + app_management::mojom::PageHandlerFactoryRequest request); - // TODO(crbug/950007): Create load histograms and embed WebuiLoadTimer. + WebuiLoadTimer webui_load_timer_; + + std::unique_ptr<AppManagementPageHandlerFactory> + app_management_page_handler_factory_; DISALLOW_COPY_AND_ASSIGN(OSSettingsUI); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc index b76ceac4ab6..19182163f23 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc @@ -9,8 +9,9 @@ #include "base/values.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" -#include "chrome/browser/chromeos/arc/arc_session_manager.h" +#include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_navigator_params.h" @@ -18,7 +19,7 @@ #include "chrome/services/app_service/public/cpp/app_registry_cache.h" #include "chrome/services/app_service/public/cpp/app_update.h" #include "chrome/services/app_service/public/mojom/types.mojom.h" -#include "components/arc/arc_util.h" +#include "chromeos/constants/chromeos_features.h" #include "ui/base/page_transition_types.h" #include "ui/base/window_open_disposition.h" #include "ui/display/types/display_constants.h" @@ -81,19 +82,32 @@ void ParentalControlsHandler::HandleLaunchFamilyLinkSettings( proxy->Launch(app_id, ui::EventFlags::EF_NONE, apps::mojom::LaunchSource::kFromParentalControls, display::kDefaultDisplayId); - } else if (arc::IsArcAvailable() && - arc::ArcSessionManager::Get()->IsAllowed()) { - // No FLH app installed, but ARC is enabled so launch Play Store - // to FLH app install page. - arc::LaunchPlayStoreWithUrl(kFamilyLinkChildHelperAppPlayStoreURL); - } else { - // As a last resort, launch browser to the family link site. - NavigateParams params(profile_, GURL(kFamilyLinkSiteURL), - ui::PAGE_TRANSITION_FROM_API); - params.disposition = WindowOpenDisposition::NEW_WINDOW; - params.window_action = NavigateParams::SHOW_WINDOW; - Navigate(¶ms); + return; } + // No FLH app installed, so try to launch Play Store to FLH app install page. + // If there is no Play Store available LaunchPlayStoreWithUrl() will return + // false. + if (arc::LaunchPlayStoreWithUrl(kFamilyLinkChildHelperAppPlayStoreURL)) { + return; + } + // As a last resort, launch browser to the family link site. + NavigateParams params(profile_, GURL(kFamilyLinkSiteURL), + ui::PAGE_TRANSITION_FROM_API); + params.disposition = WindowOpenDisposition::NEW_WINDOW; + params.window_action = NavigateParams::SHOW_WINDOW; + Navigate(¶ms); +} + +bool ShouldShowParentalControls(Profile* profile) { + // Show Parental controls for regular and child accounts that are the + // primary profile. Do not show it to any secondary profiles, managed + // accounts that aren't child accounts (i.e. enterprise and EDU accounts), + // OTR accounts, or legacy supervised user accounts. + return chromeos::features::IsParentalControlsSettingsEnabled() && + profile == ProfileManager::GetPrimaryUserProfile() && + !profile->IsLegacySupervised() && !profile->IsGuestSession() && + (profile->IsChild() || + !profile->GetProfilePolicyConnector()->IsManaged()); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h index cb498d3db33..517bc1b50fd 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h @@ -37,6 +37,9 @@ class ParentalControlsHandler : public ::settings::SettingsPageUIHandler { DISALLOW_COPY_AND_ASSIGN(ParentalControlsHandler); }; +// Indicates whether parental controls should be shown in the settings UI. +bool ShouldShowParentalControls(Profile* profile); + } // namespace settings } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc index 09518e994a3..715782b0b11 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc @@ -18,8 +18,7 @@ namespace chromeos { namespace settings { -PluginVmHandler::PluginVmHandler(Profile* profile) - : profile_(profile), weak_ptr_factory_(this) {} +PluginVmHandler::PluginVmHandler(Profile* profile) : profile_(profile) {} PluginVmHandler::~PluginVmHandler() = default; @@ -59,7 +58,8 @@ void PluginVmHandler::HandleRemovePluginVmSharedPath( vm_name, base::FilePath(path), /*unpersist=*/true, base::BindOnce( - [](const std::string& path, bool result, std::string failure_reason) { + [](const std::string& path, bool result, + const std::string& failure_reason) { if (!result) { LOG(ERROR) << "Error unsharing " << path << ": " << failure_reason; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h index 64e9d850299..d57b34da1db 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h @@ -35,7 +35,7 @@ class PluginVmHandler : public ::settings::SettingsPageUIHandler { Profile* profile_; // weak_ptr_factory_ should always be last member. - base::WeakPtrFactory<PluginVmHandler> weak_ptr_factory_; + base::WeakPtrFactory<PluginVmHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PluginVmHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.cc new file mode 100644 index 00000000000..5f169f010f8 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.cc @@ -0,0 +1,67 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h" + +#include "base/bind.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/ash/wallpaper_controller_client.h" +#include "content/public/browser/web_ui.h" + +namespace chromeos { +namespace settings { + +WallpaperHandler::WallpaperHandler(content::WebUI* webui) + : profile_(Profile::FromWebUI(webui)) {} + +WallpaperHandler::~WallpaperHandler() = default; + +void WallpaperHandler::OnJavascriptAllowed() {} +void WallpaperHandler::OnJavascriptDisallowed() {} + +void WallpaperHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "openWallpaperManager", + base::BindRepeating(&WallpaperHandler::HandleOpenWallpaperManager, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "isWallpaperSettingVisible", + base::BindRepeating(&WallpaperHandler::HandleIsWallpaperSettingVisible, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "isWallpaperPolicyControlled", + base::BindRepeating(&WallpaperHandler::HandleIsWallpaperPolicyControlled, + base::Unretained(this))); +} + +void WallpaperHandler::HandleIsWallpaperSettingVisible( + const base::ListValue* args) { + CHECK_EQ(args->GetSize(), 1U); + ResolveCallback( + args->GetList()[0], + WallpaperControllerClient::Get()->ShouldShowWallpaperSetting()); +} + +void WallpaperHandler::HandleIsWallpaperPolicyControlled( + const base::ListValue* args) { + CHECK_EQ(args->GetSize(), 1U); + bool result = WallpaperControllerClient::Get() + ->IsActiveUserWallpaperControlledByPolicy(); + ResolveCallback(args->GetList()[0], result); +} + +void WallpaperHandler::HandleOpenWallpaperManager(const base::ListValue* args) { + WallpaperControllerClient::Get()->OpenWallpaperPickerIfAllowed(); +} + +void WallpaperHandler::ResolveCallback(const base::Value& callback_id, + bool result) { + AllowJavascript(); + ResolveJavascriptCallback(callback_id, base::Value(result)); +} + +} // namespace settings +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h new file mode 100644 index 00000000000..6e0c811b9e0 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h @@ -0,0 +1,56 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_WALLPAPER_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_WALLPAPER_HANDLER_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" + +namespace base { +class ListValue; +} + +namespace content { +class WebUI; +} + +class Profile; + +namespace chromeos { +namespace settings { + +// Chrome "Personalization" settings page UI handler. +class WallpaperHandler : public ::settings::SettingsPageUIHandler { + public: + explicit WallpaperHandler(content::WebUI* webui); + ~WallpaperHandler() override; + + // SettingsPageUIHandler implementation. + void RegisterMessages() override; + void OnJavascriptAllowed() override; + void OnJavascriptDisallowed() override; + + private: + // Whether the wallpaper setting should be shown. + void HandleIsWallpaperSettingVisible(const base::ListValue* args); + + // Whether the wallpaper is policy controlled. + void HandleIsWallpaperPolicyControlled(const base::ListValue* args); + + // Open the wallpaper manager app. + void HandleOpenWallpaperManager(const base::ListValue* args); + + // Helper function to resolve the Javascript callback. + void ResolveCallback(const base::Value& callback_id, bool result); + + Profile* const profile_; + + DISALLOW_COPY_AND_ASSIGN(WallpaperHandler); +}; + +} // namespace settings +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_WALLPAPER_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/downloads_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/downloads_handler_unittest.cc index 7e7628fb021..80ea9d4632c 100644 --- a/chromium/chrome/browser/ui/webui/settings/downloads_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/downloads_handler_unittest.cc @@ -13,8 +13,8 @@ #include "chrome/test/base/testing_profile.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui.h" +#include "content/public/test/browser_task_environment.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" #include "testing/gtest/include/gtest/gtest.h" @@ -74,7 +74,7 @@ class DownloadsHandlerTest : public testing::Test { DownloadsHandler* handler() { return &handler_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; content::TestWebUI test_web_ui_; TestingProfile profile_; diff --git a/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler_unittest.cc index d5adb2866a2..c33bd5da63e 100644 --- a/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler_unittest.cc @@ -2,7 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#if defined(GOOGLE_CHROME_BUILD) && !defined(OS_CHROMEOS) +#include "build/branding_buildflags.h" + +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && !defined(OS_CHROMEOS) #include "chrome/browser/ui/webui/settings/metrics_reporting_handler.h" @@ -18,7 +20,7 @@ #include "components/policy/policy_constants.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,10 +36,10 @@ class MetricsReportingHandlerTest : public testing::Test { public: MetricsReportingHandlerTest() { // Local state must be set up before |handler_|. - local_state_.reset(new ScopedTestingLocalState( - TestingBrowserProcess::GetGlobal())); + local_state_ = std::make_unique<ScopedTestingLocalState>( + TestingBrowserProcess::GetGlobal()); - handler_.reset(new TestingMetricsReportingHandler); + handler_ = std::make_unique<TestingMetricsReportingHandler>(); handler_->set_web_ui(&test_web_ui_); EXPECT_CALL(provider_, IsInitializationComplete(testing::_)).WillRepeatedly( @@ -75,7 +77,7 @@ class MetricsReportingHandlerTest : public testing::Test { policy::MockConfigurationPolicyProvider* provider() { return &provider_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; content::TestWebUI test_web_ui_; std::unique_ptr<ScopedTestingLocalState> local_state_; std::unique_ptr<TestingMetricsReportingHandler> handler_; @@ -124,4 +126,4 @@ TEST_F(MetricsReportingHandlerTest, PolicyChangesNotifyPage) { } // namespace settings -#endif // defined(GOOGLE_CHROME_BUILD) && !defined(OS_CHROMEOS) +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) && !defined(OS_CHROMEOS) diff --git a/chromium/chrome/browser/ui/webui/settings/on_startup_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/on_startup_handler_unittest.cc index 6a2dd312163..2b60755b794 100644 --- a/chromium/chrome/browser/ui/webui/settings/on_startup_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/on_startup_handler_unittest.cc @@ -17,7 +17,7 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -58,7 +58,7 @@ class OnStartupHandlerTest : public testing::Test { profile_ = profile_manager_.CreateTestingProfile("Profile 1"); #endif - handler_.reset(new TestOnStartupHandler(profile_)); + handler_ = std::make_unique<TestOnStartupHandler>(profile_); handler_->set_web_ui(&web_ui_); } @@ -67,7 +67,7 @@ class OnStartupHandlerTest : public testing::Test { content::TestWebUI* web_ui() { return &web_ui_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_; std::unique_ptr<TestOnStartupHandler> handler_; Profile* profile_; diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.cc b/chromium/chrome/browser/ui/webui/settings/people_handler.cc index 3ea106d0157..5d7331dbf92 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.cc @@ -36,7 +36,6 @@ #include "components/autofill/core/common/autofill_prefs.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_error_controller.h" -#include "components/signin/core/browser/signin_header_helper.h" #include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_mutator.h" @@ -221,6 +220,7 @@ base::string16 GetEnterPassphraseBody(syncer::PassphraseType passphrase_type, base::TimeFormatShortDate(passphrase_time)); case syncer::PassphraseType::IMPLICIT_PASSPHRASE: case syncer::PassphraseType::KEYSTORE_PASSPHRASE: + case syncer::PassphraseType::TRUSTED_VAULT_PASSPHRASE: case syncer::PassphraseType::PASSPHRASE_TYPE_SIZE: break; } @@ -243,6 +243,7 @@ base::string16 GetFullEncryptionBody(syncer::PassphraseType passphrase_type, base::TimeFormatShortDate(passphrase_time)); case syncer::PassphraseType::IMPLICIT_PASSPHRASE: case syncer::PassphraseType::KEYSTORE_PASSPHRASE: + case syncer::PassphraseType::TRUSTED_VAULT_PASSPHRASE: case syncer::PassphraseType::PASSPHRASE_TYPE_SIZE: break; } @@ -303,6 +304,10 @@ void PeopleHandler::RegisterMessages() { "SyncSetupGetSyncStatus", base::BindRepeating(&PeopleHandler::HandleGetSyncStatus, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "SyncPrefsDispatch", + base::BindRepeating(&PeopleHandler::HandleSyncPrefsDispatch, + base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( "AttemptUserExit", @@ -404,13 +409,11 @@ void PeopleHandler::DisplayGaiaLoginInNewTabOrWindow( SigninErrorController* error_controller = SigninErrorControllerFactory::GetForProfile(browser->profile()); DCHECK(error_controller->HasError()); - browser->window()->ShowAvatarBubbleFromAvatarButton( - BrowserWindow::AVATAR_BUBBLE_MODE_REAUTH, - signin::ManageAccountsParams(), access_point, false); + browser->window()->ShowAvatarBubbleFromAvatarButton( + BrowserWindow::AVATAR_BUBBLE_MODE_REAUTH, access_point, false); } else { browser->window()->ShowAvatarBubbleFromAvatarButton( - BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, - signin::ManageAccountsParams(), access_point, false); + BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, access_point, false); } } #endif @@ -426,7 +429,7 @@ void PeopleHandler::DisplaySpinner() { const int kTimeoutSec = 30; DCHECK(!engine_start_timer_); - engine_start_timer_.reset(new base::OneShotTimer()); + engine_start_timer_ = std::make_unique<base::OneShotTimer>(); engine_start_timer_->Start(FROM_HERE, base::TimeDelta::FromSeconds(kTimeoutSec), this, &PeopleHandler::DisplayTimeout); @@ -554,7 +557,7 @@ base::Value PeopleHandler::GetStoredAccountsList() { // account. auto* identity_manager = IdentityManagerFactory::GetForProfile(profile_); base::Optional<AccountInfo> primary_account_info = - identity_manager->FindExtendedAccountInfoForAccount( + identity_manager->FindExtendedAccountInfoForAccountWithRefreshToken( identity_manager->GetPrimaryAccountInfo()); if (primary_account_info.has_value()) accounts_list.push_back(GetAccountValue(primary_account_info.value())); @@ -575,7 +578,7 @@ void PeopleHandler::HandleStartSyncingWithEmail(const base::ListValue* args) { base::Optional<AccountInfo> maybe_account = IdentityManagerFactory::GetForProfile(profile_) - ->FindAccountInfoForAccountWithRefreshTokenByEmailAddress( + ->FindExtendedAccountInfoForAccountWithRefreshTokenByEmailAddress( email->GetString()); signin_ui_util::EnableSyncFromPromo( @@ -850,6 +853,11 @@ void PeopleHandler::HandleGetSyncStatus(const base::ListValue* args) { ResolveJavascriptCallback(*callback_id, *GetSyncStatusDictionary()); } +void PeopleHandler::HandleSyncPrefsDispatch(const base::ListValue* args) { + AllowJavascript(); + PushSyncPrefs(); +} + void PeopleHandler::CloseSyncSetup() { // Stop a timer to handle timeout in waiting for checking network connection. engine_start_timer_.reset(); @@ -1037,9 +1045,8 @@ std::unique_ptr<base::DictionaryValue> PeopleHandler::GetSyncStatusDictionary() "disabled", !service || disallowed_by_policy || !service->GetUserSettings()->IsSyncAllowedByPlatform()); sync_status->SetBoolean("signedIn", identity_manager->HasPrimaryAccount()); - sync_status->SetString( - "signedInUsername", - signin_ui_util::GetAuthenticatedUsername(identity_manager)); + sync_status->SetString("signedInUsername", + signin_ui_util::GetAuthenticatedUsername(profile_)); sync_status->SetBoolean("hasUnrecoverableError", service && service->HasUnrecoverableError()); return sync_status; diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.h b/chromium/chrome/browser/ui/webui/settings/people_handler.h index 83cd8916760..51e9195e619 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.h @@ -176,6 +176,7 @@ class PeopleHandler : public SettingsPageUIHandler, void HandleSetEncryption(const base::ListValue* args); void HandleShowSetupUI(const base::ListValue* args); void HandleAttemptUserExit(const base::ListValue* args); + void HandleSyncPrefsDispatch(const base::ListValue* args); #if defined(OS_CHROMEOS) void HandleRequestPinLoginState(const base::ListValue* args); #endif 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 87b349ecacc..1a327ed2a6f 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc @@ -46,8 +46,8 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_controller.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/navigation_simulator.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "content/public/test/web_contents_tester.h" #include "testing/gtest/include/gtest/gtest.h" @@ -109,6 +109,8 @@ std::string GetConfiguration(const base::DictionaryValue* extra_values, types.Has(syncer::UserSelectableType::kExtensions)); result.SetBoolean("passwordsSynced", types.Has(syncer::UserSelectableType::kPasswords)); + result.SetBoolean("wifiConfigurationsSynced", + types.Has(syncer::UserSelectableType::kWifiConfigurations)); result.SetBoolean("preferencesSynced", types.Has(syncer::UserSelectableType::kPreferences)); result.SetBoolean("tabsSynced", types.Has(syncer::UserSelectableType::kTabs)); @@ -164,6 +166,8 @@ void CheckConfigDataTypeArguments(const base::DictionaryValue* dictionary, types.Has(syncer::UserSelectableType::kExtensions)); CheckBool(dictionary, "passwordsSynced", types.Has(syncer::UserSelectableType::kPasswords)); + CheckBool(dictionary, "wifiConfigurationsSynced", + types.Has(syncer::UserSelectableType::kWifiConfigurations)); CheckBool(dictionary, "preferencesSynced", types.Has(syncer::UserSelectableType::kPreferences)); CheckBool(dictionary, "tabsSynced", @@ -249,7 +253,7 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { &PeopleHandlerTest::OnSetupInProgressHandleDestroyed, base::Unretained(this)))))); - handler_.reset(new TestingPeopleHandler(&web_ui_, profile())); + handler_ = std::make_unique<TestingPeopleHandler>(&web_ui_, profile()); handler_->AllowJavascript(); web_ui_.set_web_contents(web_contents()); } @@ -262,12 +266,9 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { ChromeRenderViewHostTestHarness::TearDown(); } - content::BrowserContext* CreateBrowserContext() override { - // Setup the profile. - std::unique_ptr<TestingProfile> profile = - IdentityTestEnvironmentProfileAdaptor:: - CreateProfileForIdentityTestEnvironment(); - return profile.release(); + TestingProfile::TestingFactories GetTestingFactories() const override { + return IdentityTestEnvironmentProfileAdaptor:: + GetIdentityTestEnvironmentFactories(); } // Setup the expectations for calls made when displaying the config page. @@ -1107,6 +1108,7 @@ TEST_F(PeopleHandlerTest, ShowSetupSyncEverything) { CheckBool(dictionary, "bookmarksRegistered", true); CheckBool(dictionary, "extensionsRegistered", true); CheckBool(dictionary, "passwordsRegistered", true); + CheckBool(dictionary, "wifiConfigurationsRegistered", true); CheckBool(dictionary, "preferencesRegistered", true); CheckBool(dictionary, "tabsRegistered", true); CheckBool(dictionary, "themesRegistered", true); @@ -1402,7 +1404,7 @@ TEST_P(PeopleHandlerDiceUnifiedConsentTest, StoredAccountsList) { base::CommandLine::ForCurrentProcess()->AppendSwitch(switches::kNoFirstRun); ASSERT_FALSE(first_run::IsChromeFirstRun()); - content::TestBrowserThreadBundle test_browser_thread_bundle; + content::BrowserTaskEnvironment task_environment; // Decode test parameters. bool dice_enabled; diff --git a/chromium/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc index a5229444221..8bccab5cf80 100644 --- a/chromium/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc @@ -14,7 +14,7 @@ #include "chrome/test/base/testing_profile_manager.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/web_ui_data_source.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "net/base/data_url.h" #include "testing/gtest/include/gtest/gtest.h" @@ -66,7 +66,7 @@ class ProfileInfoHandlerTest : public testing::Test { profile_ = profile_manager_.CreateTestingProfile("Profile 1"); #endif - handler_.reset(new TestProfileInfoHandler(profile_)); + handler_ = std::make_unique<TestProfileInfoHandler>(profile_); handler_->set_web_ui(&web_ui_); } @@ -101,7 +101,7 @@ class ProfileInfoHandlerTest : public testing::Test { TestProfileInfoHandler* handler() const { return handler_.get(); } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_; content::TestWebUI web_ui_; 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 a1ef45f40ef..7dae9628108 100644 --- a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc @@ -212,17 +212,17 @@ void ResetSettingsHandler::OnGetReportedSettingsDone(std::string callback_id) { void ResetSettingsHandler::OnShowResetProfileDialog( const base::ListValue* args) { if (!GetResetter()->IsActive()) { - setting_snapshot_.reset(new ResettableSettingsSnapshot(profile_)); + setting_snapshot_ = std::make_unique<ResettableSettingsSnapshot>(profile_); } if (brandcode_.empty()) return; - config_fetcher_.reset(new BrandcodeConfigFetcher( + config_fetcher_ = std::make_unique<BrandcodeConfigFetcher>( g_browser_process->system_network_context_manager() ->GetURLLoaderFactory(), base::Bind(&ResetSettingsHandler::OnSettingsFetched, base::Unretained(this)), - GURL("https://tools.google.com/service/update2"), brandcode_)); + GURL("https://tools.google.com/service/update2"), brandcode_); } void ResetSettingsHandler::OnHideResetProfileDialog( @@ -260,7 +260,7 @@ void ResetSettingsHandler::ResetProfile( // If failed to fetch BrandcodedDefaultSettings or this is an organic // installation, use default settings. if (!default_settings) - default_settings.reset(new BrandcodedDefaultSettings); + default_settings = std::make_unique<BrandcodedDefaultSettings>(); GetResetter()->Reset( ProfileResetter::ALL, std::move(default_settings), @@ -275,7 +275,7 @@ void ResetSettingsHandler::ResetProfile( ProfileResetter* ResetSettingsHandler::GetResetter() { if (!resetter_) - resetter_.reset(new ProfileResetter(profile_)); + resetter_ = std::make_unique<ProfileResetter>(profile_); return resetter_.get(); } diff --git a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler_unittest.cc index 7c8f38e8be7..b21f85e169b 100644 --- a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler_unittest.cc @@ -11,7 +11,7 @@ #include "chrome/browser/ui/webui/settings/reset_settings_handler.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" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -73,7 +73,8 @@ class ResetSettingsHandlerTest : public testing::Test { public: ResetSettingsHandlerTest() { google_brand::BrandForTesting brand_for_testing(""); - handler_.reset(new TestingResetSettingsHandler(&profile_, &web_ui_)); + handler_ = + std::make_unique<TestingResetSettingsHandler>(&profile_, &web_ui_); } TestingResetSettingsHandler* handler() { return handler_.get(); } @@ -81,7 +82,7 @@ class ResetSettingsHandlerTest : public testing::Test { private: // The order here matters. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; content::TestWebUI web_ui_; std::unique_ptr<TestingResetSettingsHandler> handler_; 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 24247be5a14..37eab4887a8 100644 --- a/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc @@ -195,8 +195,8 @@ SearchEnginesHandler::CreateDictionaryForEngine(int index, bool is_default) { "keyword", table_model->GetText(index, IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN)); Profile* profile = Profile::FromWebUI(web_ui()); - dict->SetString("url", template_url->url_ref().DisplayURL( - UIThreadSearchTermsData(profile))); + dict->SetString( + "url", template_url->url_ref().DisplayURL(UIThreadSearchTermsData())); dict->SetBoolean("urlLocked", template_url->prepopulate_id() > 0); GURL icon_url = template_url->favicon_url(); if (icon_url.is_valid()) @@ -284,10 +284,10 @@ void SearchEnginesHandler::HandleSearchEngineEditStarted( return; } - edit_controller_.reset(new EditSearchEngineController( + edit_controller_ = std::make_unique<EditSearchEngineController>( index == kNewSearchEngineIndex ? nullptr : list_controller_.GetTemplateURL(index), - this, Profile::FromWebUI(web_ui()))); + this, Profile::FromWebUI(web_ui())); } void SearchEnginesHandler::OnEditedKeyword(TemplateURL* template_url, 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 d9c05922474..25dbe1f03e7 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 @@ -20,6 +20,7 @@ #include "chrome/grit/generated_resources.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_process_host.h" +#include "content/public/browser/same_site_data_remover.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_ui.h" @@ -130,6 +131,7 @@ void CookiesViewHandler::OnJavascriptAllowed() { } void CookiesViewHandler::OnJavascriptDisallowed() { + callback_weak_ptr_factory_.InvalidateWeakPtrs(); } void CookiesViewHandler::RegisterMessages() { @@ -164,6 +166,10 @@ void CookiesViewHandler::RegisterMessages() { base::BindRepeating(&CookiesViewHandler::HandleRemove, base::Unretained(this))); web_ui()->RegisterMessageCallback( + "localData.removeThirdPartyCookies", + base::BindRepeating(&CookiesViewHandler::HandleRemoveThirdParty, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "localData.reload", base::BindRepeating(&CookiesViewHandler::HandleReloadCookies, base::Unretained(this))); @@ -244,6 +250,13 @@ void CookiesViewHandler::EnsureCookiesTreeModelCreated() { } } +void CookiesViewHandler::RecreateCookiesTreeModel() { + cookies_tree_model_.reset(); + filter_.clear(); + sorted_sites_.clear(); + EnsureCookiesTreeModelCreated(); +} + void CookiesViewHandler::HandleGetCookieDetails(const base::ListValue* args) { CHECK(request_.callback_id_.empty()); CHECK_EQ(2U, args->GetSize()); @@ -306,10 +319,7 @@ void CookiesViewHandler::HandleReloadCookies(const base::ListValue* args) { CHECK(args->GetString(0, &request_.callback_id_)); AllowJavascript(); - cookies_tree_model_.reset(); - filter_.clear(); - sorted_sites_.clear(); - EnsureCookiesTreeModelCreated(); + RecreateCookiesTreeModel(); } void CookiesViewHandler::HandleRemoveAll(const base::ListValue* args) { @@ -335,6 +345,20 @@ void CookiesViewHandler::HandleRemove(const base::ListValue* args) { } } +void CookiesViewHandler::HandleRemoveThirdParty(const base::ListValue* args) { + CHECK(request_.callback_id_.empty()); + CHECK_EQ(1U, args->GetSize()); + CHECK(args->GetString(0, &request_.callback_id_)); + + AllowJavascript(); + Profile* profile = Profile::FromWebUI(web_ui()); + ClearSameSiteNoneData( + base::BindOnce(&CookiesViewHandler::RecreateCookiesTreeModel, + callback_weak_ptr_factory_.GetWeakPtr()), + profile, + /* clear_storage */ true); +} + void CookiesViewHandler::HandleRemoveShownItems(const base::ListValue* args) { CHECK_EQ(0U, args->GetSize()); diff --git a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h index 574978c9b97..d5a031bf16a 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h @@ -49,6 +49,9 @@ class CookiesViewHandler : public SettingsPageUIHandler, // Creates the CookiesTreeModel if necessary. void EnsureCookiesTreeModelCreated(); + // Resets the CookiesTreeModel, the current |filter_|, and the site list. + void RecreateCookiesTreeModel(); + // Set |filter_| and get a portion (or all) of the list items. void HandleGetDisplayList(const base::ListValue* args); @@ -70,6 +73,9 @@ class CookiesViewHandler : public SettingsPageUIHandler, // Remove selected sites data. void HandleRemove(const base::ListValue* args); + // Removes cookies and site data available in third-party contexts. + void HandleRemoveThirdParty(const base::ListValue* args); + // Get children nodes data and pass it to 'CookiesView.loadChildren' to // update the WebUI. void SendChildren(const CookieTreeNode* parent); @@ -111,6 +117,9 @@ class CookiesViewHandler : public SettingsPageUIHandler, std::unique_ptr<CookiesTreeModelUtil> model_util_; + // Used to cancel callbacks when JavaScript becomes disallowed. + base::WeakPtrFactory<CookiesViewHandler> callback_weak_ptr_factory_{this}; + DISALLOW_COPY_AND_ASSIGN(CookiesViewHandler); }; 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 f546887fdfc..b2e78bd722b 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 @@ -147,7 +147,7 @@ void ImportDataHandler::InitializeDialog(const base::ListValue* args) { std::string callback_id; CHECK(args->GetString(0, &callback_id)); - importer_list_.reset(new ImporterList()); + importer_list_ = std::make_unique<ImporterList>(); importer_list_->DetectSourceProfiles( g_browser_process->GetApplicationLocale(), true, // include_interactive_profiles diff --git a/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 9dc2fca39cb..3ff5f45c78b 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc @@ -13,6 +13,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/win/windows_version.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "build/buildflag.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" @@ -40,6 +41,7 @@ #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_payments_features.h" +#include "components/browsing_data/core/features.h" #include "components/google/core/common/google_util.h" #include "components/omnibox/common/omnibox_features.h" #include "components/password_manager/core/browser/manage_passwords_referrer.h" @@ -59,12 +61,14 @@ #include "media/base/media_switches.h" #include "net/base/url_util.h" #include "services/device/public/cpp/device_features.h" +#include "third_party/blink/public/common/features.h" #include "ui/accessibility/accessibility_switches.h" +#include "ui/base/accelerators/accelerator.h" #include "ui/base/l10n/l10n_util.h" #if defined(OS_CHROMEOS) #include "ash/public/cpp/ash_switches.h" -#include "ash/public/interfaces/voice_interaction_controller.mojom.h" +#include "ash/public/mojom/voice_interaction_controller.mojom.h" #include "base/system/sys_info.h" #include "chrome/browser/chromeos/account_manager/account_manager_util.h" #include "chrome/browser/chromeos/arc/arc_util.h" @@ -81,6 +85,7 @@ #include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h" #include "chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.h" #include "chrome/common/pref_names.h" +#include "chrome/common/webui_url_constants.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/services/assistant/public/features.h" @@ -101,12 +106,12 @@ #include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h" #include "device/fido/win/webauthn_api.h" -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) #include "base/metrics/field_trial_params.h" #include "base/strings/strcat.h" #include "chrome/grit/chrome_unscaled_resources.h" #include "ui/base/resource/resource_bundle.h" -#endif // defined(GOOGLE_CHROME_BUILD) +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) #endif // defined(OS_WIN) #if defined(USE_NSS_CERTS) @@ -116,10 +121,6 @@ namespace settings { namespace { -// Note that settings.html contains a <script> tag which imports a script of -// the following name. These names must be kept in sync. -constexpr char kLocalizedStringsFile[] = "strings.js"; - #if defined(OS_CHROMEOS) // Generates a Google Help URL which includes a "board type" parameter. Some // help pages need to be adjusted depending on the type of CrOS device that is @@ -195,13 +196,17 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { {"moreFeaturesLinkDescription", IDS_SETTINGS_MORE_FEATURES_LINK_DESCRIPTION}, {"captionsTitle", IDS_SETTINGS_CAPTIONS}, + {"captionsSettings", IDS_SETTINGS_CAPTIONS_SETTINGS}, + {"captionsPreview", IDS_SETTINGS_CAPTIONS_PREVIEW}, {"captionsTextSize", IDS_SETTINGS_CAPTIONS_TEXT_SIZE}, {"captionsTextFont", IDS_SETTINGS_CAPTIONS_TEXT_FONT}, {"captionsTextColor", IDS_SETTINGS_CAPTIONS_TEXT_COLOR}, {"captionsTextOpacity", IDS_SETTINGS_CAPTIONS_TEXT_OPACITY}, {"captionsBackgroundOpacity", IDS_SETTINGS_CAPTIONS_BACKGROUND_OPACITY}, - {"captionsOpacityMin", IDS_SETTINGS_CAPTIONS_OPACITY_MIN}, - {"captionsOpacityMax", IDS_SETTINGS_CAPTIONS_OPACITY_MAX}, + {"captionsOpacityOpaque", IDS_SETTINGS_CAPTIONS_OPACITY_OPAQUE}, + {"captionsOpacitySemiTransparent", + IDS_SETTINGS_CAPTIONS_OPACITY_SEMI_TRANSPARENT}, + {"captionsOpacityTransparent", IDS_SETTINGS_CAPTIONS_OPACITY_TRANSPARENT}, {"captionsTextShadow", IDS_SETTINGS_CAPTIONS_TEXT_SHADOW}, {"captionsTextShadowNone", IDS_SETTINGS_CAPTIONS_TEXT_SHADOW_NONE}, {"captionsTextShadowRaised", IDS_SETTINGS_CAPTIONS_TEXT_SHADOW_RAISED}, @@ -307,6 +312,8 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { {"switchAccessAutoScanLabel", IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_LABEL}, {"switchAccessAutoScanSpeedLabel", IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_SPEED_LABEL}, + {"switchAccessAutoScanKeyboardSpeedLabel", + IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_KEYBOARD_SPEED_LABEL}, {"durationInSeconds", IDS_SETTINGS_DURATION_IN_SECONDS}, {"manageAccessibilityFeatures", IDS_SETTINGS_ACCESSIBILITY_MANAGE_ACCESSIBILITY_FEATURES}, @@ -396,6 +403,11 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { html_source->AddBoolean( "showExperimentalAccessibilitySwitchAccess", cmd.HasSwitch(::switches::kEnableExperimentalAccessibilitySwitchAccess)); + + html_source->AddBoolean( + "showExperimentalAccessibilitySwitchAccessImprovedTextInput", + cmd.HasSwitch( + ::switches::kEnableExperimentalAccessibilitySwitchAccessText)); #endif } @@ -403,7 +415,7 @@ void AddAboutStrings(content::WebUIDataSource* html_source) { static constexpr LocalizedString kLocalizedStrings[] = { {"aboutProductLogoAlt", IDS_SHORT_PRODUCT_LOGO_ALT_TEXT}, -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) {"aboutReportAnIssue", IDS_SETTINGS_ABOUT_PAGE_REPORT_AN_ISSUE}, #endif @@ -431,6 +443,8 @@ void AddAboutStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_ABOUT_PAGE_RELAUNCH_AND_POWERWASH}, {"aboutRollbackInProgress", IDS_SETTINGS_UPGRADE_ROLLBACK_IN_PROGRESS}, {"aboutRollbackSuccess", IDS_SETTINGS_UPGRADE_ROLLBACK_SUCCESS}, + {"aboutUpdateOsSettingsLink", + IDS_SETTINGS_ABOUT_SEE_OS_SETTINGS_FOR_UPDATE_MESSAGE}, {"aboutUpgradeUpdatingChannelSwitch", IDS_SETTINGS_UPGRADE_UPDATING_CHANNEL_SWITCH}, {"aboutUpgradeSuccessChannelSwitch", @@ -567,9 +581,6 @@ void AddCrostiniStrings(content::WebUIDataSource* html_source, html_source->AddBoolean( "showCrostiniExportImport", crostini::IsCrostiniExportImportUIAllowedForProfile(profile)); - html_source->AddBoolean( - "enableCrostiniUsbDeviceSupport", - base::FeatureList::IsEnabled(chromeos::features::kCrostiniUsbSupport)); } void AddPluginVmStrings(content::WebUIDataSource* html_source, @@ -622,13 +633,45 @@ void AddAndroidAppStrings(content::WebUIDataSource* html_source) { void AddAppsStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"appsPageTitle", IDS_SETTINGS_APPS_TITLE}, - {"manageYourApps", IDS_SETTINGS_APPS_LINK_TEXT}, - {"manageYourAppsSublabel", IDS_SETTINGS_APPS_LINK_SUBLABEL_TEXT}, + {"appManagementTitle", IDS_SETTINGS_APPS_LINK_TEXT}, }; AddLocalizedStringsBulk(html_source, localized_strings, base::size(localized_strings)); } + +void AddAppManagementStrings(content::WebUIDataSource* html_source) { + static constexpr LocalizedString localized_strings[] = { + {"appListTitle", IDS_APP_MANAGEMENT_APP_LIST_TITLE}, + {"appNoPermission", IDS_APPLICATION_INFO_APP_NO_PERMISSIONS_TEXT}, + {"camera", IDS_APP_MANAGEMENT_CAMERA}, + {"contacts", IDS_APP_MANAGEMENT_CONTACTS}, + {"controlledByPolicy", IDS_CONTROLLED_SETTING_POLICY}, + {"lessApps", IDS_APP_MANAGEMENT_LESS_APPS}, + {"location", IDS_APP_MANAGEMENT_LOCATION}, + {"microphone", IDS_APP_MANAGEMENT_MICROPHONE}, + {"moreApps", IDS_APP_MANAGEMENT_MORE_APPS}, + {"moreSettings", IDS_APP_MANAGEMENT_MORE_SETTINGS}, + {"notifications", IDS_APP_MANAGEMENT_NOTIFICATIONS}, + {"notificationSublabel", IDS_APP_MANAGEMENT_NOTIFICATIONS_SUBLABEL}, + {"openAndroidSettings", IDS_APP_MANAGEMENT_ANDROID_SETTINGS}, + {"openExtensionsSettings", IDS_APP_MANAGEMENT_EXTENSIONS_SETTINGS}, + {"openSiteSettings", IDS_APP_MANAGEMENT_SITE_SETTING}, + {"permissions", IDS_APP_MANAGEMENT_PERMISSIONS}, + {"pinControlledByPolicy", IDS_APP_MANAGEMENT_PIN_ENFORCED_BY_POLICY}, + {"pinToShelf", IDS_APP_MANAGEMENT_PIN_TO_SHELF}, + {"policyAppUninstallPolicy", IDS_APP_MANAGEMENT_POLICY_APP_POLICY_STRING}, + {"size", IDS_APP_MANAGEMENT_SIZE}, + {"storage", IDS_APP_MANAGEMENT_STORAGE}, + {"systemAppUninstallPolicy", IDS_APP_MANAGEMENT_SYSTEM_APP_POLICY_STRING}, + {"thisAppCan", IDS_APP_MANAGEMENT_THIS_APP_CAN}, + {"title", IDS_APP_MANAGEMENT_TITLE}, + {"uninstallApp", IDS_APP_MANAGEMENT_UNINSTALL_APP}, + {"version", IDS_APP_MANAGEMENT_VERSION}, + }; + AddLocalizedStringsBulk(html_source, localized_strings, + base::size(localized_strings)); +} #endif #if defined(OS_CHROMEOS) @@ -678,7 +721,6 @@ void AddAppearanceStrings(content::WebUIDataSource* html_source, {"personalizationPageTitle", IDS_OS_SETTINGS_PERSONALIZATION}, {"openWallpaperApp", IDS_OS_SETTINGS_OPEN_WALLPAPER_APP}, {"setWallpaper", IDS_OS_SETTINGS_SET_WALLPAPER}, - {"osLanguagesPageTitle", IDS_OS_SETTINGS_LANGUAGES_AND_INPUT_PAGE_TITLE}, #endif #if defined(OS_LINUX) && !defined(OS_CHROMEOS) {"showWindowDecorations", IDS_SHOW_WINDOW_DECORATIONS}, @@ -842,6 +884,7 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { {"mouseSpeed", IDS_SETTINGS_MOUSE_SPEED_LABEL}, {"mouseSwapButtons", IDS_SETTINGS_MOUSE_SWAP_BUTTONS_LABEL}, {"mouseReverseScroll", IDS_SETTINGS_MOUSE_REVERSE_SCROLL_LABEL}, + {"pointerAccelerationLabel", IDS_SETTINGS_POINTER_ACCELERATION_LABEL}, }; AddLocalizedStringsBulk(html_source, kPointersStrings, base::size(kPointersStrings)); @@ -988,6 +1031,10 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { html_source->AddBoolean("hasExternalTouchDevice", display::HasExternalTouchscreenDevice()); + html_source->AddBoolean( + "allowDisableMouseAcceleration", + base::FeatureList::IsEnabled(features::kAllowDisableMouseAcceleration)); + static constexpr LocalizedString kStorageStrings[] = { {"storageTitle", IDS_SETTINGS_STORAGE_TITLE}, {"storageItemInUse", IDS_SETTINGS_STORAGE_ITEM_IN_USE}, @@ -1019,10 +1066,10 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { {"storageDeleteAllButtonTitle", IDS_SETTINGS_STORAGE_DELETE_ALL_BUTTON_TITLE}, {"storageExternal", IDS_SETTINGS_STORAGE_EXTERNAL}, - {"storageAndroidAppsExternalDrives", - IDS_SETTINGS_STORAGE_ANDROID_APPS_ACCESS_EXTERNAL_DRIVES}, {"storageAndroidAppsExternalDrivesNote", - IDS_SETTINGS_STORAGE_ANDROID_APPS_ACCESS_EXTERNAL_DRIVES_NOTE}}; + IDS_SETTINGS_STORAGE_ANDROID_APPS_ACCESS_EXTERNAL_DRIVES_NOTE}, + {"storageExternalStorageListHeader", + IDS_SETTINGS_STORAGE_EXTERNAL_STORAGE_LIST_HEADER}}; AddLocalizedStringsBulk(html_source, kStorageStrings, base::size(kStorageStrings)); @@ -1098,7 +1145,7 @@ void AddDownloadsStrings(content::WebUIDataSource* html_source) { base::size(kLocalizedStrings)); } -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) void AddChromeCleanupStrings(content::WebUIDataSource* html_source) { const wchar_t kUnwantedSoftwareProtectionWhitePaperUrl[] = L"https://www.google.ca/chrome/browser/privacy/" @@ -1227,11 +1274,11 @@ void AddIncompatibleApplicationsStrings(content::WebUIDataSource* html_source) { html_source->AddString("incompatibleApplicationsSubpageLearnHow", learn_how_text); } -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#endif // defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) void AddResetStrings(content::WebUIDataSource* html_source) { static constexpr LocalizedString kLocalizedStrings[] = { -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) {"resetPageTitle", IDS_SETTINGS_RESET_AND_CLEANUP}, #else {"resetPageTitle", IDS_SETTINGS_RESET}, @@ -1254,7 +1301,7 @@ void AddResetStrings(content::WebUIDataSource* html_source) { {"resetAutomatedDialogTitle", IDS_SETTINGS_RESET_AUTOMATED_DIALOG_TITLE}, {"resetProfileBannerButton", IDS_SETTINGS_RESET_BANNER_RESET_BUTTON_TEXT}, {"resetProfileBannerDescription", IDS_SETTINGS_RESET_BANNER_TEXT}, -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) {"resetCleanupComputerTrigger", IDS_SETTINGS_RESET_CLEAN_UP_COMPUTER_TRIGGER}, #endif @@ -1381,8 +1428,6 @@ void AddInternetStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_INTERNET_ADD_CONNECTION_NOT_ALLOWED}, {"internetAddThirdPartyVPN", IDS_SETTINGS_INTERNET_ADD_THIRD_PARTY_VPN}, {"internetAddVPN", IDS_SETTINGS_INTERNET_ADD_VPN}, - {"internetAddArcVPN", IDS_SETTINGS_INTERNET_ADD_ARC_VPN}, - {"internetAddArcVPNProvider", IDS_SETTINGS_INTERNET_ADD_ARC_VPN_PROVIDER}, {"internetAddWiFi", IDS_SETTINGS_INTERNET_ADD_WIFI}, {"internetConfigName", IDS_SETTINGS_INTERNET_CONFIG_NAME}, {"internetDetailPageTitle", IDS_SETTINGS_INTERNET_DETAIL}, @@ -1400,8 +1445,6 @@ void AddInternetStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_INTERNET_TOGGLE_TETHER_SUBTEXT}, {"internetToggleWiFiA11yLabel", IDS_SETTINGS_INTERNET_TOGGLE_WIFI_ACCESSIBILITY_LABEL}, - {"internetToggleWiMAXA11yLabel", - IDS_SETTINGS_INTERNET_TOGGLE_WIMAX_ACCESSIBILITY_LABEL}, {"knownNetworksAll", IDS_SETTINGS_INTERNET_KNOWN_NETWORKS_ALL}, {"knownNetworksButton", IDS_SETTINGS_INTERNET_KNOWN_NETWORKS_BUTTON}, {"knownNetworksMessage", IDS_SETTINGS_INTERNET_KNOWN_NETWORKS_MESSAGE}, @@ -1452,6 +1495,10 @@ void AddInternetStrings(content::WebUIDataSource* html_source) { {"networkShared", IDS_SETTINGS_INTERNET_NETWORK_SHARED}, {"networkVpnBuiltin", IDS_NETWORK_TYPE_VPN_BUILTIN}, {"networkOutOfRange", IDS_SETTINGS_INTERNET_WIFI_NETWORK_OUT_OF_RANGE}, + {"cellularContactSpecificCarrier", + IDS_SETTINGS_INTERNET_CELLULAR_CONTACT_SPECIFIC_CARRIER}, + {"cellularContactDefaultCarrier", + IDS_SETTINGS_INTERNET_CELLULAR_CONTACT_DEFAULT_CARRIER}, {"tetherPhoneOutOfRange", IDS_SETTINGS_INTERNET_TETHER_PHONE_OUT_OF_RANGE}, {"gmscoreNotificationsTitle", @@ -1521,6 +1568,8 @@ void AddLanguagesStrings(content::WebUIDataSource* html_source) { {"removeLanguage", IDS_SETTINGS_LANGUAGES_LANGUAGES_LIST_REMOVE}, {"addLanguages", IDS_SETTINGS_LANGUAGES_LANGUAGES_ADD}, #if defined(OS_CHROMEOS) + {"osLanguagesPageTitle", IDS_OS_SETTINGS_LANGUAGES_AND_INPUT_PAGE_TITLE}, + {"osLanguagesListTitle", IDS_OS_SETTINGS_LANGUAGES_LIST_TITLE}, {"inputMethodsListTitle", IDS_SETTINGS_LANGUAGES_INPUT_METHODS_LIST_TITLE}, {"inputMethodEnabled", IDS_SETTINGS_LANGUAGES_INPUT_METHOD_ENABLED}, {"inputMethodsExpandA11yLabel", @@ -1612,6 +1661,15 @@ void AddChromeOSUserStrings(content::WebUIDataSource* html_source, "secondaryUserBannerText", l10n_util::GetStringFUTF16(IDS_SETTINGS_SECONDARY_USER_BANNER, base::ASCIIToUTF16(primary_user_email))); + html_source->AddString("browserSettingsBannerText", + l10n_util::GetStringFUTF16( + IDS_SETTINGS_BROWSER_SETTINGS_BANNER, + base::ASCIIToUTF16(chrome::kChromeUISettingsURL))); + html_source->AddString( + "osSettingsBannerText", + l10n_util::GetStringFUTF16( + IDS_SETTINGS_OS_SETTINGS_BANNER, + base::ASCIIToUTF16(chrome::kChromeUIOSSettingsURL))); html_source->AddBoolean("isActiveDirectoryUser", user && user->IsActiveDirectoryUser()); @@ -1688,6 +1746,14 @@ void AddAutofillStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL}, {"passwordsAutosigninDescription", IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC}, + {"passwordsLeakDetectionLabel", + IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_LABEL}, + {"passwordsLeakDetectionSignedInDescription", + IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_SIGNED_IN_DESC}, + {"passwordsLeakDetectionSignedOutDisabledDescription", + IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_SIGNED_OUT_DISABLED_DESC}, + {"passwordsLeakDetectionSignedOutEnabledDescription", + IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_SIGNED_OUT_ENABLED_DESC}, {"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING}, {"passwordExceptionsHeading", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_HEADING}, {"deletePasswordException", IDS_SETTINGS_PASSWORDS_DELETE_EXCEPTION}, @@ -1766,6 +1832,16 @@ void AddAutofillStrings(content::WebUIDataSource* html_source, /*is_test_mode=*/false, /*log_manager=*/nullptr)); + html_source->AddBoolean( + "passwordsLeakDetectionEnabled", + base::FeatureList::IsEnabled(password_manager::features::kLeakDetection)); + + ui::Accelerator undoAccelerator(ui::VKEY_Z, ui::EF_PLATFORM_ACCELERATOR); + html_source->AddString( + "undoDescription", + l10n_util::GetStringFUTF16(IDS_UNDO_DESCRIPTION, + undoAccelerator.GetShortcutText())); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, base::size(kLocalizedStrings)); } @@ -1835,6 +1911,8 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_SETTINGS_KERBEROS_ACCOUNTS_REMOVE_ACCOUNT_LABEL}, {"kerberosAccountsAccountRemovedTip", IDS_SETTINGS_KERBEROS_ACCOUNTS_ACCOUNT_REMOVED_TIP}, + {"kerberosAccountsAccountRefreshedTip", + IDS_SETTINGS_KERBEROS_ACCOUNTS_ACCOUNT_REFRESHED_TIP}, {"kerberosAccountsSignedIn", IDS_SETTINGS_KERBEROS_ACCOUNTS_SIGNED_IN}, {"kerberosAccountsSignedOut", IDS_SETTINGS_KERBEROS_ACCOUNTS_SIGNED_OUT}, {"kerberosAccountsReauthenticationLabel", @@ -1909,7 +1987,6 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_SETTINGS_PEOPLE_LOCK_SCREEN_FINGERPRINT_LESS_SECURE}, {"lockScreenDeleteFingerprintLabel", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_DELETE_FINGERPRINT_ARIA_LABEL}, - {"lockScreenMediaKeys", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_MEDIA_KEYS}, {"lockScreenNotificationHide", IDS_ASH_SETTINGS_LOCK_SCREEN_NOTIFICATION_HIDE}, {"lockScreenNotificationHideSensitive", @@ -1960,6 +2037,8 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"photoDiscardAccessibleText", IDS_SETTINGS_PHOTO_DISCARD_ACCESSIBLE_TEXT}, {"photoModeAccessibleText", IDS_SETTINGS_PHOTO_MODE_ACCESSIBLE_TEXT}, {"videoModeAccessibleText", IDS_SETTINGS_VIDEO_MODE_ACCESSIBLE_TEXT}, + {"wifiConfigurationsCheckboxLabel", + IDS_SETTINGS_WIFI_CONFIGURATIONS_CHECKBOX_LABEL}, #else // !defined(OS_CHROMEOS) {"domainManagedProfile", IDS_SETTINGS_PEOPLE_DOMAIN_MANAGED_PROFILE}, {"editPerson", IDS_SETTINGS_EDIT_PERSON}, @@ -2223,7 +2302,8 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) { {"addCupsPrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_ADD_PRINTER}, {"editPrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_EDIT}, {"removePrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_REMOVE}, - {"configurePrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTER_CONFIGURE_BUTTON}, + {"setupPrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTER_SETUP_BUTTON}, + {"savePrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTER_SAVE_BUTTON}, {"searchLabel", IDS_SETTINGS_PRINTING_CUPS_SEARCH_LABEL}, {"noSearchResults", IDS_SEARCH_NO_RESULTS}, {"printerDetailsTitle", IDS_SETTINGS_PRINTING_CUPS_PRINTER_DETAILS_TITLE}, @@ -2276,6 +2356,8 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_PRINTING_CUPS_PRINTER_ADDED_PRINTER_DONE_MESSAGE}, {"printerEditedSuccessfulMessage", IDS_SETTINGS_PRINTING_CUPS_PRINTER_EDITED_PRINTER_DONE_MESSAGE}, + {"printerUnavailableMessage", + IDS_SETTINGS_PRINTING_CUPS_PRINTER_UNAVAILABLE_MESSAGE}, {"noPrinterNearbyMessage", IDS_SETTINGS_PRINTING_CUPS_PRINTER_NO_PRINTER_NEARBY}, {"searchingNearbyPrinters", @@ -2300,6 +2382,12 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_PRINTING_CUPS_EDIT_PRINTER_INVALID_PRINTER_UPDATE}, {"requireNetworkMessage", IDS_SETTINGS_PRINTING_CUPS_PRINTER_REQUIRE_INTERNET_MESSAGE}, + {"checkNetworkMessage", + IDS_SETTINGS_PRINTING_CUPS_PRINTER_CHECK_CONNECTION_MESSAGE}, + {"noInternetConnection", + IDS_SETTINGS_PRINTING_CUPS_PRINTER_NO_INTERNET_CONNECTION}, + {"checkNetworkAndTryAgain", + IDS_SETTINGS_PRINTING_CUPS_PRINTER_CONNECT_TO_NETWORK_SUBTEXT}, {"editPrinterDialogTitle", IDS_SETTINGS_PRINTING_CUPS_EDIT_PRINTER_DIALOG_TITLE}, {"editPrinterButtonText", IDS_SETTINGS_PRINTING_CUPS_EDIT_PRINTER_BUTTON}, @@ -2594,7 +2682,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, {"appCacheOrigin", IDS_SETTINGS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL}, {"cookieAppCache", IDS_SETTINGS_COOKIES_APPLICATION_CACHE}, {"cookieCacheStorage", IDS_SETTINGS_COOKIES_CACHE_STORAGE}, - {"cookieChannelId", IDS_SETTINGS_COOKIES_CHANNEL_ID}, {"cookieDatabaseStorage", IDS_SETTINGS_COOKIES_DATABASE_STORAGE}, {"cookieFileSystem", IDS_SETTINGS_COOKIES_FILE_SYSTEM}, {"cookieFlashLso", IDS_SETTINGS_COOKIES_FLASH_LSO}, @@ -2610,10 +2697,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_COOKIES_LOCAL_STORAGE_LAST_MODIFIED_LABEL}, {"cacheStorageOrigin", IDS_SETTINGS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL}, {"cacheStorageSize", IDS_SETTINGS_COOKIES_LOCAL_STORAGE_SIZE_ON_DISK_LABEL}, - {"channelIdServerId", IDS_SETTINGS_COOKIES_CHANNEL_ID_ORIGIN_LABEL}, - {"channelIdType", IDS_SETTINGS_COOKIES_CHANNEL_ID_TYPE_LABEL}, - {"channelIdCreated", IDS_SETTINGS_COOKIES_CHANNEL_ID_CREATED_LABEL}, - {"channelIdExpires", IDS_SETTINGS_COOKIES_CHANNEL_ID_EXPIRES_LABEL}, {"cookieAccessibleToScript", IDS_SETTINGS_COOKIES_COOKIE_ACCESSIBLE_TO_SCRIPT_LABEL}, {"cookieContent", IDS_SETTINGS_COOKIES_COOKIE_CONTENT_LABEL}, @@ -2739,6 +2822,14 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_SITE_SETTINGS_USB_DEVICES_ASK_RECOMMENDED}, {"siteSettingsUsbDevicesBlock", IDS_SETTINGS_SITE_SETTINGS_USB_DEVICES_BLOCK}, + {"siteSettingsNativeFileSystemWrite", + IDS_SETTINGS_SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE}, + {"siteSettingsNativeFileSystemWriteAsk", + IDS_SETTINGS_SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE_ASK}, + {"siteSettingsNativeFileSystemWriteAskRecommended", + IDS_SETTINGS_SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE_ASK_RECOMMENDED}, + {"siteSettingsNativeFileSystemWriteBlock", + IDS_SETTINGS_SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE_BLOCK}, {"siteSettingsRemoveZoomLevel", IDS_SETTINGS_SITE_SETTINGS_REMOVE_ZOOM_LEVEL}, {"siteSettingsZoomLevels", IDS_SETTINGS_SITE_SETTINGS_ZOOM_LEVELS}, @@ -2848,6 +2939,14 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_SITE_SETTINGS_COOKIE_REMOVE_ALL}, {"siteSettingsCookieRemoveAllShown", IDS_SETTINGS_SITE_SETTINGS_COOKIE_REMOVE_ALL_SHOWN}, + {"siteSettingsCookieRemoveAllThirdParty", + IDS_SETTINGS_SITE_SETTINGS_COOKIE_REMOVE_ALL_THIRD_PARTY}, + {"siteSettingsCookieRemoveThirdPartyDialogTitle", + IDS_SETTINGS_SITE_SETTINGS_THIRD_PARTY_COOKIE_REMOVE_DIALOG_TITLE}, + {"siteSettingsCookieRemoveThirdPartyConfirmation", + IDS_SETTINGS_SITE_SETTINGS_THIRD_PARTY_COOKIE_REMOVE_CONFIRMATION}, + {"siteSettingsCookiesClearThirdParty", + IDS_SETTINGS_SITE_SETTINGS_CLEAR_THIRD_PARTY_COOKIES}, {"siteSettingsCookieRemoveDialogTitle", IDS_SETTINGS_SITE_SETTINGS_COOKIE_REMOVE_DIALOG_TITLE}, {"siteSettingsCookieRemoveMultipleConfirmation", @@ -2951,10 +3050,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, base::FeatureList::IsEnabled(media::kAutoplayWhitelistSettings)); html_source->AddBoolean( - "enableSensorsContentSetting", - base::FeatureList::IsEnabled(features::kSensorContentSetting)); - - html_source->AddBoolean( "enablePaymentHandlerContentSetting", base::FeatureList::IsEnabled(features::kServiceWorkerPaymentApps)); @@ -2966,6 +3061,15 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, html_source->AddBoolean( "enableBluetoothScanningContentSetting", cmd.HasSwitch(::switches::kEnableWebBluetoothScanning)); + + html_source->AddBoolean( + "enableNativeFileSystemWriteContentSetting", + base::FeatureList::IsEnabled(::blink::features::kNativeFileSystemAPI)); + + html_source->AddBoolean( + "enableRemovingAllThirdPartyCookies", + base::FeatureList::IsEnabled( + browsing_data::features::kEnableRemovingAllThirdPartyCookies)); } #if defined(OS_CHROMEOS) @@ -3128,6 +3232,20 @@ void AddExtensionsStrings(content::WebUIDataSource* html_source) { void AddSecurityKeysStrings(content::WebUIDataSource* html_source) { static constexpr LocalizedString kSecurityKeysStrings[] = { + {"securityKeysBioEnrollmentDialogTitle", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_DIALOG_TITLE}, + {"securityKeysBioEnrollmentEnrollingLabel", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_ENROLLING_LABEL}, + {"securityKeysBioEnrollmentLabel", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_LABEL}, + {"securityKeysBioEnrollmentNoEnrollments", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_NO_ENROLLMENTS}, + {"securityKeysBioEnrollmentPinPrompt", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_PIN_PROMPT}, + {"securityKeysBioEnrollmentSubpageDescription", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_SUBPAGE_DESCRIPTION}, + {"securityKeysBioEnrollmentTouch", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_TOUCH}, {"securityKeysPINTooShort", IDS_SETTINGS_SECURITY_KEYS_PIN_ERROR_TOO_SHORT}, {"securityKeysConfirmPIN", IDS_SETTINGS_SECURITY_KEYS_CONFIRM_PIN}, @@ -3201,24 +3319,22 @@ void AddSecurityKeysStrings(content::WebUIDataSource* html_source) { }; AddLocalizedStringsBulk(html_source, kSecurityKeysStrings, base::size(kSecurityKeysStrings)); - - html_source->AddBoolean( - "enableSecurityKeysSubpage", - base::FeatureList::IsEnabled(device::kWebAuthPINSupport) + bool win_native_api_available = false; #if defined(OS_WIN) - && (!base::FeatureList::IsEnabled(device::kWebAuthUseNativeWinApi) || - !device::WinWebAuthnApi::GetDefault()->IsAvailable()) + win_native_api_available = + base::FeatureList::IsEnabled(device::kWebAuthUseNativeWinApi) && + device::WinWebAuthnApi::GetDefault()->IsAvailable(); #endif - ); + html_source->AddBoolean("enableSecurityKeysSubpage", + !win_native_api_available); html_source->AddBoolean( "enableSecurityKeysCredentialManagement", - base::FeatureList::IsEnabled(device::kWebAuthPINSupport) && - base::FeatureList::IsEnabled(device::kWebAuthCredentialManagement) -#if defined(OS_WIN) - && (!base::FeatureList::IsEnabled(device::kWebAuthUseNativeWinApi) || - !device::WinWebAuthnApi::GetDefault()->IsAvailable()) -#endif - ); + base::FeatureList::IsEnabled(device::kWebAuthCredentialManagement) && + !win_native_api_available); + html_source->AddBoolean( + "enableSecurityKeysBioEnrollment", + base::FeatureList::IsEnabled(device::kWebAuthBiometricEnrollment) && + !win_native_api_available); } } // namespace @@ -3230,10 +3346,10 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, AddAutofillStrings(html_source, profile); AddAppearanceStrings(html_source, profile); -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) AddChromeCleanupStrings(html_source); AddIncompatibleApplicationsStrings(html_source); -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#endif // defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) AddChangePasswordStrings(html_source); AddClearBrowsingDataStrings(html_source, profile); @@ -3255,12 +3371,12 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, AddWebContentStrings(html_source); #if defined(OS_CHROMEOS) - AddCrostiniStrings(html_source, profile); - AddPluginVmStrings(html_source, profile); AddAndroidAppStrings(html_source); + AddAppManagementStrings(html_source); AddAppsStrings(html_source); AddBluetoothStrings(html_source); AddChromeOSUserStrings(html_source, profile); + AddCrostiniStrings(html_source, profile); AddDateTimeStrings(html_source); AddDeviceStrings(html_source); AddEasyUnlockStrings(html_source); @@ -3268,6 +3384,7 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, AddInternetStrings(html_source); AddMultideviceStrings(html_source); AddParentalControlStrings(html_source); + AddPluginVmStrings(html_source, profile); AddUsersStrings(html_source); #else AddDefaultBrowserStrings(html_source); @@ -3290,7 +3407,7 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, policy_indicator::AddLocalizedStrings(html_source); AddSecurityKeysStrings(html_source); - html_source->SetJsonPath(kLocalizedStringsFile); + html_source->UseStringsJs(); } } // namespace settings 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 d7ee5c19f6d..3cc1952359a 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 @@ -11,7 +11,7 @@ #include "chrome/test/base/testing_profile_manager.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui_data_source.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -40,7 +40,7 @@ class ManageProfileHandlerTest : public testing::Test { ASSERT_TRUE(profile_manager_.SetUp()); profile_ = profile_manager_.CreateTestingProfile("Profile 1"); - handler_.reset(new TestManageProfileHandler(profile_)); + handler_ = std::make_unique<TestManageProfileHandler>(profile_); handler_->set_web_ui(&web_ui_); handler()->AllowJavascript(); web_ui()->ClearTrackedCalls(); @@ -60,7 +60,7 @@ class ManageProfileHandlerTest : public testing::Test { TestManageProfileHandler* handler() const { return handler_.get(); } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_; content::TestWebUI web_ui_; diff --git a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc index 0215a9b4c38..8f725e8ca0d 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc @@ -11,11 +11,14 @@ #include "base/optional.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "chrome/browser/ui/webui/settings/settings_security_key_handler.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/system_connector.h" #include "content/public/browser/web_ui.h" #include "content/public/common/service_manager_connection.h" +#include "device/fido/bio/enrollment_handler.h" #include "device/fido/credential_management.h" #include "device/fido/credential_management_handler.h" #include "device/fido/fido_discovery_factory.h" @@ -408,7 +411,8 @@ void SecurityKeysCredentialHandler::OnHaveCredentials( DCHECK(!callback_id_.empty()); if (status != device::CtapDeviceResponseCode::kSuccess) { - OnFinished(device::FidoReturnCode::kAuthenticatorResponseInvalid); + OnFinished( + device::CredentialManagementStatus::kAuthenticatorResponseInvalid); return; } DCHECK(responses); @@ -481,38 +485,294 @@ void SecurityKeysCredentialHandler::OnCredentialsDeleted( : IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_FAILED))); } -void SecurityKeysCredentialHandler::OnFinished(device::FidoReturnCode status) { +void SecurityKeysCredentialHandler::OnFinished( + device::CredentialManagementStatus status) { DCHECK_CURRENTLY_ON(BrowserThread::UI); int error; switch (status) { - case device::FidoReturnCode::kSoftPINBlock: + case device::CredentialManagementStatus::kSoftPINBlock: error = IDS_SETTINGS_SECURITY_KEYS_PIN_SOFT_LOCK; break; - case device::FidoReturnCode::kHardPINBlock: + case device::CredentialManagementStatus::kHardPINBlock: error = IDS_SETTINGS_SECURITY_KEYS_PIN_HARD_LOCK; break; - case device::FidoReturnCode::kAuthenticatorMissingCredentialManagement: + case device::CredentialManagementStatus:: + kAuthenticatorMissingCredentialManagement: error = IDS_SETTINGS_SECURITY_KEYS_NO_CREDENTIAL_MANAGEMENT; break; - case device::FidoReturnCode::kAuthenticatorMissingUserVerification: + case device::CredentialManagementStatus::kNoPINSet: error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_NO_PIN; break; - case device::FidoReturnCode::kAuthenticatorResponseInvalid: + case device::CredentialManagementStatus::kAuthenticatorResponseInvalid: error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_ERROR; break; - case device::FidoReturnCode::kSuccess: + case device::CredentialManagementStatus::kSuccess: error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_REMOVED; break; - default: - NOTREACHED(); - error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_ERROR; - break; } FireWebUIListener("security-keys-credential-management-finished", base::Value(l10n_util::GetStringUTF8(std::move(error)))); } +SecurityKeysBioEnrollmentHandler::SecurityKeysBioEnrollmentHandler() = default; +SecurityKeysBioEnrollmentHandler::~SecurityKeysBioEnrollmentHandler() = default; + +void SecurityKeysBioEnrollmentHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollStart", + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::HandleStart, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollProvidePIN", + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::HandleProvidePIN, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollEnumerate", + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::HandleEnumerate, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollStartEnrolling", + base::BindRepeating( + &SecurityKeysBioEnrollmentHandler::HandleStartEnrolling, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollDelete", + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::HandleDelete, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollCancel", + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::HandleCancel, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollClose", + base::BindRepeating( + &HandleClose, + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::Close, + base::Unretained(this)))); +} + +void SecurityKeysBioEnrollmentHandler::Close() { + weak_factory_.InvalidateWeakPtrs(); + state_ = State::kNone; + discovery_factory_.reset(); + bio_.reset(); + callback_id_.clear(); + discovery_factory_.reset(); + provide_pin_cb_.Reset(); +} + +void SecurityKeysBioEnrollmentHandler::HandleStart( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(state_, State::kNone); + DCHECK_EQ(1u, args->GetSize()); + DCHECK(callback_id_.empty()); + + AllowJavascript(); + state_ = State::kStart; + callback_id_ = args->GetList()[0].GetString(); + discovery_factory_ = std::make_unique<device::FidoDiscoveryFactory>(); + bio_ = std::make_unique<device::BioEnrollmentHandler>( + content::ServiceManagerConnection::GetForProcess()->GetConnector(), + supported_transports(), + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnReady, + weak_factory_.GetWeakPtr()), + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnError, + weak_factory_.GetWeakPtr()), + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::OnGatherPIN, + weak_factory_.GetWeakPtr()), + discovery_factory_.get()); +} + +void SecurityKeysBioEnrollmentHandler::OnReady() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(bio_); + DCHECK_EQ(state_, State::kGatherPIN); + DCHECK(!callback_id_.empty()); + state_ = State::kReady; + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value()); +} + +void SecurityKeysBioEnrollmentHandler::OnError( + device::BioEnrollmentStatus status) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + state_ = State::kNone; + + int error; + switch (status) { + case device::BioEnrollmentStatus::kSoftPINBlock: + error = IDS_SETTINGS_SECURITY_KEYS_PIN_SOFT_LOCK; + break; + case device::BioEnrollmentStatus::kHardPINBlock: + error = IDS_SETTINGS_SECURITY_KEYS_PIN_HARD_LOCK; + break; + case device::BioEnrollmentStatus::kAuthenticatorMissingBioEnrollment: + error = IDS_SETTINGS_SECURITY_KEYS_NO_BIOMETRIC_ENROLLMENT; + break; + case device::BioEnrollmentStatus::kNoPINSet: + error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_NO_PIN; + break; + case device::BioEnrollmentStatus::kAuthenticatorResponseInvalid: + error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_ERROR; + break; + case device::BioEnrollmentStatus::kSuccess: + error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_REMOVED; + break; + } + + FireWebUIListener("security-keys-bio-enroll-error", + base::Value(l10n_util::GetStringUTF8(error))); + + // If |callback_id_| is not empty, there is an ongoing operation, + // which means there is an unresolved Promise. Reject it so that + // it isn't leaked. + if (!callback_id_.empty()) { + RejectJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value()); + } +} + +void SecurityKeysBioEnrollmentHandler::OnGatherPIN( + int64_t retries, + base::OnceCallback<void(std::string)> cb) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(!callback_id_.empty()); + DCHECK(state_ == State::kStart || state_ == State::kGatherPIN); + state_ = State::kGatherPIN; + provide_pin_cb_ = std::move(cb); + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value(static_cast<int>(retries))); +} + +void SecurityKeysBioEnrollmentHandler::HandleProvidePIN( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(2u, args->GetSize()); + DCHECK_EQ(state_, State::kGatherPIN); + state_ = State::kGatherPIN; + callback_id_ = args->GetList()[0].GetString(); + std::move(provide_pin_cb_).Run(args->GetList()[1].GetString()); +} + +void SecurityKeysBioEnrollmentHandler::HandleEnumerate( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(1u, args->GetSize()); + DCHECK_EQ(state_, State::kReady); + state_ = State::kEnumerating; + callback_id_ = args->GetList()[0].GetString(); + bio_->EnumerateTemplates( + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnHaveEnumeration, + weak_factory_.GetWeakPtr())); +} + +void SecurityKeysBioEnrollmentHandler::OnHaveEnumeration( + device::CtapDeviceResponseCode code, + base::Optional<std::map<std::vector<uint8_t>, std::string>> enrollments) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(!callback_id_.empty()); + DCHECK_EQ(state_, State::kEnumerating); + + base::Value::ListStorage list; + if (enrollments) { + for (const auto& enrollment : *enrollments) { + base::DictionaryValue elem; + elem.SetStringKey("name", std::move(enrollment.second)); + elem.SetStringKey("id", base::HexEncode(enrollment.first.data(), + enrollment.first.size())); + list.emplace_back(std::move(elem)); + } + } + + state_ = State::kReady; + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::ListValue(std::move(list))); +} + +void SecurityKeysBioEnrollmentHandler::HandleStartEnrolling( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(1u, args->GetSize()); + DCHECK_EQ(state_, State::kReady); + state_ = State::kEnrolling; + callback_id_ = args->GetList()[0].GetString(); + bio_->EnrollTemplate( + base::BindRepeating( + &SecurityKeysBioEnrollmentHandler::OnEnrollingResponse, + weak_factory_.GetWeakPtr()), + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnEnrollmentFinished, + weak_factory_.GetWeakPtr())); +} + +void SecurityKeysBioEnrollmentHandler::OnEnrollingResponse( + device::BioEnrollmentSampleStatus status, + uint8_t remaining_samples) { + DCHECK_EQ(state_, State::kEnrolling); + base::DictionaryValue d; + d.SetIntKey("status", static_cast<int>(status)); + d.SetIntKey("remaining", static_cast<int>(remaining_samples)); + FireWebUIListener("security-keys-bio-enroll-status", std::move(d)); +} + +void SecurityKeysBioEnrollmentHandler::OnEnrollmentFinished( + device::CtapDeviceResponseCode code) { + DCHECK_EQ(state_, State::kEnrolling); + DCHECK(!callback_id_.empty()); + state_ = State::kReady; + base::DictionaryValue d; + d.SetIntKey("code", static_cast<int>(code)); + d.SetIntKey("remaining", 0); + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), std::move(d)); +} + +void SecurityKeysBioEnrollmentHandler::HandleDelete( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(2u, args->GetSize()); + state_ = State::kDeleting; + callback_id_ = args->GetList()[0].GetString(); + std::vector<uint8_t> template_id; + if (!base::HexStringToBytes(args->GetList()[1].GetString(), &template_id)) { + NOTREACHED(); + return; + } + bio_->DeleteTemplate( + std::move(template_id), + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnDelete, + weak_factory_.GetWeakPtr())); +} + +void SecurityKeysBioEnrollmentHandler::OnDelete( + device::CtapDeviceResponseCode c) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(state_, State::kDeleting); + DCHECK(!callback_id_.empty()); + state_ = State::kEnumerating; + bio_->EnumerateTemplates( + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnHaveEnumeration, + weak_factory_.GetWeakPtr())); +} + +void SecurityKeysBioEnrollmentHandler::HandleCancel( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(1u, args->GetSize()); + state_ = State::kCancelling; + callback_id_ = args->GetList()[0].GetString(); + bio_->Cancel(base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnEnrollCancel, + weak_factory_.GetWeakPtr())); +} + +void SecurityKeysBioEnrollmentHandler::OnEnrollCancel( + device::CtapDeviceResponseCode) { + DCHECK_EQ(state_, State::kCancelling); + state_ = State::kReady; + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value()); +} + } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h index 2b9e1b17317..60196df0fba 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h @@ -14,6 +14,8 @@ #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "device/fido/fido_constants.h" +#include "device/fido/bio/enrollment.h" + namespace base { class ListValue; } @@ -22,8 +24,11 @@ namespace device { struct AggregatedEnumerateCredentialsResponse; class FidoDiscoveryFactory; class CredentialManagementHandler; +enum class CredentialManagementStatus; class SetPINRequestHandler; class ResetRequestHandler; +class BioEnrollmentHandler; +enum class BioEnrollmentStatus; } // namespace device namespace settings { @@ -149,7 +154,7 @@ class SecurityKeysCredentialHandler : public SecurityKeysHandlerBase { base::Optional<size_t> remaining_credentials); void OnGatherPIN(int64_t num_retries, base::OnceCallback<void(std::string)>); void OnCredentialsDeleted(device::CtapDeviceResponseCode status); - void OnFinished(device::FidoReturnCode status); + void OnFinished(device::CredentialManagementStatus status); State state_ = State::kNone; base::OnceCallback<void(std::string)> credential_management_provide_pin_cb_; @@ -161,6 +166,60 @@ class SecurityKeysCredentialHandler : public SecurityKeysHandlerBase { base::WeakPtrFactory<SecurityKeysCredentialHandler> weak_factory_{this}; }; +// SecurityKeysBioEnrollmentHandler processes messages from the "Manage +// fingerprints" dialog of the "Security Keys" settings subpage. An instance of +// this class is created for each settings tab and is destroyed when the tab is +// closed. See SecurityKeysBioEnrollProxy about the interface. +class SecurityKeysBioEnrollmentHandler : public SecurityKeysHandlerBase { + public: + SecurityKeysBioEnrollmentHandler(); + ~SecurityKeysBioEnrollmentHandler() override; + + private: + enum class State { + kNone, + kStart, + kGatherPIN, + kReady, + kEnumerating, + kEnrolling, + kDeleting, + kCancelling, + }; + + void RegisterMessages() override; + void Close() override; + + void HandleStart(const base::ListValue* args); + void OnReady(); + void OnError(device::BioEnrollmentStatus status); + void OnGatherPIN(int64_t retries, base::OnceCallback<void(std::string)>); + + void HandleProvidePIN(const base::ListValue* args); + + void HandleEnumerate(const base::ListValue* args); + void OnHaveEnumeration( + device::CtapDeviceResponseCode, + base::Optional<std::map<std::vector<uint8_t>, std::string>>); + + void HandleStartEnrolling(const base::ListValue* args); + void OnEnrollingResponse(device::BioEnrollmentSampleStatus, uint8_t); + void OnEnrollmentFinished(device::CtapDeviceResponseCode); + + void HandleDelete(const base::ListValue* args); + void OnDelete(device::CtapDeviceResponseCode); + + void HandleCancel(const base::ListValue* args); + void OnEnrollCancel(device::CtapDeviceResponseCode); + + State state_ = State::kNone; + std::string callback_id_; + base::OnceCallback<void(std::string)> provide_pin_cb_; + std::unique_ptr<device::FidoDiscoveryFactory> discovery_factory_; + std::unique_ptr<device::BioEnrollmentHandler> bio_; + base::WeakPtrFactory<SecurityKeysBioEnrollmentHandler> weak_factory_{this}; +}; + } // namespace settings #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_SETTINGS_SECURITY_KEY_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/settings_ui.cc index d33e9f09336..3ea47f5691e 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_ui.cc @@ -17,7 +17,6 @@ #include "base/stl_util.h" #include "build/branding_buildflags.h" #include "build/build_config.h" -#include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/passwords/manage_passwords_view_utils.h" @@ -55,6 +54,7 @@ #include "components/favicon_base/favicon_url_parser.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/pref_registry/pref_registry_syncable.h" +#include "components/safe_browsing/buildflags.h" #include "components/unified_consent/feature.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" @@ -79,6 +79,7 @@ #endif // defined(OS_WIN) || defined(OS_CHROMEOS) #if defined(OS_CHROMEOS) +#include "ash/public/cpp/network_config_service.h" #include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" #include "ash/public/cpp/stylus_utils.h" #include "chrome/browser/browser_process.h" @@ -92,7 +93,6 @@ #include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_client_factory.h" #include "chrome/browser/chromeos/plugin_vm/plugin_vm_util.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" -#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h" @@ -113,24 +113,23 @@ #include "chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h" +#include "chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h" #include "chrome/browser/web_applications/system_web_app_manager.h" -#include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/grit/browser_resources.h" #include "chromeos/components/account_manager/account_manager.h" #include "chromeos/components/account_manager/account_manager_factory.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/constants/chromeos_pref_names.h" -#include "chromeos/constants/chromeos_switches.h" #include "chromeos/login/auth/password_visibility_utils.h" #include "chromeos/services/multidevice_setup/public/cpp/prefs.h" #include "chromeos/services/network_config/public/mojom/constants.mojom.h" // nogncheck #include "components/arc/arc_util.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user.h" -#include "services/service_manager/public/cpp/connector.h" #include "ui/base/ui_base_features.h" #include "ui/chromeos/resources/grit/ui_chromeos_resources.h" +#include "ui/resources/grit/webui_resources.h" #else // !defined(OS_CHROMEOS) #include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/ui/webui/settings/settings_default_browser_handler.h" @@ -148,32 +147,12 @@ #include "chrome/browser/ui/webui/settings/printing_handler.h" #endif -#if defined(FULL_SAFE_BROWSING) +#if BUILDFLAG(FULL_SAFE_BROWSING) #include "chrome/browser/safe_browsing/chrome_password_protection_service.h" #include "chrome/browser/ui/webui/settings/change_password_handler.h" #endif namespace settings { - -namespace { - -#if defined(OS_CHROMEOS) -bool ShouldShowParentalControls(Profile* profile) { - // Show Parental controls for regular and child accounts that are the - // primary profile. Do not show it to any secondary profiles, managed - // accounts that aren't child accounts (i.e. enterprise and EDU accounts), - // OTR accounts, or legacy supervised user accounts. - return chromeos::switches::IsParentalControlsSettingsEnabled() && - profile == ProfileManager::GetPrimaryUserProfile() && - !profile->IsLegacySupervised() && !profile->IsGuestSession() && - (profile->IsChild() || - !profile->GetProfilePolicyConnector()->IsManaged()); -} - -#endif // defined(OS_CHROMEOS) - -} // namespace - // static void SettingsUI::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { @@ -234,6 +213,8 @@ SettingsUI::SettingsUI(content::WebUI* web_ui) AddSettingsPageUIHandler(std::make_unique<SecurityKeysPINHandler>()); AddSettingsPageUIHandler(std::make_unique<SecurityKeysResetHandler>()); AddSettingsPageUIHandler(std::make_unique<SecurityKeysCredentialHandler>()); + AddSettingsPageUIHandler( + std::make_unique<SecurityKeysBioEnrollmentHandler>()); #if defined(OS_WIN) || defined(OS_MACOSX) AddSettingsPageUIHandler(std::make_unique<CaptionsHandler>()); @@ -270,7 +251,7 @@ SettingsUI::SettingsUI(content::WebUI* web_ui) #endif // OS_WIN && BUILDFLAG(GOOGLE_CHROME_BRANDING) bool password_protection_available = false; -#if defined(FULL_SAFE_BROWSING) +#if BUILDFLAG(FULL_SAFE_BROWSING) safe_browsing::ChromePasswordProtectionService* password_protection = safe_browsing::ChromePasswordProtectionService:: GetPasswordProtectionService(profile); @@ -301,8 +282,9 @@ SettingsUI::SettingsUI(content::WebUI* web_ui) password_manager::features::kPasswordImport)); #if defined(OS_CHROMEOS) - html_source->AddBoolean("showParentalControls", - ShouldShowParentalControls(profile)); + html_source->AddBoolean( + "showParentalControls", + chromeos::settings::ShouldShowParentalControls(profile)); #endif #if defined(OS_CHROMEOS) @@ -412,10 +394,8 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, chromeos::settings::DateTimeHandler::Create(html_source))); web_ui->AddMessageHandler( std::make_unique<chromeos::settings::FingerprintHandler>(profile)); - if (chromeos::switches::IsAssistantEnabled()) { - web_ui->AddMessageHandler( - std::make_unique<chromeos::settings::GoogleAssistantHandler>(profile)); - } + web_ui->AddMessageHandler( + std::make_unique<chromeos::settings::GoogleAssistantHandler>(profile)); if (g_browser_process->local_state()->GetBoolean(prefs::kKerberosEnabled)) { // Note that UI is also dependent on this pref. web_ui->AddMessageHandler( @@ -423,6 +403,12 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, } web_ui->AddMessageHandler( std::make_unique<chromeos::settings::KeyboardHandler>()); + + // TODO(crbug/950007): Remove adding WallpaperHandler when + // SplitSettings complete. + web_ui->AddMessageHandler( + std::make_unique<chromeos::settings::WallpaperHandler>(web_ui)); + if (plugin_vm::IsPluginVmEnabled(profile)) { web_ui->AddMessageHandler( std::make_unique<chromeos::settings::PluginVmHandler>(profile)); @@ -454,7 +440,7 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, : nullptr, android_sms_service ? android_sms_service->android_sms_app_manager() : nullptr)); - if (ShouldShowParentalControls(profile)) { + if (chromeos::settings::ShouldShowParentalControls(profile)) { web_ui->AddMessageHandler( std::make_unique<chromeos::settings::ParentalControlsHandler>( profile)); @@ -485,15 +471,22 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, html_source->AddInteger( "fingerprintReaderLocation", static_cast<int32_t>(chromeos::quick_unlock::GetFingerprintLocation())); + + // To use lottie, the worker-src CSP needs to be updated for the web ui that + // is using it. Since as of now there are only a couple of webuis using + // lottie animations, this update has to be performed manually. As the usage + // increases, set this as the default so manual override is no longer + // required. + html_source->OverrideContentSecurityPolicyWorkerSrc( + "worker-src blob: 'self';"); + html_source->AddResourcePath("finger_print.json", + IDR_LOGIN_FINGER_PRINT_TABLET_ANIMATION); } html_source->AddBoolean("lockScreenNotificationsEnabled", ash::features::IsLockScreenNotificationsEnabled()); html_source->AddBoolean( "lockScreenHideSensitiveNotificationsSupported", ash::features::IsLockScreenHideSensitiveNotificationsSupported()); - html_source->AddBoolean( - "lockScreenMediaKeysEnabled", - base::FeatureList::IsEnabled(ash::features::kLockScreenMediaKeys)); html_source->AddBoolean("showTechnologyBadge", !ash::features::IsSeparateNetworkIconsEnabled()); html_source->AddBoolean("hasInternalStylus", @@ -512,9 +505,6 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, html_source->AddBoolean("isDemoSession", chromeos::DemoSession::IsDeviceInDemoMode()); - html_source->AddBoolean("assistantEnabled", - chromeos::switches::IsAssistantEnabled()); - // We have 2 variants of Android apps settings. Default case, when the Play // Store app exists we show expandable section that allows as to // enable/disable the Play Store and link to Android settings which is @@ -531,10 +521,8 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, std::make_unique<chromeos::settings::PowerHandler>(profile->GetPrefs())); html_source->AddBoolean( - "showApps", base::FeatureList::IsEnabled(features::kAppManagement)); - - html_source->AddBoolean("showParentalControlsSettings", - ShouldShowParentalControls(profile)); + "showParentalControlsSettings", + chromeos::settings::ShouldShowParentalControls(profile)); } #endif // defined(OS_CHROMEOS) @@ -547,10 +535,7 @@ void SettingsUI::AddSettingsPageUIHandler( #if defined(OS_CHROMEOS) void SettingsUI::BindCrosNetworkConfig( chromeos::network_config::mojom::CrosNetworkConfigRequest request) { - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()) - ->BindInterface(chromeos::network_config::mojom::kServiceName, - std::move(request)); + ash::GetNetworkConfigService(std::move(request)); } #endif // defined(OS_CHROMEOS) 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 b0869cafd40..3d5fc205b3d 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 @@ -48,10 +48,11 @@ #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_ui_data_source.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension_builder.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "ppapi/buildflags/buildflags.h" #include "services/device/public/cpp/test/fake_usb_device_manager.h" #include "testing/gtest/include/gtest/gtest.h" @@ -468,7 +469,7 @@ class SiteSettingsHandlerTest : public testing::Test { const std::string kFlash; private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; TestingProfile* incognito_profile_; content::TestWebUI web_ui_; @@ -1009,8 +1010,7 @@ TEST_F(SiteSettingsHandlerTest, GetAndSetOriginPermissions) { #if BUILDFLAG(ENABLE_PLUGINS) TEST_F(SiteSettingsHandlerTest, ChangingFlashSettingForSiteIsRemembered) { - ChromePluginServiceFilter::GetInstance()->RegisterResourceContext( - profile(), profile()->GetResourceContext()); + ChromePluginServiceFilter::GetInstance()->RegisterProfile(profile()); FlashContentSettingsChangeWaiter waiter(profile()); const std::string origin_with_port("https://www.example.com:443"); @@ -1561,9 +1561,10 @@ class SiteSettingsHandlerChooserExceptionTest : public SiteSettingsHandlerTest { 6355, 0, "Google", "Widget", "789XYZ"); auto* chooser_context = UsbChooserContextFactory::GetForProfile(profile()); - device::mojom::UsbDeviceManagerPtr device_manager_ptr; - device_manager_.AddBinding(mojo::MakeRequest(&device_manager_ptr)); - chooser_context->SetDeviceManagerForTesting(std::move(device_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> device_manager; + device_manager_.AddReceiver( + device_manager.InitWithNewPipeAndPassReceiver()); + chooser_context->SetDeviceManagerForTesting(std::move(device_manager)); chooser_context->GetDevices( base::DoNothing::Once<std::vector<device::mojom::UsbDeviceInfoPtr>>()); base::RunLoop().RunUntilIdle(); @@ -1603,9 +1604,10 @@ class SiteSettingsHandlerChooserExceptionTest : public SiteSettingsHandlerTest { CreateIncognitoProfile(); auto* chooser_context = UsbChooserContextFactory::GetForProfile(incognito_profile()); - device::mojom::UsbDeviceManagerPtr device_manager_ptr; - device_manager_.AddBinding(mojo::MakeRequest(&device_manager_ptr)); - chooser_context->SetDeviceManagerForTesting(std::move(device_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> device_manager; + device_manager_.AddReceiver( + device_manager.InitWithNewPipeAndPassReceiver()); + chooser_context->SetDeviceManagerForTesting(std::move(device_manager)); chooser_context->GetDevices( base::DoNothing::Once<std::vector<device::mojom::UsbDeviceInfoPtr>>()); base::RunLoop().RunUntilIdle(); diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc index 440e917e224..605afeb6055 100644 --- a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc @@ -11,6 +11,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_observer.h" +#include "chrome/browser/ui/chrome_pages.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/tts_controller.h" @@ -24,7 +25,7 @@ #include "ui/base/l10n/l10n_util.h" namespace settings { -TtsHandler::TtsHandler() : weak_factory_(this) {} +TtsHandler::TtsHandler() {} TtsHandler::~TtsHandler() { content::TtsController::GetInstance()->RemoveVoicesChangedDelegate(this); @@ -143,7 +144,8 @@ void TtsHandler::HandlePreviewTtsVoice(const base::ListValue* args) { utterance->SetText(text); utterance->SetVoiceName(name); utterance->SetEngineId(extension_id); - utterance->SetSrcUrl(GURL("chrome://settings/manageAccessibility/tts")); + utterance->SetSrcUrl( + GURL(chrome::GetOSSettingsUrl("manageAccessibility/tts"))); utterance->SetEventDelegate(this); content::TtsController::GetInstance()->Stop(); diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.h b/chromium/chrome/browser/ui/webui/settings/tts_handler.h index f26fbb230e5..a839dee3c0b 100644 --- a/chromium/chrome/browser/ui/webui/settings/tts_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.h @@ -46,7 +46,7 @@ class TtsHandler : public SettingsPageUIHandler, int GetVoiceLangMatchScore(const content::VoiceData* voice, const std::string& app_locale); - base::WeakPtrFactory<TtsHandler> weak_factory_; + base::WeakPtrFactory<TtsHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TtsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings_utils_linux.cc b/chromium/chrome/browser/ui/webui/settings_utils_linux.cc index 9eef3566d25..19f554e3951 100644 --- a/chromium/chrome/browser/ui/webui/settings_utils_linux.cc +++ b/chromium/chrome/browser/ui/webui/settings_utils_linux.cc @@ -133,9 +133,9 @@ void DetectAndStartProxyConfigUtil(int render_process_id, if (launched) return; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ShowLinuxProxyConfigUrl, - render_process_id, render_view_id)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ShowLinuxProxyConfigUrl, render_process_id, + render_view_id)); } } // namespace @@ -143,8 +143,9 @@ void DetectAndStartProxyConfigUtil(int render_process_id, namespace settings_utils { void ShowNetworkProxySettings(content::WebContents* web_contents) { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::BindOnce(&DetectAndStartProxyConfigUtil, web_contents->GetRenderViewHost()->GetProcess()->GetID(), web_contents->GetRenderViewHost()->GetRoutingID())); diff --git a/chromium/chrome/browser/ui/webui/settings_utils_win.cc b/chromium/chrome/browser/ui/webui/settings_utils_win.cc index 69db0748f26..c5d1717a99a 100644 --- a/chromium/chrome/browser/ui/webui/settings_utils_win.cc +++ b/chromium/chrome/browser/ui/webui/settings_utils_win.cc @@ -109,9 +109,10 @@ void ShowNetworkProxySettings(content::WebContents* web_contents) { Profile::FromBrowserContext(web_contents->GetBrowserContext()), GURL("ms-settings:network-proxy")); } else { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, - base::BindOnce(&OpenConnectionDialogCallback)); + base::PostTask(FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, + base::MayBlock()}, + base::BindOnce(&OpenConnectionDialogCallback)); } } diff --git a/chromium/chrome/browser/ui/webui/signin/OWNERS b/chromium/chrome/browser/ui/webui/signin/OWNERS index a058d8e5b28..74b64b88981 100644 --- a/chromium/chrome/browser/ui/webui/signin/OWNERS +++ b/chromium/chrome/browser/ui/webui/signin/OWNERS @@ -1,6 +1,5 @@ achuith@chromium.org msarda@chromium.org -rogerta@chromium.org xiyuan@chromium.org per-file inline_login_handler_impl*=file://chrome/credential_provider/OWNERS 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 dd5f7fb4911..0086f6c69f5 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 @@ -74,8 +74,9 @@ class DiceTurnSyncOnHelperShutdownNotifierFactory AccountInfo GetAccountInfo(signin::IdentityManager* identity_manager, const std::string& account_id) { auto maybe_account_info = - identity_manager->FindAccountInfoForAccountWithRefreshTokenByAccountId( - account_id); + identity_manager + ->FindExtendedAccountInfoForAccountWithRefreshTokenByAccountId( + account_id); return maybe_account_info.has_value() ? maybe_account_info.value() : AccountInfo(); } 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 bcc7150897b..b3d39140ff4 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 @@ -38,7 +38,7 @@ #include "components/unified_consent/feature.h" #include "components/unified_consent/scoped_unified_consent.h" #include "components/unified_consent/url_keyed_data_collection_consent_helper.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "google_apis/gaia/google_service_auth_error.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "testing/gtest/include/gtest/gtest.h" @@ -405,7 +405,7 @@ class DiceTurnSyncOnHelperTestBase : public testing::Test { bool expected_sync_settings_shown_ = false; private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; base::ScopedTempDir temp_dir_; ScopedTestingLocalState local_state_; std::string account_id_; @@ -612,7 +612,7 @@ TEST_F(DiceTurnSyncOnHelperTest, EnterpriseConfirmationAbort) { } // Continue after the enterprise confirmation prompt. -TEST_F(DiceTurnSyncOnHelperTest, EnterpriseConfirmationContinue) { +TEST_F(DiceTurnSyncOnHelperTest, DISABLED_EnterpriseConfirmationContinue) { // Set expectations. expected_enterprise_confirmation_email_ = kEmail; expected_sync_confirmation_shown_ = true; 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 d025828e2ed..fb483f45025 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc @@ -46,6 +46,10 @@ void InlineLoginHandler::RegisterMessages() { base::BindRepeating(&InlineLoginHandler::HandleInitializeMessage, base::Unretained(this))); web_ui()->RegisterMessageCallback( + "authExtensionReady", + base::BindRepeating(&InlineLoginHandler::HandleAuthExtensionReadyMessage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "completeLogin", base::BindRepeating(&InlineLoginHandler::HandleCompleteLoginMessage, base::Unretained(this))); @@ -170,7 +174,7 @@ void InlineLoginHandler::HandleCompleteLoginMessage( void InlineLoginHandler::HandleCompleteLoginMessageWithCookies( const base::ListValue& args, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies) { const base::DictionaryValue* dict = nullptr; args.GetDictionary(0, &dict); @@ -180,9 +184,9 @@ void InlineLoginHandler::HandleCompleteLoginMessageWithCookies( const std::string& gaia_id = dict->FindKey("gaiaId")->GetString(); std::string auth_code; - for (const auto& cookie : cookies) { - if (cookie.Name() == "oauth_code") - auth_code = cookie.Value(); + for (const auto& cookie_with_status : cookies) { + if (cookie_with_status.cookie.Name() == "oauth_code") + auth_code = cookie_with_status.cookie.Value(); } bool skip_for_now = false; @@ -233,6 +237,8 @@ void InlineLoginHandler::HandleNavigationButtonClicked( #if !defined(OS_CHROMEOS) NOTREACHED() << "The inline login handler is no longer used in a browser " "or tab modal dialog."; +#else + FireWebUIListener("navigateBackInWebview"); #endif } diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h index 65e1ac89af0..ef8ce7823e3 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_H_ +#include <string> #include <vector> #include "base/macros.h" @@ -16,10 +17,6 @@ namespace base { class DictionaryValue; } -namespace net { -class CanonicalCookie; -} - namespace signin_metrics { enum class AccessPoint; } @@ -57,6 +54,9 @@ class InlineLoginHandler : public content::WebUIMessageHandler { // |SetExtraInitParams| to set extra init params. void ContinueHandleInitializeMessage(); + // JS callback to handle tasks after auth extension loads. + virtual void HandleAuthExtensionReadyMessage(const base::ListValue* args) {} + // JS callback to complete login. It calls |CompleteLogin| to do the real // work. void HandleCompleteLoginMessage(const base::ListValue* args); @@ -65,7 +65,7 @@ class InlineLoginHandler : public content::WebUIMessageHandler { // from the CookieManager. void HandleCompleteLoginMessageWithCookies( const base::ListValue& args, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies); // JS callback to switch the UI from a constrainted dialog to a full tab. @@ -76,7 +76,7 @@ class InlineLoginHandler : public content::WebUIMessageHandler { void HandleNavigationButtonClicked(const base::ListValue* args); // Handles the web ui message sent when the window is closed from javascript. - void HandleDialogClose(const base::ListValue* args); + virtual void HandleDialogClose(const base::ListValue* args); virtual void SetExtraInitParams(base::DictionaryValue& params) {} virtual void CompleteLogin(const std::string& email, diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc index 3e034ca354a..a127593b60e 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc @@ -132,6 +132,12 @@ void InlineLoginHandlerChromeOS::SetExtraInitParams( params.SetBoolean("ignoreCrOSIdpSetting", true); } +void InlineLoginHandlerChromeOS::HandleAuthExtensionReadyMessage( + const base::ListValue* args) { + AllowJavascript(); + FireWebUIListener("showBackButton"); +} + void InlineLoginHandlerChromeOS::CompleteLogin(const std::string& email, const std::string& password, const std::string& gaia_id, @@ -161,6 +167,12 @@ void InlineLoginHandlerChromeOS::CompleteLogin(const std::string& email, auth_code); } +void InlineLoginHandlerChromeOS::HandleDialogClose( + const base::ListValue* args) { + AllowJavascript(); + close_dialog_closure_.Run(); +} + void InlineLoginHandlerChromeOS::ShowIncognitoAndCloseDialog( const base::ListValue* args) { chrome::NewIncognitoWindow(Profile::FromWebUI(web_ui())); diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h index 415bf57ea09..56c511d5973 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h @@ -23,6 +23,7 @@ class InlineLoginHandlerChromeOS : public InlineLoginHandler { // InlineLoginHandler overrides. void RegisterMessages() override; void SetExtraInitParams(base::DictionaryValue& params) override; + void HandleAuthExtensionReadyMessage(const base::ListValue* args) override; void CompleteLogin(const std::string& email, const std::string& password, const std::string& gaia_id, @@ -31,6 +32,7 @@ class InlineLoginHandlerChromeOS : public InlineLoginHandler { bool trusted, bool trusted_found, bool choose_what_to_sync) override; + void HandleDialogClose(const base::ListValue* args) override; private: void ShowIncognitoAndCloseDialog(const base::ListValue* args); 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 201e1922675..08092d21e0c 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 @@ -258,7 +258,7 @@ void OnSyncSetupComplete(Profile* profile, ServiceAccessType::EXPLICIT_ACCESS); password_store->SaveGaiaPasswordHash( username, base::UTF8ToUTF16(password), - password_manager::metrics_util::SyncPasswordHashChange:: + password_manager::metrics_util::GaiaPasswordHashChange:: SAVED_ON_CHROME_SIGNIN); if (profiles::IsLockAvailable(profile)) @@ -374,7 +374,7 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( if (password_store && !primary_email.empty()) { password_store->SaveGaiaPasswordHash( primary_email, base::UTF8ToUTF16(password_), - password_manager::metrics_util::SyncPasswordHashChange:: + password_manager::metrics_util::GaiaPasswordHashChange:: SAVED_ON_CHROME_SIGNIN); } } diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc index 9b42b10cf06..62f1e70fb49 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc @@ -37,7 +37,7 @@ content::WebUIDataSource* CreateWebUIDataSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIChromeSigninHost); source->OverrideContentSecurityPolicyObjectSrc("object-src chrome:;"); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_INLINE_LOGIN_HTML); diff --git a/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc b/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc index aff12cc4469..e9b169c910f 100644 --- a/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc +++ b/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc @@ -16,7 +16,6 @@ #include "chrome/browser/ui/scoped_tabbed_browser_displayer.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/url_constants.h" -#include "components/signin/core/browser/signin_header_helper.h" #if !defined(OS_CHROMEOS) #include "chrome/browser/ui/user_manager.h" @@ -112,7 +111,7 @@ void LoginUIService::DisplayLoginResult(Browser* browser, } else if (browser) { browser->window()->ShowAvatarBubbleFromAvatarButton( BrowserWindow::AVATAR_BUBBLE_MODE_CONFIRM_SIGNIN, - signin::ManageAccountsParams(), + signin_metrics::AccessPoint::ACCESS_POINT_EXTENSIONS, false); } #endif diff --git a/chromium/chrome/browser/ui/webui/signin/login_ui_service_unittest.cc b/chromium/chrome/browser/ui/webui/signin/login_ui_service_unittest.cc index b2fb62b06da..d5a7a11066e 100644 --- a/chromium/chrome/browser/ui/webui/signin/login_ui_service_unittest.cc +++ b/chromium/chrome/browser/ui/webui/signin/login_ui_service_unittest.cc @@ -12,7 +12,7 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -43,7 +43,7 @@ class LoginUIServiceTest : public testing::Test { } protected: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_; // Test profile used by all tests - this is owned by profile_manager_. 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 dec3301d61e..b08ea973884 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 @@ -18,7 +18,6 @@ #include "base/value_conversions.h" #include "base/values.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" @@ -28,6 +27,7 @@ #include "chrome/browser/signin/signin_error_controller_factory.h" #include "chrome/browser/signin/signin_util.h" #include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/user_manager.h" #include "chrome/browser/ui/webui/profile_helper.h" #include "chrome/browser/ui/webui/signin/signin_utils.h" @@ -39,14 +39,14 @@ #include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/notification_service.h" #include "content/public/browser/web_ui.h" #include "ui/base/l10n/l10n_util.h" -SigninCreateProfileHandler::SigninCreateProfileHandler() - : profile_creation_type_(NO_CREATION_IN_PROGRESS) {} +SigninCreateProfileHandler::SigninCreateProfileHandler() = default; -SigninCreateProfileHandler::~SigninCreateProfileHandler() {} +SigninCreateProfileHandler::~SigninCreateProfileHandler() { + BrowserList::RemoveObserver(this); +} void SigninCreateProfileHandler::GetLocalizedValues( base::DictionaryValue* localized_strings) { @@ -83,6 +83,43 @@ void SigninCreateProfileHandler::RegisterMessages() { base::Unretained(this))); } +void SigninCreateProfileHandler::OnBrowserAdded(Browser* browser) { + // Only respond to one OnBrowserAdded. + BrowserList::RemoveObserver(this); + UserManager::Hide(); +} + +void SigninCreateProfileHandler::OpenNewWindowForProfile( + Profile* profile, + Profile::CreateStatus status) { + profiles::OpenBrowserWindowForProfile( + base::Bind(&SigninCreateProfileHandler::OnBrowserReadyCallback, + weak_ptr_factory_.GetWeakPtr()), + false, // Don't create a window if one already exists. + true, // Create a first run window. + false, // There is no need to unblock all extensions because we only open + // browser window if the Profile is not locked. Hence there is no + // extension blocked. + profile, status); +} + +void SigninCreateProfileHandler::OpenForceSigninDialogForProfile( + Profile* profile) { + UserManagerProfileDialog::ShowForceSigninDialog( + web_ui()->GetWebContents()->GetBrowserContext(), profile->GetPath()); +} + +void SigninCreateProfileHandler::DoCreateProfile(const base::string16& name, + const std::string& icon_url, + bool create_shortcut) { + ProfileMetrics::LogProfileAddNewUser(ProfileMetrics::ADD_NEW_USER_DIALOG); + + profile_path_being_created_ = ProfileManager::CreateMultiProfileAsync( + name, icon_url, + base::Bind(&SigninCreateProfileHandler::OnProfileCreated, + weak_ptr_factory_.GetWeakPtr(), create_shortcut)); +} + void SigninCreateProfileHandler::RequestDefaultProfileIcons( const base::ListValue* args) { web_ui()->CallJavascriptFunctionUnsafe( @@ -121,17 +158,6 @@ void SigninCreateProfileHandler::CreateProfile(const base::ListValue* args) { DoCreateProfile(name, icon_url, create_shortcut); } -void SigninCreateProfileHandler::DoCreateProfile(const base::string16& name, - const std::string& icon_url, - bool create_shortcut) { - ProfileMetrics::LogProfileAddNewUser(ProfileMetrics::ADD_NEW_USER_DIALOG); - - profile_path_being_created_ = ProfileManager::CreateMultiProfileAsync( - name, icon_url, - base::Bind(&SigninCreateProfileHandler::OnProfileCreated, - weak_ptr_factory_.GetWeakPtr(), create_shortcut)); -} - void SigninCreateProfileHandler::OnProfileCreated( bool create_shortcut, Profile* profile, @@ -210,26 +236,6 @@ void SigninCreateProfileHandler::CreateShortcutAndShowSuccess( profile_creation_type_ = NO_CREATION_IN_PROGRESS; } -void SigninCreateProfileHandler::OpenNewWindowForProfile( - Profile* profile, - Profile::CreateStatus status) { - profiles::OpenBrowserWindowForProfile( - base::Bind(&SigninCreateProfileHandler::OnBrowserReadyCallback, - weak_ptr_factory_.GetWeakPtr()), - false, // Don't create a window if one already exists. - true, // Create a first run window. - false, // There is no need to unblock all extensions because we only open - // browser window if the Profile is not locked. Hence there is no - // extension blocked. - profile, status); -} - -void SigninCreateProfileHandler::OpenForceSigninDialogForProfile( - Profile* profile) { - UserManagerProfileDialog::ShowForceSigninDialog( - web_ui()->GetWebContents()->GetBrowserContext(), profile->GetPath()); -} - void SigninCreateProfileHandler::ShowProfileCreationError( Profile* profile, const base::string16& error) { @@ -260,30 +266,16 @@ base::string16 SigninCreateProfileHandler::GetProfileCreationErrorMessageLocal() return l10n_util::GetStringUTF16(IDS_PROFILES_CREATE_LOCAL_ERROR); } -void SigninCreateProfileHandler::Observe( - int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - DCHECK_EQ(chrome::NOTIFICATION_BROWSER_OPENED, type); - - // Only respond to one Browser Opened event. - registrar_.Remove(this, chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); - UserManager::Hide(); -} - void SigninCreateProfileHandler::OnBrowserReadyCallback( Profile* profile, Profile::CreateStatus profile_create_status) { Browser* browser = chrome::FindAnyBrowser(profile, false); // Closing the User Manager before the window is created can flakily cause // Chrome to close. - if (browser && browser->window()) { + if (browser && browser->window()) UserManager::Hide(); - } else { - registrar_.Add(this, chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); - } + else + BrowserList::AddObserver(this); } base::Value SigninCreateProfileHandler::GetWebUIListenerName( diff --git a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h index db7c0811783..020f91adad3 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h +++ b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h @@ -12,9 +12,8 @@ #include "base/time/time.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_window.h" +#include "chrome/browser/ui/browser_list_observer.h" #include "chrome/common/buildflags.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/google_service_auth_error.h" @@ -25,14 +24,35 @@ class ListValue; // Handler for the 'create profile' page. class SigninCreateProfileHandler : public content::WebUIMessageHandler, - public content::NotificationObserver { + public BrowserListObserver { public: SigninCreateProfileHandler(); ~SigninCreateProfileHandler() override; void GetLocalizedValues(base::DictionaryValue* localized_strings); + // WebUIMessageHandler: + void RegisterMessages() override; + + // BrowserListObserver: + void OnBrowserAdded(Browser* browser) override; + protected: + // These methods are virtual for testing. + // Opens a new window for |profile|. + virtual void OpenNewWindowForProfile(Profile* profile, + Profile::CreateStatus status); + + // Opens a new signin dialog for |profile|. + virtual void OpenForceSigninDialogForProfile(Profile* profile); + + // Asynchronously creates and initializes a new profile. + virtual void DoCreateProfile(const base::string16& name, + const std::string& icon_url, + bool create_shortcut); + + private: + friend class TestSigninCreateProfileHandler; FRIEND_TEST_ALL_PREFIXES(SigninCreateProfileHandlerTest, ReturnDefaultProfileIcons); FRIEND_TEST_ALL_PREFIXES(SigninCreateProfileHandlerTest, @@ -41,15 +61,6 @@ class SigninCreateProfileHandler : public content::WebUIMessageHandler, CreateProfile); FRIEND_TEST_ALL_PREFIXES(SigninCreateProfileHandlerTest, CreateProfileWithForceSignin); - - // WebUIMessageHandler implementation. - void RegisterMessages() override; - - // content::NotificationObserver implementation: - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; - // Represents the final profile creation status. It is used to map // the status to the javascript method to be called. enum ProfileCreationStatus { @@ -92,13 +103,6 @@ class SigninCreateProfileHandler : public content::WebUIMessageHandler, void CreateShortcutAndShowSuccess(bool create_shortcut, Profile* profile); - // Opens a new window for |profile|. - virtual void OpenNewWindowForProfile(Profile* profile, - Profile::CreateStatus status); - - // Opens a new signin dialog for |profile|. - virtual void OpenForceSigninDialogForProfile(Profile* profile); - // This callback is run after a new browser (but not the window) has been // created for the new profile. void OnBrowserReadyCallback(Profile* profile, Profile::CreateStatus status); @@ -123,18 +127,10 @@ class SigninCreateProfileHandler : public content::WebUIMessageHandler, // Indicates the type of the in progress profile creation operation. // The value is only relevant while we are creating/importing a profile. - ProfileCreationOperationType profile_creation_type_; - - // Asynchronously creates and initializes a new profile. - virtual void DoCreateProfile(const base::string16& name, - const std::string& icon_url, - bool create_shortcut); - - content::NotificationRegistrar registrar_; + ProfileCreationOperationType profile_creation_type_ = NO_CREATION_IN_PROGRESS; base::WeakPtrFactory<SigninCreateProfileHandler> weak_ptr_factory_{this}; - private: DISALLOW_COPY_AND_ASSIGN(SigninCreateProfileHandler); }; diff --git a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc index 8e714ee6b01..1a448873b44 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc @@ -101,8 +101,8 @@ class SigninCreateProfileHandlerTest : public BrowserWithTestWindowTest { BrowserWithTestWindowTest::SetUp(); profile_manager()->DeleteAllTestingProfiles(); - handler_.reset(new TestSigninCreateProfileHandler(web_ui(), - profile_manager())); + handler_ = std::make_unique<TestSigninCreateProfileHandler>( + web_ui(), profile_manager()); } void TearDown() override { diff --git a/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_ui.cc b/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_ui.cc index 1aaef4ddc1f..fbdc4b44378 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_ui.cc @@ -23,7 +23,7 @@ SigninEmailConfirmationUI::SigninEmailConfirmationUI(content::WebUI* web_ui) content::WebUIDataSource* source = content::WebUIDataSource::Create( chrome::kChromeUISigninEmailConfirmationHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_SIGNIN_EMAIL_CONFIRMATION_HTML); source->AddResourcePath("signin_email_confirmation.js", IDR_SIGNIN_EMAIL_CONFIRMATION_JS); diff --git a/chromium/chrome/browser/ui/webui/signin/signin_error_handler_unittest.cc b/chromium/chrome/browser/ui/webui/signin/signin_error_handler_unittest.cc index 1f5e003de36..362f08bf1fa 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_error_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_error_handler_unittest.cc @@ -71,7 +71,7 @@ class SigninErrorHandlerTest : public BrowserWithTestWindowTest { chrome::NewTab(browser()); web_ui()->set_web_contents( browser()->tab_strip_model()->GetActiveWebContents()); - signin_error_ui_.reset(new SigninErrorUI(web_ui())); + signin_error_ui_ = std::make_unique<SigninErrorUI>(web_ui()); } void TearDown() override { @@ -85,7 +85,7 @@ class SigninErrorHandlerTest : public BrowserWithTestWindowTest { auto handler = std::make_unique<TestingSigninErrorHandler>( browser(), false /* is_system_profile */, web_ui()); handler_ = handler.get(); - signin_error_ui_.reset(new SigninErrorUI(web_ui())); + signin_error_ui_ = std::make_unique<SigninErrorUI>(web_ui()); web_ui()->AddMessageHandler(std::move(handler)); } 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 b7fc877daf6..5a6f3effed4 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc @@ -66,7 +66,7 @@ void SigninErrorUI::Initialize(Browser* browser, bool is_system_profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUISigninErrorHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_SIGNIN_ERROR_HTML); source->AddResourcePath("signin_error.js", IDR_SIGNIN_ERROR_JS); source->AddResourcePath("signin_shared_css.html", IDR_SIGNIN_SHARED_CSS_HTML); 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 59859724861..2ae8e584e01 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc @@ -104,7 +104,7 @@ void SyncConfirmationHandler::HandleAccountImageRequest( const base::ListValue* args) { DCHECK(profile_->IsSyncAllowed()); base::Optional<AccountInfo> primary_account_info = - identity_manager_->FindExtendedAccountInfoForAccount( + identity_manager_->FindExtendedAccountInfoForAccountWithRefreshToken( identity_manager_->GetPrimaryAccountInfo()); // Fire the "account-image-changed" listener from |SetUserImageURL()|. @@ -215,7 +215,7 @@ void SyncConfirmationHandler::HandleInitializedWithSize( return; base::Optional<AccountInfo> primary_account_info = - identity_manager_->FindExtendedAccountInfoForAccount( + identity_manager_->FindExtendedAccountInfoForAccountWithRefreshToken( identity_manager_->GetPrimaryAccountInfo()); if (!primary_account_info) { // No account is signed in, so there is nothing to be displayed in the sync 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 3593351d31e..a38f485d26e 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 @@ -31,7 +31,7 @@ #include "components/consent_auditor/fake_consent_auditor.h" #include "components/signin/public/base/avatar_icon_util.h" #include "components/unified_consent/scoped_unified_consent.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" const int kExpectedProfileImageSize = 128; @@ -86,7 +86,7 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest, auto handler = std::make_unique<TestingSyncConfirmationHandler>( browser(), web_ui(), GetStringToGrdIdMap()); handler_ = handler.get(); - sync_confirmation_ui_.reset(new SyncConfirmationUI(web_ui())); + sync_confirmation_ui_ = std::make_unique<SyncConfirmationUI>(web_ui()); web_ui()->AddMessageHandler(std::move(handler)); identity_test_env_adaptor_ = @@ -168,7 +168,7 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest, signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile()); base::Optional<AccountInfo> primary_account = - identity_manager->FindExtendedAccountInfoForAccount( + identity_manager->FindExtendedAccountInfoForAccountWithRefreshToken( identity_manager->GetPrimaryAccountInfo()); std::string original_picture_url = diff --git a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc index 5d58676bbbe..233b67c2b9d 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc @@ -33,7 +33,7 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUISyncConfirmationHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("signin_shared_css.html", IDR_SIGNIN_SHARED_CSS_HTML); if (is_sync_allowed) { @@ -67,7 +67,7 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); base::Optional<AccountInfo> primary_account_info = - identity_manager->FindExtendedAccountInfoForAccount( + identity_manager->FindExtendedAccountInfoForAccountWithRefreshToken( identity_manager->GetPrimaryAccountInfo()); GURL account_picture_url(primary_account_info ? primary_account_info->picture_url 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 1e7be5fffb2..faa9222bb43 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/value_conversions.h" #include "base/values.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" @@ -52,7 +51,6 @@ #include "components/account_id/account_id.h" #include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" -#include "content/public/browser/notification_service.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -296,7 +294,9 @@ UserManagerScreenHandler::UserManagerScreenHandler() { } } -UserManagerScreenHandler::~UserManagerScreenHandler() {} +UserManagerScreenHandler::~UserManagerScreenHandler() { + BrowserList::RemoveObserver(this); +} void UserManagerScreenHandler::HandleInitialize(const base::ListValue* args) { // If the URL has a hash parameter, store it for later. @@ -349,10 +349,10 @@ void UserManagerScreenHandler::HandleAuthenticatedLaunchUser( // still have a hash of the old one. The new way of checking a password // change makes use of a token so we do that... if it's available. if (!oauth_client_) { - oauth_client_.reset(new gaia::GaiaOAuthClient( + oauth_client_ = std::make_unique<gaia::GaiaOAuthClient>( content::BrowserContext::GetDefaultStoragePartition( web_ui()->GetWebContents()->GetBrowserContext()) - ->GetURLLoaderFactoryForBrowserProcess())); + ->GetURLLoaderFactoryForBrowserProcess()); } const std::string token = entry->GetPasswordChangeDetectionToken(); @@ -620,6 +620,37 @@ void UserManagerScreenHandler::RegisterMessages() { web_ui()->RegisterMessageCallback("noPodFocused", base::DoNothing()); } +void UserManagerScreenHandler::OnBrowserAdded(Browser* browser) { + // Only respond to one Browser Opened event. + BrowserList::RemoveObserver(this); + + // Unlock the profile after browser opens so startup can read the lock bit. + // Any necessary authentication must have been successful to reach this point. + ProfileAttributesEntry* entry = nullptr; + if (!browser->profile()->IsGuestSession()) { + bool has_entry = g_browser_process->profile_manager() + ->GetProfileAttributesStorage() + .GetProfileAttributesWithPath( + browser->profile()->GetPath(), &entry); + DCHECK(has_entry); + // If force sign in is enabled and profile is not signed in, do not close + // UserManager and unlock profile. + if (signin_util::IsForceSigninEnabled() && !entry->IsAuthenticated()) + return; + entry->SetIsSigninRequired(false); + } + + if (!url_hash_.empty()) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&UrlHashHelper::ExecuteUrlHash, + base::Owned(new UrlHashHelper(browser, url_hash_)))); + } + + // This call is last as it deletes this object. + UserManager::Hide(); +} + void UserManagerScreenHandler::GetLocalizedValues( base::DictionaryValue* localized_strings) { // For Control Bar. @@ -827,48 +858,6 @@ void UserManagerScreenHandler::ReportAuthenticationResult( } } -void UserManagerScreenHandler::OnBrowserOpened(Browser* browser) { - DCHECK(browser); - DCHECK(browser->window()); - - // Unlock the profile after browser opens so startup can read the lock bit. - // Any necessary authentication must have been successful to reach this point. - ProfileAttributesEntry* entry = nullptr; - if (!browser->profile()->IsGuestSession()) { - bool has_entry = g_browser_process->profile_manager()-> - GetProfileAttributesStorage(). - GetProfileAttributesWithPath(browser->profile()->GetPath(), &entry); - DCHECK(has_entry); - // If force sign in is enabled and profile is not signed in, do not close - // UserManager and unlock profile. - if (signin_util::IsForceSigninEnabled() && !entry->IsAuthenticated()) - return; - entry->SetIsSigninRequired(false); - } - - if (!url_hash_.empty()) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&UrlHashHelper::ExecuteUrlHash, - base::Owned(new UrlHashHelper(browser, url_hash_)))); - } - - // This call is last as it deletes this object. - UserManager::Hide(); -} - -void UserManagerScreenHandler::Observe( - int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - DCHECK_EQ(chrome::NOTIFICATION_BROWSER_OPENED, type); - - // Only respond to one Browser Opened event. - registrar_.Remove(this, chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); - OnBrowserOpened(content::Source<Browser>(source).ptr()); -} - // This callback is run after switching to a new profile has finished. This // means either a new browser has been created (but not the window), or an // existing one has been found. The HideUserManager task needs to be posted @@ -877,10 +866,8 @@ void UserManagerScreenHandler::Observe( void UserManagerScreenHandler::OnSwitchToProfileComplete( Profile* profile, Profile::CreateStatus profile_create_status) { Browser* browser = chrome::FindAnyBrowser(profile, false); - if (browser && browser->window()) { - OnBrowserOpened(browser); - } else { - registrar_.Add(this, chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); - } + if (browser && browser->window()) + OnBrowserAdded(browser); + else + BrowserList::AddObserver(this); } 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 8906900c485..0e405c571b0 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,8 +17,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_statistics.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" +#include "chrome/browser/ui/browser_list_observer.h" #include "content/public/browser/web_ui_message_handler.h" #include "google_apis/gaia/gaia_oauth_client.h" @@ -43,10 +42,9 @@ enum AuthenticatedLaunchUserEvent { EVENT_COUNT, }; -class UserManagerScreenHandler - : public content::WebUIMessageHandler, - public gaia::GaiaOAuthClient::Delegate, - public content::NotificationObserver { +class UserManagerScreenHandler : public content::WebUIMessageHandler, + public BrowserListObserver, + public gaia::GaiaOAuthClient::Delegate { public: UserManagerScreenHandler(); ~UserManagerScreenHandler() override; @@ -58,13 +56,11 @@ class UserManagerScreenHandler // that all the visible user manager screens can be updated. class ProfileUpdateObserver; - // WebUIMessageHandler implementation. + // WebUIMessageHandler: void RegisterMessages() override; - // content::NotificationObserver implementation: - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; + // BrowserListObserver: + void OnBrowserAdded(Browser* browser) override; void HandleInitialize(const base::ListValue* args); void HandleAuthenticatedLaunchUser(const base::ListValue* args); @@ -83,15 +79,12 @@ class UserManagerScreenHandler base::Time start_time, profiles::ProfileCategoryStats result); - // Handle GAIA auth results. + // gaia::GaiaOAuthClient::Delegate: void OnGetTokenInfoResponse( std::unique_ptr<base::DictionaryValue> token_info) override; void OnOAuthError() override; void OnNetworkError(int response_code) override; - // Handle when Notified of a NOTIFICATION_BROWSER_OPENED event. - void OnBrowserOpened(Browser* browser); - // Sends user list to account chooser. void SendUserList(); @@ -119,8 +112,6 @@ class UserManagerScreenHandler // URL hash, used to key post-profile actions if present. std::string url_hash_; - content::NotificationRegistrar registrar_; - // The CancelableTaskTracker is currently used by GetProfileStatistics base::CancelableTaskTracker tracker_; diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc b/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc index cd70f2e9a14..628865ae71b 100644 --- a/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc @@ -61,7 +61,7 @@ content::WebUIDataSource* UserManagerUI::CreateUIDataSource( source->AddBoolean("isForceSigninEnabled", signin_util::IsForceSigninEnabled()); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("control_bar.html", IDR_CONTROL_BAR_HTML); source->AddResourcePath("control_bar.js", IDR_CONTROL_BAR_JS); diff --git a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc index 6181aae010b..8f288996daf 100644 --- a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc @@ -27,7 +27,7 @@ content::WebUIDataSource* CreateSignInInternalsHTMLSource() { source->OverrideContentSecurityPolicyScriptSrc( "script-src chrome://resources 'self' 'unsafe-eval';"); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("signin_internals.js", IDR_SIGNIN_INTERNALS_INDEX_JS); source->SetDefaultResource(IDR_SIGNIN_INTERNALS_INDEX_HTML); return source; diff --git a/chromium/chrome/browser/ui/webui/site_settings_helper.cc b/chromium/chrome/browser/ui/webui/site_settings_helper.cc index 701e6da03b0..3430d836de6 100644 --- a/chromium/chrome/browser/ui/webui/site_settings_helper.cc +++ b/chromium/chrome/browser/ui/webui/site_settings_helper.cc @@ -90,6 +90,8 @@ const ContentSettingsTypeNameEntry kContentSettingsTypeGroupNames[] = { {CONTENT_SETTINGS_TYPE_BLUETOOTH_SCANNING, "bluetooth-scanning"}, {CONTENT_SETTINGS_TYPE_HID_GUARD, "hid-devices"}, {CONTENT_SETTINGS_TYPE_HID_CHOOSER_DATA, kHidChooserDataGroupType}, + {CONTENT_SETTINGS_TYPE_NATIVE_FILE_SYSTEM_WRITE_GUARD, + "native-file-system-write"}, // Add new content settings here if a corresponding Javascript string // representation for it is not required. Note some exceptions do have UI in diff --git a/chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc b/chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc index 0a9cddf2b14..fa6bc52b900 100644 --- a/chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc +++ b/chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc @@ -20,8 +20,9 @@ #include "components/content_settings/core/test/content_settings_mock_provider.h" #include "components/content_settings/core/test/content_settings_test_utils.h" #include "components/prefs/pref_service.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/extension_registry.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "services/device/public/cpp/test/fake_usb_device_manager.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -63,7 +64,7 @@ class SiteSettingsHelperTest : public testing::Test { } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(SiteSettingsHelperTest, CheckExceptionOrder) { @@ -457,9 +458,10 @@ class SiteSettingsHelperChooserExceptionTest : public testing::Test { device_manager_.CreateAndAddDevice(6354, 0, "Google", "Gadget", ""); auto* chooser_context = UsbChooserContextFactory::GetForProfile(profile()); - device::mojom::UsbDeviceManagerPtr device_manager_ptr; - device_manager_.AddBinding(mojo::MakeRequest(&device_manager_ptr)); - chooser_context->SetDeviceManagerForTesting(std::move(device_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> device_manager; + device_manager_.AddReceiver( + device_manager.InitWithNewPipeAndPassReceiver()); + chooser_context->SetDeviceManagerForTesting(std::move(device_manager)); chooser_context->GetDevices( base::DoNothing::Once<std::vector<device::mojom::UsbDeviceInfoPtr>>()); base::RunLoop().RunUntilIdle(); @@ -490,7 +492,7 @@ class SiteSettingsHelperChooserExceptionTest : public testing::Test { device::FakeUsbDeviceManager device_manager_; private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; }; diff --git a/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn index 0575b4b15d2..f83f5c25536 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn @@ -8,7 +8,4 @@ mojom("mojo_bindings") { sources = [ "snippets_internals.mojom", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } diff --git a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.cc index 82628d37081..2bcda35f859 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.cc @@ -117,8 +117,7 @@ SnippetsInternalsPageHandler::SnippetsInternalsPageHandler( content_suggestions_service_ ->remote_suggestions_provider_for_debugging()), pref_service_(pref_service), - page_(std::move(page)), - weak_ptr_factory_(this) {} + page_(std::move(page)) {} SnippetsInternalsPageHandler::~SnippetsInternalsPageHandler() {} diff --git a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.h b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.h index e2ab4c8cbb3..7702050a60e 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.h +++ b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.h @@ -92,7 +92,7 @@ class SnippetsInternalsPageHandler // Handle back to the page by which we can update. snippets_internals::mojom::PagePtr page_; - base::WeakPtrFactory<SnippetsInternalsPageHandler> weak_ptr_factory_; + base::WeakPtrFactory<SnippetsInternalsPageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SnippetsInternalsPageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc index cfe01dc50f0..89f723083ee 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc @@ -53,9 +53,9 @@ void SnippetsInternalsUI::CreatePageHandler( CreatePageHandlerCallback callback) { DCHECK(page); snippets_internals::mojom::PageHandlerPtr handler; - page_handler_.reset(new SnippetsInternalsPageHandler( + page_handler_ = std::make_unique<SnippetsInternalsPageHandler>( mojo::MakeRequest(&handler), std::move(page), - content_suggestions_service_, pref_service_)); + content_suggestions_service_, pref_service_); std::move(callback).Run(std::move(handler)); } 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 28d6c59af0f..be07aad14bc 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 @@ -17,6 +17,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/supervised_user/child_accounts/child_account_service.h" +#include "chrome/browser/supervised_user/supervised_user_error_page/supervised_user_error_page.h" #include "chrome/browser/supervised_user/supervised_user_service.h" #include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chrome/browser/supervised_user/supervised_user_settings_service.h" @@ -24,7 +25,6 @@ #include "chrome/browser/supervised_user/supervised_user_url_filter.h" #include "chrome/common/channel_info.h" #include "components/signin/public/identity_manager/identity_manager.h" -#include "components/supervised_user_error_page/supervised_user_error_page.h" #include "components/url_formatter/url_fixer.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" diff --git a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h index 7be0cfac16b..f257eaac9ec 100644 --- a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h +++ b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h @@ -9,9 +9,9 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" +#include "chrome/browser/supervised_user/supervised_user_error_page/supervised_user_error_page.h" #include "chrome/browser/supervised_user/supervised_user_service_observer.h" #include "chrome/browser/supervised_user/supervised_user_url_filter.h" -#include "components/supervised_user_error_page/supervised_user_error_page.h" #include "content/public/browser/web_ui_message_handler.h" namespace base { 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 cf5c1ba9541..d21278ee6f6 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 @@ -18,6 +18,7 @@ #include "chrome/browser/sync_file_system/sync_file_system_service_factory.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/common/extension.h" @@ -28,6 +29,10 @@ namespace syncfs_internals { namespace { +// TODO(crbug.com/989631): Break this and GetExtensionStatusesAsDictionary +// into a separate library, so the callbacks can use weak pointers to the +// calling instances. This will also break the dependency between +// ExtensionStatusesHandler and FileMetadataHandler. void ConvertExtensionStatusToDictionary( const base::WeakPtr<extensions::ExtensionService>& extension_service, const base::Callback<void(const base::ListValue&)>& callback, @@ -37,13 +42,17 @@ void ConvertExtensionStatusToDictionary( return; } + extensions::ExtensionRegistry* extension_registry = + extensions::ExtensionRegistry::Get(extension_service->profile()); + base::ListValue list; for (auto itr = status_map.begin(); itr != status_map.end(); ++itr) { std::string extension_id = itr->first.HostNoBrackets(); // Join with human readable extension name. const extensions::Extension* extension = - extension_service->GetExtensionById(extension_id, true); + extension_registry->GetExtensionById( + extension_id, extensions::ExtensionRegistry::COMPATIBILITY); if (!extension) continue; diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.cc b/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.cc index 50edaaa95b8..bdc01392797 100644 --- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.cc @@ -22,7 +22,7 @@ content::WebUIDataSource* CreateSyncFileSystemInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create( chrome::kChromeUISyncFileSystemInternalsHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath( "utils.js", IDR_SYNC_FILE_SYSTEM_INTERNALS_UTILS_JS); 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 0e69a9c4617..b4091b4eab5 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 @@ -120,11 +120,11 @@ class SyncInternalsMessageHandlerTest : public ChromeRenderViewHostTestHarness { browser_sync::UserEventServiceFactory::GetInstance() ->SetTestingFactoryAndUse( profile(), base::BindRepeating(&BuildFakeUserEventService))); - handler_.reset(new TestableSyncInternalsMessageHandler( + handler_ = std::make_unique<TestableSyncInternalsMessageHandler>( &web_ui_, base::BindRepeating( &SyncInternalsMessageHandlerTest::ConstructAboutInformation, - base::Unretained(this)))); + base::Unretained(this))); } void TearDown() override { diff --git a/chromium/chrome/browser/ui/webui/sync_internals_ui.cc b/chromium/chrome/browser/ui/webui/sync_internals_ui.cc index 8b360af1286..d4d18359242 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/sync_internals_ui.cc @@ -22,7 +22,7 @@ content::WebUIDataSource* CreateSyncInternalsHTMLSource() { source->OverrideContentSecurityPolicyScriptSrc( "script-src chrome://resources 'self' 'unsafe-eval';"); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath(syncer::sync_ui_util::kSyncIndexJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_INDEX_JS); source->AddResourcePath(syncer::sync_ui_util::kChromeSyncJS, diff --git a/chromium/chrome/browser/ui/webui/system_info_ui.cc b/chromium/chrome/browser/ui/webui/system_info_ui.cc index cf886af54c8..12a75b82441 100644 --- a/chromium/chrome/browser/ui/webui/system_info_ui.cc +++ b/chromium/chrome/browser/ui/webui/system_info_ui.cc @@ -66,7 +66,7 @@ content::WebUIDataSource* CreateSystemInfoUIDataSource() { html_source->AddResourcePath("about_sys.js", IDR_ABOUT_SYS_JS); html_source->AddResourcePath("about_sys.css", IDR_ABOUT_SYS_CSS); html_source->SetDefaultResource(IDR_ABOUT_SYS_HTML); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); return html_source; } diff --git a/chromium/chrome/browser/ui/webui/tab_strip/OWNERS b/chromium/chrome/browser/ui/webui/tab_strip/OWNERS new file mode 100644 index 00000000000..b84c705bb6e --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/OWNERS @@ -0,0 +1,4 @@ +dpapad@chromium.org +johntlee@chromium.org + +# COMPONENT: UI>Browser>WebUI diff --git a/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.cc b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.cc new file mode 100644 index 00000000000..f294f8d2890 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.cc @@ -0,0 +1,166 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui.h" + +#include <memory> +#include <string> +#include <utility> +#include <vector> + +#include "base/base64.h" +#include "base/values.h" +#include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/favicon_source.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/tab_strip_resources.h" +#include "chrome/grit/tab_strip_resources_map.h" +#include "components/favicon_base/favicon_url_parser.h" +#include "content/public/browser/url_data_source.h" +#include "content/public/browser/web_ui_data_source.h" +#include "content/public/browser/web_ui_message_handler.h" +#include "third_party/skia/include/core/SkImageEncoder.h" +#include "third_party/skia/include/core/SkStream.h" + +namespace { + +// Writes bytes to a std::vector that can be fetched. This is used to record the +// output of skia image encoding. +// +// TODO(crbug.com/991393): remove this when we no longer transcode images here. +class BufferWStream : public SkWStream { + public: + BufferWStream() = default; + ~BufferWStream() override = default; + + // Returns the output buffer by moving. + std::vector<unsigned char> GetBuffer() { return std::move(result_); } + + // SkWStream: + bool write(const void* buffer, size_t size) override { + const unsigned char* bytes = reinterpret_cast<const unsigned char*>(buffer); + result_.insert(result_.end(), bytes, bytes + size); + return true; + } + + size_t bytesWritten() const override { return result_.size(); } + + private: + std::vector<unsigned char> result_; +}; + +class TabStripUIHandler : public content::WebUIMessageHandler { + public: + explicit TabStripUIHandler(Profile* profile) + : profile_(profile), + thumbnail_tracker_(base::Bind(&TabStripUIHandler::HandleThumbnailUpdate, + base::Unretained(this))) {} + ~TabStripUIHandler() override = default; + + protected: + void RegisterMessages() override { + web_ui()->RegisterMessageCallback( + "addTrackedTab", + base::Bind(&TabStripUIHandler::AddTrackedTab, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "removeTrackedTab", base::Bind(&TabStripUIHandler::RemoveTrackedTab, + base::Unretained(this))); + } + + private: + void AddTrackedTab(const base::ListValue* args) { + AllowJavascript(); + + int tab_id = 0; + if (!args->GetInteger(0, &tab_id)) + return; + + content::WebContents* tab = nullptr; + if (!extensions::ExtensionTabUtil::GetTabById(tab_id, profile_, true, + &tab)) { + // ID didn't refer to a valid tab. + DVLOG(1) << "Invalid tab ID"; + return; + } + thumbnail_tracker_.WatchTab(tab); + } + + void RemoveTrackedTab(const base::ListValue* args) { + AllowJavascript(); + + int tab_id = 0; + if (!args->GetInteger(0, &tab_id)) + return; + // TODO(crbug.com/991393): un-watch tabs when we are done. + } + + // Callback passed to |thumbnail_tracker_|. Called when a tab's thumbnail + // changes, or when we start watching the tab. + void HandleThumbnailUpdate(content::WebContents* tab, gfx::ImageSkia image) { + const SkBitmap& bitmap = + image.GetRepresentation(web_ui()->GetDeviceScaleFactor()).GetBitmap(); + BufferWStream stream; + const bool encoding_succeeded = + SkEncodeImage(&stream, bitmap, SkEncodedImageFormat::kJPEG, 100); + DCHECK(encoding_succeeded); + const std::vector<unsigned char> image_data = stream.GetBuffer(); + + // Send base-64 encoded image to JS side. + // + // TODO(crbug.com/991393): streamline the process from tab capture to + // sending the image. Currently, a frame is captured, sent to + // ThumbnailImage, encoded to JPEG (w/ a copy), decoded to a raw bitmap + // (another copy), and sent to observers. Here, we then re-encode the image + // to a JPEG (another copy), encode to base64 (another copy), append the + // base64 header (another copy), and send it (another copy). This is 6 + // copies of essentially the same image, and it is de-encoded and re-encoded + // to the same format. We can reduce the number of copies and avoid the + // redundant encoding. + std::string encoded_image = + base::Base64Encode(base::as_bytes(base::make_span(image_data))); + encoded_image = "data:image/jpeg;base64," + encoded_image; + + const int tab_id = extensions::ExtensionTabUtil::GetTabId(tab); + FireWebUIListener("tab-thumbnail-updated", base::Value(tab_id), + base::Value(encoded_image)); + } + + Profile* profile_; + ThumbnailTracker thumbnail_tracker_; + + DISALLOW_COPY_AND_ASSIGN(TabStripUIHandler); +}; + +} // namespace + +TabStripUI::TabStripUI(content::WebUI* web_ui) + : content::WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + content::WebUIDataSource* html_source = + content::WebUIDataSource::Create(chrome::kChromeUITabStripHost); + + std::string generated_path = + "@out_folder@/gen/chrome/browser/resources/tab_strip/"; + + for (size_t i = 0; i < kTabStripResourcesSize; ++i) { + std::string path = kTabStripResources[i].name; + if (path.rfind(generated_path, 0) == 0) { + path = path.substr(generated_path.length()); + } + html_source->AddResourcePath(path, kTabStripResources[i].value); + } + + html_source->SetDefaultResource(IDR_TAB_STRIP_HTML); + + content::WebUIDataSource::Add(profile, html_source); + + content::URLDataSource::Add( + profile, std::make_unique<FaviconSource>( + profile, chrome::FaviconUrlFormat::kFavicon2)); + + web_ui->AddMessageHandler(std::make_unique<TabStripUIHandler>(profile)); +} + +TabStripUI::~TabStripUI() {} diff --git a/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.h b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.h new file mode 100644 index 00000000000..8e8b31d9ddf --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.h @@ -0,0 +1,25 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_TAB_STRIP_TAB_STRIP_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_TAB_STRIP_TAB_STRIP_UI_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h" +#include "content/public/browser/web_ui_controller.h" + +// The WebUI version of the tab strip in the browser. It is currently only +// supported on ChromeOS in tablet mode. +class TabStripUI : public content::WebUIController { + public: + explicit TabStripUI(content::WebUI* web_ui); + ~TabStripUI() override; + + private: + void HandleThumbnailUpdate(int extension_tab_id, gfx::ImageSkia image); + + DISALLOW_COPY_AND_ASSIGN(TabStripUI); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_TAB_STRIP_TAB_STRIP_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.cc b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.cc new file mode 100644 index 00000000000..6c74dd96578 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.cc @@ -0,0 +1,103 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h" + +#include <memory> +#include <utility> + +#include "base/scoped_observer.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/thumbnails/thumbnail_image.h" +#include "chrome/browser/ui/thumbnails/thumbnail_tab_helper.h" +#include "content/public/browser/web_contents_observer.h" + +// Handles requests for a given tab's thumbnail and watches for thumbnail +// updates for the lifetime of the tab. +class ThumbnailTracker::ContentsData : public content::WebContentsObserver, + public ThumbnailImage::Observer { + public: + ContentsData(ThumbnailTracker* parent, content::WebContents* contents) + : content::WebContentsObserver(contents), + parent_(parent), + observer_(this) { + thumbnail_ = parent_->thumbnail_getter_.Run(contents); + if (thumbnail_) + observer_.Add(thumbnail_.get()); + } + + void RequestThumbnail() { + if (thumbnail_) + thumbnail_->RequestThumbnailImage(); + } + + // content::WebContents: + void WebContentsDestroyed() override { + // We must un-observe each ThumbnailImage when the WebContents it came from + // closes. + if (thumbnail_) { + observer_.Remove(thumbnail_.get()); + thumbnail_.reset(); + } + + // Destroy ourself. After this call, |this| doesn't exist! + parent_->ContentsClosed(web_contents()); + } + + // ThumbnailImage::Observer: + void OnThumbnailImageAvailable(gfx::ImageSkia thumbnail_image) override { + parent_->ThumbnailUpdated(web_contents(), thumbnail_image); + } + + private: + ThumbnailTracker* parent_; + scoped_refptr<ThumbnailImage> thumbnail_; + ScopedObserver<ThumbnailImage, ContentsData> observer_; +}; + +ThumbnailTracker::ThumbnailTracker(ThumbnailUpdatedCallback callback) + : ThumbnailTracker(std::move(callback), + base::Bind(GetThumbnailFromTabHelper)) {} + +ThumbnailTracker::ThumbnailTracker(ThumbnailUpdatedCallback callback, + GetThumbnailCallback thumbnail_getter) + : thumbnail_getter_(std::move(thumbnail_getter)), + callback_(std::move(callback)) {} + +ThumbnailTracker::~ThumbnailTracker() = default; + +void ThumbnailTracker::WatchTab(content::WebContents* contents) { + auto data_it = contents_data_.find(contents); + if (data_it == contents_data_.end()) { + data_it = contents_data_.emplace_hint( + data_it, contents, std::make_unique<ContentsData>(this, contents)); + } + + data_it->second->RequestThumbnail(); +} + +void ThumbnailTracker::ThumbnailUpdated(content::WebContents* contents, + gfx::ImageSkia image) { + callback_.Run(contents, image); +} + +void ThumbnailTracker::ContentsClosed(content::WebContents* contents) { + contents_data_.erase(contents); +} + +// static +scoped_refptr<ThumbnailImage> ThumbnailTracker::GetThumbnailFromTabHelper( + content::WebContents* contents) { + ThumbnailTabHelper* thumbnail_helper = + ThumbnailTabHelper::FromWebContents(contents); + // Gracefully handle when ThumbnailTabHelper isn't available. + if (thumbnail_helper) { + auto thumbnail = thumbnail_helper->thumbnail(); + DCHECK(thumbnail); + return thumbnail; + } else { + DVLOG(1) << "ThumbnailTabHelper doesn't exist for tab"; + return nullptr; + } +} diff --git a/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h new file mode 100644 index 00000000000..2d64d3d8ecc --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h @@ -0,0 +1,64 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_TAB_STRIP_THUMBNAIL_TRACKER_H_ +#define CHROME_BROWSER_UI_WEBUI_TAB_STRIP_THUMBNAIL_TRACKER_H_ + +#include <memory> + +#include "base/containers/flat_map.h" +#include "base/memory/scoped_refptr.h" +#include "ui/gfx/image/image_skia.h" + +namespace content { +class WebContents; +} + +class ThumbnailImage; + +// Tracks the thumbnails of a set of WebContentses. This set is dynamically +// managed, and WebContents closure is handled gracefully. The user is notified +// of any thumbnail change via a callback specified on construction. +class ThumbnailTracker { + public: + // Should return the ThumbnailImage instance for a WebContents. + using GetThumbnailCallback = + base::RepeatingCallback<scoped_refptr<ThumbnailImage>( + content::WebContents*)>; + + // Handles a thumbnail update for a tab. + using ThumbnailUpdatedCallback = + base::RepeatingCallback<void(content::WebContents*, gfx::ImageSkia)>; + + explicit ThumbnailTracker(ThumbnailUpdatedCallback callback); + // Specifies how to get a ThumbnailImage for a WebContents. This is intended + // for tests. + ThumbnailTracker(ThumbnailUpdatedCallback callback, + GetThumbnailCallback thumbnail_getter); + + ~ThumbnailTracker(); + + // Registers a tab to receive thumbnail updates for. Also immediately requests + // the current thumbnail. + void WatchTab(content::WebContents* contents); + + private: + void ThumbnailUpdated(content::WebContents* contents, gfx::ImageSkia image); + void ContentsClosed(content::WebContents* contents); + + // The default |GetThumbnailCallback| implementation. + static scoped_refptr<ThumbnailImage> GetThumbnailFromTabHelper( + content::WebContents* contents); + + GetThumbnailCallback thumbnail_getter_; + ThumbnailUpdatedCallback callback_; + + // ContentsData tracks a particular WebContents. One is created for a tab on + // its first thumbnail request and exists until the contents is closed. + class ContentsData; + base::flat_map<content::WebContents*, std::unique_ptr<ContentsData>> + contents_data_; +}; + +#endif // CHROME_BROWSER_UI_WEBUI_TAB_STRIP_THUMBNAIL_TRACKER_H_ diff --git a/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker_unittest.cc b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker_unittest.cc new file mode 100644 index 00000000000..eac65cc2104 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker_unittest.cc @@ -0,0 +1,153 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h" + +#include <map> +#include <memory> +#include <utility> + +#include "base/run_loop.h" +#include "base/test/mock_callback.h" +#include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/browser/sessions/session_tab_helper.h" +#include "chrome/browser/ui/thumbnails/thumbnail_image.h" +#include "chrome/test/base/testing_profile.h" +#include "content/public/test/browser_task_environment.h" +#include "content/public/test/web_contents_tester.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/skia/include/core/SkBitmap.h" + +namespace { + +class TestThumbnailImageDelegate : public ThumbnailImage::Delegate { + public: + TestThumbnailImageDelegate() = default; + + ~TestThumbnailImageDelegate() override = default; + + void ThumbnailImageBeingObservedChanged(bool is_being_observed) override {} +}; + +class ThumbnailTrackerTest : public ::testing::Test, + public ThumbnailImage::Delegate { + protected: + ThumbnailTrackerTest() + : thumbnail_tracker_( + thumbnail_updated_callback_.Get(), + base::Bind(&ThumbnailTrackerTest::GetTestingThumbnail, + base::Unretained(this))) {} + + static SkBitmap CreateTestingBitmap() { + SkBitmap bitmap; + bitmap.allocN32Pixels(1, 1, true); + bitmap.eraseColor(SK_ColorBLACK); + bitmap.setImmutable(); + return bitmap; + } + + std::unique_ptr<content::WebContents> CreateWebContents() { + auto contents = + content::WebContentsTester::CreateTestWebContents(&profile_, nullptr); + SessionTabHelper::CreateForWebContents(contents.get()); + return contents; + } + + scoped_refptr<ThumbnailImage> GetTestingThumbnail( + content::WebContents* contents) { + return tab_thumbnails_[contents].thumbnail_image; + } + + // ThumbnailImage::Delegate: + void ThumbnailImageBeingObservedChanged(bool is_being_observed) override {} + + content::BrowserTaskEnvironment task_environment_; + TestingProfile profile_; + + base::MockCallback<ThumbnailTracker::ThumbnailUpdatedCallback> + thumbnail_updated_callback_; + + struct ThumbnailData { + ThumbnailData() + : thumbnail_image(base::MakeRefCounted<ThumbnailImage>(&delegate)) {} + + TestThumbnailImageDelegate delegate; + scoped_refptr<ThumbnailImage> thumbnail_image; + }; + std::map<content::WebContents*, ThumbnailData> tab_thumbnails_; + + ThumbnailTracker thumbnail_tracker_; +}; + +} // namespace + +using ::testing::_; + +TEST_F(ThumbnailTrackerTest, WatchTabGetsCurrentThumbnail) { + auto contents = CreateWebContents(); + auto thumbnail = GetTestingThumbnail(contents.get()); + + // Set the thumbnail image and wait for it to be stored. + base::RunLoop encode_loop; + thumbnail->set_async_operation_finished_callback_for_testing( + encode_loop.QuitClosure()); + thumbnail->AssignSkBitmap(CreateTestingBitmap()); + encode_loop.Run(); + + // Verify that WatchTab() gets the current image, waiting for the decoding to + // happen. + EXPECT_CALL(thumbnail_updated_callback_, Run(contents.get(), _)).Times(1); + base::RunLoop notify_loop; + thumbnail->set_async_operation_finished_callback_for_testing( + notify_loop.QuitClosure()); + thumbnail_tracker_.WatchTab(contents.get()); + notify_loop.Run(); +} + +TEST_F(ThumbnailTrackerTest, PropagatesThumbnailUpdate) { + auto contents1 = CreateWebContents(); + auto thumbnail1 = GetTestingThumbnail(contents1.get()); + auto contents2 = CreateWebContents(); + auto thumbnail2 = GetTestingThumbnail(contents2.get()); + + // Since no thumbnail image exists yet, this shouldn't notify our callback. + thumbnail_tracker_.WatchTab(contents1.get()); + thumbnail_tracker_.WatchTab(contents2.get()); + + { + ::testing::InSequence seq; + EXPECT_CALL(thumbnail_updated_callback_, Run(contents1.get(), _)).Times(1); + EXPECT_CALL(thumbnail_updated_callback_, Run(contents2.get(), _)).Times(1); + } + + base::RunLoop first_update_loop; + thumbnail1->set_async_operation_finished_callback_for_testing( + first_update_loop.QuitClosure()); + thumbnail1->AssignSkBitmap(CreateTestingBitmap()); + first_update_loop.Run(); + + base::RunLoop second_update_loop; + thumbnail2->set_async_operation_finished_callback_for_testing( + second_update_loop.QuitClosure()); + thumbnail2->AssignSkBitmap(CreateTestingBitmap()); + second_update_loop.Run(); +} + +TEST_F(ThumbnailTrackerTest, StopsObservingOnTabClose) { + auto contents = CreateWebContents(); + auto thumbnail = GetTestingThumbnail(contents.get()); + thumbnail_tracker_.WatchTab(contents.get()); + + // |thumbnail| is still valid, but |thumbnail_tracker_| should stop watching + // it when |contents| goes away. + EXPECT_CALL(thumbnail_updated_callback_, Run(_, _)).Times(0); + contents.reset(); + + base::RunLoop update_loop; + thumbnail->set_async_operation_finished_callback_for_testing( + update_loop.QuitClosure()); + thumbnail->AssignSkBitmap(CreateTestingBitmap()); + update_loop.Run(); +} diff --git a/chromium/chrome/browser/ui/webui/test_data_source.cc b/chromium/chrome/browser/ui/webui/test_data_source.cc index b857b4fd032..3c2b5ac0d41 100644 --- a/chromium/chrome/browser/ui/webui/test_data_source.cc +++ b/chromium/chrome/browser/ui/webui/test_data_source.cc @@ -31,10 +31,11 @@ std::string TestDataSource::GetSource() { void TestDataSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&TestDataSource::ReadFile, base::Unretained(this), path, callback)); } @@ -71,11 +72,22 @@ GURL TestDataSource::GetURLForPath(const std::string& path) { void TestDataSource::ReadFile( const std::string& path, const content::URLDataSource::GotDataCallback& callback) { - if (test_data_.empty()) { - CHECK(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_)); - CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &source_root_)); + if (src_root_.empty()) { + base::FilePath test_data; + CHECK(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data)); + src_root_ = test_data.Append(FILE_PATH_LITERAL("webui")); } - base::FilePath root = test_data_.Append(FILE_PATH_LITERAL("webui")); + + if (gen_root_.empty()) { + std::string gen_path = "gen/chrome/test/data/webui/"; +#if defined(OS_WIN) + base::ReplaceChars(gen_path, "//", "\\", &gen_path); +#endif + base::FilePath exe_dir; + base::PathService::Get(base::DIR_EXE, &exe_dir); + gen_root_ = exe_dir.AppendASCII(gen_path); + } + std::string content; GURL url = GetURLForPath(path); @@ -83,18 +95,32 @@ void TestDataSource::ReadFile( if (base::StartsWith(url.query(), kModuleQuery, base::CompareCase::INSENSITIVE_ASCII)) { std::string js_path = url.query().substr(strlen(kModuleQuery)); + base::FilePath file_path = - root.Append(base::FilePath::FromUTF8Unsafe(js_path)); + src_root_.Append(base::FilePath::FromUTF8Unsafe(js_path)); // Do some basic validation of the JS file path provided in the query. CHECK_EQ(file_path.Extension(), FILE_PATH_LITERAL(".js")); - CHECK(base::PathExists(file_path)) + + base::FilePath file_path2 = + gen_root_.Append(base::FilePath::FromUTF8Unsafe(js_path)); + CHECK(base::PathExists(file_path) || base::PathExists(file_path2)) << url.spec() << "=" << file_path.value(); content = "<script type=\"module\" src=\"" + js_path + "\"></script>"; } else { + // Try the |src_root_| folder first. base::FilePath file_path = - root.Append(base::FilePath::FromUTF8Unsafe(path)); - CHECK(base::ReadFileToString(file_path, &content)) - << url.spec() << "=" << file_path.value(); + src_root_.Append(base::FilePath::FromUTF8Unsafe(path)); + if (base::PathExists(file_path)) { + CHECK(base::ReadFileToString(file_path, &content)) + << url.spec() << "=" << file_path.value(); + } else { + // Then try the |gen_root_| folder, covering cases where the test file is + // generated at build time. + base::FilePath file_path = + gen_root_.Append(base::FilePath::FromUTF8Unsafe(path)); + CHECK(base::ReadFileToString(file_path, &content)) + << url.spec() << "=" << file_path.value(); + } } scoped_refptr<base::RefCountedString> response = diff --git a/chromium/chrome/browser/ui/webui/test_data_source.h b/chromium/chrome/browser/ui/webui/test_data_source.h index 680979c02c1..86816587eb2 100644 --- a/chromium/chrome/browser/ui/webui/test_data_source.h +++ b/chromium/chrome/browser/ui/webui/test_data_source.h @@ -21,7 +21,7 @@ class TestDataSource : public content::URLDataSource { private: void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; @@ -39,8 +39,8 @@ class TestDataSource : public content::URLDataSource { void ReadFile(const std::string& path, const content::URLDataSource::GotDataCallback& callback); - base::FilePath test_data_; - base::FilePath source_root_; + base::FilePath src_root_; + base::FilePath gen_root_; DISALLOW_COPY_AND_ASSIGN(TestDataSource); }; diff --git a/chromium/chrome/browser/ui/webui/theme_source.cc b/chromium/chrome/browser/ui/webui/theme_source.cc index 673b625f6e0..cc006a1e38e 100644 --- a/chromium/chrome/browser/ui/webui/theme_source.cc +++ b/chromium/chrome/browser/ui/webui/theme_source.cc @@ -80,7 +80,7 @@ std::string ThemeSource::GetSource() { void ThemeSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { // Default scale factor if not specified. float scale = 1.0f; @@ -233,7 +233,7 @@ void ThemeSource::SendThemeImage( DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // Fetching image data in ResourceBundle should happen on the UI thread. See // crbug.com/449277 - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&ProcessResourceOnUiThread, resource_id, scale, data), base::BindOnce(callback, data)); diff --git a/chromium/chrome/browser/ui/webui/theme_source.h b/chromium/chrome/browser/ui/webui/theme_source.h index aa323d6efbc..321ea0b8fbd 100644 --- a/chromium/chrome/browser/ui/webui/theme_source.h +++ b/chromium/chrome/browser/ui/webui/theme_source.h @@ -24,7 +24,7 @@ class ThemeSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; scoped_refptr<base::SingleThreadTaskRunner> TaskRunnerForRequestPath( diff --git a/chromium/chrome/browser/ui/webui/theme_source_unittest.cc b/chromium/chrome/browser/ui/webui/theme_source_unittest.cc index abbf029bf54..55ee176f9b1 100644 --- a/chromium/chrome/browser/ui/webui/theme_source_unittest.cc +++ b/chromium/chrome/browser/ui/webui/theme_source_unittest.cc @@ -12,7 +12,7 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/theme_resources.h" #include "chrome/test/base/testing_profile.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" class WebUISourcesTest : public testing::Test { @@ -24,18 +24,16 @@ class WebUISourcesTest : public testing::Test { size_t result_data_size() const { return result_data_size_; } void StartDataRequest(const std::string& source) { - theme_source()->StartDataRequest( - source, - content::ResourceRequestInfo::WebContentsGetter(), - callback_); + theme_source()->StartDataRequest(source, content::WebContents::Getter(), + callback_); } size_t result_data_size_; private: void SetUp() override { - profile_.reset(new TestingProfile()); - theme_source_.reset(new ThemeSource(profile_.get())); + profile_ = std::make_unique<TestingProfile>(); + theme_source_ = std::make_unique<ThemeSource>(profile_.get()); callback_ = base::Bind(&WebUISourcesTest::SendResponse, base::Unretained(this)); } @@ -51,7 +49,7 @@ class WebUISourcesTest : public testing::Test { content::URLDataSource::GotDataCallback callback_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<TestingProfile> profile_; std::unique_ptr<ThemeSource> theme_source_; diff --git a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_ui.cc b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_ui.cc index dfd9efd9f8f..42d192b77dd 100644 --- a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_ui.cc @@ -29,7 +29,7 @@ content::WebUIDataSource* CreateTranslateInternalsHTMLSource() { content::WebUIDataSource::Create(chrome::kChromeUITranslateInternalsHost); source->SetDefaultResource(IDR_TRANSLATE_INTERNALS_HTML); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("translate_internals.js", IDR_TRANSLATE_INTERNALS_JS); base::DictionaryValue langs; diff --git a/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn index 5229f5ba6f3..d193360fcec 100644 --- a/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn @@ -13,7 +13,4 @@ mojom("mojo_bindings") { "//services/device/public/mojom:usb", "//services/device/public/mojom:usb_test", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals.mojom b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals.mojom index 88b50f749a2..b980f6586de 100644 --- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals.mojom +++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals.mojom @@ -8,9 +8,11 @@ import "services/device/public/mojom/usb_manager.mojom"; import "services/device/public/mojom/usb_manager_test.mojom"; interface UsbInternalsPageHandler { - // Bind the UsbDeviceManager interface to get all devices that connected. - BindUsbDeviceManagerInterface(device.mojom.UsbDeviceManager& request); + // Bind the UsbDeviceManager receiver to get all devices that connected. + BindUsbDeviceManagerInterface( + pending_receiver<device.mojom.UsbDeviceManager> receiver); // Simulate the connection of a new device with the given properties. - BindTestInterface(device.mojom.UsbDeviceManagerTest& request); + BindTestInterface( + pending_receiver<device.mojom.UsbDeviceManagerTest> receiver); }; diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc index c5989ed4357..1b4796bba02 100644 --- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc @@ -11,21 +11,21 @@ #include "services/service_manager/public/cpp/connector.h" UsbInternalsPageHandler::UsbInternalsPageHandler( - mojom::UsbInternalsPageHandlerRequest request) - : binding_(this, std::move(request)) {} + mojo::PendingReceiver<mojom::UsbInternalsPageHandler> receiver) + : receiver_(this, std::move(receiver)) {} UsbInternalsPageHandler::~UsbInternalsPageHandler() {} void UsbInternalsPageHandler::BindTestInterface( - device::mojom::UsbDeviceManagerTestRequest request) { + mojo::PendingReceiver<device::mojom::UsbDeviceManagerTest> receiver) { // Forward the request to the DeviceService. - content::GetSystemConnector()->BindInterface(device::mojom::kServiceName, - std::move(request)); + content::GetSystemConnector()->Connect(device::mojom::kServiceName, + std::move(receiver)); } void UsbInternalsPageHandler::BindUsbDeviceManagerInterface( - device::mojom::UsbDeviceManagerRequest request) { + mojo::PendingReceiver<device::mojom::UsbDeviceManager> receiver) { // Forward the request to the DeviceService. - content::GetSystemConnector()->BindInterface(device::mojom::kServiceName, - std::move(request)); + content::GetSystemConnector()->Connect(device::mojom::kServiceName, + std::move(receiver)); } 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 5530f76bc98..01f967c9ce1 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 @@ -7,24 +7,26 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/usb_internals/usb_internals.mojom.h" -#include "mojo/public/cpp/bindings/binding.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/receiver.h" #include "services/device/public/mojom/usb_manager.mojom.h" #include "services/device/public/mojom/usb_manager_test.mojom.h" class UsbInternalsPageHandler : public mojom::UsbInternalsPageHandler { public: explicit UsbInternalsPageHandler( - mojom::UsbInternalsPageHandlerRequest request); + mojo::PendingReceiver<mojom::UsbInternalsPageHandler> receiver); ~UsbInternalsPageHandler() override; void BindUsbDeviceManagerInterface( - device::mojom::UsbDeviceManagerRequest request) override; + mojo::PendingReceiver<device::mojom::UsbDeviceManager> receiver) override; void BindTestInterface( - device::mojom::UsbDeviceManagerTestRequest request) override; + mojo::PendingReceiver<device::mojom::UsbDeviceManagerTest> receiver) + override; private: - mojo::Binding<mojom::UsbInternalsPageHandler> binding_; + mojo::Receiver<mojom::UsbInternalsPageHandler> receiver_; DISALLOW_COPY_AND_ASSIGN(UsbInternalsPageHandler); }; 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 abd87cd6619..7b8d5847b99 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 @@ -45,6 +45,7 @@ UsbInternalsUI::UsbInternalsUI(content::WebUI* web_ui) UsbInternalsUI::~UsbInternalsUI() {} void UsbInternalsUI::BindUsbInternalsPageHandler( - mojom::UsbInternalsPageHandlerRequest request) { - page_handler_.reset(new UsbInternalsPageHandler(std::move(request))); + mojo::PendingReceiver<mojom::UsbInternalsPageHandler> receiver) { + page_handler_ = + std::make_unique<UsbInternalsPageHandler>(std::move(receiver)); } 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 0f4fc201756..249d376248e 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 @@ -7,6 +7,7 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/usb_internals/usb_internals.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "ui/webui/mojo_web_ui_controller.h" class UsbInternalsPageHandler; @@ -19,7 +20,7 @@ class UsbInternalsUI : public ui::MojoWebUIController { private: void BindUsbInternalsPageHandler( - mojom::UsbInternalsPageHandlerRequest request); + mojo::PendingReceiver<mojom::UsbInternalsPageHandler> receiver); 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 b62cff1dceb..8589c0479e3 100644 --- a/chromium/chrome/browser/ui/webui/version_handler.cc +++ b/chromium/chrome/browser/ui/webui/version_handler.cc @@ -26,6 +26,7 @@ #include "content/public/browser/plugin_service.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_message_handler.h" #include "content/public/common/content_constants.h" #include "ppapi/buildflags/buildflags.h" #include "ui/base/l10n/l10n_util.h" @@ -66,53 +67,103 @@ void VersionHandler::RegisterMessages() { version_ui::kRequestVersionInfo, base::BindRepeating(&VersionHandler::HandleRequestVersionInfo, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + version_ui::kRequestVariationInfo, + base::BindRepeating(&VersionHandler::HandleRequestVariationInfo, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + version_ui::kRequestPluginInfo, + base::BindRepeating(&VersionHandler::HandleRequestPluginInfo, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + version_ui::kRequestPathInfo, + base::BindRepeating(&VersionHandler::HandleRequestPathInfo, + base::Unretained(this))); } void VersionHandler::HandleRequestVersionInfo(const base::ListValue* args) { + // This method is overridden by platform-specific handlers which may still + // use |CallJavascriptFunction|. Main version info is returned by promise + // using handlers below. + // TODO(orinj): To fully eliminate chrome.send usage in JS, derived classes + // could be made to work more like this base class, using + // |ResolveJavascriptCallback| instead of |CallJavascriptFunction|. + AllowJavascript(); +} + +void VersionHandler::HandleRequestVariationInfo(const base::ListValue* args) { + AllowJavascript(); + + std::string callback_id; + bool include_variations_cmd; + CHECK_EQ(2U, args->GetSize()); + CHECK(args->GetString(0, &callback_id)); + CHECK(args->GetBoolean(1, &include_variations_cmd)); + + base::Value response(base::Value::Type::DICTIONARY); + response.SetKey(version_ui::kKeyVariationsList, + std::move(*version_ui::GetVariationsList())); + if (include_variations_cmd) { + response.SetKey(version_ui::kKeyVariationsCmd, + version_ui::GetVariationsCommandLineAsValue()); + } + ResolveJavascriptCallback(base::Value(callback_id), response); +} + +void VersionHandler::HandleRequestPluginInfo(const base::ListValue* args) { AllowJavascript(); + + std::string callback_id; + CHECK_EQ(1U, args->GetSize()); + CHECK(args->GetString(0, &callback_id)); + #if BUILDFLAG(ENABLE_PLUGINS) // The Flash version information is needed in the response, so make sure // the plugins are loaded. content::PluginService::GetInstance()->GetPlugins( - base::Bind(&VersionHandler::OnGotPlugins, - weak_ptr_factory_.GetWeakPtr())); + base::Bind(&VersionHandler::OnGotPlugins, weak_ptr_factory_.GetWeakPtr(), + callback_id)); +#else + RejectJavascriptCallback(base::Value(callback_id), base::Value()); #endif +} + +void VersionHandler::HandleRequestPathInfo(const base::ListValue* args) { + AllowJavascript(); + + std::string callback_id; + CHECK_EQ(1U, args->GetSize()); + CHECK(args->GetString(0, &callback_id)); // Grab the executable path on the FILE thread. It is returned in // OnGotFilePaths. base::string16* exec_path_buffer = new base::string16; base::string16* profile_path_buffer = new base::string16; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::BindOnce(&GetFilePaths, Profile::FromWebUI(web_ui())->GetPath(), base::Unretained(exec_path_buffer), base::Unretained(profile_path_buffer)), - base::BindOnce( - &VersionHandler::OnGotFilePaths, weak_ptr_factory_.GetWeakPtr(), - base::Owned(exec_path_buffer), base::Owned(profile_path_buffer))); - - // Respond with the variations info immediately. - CallJavascriptFunction(version_ui::kReturnVariationInfo, - *version_ui::GetVariationsList()); - GURL current_url = web_ui()->GetWebContents()->GetVisibleURL(); - if (current_url.query().find(version_ui::kVariationsShowCmdQuery) != - std::string::npos) { - CallJavascriptFunction(version_ui::kReturnVariationCmd, - version_ui::GetVariationsCommandLineAsValue()); - } + base::BindOnce(&VersionHandler::OnGotFilePaths, + weak_ptr_factory_.GetWeakPtr(), callback_id, + base::Owned(exec_path_buffer), + base::Owned(profile_path_buffer))); } -void VersionHandler::OnGotFilePaths(base::string16* executable_path_data, +void VersionHandler::OnGotFilePaths(std::string callback_id, + base::string16* executable_path_data, base::string16* profile_path_data) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - base::Value exec_path(*executable_path_data); - base::Value profile_path(*profile_path_data); - CallJavascriptFunction(version_ui::kReturnFilePaths, exec_path, profile_path); + base::Value response(base::Value::Type::DICTIONARY); + response.SetKey(version_ui::kKeyExecPath, base::Value(*executable_path_data)); + response.SetKey(version_ui::kKeyProfilePath, base::Value(*profile_path_data)); + ResolveJavascriptCallback(base::Value(callback_id), response); } #if BUILDFLAG(ENABLE_PLUGINS) void VersionHandler::OnGotPlugins( + std::string callback_id, const std::vector<content::WebPluginInfo>& plugins) { // Obtain the version of the first enabled Flash plugin. std::vector<content::WebPluginInfo> info_array; @@ -132,9 +183,7 @@ void VersionHandler::OnGotPlugins( } } } - - base::Value arg(flash_version_and_path); - - CallJavascriptFunction(version_ui::kReturnFlashVersion, arg); + ResolveJavascriptCallback(base::Value(callback_id), + base::Value(flash_version_and_path)); } #endif // BUILDFLAG(ENABLE_PLUGINS) diff --git a/chromium/chrome/browser/ui/webui/version_handler.h b/chromium/chrome/browser/ui/webui/version_handler.h index e4c27a5308e..47e66e7a029 100644 --- a/chromium/chrome/browser/ui/webui/version_handler.h +++ b/chromium/chrome/browser/ui/webui/version_handler.h @@ -22,20 +22,36 @@ class VersionHandler : public content::WebUIMessageHandler { // content::WebUIMessageHandler implementation. void RegisterMessages() override; - // Callback for the "requestVersionInfo" message. This asynchronously requests - // the flash version and eventually returns it to the front end along with the - // list of variations using OnGotPlugins. + // Callback for the "requestVersionInfo" message sent by |chrome.send| in JS. + // This is still supported for platform-specific asynchronous calls (see + // derived classes) but the main version information is now retrieved with + // below messages using |cr.sendWithPromise|. virtual void HandleRequestVersionInfo(const base::ListValue* args); + // Callback for the "requestVariationInfo" message. This resolves immediately + // with variations list as well as command variations if requested. + virtual void HandleRequestVariationInfo(const base::ListValue* args); + + // Callback for the "requestPluginInfo" message. This asynchronously requests + // the flash version and eventually returns it to the front end along with the + // list of variations using |OnGotPlugins|. + virtual void HandleRequestPluginInfo(const base::ListValue* args); + + // Callback for the "requestPathInfo" message. This resolves asynchronously + // with |OnGotFilePaths|. + virtual void HandleRequestPathInfo(const base::ListValue* args); + private: // Callback which handles returning the executable and profile paths to the // front end. - void OnGotFilePaths(base::string16* executable_path_data, + void OnGotFilePaths(std::string callback_id, + base::string16* executable_path_data, base::string16* profile_path_data); // Callback for GetPlugins which responds to the page with the Flash version. // This also initiates the OS Version load on ChromeOS. - void OnGotPlugins(const std::vector<content::WebPluginInfo>& plugins); + void OnGotPlugins(std::string callback_id, + const std::vector<content::WebPluginInfo>& plugins); // Factory for the creating refs in callbacks. base::WeakPtrFactory<VersionHandler> weak_ptr_factory_{this}; diff --git a/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc index 07917010b9f..a2ed0a779c2 100644 --- a/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc +++ b/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc @@ -10,32 +10,34 @@ #include "components/version_info/channel.h" #include "content/public/browser/web_ui.h" -VersionHandlerChromeOS::VersionHandlerChromeOS() : weak_factory_(this) {} +VersionHandlerChromeOS::VersionHandlerChromeOS() {} VersionHandlerChromeOS::~VersionHandlerChromeOS() {} void VersionHandlerChromeOS::HandleRequestVersionInfo( const base::ListValue* args) { + VersionHandler::HandleRequestVersionInfo(args); + // Start the asynchronous load of the versions. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&chromeos::version_loader::GetVersion, chromeos::version_loader::VERSION_FULL), base::Bind(&VersionHandlerChromeOS::OnVersion, weak_factory_.GetWeakPtr())); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&chromeos::version_loader::GetFirmware), base::Bind(&VersionHandlerChromeOS::OnOSFirmware, weak_factory_.GetWeakPtr())); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&chromeos::version_loader::GetARCVersion), base::Bind(&VersionHandlerChromeOS::OnARCVersion, weak_factory_.GetWeakPtr())); - - // Parent class takes care of the rest. - VersionHandler::HandleRequestVersionInfo(args); } void VersionHandlerChromeOS::OnVersion(const std::string& version) { diff --git a/chromium/chrome/browser/ui/webui/version_handler_chromeos.h b/chromium/chrome/browser/ui/webui/version_handler_chromeos.h index e36377fc778..0bc597a3270 100644 --- a/chromium/chrome/browser/ui/webui/version_handler_chromeos.h +++ b/chromium/chrome/browser/ui/webui/version_handler_chromeos.h @@ -28,7 +28,7 @@ class VersionHandlerChromeOS : public VersionHandler { void OnARCVersion(const std::string& version); private: - base::WeakPtrFactory<VersionHandlerChromeOS> weak_factory_; + base::WeakPtrFactory<VersionHandlerChromeOS> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VersionHandlerChromeOS); }; diff --git a/chromium/chrome/browser/ui/webui/version_handler_win.cc b/chromium/chrome/browser/ui/webui/version_handler_win.cc index 3540aa13b9b..315ce149694 100644 --- a/chromium/chrome/browser/ui/webui/version_handler_win.cc +++ b/chromium/chrome/browser/ui/webui/version_handler_win.cc @@ -11,21 +11,21 @@ #include "chrome/browser/ui/webui/version_util_win.h" #include "content/public/browser/web_ui.h" -VersionHandlerWindows::VersionHandlerWindows() : weak_factory_(this) {} +VersionHandlerWindows::VersionHandlerWindows() {} VersionHandlerWindows::~VersionHandlerWindows() {} void VersionHandlerWindows::HandleRequestVersionInfo( const base::ListValue* args) { + VersionHandler::HandleRequestVersionInfo(args); + // Start the asynchronous load of the versions. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&version_utils::win::GetFullWindowsVersion), base::BindOnce(&VersionHandlerWindows::OnVersion, weak_factory_.GetWeakPtr())); - - // Parent class takes care of the rest. - VersionHandler::HandleRequestVersionInfo(args); } void VersionHandlerWindows::OnVersion(const std::string& version) { diff --git a/chromium/chrome/browser/ui/webui/version_handler_win.h b/chromium/chrome/browser/ui/webui/version_handler_win.h index 83a41ecce31..2c424dcc2f2 100644 --- a/chromium/chrome/browser/ui/webui/version_handler_win.h +++ b/chromium/chrome/browser/ui/webui/version_handler_win.h @@ -27,7 +27,7 @@ class VersionHandlerWindows : public VersionHandler { static std::string GetFullWindowsVersionForTesting(); private: - base::WeakPtrFactory<VersionHandlerWindows> weak_factory_; + base::WeakPtrFactory<VersionHandlerWindows> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VersionHandlerWindows); }; diff --git a/chromium/chrome/browser/ui/webui/version_ui.cc b/chromium/chrome/browser/ui/webui/version_ui.cc index e0759744e1f..aab730053ec 100644 --- a/chromium/chrome/browser/ui/webui/version_ui.cc +++ b/chromium/chrome/browser/ui/webui/version_ui.cc @@ -83,7 +83,7 @@ WebUIDataSource* CreateVersionUIDataSource() { VersionUI::AddVersionDetailStrings(html_source); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->AddResourcePath(version_ui::kVersionJS, IDR_VERSION_UI_JS); html_source->AddResourcePath(version_ui::kAboutVersionCSS, IDR_VERSION_UI_CSS); diff --git a/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.cc b/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.cc new file mode 100644 index 00000000000..396b82eaa37 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.cc @@ -0,0 +1,27 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/web_footer_experiment_ui.h" + +#include "base/logging.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/managed_ui_handler.h" +#include "chrome/browser/ui/webui/theme_source.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "content/public/browser/web_ui_data_source.h" + +WebFooterExperimentUI::WebFooterExperimentUI(content::WebUI* web_ui) + : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + + content::WebUIDataSource* source = content::WebUIDataSource::Create( + chrome::kChromeUIWebFooterExperimentHost); + source->AddResourcePath("index.html", IDR_WEB_FOOTER_EXPERIMENT_HTML); + source->SetDefaultResource(IDR_WEB_FOOTER_EXPERIMENT_HTML); + ManagedUIHandler::Initialize(web_ui, source); + content::WebUIDataSource::Add(profile, source); +} + +WebFooterExperimentUI::~WebFooterExperimentUI() = default; diff --git a/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.h b/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.h new file mode 100644 index 00000000000..7dda354b888 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.h @@ -0,0 +1,20 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_WEB_FOOTER_EXPERIMENT_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_WEB_FOOTER_EXPERIMENT_UI_H_ + +#include "base/macros.h" +#include "content/public/browser/web_ui_controller.h" + +class WebFooterExperimentUI : public content::WebUIController { + public: + explicit WebFooterExperimentUI(content::WebUI* web_ui); + ~WebFooterExperimentUI() override; + + private: + DISALLOW_COPY_AND_ASSIGN(WebFooterExperimentUI); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_WEB_FOOTER_EXPERIMENT_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/webapks_ui.cc b/chromium/chrome/browser/ui/webui/webapks_ui.cc index 953c000a908..9e45e8dc7d6 100644 --- a/chromium/chrome/browser/ui/webui/webapks_ui.cc +++ b/chromium/chrome/browser/ui/webui/webapks_ui.cc @@ -21,7 +21,7 @@ namespace { WebUIDataSource* CreateWebApksUIDataSource() { WebUIDataSource* html_source = WebUIDataSource::Create(chrome::kChromeUIWebApksHost); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->AddResourcePath("webapks.js", IDR_WEBAPKS_UI_JS); html_source->AddResourcePath("about_webapks.css", IDR_WEBAPKS_UI_CSS); html_source->SetDefaultResource(IDR_WEBAPKS_UI_HTML); diff --git a/chromium/chrome/browser/ui/webui/webui_load_timer.cc b/chromium/chrome/browser/ui/webui/webui_load_timer.cc index f865c2131df..9bfadd5fb83 100644 --- a/chromium/chrome/browser/ui/webui/webui_load_timer.cc +++ b/chromium/chrome/browser/ui/webui/webui_load_timer.cc @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/webui_load_timer.h" #include "base/metrics/histogram.h" +#include "base/timer/elapsed_timer.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" diff --git a/chromium/chrome/browser/ui/webui/webui_load_timer.h b/chromium/chrome/browser/ui/webui/webui_load_timer.h index 0fee6dfb048..5474b646af3 100644 --- a/chromium/chrome/browser/ui/webui/webui_load_timer.h +++ b/chromium/chrome/browser/ui/webui/webui_load_timer.h @@ -9,9 +9,12 @@ #include <string> #include "base/macros.h" -#include "base/timer/elapsed_timer.h" #include "content/public/browser/web_contents_observer.h" +namespace base { +class ElapsedTimer; +} + // Measures and reports page load times for WebUI. class WebuiLoadTimer : public content::WebContentsObserver { public: diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/DEPS b/chromium/chrome/browser/ui/webui/welcome/DEPS index cbcb3569274..cbcb3569274 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/DEPS +++ b/chromium/chrome/browser/ui/webui/welcome/DEPS diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.cc b/chromium/chrome/browser/ui/webui/welcome/bookmark_handler.cc index e09ec04fbc0..74dea3937c1 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/bookmark_handler.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/welcome/nux/bookmark_handler.h" +#include "chrome/browser/ui/webui/welcome/bookmark_handler.h" #include "base/bind.h" #include "chrome/grit/browser_resources.h" @@ -10,7 +10,7 @@ #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui_data_source.h" -namespace nux { +namespace welcome { BookmarkHandler::BookmarkHandler(PrefService* prefs) : prefs_(prefs) {} @@ -46,4 +46,4 @@ void BookmarkHandler::HandleIsBookmarkBarShown(const base::ListValue* args) { base::Value(prefs_->GetBoolean(bookmarks::prefs::kShowBookmarkBar))); } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.h b/chromium/chrome/browser/ui/webui/welcome/bookmark_handler.h index b9240c93816..c3cf53d941e 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/bookmark_handler.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_WELCOME_NUX_BOOKMARK_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_HANDLER_H_ #include "base/macros.h" #include "base/values.h" @@ -11,7 +11,7 @@ class PrefService; -namespace nux { +namespace welcome { class BookmarkHandler : public content::WebUIMessageHandler { public: @@ -32,6 +32,6 @@ class BookmarkHandler : public content::WebUIMessageHandler { DISALLOW_COPY_AND_ASSIGN(BookmarkHandler); }; -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.cc b/chromium/chrome/browser/ui/webui/welcome/bookmark_item.cc index ba59a856786..fc61b6b3567 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.cc +++ b/chromium/chrome/browser/ui/webui/welcome/bookmark_item.cc @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" +#include "chrome/browser/ui/webui/welcome/bookmark_item.h" #include "base/strings/string16.h" #include "base/values.h" -namespace nux { +namespace welcome { base::ListValue BookmarkItemsToListValue(const BookmarkItem items[], size_t count) { @@ -41,4 +41,4 @@ base::ListValue BookmarkItemsToListValue( return list_value; } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.h b/chromium/chrome/browser/ui/webui/welcome/bookmark_item.h index 838735a9a8a..fbea6f52a13 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.h +++ b/chromium/chrome/browser/ui/webui/welcome/bookmark_item.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_WELCOME_NUX_BOOKMARK_ITEM_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_ITEM_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_ITEM_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_ITEM_H_ #include <stddef.h> #include <string> @@ -13,7 +13,7 @@ namespace base { class ListValue; } // namespace base -namespace nux { +namespace welcome { struct BookmarkItem { const int id; @@ -29,6 +29,6 @@ base::ListValue BookmarkItemsToListValue(const BookmarkItem items[], base::ListValue BookmarkItemsToListValue( const std::vector<BookmarkItem>& items); -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_ITEM_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_ITEM_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.cc b/chromium/chrome/browser/ui/webui/welcome/google_apps_handler.cc index b76a8185d3d..4cedf809283 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/google_apps_handler.cc @@ -2,19 +2,20 @@ // 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/welcome/nux/google_apps_handler.h" +#include "chrome/browser/ui/webui/welcome/google_apps_handler.h" #include "base/bind.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" +#include "build/branding_buildflags.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" -#include "chrome/browser/ui/webui/welcome/nux_helper.h" +#include "chrome/browser/ui/webui/welcome/bookmark_item.h" +#include "chrome/browser/ui/webui/welcome/helpers.h" #include "chrome/grit/chrome_unscaled_resources.h" #include "chrome/grit/generated_resources.h" -#include "chrome/grit/onboarding_welcome_resources.h" +#include "chrome/grit/welcome_resources.h" #include "components/favicon/core/favicon_service.h" #include "components/grit/components_resources.h" #include "components/grit/components_scaled_resources.h" @@ -24,7 +25,7 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" -namespace nux { +namespace welcome { // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. @@ -45,50 +46,48 @@ const char* kGoogleAppsInteractionHistogram = constexpr const int kGoogleAppIconSize = 48; // Pixels. GoogleAppsHandler::GoogleAppsHandler() { -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) // Do not translate icon name as it is not human visible and needs to // match CSS. BookmarkItem gmail = { static_cast<int>(GoogleApps::kGmail), - l10n_util::GetStringUTF8(IDS_ONBOARDING_WELCOME_NUX_GOOGLE_GMAIL), - "gmail", "https://accounts.google.com/b/0/AddMailService", - IDS_ONBOARDING_WELCOME_GMAIL}; + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_GMAIL), "gmail", + "https://accounts.google.com/b/0/AddMailService", IDS_WELCOME_GMAIL}; if (IsAppVariationEnabled()) { - google_apps_.push_back( - {static_cast<int>(GoogleApps::kSearch), - l10n_util::GetStringUTF8(IDS_ONBOARDING_WELCOME_NUX_GOOGLE_SEARCH), - "search", "https://google.com", IDS_ONBOARDING_WELCOME_SEARCH}); + google_apps_.push_back({static_cast<int>(GoogleApps::kSearch), + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_SEARCH), + "search", "https://google.com", + IDS_WELCOME_SEARCH}); } else { google_apps_.push_back(gmail); } google_apps_.push_back( {static_cast<int>(GoogleApps::kYouTube), - l10n_util::GetStringUTF8(IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_YOUTUBE), - "youtube", "https://youtube.com", IDS_ONBOARDING_WELCOME_YOUTUBE}); + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_APPS_YOUTUBE), "youtube", + "https://youtube.com", IDS_WELCOME_YOUTUBE}); google_apps_.push_back( {static_cast<int>(GoogleApps::kMaps), - l10n_util::GetStringUTF8(IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_MAPS), - "maps", "https://maps.google.com", IDS_ONBOARDING_WELCOME_MAPS}); + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_APPS_MAPS), "maps", + "https://maps.google.com", IDS_WELCOME_MAPS}); if (IsAppVariationEnabled()) { google_apps_.push_back(gmail); } else { google_apps_.push_back( {static_cast<int>(GoogleApps::kNews), - l10n_util::GetStringUTF8(IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_NEWS), - "news", "https://news.google.com", IDS_ONBOARDING_WELCOME_NEWS}); + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_APPS_NEWS), "news", + "https://news.google.com", IDS_WELCOME_NEWS}); } - google_apps_.push_back({static_cast<int>(GoogleApps::kTranslate), - l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_TRANSLATE), - "translate", "https://translate.google.com", - IDS_ONBOARDING_WELCOME_TRANSLATE}); -#endif // defined(GOOGLE_CHROME_BUILD) + google_apps_.push_back( + {static_cast<int>(GoogleApps::kTranslate), + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_APPS_TRANSLATE), "translate", + "https://translate.google.com", IDS_WELCOME_TRANSLATE}); +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) } GoogleAppsHandler::~GoogleAppsHandler() {} @@ -109,7 +108,7 @@ void GoogleAppsHandler::HandleCacheGoogleAppIcon(const base::ListValue* args) { int appId; args->GetInteger(0, &appId); - const BookmarkItem* selectedApp = NULL; + const BookmarkItem* selectedApp = nullptr; for (const auto& google_app : google_apps_) { if (google_app.id == appId) { selectedApp = &google_app; @@ -141,4 +140,4 @@ void GoogleAppsHandler::HandleGetGoogleAppsList(const base::ListValue* args) { BookmarkItemsToListValue(google_apps_.data(), google_apps_.size())); } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.h b/chromium/chrome/browser/ui/webui/welcome/google_apps_handler.h index f35e22d4cb3..1d28ebf3307 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/google_apps_handler.h @@ -2,17 +2,17 @@ // 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_WELCOME_NUX_GOOGLE_APPS_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_GOOGLE_APPS_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_GOOGLE_APPS_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_GOOGLE_APPS_HANDLER_H_ #include <vector> #include "base/macros.h" #include "base/values.h" -#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" +#include "chrome/browser/ui/webui/welcome/bookmark_item.h" #include "content/public/browser/web_ui_message_handler.h" -namespace nux { +namespace welcome { extern const char* kGoogleAppsInteractionHistogram; @@ -43,6 +43,6 @@ class GoogleAppsHandler : public content::WebUIMessageHandler { DISALLOW_COPY_AND_ASSIGN(GoogleAppsHandler); }; -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_GOOGLE_APPS_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_GOOGLE_APPS_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc b/chromium/chrome/browser/ui/webui/welcome/helpers.cc index f8e669c0863..0fe4562325e 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc +++ b/chromium/chrome/browser/ui/webui/welcome/helpers.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/welcome/nux_helper.h" +#include "chrome/browser/ui/webui/welcome/helpers.h" #include <string> #include <vector> @@ -14,13 +14,16 @@ #include "base/strings/string_tokenizer.h" #include "base/values.h" #include "build/branding_buildflags.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/policy/browser_signin_policy_handler.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_attributes_entry.h" +#include "chrome/browser/profiles/profile_attributes_storage.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/search/ntp_features.h" #include "chrome/browser/search/search.h" -#include "chrome/browser/ui/webui/welcome/nux/constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "components/policy/core/common/policy_map.h" @@ -28,30 +31,55 @@ #include "components/policy/policy_constants.h" #include "components/prefs/pref_service.h" -namespace nux { +namespace welcome { -bool CanShowGoogleAppModule(const policy::PolicyMap& policies) { - const base::Value* bookmark_bar_enabled_value = - policies.GetValue(policy::key::kBookmarkBarEnabled); +// Available modules for both new and returning users. +const char kDefaultNewUserModules[] = + "nux-google-apps,nux-ntp-background,nux-set-as-default,signin-view"; +const char kDefaultReturningUserModules[] = "nux-set-as-default"; - if (bookmark_bar_enabled_value && !bookmark_bar_enabled_value->GetBool()) { - return false; - } +// Feature flag. +const base::Feature kFeature{"NuxOnboarding", base::FEATURE_ENABLED_BY_DEFAULT}; +// For testing purposes +const base::Feature kForceEnabled = {"NuxOnboardingForceEnabled", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// The value of these FeatureParam values should be a comma-delimited list +// of element names whitelisted in the MODULES_WHITELIST list, defined in +// chrome/browser/resources/welcome/welcome_app.js +const base::FeatureParam<std::string> kNewUserModules{ + &kFeature, "new-user-modules", kDefaultNewUserModules}; +const base::FeatureParam<std::string> kReturningUserModules{ + &kFeature, "returning-user-modules", kDefaultReturningUserModules}; +// For testing purposes +const base::FeatureParam<std::string> kForceEnabledNewUserModules = { + &kForceEnabled, "new-user-modules", kDefaultNewUserModules}; +const base::FeatureParam<std::string> kForceEnabledReturningUserModules = { + &kForceEnabled, "returning-user-modules", kDefaultReturningUserModules}; + +// FeatureParam for app variation. +const base::FeatureParam<bool> kShowGoogleApp{&kFeature, + "app-variation-enabled", false}; +// For testing purposes +const base::FeatureParam<bool> kForceEnabledShowGoogleApp = { + &kForceEnabled, "app-variation-enabled", false}; + +bool IsPolicySetAndFalse(const policy::PolicyMap& policies, + const std::string& policy_name) { + const base::Value* policy = policies.GetValue(policy_name); + return policy && policy->is_bool() && !policy->GetBool(); +} - const base::Value* edit_bookmarks_value = - policies.GetValue(policy::key::kEditBookmarksEnabled); +bool CanShowGoogleAppModule(const policy::PolicyMap& policies) { + if (IsPolicySetAndFalse(policies, policy::key::kBookmarkBarEnabled)) + return false; - if (edit_bookmarks_value && !edit_bookmarks_value->GetBool()) { + if (IsPolicySetAndFalse(policies, policy::key::kEditBookmarksEnabled)) return false; - } return true; } -bool CanShowGoogleAppModuleForTesting(const policy::PolicyMap& policies) { - return CanShowGoogleAppModule(policies); -} - bool CanShowNTPBackgroundModule(const policy::PolicyMap& policies, Profile* profile) { // We can't set the background if the NTP is something other than Google. @@ -59,20 +87,11 @@ bool CanShowNTPBackgroundModule(const policy::PolicyMap& policies, search::DefaultSearchProviderIsGoogle(profile); } -bool CanShowNTPBackgroundModuleForTesting(const policy::PolicyMap& policies, - Profile* profile) { - return CanShowNTPBackgroundModule(policies, profile); -} - bool CanShowSetDefaultModule(const policy::PolicyMap& policies) { - const base::Value* set_default_value = - policies.GetValue(policy::key::kDefaultBrowserSettingEnabled); - - return !set_default_value || set_default_value->GetBool(); -} + if (IsPolicySetAndFalse(policies, policy::key::kDefaultBrowserSettingEnabled)) + return false; -bool CanShowSetDefaultModuleForTesting(const policy::PolicyMap& policies) { - return CanShowSetDefaultModule(policies); + return true; } bool CanShowSigninModule(const policy::PolicyMap& policies) { @@ -90,11 +109,7 @@ bool CanShowSigninModule(const policy::PolicyMap& policies) { policy::BrowserSigninMode::kDisabled; } -bool CanShowSigninModuleForTesting(const policy::PolicyMap& policies) { - return CanShowSigninModule(policies); -} - -#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN) +#if defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN) // These feature flags are used to tie our experiment to specific studies. // go/navi-app-variation for details. // TODO(hcarmona): find a solution that scales better. @@ -108,33 +123,12 @@ const base::Feature kNaviShortcutVariationEnabled = { "NaviShortcutVariationEnabled", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN) -// This feature flag is used to force the feature to be turned on for non-win -// and non-branded builds, like with tests or development on other platforms. -const base::Feature kNuxOnboardingForceEnabled = { - "NuxOnboardingForceEnabled", base::FEATURE_DISABLED_BY_DEFAULT}; - -// The value of these FeatureParam values should be a comma-delimited list -// of element names whitelisted in the MODULES_WHITELIST list, defined in -// chrome/browser/resources/welcome/onboarding_welcome/welcome_app.js -const base::FeatureParam<std::string> kNuxOnboardingForceEnabledNewUserModules = - {&kNuxOnboardingForceEnabled, "new-user-modules", - "nux-google-apps,nux-ntp-background,nux-set-as-default," - "signin-view"}; -const base::FeatureParam<std::string> - kNuxOnboardingForceEnabledReturningUserModules = { - &kNuxOnboardingForceEnabled, "returning-user-modules", - "nux-set-as-default"}; -const base::FeatureParam<bool> kNuxOnboardingForceEnabledShowGoogleApp = { - &kNuxOnboardingForceEnabled, "app-variation-enabled", false}; - -// Onboarding experiments depend on Google being the default search provider. +// Welcome experiments depend on Google being the default search provider. bool CanExperimentWithVariations(Profile* profile) { return search::DefaultSearchProviderIsGoogle(profile); } -// Must match study name in configs. -const char kNuxOnboardingStudyName[] = "NaviOnboarding"; - +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN) // Get the group for users who onboard in this experiment. // Groups are: // - Specified by study @@ -151,59 +145,56 @@ std::string GetOnboardingGroup(Profile* profile) { // We need to use |base::GetFieldTrialParamValue| instead of // |base::FeatureParam| because our control group needs a custom value for // this param. - return base::GetFieldTrialParamValue(kNuxOnboardingStudyName, - "onboarding-group"); + // "NaviOnboarding" match study name in configs. + return base::GetFieldTrialParamValue("NaviOnboarding", "onboarding-group"); } -#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN) void JoinOnboardingGroup(Profile* profile) { PrefService* prefs = profile->GetPrefs(); - std::string onboard_group; + std::string group; if (prefs->GetBoolean(prefs::kHasSeenWelcomePage)) { - // Get user's original onboarding group. - onboard_group = prefs->GetString(prefs::kNaviOnboardGroup); + // Get user's original group. + group = prefs->GetString(prefs::kNaviOnboardGroup); - // Users who onboarded before Navi won't have an onboarding group. - if (onboard_group.empty()) + // Users who onboarded before Navi won't have a group. + if (group.empty()) return; } else { // Join the latest group if onboarding for the first time! - onboard_group = GetOnboardingGroup(profile); - profile->GetPrefs()->SetString(prefs::kNaviOnboardGroup, onboard_group); + group = GetOnboardingGroup(profile); + profile->GetPrefs()->SetString(prefs::kNaviOnboardGroup, group); } - // User will be tied to their original onboarding group, even after - // experiment ends. + // User will be tied to their original group, even after experiment ends. ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial( - "NaviOnboardingSynthetic", onboard_group); + "NaviOnboardingSynthetic", group); - // Check for feature based on onboarding group. + // Check for feature based on group. // TODO(hcarmona): find a solution that scales better. - if (onboard_group.compare("ControlSynthetic-008") == 0) + if (group.compare("ControlSynthetic-008") == 0) base::FeatureList::IsEnabled(kNaviControlEnabled); - else if (onboard_group.compare("AppVariationSynthetic-008") == 0) + else if (group.compare("AppVariationSynthetic-008") == 0) base::FeatureList::IsEnabled(kNaviAppVariationEnabled); - else if (onboard_group.compare("NTPVariationSynthetic-008") == 0) + else if (group.compare("NTPVariationSynthetic-008") == 0) base::FeatureList::IsEnabled(kNaviNTPVariationEnabled); - else if (onboard_group.compare("ShortcutVariationSynthetic-008") == 0) + else if (group.compare("ShortcutVariationSynthetic-008") == 0) base::FeatureList::IsEnabled(kNaviShortcutVariationEnabled); } #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN) -bool IsNuxOnboardingEnabled(Profile* profile) { -#if BUILDFLAG(GOOGLE_CHROME_BRANDING) - return base::FeatureList::IsEnabled(nux::kNuxOnboardingFeature) || - base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled); +bool IsEnabled(Profile* profile) { +#if defined(GOOGLE_CHROME_BUILD) + return base::FeatureList::IsEnabled(welcome::kFeature) || + base::FeatureList::IsEnabled(welcome::kForceEnabled); #else // Allow enabling outside official builds for testing purposes. - return base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled); -#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) + return base::FeatureList::IsEnabled(welcome::kForceEnabled); +#endif // defined(GOOGLE_CHROME_BUILD) } bool IsAppVariationEnabled() { - return kNuxOnboardingForceEnabledShowGoogleApp.Get() || - kNuxOnboardingShowGoogleApp.Get(); + return kForceEnabledShowGoogleApp.Get() || kShowGoogleApp.Get(); } const policy::PolicyMap& GetPoliciesFromProfile(Profile* profile) { @@ -230,13 +221,13 @@ std::vector<std::string> GetAvailableModules(Profile* profile) { return available_modules; } -bool DoesOnboardingHaveModulesToShow(Profile* profile) { - const base::Value* force_ephemeral_profiles_value = - GetPoliciesFromProfile(profile).GetValue( - policy::key::kForceEphemeralProfiles); - // Modules won't have a lasting effect if profile is ephemeral. - if (force_ephemeral_profiles_value && - force_ephemeral_profiles_value->GetBool()) { +bool HasModulesToShow(Profile* profile) { + // Modules won't have lasting effect if profile is ephemeral, so we can skip. + ProfileAttributesStorage& storage = + g_browser_process->profile_manager()->GetProfileAttributesStorage(); + ProfileAttributesEntry* entry = nullptr; + if (storage.GetProfileAttributesWithPath(profile->GetPath(), &entry) && + entry->IsEphemeral()) { return false; } @@ -259,20 +250,19 @@ std::string FilterModules(const std::string& requested_modules, return base::JoinString(filtered_modules, ","); } -base::DictionaryValue GetNuxOnboardingModules(Profile* profile) { - // This function should not be called when nux onboarding feature is not on. - DCHECK(nux::IsNuxOnboardingEnabled(profile)); +base::DictionaryValue GetModules(Profile* profile) { + // This function should not be called when feature is not on. + DCHECK(welcome::IsEnabled(profile)); std::string new_user_modules = kDefaultNewUserModules; std::string returning_user_modules = kDefaultReturningUserModules; - if (base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled)) { - new_user_modules = kNuxOnboardingForceEnabledNewUserModules.Get(); - returning_user_modules = - kNuxOnboardingForceEnabledReturningUserModules.Get(); + if (base::FeatureList::IsEnabled(welcome::kForceEnabled)) { + new_user_modules = kForceEnabledNewUserModules.Get(); + returning_user_modules = kForceEnabledReturningUserModules.Get(); } else if (CanExperimentWithVariations(profile)) { - new_user_modules = kNuxOnboardingNewUserModules.Get(); - returning_user_modules = kNuxOnboardingReturningUserModules.Get(); + new_user_modules = kNewUserModules.Get(); + returning_user_modules = kReturningUserModules.Get(); } std::vector<std::string> available_modules = GetAvailableModules(profile); @@ -284,4 +274,21 @@ base::DictionaryValue GetNuxOnboardingModules(Profile* profile) { FilterModules(returning_user_modules, available_modules)); return modules; } -} // namespace nux + +bool CanShowGoogleAppModuleForTesting(const policy::PolicyMap& policies) { + return CanShowGoogleAppModule(policies); +} + +bool CanShowNTPBackgroundModuleForTesting(const policy::PolicyMap& policies, + Profile* profile) { + return CanShowNTPBackgroundModule(policies, profile); +} + +bool CanShowSetDefaultModuleForTesting(const policy::PolicyMap& policies) { + return CanShowSetDefaultModule(policies); +} + +bool CanShowSigninModuleForTesting(const policy::PolicyMap& policies) { + return CanShowSigninModule(policies); +} +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux_helper.h b/chromium/chrome/browser/ui/webui/welcome/helpers.h index fb99d65d282..258c956b80c 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux_helper.h +++ b/chromium/chrome/browser/ui/webui/welcome/helpers.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_WELCOME_NUX_HELPER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_HELPER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_HELPERS_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_HELPERS_H_ #include <string> @@ -22,14 +22,7 @@ class PolicyMap; class Profile; -namespace nux { -extern const base::Feature kNuxOnboardingForceEnabled; - -extern const base::FeatureParam<std::string> - kNuxOnboardingForceEnabledNewUserModules; -extern const base::FeatureParam<std::string> - kNuxOnboardingForceEnabledReturningUserModules; - +namespace welcome { #if defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN) // Onboarding groups are used for running field trials related to first run // experience. This will make a new profile join whatever group is currently @@ -38,21 +31,23 @@ extern const base::FeatureParam<std::string> void JoinOnboardingGroup(Profile* profile); #endif // defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN) -bool IsNuxOnboardingEnabled(Profile* profile); +bool IsEnabled(Profile* profile); bool IsAppVariationEnabled(); -bool DoesOnboardingHaveModulesToShow(Profile* profile); +bool HasModulesToShow(Profile* profile); -base::DictionaryValue GetNuxOnboardingModules(Profile* profile); +base::DictionaryValue GetModules(Profile* profile); // Exposed for testing. +extern const base::Feature kForceEnabled; + bool CanShowGoogleAppModuleForTesting(const policy::PolicyMap& policies); bool CanShowNTPBackgroundModuleForTesting(const policy::PolicyMap& policies, Profile* profile); bool CanShowSetDefaultModuleForTesting(const policy::PolicyMap& policies); bool CanShowSigninModuleForTesting(const policy::PolicyMap& policies); -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_HELPER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_HELPERS_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.cc b/chromium/chrome/browser/ui/webui/welcome/ntp_background_fetcher.cc index 658de1d4c86..33ff4884574 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.cc +++ b/chromium/chrome/browser/ui/webui/welcome/ntp_background_fetcher.cc @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.h" +#include "chrome/browser/ui/webui/welcome/ntp_background_fetcher.h" #include <utility> #include "chrome/browser/browser_process.h" #include "chrome/browser/net/system_network_context_manager.h" -#include "chrome/browser/search/background/onboarding_ntp_backgrounds.h" +#include "chrome/browser/search/background/ntp_backgrounds.h" #include "net/base/load_flags.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request.h" @@ -16,7 +16,7 @@ #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "url/gurl.h" -namespace nux { +namespace welcome { NtpBackgroundFetcher::NtpBackgroundFetcher( size_t index, @@ -46,7 +46,7 @@ NtpBackgroundFetcher::NtpBackgroundFetcher( policy_exception_justification: "Not implemented." })"); - auto backgrounds = GetOnboardingNtpBackgrounds(); + auto backgrounds = GetNtpBackgrounds(); if (index_ >= backgrounds.size()) { OnFetchCompleted(nullptr); @@ -56,8 +56,7 @@ NtpBackgroundFetcher::NtpBackgroundFetcher( GURL url = backgrounds[index_]; auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = url; - resource_request->load_flags = - net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES; + resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; simple_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); @@ -80,4 +79,4 @@ void NtpBackgroundFetcher::OnFetchCompleted( } } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.h b/chromium/chrome/browser/ui/webui/welcome/ntp_background_fetcher.h index 1e4892a4ad9..bfd25a376a8 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.h +++ b/chromium/chrome/browser/ui/webui/welcome/ntp_background_fetcher.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_NTP_BACKGROUND_FETCHER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_NTP_BACKGROUND_FETCHER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_FETCHER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_FETCHER_H_ #include <memory> #include <string> @@ -16,7 +16,7 @@ namespace network { class SimpleURLLoader; } -namespace nux { +namespace welcome { class NtpBackgroundFetcher { public: @@ -35,6 +35,6 @@ class NtpBackgroundFetcher { DISALLOW_COPY_AND_ASSIGN(NtpBackgroundFetcher); }; -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_NTP_BACKGROUND_FETCHER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_FETCHER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.cc b/chromium/chrome/browser/ui/webui/welcome/ntp_background_handler.cc index 914372cffe1..b970bec8740 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/ntp_background_handler.cc @@ -2,25 +2,26 @@ // 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/welcome/nux/ntp_background_handler.h" +#include "chrome/browser/ui/webui/welcome/ntp_background_handler.h" #include <memory> #include <utility> #include "base/bind.h" +#include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/background/onboarding_ntp_backgrounds.h" +#include "chrome/browser/search/background/ntp_backgrounds.h" #include "chrome/browser/search/instant_service.h" #include "chrome/browser/search/instant_service_factory.h" #include "chrome/grit/generated_resources.h" -#include "chrome/grit/onboarding_welcome_resources.h" +#include "chrome/grit/welcome_resources.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" -namespace nux { +namespace welcome { enum class NtpBackgrounds { kArt = 0, @@ -53,7 +54,7 @@ void NtpBackgroundHandler::RegisterMessages() { void NtpBackgroundHandler::HandleClearBackground(const base::ListValue* args) { InstantService* instant_service = InstantServiceFactory::GetForProfile(Profile::FromWebUI(web_ui())); - instant_service->SetCustomBackgroundURL(GURL("")); + instant_service->ResetCustomBackgroundInfo(); } void NtpBackgroundHandler::HandleGetBackgrounds(const base::ListValue* args) { @@ -63,58 +64,52 @@ void NtpBackgroundHandler::HandleGetBackgrounds(const base::ListValue* args) { CHECK(args->Get(0, &callback_id)); base::ListValue list_value; - std::array<GURL, kOnboardingNtpBackgroundsCount> onboardingNtpBackgrounds = - GetOnboardingNtpBackgrounds(); + std::array<GURL, kNtpBackgroundsCount> NtpBackgrounds = GetNtpBackgrounds(); const std::string kUrlPrefix = "preview-background.jpg?"; auto element = std::make_unique<base::DictionaryValue>(); int id = static_cast<int>(NtpBackgrounds::kEarth); element->SetInteger("id", id); - element->SetString("title", - l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_EARTH_TITLE)); - element->SetString("imageUrl", kUrlPrefix + std::to_string(id)); + element->SetString("title", l10n_util::GetStringUTF8( + IDS_WELCOME_NTP_BACKGROUND_EARTH_TITLE)); + element->SetString("imageUrl", kUrlPrefix + base::NumberToString(id)); element->SetString("thumbnailClass", "earth"); list_value.Append(std::move(element)); element = std::make_unique<base::DictionaryValue>(); id = static_cast<int>(NtpBackgrounds::kCityscape); element->SetInteger("id", id); - element->SetString( - "title", l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_CITYSCAPE_TITLE)); - element->SetString("imageUrl", kUrlPrefix + std::to_string(id)); + element->SetString("title", l10n_util::GetStringUTF8( + IDS_WELCOME_NTP_BACKGROUND_CITYSCAPE_TITLE)); + element->SetString("imageUrl", kUrlPrefix + base::NumberToString(id)); element->SetString("thumbnailClass", "cityscape"); list_value.Append(std::move(element)); element = std::make_unique<base::DictionaryValue>(); id = static_cast<int>(NtpBackgrounds::kLandscape); element->SetInteger("id", id); - element->SetString( - "title", l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_LANDSCAPE_TITLE)); - element->SetString("imageUrl", kUrlPrefix + std::to_string(id)); + element->SetString("title", l10n_util::GetStringUTF8( + IDS_WELCOME_NTP_BACKGROUND_LANDSCAPE_TITLE)); + element->SetString("imageUrl", kUrlPrefix + base::NumberToString(id)); element->SetString("thumbnailClass", "landscape"); list_value.Append(std::move(element)); element = std::make_unique<base::DictionaryValue>(); id = static_cast<int>(NtpBackgrounds::kArt); element->SetInteger("id", id); - element->SetString("title", - l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_ART_TITLE)); - element->SetString("imageUrl", kUrlPrefix + std::to_string(id)); + element->SetString( + "title", l10n_util::GetStringUTF8(IDS_WELCOME_NTP_BACKGROUND_ART_TITLE)); + element->SetString("imageUrl", kUrlPrefix + base::NumberToString(id)); element->SetString("thumbnailClass", "art"); list_value.Append(std::move(element)); element = std::make_unique<base::DictionaryValue>(); id = static_cast<int>(NtpBackgrounds::kGeometricShapes); element->SetInteger("id", id); - element->SetString( - "title", - l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_GEOMETRIC_SHAPES_TITLE)); - element->SetString("imageUrl", kUrlPrefix + std::to_string(id)); + element->SetString("title", + l10n_util::GetStringUTF8( + IDS_WELCOME_NTP_BACKGROUND_GEOMETRIC_SHAPES_TITLE)); + element->SetString("imageUrl", kUrlPrefix + base::NumberToString(id)); element->SetString("thumbnailClass", "geometric-shapes"); list_value.Append(std::move(element)); @@ -126,24 +121,22 @@ void NtpBackgroundHandler::HandleSetBackground(const base::ListValue* args) { int backgroundIndex; args->GetInteger(0, &backgroundIndex); - std::array<GURL, kOnboardingNtpBackgroundsCount> onboardingNtpBackgrounds = - GetOnboardingNtpBackgrounds(); + std::array<GURL, kNtpBackgroundsCount> NtpBackgrounds = GetNtpBackgrounds(); InstantService* instant_service = InstantServiceFactory::GetForProfile(Profile::FromWebUI(web_ui())); switch (backgroundIndex) { case static_cast<int>(NtpBackgrounds::kArt): instant_service->SetCustomBackgroundInfo( - onboardingNtpBackgrounds[backgroundIndex], "Universe Cosmic Vacum", + NtpBackgrounds[backgroundIndex], "Universe Cosmic Vacum", "Philipp Rietz — Walli", GURL("https://walli.shanga.co/image/view/?id=370"), ""); break; case static_cast<int>(NtpBackgrounds::kCityscape): instant_service->SetCustomBackgroundInfo( - onboardingNtpBackgrounds[backgroundIndex], - l10n_util::GetStringFUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, - base::UTF8ToUTF16("Ev Tchebotarev")), + NtpBackgrounds[backgroundIndex], + l10n_util::GetStringFUTF8(IDS_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, + base::UTF8ToUTF16("Ev Tchebotarev")), "", GURL("https://500px.com/photo/135751035/" "soulseek-by-%E5%B0%A4%E9%87%91%E5%B0%BC-ev-tchebotarev"), @@ -151,24 +144,22 @@ void NtpBackgroundHandler::HandleSetBackground(const base::ListValue* args) { break; case static_cast<int>(NtpBackgrounds::kEarth): instant_service->SetCustomBackgroundInfo( - onboardingNtpBackgrounds[backgroundIndex], - l10n_util::GetStringFUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, - base::UTF8ToUTF16("NASA Image Library")), + NtpBackgrounds[backgroundIndex], + l10n_util::GetStringFUTF8(IDS_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, + base::UTF8ToUTF16("NASA Image Library")), "", GURL("https://www.google.com/sky/"), ""); break; case static_cast<int>(NtpBackgrounds::kGeometricShapes): instant_service->SetCustomBackgroundInfo( - onboardingNtpBackgrounds[backgroundIndex], "Tessellation 15", + NtpBackgrounds[backgroundIndex], "Tessellation 15", "Justin Prno — Walli", GURL("https://walli.shanga.co/image/view/?id=1375"), ""); break; case static_cast<int>(NtpBackgrounds::kLandscape): instant_service->SetCustomBackgroundInfo( - onboardingNtpBackgrounds[backgroundIndex], - l10n_util::GetStringFUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, - base::UTF8ToUTF16("Giulio Rosso Chioso")), + NtpBackgrounds[backgroundIndex], + l10n_util::GetStringFUTF8(IDS_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, + base::UTF8ToUTF16("Giulio Rosso Chioso")), "", GURL("https://500px.com/photo/41149196/" "le-piscine-sunset-by-giulio-rosso-chioso"), @@ -177,4 +168,4 @@ void NtpBackgroundHandler::HandleSetBackground(const base::ListValue* args) { } } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.h b/chromium/chrome/browser/ui/webui/welcome/ntp_background_handler.h index d2c23fab9d2..acf86d33a7f 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/ntp_background_handler.h @@ -2,12 +2,12 @@ // 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_WELCOME_NUX_NTP_BACKGROUND_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_NTP_BACKGROUND_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_HANDLER_H_ #include "content/public/browser/web_ui_message_handler.h" -namespace nux { +namespace welcome { class NtpBackgroundHandler : public content::WebUIMessageHandler { public: @@ -26,6 +26,6 @@ class NtpBackgroundHandler : public content::WebUIMessageHandler { DISALLOW_COPY_AND_ASSIGN(NtpBackgroundHandler); }; -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_NTP_BACKGROUND_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/README b/chromium/chrome/browser/ui/webui/welcome/nux/README deleted file mode 100644 index b2d6888146e..00000000000 --- a/chromium/chrome/browser/ui/webui/welcome/nux/README +++ /dev/null @@ -1,3 +0,0 @@ -New User Experience Experiment (NUX). Code here will prompt new users to go -through an onboarding experience to customize their new browser install to -their common usages.
\ No newline at end of file diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/constants.cc b/chromium/chrome/browser/ui/webui/welcome/nux/constants.cc deleted file mode 100644 index ac31489fd77..00000000000 --- a/chromium/chrome/browser/ui/webui/welcome/nux/constants.cc +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/welcome/nux/constants.h" - -#include "base/feature_list.h" - -namespace nux { - -const base::Feature kNuxOnboardingFeature{"NuxOnboarding", - base::FEATURE_ENABLED_BY_DEFAULT}; - -const char kDefaultNewUserModules[] = - "nux-google-apps,nux-set-as-default,signin-view"; -const char kDefaultReturningUserModules[] = "nux-set-as-default"; - -// The value of these FeatureParam values should be a comma-delimited list -// of element names whitelisted in the MODULES_WHITELIST list, defined in -// chrome/browser/resources/welcome/onboarding_welcome/welcome_app.js -const base::FeatureParam<std::string> kNuxOnboardingNewUserModules{ - &kNuxOnboardingFeature, "new-user-modules", kDefaultNewUserModules}; -const base::FeatureParam<std::string> kNuxOnboardingReturningUserModules{ - &kNuxOnboardingFeature, "returning-user-modules", - kDefaultReturningUserModules}; - -const base::FeatureParam<bool> kNuxOnboardingShowGoogleApp{ - &kNuxOnboardingFeature, "app-variation-enabled", false}; - -} // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/constants.h b/chromium/chrome/browser/ui/webui/welcome/nux/constants.h deleted file mode 100644 index de397b2f0d6..00000000000 --- a/chromium/chrome/browser/ui/webui/welcome/nux/constants.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_CONSTANTS_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_CONSTANTS_H_ - -#include <string> -#include "base/metrics/field_trial_params.h" - -namespace base { -struct Feature; -} // namespace base - -namespace nux { - -extern const base::Feature kNuxOnboardingFeature; - -extern const char kDefaultNewUserModules[]; -extern const char kDefaultReturningUserModules[]; - -extern const base::FeatureParam<std::string> kNuxOnboardingNewUserModules; -extern const base::FeatureParam<std::string> kNuxOnboardingReturningUserModules; -extern const base::FeatureParam<bool> kNuxOnboardingShowGoogleApp; - -} // namespace nux - -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_CONSTANTS_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.cc b/chromium/chrome/browser/ui/webui/welcome/set_as_default_handler.cc index 3d4f3387ec8..bd511dcc572 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/set_as_default_handler.cc @@ -2,9 +2,9 @@ // 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/welcome/nux/set_as_default_handler.h" +#include "chrome/browser/ui/webui/welcome/set_as_default_handler.h" -namespace nux { +namespace welcome { SetAsDefaultHandler::SetAsDefaultHandler() : settings::DefaultBrowserHandler() {} @@ -15,4 +15,4 @@ void SetAsDefaultHandler::RecordSetAsDefaultUMA() { // TODO(hcarmona): Add UMA tracking. } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h b/chromium/chrome/browser/ui/webui/welcome/set_as_default_handler.h index 5f70e699ea6..e06476a4583 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/set_as_default_handler.h @@ -2,13 +2,13 @@ // 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_WELCOME_NUX_SET_AS_DEFAULT_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_SET_AS_DEFAULT_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_SET_AS_DEFAULT_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_SET_AS_DEFAULT_HANDLER_H_ #include "base/macros.h" #include "chrome/browser/ui/webui/settings/settings_default_browser_handler.h" -namespace nux { +namespace welcome { class SetAsDefaultHandler : public settings::DefaultBrowserHandler { public: @@ -21,6 +21,6 @@ class SetAsDefaultHandler : public settings::DefaultBrowserHandler { DISALLOW_COPY_AND_ASSIGN(SetAsDefaultHandler); }; -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_SET_AS_DEFAULT_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_SET_AS_DEFAULT_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc index 222a102b2be..17d4764ec78 100644 --- a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc @@ -61,7 +61,7 @@ void WelcomeHandler::OnSyncConfirmationUIClosed( if (result != LoginUIService::ABORT_SIGNIN) { result_ = WelcomeResult::SIGNED_IN; - // When signed in from NUX onboarding flow, it's possible to come back to + // When signed in from welcome flow, it's possible to come back to // chrome://welcome/... after closing sync-confirmation UI. If current URL // matches such a case, do not navigate away. if (!is_redirected_welcome_impression_) { @@ -110,7 +110,7 @@ void WelcomeHandler::HandleUserDecline(const base::ListValue* args) { // Override from WebUIMessageHandler. void WelcomeHandler::RegisterMessages() { - // Check if this instance of WelcomeHandler is spawned by onboarding flow + // Check if this instance of WelcomeHandler is spawned by welcome flow // redirecting users back to welcome page. This is done here instead of // constructor, because web_ui hasn't loaded yet at that time. is_redirected_welcome_impression_ = isValidRedirectUrl(); diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc index d05ae4c1e86..d0b69ca81d4 100644 --- a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc +++ b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc @@ -9,19 +9,18 @@ #include "build/branding_buildflags.h" #include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/ui/webui/localized_string.h" -#include "chrome/browser/ui/webui/welcome/nux/bookmark_handler.h" -#include "chrome/browser/ui/webui/welcome/nux/constants.h" -#include "chrome/browser/ui/webui/welcome/nux/google_apps_handler.h" -#include "chrome/browser/ui/webui/welcome/nux/ntp_background_handler.h" -#include "chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h" -#include "chrome/browser/ui/webui/welcome/nux_helper.h" +#include "chrome/browser/ui/webui/welcome/bookmark_handler.h" +#include "chrome/browser/ui/webui/welcome/google_apps_handler.h" +#include "chrome/browser/ui/webui/welcome/helpers.h" +#include "chrome/browser/ui/webui/welcome/ntp_background_handler.h" +#include "chrome/browser/ui/webui/welcome/set_as_default_handler.h" #include "chrome/browser/ui/webui/welcome/welcome_handler.h" #include "chrome/common/pref_names.h" #include "chrome/grit/chrome_unscaled_resources.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" -#include "chrome/grit/onboarding_welcome_resources.h" -#include "chrome/grit/onboarding_welcome_resources_map.h" +#include "chrome/grit/welcome_resources.h" +#include "chrome/grit/welcome_resources_map.h" #include "components/prefs/pref_service.h" #include "components/signin/public/base/signin_pref_names.h" #include "components/strings/grit/components_strings.h" @@ -67,49 +66,44 @@ void HandleRequestCallback( weak_ptr->CreateBackgroundFetcher(background_index, callback); } -void AddOnboardingStrings(content::WebUIDataSource* html_source) { +void AddStrings(content::WebUIDataSource* html_source) { static constexpr LocalizedString kLocalizedStrings[] = { // Shared strings. - {"bookmarkAdded", IDS_ONBOARDING_WELCOME_BOOKMARK_ADDED}, - {"bookmarksAdded", IDS_ONBOARDING_WELCOME_BOOKMARKS_ADDED}, - {"bookmarkRemoved", IDS_ONBOARDING_WELCOME_BOOKMARK_REMOVED}, - {"bookmarksRemoved", IDS_ONBOARDING_WELCOME_BOOKMARKS_REMOVED}, - {"defaultBrowserChanged", IDS_ONBOARDING_DEFAULT_BROWSER_CHANGED}, + {"bookmarkAdded", IDS_WELCOME_BOOKMARK_ADDED}, + {"bookmarksAdded", IDS_WELCOME_BOOKMARKS_ADDED}, + {"bookmarkRemoved", IDS_WELCOME_BOOKMARK_REMOVED}, + {"bookmarksRemoved", IDS_WELCOME_BOOKMARKS_REMOVED}, + {"defaultBrowserChanged", IDS_DEFAULT_BROWSER_CHANGED}, {"headerText", IDS_WELCOME_HEADER}, - {"next", IDS_ONBOARDING_WELCOME_NEXT}, + {"next", IDS_WELCOME_NEXT}, {"noThanks", IDS_NO_THANKS}, - {"skip", IDS_ONBOARDING_WELCOME_SKIP}, + {"skip", IDS_WELCOME_SKIP}, // Sign-in view strings. - {"signInHeader", IDS_ONBOARDING_WELCOME_SIGNIN_VIEW_HEADER}, - {"signInSubHeader", IDS_ONBOARDING_WELCOME_SIGNIN_VIEW_SUB_HEADER}, - {"signIn", IDS_ONBOARDING_WELCOME_SIGNIN_VIEW_SIGNIN}, + {"signInHeader", IDS_WELCOME_SIGNIN_VIEW_HEADER}, + {"signInSubHeader", IDS_WELCOME_SIGNIN_VIEW_SUB_HEADER}, + {"signIn", IDS_WELCOME_SIGNIN_VIEW_SIGNIN}, // Google apps module strings. - {"googleAppsDescription", - IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_DESCRIPTION}, + {"googleAppsDescription", IDS_WELCOME_GOOGLE_APPS_DESCRIPTION}, // New Tab Page background module strings. - {"ntpBackgroundDescription", - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_DESCRIPTION}, - {"ntpBackgroundDefault", - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_DEFAULT_TITLE}, + {"ntpBackgroundDescription", IDS_WELCOME_NTP_BACKGROUND_DESCRIPTION}, + {"ntpBackgroundDefault", IDS_WELCOME_NTP_BACKGROUND_DEFAULT_TITLE}, {"ntpBackgroundPreviewUpdated", - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PREVIEW_UPDATED}, - {"ntpBackgroundReset", IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_RESET}, + IDS_WELCOME_NTP_BACKGROUND_PREVIEW_UPDATED}, + {"ntpBackgroundReset", IDS_WELCOME_NTP_BACKGROUND_RESET}, // Set as default module strings. - {"setDefaultHeader", IDS_ONBOARDING_WELCOME_NUX_SET_AS_DEFAULT_HEADER}, - {"setDefaultSubHeader", - IDS_ONBOARDING_WELCOME_NUX_SET_AS_DEFAULT_SUB_HEADER}, - {"setDefaultConfirm", - IDS_ONBOARDING_WELCOME_NUX_SET_AS_DEFAULT_SET_AS_DEFAULT}, + {"setDefaultHeader", IDS_WELCOME_SET_AS_DEFAULT_HEADER}, + {"setDefaultSubHeader", IDS_WELCOME_SET_AS_DEFAULT_SUB_HEADER}, + {"setDefaultConfirm", IDS_WELCOME_SET_AS_DEFAULT_SET_AS_DEFAULT}, // Landing view strings. - {"landingTitle", IDS_ONBOARDING_WELCOME_LANDING_TITLE}, - {"landingDescription", IDS_ONBOARDING_WELCOME_LANDING_DESCRIPTION}, - {"landingNewUser", IDS_ONBOARDING_WELCOME_LANDING_NEW_USER}, - {"landingExistingUser", IDS_ONBOARDING_WELCOME_LANDING_EXISTING_USER}, + {"landingTitle", IDS_WELCOME_LANDING_TITLE}, + {"landingDescription", IDS_WELCOME_LANDING_DESCRIPTION}, + {"landingNewUser", IDS_WELCOME_LANDING_NEW_USER}, + {"landingExistingUser", IDS_WELCOME_LANDING_EXISTING_USER}, }; AddLocalizedStringsBulk(html_source, kLocalizedStrings, base::size(kLocalizedStrings)); @@ -134,13 +128,13 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) content::WebUIDataSource* html_source = content::WebUIDataSource::Create(url.host()); - // Add Onboarding welcome strings. - AddOnboardingStrings(html_source); + // Add welcome strings. + AddStrings(html_source); - // Add all Onboarding resources. - for (size_t i = 0; i < kOnboardingWelcomeResourcesSize; ++i) { - html_source->AddResourcePath(kOnboardingWelcomeResources[i].name, - kOnboardingWelcomeResources[i].value); + // Add all welcome resources. + for (size_t i = 0; i < kWelcomeResourcesSize; ++i) { + html_source->AddResourcePath(kWelcomeResources[i].name, + kWelcomeResources[i].value); } #if BUILDFLAG(GOOGLE_CHROME_BRANDING) @@ -174,33 +168,32 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) // chrome://welcome - html_source->SetDefaultResource(IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_HTML); + html_source->SetDefaultResource(IDR_WELCOME_HTML); #if defined(OS_WIN) html_source->AddBoolean("is_win10", base::win::GetVersion() >= base::win::Version::WIN10); #endif - // Add the shared bookmark handler for onboarding modules. + // Add the shared bookmark handler for welcome modules. web_ui->AddMessageHandler( - std::make_unique<nux::BookmarkHandler>(profile->GetPrefs())); + std::make_unique<welcome::BookmarkHandler>(profile->GetPrefs())); - // Add google apps bookmarking onboarding module. - web_ui->AddMessageHandler(std::make_unique<nux::GoogleAppsHandler>()); + // Add google apps bookmarking module. + web_ui->AddMessageHandler(std::make_unique<welcome::GoogleAppsHandler>()); - // Add NTP custom background onboarding module. - web_ui->AddMessageHandler(std::make_unique<nux::NtpBackgroundHandler>()); + // Add NTP custom background module. + web_ui->AddMessageHandler(std::make_unique<welcome::NtpBackgroundHandler>()); - // Add set-as-default onboarding module. - web_ui->AddMessageHandler(std::make_unique<nux::SetAsDefaultHandler>()); + // Add set-as-default module. + web_ui->AddMessageHandler(std::make_unique<welcome::SetAsDefaultHandler>()); html_source->AddString( "newUserModules", - nux::GetNuxOnboardingModules(profile).FindKey("new-user")->GetString()); - html_source->AddString("returningUserModules", - nux::GetNuxOnboardingModules(profile) - .FindKey("returning-user") - ->GetString()); + welcome::GetModules(profile).FindKey("new-user")->GetString()); + html_source->AddString( + "returningUserModules", + welcome::GetModules(profile).FindKey("returning-user")->GetString()); html_source->AddBoolean( "signinAllowed", profile->GetPrefs()->GetBoolean(prefs::kSigninAllowed)); html_source->SetRequestFilter( @@ -208,7 +201,7 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) weak_ptr_factory_.GetWeakPtr()), base::BindRepeating(&HandleRequestCallback, weak_ptr_factory_.GetWeakPtr())); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); content::WebUIDataSource::Add(profile, html_source); } @@ -218,8 +211,8 @@ WelcomeUI::~WelcomeUI() {} void WelcomeUI::CreateBackgroundFetcher( size_t background_index, const content::WebUIDataSource::GotDataCallback& callback) { - background_fetcher_ = - std::make_unique<nux::NtpBackgroundFetcher>(background_index, callback); + background_fetcher_ = std::make_unique<welcome::NtpBackgroundFetcher>( + background_index, callback); } void WelcomeUI::StorePageSeen(Profile* profile) { diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h index ed54ca23bc1..3f0be1af968 100644 --- a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h +++ b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h @@ -10,7 +10,7 @@ #include "base/memory/weak_ptr.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.h" +#include "chrome/browser/ui/webui/welcome/ntp_background_fetcher.h" #include "content/public/browser/web_ui_controller.h" #include "content/public/browser/web_ui_data_source.h" #include "url/gurl.h" @@ -34,7 +34,7 @@ class WelcomeUI : public content::WebUIController { private: void StorePageSeen(Profile* profile); - std::unique_ptr<nux::NtpBackgroundFetcher> background_fetcher_; + std::unique_ptr<welcome::NtpBackgroundFetcher> background_fetcher_; base::WeakPtrFactory<WelcomeUI> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WelcomeUI); |