diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-08-28 15:28:34 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-08-28 13:54:51 +0000 |
commit | 2a19c63448c84c1805fb1a585c3651318bb86ca7 (patch) | |
tree | eb17888e8531aa6ee5e85721bd553b832a7e5156 /chromium/chrome/browser/ui | |
parent | b014812705fc80bff0a5c120dfcef88f349816dc (diff) | |
download | qtwebengine-chromium-2a19c63448c84c1805fb1a585c3651318bb86ca7.tar.gz |
BASELINE: Update Chromium to 69.0.3497.70
Change-Id: I2b7b56e4e7a8b26656930def0d4575dc32b900a0
Reviewed-by: Allan Sandfeld Jensen <allan.jensen@qt.io>
Diffstat (limited to 'chromium/chrome/browser/ui')
253 files changed, 7096 insertions, 3515 deletions
diff --git a/chromium/chrome/browser/ui/BUILD.gn b/chromium/chrome/browser/ui/BUILD.gn index c514878fafe..4ef83e1a942 100644 --- a/chromium/chrome/browser/ui/BUILD.gn +++ b/chromium/chrome/browser/ui/BUILD.gn @@ -73,12 +73,6 @@ split_static_library("ui") { "cocoa/autofill/autofill_popup_view_cocoa.mm", "cocoa/autofill/autofill_tooltip_controller.h", "cocoa/autofill/autofill_tooltip_controller.mm", - "cocoa/autofill/credit_card_autofill_touch_bar_controller.h", - "cocoa/autofill/credit_card_autofill_touch_bar_controller.mm", - "cocoa/autofill/password_generation_popup_view_bridge.h", - "cocoa/autofill/password_generation_popup_view_bridge.mm", - "cocoa/autofill/password_generation_popup_view_cocoa.h", - "cocoa/autofill/password_generation_popup_view_cocoa.mm", "cocoa/autofill/save_card_bubble_view_views.h", "cocoa/autofill/save_card_bubble_view_views.mm", "cocoa/background_gradient_view.h", @@ -111,6 +105,8 @@ split_static_library("ui") { "cocoa/bookmarks/bookmark_bubble_controller.mm", "cocoa/bookmarks/bookmark_bubble_observer_cocoa.h", "cocoa/bookmarks/bookmark_bubble_observer_cocoa.mm", + "cocoa/bookmarks/bookmark_bar_util.h", + "cocoa/bookmarks/bookmark_bar_util.mm", "cocoa/bookmarks/bookmark_button.h", "cocoa/bookmarks/bookmark_button.mm", "cocoa/bookmarks/bookmark_button_cell.h", @@ -148,8 +144,6 @@ split_static_library("ui") { "cocoa/browser_window_fullscreen_transition.mm", "cocoa/browser_window_layout.h", "cocoa/browser_window_layout.mm", - "cocoa/browser_window_touch_bar.h", - "cocoa/browser_window_touch_bar.mm", "cocoa/browser_window_utils.h", "cocoa/browser_window_utils.mm", "cocoa/bubble_anchor_helper.h", @@ -171,6 +165,8 @@ split_static_library("ui") { "cocoa/chrome_event_processing_window.mm", "cocoa/clickhold_button_cell.h", "cocoa/clickhold_button_cell.mm", + "cocoa/cocoa_util.h", + "cocoa/cocoa_util.mm", "cocoa/constrained_web_dialog_delegate_mac.mm", "cocoa/constrained_window/constrained_window_alert.h", "cocoa/constrained_window/constrained_window_alert.mm", @@ -310,6 +306,10 @@ split_static_library("ui") { "cocoa/fullscreen/fullscreen_toolbar_animation_controller.mm", "cocoa/fullscreen/fullscreen_toolbar_controller.h", "cocoa/fullscreen/fullscreen_toolbar_controller.mm", + "cocoa/fullscreen/fullscreen_toolbar_controller_cocoa.h", + "cocoa/fullscreen/fullscreen_toolbar_controller_cocoa.mm", + "cocoa/fullscreen/fullscreen_toolbar_controller_views.h", + "cocoa/fullscreen/fullscreen_toolbar_controller_views.mm", "cocoa/fullscreen/fullscreen_toolbar_mouse_tracker.h", "cocoa/fullscreen/fullscreen_toolbar_mouse_tracker.mm", "cocoa/fullscreen/fullscreen_toolbar_visibility_lock_controller.h", @@ -475,6 +475,7 @@ split_static_library("ui") { "cocoa/spinner_view.mm", "cocoa/ssl_client_certificate_selector_cocoa.h", "cocoa/ssl_client_certificate_selector_cocoa.mm", + "cocoa/spinner_util.h", "cocoa/status_bubble_mac.h", "cocoa/status_bubble_mac.mm", "cocoa/styled_text_field.h", @@ -541,6 +542,12 @@ split_static_library("ui") { "cocoa/toolbar/toolbar_controller.mm", "cocoa/toolbar/toolbar_view_cocoa.h", "cocoa/toolbar/toolbar_view_cocoa.mm", + "cocoa/touchbar/credit_card_autofill_touch_bar_controller.h", + "cocoa/touchbar/credit_card_autofill_touch_bar_controller.mm", + "cocoa/touchbar/suggested_text_touch_bar_controller.h", + "cocoa/touchbar/suggested_text_touch_bar_controller.mm", + "cocoa/touchbar/web_textfield_touch_bar_controller.h", + "cocoa/touchbar/web_textfield_touch_bar_controller.mm", "cocoa/translate/translate_bubble_bridge_views.h", "cocoa/translate/translate_bubble_bridge_views.mm", "cocoa/translate/translate_bubble_controller.h", @@ -554,16 +561,11 @@ split_static_library("ui") { "cocoa/view_resizer.h", "cocoa/web_contents_modal_dialog_manager_views_mac.h", "cocoa/web_contents_modal_dialog_manager_views_mac.mm", - "cocoa/web_textfield_touch_bar_controller.h", - "cocoa/web_textfield_touch_bar_controller.mm", # TODO(estade): this class should be deleted in favor of a combobox model. # See crbug.com/590850 "content_settings/content_setting_media_menu_model.cc", "content_settings/content_setting_media_menu_model.h", - "javascript_dialogs/javascript_dialog_cocoa.h", - "javascript_dialogs/javascript_dialog_cocoa.mm", - "javascript_dialogs/javascript_dialog_mac.cc", "proximity_auth/proximity_auth_error_bubble_stub.cc", "startup/session_crashed_infobar_delegate.cc", "startup/session_crashed_infobar_delegate.h", @@ -595,18 +597,13 @@ split_static_library("ui") { "autofill/credit_card_scanner_view.cc", "autofill/credit_card_scanner_view.h", "autofill/credit_card_scanner_view_delegate.h", - "autofill/password_generation_popup_controller.cc", - "autofill/password_generation_popup_controller.h", - "autofill/password_generation_popup_controller_impl.cc", - "autofill/password_generation_popup_controller_impl.h", - "autofill/password_generation_popup_observer.h", - "autofill/password_generation_popup_view.cc", - "autofill/password_generation_popup_view.h", "autofill/popup_constants.h", "autofill/popup_controller_common.cc", "autofill/popup_controller_common.h", "autofill/popup_view_common.cc", "autofill/popup_view_common.h", + "bloated_renderer/bloated_renderer_tab_helper.cc", + "bloated_renderer/bloated_renderer_tab_helper.h", "blocked_content/blocked_window_params.cc", "blocked_content/blocked_window_params.h", "blocked_content/list_item_position.cc", @@ -652,8 +649,6 @@ split_static_library("ui") { "find_bar/find_tab_helper.cc", "find_bar/find_tab_helper.h", "forced_reauthentication_dialog.h", - "history_ui.cc", - "history_ui.h", "interventions/framebust_block_message_delegate.cc", "interventions/framebust_block_message_delegate.h", "interventions/intervention_delegate.h", @@ -681,6 +676,13 @@ split_static_library("ui") { "passwords/manage_passwords_view_utils.h", "passwords/password_access_authenticator.cc", "passwords/password_access_authenticator.h", + "passwords/password_generation_popup_controller.cc", + "passwords/password_generation_popup_controller.h", + "passwords/password_generation_popup_controller_impl.cc", + "passwords/password_generation_popup_controller_impl.h", + "passwords/password_generation_popup_observer.h", + "passwords/password_generation_popup_view.cc", + "passwords/password_generation_popup_view.h", "passwords/password_manager_porter.cc", "passwords/password_manager_porter.h", "passwords/password_manager_presenter.cc", @@ -694,6 +696,8 @@ split_static_library("ui") { "profile_error_dialog.h", "protocol_dialog_delegate.h", "proximity_auth/proximity_auth_error_bubble.h", + "recently_audible_helper.cc", + "recently_audible_helper.h", "screen_capture_notification_ui.h", "search_engines/edit_search_engine_controller.cc", "search_engines/edit_search_engine_controller.h", @@ -739,6 +743,7 @@ split_static_library("ui") { "uninstall_browser_prompt.h", "view_ids.h", "web_contents_sizer.h", + "webauthn/authenticator_request_dialog.h", "webui/about_ui.cc", "webui/about_ui.h", "webui/chrome_web_ui_controller_factory.cc", @@ -851,6 +856,8 @@ split_static_library("ui") { "webui/version_handler.h", "webui/version_ui.cc", "webui/version_ui.h", + "webui/webui_util.cc", + "webui/webui_util.h", ] if (safe_browsing_mode == 1) { @@ -954,6 +961,7 @@ split_static_library("ui") { "//components/invalidation/impl", "//components/keyed_service/content", "//components/keyed_service/core", + "//components/language/core/browser", "//components/language/core/common", "//components/navigation_metrics", "//components/net_log", @@ -1008,6 +1016,7 @@ split_static_library("ui") { "//components/ukm:ukm", "//components/ukm/content", "//components/undo", + "//components/unified_consent", "//components/update_client", "//components/upload_list", "//components/url_formatter", @@ -1031,7 +1040,9 @@ split_static_library("ui") { "//ppapi/buildflags", "//printing/buildflags", "//rlz/buildflags", + "//services/identity/public/cpp", "//services/metrics/public/cpp:ukm_builders", + "//services/network/public/mojom", "//services/service_manager/runner/common", "//skia", "//storage/browser", @@ -1078,7 +1089,10 @@ split_static_library("ui") { } if (is_android) { - deps += [ "//chrome/browser/ui/webui/snippets_internals:mojo_bindings" ] + deps += [ + "//chrome/browser/ui/webui/eoc_internals:mojo_bindings", + "//chrome/browser/ui/webui/snippets_internals:mojo_bindings", + ] } if (!is_fuchsia) { @@ -1162,6 +1176,8 @@ split_static_library("ui") { "android/infobars/previews_infobar.h", "android/infobars/reader_mode_infobar.cc", "android/infobars/reader_mode_infobar.h", + "android/infobars/save_password_infobar.cc", + "android/infobars/save_password_infobar.h", "android/infobars/search_geolocation_disclosure_infobar.cc", "android/infobars/search_geolocation_disclosure_infobar.h", "android/infobars/simple_confirm_infobar_builder.cc", @@ -1216,6 +1232,10 @@ split_static_library("ui") { "android/view_android_helper.h", "browser_otr_state_android.cc", "screen_capture_notification_ui_stub.cc", + "webui/eoc_internals/eoc_internals_page_handler.cc", + "webui/eoc_internals/eoc_internals_page_handler.h", + "webui/eoc_internals/eoc_internals_ui.cc", + "webui/eoc_internals/eoc_internals_ui.h", "webui/offline/offline_internals_ui.cc", "webui/offline/offline_internals_ui.h", "webui/offline/offline_internals_ui_message_handler.cc", @@ -1231,9 +1251,9 @@ split_static_library("ui") { ] deps += [ "//chrome/browser:jni_headers", + "//components/embedder_support/android:web_contents_delegate", "//components/navigation_interception", "//components/subresource_filter/core/browser:browser", - "//components/web_contents_delegate_android", "//crypto:platform", "//device/usb/mojo", "//device/usb/public/cpp", @@ -1269,8 +1289,7 @@ split_static_library("ui") { "bookmarks/bookmark_drag_drop.h", "bookmarks/bookmark_tab_helper.cc", "bookmarks/bookmark_tab_helper.h", - "bookmarks/bookmark_tab_helper_delegate.cc", - "bookmarks/bookmark_tab_helper_delegate.h", + "bookmarks/bookmark_tab_helper_observer.h", "bookmarks/bookmark_utils_desktop.cc", "bookmarks/bookmark_utils_desktop.h", "bookmarks/enhanced_bookmark_key_service.cc", @@ -1376,6 +1395,7 @@ split_static_library("ui") { "media_router/cast_dialog_model.h", "media_router/cast_modes_with_media_sources.cc", "media_router/cast_modes_with_media_sources.h", + "media_router/cloud_services_dialog.h", "media_router/media_cast_mode.cc", "media_router/media_cast_mode.h", "media_router/media_router_dialog_controller_impl_base.cc", @@ -1449,6 +1469,7 @@ split_static_library("ui") { "search/new_tab_page_navigation_throttle.h", "search/ntp_user_data_logger.cc", "search/ntp_user_data_logger.h", + "search/ntp_user_data_types.h", "search/search_ipc_router.cc", "search/search_ipc_router.h", "search/search_ipc_router_policy_impl.cc", @@ -1472,6 +1493,8 @@ split_static_library("ui") { "startup/startup_tab_provider.cc", "startup/startup_tab_provider.h", "startup/startup_types.h", + "sync/browser_synced_tab_delegate.cc", + "sync/browser_synced_tab_delegate.h", "sync/browser_synced_window_delegate.cc", "sync/browser_synced_window_delegate.h", "sync/browser_synced_window_delegates_getter.cc", @@ -1533,7 +1556,6 @@ split_static_library("ui") { "toolbar/media_router_contextual_menu.h", "toolbar/recent_tabs_sub_menu_model.cc", "toolbar/recent_tabs_sub_menu_model.h", - "toolbar/toolbar_action_button_state.h", "toolbar/toolbar_action_view_controller.h", "toolbar/toolbar_action_view_delegate.h", "toolbar/toolbar_actions_bar.cc", @@ -1715,6 +1737,7 @@ split_static_library("ui") { deps += [ "//chrome/app/vector_icons", "//chrome/browser:theme_properties", + "//chrome/browser/apps/foundation/app_service/public/mojom", "//chrome/browser/media/router", "//chrome/browser/profile_resetter:profile_reset_report_proto", "//chrome/browser/resource_coordinator:tab_metrics_event_proto", @@ -1733,19 +1756,38 @@ split_static_library("ui") { "//mash/public/mojom", "//services/device/public/cpp:device_features", "//services/device/public/mojom", + "//services/identity/public/cpp", "//services/metrics/public/cpp:metrics_cpp", "//third_party/libaddressinput", "//third_party/libaddressinput:strings", "//ui/events", ] + + if (!toolkit_views) { + sources += [ "media_router/cloud_services_dialog.cc" ] + } + + if (enable_extensions) { + deps += [ + # TODO(loyso): Remove the first dependency. http://crbug.com/862049 + "//chrome/browser/web_applications", + "//chrome/browser/web_applications/components", + "//chrome/browser/web_applications/extensions", + ] + } + } + + if (enable_supervised_users && !is_android && !is_chromeos) { + sources += [ + "startup/supervised_users_deprecated_infobar_delegate.cc", + "startup/supervised_users_deprecated_infobar_delegate.h", + ] } if (is_chromeos) { assert(enable_extensions) assert(toolkit_views) sources += [ - "app_list/app_list_controller_impl.cc", - "app_list/app_list_controller_impl.h", "app_list/app_sync_ui_state.cc", "app_list/app_sync_ui_state.h", "app_list/app_sync_ui_state_factory.cc", @@ -1767,10 +1809,8 @@ split_static_library("ui") { "ash/ash_shell_init.h", "ash/ash_util.cc", "ash/ash_util.h", - "ash/assistant/assistant_context_util.cc", - "ash/assistant/assistant_context_util.h", - "ash/auto_connect_notifier.cc", - "ash/auto_connect_notifier.h", + "ash/browser_image_registrar.cc", + "ash/browser_image_registrar.h", "ash/cast_config_client_media_router.cc", "ash/cast_config_client_media_router.h", "ash/chrome_browser_main_extra_parts_ash.cc", @@ -1784,9 +1824,6 @@ split_static_library("ui") { "ash/chrome_screenshot_grabber.cc", "ash/chrome_screenshot_grabber.h", "ash/chrome_screenshot_grabber_test_observer.h", - "ash/chrome_shell_content_state.cc", - "ash/chrome_shell_content_state.h", - "ash/chrome_shell_content_state_chromeos.cc", "ash/chrome_shell_delegate.cc", "ash/chrome_shell_delegate.h", "ash/ime_controller_client.cc", @@ -1865,6 +1902,8 @@ split_static_library("ui") { "ash/session_controller_client.h", "ash/session_util.cc", "ash/session_util.h", + "ash/shell_state_client.cc", + "ash/shell_state_client.h", "ash/system_tray_client.cc", "ash/system_tray_client.h", "ash/tab_scrubber.cc", @@ -1897,6 +1936,8 @@ split_static_library("ui") { "views/extensions/request_file_system_dialog_view.h", "views/frame/browser_frame_ash.cc", "views/frame/browser_frame_ash.h", + "views/frame/browser_frame_mash.cc", + "views/frame/browser_frame_mash.h", "views/frame/browser_non_client_frame_view_ash.cc", "views/frame/browser_non_client_frame_view_ash.h", "views/frame/immersive_context_mus.cc", @@ -1921,12 +1962,19 @@ split_static_library("ui") { "views/select_file_dialog_extension_factory.cc", "views/select_file_dialog_extension_factory.h", "views/tabs/window_finder_ash.cc", - "views/touch_uma/touch_uma_ash.cc", "webui/chromeos/assistant_optin/assistant_optin_handler.cc", "webui/chromeos/assistant_optin/assistant_optin_handler.h", "webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h", "webui/chromeos/assistant_optin/assistant_optin_ui.cc", "webui/chromeos/assistant_optin/assistant_optin_ui.h", + "webui/chromeos/assistant_optin/confirm_reject_screen_handler.cc", + "webui/chromeos/assistant_optin/confirm_reject_screen_handler.h", + "webui/chromeos/assistant_optin/get_more_screen_handler.cc", + "webui/chromeos/assistant_optin/get_more_screen_handler.h", + "webui/chromeos/assistant_optin/ready_screen_handler.cc", + "webui/chromeos/assistant_optin/ready_screen_handler.h", + "webui/chromeos/assistant_optin/third_party_screen_handler.cc", + "webui/chromeos/assistant_optin/third_party_screen_handler.h", "webui/chromeos/assistant_optin/value_prop_screen_handler.cc", "webui/chromeos/assistant_optin/value_prop_screen_handler.h", "webui/chromeos/bluetooth_dialog_localized_strings_provider.cc", @@ -1957,6 +2005,8 @@ split_static_library("ui") { "webui/chromeos/keyboard_overlay_ui.h", "webui/chromeos/login/active_directory_password_change_screen_handler.cc", "webui/chromeos/login/active_directory_password_change_screen_handler.h", + "webui/chromeos/login/app_downloading_screen_handler.cc", + "webui/chromeos/login/app_downloading_screen_handler.h", "webui/chromeos/login/app_launch_splash_screen_handler.cc", "webui/chromeos/login/app_launch_splash_screen_handler.h", "webui/chromeos/login/arc_kiosk_splash_screen_handler.cc", @@ -1973,10 +2023,22 @@ split_static_library("ui") { "webui/chromeos/login/controller_pairing_screen_handler.h", "webui/chromeos/login/core_oobe_handler.cc", "webui/chromeos/login/core_oobe_handler.h", + "webui/chromeos/login/demo_preferences_screen_handler.cc", + "webui/chromeos/login/demo_preferences_screen_handler.h", "webui/chromeos/login/demo_setup_screen_handler.cc", "webui/chromeos/login/demo_setup_screen_handler.h", "webui/chromeos/login/device_disabled_screen_handler.cc", "webui/chromeos/login/device_disabled_screen_handler.h", + "webui/chromeos/login/discover/discover_handler.cc", + "webui/chromeos/login/discover/discover_handler.h", + "webui/chromeos/login/discover/discover_manager.cc", + "webui/chromeos/login/discover/discover_manager.h", + "webui/chromeos/login/discover/discover_ui.cc", + "webui/chromeos/login/discover/discover_ui.h", + "webui/chromeos/login/discover/modules/discover_module_welcome.cc", + "webui/chromeos/login/discover/modules/discover_module_welcome.h", + "webui/chromeos/login/discover_screen_handler.cc", + "webui/chromeos/login/discover_screen_handler.h", "webui/chromeos/login/enable_debugging_screen_handler.cc", "webui/chromeos/login/enable_debugging_screen_handler.h", "webui/chromeos/login/encryption_migration_screen_handler.cc", @@ -2002,12 +2064,8 @@ split_static_library("ui") { "webui/chromeos/login/l10n_util.cc", "webui/chromeos/login/l10n_util.h", "webui/chromeos/login/native_window_delegate.h", - "webui/chromeos/login/network_dropdown.cc", - "webui/chromeos/login/network_dropdown.h", "webui/chromeos/login/network_dropdown_handler.cc", "webui/chromeos/login/network_dropdown_handler.h", - "webui/chromeos/login/network_screen_handler.cc", - "webui/chromeos/login/network_screen_handler.h", "webui/chromeos/login/network_state_informer.cc", "webui/chromeos/login/network_state_informer.h", "webui/chromeos/login/oobe_display_chooser.cc", @@ -2042,6 +2100,8 @@ split_static_library("ui") { "webui/chromeos/login/voice_interaction_value_prop_screen_handler.h", "webui/chromeos/login/wait_for_container_ready_screen_handler.cc", "webui/chromeos/login/wait_for_container_ready_screen_handler.h", + "webui/chromeos/login/welcome_screen_handler.cc", + "webui/chromeos/login/welcome_screen_handler.h", "webui/chromeos/login/wrong_hwid_screen_handler.cc", "webui/chromeos/login/wrong_hwid_screen_handler.h", "webui/chromeos/mobile_setup_dialog.cc", @@ -2108,10 +2168,16 @@ split_static_library("ui") { "webui/settings/chromeos/google_assistant_handler.h", "webui/settings/chromeos/internet_handler.cc", "webui/settings/chromeos/internet_handler.h", + "webui/settings/chromeos/multidevice_handler.cc", + "webui/settings/chromeos/multidevice_handler.h", "webui/settings/chromeos/smb_handler.cc", "webui/settings/chromeos/smb_handler.h", "webui/settings/tts_handler.cc", "webui/settings/tts_handler.h", + "webui/signin/inline_login_handler_chromeos.cc", + "webui/signin/inline_login_handler_chromeos.h", + "webui/signin/inline_login_handler_dialog_chromeos.cc", + "webui/signin/inline_login_handler_dialog_chromeos.h", "webui/version_handler_chromeos.cc", "webui/version_handler_chromeos.h", "window_sizer/window_sizer_ash.cc", @@ -2119,7 +2185,6 @@ split_static_library("ui") { deps += [ "//ash", "//ash:ash_with_content", - "//ash/app_list/presenter", "//ash/components/shortcut_viewer:lib", "//ash/components/shortcut_viewer/public/mojom", "//ash/public/cpp", @@ -2152,6 +2217,7 @@ split_static_library("ui") { "//ui/chromeos", "//ui/chromeos/events", "//ui/compositor_extra", + "//ui/keyboard", "//ui/keyboard:mojom", ] allow_circular_includes_from += [ "//chrome/browser/chromeos" ] @@ -2176,8 +2242,16 @@ split_static_library("ui") { if (is_win || is_mac || is_desktop_linux || is_chromeos) { sources += [ + "signin_view_controller.cc", + "signin_view_controller.h", + "signin_view_controller_delegate.cc", + "signin_view_controller_delegate.h", "webui/discards/discards_ui.cc", "webui/discards/discards_ui.h", + "webui/signin/inline_login_handler.cc", + "webui/signin/inline_login_handler.h", + "webui/signin/inline_login_ui.cc", + "webui/signin/inline_login_ui.h", ] deps += [ "//ui/webui" ] } @@ -2189,10 +2263,6 @@ split_static_library("ui") { "avatar_button_error_controller_delegate.h", "external_protocol_dialog_delegate.cc", "external_protocol_dialog_delegate.h", - "signin_view_controller.cc", - "signin_view_controller.h", - "signin_view_controller_delegate.cc", - "signin_view_controller_delegate.h", "startup/default_browser_infobar_delegate.cc", "startup/default_browser_infobar_delegate.h", "startup/default_browser_prompt.cc", @@ -2226,12 +2296,8 @@ split_static_library("ui") { "webui/settings/settings_manage_profile_handler.h", "webui/settings/system_handler.cc", "webui/settings/system_handler.h", - "webui/signin/inline_login_handler.cc", - "webui/signin/inline_login_handler.h", "webui/signin/inline_login_handler_impl.cc", "webui/signin/inline_login_handler_impl.h", - "webui/signin/inline_login_ui.cc", - "webui/signin/inline_login_ui.h", "webui/signin/md_user_manager_ui.cc", "webui/signin/md_user_manager_ui.h", "webui/signin/signin_create_profile_handler.cc", @@ -2264,8 +2330,6 @@ split_static_library("ui") { sources += [ "views/profiles/avatar_button.cc", "views/profiles/avatar_button.h", - "views/profiles/avatar_toolbar_button.cc", - "views/profiles/avatar_toolbar_button.h", "views/profiles/user_manager_view.cc", "views/profiles/user_manager_view.h", ] @@ -2307,13 +2371,19 @@ split_static_library("ui") { "input_method/input_method_engine.h", "views/confirm_quit_bubble.cc", "views/confirm_quit_bubble.h", - "views/confirm_quit_bubble.h", "views/confirm_quit_bubble_controller.cc", "views/confirm_quit_bubble_controller.h", ] } } + if (is_mac || is_win || (is_linux && !is_chromeos)) { + sources += [ + "confirm_quit.cc", + "confirm_quit.h", + ] + } + if (is_mac) { sources += [ "browser_commands_mac.cc", @@ -2368,7 +2438,6 @@ split_static_library("ui") { "cocoa/chrome_style.h", "cocoa/color_chooser_mac.h", "cocoa/color_chooser_mac.mm", - "cocoa/confirm_quit.h", "cocoa/confirm_quit_panel_controller.h", "cocoa/confirm_quit_panel_controller.mm", "cocoa/dock_icon.h", @@ -2439,6 +2508,10 @@ split_static_library("ui") { "cocoa/tab_contents/web_drag_bookmark_handler_mac.mm", "cocoa/task_manager_mac.h", "cocoa/task_manager_mac.mm", + "cocoa/touchbar/browser_window_default_touch_bar.h", + "cocoa/touchbar/browser_window_default_touch_bar.mm", + "cocoa/touchbar/browser_window_touch_bar_controller.h", + "cocoa/touchbar/browser_window_touch_bar_controller.mm", "cocoa/ui_localizer.h", "cocoa/ui_localizer.mm", "cocoa/web_contents_modal_dialog_host_cocoa.h", @@ -2553,9 +2626,6 @@ split_static_library("ui") { "cocoa/simple_message_box_bridge_views.mm", "cocoa/subresource_filter/subresource_filter_bubble_controller.h", "cocoa/subresource_filter/subresource_filter_bubble_controller.mm", - "javascript_dialogs/javascript_dialog_cocoa.h", - "javascript_dialogs/javascript_dialog_cocoa.mm", - "javascript_dialogs/javascript_dialog_mac.cc", ] } } else { # non-Mac. @@ -2587,8 +2657,6 @@ split_static_library("ui") { "views/color_chooser_dialog.cc", "views/color_chooser_dialog.h", "views/color_chooser_win.cc", - "views/conflicting_module_view_win.cc", - "views/conflicting_module_view_win.h", "views/critical_notification_bubble_view.cc", "views/critical_notification_bubble_view.h", "views/desktop_ios_promotion/desktop_ios_promotion_bubble_view.cc", @@ -2629,12 +2697,10 @@ split_static_library("ui") { "views/try_chrome_dialog_win/try_chrome_dialog.h", "views/uninstall_view.cc", "views/uninstall_view.h", - "webui/conflicts_handler.cc", - "webui/conflicts_handler.h", - "webui/conflicts_ui.cc", - "webui/conflicts_ui.h", - "webui/module_database_conflicts_handler.cc", - "webui/module_database_conflicts_handler.h", + "webui/conflicts/conflicts_handler.cc", + "webui/conflicts/conflicts_handler.h", + "webui/conflicts/conflicts_ui.cc", + "webui/conflicts/conflicts_ui.h", "webui/settings/chrome_cleanup_handler.cc", "webui/settings/chrome_cleanup_handler.h", "webui/settings_utils_win.cc", @@ -2766,6 +2832,9 @@ split_static_library("ui") { if (toolkit_views) { sources += [ + "autofill/local_card_migration_bubble.h", + "autofill/local_card_migration_bubble_controller_impl.cc", + "autofill/local_card_migration_bubble_controller_impl.h", "autofill/save_card_bubble_controller_impl.cc", "autofill/save_card_bubble_controller_impl.h", "autofill/save_card_bubble_view.h", @@ -2801,6 +2870,8 @@ split_static_library("ui") { "views/autofill/autofill_popup_view_views.h", "views/autofill/card_unmask_prompt_views.cc", "views/autofill/card_unmask_prompt_views.h", + "views/autofill/local_card_migration_bubble_views.cc", + "views/autofill/local_card_migration_bubble_views.h", "views/autofill/save_card_bubble_views.cc", "views/autofill/save_card_bubble_views.h", "views/autofill/view_util.cc", @@ -2886,6 +2957,8 @@ split_static_library("ui") { "views/login_handler_views.cc", "views/login_view.cc", "views/login_view.h", + "views/overlay/close_image_button.cc", + "views/overlay/close_image_button.h", "views/overlay/overlay_window_views.cc", "views/overlay/overlay_window_views.h", "views/page_info/chosen_object_view.cc", @@ -2979,10 +3052,25 @@ split_static_library("ui") { "views/task_manager_view.h", "views/toolbar/toolbar_actions_bar_bubble_views.cc", "views/toolbar/toolbar_actions_bar_bubble_views.h", + "views/touch_uma/touch_uma.cc", + "views/touch_uma/touch_uma.h", "views/translate/translate_bubble_view.cc", "views/translate/translate_bubble_view.h", "views/update_recommended_message_box.cc", "views/update_recommended_message_box.h", + "views/webauthn/authenticator_request_dialog_view.cc", + "views/webauthn/authenticator_request_dialog_view.h", + "views/webauthn/authenticator_request_sheet_view.cc", + "views/webauthn/authenticator_request_sheet_view.h", + "views/webauthn/authenticator_transport_selector_sheet_view.cc", + "views/webauthn/authenticator_transport_selector_sheet_view.h", + "views/webauthn/sheet_view_factory.cc", + "views/webauthn/sheet_view_factory.h", + "views/webauthn/transport_list_view.cc", + "views/webauthn/transport_list_view.h", + "webauthn/authenticator_request_sheet_model.h", + "webauthn/sheet_models.cc", + "webauthn/sheet_models.h", ] deps += [ "//chrome/browser/ui/views", @@ -3037,11 +3125,10 @@ split_static_library("ui") { if (!is_mac || mac_views_browser) { sources += [ - "javascript_dialogs/javascript_dialog.cc", "views/accessibility/invert_bubble_view.cc", "views/accessibility/invert_bubble_view.h", - "views/autofill/password_generation_popup_view_views.cc", - "views/autofill/password_generation_popup_view_views.h", + "views/autofill/local_card_migration_icon_view.cc", + "views/autofill/local_card_migration_icon_view.h", "views/autofill/save_card_icon_view.cc", "views/autofill/save_card_icon_view.h", "views/bookmarks/bookmark_bar_instructions_view.cc", @@ -3168,12 +3255,18 @@ split_static_library("ui") { "views/location_bar/selected_keyword_view.h", "views/location_bar/star_view.cc", "views/location_bar/star_view.h", - "views/location_bar/zoom_view.cc", - "views/location_bar/zoom_view.h", + "views/media_router/cast_dialog_metrics.cc", + "views/media_router/cast_dialog_metrics.h", + "views/media_router/cast_dialog_no_sinks_view.cc", + "views/media_router/cast_dialog_no_sinks_view.h", "views/media_router/cast_dialog_sink_button.cc", "views/media_router/cast_dialog_sink_button.h", "views/media_router/cast_dialog_view.cc", "views/media_router/cast_dialog_view.h", + "views/media_router/cloud_services_dialog_view.cc", + "views/media_router/cloud_services_dialog_view.h", + "views/media_router/media_remoting_dialog_view.cc", + "views/media_router/media_remoting_dialog_view.h", "views/media_router/media_router_dialog_controller_views.cc", "views/media_router/media_router_dialog_controller_views.h", "views/media_router/media_router_views_ui.cc", @@ -3203,13 +3296,21 @@ split_static_library("ui") { "views/page_action/page_action_icon_container_view.h", "views/page_action/page_action_icon_view.cc", "views/page_action/page_action_icon_view.h", + "views/page_action/zoom_view.cc", + "views/page_action/zoom_view.h", "views/passwords/manage_passwords_icon_views.cc", "views/passwords/manage_passwords_icon_views.h", + "views/passwords/password_generation_popup_view_views.cc", + "views/passwords/password_generation_popup_view_views.h", "views/permission_bubble/chooser_bubble_ui_views.cc", "views/permission_bubble/permission_prompt_impl_views.cc", "views/profiles/avatar_button_style.h", + "views/profiles/avatar_toolbar_button.cc", + "views/profiles/avatar_toolbar_button.h", "views/profiles/profile_indicator_icon.cc", "views/profiles/profile_indicator_icon.h", + "views/profiles/signin_view_controller_delegate_views.cc", + "views/profiles/signin_view_controller_delegate_views.h", "views/proximity_auth/proximity_auth_error_bubble_view.cc", "views/proximity_auth/proximity_auth_error_bubble_view.h", "views/sad_tab_view.cc", @@ -3278,7 +3379,6 @@ split_static_library("ui") { "views/toolbar/toolbar_ink_drop_util.h", "views/toolbar/toolbar_view.cc", "views/toolbar/toolbar_view.h", - "views/touch_uma/touch_uma.h", "views/translate/translate_icon_view.cc", "views/translate/translate_icon_view.h", "views/webshare/webshare_target_picker_view.cc", @@ -3318,11 +3418,8 @@ split_static_library("ui") { "views/policy/enterprise_startup_dialog_view.h", "views/profiles/forced_reauthentication_dialog_view.cc", "views/profiles/forced_reauthentication_dialog_view.h", - "views/profiles/signin_view_controller_delegate_views.cc", - "views/profiles/signin_view_controller_delegate_views.h", "views/sync/one_click_signin_dialog_view.cc", "views/sync/one_click_signin_dialog_view.h", - "views/touch_uma/touch_uma.cc", ] } @@ -3409,6 +3506,13 @@ split_static_library("ui") { if (is_chrome_branded) { deps += [ "//chrome/browser/ui/media_router/internal/vector_icons" ] } + + if (is_win) { + sources += [ + "views/feature_promos/bookmark_bar_promo_bubble_view.cc", + "views/feature_promos/bookmark_bar_promo_bubble_view.h", + ] + } } if (use_aura) { @@ -3470,8 +3574,6 @@ split_static_library("ui") { ] deps += [ "//ui/aura", - "//ui/keyboard", - "//ui/keyboard:resources", "//ui/wm", ] @@ -3513,6 +3615,8 @@ split_static_library("ui") { "app_list/extension_app_item.h", "app_list/extension_app_model_builder.cc", "app_list/extension_app_model_builder.h", + "app_list/extension_app_utils.cc", + "app_list/extension_app_utils.h", "app_list/extension_uninstaller.cc", "app_list/extension_uninstaller.h", "app_list/search/answer_card/answer_card_contents.cc", @@ -3589,9 +3693,9 @@ split_static_library("ui") { deps += [ # TODO(wutao): Put new icons resources to ash/public/cpp/vector_icons/ # when UX provides them. + "//ash/app_list", "//ash/public/cpp/app_list/vector_icons", "//ash/resources/vector_icons", - "//ui/app_list", "//ui/views/mus/remote_view:remote_view_provider", ] @@ -3617,8 +3721,11 @@ split_static_library("ui") { "app_list/arc/arc_app_model_builder.h", "app_list/arc/arc_app_utils.cc", "app_list/arc/arc_app_utils.h", + "app_list/arc/arc_data_removal_dialog.h", "app_list/arc/arc_default_app_list.cc", "app_list/arc/arc_default_app_list.h", + "app_list/arc/arc_fast_app_reinstall_starter.cc", + "app_list/arc/arc_fast_app_reinstall_starter.h", "app_list/arc/arc_package_sync_data_type_controller.cc", "app_list/arc/arc_package_sync_data_type_controller.h", "app_list/arc/arc_package_syncable_service.cc", @@ -3675,6 +3782,8 @@ split_static_library("ui") { "ash/launcher/arc_launcher_context_menu.h", "ash/launcher/arc_shelf_spinner_item_controller.cc", "ash/launcher/arc_shelf_spinner_item_controller.h", + "ash/launcher/crostini_app_display.cc", + "ash/launcher/crostini_app_display.h", "ash/launcher/crostini_app_window_shelf_controller.cc", "ash/launcher/crostini_app_window_shelf_controller.h", "ash/launcher/crostini_shelf_context_menu.cc", @@ -3692,6 +3801,7 @@ split_static_library("ui") { "ash/launcher/shelf_spinner_item_controller.cc", "ash/launcher/shelf_spinner_item_controller.h", "views/arc_app_dialog_view.cc", + "views/arc_data_removal_dialog_view.cc", "views/crostini/crostini_installer_view.cc", "views/crostini/crostini_installer_view.h", "views/crostini/crostini_uninstaller_view.cc", @@ -3709,26 +3819,27 @@ split_static_library("ui") { ] sources += [ - "ash/assistant/assistant_card_renderer.cc", - "ash/assistant/assistant_card_renderer.h", "ash/assistant/assistant_client.cc", "ash/assistant/assistant_client.h", - "ash/assistant/assistant_context.cc", - "ash/assistant/assistant_context.h", + "ash/assistant/assistant_context_util.cc", + "ash/assistant/assistant_context_util.h", "ash/assistant/assistant_image_downloader.cc", "ash/assistant/assistant_image_downloader.h", - "ash/assistant/platform_audio_input_host.cc", - "ash/assistant/platform_audio_input_host.h", + "ash/assistant/assistant_setup.cc", + "ash/assistant/assistant_setup.h", + "ash/assistant/device_actions.cc", + "ash/assistant/device_actions.h", + "ash/assistant/web_contents_manager.cc", + "ash/assistant/web_contents_manager.h", ] } if (enable_extensions) { deps += [ "//apps", - "//chrome/browser/apps", + "//chrome/browser/apps/platform_apps", "//chrome/browser/extensions", "//chrome/common/extensions/api", - "//chrome/common/extensions/api:api_registration", "//components/drive", "//components/guest_view/browser", "//extensions/browser", @@ -3737,7 +3848,7 @@ split_static_library("ui") { "//extensions/strings", ] allow_circular_includes_from += [ - "//chrome/browser/apps", + "//chrome/browser/apps/platform_apps", "//chrome/browser/extensions", ] sources += [ @@ -3821,6 +3932,10 @@ split_static_library("ui") { deps += [ "//components/nacl/browser" ] } + if (is_win && is_chrome_branded) { + deps += [ "//components/nux_google_apps:nux_google_apps_feature" ] + } + if (enable_plugins) { sources += [ "hung_plugin_tab_helper.cc", @@ -3848,6 +3963,8 @@ split_static_library("ui") { } if (enable_print_preview) { sources += [ + "webui/print_preview/cloud_printer_handler.cc", + "webui/print_preview/cloud_printer_handler.h", "webui/print_preview/extension_printer_handler.cc", "webui/print_preview/extension_printer_handler.h", "webui/print_preview/pdf_printer_handler.cc", @@ -3950,6 +4067,8 @@ static_library("test_support") { "cocoa/test/run_loop_testing.mm", "cocoa/test/scoped_force_rtl_mac.h", "cocoa/test/scoped_force_rtl_mac.mm", + "content_settings/fake_owner.cc", + "content_settings/fake_owner.h", "find_bar/find_bar_host_unittest_util.h", "login/login_handler_test_utils.cc", "login/login_handler_test_utils.h", @@ -3986,7 +4105,10 @@ static_library("test_support") { ] if (toolkit_views) { - deps += [ "//ui/views:test_support" ] + deps += [ + "//components/constrained_window:constrained_window", + "//ui/views:test_support", + ] sources += [ "../../test/views/scoped_macviews_browser_mode.cc", "../../test/views/scoped_macviews_browser_mode.h", @@ -3994,6 +4116,8 @@ static_library("test_support") { "views/payments/test_chrome_payment_request_delegate.cc", "views/payments/test_chrome_payment_request_delegate.h", "views/toolbar/browser_action_test_util_views_mac.mm", + "views/webauthn/authenticator_request_dialog_view_test_api.cc", + "views/webauthn/authenticator_request_dialog_view_test_api.h", ] if (is_mac) { sources += [ diff --git a/chromium/chrome/browser/ui/libgtkui/BUILD.gn b/chromium/chrome/browser/ui/libgtkui/BUILD.gn index ccbed52a0a3..de40baffe51 100644 --- a/chromium/chrome/browser/ui/libgtkui/BUILD.gn +++ b/chromium/chrome/browser/ui/libgtkui/BUILD.gn @@ -86,6 +86,7 @@ template("libgtkui") { deps = invoker.deps + [ "//chrome/browser/ui/views", + "//chrome/common:constants", "//base", "//base:i18n", "//base/third_party/dynamic_annotations", @@ -96,6 +97,7 @@ template("libgtkui") { "//chrome:strings", "//chrome/app:command_ids", "//chrome/app/theme:theme_resources", + "//components/prefs", "//components/resources", "//content/public/browser", "//printing", @@ -110,6 +112,7 @@ template("libgtkui") { "//ui/base/ime", "//ui/display", "//ui/events", + "//ui/events:dom_keyboard_layout", "//ui/events:dom_keycode_converter", "//ui/events:events_base", "//ui/events/platform/x11", diff --git a/chromium/chrome/browser/ui/webui/about_ui.cc b/chromium/chrome/browser/ui/webui/about_ui.cc index a54cb8f97e1..9ca0978f164 100644 --- a/chromium/chrome/browser/ui/webui/about_ui.cc +++ b/chromium/chrome/browser/ui/webui/about_ui.cc @@ -75,10 +75,6 @@ #include "chrome/browser/ui/webui/theme_source.h" #endif -#if defined(OS_WIN) -#include "chrome/browser/win/enumerate_modules_model.h" -#endif - #if defined(OS_CHROMEOS) #include "chrome/browser/browser_process_platform_part_chromeos.h" #include "chrome/browser/chromeos/customization/customization_document.h" @@ -326,66 +322,6 @@ std::string ChromeURLs() { return html; } -// AboutDnsHandler bounces the request back to the IO thread to collect -// the DNS information. -class AboutDnsHandler : public base::RefCountedThreadSafe<AboutDnsHandler> { - public: - static void Start(Profile* profile, - const content::URLDataSource::GotDataCallback& callback) { - scoped_refptr<AboutDnsHandler> handler( - new AboutDnsHandler(profile, callback)); - handler->StartOnUIThread(); - } - - private: - friend class base::RefCountedThreadSafe<AboutDnsHandler>; - - AboutDnsHandler(Profile* profile, - const content::URLDataSource::GotDataCallback& callback) - : profile_(profile), - callback_(callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - } - - virtual ~AboutDnsHandler() {} - - // Calls FinishOnUIThread() on completion. - void StartOnUIThread() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - chrome_browser_net::Predictor* predictor = profile_->GetNetworkPredictor(); - BrowserThread::PostTask( - BrowserThread::IO, FROM_HERE, - base::BindOnce(&AboutDnsHandler::StartOnIOThread, this, predictor)); - } - - void StartOnIOThread(chrome_browser_net::Predictor* predictor) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - - std::string data; - AppendHeader(&data, 0, "About DNS"); - AppendBody(&data); - chrome_browser_net::Predictor::PredictorGetHtmlInfo(predictor, &data); - AppendFooter(&data); - - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::BindOnce(&AboutDnsHandler::FinishOnUIThread, this, data)); - } - - void FinishOnUIThread(const std::string& data) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - std::string data_copy(data); - callback_.Run(base::RefCountedString::TakeString(&data_copy)); - } - - Profile* profile_; - - // Callback to run with the response. - content::URLDataSource::GotDataCallback callback_; - - DISALLOW_COPY_AND_ASSIGN(AboutDnsHandler); -}; - #if defined(OS_LINUX) || defined(OS_OPENBSD) std::string AboutLinuxProxyConfig() { std::string data; @@ -441,9 +377,6 @@ void AboutUIHTMLSource::StartDataRequest( .GetRawDataResource(idr) .as_string(); } - } else if (source_name_ == chrome::kChromeUIDNSHost) { - AboutDnsHandler::Start(profile(), callback); - return; #if defined(OS_LINUX) || defined(OS_OPENBSD) } else if (source_name_ == chrome::kChromeUILinuxProxyConfigHost) { response = AboutLinuxProxyConfig(); 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 e2fe3585859..d804302e241 100644 --- a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc +++ b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc @@ -30,8 +30,6 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" -class ExtensionService; - using content::BrowserThread; /////////////////////////////////////////////////////////////////////////////// @@ -42,7 +40,7 @@ AppLauncherPageUI::AppLauncherPageUI(content::WebUI* web_ui) web_ui->OverrideTitle(l10n_util::GetStringUTF16(IDS_APP_LAUNCHER_TAB_TITLE)); if (!GetProfile()->IsOffTheRecord()) { - ExtensionService* service = + extensions::ExtensionService* service = extensions::ExtensionSystem::Get(GetProfile())->extension_service(); // We should not be launched without an ExtensionService. DCHECK(service); 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 efe43ca5e6a..d789c144fe7 100644 --- a/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc @@ -61,21 +61,23 @@ class TestSyncService : public browser_sync::TestProfileSyncService { explicit TestSyncService(Profile* profile) : browser_sync::TestProfileSyncService( CreateProfileSyncServiceParamsForTest(profile)), - sync_active_(true) {} + state_(State::ACTIVE) {} - bool IsSyncActive() const override { return sync_active_; } + State GetState() const override { return state_; } syncer::ModelTypeSet GetActiveDataTypes() const override { return syncer::ModelTypeSet::All(); } - void SetSyncActive(bool active) { - sync_active_ = active; + void SetState(State state) { + state_ = state; NotifyObservers(); } private: - bool sync_active_; + State state_; + + DISALLOW_COPY_AND_ASSIGN(TestSyncService); }; class BrowsingHistoryHandlerWithWebUIForTesting @@ -91,6 +93,8 @@ class BrowsingHistoryHandlerWithWebUIForTesting private: base::SimpleTestClock test_clock_; + + DISALLOW_COPY_AND_ASSIGN(BrowsingHistoryHandlerWithWebUIForTesting); }; } // namespace @@ -143,11 +147,8 @@ class BrowsingHistoryHandlerTest : public ::testing::Test { static std::unique_ptr<KeyedService> BuildFakeWebHistoryService( content::BrowserContext* context) { - Profile* profile = static_cast<TestingProfile*>(context); - std::unique_ptr<history::FakeWebHistoryService> service = - std::make_unique<history::FakeWebHistoryService>( - profile->GetRequestContext()); + std::make_unique<history::FakeWebHistoryService>(); service->SetupFakeResponse(true /* success */, net::HTTP_OK); return std::move(service); } @@ -168,7 +169,7 @@ TEST_F(BrowsingHistoryHandlerTest, ObservingWebHistoryDeletions) { // BrowsingHistoryHandler is informed about WebHistoryService history // deletions. { - sync_service()->SetSyncActive(true); + sync_service()->SetState(syncer::SyncService::State::ACTIVE); BrowsingHistoryHandlerWithWebUIForTesting handler(web_ui()); handler.RegisterMessages(); @@ -183,10 +184,10 @@ TEST_F(BrowsingHistoryHandlerTest, ObservingWebHistoryDeletions) { // BrowsingHistoryHandler will be informed about WebHistoryService deletions // even if history sync is activated later. { - sync_service()->SetSyncActive(false); + sync_service()->SetState(syncer::SyncService::State::INITIALIZING); BrowsingHistoryHandlerWithWebUIForTesting handler(web_ui()); handler.RegisterMessages(); - sync_service()->SetSyncActive(true); + sync_service()->SetState(syncer::SyncService::State::ACTIVE); web_history_service()->ExpireHistoryBetween( std::set<GURL>(), base::Time(), base::Time::Max(), callback, @@ -199,7 +200,7 @@ TEST_F(BrowsingHistoryHandlerTest, ObservingWebHistoryDeletions) { // BrowsingHistoryHandler does not fire historyDeleted while a web history // delete request is happening. { - sync_service()->SetSyncActive(true); + sync_service()->SetState(syncer::SyncService::State::ACTIVE); BrowsingHistoryHandlerWithWebUIForTesting handler(web_ui()); handler.RegisterMessages(); @@ -221,7 +222,7 @@ TEST_F(BrowsingHistoryHandlerTest, ObservingWebHistoryDeletions) { // deletions. The WebHistoryService object still exists (because it's a // BrowserContextKeyedService), but is not visible to BrowsingHistoryHandler. { - sync_service()->SetSyncActive(false); + sync_service()->SetState(syncer::SyncService::State::INITIALIZING); BrowsingHistoryHandlerWithWebUIForTesting handler(web_ui()); handler.RegisterMessages(); diff --git a/chromium/chrome/browser/ui/webui/certificates_handler.cc b/chromium/chrome/browser/ui/webui/certificates_handler.cc index 53fafce0499..71beb63980b 100644 --- a/chromium/chrome/browser/ui/webui/certificates_handler.cc +++ b/chromium/chrome/browser/ui/webui/certificates_handler.cc @@ -52,22 +52,22 @@ using base::UTF8ToUTF16; namespace { // Field names for communicating certificate info to JS. -static const char kEmailField[] = "email"; -static const char kExtractableField[] = "extractable"; -static const char kKeyField[] = "id"; -static const char kNameField[] = "name"; -static const char kObjSignField[] = "objSign"; -static const char kPolicyField[] = "policy"; -static const char kReadonlyField[] = "readonly"; -static const char kSslField[] = "ssl"; -static const char kSubnodesField[] = "subnodes"; -static const char kUntrustedField[] = "untrusted"; +static const char kCertificatesHandlerEmailField[] = "email"; +static const char kCertificatesHandlerExtractableField[] = "extractable"; +static const char kCertificatesHandlerKeyField[] = "id"; +static const char kCertificatesHandlerNameField[] = "name"; +static const char kCertificatesHandlerObjSignField[] = "objSign"; +static const char kCertificatesHandlerPolicyField[] = "policy"; +static const char kCertificatesHandlerReadonlyField[] = "readonly"; +static const char kCertificatesHandlerSslField[] = "ssl"; +static const char kCertificatesHandlerSubnodesField[] = "subnodes"; +static const char kCertificatesHandlerUntrustedField[] = "untrusted"; // Field names for communicating erros to JS. -static const char kCertificateErrors[] = "certificateErrors"; -static const char kErrorDescription[] = "description"; -static const char kErrorField[] = "error"; -static const char kErrorTitle[] = "title"; +static const char kCertificatesHandlerCertificateErrors[] = "certificateErrors"; +static const char kCertificatesHandlerErrorDescription[] = "description"; +static const char kCertificatesHandlerErrorField[] = "error"; +static const char kCertificatesHandlerErrorTitle[] = "title"; // Enumeration of different callers of SelectFile. (Start counting at 1 so // if SelectFile is accidentally called with params=NULL it won't match any.) @@ -97,8 +97,8 @@ struct DictionaryIdComparator { DCHECK(b_is_dictionary); base::string16 a_str; base::string16 b_str; - a_dict->GetString(kNameField, &a_str); - b_dict->GetString(kNameField, &b_str); + a_dict->GetString(kCertificatesHandlerNameField, &a_str); + b_dict->GetString(kCertificatesHandlerNameField, &b_str); if (collator_ == NULL) return a_str < b_str; return base::i18n::CompareString16WithCollator(*collator_, a_str, b_str) == @@ -496,13 +496,13 @@ void CertificatesHandler::HandleGetCATrust(const base::ListValue* args) { std::unique_ptr<base::DictionaryValue> ca_trust_info( new base::DictionaryValue); ca_trust_info->SetBoolean( - kSslField, + kCertificatesHandlerSslField, static_cast<bool>(trust_bits & net::NSSCertDatabase::TRUSTED_SSL)); ca_trust_info->SetBoolean( - kEmailField, + kCertificatesHandlerEmailField, static_cast<bool>(trust_bits & net::NSSCertDatabase::TRUSTED_EMAIL)); ca_trust_info->SetBoolean( - kObjSignField, + kCertificatesHandlerObjSignField, static_cast<bool>(trust_bits & net::NSSCertDatabase::TRUSTED_OBJ_SIGN)); ResolveCallback(*ca_trust_info); } @@ -1045,8 +1045,8 @@ void CertificatesHandler::PopulateTree( i != map.end(); ++i) { // Populate first level (org name). std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); - dict->SetString(kKeyField, OrgNameToId(i->first)); - dict->SetString(kNameField, i->first); + dict->SetString(kCertificatesHandlerKeyField, OrgNameToId(i->first)); + dict->SetString(kCertificatesHandlerNameField, i->first); // Populate second level (certs). auto subnodes = std::make_unique<base::ListValue>(); @@ -1056,33 +1056,35 @@ void CertificatesHandler::PopulateTree( std::unique_ptr<base::DictionaryValue> cert_dict( new base::DictionaryValue); CERTCertificate* cert = org_cert_it->get(); - cert_dict->SetString(kKeyField, cert_id_map_->CertToId(cert)); + cert_dict->SetString(kCertificatesHandlerKeyField, + cert_id_map_->CertToId(cert)); cert_dict->SetString( - kNameField, certificate_manager_model_->GetColumnText( - cert, CertificateManagerModel::COL_SUBJECT_NAME)); + kCertificatesHandlerNameField, + certificate_manager_model_->GetColumnText( + cert, CertificateManagerModel::COL_SUBJECT_NAME)); cert_dict->SetBoolean( - kReadonlyField, + kCertificatesHandlerReadonlyField, certificate_manager_model_->cert_db()->IsReadOnly(cert)); // Policy-installed certificates with web trust are trusted. bool policy_trusted = IsPolicyInstalledWithWebTrust(web_trust_certs, cert); cert_dict->SetBoolean( - kUntrustedField, + kCertificatesHandlerUntrustedField, !policy_trusted && certificate_manager_model_->cert_db()->IsUntrusted(cert)); - cert_dict->SetBoolean(kPolicyField, policy_trusted); + cert_dict->SetBoolean(kCertificatesHandlerPolicyField, policy_trusted); // TODO(hshi): This should be determined by testing for PKCS #11 // CKA_EXTRACTABLE attribute. We may need to use the NSS function // PK11_ReadRawAttribute to do that. cert_dict->SetBoolean( - kExtractableField, + kCertificatesHandlerExtractableField, !certificate_manager_model_->IsHardwareBacked(cert)); // TODO(mattm): Other columns. subnodes->Append(std::move(cert_dict)); } std::sort(subnodes->begin(), subnodes->end(), comparator); - dict->Set(kSubnodesField, std::move(subnodes)); + dict->Set(kCertificatesHandlerSubnodesField, std::move(subnodes)); nodes->Append(std::move(dict)); } std::sort(nodes->begin(), nodes->end(), comparator); @@ -1106,8 +1108,8 @@ void CertificatesHandler::RejectCallback(const base::Value& response) { void CertificatesHandler::RejectCallbackWithError(const std::string& title, const std::string& error) { std::unique_ptr<base::DictionaryValue> error_info(new base::DictionaryValue); - error_info->SetString(kErrorTitle, title); - error_info->SetString(kErrorDescription, error); + error_info->SetString(kCertificatesHandlerErrorTitle, title); + error_info->SetString(kCertificatesHandlerErrorDescription, error); RejectCallback(*error_info); } @@ -1130,16 +1132,19 @@ void CertificatesHandler::RejectCallbackWithImportError( for (size_t i = 0; i < not_imported.size(); ++i) { const net::NSSCertDatabase::ImportCertFailure& failure = not_imported[i]; std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); - dict->SetString(kNameField, x509_certificate_model::GetSubjectDisplayName( - failure.certificate.get())); - dict->SetString(kErrorField, NetErrorToString(failure.net_error)); + dict->SetString(kCertificatesHandlerNameField, + x509_certificate_model::GetSubjectDisplayName( + failure.certificate.get())); + dict->SetString(kCertificatesHandlerErrorField, + NetErrorToString(failure.net_error)); cert_error_list->Append(std::move(dict)); } std::unique_ptr<base::DictionaryValue> error_info(new base::DictionaryValue); - error_info->SetString(kErrorTitle, title); - error_info->SetString(kErrorDescription, error); - error_info->Set(kCertificateErrors, std::move(cert_error_list)); + error_info->SetString(kCertificatesHandlerErrorTitle, title); + error_info->SetString(kCertificatesHandlerErrorDescription, error); + error_info->Set(kCertificatesHandlerCertificateErrors, + std::move(cert_error_list)); RejectCallback(*error_info); } 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 4ad61d2d8ca..be8b073e7bd 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 @@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/feature_list.h" #include "base/location.h" +#include "base/memory/ptr_util.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "chrome/browser/about_flags.h" @@ -21,7 +22,6 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/search/suggestions/suggestions_ui.h" -#include "chrome/browser/ui/history_ui.h" #include "chrome/browser/ui/webui/about_ui.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h" #include "chrome/browser/ui/webui/components_ui.h" @@ -74,6 +74,7 @@ #include "components/favicon/core/favicon_service.h" #include "components/favicon_base/favicon_util.h" #include "components/favicon_base/select_favicon_frames.h" +#include "components/grit/components_scaled_resources.h" #include "components/history/core/browser/history_types.h" #include "components/nacl/common/buildflags.h" #include "components/prefs/pref_service.h" @@ -91,6 +92,7 @@ #include "media/media_buildflags.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" +#include "ui/base/resource/resource_bundle.h" #include "ui/gfx/favicon_size.h" #include "ui/web_dialogs/web_dialog_ui.h" #include "url/gurl.h" @@ -113,6 +115,7 @@ #endif #if defined(OS_ANDROID) +#include "chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.h" #include "chrome/browser/ui/webui/offline/offline_internals_ui.h" #include "chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.h" #include "chrome/browser/ui/webui/webapks_ui.h" @@ -130,8 +133,10 @@ #if defined(OS_CHROMEOS) #include "base/sys_info.h" +#include "chrome/browser/chromeos/device_sync/device_sync_client_factory.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_factory.h" +#include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h" #include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h" #include "chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.h" #include "chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.h" @@ -150,6 +155,8 @@ #include "chrome/browser/ui/webui/chromeos/slow_trace_ui.h" #include "chrome/browser/ui/webui/chromeos/slow_ui.h" #include "chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_ui.h" +#include "chrome/browser/ui/webui/signin/inline_login_ui.h" +#include "chromeos/chromeos_features.h" #include "chromeos/components/proximity_auth/webui/proximity_auth_ui.h" #include "chromeos/components/proximity_auth/webui/url_constants.h" #endif @@ -173,7 +180,7 @@ #endif #if defined(OS_WIN) -#include "chrome/browser/ui/webui/conflicts_ui.h" +#include "chrome/browser/ui/webui/conflicts/conflicts_ui.h" #include "chrome/browser/ui/webui/set_as_default_browser_ui_win.h" #include "chrome/browser/ui/webui/welcome_win10_ui.h" #endif @@ -197,7 +204,6 @@ #if BUILDFLAG(ENABLE_EXTENSIONS) #include "chrome/browser/extensions/extension_web_ui.h" #include "chrome/browser/ui/webui/extensions/extensions_ui.h" -#include "chrome/common/chrome_features.h" #include "chrome/common/extensions/extension_constants.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" @@ -256,10 +262,23 @@ WebUIController* NewWebUI<proximity_auth::ProximityAuthUI>(WebUI* web_ui, const GURL& url) { content::BrowserContext* browser_context = web_ui->GetWebContents()->GetBrowserContext(); + // TODO(crbug.com/848956): Only pass DeviceSyncClient once Smart Lock has + // fully migrated to the DeviceSync API. return new proximity_auth::ProximityAuthUI( web_ui, - chromeos::EasyUnlockServiceFactory::GetForBrowserContext(browser_context) - ->proximity_auth_client()); + base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi) + ? nullptr + : chromeos::EasyUnlockServiceFactory::GetForBrowserContext( + browser_context) + ->proximity_auth_client(), + base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi) + ? chromeos::device_sync::DeviceSyncClientFactory::GetForProfile( + Profile::FromBrowserContext(browser_context)) + : nullptr, + base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi) + ? chromeos::secure_channel::SecureChannelClientProvider::GetInstance() + ->GetClient() + : nullptr); } #endif @@ -294,8 +313,7 @@ WebUIController* NewWebUI<WelcomeWin10UI>(WebUI* web_ui, const GURL& url) { bool IsAboutUI(const GURL& url) { return (url.host_piece() == chrome::kChromeUIChromeURLsHost || - url.host_piece() == chrome::kChromeUICreditsHost || - url.host_piece() == chrome::kChromeUIDNSHost + url.host_piece() == chrome::kChromeUICreditsHost #if !defined(OS_ANDROID) || url.host_piece() == chrome::kChromeUITermsHost #endif @@ -404,13 +422,15 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, #if !defined(OS_CHROMEOS) // AppLauncherPage is not needed on Android or ChromeOS. if (url.host_piece() == chrome::kChromeUIAppLauncherPageHost && profile && - extensions::ExtensionSystem::Get(profile)->extension_service()) { + extensions::ExtensionSystem::Get(profile)->extension_service() && + !profile->IsGuestSession()) { return &NewWebUI<AppLauncherPageUI>; } #endif // defined(OS_CHROMEOS) if (profile->IsGuestSession() && - (url.host_piece() == chrome::kChromeUIBookmarksHost || + (url.host_piece() == chrome::kChromeUIAppLauncherPageHost || + url.host_piece() == chrome::kChromeUIBookmarksHost || url.host_piece() == chrome::kChromeUIHistoryHost || url.host_piece() == chrome::kChromeUIExtensionsHost)) { return &NewWebUI<PageNotAvailableForGuestUI>; @@ -437,6 +457,9 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<SyncFileSystemInternalsUI>; if (url.host_piece() == chrome::kChromeUISystemInfoHost) return &NewWebUI<SystemInfoUI>; + // Inline login UI is available on all platforms except Android. + if (url.host_piece() == chrome::kChromeUIChromeSigninHost) + return &NewWebUI<InlineLoginUI>; #endif // !defined(OS_ANDROID) #if defined(OS_WIN) if (url.host_piece() == chrome::kChromeUIConflictsHost) @@ -492,6 +515,9 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, #endif // !defined(OFFICIAL_BUILD) #endif // defined(OS_CHROMEOS) #if defined(OS_ANDROID) + if (url.host_piece() == chrome::kChromeUIEocInternalsHost && + !profile->IsOffTheRecord()) + return &NewWebUI<EocInternalsUI>; if (url.host_piece() == chrome::kChromeUIOfflineInternalsHost) return &NewWebUI<OfflineInternalsUI>; if (url.host_piece() == chrome::kChromeUISnippetsInternalsHost && @@ -512,8 +538,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<InspectUI>; #endif #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) - if (url.host_piece() == chrome::kChromeUIChromeSigninHost) - return &NewWebUI<InlineLoginUI>; if (url.host_piece() == chrome::kChromeUIMdUserManagerHost) return &NewWebUI<MDUserManagerUI>; if (url.host_piece() == chrome::kChromeUISigninErrorHost && @@ -675,18 +699,19 @@ bool ChromeWebUIControllerFactory::UseWebUIBindingsForURL( return UseWebUIForURL(browser_context, url); } -WebUIController* ChromeWebUIControllerFactory::CreateWebUIControllerForURL( +std::unique_ptr<WebUIController> +ChromeWebUIControllerFactory::CreateWebUIControllerForURL( WebUI* web_ui, const GURL& url) const { Profile* profile = Profile::FromWebUI(web_ui); WebUIFactoryFunction function = GetWebUIFactoryFunction(web_ui, profile, url); if (!function) - return NULL; + return nullptr; - if (web_ui->GetWebContents()->GetMainFrame() != nullptr) + if (web_ui->GetWebContents()->GetMainFrame()) webui::LogWebUIUrl(url); - return (*function)(web_ui, url); + return base::WrapUnique((*function)(web_ui, url)); } void ChromeWebUIControllerFactory::GetFaviconForURL( @@ -755,6 +780,26 @@ ChromeWebUIControllerFactory* ChromeWebUIControllerFactory::GetInstance() { return base::Singleton<ChromeWebUIControllerFactory>::get(); } +// static +bool ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests( + const url::Origin& origin) { + // Whitelist to work around exceptional cases. + // + // If you are adding a new host to this list, please file a corresponding bug + // to track its removal. See https://crbug.com/829412 for the metabug. + return +#if BUILDFLAG(ENABLE_PRINT_PREVIEW) + // https://crbug.com/829414 + origin.host() == chrome::kChromeUIPrintHost || +#endif + // https://crbug.com/831812 + origin.host() == chrome::kChromeUISyncConfirmationHost || + // https://crbug.com/831813 + origin.host() == chrome::kChromeUIInspectHost || + // https://crbug.com/859345 + origin.host() == chrome::kChromeUIDownloadsHost; +} + ChromeWebUIControllerFactory::ChromeWebUIControllerFactory() { } @@ -788,9 +833,10 @@ base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( if (page_url.host_piece() == chrome::kChromeUIFlagsHost) return FlagsUI::GetFaviconResourceBytes(scale_factor); - // TODO(dbeam): does this actually need to exist on all platforms? - if (page_url.host_piece() == chrome::kChromeUIHistoryHost) - return history_ui::GetFaviconResourceBytes(scale_factor); + if (page_url.host_piece() == chrome::kChromeUIHistoryHost) { + return ui::ResourceBundle::GetSharedInstance() + .LoadDataResourceBytesForScale(IDR_HISTORY_FAVICON, scale_factor); + } #if !defined(OS_ANDROID) #if !defined(OS_CHROMEOS) 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 29064b60b68..b0a3fa7365b 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 @@ -18,15 +18,29 @@ namespace base { class RefCountedMemory; } +namespace url { +class Origin; +} + class ChromeWebUIControllerFactory : public content::WebUIControllerFactory { public: + static ChromeWebUIControllerFactory* GetInstance(); + + // http://crbug.com/829412 + // Renderers with WebUI bindings shouldn't make http(s) requests for security + // reasons (e.g. to avoid malicious responses being able to run code in + // priviliged renderers). Fix these webui's to make requests through C++ + // code instead. + static bool IsWebUIAllowedToMakeNetworkRequests(const url::Origin& origin); + + // content::WebUIControllerFactory: content::WebUI::TypeID GetWebUIType(content::BrowserContext* browser_context, const GURL& url) const override; bool UseWebUIForURL(content::BrowserContext* browser_context, const GURL& url) const override; bool UseWebUIBindingsForURL(content::BrowserContext* browser_context, const GURL& url) const override; - content::WebUIController* CreateWebUIControllerForURL( + std::unique_ptr<content::WebUIController> CreateWebUIControllerForURL( content::WebUI* web_ui, const GURL& url) const override; @@ -38,8 +52,6 @@ class ChromeWebUIControllerFactory : public content::WebUIControllerFactory { const std::vector<int>& desired_sizes_in_pixel, const favicon_base::FaviconResultsCallback& callback) const; - static ChromeWebUIControllerFactory* GetInstance(); - protected: ChromeWebUIControllerFactory(); ~ChromeWebUIControllerFactory() override; diff --git a/chromium/chrome/browser/ui/webui/chromeos/OWNERS b/chromium/chrome/browser/ui/webui/chromeos/OWNERS index 7de2d5dcaf9..b63e5656fa7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/OWNERS +++ b/chromium/chrome/browser/ui/webui/chromeos/OWNERS @@ -6,5 +6,4 @@ xiyuan@chromium.org zelidrag@chromium.org per-file network*=stevenjb@chromium.org -per-file drive_internals_ui.*=hashimoto@chromium.org -per-file drive_internals_ui.*=kinaba@chromium.org +per-file drive_internals_ui.*=file://ui/file_manager/OWNERS diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_handler.cc index 2dc463e4606..8ad3c438e86 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_handler.cc @@ -5,25 +5,214 @@ #include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_handler.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.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 "services/service_manager/public/cpp/connector.h" +#include "ui/base/l10n/l10n_util.h" + +namespace chromeos { namespace { constexpr char kJsScreenPath[] = "assistantOptin"; -} // namespace +// Construct SettingsUiSelector for the ConsentFlow UI. +assistant::SettingsUiSelector GetSettingsUiSelector() { + assistant::SettingsUiSelector selector; + assistant::ConsentFlowUiSelector* consent_flow_ui = + selector.mutable_consent_flow_ui_selector(); + consent_flow_ui->set_flow_id(assistant::ActivityControlSettingsUiSelector:: + ASSISTANT_SUW_ONBOARDING_ON_CHROME_OS); + selector.set_email_opt_in(true); + return selector; +} -namespace chromeos { +// Construct SettingsUiUpdate for user opt-in. +assistant::SettingsUiUpdate GetSettingsUiUpdate( + const std::string& consent_token) { + assistant::SettingsUiUpdate update; + assistant::ConsentFlowUiUpdate* consent_flow_update = + update.mutable_consent_flow_ui_update(); + consent_flow_update->set_flow_id( + assistant::ActivityControlSettingsUiSelector:: + ASSISTANT_SUW_ONBOARDING_ON_CHROME_OS); + consent_flow_update->set_consent_token(consent_token); + + return update; +} + +// Construct SettingsUiUpdate for email opt-in. +assistant::SettingsUiUpdate GetEmailOptInUpdate(bool opted_in) { + assistant::SettingsUiUpdate update; + assistant::EmailOptInUpdate* email_optin_update = + update.mutable_email_opt_in_update(); + email_optin_update->set_email_opt_in_update_state( + opted_in ? assistant::EmailOptInUpdate::OPT_IN + : assistant::EmailOptInUpdate::OPT_OUT); + + return update; +} + +using SettingZippyList = google::protobuf::RepeatedPtrField< + assistant::ClassicActivityControlUiTexts::SettingZippy>; +// Helper method to create zippy data. +base::ListValue CreateZippyData(const SettingZippyList& zippy_list) { + base::ListValue zippy_data; + for (auto& setting_zippy : zippy_list) { + base::DictionaryValue data; + data.SetString("title", setting_zippy.title()); + if (setting_zippy.description_paragraph_size()) { + data.SetString("description", setting_zippy.description_paragraph(0)); + } + if (setting_zippy.additional_info_paragraph_size()) { + data.SetString("additionalInfo", + setting_zippy.additional_info_paragraph(0)); + } + data.SetString("iconUri", setting_zippy.icon_uri()); + zippy_data.GetList().push_back(std::move(data)); + } + return zippy_data; +} + +// Helper method to create disclosure data. +base::ListValue CreateDisclosureData(const SettingZippyList& disclosure_list) { + base::ListValue disclosure_data; + for (auto& disclosure : disclosure_list) { + base::DictionaryValue data; + data.SetString("title", disclosure.title()); + if (disclosure.description_paragraph_size()) { + data.SetString("description", disclosure.description_paragraph(0)); + } + if (disclosure.additional_info_paragraph_size()) { + data.SetString("additionalInfo", disclosure.additional_info_paragraph(0)); + } + data.SetString("iconUri", disclosure.icon_uri()); + disclosure_data.GetList().push_back(std::move(data)); + } + return disclosure_data; +} + +// Helper method to create get more screen data. +base::ListValue CreateGetMoreData( + bool email_optin_needed, + const assistant::EmailOptInUi& email_optin_ui) { + base::ListValue get_more_data; + + // Process screen context data. + base::DictionaryValue context_data; + context_data.SetString( + "title", l10n_util::GetStringUTF16(IDS_ASSISTANT_SCREEN_CONTEXT_TITLE)); + context_data.SetString("description", l10n_util::GetStringUTF16( + IDS_ASSISTANT_SCREEN_CONTEXT_DESC)); + context_data.SetBoolean("defaultEnabled", true); + context_data.SetString("iconUri", + "https://www.gstatic.com/images/icons/material/system/" + "2x/laptop_chromebook_grey600_24dp.png"); + get_more_data.GetList().push_back(std::move(context_data)); + + // Process email optin data. + if (email_optin_needed) { + base::DictionaryValue data; + data.SetString("title", email_optin_ui.title()); + data.SetString("description", email_optin_ui.description()); + data.SetBoolean("defaultEnabled", email_optin_ui.default_enabled()); + data.SetString("iconUri", email_optin_ui.icon_uri()); + get_more_data.GetList().push_back(std::move(data)); + } + + return get_more_data; +} + +// Get string constants for settings ui. +base::DictionaryValue GetSettingsUiStrings( + const assistant::SettingsUi& settings_ui, + bool activity_control_needed) { + auto consent_ui = settings_ui.consent_flow_ui().consent_ui(); + auto confirm_reject_ui = consent_ui.activity_control_confirm_reject_ui(); + auto activity_control_ui = consent_ui.activity_control_ui(); + auto third_party_disclosure_ui = consent_ui.third_party_disclosure_ui(); + base::DictionaryValue dictionary; + + // Add activity controll string constants. + if (activity_control_needed) { + dictionary.SetString("valuePropIdentity", activity_control_ui.identity()); + if (activity_control_ui.intro_text_paragraph_size()) { + dictionary.SetString("valuePropIntro", + activity_control_ui.intro_text_paragraph(0)); + } + if (activity_control_ui.footer_paragraph_size()) { + dictionary.SetString("valuePropFooter", + activity_control_ui.footer_paragraph(0)); + } + dictionary.SetString("valuePropNextButton", + consent_ui.accept_button_text()); + dictionary.SetString("valuePropSkipButton", + consent_ui.reject_button_text()); + } + + // Add confirm reject screen string constants. + // TODO(updowndota) Use remote strings after server bug fixed. + dictionary.SetString( + "confirmRejectTitle", + l10n_util::GetStringUTF16(IDS_ASSISTANT_CONFIRM_SCREEN_TITLE)); + dictionary.SetString( + "confirmRejectAcceptTitle", + l10n_util::GetStringUTF16(IDS_ASSISTANT_CONFIRM_SCREEN_ACCEPT_TITLE)); + dictionary.SetString( + "confirmRejectAcceptMessage", + l10n_util::GetStringUTF16(IDS_ASSISTANT_CONFIRM_SCREEN_ACCEPT_MESSAGE)); + dictionary.SetString( + "confirmRejectAcceptMessageExpanded", + l10n_util::GetStringUTF16( + IDS_ASSISTANT_CONFIRM_SCREEN_ACCEPT_MESSAGE_EXPANDED)); + dictionary.SetString( + "confirmRejectRejectTitle", + l10n_util::GetStringUTF16(IDS_ASSISTANT_CONFIRM_SCREEN_REJECT_TITLE)); + dictionary.SetString( + "confirmRejectRejectMessage", + l10n_util::GetStringUTF16(IDS_ASSISTANT_CONFIRM_SCREEN_REJECT_MESSAGE)); + dictionary.SetString( + "confirmRejectContinueButton", + l10n_util::GetStringUTF16(IDS_ASSISTANT_CONTINUE_BUTTON)); + + // Add third party string constants. + dictionary.SetString( + "thirdPartyTitle", + l10n_util::GetStringUTF16(IDS_ASSISTANT_THIRD_PARTY_SCREEN_TITLE)); + dictionary.SetString( + "thirdPartyContinueButton", + l10n_util::GetStringUTF16(IDS_ASSISTANT_CONTINUE_BUTTON)); + dictionary.SetString("thirdPartyFooter", consent_ui.tos_pp_links()); + + // Add get more screen string constants. + dictionary.SetString( + "getMoreTitle", + l10n_util::GetStringUTF16(IDS_ASSISTANT_GET_MORE_SCREEN_TITLE)); + dictionary.SetString( + "getMoreContinueButton", + l10n_util::GetStringUTF16(IDS_ASSISTANT_CONTINUE_BUTTON)); + + return dictionary; +} + +} // namespace AssistantOptInHandler::AssistantOptInHandler( JSCallsContainer* js_calls_container) - : BaseWebUIHandler(js_calls_container) { + : BaseWebUIHandler(js_calls_container), weak_factory_(this) { DCHECK(js_calls_container); set_call_js_prefix(kJsScreenPath); } -AssistantOptInHandler::~AssistantOptInHandler() = default; +AssistantOptInHandler::~AssistantOptInHandler() { + arc::VoiceInteractionControllerClient::Get()->RemoveObserver(this); +} void AssistantOptInHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) {} @@ -32,14 +221,154 @@ void AssistantOptInHandler::RegisterMessages() { AddCallback("initialized", &AssistantOptInHandler::HandleInitialized); } -void AssistantOptInHandler::Initialize() {} +void AssistantOptInHandler::Initialize() { + if (arc::VoiceInteractionControllerClient::Get()->voice_interaction_state() != + ash::mojom::VoiceInteractionState::RUNNING) { + arc::VoiceInteractionControllerClient::Get()->AddObserver(this); + } else { + BindAssistantSettingsManager(); + } +} + +void AssistantOptInHandler::ShowNextScreen() { + CallJSOrDefer("showNextScreen"); +} + +void AssistantOptInHandler::OnActivityControlOptInResult(bool opted_in) { + if (opted_in) { + settings_manager_->UpdateSettings( + GetSettingsUiUpdate(consent_token_).SerializeAsString(), + base::BindOnce(&AssistantOptInHandler::OnUpdateSettingsResponse, + weak_factory_.GetWeakPtr())); + } else { + PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs(); + prefs->SetBoolean(arc::prefs::kVoiceInteractionActivityControlAccepted, + false); + prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, true); + prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, true); + CallJSOrDefer("closeDialog"); + } +} + +void AssistantOptInHandler::OnEmailOptInResult(bool opted_in) { + if (!email_optin_needed_) { + DCHECK(!opted_in); + ShowNextScreen(); + return; + } + + settings_manager_->UpdateSettings( + GetEmailOptInUpdate(opted_in).SerializeAsString(), + base::BindOnce(&AssistantOptInHandler::OnUpdateSettingsResponse, + weak_factory_.GetWeakPtr())); +} + +void AssistantOptInHandler::OnStateChanged( + ash::mojom::VoiceInteractionState state) { + if (state == ash::mojom::VoiceInteractionState::RUNNING) + BindAssistantSettingsManager(); +} + +void AssistantOptInHandler::BindAssistantSettingsManager() { + if (settings_manager_.is_bound()) + return; + + // Set up settings mojom. + service_manager::Connector* connector = + content::BrowserContext::GetConnectorFor(Profile::FromWebUI(web_ui())); + connector->BindInterface(assistant::mojom::kServiceName, + mojo::MakeRequest(&settings_manager_)); + + SendGetSettingsRequest(); +} + +void AssistantOptInHandler::SendGetSettingsRequest() { + assistant::SettingsUiSelector selector = GetSettingsUiSelector(); + settings_manager_->GetSettings( + selector.SerializeAsString(), + base::BindOnce(&AssistantOptInHandler::OnGetSettingsResponse, + weak_factory_.GetWeakPtr())); +} void AssistantOptInHandler::ReloadContent(const base::DictionaryValue& dict) { CallJSOrDefer("reloadContent", dict); } -void AssistantOptInHandler::AddSettingZippy(const base::ListValue& data) { - CallJSOrDefer("addSettingZippy", data); +void AssistantOptInHandler::AddSettingZippy(const std::string& type, + const base::ListValue& data) { + CallJSOrDefer("addSettingZippy", type, data); +} + +void AssistantOptInHandler::OnGetSettingsResponse(const std::string& settings) { + assistant::SettingsUi settings_ui; + settings_ui.ParseFromString(settings); + + DCHECK(settings_ui.has_consent_flow_ui()); + auto consent_ui = settings_ui.consent_flow_ui().consent_ui(); + auto activity_control_ui = consent_ui.activity_control_ui(); + auto confirm_reject_ui = consent_ui.activity_control_confirm_reject_ui(); + auto third_party_disclosure_ui = consent_ui.third_party_disclosure_ui(); + + consent_token_ = activity_control_ui.consent_token(); + + // Process activity control data. + if (!activity_control_ui.setting_zippy().size()) { + // No need to consent. Move to the next screen. + activity_control_needed_ = false; + PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs(); + prefs->SetBoolean(arc::prefs::kVoiceInteractionActivityControlAccepted, + true); + prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, true); + prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, true); + ShowNextScreen(); + } else { + AddSettingZippy("settings", + CreateZippyData(activity_control_ui.setting_zippy())); + } + + // Process third party disclosure data. + AddSettingZippy("disclosure", CreateDisclosureData( + third_party_disclosure_ui.disclosures())); + + // Process get more data. + email_optin_needed_ = settings_ui.has_email_opt_in_ui() && + settings_ui.email_opt_in_ui().has_title(); + AddSettingZippy("get-more", CreateGetMoreData(email_optin_needed_, + settings_ui.email_opt_in_ui())); + + // Pass string constants dictionary. + ReloadContent(GetSettingsUiStrings(settings_ui, activity_control_needed_)); +} + +void AssistantOptInHandler::OnUpdateSettingsResponse( + const std::string& result) { + assistant::SettingsUiUpdateResult ui_result; + ui_result.ParseFromString(result); + + if (ui_result.has_consent_flow_update_result()) { + if (ui_result.consent_flow_update_result().update_status() != + assistant::ConsentFlowUiUpdateResult::SUCCESS) { + // TODO(updowndta): Handle consent update failure. + LOG(ERROR) << "Consent udpate error."; + } else if (activity_control_needed_) { + activity_control_needed_ = false; + PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs(); + prefs->SetBoolean(arc::prefs::kVoiceInteractionActivityControlAccepted, + true); + prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, true); + prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, true); + } + } + + if (ui_result.has_email_opt_in_update_result()) { + if (ui_result.email_opt_in_update_result().update_status() != + assistant::EmailOptInUpdateResult::SUCCESS) { + // TODO(updowndta): Handle email optin update failure. + LOG(ERROR) << "Email OptIn udpate error."; + } + } + + ShowNextScreen(); } void AssistantOptInHandler::HandleInitialized() { diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_handler.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_handler.h index 39e21c37443..5f3dd0e5187 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_handler.h @@ -9,11 +9,15 @@ #include <string> #include "base/macros.h" +#include "chrome/browser/chromeos/arc/voice_interaction/voice_interaction_controller_client.h" #include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" +#include "chromeos/services/assistant/public/mojom/settings.mojom.h" namespace chromeos { -class AssistantOptInHandler : public BaseWebUIHandler { +class AssistantOptInHandler + : public BaseWebUIHandler, + public arc::VoiceInteractionControllerClient::Observer { public: explicit AssistantOptInHandler(JSCallsContainer* js_calls_container); ~AssistantOptInHandler() override; @@ -24,14 +28,46 @@ class AssistantOptInHandler : public BaseWebUIHandler { void RegisterMessages() override; void Initialize() override; + // Send messages to the page. + void ShowNextScreen(); + + // Handle user opt-in result. + void OnActivityControlOptInResult(bool opted_in); + void OnEmailOptInResult(bool opted_in); + + private: + // arc::VoiceInteractionControllerClient::Observer overrides + void OnStateChanged(ash::mojom::VoiceInteractionState state) override; + + // Connect to assistant settings manager. + void BindAssistantSettingsManager(); + + // Send GetSettings request for the opt-in UI. + void SendGetSettingsRequest(); + // Send message and consent data to the page. void ReloadContent(const base::DictionaryValue& dict); - void AddSettingZippy(const base::ListValue& data); + void AddSettingZippy(const std::string& type, const base::ListValue& data); + + // Handle response from the settings manager. + void OnGetSettingsResponse(const std::string& settings); + void OnUpdateSettingsResponse(const std::string& settings); - private: // Handler for JS WebUI message. void HandleInitialized(); + // Consent token used to complete the opt-in. + std::string consent_token_; + + // Whether activity control is needed for user. + bool activity_control_needed_ = true; + + // Whether email optin is needed for user. + bool email_optin_needed_ = false; + + assistant::mojom::AssistantSettingsManagerPtr settings_manager_; + base::WeakPtrFactory<AssistantOptInHandler> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(AssistantOptInHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h index d406d9e3326..40986386f49 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h @@ -14,6 +14,11 @@ namespace chromeos { enum class AssistantOptInScreenExitCode { VALUE_PROP_SKIPPED = 0, VALUE_PROP_ACCEPTED = 1, + THIRD_PARTY_CONTINUED = 2, + EMAIL_OPTED_IN = 3, + EMAIL_OPTED_OUT = 4, + CONFIRM_ACCEPTED = 5, + CONFIRM_REJECTED = 6, EXIT_CODES_COUNT }; 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 4d30bdadddd..754e9533c04 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 @@ -10,17 +10,18 @@ #include "base/macros.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/confirm_reject_screen_handler.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/get_more_screen_handler.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/ready_screen_handler.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/third_party_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.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/prefs/pref_service.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" namespace chromeos { @@ -31,30 +32,6 @@ bool is_active = false; constexpr int kAssistantOptInDialogWidth = 576; constexpr int kAssistantOptInDialogHeight = 480; -// Construct SettingsUiSelector for the ConsentFlow UI. -assistant::SettingsUiSelector GetSettingsUiSelector() { - assistant::SettingsUiSelector selector; - assistant::ConsentFlowUiSelector* consent_flow_ui = - selector.mutable_consent_flow_ui_selector(); - consent_flow_ui->set_flow_id(assistant::ActivityControlSettingsUiSelector:: - ASSISTANT_SUW_ONBOARDING_ON_CHROME_OS); - return selector; -} - -// Construct SettingsUiUpdate for user opt-in. -assistant::SettingsUiUpdate GetSettingsUiUpdate( - const std::string& consent_token) { - assistant::SettingsUiUpdate update; - assistant::ConsentFlowUiUpdate* consent_flow_update = - update.mutable_consent_flow_ui_update(); - consent_flow_update->set_flow_id( - assistant::ActivityControlSettingsUiSelector:: - ASSISTANT_SUW_ONBOARDING_ON_CHROME_OS); - consent_flow_update->set_consent_token(consent_token); - - return update; -} - } // namespace AssistantOptInUI::AssistantOptInUI(content::WebUI* web_ui) @@ -65,13 +42,21 @@ AssistantOptInUI::AssistantOptInUI(content::WebUI* web_ui) js_calls_container_ = std::make_unique<JSCallsContainer>(); - auto base_handler = + auto assistant_handler = std::make_unique<AssistantOptInHandler>(js_calls_container_.get()); - assistant_handler_ = base_handler.get(); - AddScreenHandler(std::move(base_handler)); + assistant_handler_ = assistant_handler.get(); + AddScreenHandler(std::move(assistant_handler)); + assistant_handler_->Initialize(); AddScreenHandler(std::make_unique<ValuePropScreenHandler>( base::BindOnce(&AssistantOptInUI::OnExit, weak_factory_.GetWeakPtr()))); + AddScreenHandler(std::make_unique<ConfirmRejectScreenHandler>( + base::BindOnce(&AssistantOptInUI::OnExit, weak_factory_.GetWeakPtr()))); + AddScreenHandler(std::make_unique<ThirdPartyScreenHandler>( + base::BindOnce(&AssistantOptInUI::OnExit, weak_factory_.GetWeakPtr()))); + AddScreenHandler(std::make_unique<GetMoreScreenHandler>( + base::BindOnce(&AssistantOptInUI::OnExit, weak_factory_.GetWeakPtr()))); + AddScreenHandler(std::make_unique<ReadyScreenHandler>()); base::DictionaryValue localized_strings; for (auto* handler : screen_handlers_) @@ -80,44 +65,12 @@ AssistantOptInUI::AssistantOptInUI(content::WebUI* web_ui) source->SetJsonPath("strings.js"); source->AddResourcePath("assistant_optin.js", IDR_ASSISTANT_OPTIN_JS); + source->AddResourcePath("assistant_logo.png", IDR_ASSISTANT_LOGO_PNG); source->SetDefaultResource(IDR_ASSISTANT_OPTIN_HTML); content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); - - if (arc::VoiceInteractionControllerClient::Get()->voice_interaction_state() != - ash::mojom::VoiceInteractionState::RUNNING) { - arc::VoiceInteractionControllerClient::Get()->AddObserver(this); - } else { - Initialize(); - } -} - -AssistantOptInUI::~AssistantOptInUI() { - arc::VoiceInteractionControllerClient::Get()->RemoveObserver(this); } -void AssistantOptInUI::OnStateChanged(ash::mojom::VoiceInteractionState state) { - if (state == ash::mojom::VoiceInteractionState::RUNNING) - Initialize(); -} - -void AssistantOptInUI::Initialize() { - if (settings_manager_.is_bound()) - return; - - // Set up settings mojom. - Profile* const profile = Profile::FromWebUI(web_ui()); - service_manager::Connector* connector = - content::BrowserContext::GetConnectorFor(profile); - connector->BindInterface(assistant::mojom::kServiceName, - mojo::MakeRequest(&settings_manager_)); - - // Send GetSettings request for the ConsentFlow UI. - assistant::SettingsUiSelector selector = GetSettingsUiSelector(); - settings_manager_->GetSettings( - selector.SerializeAsString(), - base::BindOnce(&AssistantOptInUI::OnGetSettingsResponse, - weak_factory_.GetWeakPtr())); -} +AssistantOptInUI::~AssistantOptInUI() = default; void AssistantOptInUI::AddScreenHandler( std::unique_ptr<BaseWebUIHandler> handler) { @@ -126,92 +79,40 @@ void AssistantOptInUI::AddScreenHandler( } void AssistantOptInUI::OnExit(AssistantOptInScreenExitCode exit_code) { - PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs(); switch (exit_code) { case AssistantOptInScreenExitCode::VALUE_PROP_SKIPPED: - prefs->SetBoolean(arc::prefs::kArcVoiceInteractionValuePropAccepted, - false); - prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, false); - CloseDialog(nullptr); + assistant_handler_->ShowNextScreen(); break; case AssistantOptInScreenExitCode::VALUE_PROP_ACCEPTED: - // Send the update to complete user opt-in. - settings_manager_->UpdateSettings( - GetSettingsUiUpdate(consent_token_).SerializeAsString(), - base::BindOnce(&AssistantOptInUI::OnUpdateSettingsResponse, - weak_factory_.GetWeakPtr())); + assistant_handler_->OnActivityControlOptInResult(true); + break; + case AssistantOptInScreenExitCode::CONFIRM_ACCEPTED: + assistant_handler_->OnActivityControlOptInResult(true); + break; + case AssistantOptInScreenExitCode::CONFIRM_REJECTED: + assistant_handler_->OnActivityControlOptInResult(false); + break; + case AssistantOptInScreenExitCode::THIRD_PARTY_CONTINUED: + assistant_handler_->ShowNextScreen(); + break; + case AssistantOptInScreenExitCode::EMAIL_OPTED_IN: + assistant_handler_->OnEmailOptInResult(true); + break; + case AssistantOptInScreenExitCode::EMAIL_OPTED_OUT: + assistant_handler_->OnEmailOptInResult(false); break; default: NOTREACHED(); } } -void AssistantOptInUI::OnGetSettingsResponse(const std::string& settings) { - assistant::SettingsUi settings_ui; - assistant::ConsentFlowUi::ConsentUi::ActivityControlUi activity_control_ui; - settings_ui.ParseFromString(settings); - - DCHECK(settings_ui.has_consent_flow_ui()); - activity_control_ui = - settings_ui.consent_flow_ui().consent_ui().activity_control_ui(); - consent_token_ = activity_control_ui.consent_token(); - - base::ListValue zippy_data; - if (activity_control_ui.setting_zippy().size() == 0) { - // No need to consent. Close the dialog for now. - CloseDialog(nullptr); - return; - } - for (auto& setting_zippy : activity_control_ui.setting_zippy()) { - base::DictionaryValue data; - data.SetString("title", setting_zippy.title()); - data.SetString("description", setting_zippy.description_paragraph(0)); - data.SetString("additionalInfo", - setting_zippy.additional_info_paragraph(0)); - data.SetString("iconUri", setting_zippy.icon_uri()); - zippy_data.GetList().push_back(std::move(data)); - } - assistant_handler_->AddSettingZippy(zippy_data); - - base::DictionaryValue dictionary; - dictionary.SetString("valuePropIntro", - activity_control_ui.intro_text_paragraph(0)); - dictionary.SetString("valuePropIdentity", activity_control_ui.identity()); - dictionary.SetString("valuePropFooter", - activity_control_ui.footer_paragraph(0)); - dictionary.SetString( - "valuePropNextButton", - settings_ui.consent_flow_ui().consent_ui().accept_button_text()); - dictionary.SetString( - "valuePropSkipButton", - settings_ui.consent_flow_ui().consent_ui().reject_button_text()); - assistant_handler_->ReloadContent(dictionary); -} - -void AssistantOptInUI::OnUpdateSettingsResponse(const std::string& result) { - assistant::SettingsUiUpdateResult ui_result; - ui_result.ParseFromString(result); - - DCHECK(ui_result.has_consent_flow_update_result()); - if (ui_result.consent_flow_update_result().update_status() != - assistant::ConsentFlowUiUpdateResult::SUCCESS) { - // TODO(updowndta): Handle consent update failure. - LOG(ERROR) << "Consent udpate error."; - } - - // More screens to be added. Close the dialog for now. - PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs(); - prefs->SetBoolean(arc::prefs::kArcVoiceInteractionValuePropAccepted, true); - prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, true); - CloseDialog(nullptr); -} - // AssistantOptInDialog // static -void AssistantOptInDialog::Show() { +void AssistantOptInDialog::Show( + ash::mojom::AssistantSetup::StartAssistantOptInFlowCallback callback) { DCHECK(!is_active); - AssistantOptInDialog* dialog = new AssistantOptInDialog(); + AssistantOptInDialog* dialog = new AssistantOptInDialog(std::move(callback)); dialog->ShowSystemDialog(true); } @@ -220,9 +121,11 @@ bool AssistantOptInDialog::IsActive() { return is_active; } -AssistantOptInDialog::AssistantOptInDialog() +AssistantOptInDialog::AssistantOptInDialog( + ash::mojom::AssistantSetup::StartAssistantOptInFlowCallback callback) : SystemWebDialogDelegate(GURL(chrome::kChromeUIAssistantOptInURL), - base::string16()) { + base::string16()), + callback_(std::move(callback)) { DCHECK(!is_active); is_active = true; } @@ -243,4 +146,13 @@ bool AssistantOptInDialog::ShouldShowDialogTitle() const { return false; } +void AssistantOptInDialog::OnDialogClosed(const std::string& json_retval) { + PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); + const bool completed = + prefs->GetBoolean(arc::prefs::kVoiceInteractionEnabled) && + prefs->GetBoolean(arc::prefs::kArcVoiceInteractionValuePropAccepted); + std::move(callback_).Run(completed); + SystemWebDialogDelegate::OnDialogClosed(json_retval); +} + } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h index 1d6b7687462..4174b738e37 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 @@ -7,50 +7,33 @@ #include <vector> +#include "ash/public/interfaces/assistant_controller.mojom.h" #include "base/callback.h" #include "base/macros.h" -#include "chrome/browser/chromeos/arc/voice_interaction/voice_interaction_controller_client.h" #include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_handler.h" #include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h" #include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" #include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" -#include "chromeos/services/assistant/public/mojom/settings.mojom.h" #include "content/public/browser/web_ui_controller.h" #include "ui/web_dialogs/web_dialog_ui.h" namespace chromeos { // Controller for chrome://assistant-optin/ page. -class AssistantOptInUI - : public ui::WebDialogUI, - public arc::VoiceInteractionControllerClient::Observer { +class AssistantOptInUI : public ui::WebDialogUI { public: explicit AssistantOptInUI(content::WebUI* web_ui); ~AssistantOptInUI() override; - // arc::VoiceInteractionControllerClient::Observer overrides - void OnStateChanged(ash::mojom::VoiceInteractionState state) override; - private: - // Initilize connection to settings manager. - void Initialize(); - // Add message handler for optin screens. void AddScreenHandler(std::unique_ptr<BaseWebUIHandler> handler); // Called by a screen when user's done with it. void OnExit(AssistantOptInScreenExitCode exit_code); - // Handle response from the settings manager. - void OnGetSettingsResponse(const std::string& settings); - void OnUpdateSettingsResponse(const std::string& settings); - - // Consent token used to complete the opt-in. - std::string consent_token_; - AssistantOptInHandler* assistant_handler_ = nullptr; std::unique_ptr<JSCallsContainer> js_calls_container_; - assistant::mojom::AssistantSettingsManagerPtr settings_manager_; std::vector<BaseWebUIHandler*> screen_handlers_; base::WeakPtrFactory<AssistantOptInUI> weak_factory_; @@ -61,21 +44,27 @@ class AssistantOptInUI class AssistantOptInDialog : public SystemWebDialogDelegate { public: // Shows the assistant optin dialog. - static void Show(); + static void Show(ash::mojom::AssistantSetup::StartAssistantOptInFlowCallback + callback = base::DoNothing()); // Returns whether the dialog is being shown. static bool IsActive(); protected: - AssistantOptInDialog(); + explicit AssistantOptInDialog( + ash::mojom::AssistantSetup::StartAssistantOptInFlowCallback callback); ~AssistantOptInDialog() override; // ui::WebDialogDelegate void GetDialogSize(gfx::Size* size) const override; std::string GetDialogArgs() const override; bool ShouldShowDialogTitle() const override; + void OnDialogClosed(const std::string& json_retval) override; private: + // Callback to run if the flow is completed. + ash::mojom::AssistantSetup::StartAssistantOptInFlowCallback callback_; + DISALLOW_COPY_AND_ASSIGN(AssistantOptInDialog); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/confirm_reject_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/confirm_reject_screen_handler.cc new file mode 100644 index 00000000000..821e080e85c --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/confirm_reject_screen_handler.cc @@ -0,0 +1,48 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/assistant_optin/confirm_reject_screen_handler.h" + +#include "chrome/browser/browser_process.h" +#include "chrome/grit/generated_resources.h" +#include "components/login/localized_values_builder.h" + +namespace { + +constexpr char kJsScreenPath[] = "AssistantConfirmRejectScreen"; + +} // namespace + +namespace chromeos { + +ConfirmRejectScreenHandler::ConfirmRejectScreenHandler( + OnAssistantOptInScreenExitCallback callback) + : BaseWebUIHandler(), exit_callback_(std::move(callback)) { + set_call_js_prefix(kJsScreenPath); +} + +ConfirmRejectScreenHandler::~ConfirmRejectScreenHandler() = default; + +void ConfirmRejectScreenHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) {} + +void ConfirmRejectScreenHandler::RegisterMessages() { + AddPrefixedCallback("userActed", + &ConfirmRejectScreenHandler::HandleUserAction); +} + +void ConfirmRejectScreenHandler::Initialize() {} + +void ConfirmRejectScreenHandler::HandleUserAction(bool confirm_result) { + DCHECK(exit_callback_); + if (confirm_result) { + std::move(exit_callback_) + .Run(AssistantOptInScreenExitCode::CONFIRM_ACCEPTED); + } else { + std::move(exit_callback_) + .Run(AssistantOptInScreenExitCode::CONFIRM_REJECTED); + } +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/confirm_reject_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/confirm_reject_screen_handler.h new file mode 100644 index 00000000000..b1022678261 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/confirm_reject_screen_handler.h @@ -0,0 +1,39 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_CONFIRM_REJECT_SCREEN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_CONFIRM_REJECT_SCREEN_HANDLER_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h" +#include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" + +namespace chromeos { + +class ConfirmRejectScreenHandler : public BaseWebUIHandler { + public: + explicit ConfirmRejectScreenHandler( + OnAssistantOptInScreenExitCallback callback); + ~ConfirmRejectScreenHandler() override; + + // BaseWebUIHandler: + void DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) override; + void RegisterMessages() override; + void Initialize() override; + + private: + void HandleUserAction(bool confirm_result); + + OnAssistantOptInScreenExitCallback exit_callback_; + + DISALLOW_COPY_AND_ASSIGN(ConfirmRejectScreenHandler); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_CONFIRM_REJECT_SCREEN_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/get_more_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/get_more_screen_handler.cc new file mode 100644 index 00000000000..d9864c4668f --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/get_more_screen_handler.cc @@ -0,0 +1,54 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/assistant_optin/get_more_screen_handler.h" + +#include "chrome/browser/browser_process.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/grit/generated_resources.h" +#include "components/arc/arc_prefs.h" +#include "components/login/localized_values_builder.h" +#include "components/prefs/pref_service.h" + +namespace { + +constexpr char kJsScreenPath[] = "AssistantGetMoreScreen"; + +} // namespace + +namespace chromeos { + +GetMoreScreenHandler::GetMoreScreenHandler( + OnAssistantOptInScreenExitCallback callback) + : BaseWebUIHandler(), exit_callback_(std::move(callback)) { + set_call_js_prefix(kJsScreenPath); +} + +GetMoreScreenHandler::~GetMoreScreenHandler() = default; + +void GetMoreScreenHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) {} + +void GetMoreScreenHandler::RegisterMessages() { + AddPrefixedCallback("userActed", &GetMoreScreenHandler::HandleUserAction); +} + +void GetMoreScreenHandler::Initialize() {} + +void GetMoreScreenHandler::HandleUserAction(const bool screen_context, + const bool email_opted_in) { + PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs(); + prefs->SetBoolean(arc::prefs::kVoiceInteractionContextEnabled, + screen_context); + + DCHECK(exit_callback_); + if (email_opted_in) { + std::move(exit_callback_).Run(AssistantOptInScreenExitCode::EMAIL_OPTED_IN); + } else { + std::move(exit_callback_) + .Run(AssistantOptInScreenExitCode::EMAIL_OPTED_OUT); + } +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/get_more_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/get_more_screen_handler.h new file mode 100644 index 00000000000..5ee693ac156 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/get_more_screen_handler.h @@ -0,0 +1,38 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_GET_MORE_SCREEN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_GET_MORE_SCREEN_HANDLER_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h" +#include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" + +namespace chromeos { + +class GetMoreScreenHandler : public BaseWebUIHandler { + public: + explicit GetMoreScreenHandler(OnAssistantOptInScreenExitCallback callback); + ~GetMoreScreenHandler() override; + + // BaseWebUIHandler: + void DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) override; + void RegisterMessages() override; + void Initialize() override; + + private: + void HandleUserAction(const bool screen_context, const bool email_opted_in); + + OnAssistantOptInScreenExitCallback exit_callback_; + + DISALLOW_COPY_AND_ASSIGN(GetMoreScreenHandler); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_GET_MORE_SCREEN_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/ready_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/ready_screen_handler.cc new file mode 100644 index 00000000000..268ce349dd3 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/ready_screen_handler.cc @@ -0,0 +1,26 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/assistant_optin/ready_screen_handler.h" + +#include "chrome/browser/browser_process.h" +#include "chrome/grit/generated_resources.h" +#include "components/login/localized_values_builder.h" + +namespace chromeos { + +ReadyScreenHandler::ReadyScreenHandler() : BaseWebUIHandler() {} + +ReadyScreenHandler::~ReadyScreenHandler() = default; + +void ReadyScreenHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) { + builder->Add("assistantReadyTitle", IDS_ASSISTANT_READY_SCREEN_TITLE); + builder->Add("assistantReadyMessage", IDS_ASSISTANT_READY_SCREEN_MESSAGE); + builder->Add("assistantReadyButton", IDS_ASSISTANT_DONE_BUTTON); +} + +void ReadyScreenHandler::Initialize() {} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/ready_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/ready_screen_handler.h new file mode 100644 index 00000000000..0975ce8032d --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/ready_screen_handler.h @@ -0,0 +1,33 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_READY_SCREEN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_READY_SCREEN_HANDLER_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h" +#include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" + +namespace chromeos { + +class ReadyScreenHandler : public BaseWebUIHandler { + public: + ReadyScreenHandler(); + ~ReadyScreenHandler() override; + + // BaseWebUIHandler: + void DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) override; + void Initialize() override; + + private: + DISALLOW_COPY_AND_ASSIGN(ReadyScreenHandler); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_READY_SCREEN_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/third_party_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/third_party_screen_handler.cc new file mode 100644 index 00000000000..6489db3a11f --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/third_party_screen_handler.cc @@ -0,0 +1,46 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/assistant_optin/third_party_screen_handler.h" + +#include "chrome/browser/browser_process.h" +#include "chrome/grit/generated_resources.h" +#include "components/login/localized_values_builder.h" + +namespace { + +constexpr char kJsScreenPath[] = "AssistantThirdPartyScreen"; + +constexpr char kUserActionNextPressed[] = "next-pressed"; + +} // namespace + +namespace chromeos { + +ThirdPartyScreenHandler::ThirdPartyScreenHandler( + OnAssistantOptInScreenExitCallback callback) + : BaseWebUIHandler(), exit_callback_(std::move(callback)) { + set_call_js_prefix(kJsScreenPath); +} + +ThirdPartyScreenHandler::~ThirdPartyScreenHandler() = default; + +void ThirdPartyScreenHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) {} + +void ThirdPartyScreenHandler::RegisterMessages() { + AddPrefixedCallback("userActed", &ThirdPartyScreenHandler::HandleUserAction); +} + +void ThirdPartyScreenHandler::Initialize() {} + +void ThirdPartyScreenHandler::HandleUserAction(const std::string& action) { + DCHECK(exit_callback_); + if (action == kUserActionNextPressed) { + std::move(exit_callback_) + .Run(AssistantOptInScreenExitCode::THIRD_PARTY_CONTINUED); + } +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/third_party_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/third_party_screen_handler.h new file mode 100644 index 00000000000..97228314c42 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/third_party_screen_handler.h @@ -0,0 +1,38 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_THIRD_PARTY_SCREEN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_THIRD_PARTY_SCREEN_HANDLER_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_screen_exit_code.h" +#include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" + +namespace chromeos { + +class ThirdPartyScreenHandler : public BaseWebUIHandler { + public: + explicit ThirdPartyScreenHandler(OnAssistantOptInScreenExitCallback callback); + ~ThirdPartyScreenHandler() override; + + // BaseWebUIHandler: + void DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) override; + void RegisterMessages() override; + void Initialize() override; + + private: + void HandleUserAction(const std::string& action); + + OnAssistantOptInScreenExitCallback exit_callback_; + + DISALLOW_COPY_AND_ASSIGN(ThirdPartyScreenHandler); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ASSISTANT_OPTIN_THIRD_PARTY_SCREEN_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.cc index 5cc5e1da71c..095484482a4 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.cc @@ -10,10 +10,10 @@ namespace { -const char kJsScreenPath[] = "AssistantValuePropScreen"; +constexpr char kJsScreenPath[] = "AssistantValuePropScreen"; -constexpr const char kUserActionSkipPressed[] = "skip-pressed"; -constexpr const char kUserActionNextPressed[] = "next-pressed"; +constexpr char kUserActionSkipPressed[] = "skip-pressed"; +constexpr char kUserActionNextPressed[] = "next-pressed"; } // namespace @@ -32,14 +32,15 @@ void ValuePropScreenHandler::DeclareLocalizedValues( builder->Add("locale", g_browser_process->GetApplicationLocale()); // TODO(updowndota) Replace this with new string constants. // Use string constant for old flow for now before we have final UX. - builder->Add("valuePropLoading", IDS_VOICE_INTERACTION_VALUE_PROP_LOADING); - builder->Add("valuePropLoadErrorTitle", + builder->Add("assistantOptinLoading", + IDS_VOICE_INTERACTION_VALUE_PROP_LOADING); + builder->Add("assistantOptinLoadErrorTitle", IDS_VOICE_INTERACTION_VALUE_PROP_LOAD_ERROR_TITLE); - builder->Add("valuePropLoadErrorMessage", + builder->Add("assistantOptinLoadErrorMessage", IDS_VOICE_INTERACTION_VALUE_PROP_LOAD_ERROR_MESSAGE); - builder->Add("valuePropRetryButton", + builder->Add("assistantOptinRetryButton", IDS_VOICE_INTERACTION_VALUE_PROP_RETRY_BUTTON); - builder->Add("valuePropMoreButton", + builder->Add("assistantOptinMoreButton", IDS_VOICE_INTERACTION_VALUE_PROP_MORE_BUTTION); builder->Add("back", IDS_EULA_BACK_BUTTON); builder->Add("next", IDS_EULA_NEXT_BUTTON); 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 eb336106ca9..af67afa5562 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc @@ -246,8 +246,6 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { drive::DriveServiceInterface* drive_service); void UpdateAppListSection( drive::DriveServiceInterface* drive_service); - void UpdateLocalMetadataSection( - drive::DebugInfoCollector* debug_info_collector); void UpdateDeltaUpdateStatusSection( drive::DebugInfoCollector* debug_info_collector); void UpdateInFlightOperationsSection(drive::JobListInterface* job_list); @@ -290,13 +288,11 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { void OnGetAppList(google_apis::DriveApiErrorCode status, std::unique_ptr<google_apis::AppList> app_list); - // Callback for DebugInfoCollector::GetMetadata for local update. - void OnGetFilesystemMetadataForLocal( - const drive::FileSystemMetadata& metadata); - // Callback for DebugInfoCollector::GetMetadata for delta update. void OnGetFilesystemMetadataForDeltaUpdate( - const drive::FileSystemMetadata& metadata); + const drive::FileSystemMetadata& metadata, + const std::map<std::string, drive::FileSystemMetadata>& + team_drive_metadata); // Called when the page requests periodic update. void OnPeriodicUpdate(const base::ListValue* args); @@ -434,24 +430,30 @@ void DriveInternalsWebUIHandler::OnPageLoaded(const base::ListValue* args) { if (!integration_service) return; + UpdateDriveRelatedPreferencesSection(); + UpdateGCacheContentsSection(); + UpdateLocalStorageUsageSection(); + UpdatePathConfigurationsSection(); + drive::DriveServiceInterface* drive_service = integration_service->drive_service(); - DCHECK(drive_service); + if (drive_service) { + UpdateConnectionStatusSection(drive_service); + UpdateAboutResourceSection(drive_service); + UpdateAppListSection(drive_service); + } + drive::DebugInfoCollector* debug_info_collector = integration_service->debug_info_collector(); - DCHECK(debug_info_collector); + if (debug_info_collector) { + UpdateDeltaUpdateStatusSection(debug_info_collector); + UpdateCacheContentsSection(debug_info_collector); + } - UpdateDriveRelatedPreferencesSection(); - UpdateConnectionStatusSection(drive_service); - UpdateAboutResourceSection(drive_service); - UpdateAppListSection(drive_service); - UpdateLocalMetadataSection(debug_info_collector); - UpdateDeltaUpdateStatusSection(debug_info_collector); - UpdateInFlightOperationsSection(integration_service->job_list()); - UpdateGCacheContentsSection(); - UpdateCacheContentsSection(debug_info_collector); - UpdateLocalStorageUsageSection(); - UpdatePathConfigurationsSection(); + drive::JobListInterface* job_list = integration_service->job_list(); + if (job_list) { + UpdateInFlightOperationsSection(job_list); + } // When the drive-internals page is reloaded by the reload key, the page // content is recreated, but this WebUI object is not (instead, OnPageLoaded @@ -540,27 +542,6 @@ void DriveInternalsWebUIHandler::UpdateAppListSection( weak_ptr_factory_.GetWeakPtr())); } -void DriveInternalsWebUIHandler::UpdateLocalMetadataSection( - drive::DebugInfoCollector* debug_info_collector) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(debug_info_collector); - - debug_info_collector->GetMetadata( - base::Bind(&DriveInternalsWebUIHandler::OnGetFilesystemMetadataForLocal, - weak_ptr_factory_.GetWeakPtr())); -} - -void DriveInternalsWebUIHandler::OnGetFilesystemMetadataForLocal( - const drive::FileSystemMetadata& metadata) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - base::DictionaryValue local_metadata; - local_metadata.SetString("account-start-page-token-local", - metadata.start_page_token); - local_metadata.SetBoolean("account-metadata-refreshing", metadata.refreshing); - web_ui()->CallJavascriptFunctionUnsafe("updateLocalMetadata", local_metadata); -} - void DriveInternalsWebUIHandler::ClearAccessToken(const base::ListValue* args) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -616,7 +597,9 @@ void DriveInternalsWebUIHandler::UpdateDeltaUpdateStatusSection( } void DriveInternalsWebUIHandler::OnGetFilesystemMetadataForDeltaUpdate( - const drive::FileSystemMetadata& metadata) { + const drive::FileSystemMetadata& metadata, + const std::map<std::string, drive::FileSystemMetadata>& + team_drive_metadata) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Profile* profile = Profile::FromWebUI(web_ui()); @@ -629,13 +612,40 @@ void DriveInternalsWebUIHandler::OnGetFilesystemMetadataForDeltaUpdate( delta_update_status.SetBoolean( "push-notification-enabled", drive_notification_manager->push_notification_enabled()); - delta_update_status.SetString( - "last-update-check-time", - google_apis::util::FormatTimeAsStringLocaltime( - metadata.last_update_check_time)); - delta_update_status.SetString( - "last-update-check-error", + + auto items = std::make_unique<base::ListValue>(); + // Users default corpus first. + auto app_data = std::make_unique<base::DictionaryValue>(); + app_data->SetString("id", "default corpus"); + app_data->SetString("root_entry_path", metadata.path); + app_data->SetString("start_page_token", metadata.start_page_token); + app_data->SetString("last_check_time", + google_apis::util::FormatTimeAsStringLocaltime( + metadata.last_update_check_time)); + app_data->SetString( + "last_check_result", drive::FileErrorToString(metadata.last_update_check_error)); + app_data->SetString("refreshing", metadata.refreshing ? "Yes" : "No"); + + items->Append(std::move(app_data)); + + for (const auto& team_drive : team_drive_metadata) { + app_data = std::make_unique<base::DictionaryValue>(); + app_data->SetString("id", team_drive.first); + app_data->SetString("root_entry_path", team_drive.second.path); + app_data->SetString("start_page_token", team_drive.second.start_page_token); + app_data->SetString("last_check_time", + google_apis::util::FormatTimeAsStringLocaltime( + team_drive.second.last_update_check_time)); + app_data->SetString( + "last_check_result", + drive::FileErrorToString(team_drive.second.last_update_check_error)); + app_data->SetString("refreshing", + team_drive.second.refreshing ? "Yes" : "No"); + items->Append(std::move(app_data)); + } + + delta_update_status.Set("items", std::move(items)); web_ui()->CallJavascriptFunctionUnsafe("updateDeltaUpdateStatus", delta_update_status); @@ -887,8 +897,12 @@ void DriveInternalsWebUIHandler::OnPeriodicUpdate(const base::ListValue* args) { if (!integration_service) return; - UpdateInFlightOperationsSection(integration_service->job_list()); UpdateEventLogSection(); + + drive::JobListInterface* job_list = integration_service->job_list(); + if (job_list) { + UpdateInFlightOperationsSection(job_list); + } } } // namespace diff --git a/chromium/chrome/browser/ui/webui/chromeos/emulator/DEPS b/chromium/chrome/browser/ui/webui/chromeos/emulator/DEPS index d12b86a6d2a..e9d9de6def2 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/emulator/DEPS +++ b/chromium/chrome/browser/ui/webui/chromeos/emulator/DEPS @@ -1,6 +1,6 @@ specific_include_rules = { "device_emulator_message_handler\.cc": [ - # TODO(mash): Remove. http://crbug.com/770866 + # TODO(mash): Remove. http://crbug.com/756094 "+ash/shell.h", "+ash/system/bluetooth/tray_bluetooth_helper.h", ], diff --git a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc index bf1b2908c44..3e457ff2461 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc @@ -8,7 +8,6 @@ #include <memory> -#include "ash/public/cpp/ash_features.h" #include "ash/shell.h" #include "base/bind.h" #include "base/bind_helpers.h" @@ -341,8 +340,6 @@ content::WebUIDataSource* CreateKeyboardOverlayUIHTMLSource(Profile* profile) { TopRowKeysAreFunctionKeys(profile)); source->AddBoolean("voiceInteractionEnabled", chromeos::switches::IsVoiceInteractionEnabled()); - source->AddBoolean("displayMoveWindowAccelsEnabled", - ash::features::IsDisplayMoveWindowAccelsEnabled()); source->AddBoolean("keyboardOverlayUsesLayout2", ui::DeviceUsesKeyboardLayout2()); ash::Shell* shell = ash::Shell::Get(); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/DEPS b/chromium/chrome/browser/ui/webui/chromeos/login/DEPS index da871fcd8bd..5c8707bba38 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/DEPS +++ b/chromium/chrome/browser/ui/webui/chromeos/login/DEPS @@ -1,35 +1,27 @@ -# TODO(mash): Remove ash includes. http://crbug.com/770866 specific_include_rules = { + # TODO(mash): Fix. https://crbug.com/856375. "core_oobe_handler\.cc": [ "+ash/shell.h", ], - "network_dropdown\.cc": [ - "+ash/system/network/network_icon.h", - "+ash/system/network/network_icon_animation.h", - ], - "network_dropdown\.h": [ - "+ash/system/network/network_icon_animation_observer.h", - ], - "oobe_display_chooser\.cc": [ - "+ash/display/window_tree_host_manager.h", + # TODO(mash): Fix or deprecate. https://crbug.com/678990 + "signin_screen_handler\.cc": [ + "+ash/detachable_base", "+ash/shell.h", ], + "signin_screen_handler\.h": [ + "+ash/detachable_base/detachable_base_observer.h", + ], + + # Tests. "oobe_display_chooser_browsertest\.cc": [ "+ash/shell.h", ], "oobe_display_chooser_unittest.cc": [ + # TODO(mash) Use a non-ash test ui::InputDeviceEventObserver + # environment for testing this. "+ash/display/display_configuration_controller.h", "+ash/shell.h", "+ash/test/ash_test_base.h", - # TODO(mash): Remove. http://crbug.com/720917. - "+ui/events/devices/device_data_manager.h", - ], - "signin_screen_handler\.cc": [ - "+ash/detachable_base", - "+ash/shell.h", - ], - "signin_screen_handler\.h": [ - "+ash/detachable_base/detachable_base_observer.h", ], "signin_userlist_unittest\.cc": [ "+ash/test/ash_test_base.h" diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.cc new file mode 100644 index 00000000000..bc31372f2a9 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.cc @@ -0,0 +1,53 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.h" + +#include "chrome/browser/chromeos/login/screens/app_downloading_screen.h" +#include "chrome/grit/generated_resources.h" +#include "components/login/localized_values_builder.h" + +namespace { + +const char kJsScreenPath[] = "login.AppDownloadingScreen"; + +} // namespace + +namespace chromeos { + +AppDownloadingScreenHandler::AppDownloadingScreenHandler() + : BaseScreenHandler(kScreenId) { + set_call_js_prefix(kJsScreenPath); +} + +AppDownloadingScreenHandler::~AppDownloadingScreenHandler() {} + +void AppDownloadingScreenHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) { + builder->Add("appDownloadingScreenTitle", + IDS_LOGIN_APP_DOWNLOADING_SCREEN_TITLE); + builder->Add("appDownloadingScreenDescription", + IDS_LOGIN_APP_DOWNLOADING_SCREEN_DESCRIPTION); + builder->Add("appDownloadingContinueSetup", + IDS_LOGIN_APP_DOWNLOADING_CONTINUE_SETUP); +} + +void AppDownloadingScreenHandler::RegisterMessages() { + BaseScreenHandler::RegisterMessages(); +} + +void AppDownloadingScreenHandler::Bind(AppDownloadingScreen* screen) { + screen_ = screen; + BaseScreenHandler::SetBaseScreen(screen); +} + +void AppDownloadingScreenHandler::Show() { + ShowScreen(kScreenId); +} + +void AppDownloadingScreenHandler::Hide() {} + +void AppDownloadingScreenHandler::Initialize() {} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.h new file mode 100644 index 00000000000..0011d308fb7 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.h @@ -0,0 +1,44 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_APP_DOWNLOADING_SCREEN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_APP_DOWNLOADING_SCREEN_HANDLER_H_ + +#include "base/macros.h" +#include "chrome/browser/chromeos/login/screens/app_downloading_screen_view.h" +#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" + +namespace chromeos { + +class AppDownloadingScreen; + +// The sole implementation of the AppDownloadingScreenView, using WebUI. +class AppDownloadingScreenHandler : public BaseScreenHandler, + public AppDownloadingScreenView { + public: + AppDownloadingScreenHandler(); + ~AppDownloadingScreenHandler() override; + + // BaseScreenHandler: + void DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) override; + void RegisterMessages() override; + + // AppDownloadingScreenView: + void Bind(AppDownloadingScreen* screen) override; + void Show() override; + void Hide() override; + + private: + // BaseScreenHandler: + void Initialize() override; + + AppDownloadingScreen* screen_ = nullptr; + + DISALLOW_COPY_AND_ASSIGN(AppDownloadingScreenHandler); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_APP_DOWNLOADING_SCREEN_HANDLER_H_ 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 00095745435..763a78625a8 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 @@ -9,7 +9,10 @@ #include "chrome/browser/chromeos/arc/arc_support_host.h" #include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/chromeos/arc/optin/arc_optin_preference_handler.h" +#include "chrome/browser/chromeos/login/screens/arc_terms_of_service_screen.h" #include "chrome/browser/chromeos/login/screens/arc_terms_of_service_screen_view_observer.h" +#include "chrome/browser/chromeos/login/ui/login_display_host.h" +#include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/consent_auditor/consent_auditor_factory.h" #include "chrome/browser/profiles/profile.h" @@ -54,6 +57,8 @@ ArcTermsOfServiceScreenHandler::~ArcTermsOfServiceScreenHandler() { } void ArcTermsOfServiceScreenHandler::RegisterMessages() { + BaseScreenHandler::RegisterMessages(); + AddCallback("arcTermsOfServiceSkip", &ArcTermsOfServiceScreenHandler::HandleSkip); AddCallback("arcTermsOfServiceAccept", @@ -103,6 +108,8 @@ void ArcTermsOfServiceScreenHandler::DeclareLocalizedValues( builder->Add("arcTermsOfServiceRetryButton", IDS_ARC_OOBE_TERMS_BUTTON_RETRY); builder->Add("arcTermsOfServiceAcceptButton", IDS_ARC_OOBE_TERMS_BUTTON_ACCEPT); + builder->Add("arcTermsOfServiceAcceptAndContinueButton", + IDS_ARC_OOBE_TERMS_BUTTON_ACCEPT_AND_CONTINUE); builder->Add("arcTermsOfServiceNextButton", IDS_ARC_OPT_IN_DIALOG_BUTTON_NEXT); builder->Add("arcPolicyLink", IDS_ARC_OPT_IN_PRIVACY_POLICY_LINK); @@ -111,6 +118,10 @@ void ArcTermsOfServiceScreenHandler::DeclareLocalizedValues( builder->Add("arcTextPaiService", IDS_ARC_OPT_IN_PAI); builder->Add("arcTextGoogleServiceConfirmation", IDS_ARC_OPT_IN_GOOGLE_SERVICE_CONFIRMATION); + builder->Add("arcTextMetricsManagedEnabled", + IDS_ARC_OOBE_TERMS_DIALOG_METRICS_MANAGED_ENABLED); + builder->Add("arcAcceptAndContinueGoogleServiceConfirmation", + IDS_ARC_OPT_IN_ACCEPT_AND_CONTINUE_GOOGLE_SERVICE_CONFIRMATION); builder->Add("arcLearnMoreStatistics", IDS_ARC_OPT_IN_LEARN_MORE_STATISTICS); builder->Add("arcLearnMoreLocationService", IDS_ARC_OPT_IN_LEARN_MORE_LOCATION_SERVICES); @@ -180,7 +191,14 @@ void ArcTermsOfServiceScreenHandler::Show() { return; } - DoShow(); + // Demo mode setup flow requires different variant of Play Store terms. It + // does not allow to skip, but instead has back button. Some options are not + // displayed, because they are not relevant for demo mode usage. + if (arc::IsArcDemoModeSetupFlow()) { + DoShowForDemoModeSetup(); + } else { + DoShow(); + } } void ArcTermsOfServiceScreenHandler::Hide() { @@ -188,6 +206,10 @@ void ArcTermsOfServiceScreenHandler::Hide() { pref_handler_.reset(); } +void ArcTermsOfServiceScreenHandler::Bind(ArcTermsOfServiceScreen* screen) { + BaseScreenHandler::SetBaseScreen(screen); +} + void ArcTermsOfServiceScreenHandler::StartNetworkAndTimeZoneObserving() { if (network_time_zone_observing_) return; @@ -241,6 +263,16 @@ void ArcTermsOfServiceScreenHandler::DoShow() { pref_handler_->Start(); } +void ArcTermsOfServiceScreenHandler::DoShowForDemoModeSetup() { + DCHECK(arc::IsArcDemoModeSetupFlow()); + + CallJS("setupForDemoMode"); + action_taken_ = false; + ShowScreen(kScreenId); + MaybeLoadPlayStoreToS(true); + StartNetworkAndTimeZoneObserving(); +} + bool ArcTermsOfServiceScreenHandler::NeedDispatchEventOnAction() { if (action_taken_) return false; @@ -295,6 +327,8 @@ void ArcTermsOfServiceScreenHandler::RecordConsents( void ArcTermsOfServiceScreenHandler::HandleSkip( const std::string& tos_content) { + DCHECK(!arc::IsArcDemoModeSetupFlow()); + if (!NeedDispatchEventOnAction()) return; @@ -312,8 +346,16 @@ void ArcTermsOfServiceScreenHandler::HandleAccept( bool enable_backup_restore, bool enable_location_services, const std::string& tos_content) { + if (arc::IsArcDemoModeSetupFlow()) { + for (auto& observer : observer_list_) + observer.OnAccept(); + // TODO(agawronska): Record consent. + return; + } + if (!NeedDispatchEventOnAction()) return; + pref_handler_->EnableBackupRestore(enable_backup_restore); pref_handler_->EnableLocationService(enable_location_services); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.h index 45d39e2d912..5bc0eafabf8 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.h @@ -23,6 +23,8 @@ class ArcOptInPreferenceHandler; namespace chromeos { +class ArcTermsOfServiceScreen; + // The sole implementation of the ArcTermsOfServiceScreenView, using WebUI. class ArcTermsOfServiceScreenHandler : public BaseScreenHandler, @@ -47,6 +49,7 @@ class ArcTermsOfServiceScreenHandler void RemoveObserver(ArcTermsOfServiceScreenViewObserver* observer) override; void Show() override; void Hide() override; + void Bind(ArcTermsOfServiceScreen* screen) override; // OobeUI::Observer: void OnCurrentScreenChanged(OobeScreen current_screen, @@ -63,7 +66,14 @@ class ArcTermsOfServiceScreenHandler // BaseScreenHandler: void Initialize() override; + // Shows default terms of service screen. void DoShow(); + + // Shows screen variant for demo mode setup flow. The flow is part of OOBE and + // runs before any user is created or before device local account is + // configured for Public Session. + void DoShowForDemoModeSetup(); + void HandleSkip(const std::string& tos_content); void HandleAccept(bool enable_backup_restore, bool enable_location_services, 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 6dfcccf4581..919aa82003b 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 @@ -47,8 +47,7 @@ #include "google_apis/google_api_keys.h" #include "services/service_manager/public/cpp/connector.h" #include "ui/aura/window_tree_host.h" -#include "ui/display/display.h" -#include "ui/display/manager/display_manager.h" +#include "ui/base/ui_base_features.h" #include "ui/display/screen.h" #include "ui/events/event_sink.h" #include "ui/gfx/geometry/size.h" @@ -89,10 +88,11 @@ CoreOobeHandler::CoreOobeHandler(OobeUI* oobe_ui, JSCallsContainer* js_calls_container) : BaseWebUIHandler(js_calls_container), oobe_ui_(oobe_ui), - version_info_updater_(this) { + version_info_updater_(this), + weak_ptr_factory_(this) { DCHECK(js_calls_container); set_call_js_prefix(kJsScreenPath); - if (!ash_util::IsRunningInMash()) { + if (features::IsAshInBrowserProcess()) { AccessibilityManager* accessibility_manager = AccessibilityManager::Get(); CHECK(accessibility_manager); accessibility_subscription_ = accessibility_manager->RegisterCallback( @@ -104,9 +104,19 @@ CoreOobeHandler::CoreOobeHandler(OobeUI* oobe_ui, TabletModeClient* tablet_mode_client = TabletModeClient::Get(); tablet_mode_client->AddObserver(this); + + OobeConfiguration::Get()->AddObserver(this); + + // |connector| may be null in tests. + auto* connector = ash_util::GetServiceManagerConnector(); + if (connector) { + connector->BindInterface(ash::mojom::kServiceName, + &cros_display_config_ptr_); + } } CoreOobeHandler::~CoreOobeHandler() { + OobeConfiguration::Get()->RemoveObserver(this); TabletModeClient::Get()->RemoveObserver(this); } @@ -141,6 +151,14 @@ void CoreOobeHandler::DeclareLocalizedValues( builder->Add("deviceRequisitionSharkPromptText", IDS_ENTERPRISE_DEVICE_REQUISITION_SHARK_PROMPT_TEXT); + // Strings for enable demo mode dialog. + builder->Add("enableDemoModeDialogTitle", IDS_ENABLE_DEMO_MODE_DIALOG_TITLE); + builder->Add("enableDemoModeDialogText", IDS_ENABLE_DEMO_MODE_DIALOG_TEXT); + builder->Add("enableDemoModeDialogConfirm", + IDS_ENABLE_DEMO_MODE_DIALOG_CONFIRM); + builder->Add("enableDemoModeDialogCancel", + IDS_ENABLE_DEMO_MODE_DIALOG_CANCEL); + // Strings for Asset Identifier shown in version string. builder->Add("assetIdLabel", IDS_OOBE_ASSET_ID_LABEL); @@ -159,6 +177,7 @@ void CoreOobeHandler::Initialize() { UpdateDeviceRequisition(); UpdateKeyboardState(); UpdateClientAreaSize(); + UpdateOobeConfiguration(); } void CoreOobeHandler::GetAdditionalParameters(base::DictionaryValue* dict) { @@ -195,6 +214,9 @@ void CoreOobeHandler::RegisterMessages() { AddCallback("raiseTabKeyEvent", &CoreOobeHandler::HandleRaiseTabKeyEvent); AddCallback("setOobeBootstrappingSlave", &CoreOobeHandler::HandleSetOobeBootstrappingSlave); + // Note: Used by enterprise_RemoraRequisitionDisplayUsage.py: + // TODO(felixe): Use chrome.system.display or cros_display_config.mojom, + // https://crbug.com/858958. AddRawCallback("getPrimaryDisplayNameForTesting", &CoreOobeHandler::HandleGetPrimaryDisplayNameForTesting); AddCallback("setupDemoMode", &CoreOobeHandler::HandleSetupDemoMode); @@ -257,10 +279,6 @@ void CoreOobeHandler::SetUsageStats(bool checked) { CallJSOrDefer("setUsageStats", checked); } -void CoreOobeHandler::SetOemEulaUrl(const std::string& oem_eula_url) { - CallJSOrDefer("setOemEulaUrl", oem_eula_url); -} - void CoreOobeHandler::SetTpmPassword(const std::string& tpm_password) { CallJSOrDefer("setTpmPassword", tpm_password); } @@ -293,6 +311,7 @@ void CoreOobeHandler::SetClientAreaSize(int width, int height) { void CoreOobeHandler::HandleInitialized() { ExecuteDeferredJSCalls(); oobe_ui_->InitializeHandlers(); + AllowJavascript(); } void CoreOobeHandler::HandleSkipUpdateEnrollAfterEula() { @@ -370,7 +389,15 @@ void CoreOobeHandler::HandleScreenAssetsLoaded( } void CoreOobeHandler::HandleSkipToLoginForTesting(const base::ListValue* args) { - LoginScreenContext context(args); + LoginScreenContext context; + + // Parse |args|. + if (args->GetSize() > 0) { + std::string email; + if (args->GetString(0, &email)) + context.set_email(email); + } + if (WizardController::default_controller()) WizardController::default_controller()->SkipToLoginForTesting(context); } @@ -437,8 +464,12 @@ void CoreOobeHandler::SetLoginUserCount(int user_count) { CallJSOrDefer("setLoginUserCount", user_count); } +void CoreOobeHandler::ForwardAccelerator(std::string accelerator_name) { + CallJSOrDefer("handleAccelerator", accelerator_name); +} + void CoreOobeHandler::UpdateA11yState() { - if (ash_util::IsRunningInMash()) { + if (!features::IsAshInBrowserProcess()) { NOTIMPLEMENTED(); return; } @@ -460,9 +491,11 @@ void CoreOobeHandler::UpdateA11yState() { void CoreOobeHandler::UpdateOobeUIVisibility() { const std::string& display = oobe_ui_->display_type(); - CallJSOrDefer("showAPIKeysNotice", !google_apis::HasKeysConfigured() && - (display == OobeUI::kOobeDisplay || - display == OobeUI::kLoginDisplay)); + bool has_api_keys_configured = google_apis::HasAPIKeyConfigured() && + google_apis::HasOAuthClientConfigured(); + CallJSOrDefer("showAPIKeysNotice", + !has_api_keys_configured && (display == OobeUI::kOobeDisplay || + display == OobeUI::kLoginDisplay)); // Don't show version label on the stable channel by default. bool should_show_version = true; @@ -512,12 +545,15 @@ void CoreOobeHandler::UpdateDeviceRequisition() { } void CoreOobeHandler::UpdateKeyboardState() { - keyboard::KeyboardController* keyboard_controller = - keyboard::KeyboardController::GetInstance(); - if (keyboard_controller) { - const bool is_keyboard_shown = keyboard_controller->keyboard_visible(); - ShowControlBar(!is_keyboard_shown); - SetVirtualKeyboardShown(is_keyboard_shown); + // TODO(mash): Support virtual keyboard under MASH. There is no + // KeyboardController in the browser process under MASH. + if (features::IsAshInBrowserProcess()) { + auto* keyboard_controller = keyboard::KeyboardController::Get(); + if (keyboard_controller->enabled()) { + const bool is_keyboard_shown = keyboard_controller->IsKeyboardVisible(); + ShowControlBar(!is_keyboard_shown); + SetVirtualKeyboardShown(is_keyboard_shown); + } } } @@ -531,6 +567,17 @@ void CoreOobeHandler::UpdateClientAreaSize() { SetClientAreaSize(size.width(), size.height()); } +void CoreOobeHandler::OnOobeConfigurationChanged() { + UpdateOobeConfiguration(); +} + +void CoreOobeHandler::UpdateOobeConfiguration() { + if (OobeConfiguration::Get()) { + CallJSOrDefer("updateOobeConfiguration", + OobeConfiguration::Get()->GetConfiguration()); + } +} + void CoreOobeHandler::OnAccessibilityStatusChanged( const AccessibilityStatusEventDetails& details) { if (details.notification_type == ACCESSIBILITY_MANAGER_SHUTDOWN) @@ -577,27 +624,31 @@ void CoreOobeHandler::HandleGetPrimaryDisplayNameForTesting( const base::Value* callback_id; CHECK(args->Get(0, &callback_id)); - const auto primary_display_id = - display::Screen::GetScreen()->GetPrimaryDisplay().id(); - const display::DisplayManager* display_manager = - ash::Shell::Get()->display_manager(); - const std::string display_name = - display_manager->GetDisplayNameForId(primary_display_id); + cros_display_config_ptr_->GetDisplayUnitInfoList( + false /* single_unified */, + base::BindOnce(&CoreOobeHandler::GetPrimaryDisplayNameCallback, + weak_ptr_factory_.GetWeakPtr(), callback_id->Clone())); +} +void CoreOobeHandler::GetPrimaryDisplayNameCallback( + const base::Value& callback_id, + std::vector<ash::mojom::DisplayUnitInfoPtr> info_list) { AllowJavascript(); - ResolveJavascriptCallback(*callback_id, base::Value(display_name)); + std::string display_name; + for (const ash::mojom::DisplayUnitInfoPtr& info : info_list) { + if (info->is_primary) { + display_name = info->name; + break; + } + } + DCHECK(!display_name.empty()); + ResolveJavascriptCallback(callback_id, base::Value(display_name)); } void CoreOobeHandler::HandleSetupDemoMode() { - const bool is_demo_mode_enabled = - base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kEnableDemoMode); - if (!is_demo_mode_enabled) - return; - WizardController* wizard_controller = WizardController::default_controller(); if (wizard_controller && !wizard_controller->login_screen_started()) { - wizard_controller->AdvanceToScreen(OobeScreen::SCREEN_OOBE_DEMO_SETUP); + wizard_controller->StartDemoModeSetup(); } } 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 9c57496980d..95ff28854a8 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,11 +9,14 @@ #include <string> #include <vector> +#include "ash/public/interfaces/cros_display_config.mojom.h" #include "base/callback.h" #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "base/values.h" #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" #include "chrome/browser/chromeos/login/demo_mode/demo_mode_detector.h" +#include "chrome/browser/chromeos/login/oobe_configuration.h" #include "chrome/browser/chromeos/login/screens/core_oobe_view.h" #include "chrome/browser/chromeos/login/version_info_updater.h" #include "chrome/browser/ui/ash/tablet_mode_client_observer.h" @@ -22,6 +25,7 @@ namespace base { class ListValue; +class Value; } namespace ui { @@ -38,7 +42,8 @@ class CoreOobeHandler : public BaseWebUIHandler, public VersionInfoUpdater::Delegate, public CoreOobeView, public ui::EventSource, - public TabletModeClientObserver { + public TabletModeClientObserver, + public OobeConfiguration::Observer { public: explicit CoreOobeHandler(OobeUI* oobe_ui, JSCallsContainer* js_calls_container); @@ -80,6 +85,9 @@ class CoreOobeHandler : public BaseWebUIHandler, // Notify WebUI of the user count on the views login screen. void SetLoginUserCount(int user_count); + // Forwards an accelerator value to cr.ui.Oobe.handleAccelerator. + void ForwardAccelerator(std::string accelerator_name); + private: // CoreOobeView implementation: void ShowSignInError(int login_attempts, @@ -94,7 +102,6 @@ class CoreOobeHandler : public BaseWebUIHandler, void ShowPasswordChangedScreen(bool show_password_error, const std::string& email) override; void SetUsageStats(bool checked) override; - void SetOemEulaUrl(const std::string& oem_eula_url) override; void SetTpmPassword(const std::string& tmp_password) override; void ClearErrors() override; void ReloadContent(const base::DictionaryValue& dictionary) override; @@ -114,6 +121,9 @@ class CoreOobeHandler : public BaseWebUIHandler, // TabletModeClientObserver: void OnTabletModeToggled(bool enabled) override; + // OobeConfiguration::Observer: + void OnOobeConfigurationChanged() override; + // Handlers for JS WebUI messages. void HandleEnableLargeCursor(bool enabled); void HandleEnableHighContrast(bool enabled); @@ -133,6 +143,9 @@ class CoreOobeHandler : public BaseWebUIHandler, void HandleHeaderBarVisible(); void HandleSetOobeBootstrappingSlave(); void HandleGetPrimaryDisplayNameForTesting(const base::ListValue* args); + void GetPrimaryDisplayNameCallback( + const base::Value& callback_id, + std::vector<ash::mojom::DisplayUnitInfoPtr> info_list); void HandleSetupDemoMode(); // When keyboard_utils.js arrow key down event is reached, raise it @@ -154,6 +167,9 @@ class CoreOobeHandler : public BaseWebUIHandler, // Updates client area size based on the primary screen size. void UpdateClientAreaSize(); + // Updates OOBE configuration. + void UpdateOobeConfiguration(); + // Notification of a change in the accessibility settings. void OnAccessibilityStatusChanged( const AccessibilityStatusEventDetails& details); @@ -174,6 +190,10 @@ class CoreOobeHandler : public BaseWebUIHandler, DemoModeDetector demo_mode_detector_; + ash::mojom::CrosDisplayConfigControllerPtr cros_display_config_ptr_; + + base::WeakPtrFactory<CoreOobeHandler> weak_ptr_factory_; + DISALLOW_COPY_AND_ASSIGN(CoreOobeHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/demo_preferences_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/demo_preferences_screen_handler.cc new file mode 100644 index 00000000000..f8a332954a4 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/demo_preferences_screen_handler.cc @@ -0,0 +1,55 @@ +// Copyright (c) 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/login/demo_preferences_screen_handler.h" + +#include "chrome/browser/chromeos/login/oobe_screen.h" +#include "chrome/browser/chromeos/login/screens/demo_preferences_screen.h" +#include "chrome/grit/generated_resources.h" +#include "components/login/localized_values_builder.h" + +namespace { + +constexpr char kJsScreenPath[] = "login.DemoPreferencesScreen"; + +} // namespace + +namespace chromeos { + +DemoPreferencesScreenHandler::DemoPreferencesScreenHandler() + : BaseScreenHandler(kScreenId) { + set_call_js_prefix(kJsScreenPath); +} + +DemoPreferencesScreenHandler::~DemoPreferencesScreenHandler() { + if (screen_) + screen_->OnViewDestroyed(this); +} + +void DemoPreferencesScreenHandler::Show() { + ShowScreen(kScreenId); +} + +void DemoPreferencesScreenHandler::Hide() {} + +void DemoPreferencesScreenHandler::Bind(DemoPreferencesScreen* screen) { + screen_ = screen; + BaseScreenHandler::SetBaseScreen(screen); +} + +void DemoPreferencesScreenHandler::Initialize() {} + +void DemoPreferencesScreenHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) { + builder->Add("demoPreferencesScreenTitle", + IDS_OOBE_DEMO_SETUP_PREFERENCES_SCREEN_TITLE); + builder->Add("demoPreferencesNextButtonLabel", + IDS_OOBE_DEMO_SETUP_PREFERENCES_SCREEN_NEXT_BUTTON_LABEL); + builder->Add("languageDropdownTitle", IDS_LANGUAGE_DROPDOWN_TITLE); + builder->Add("languageDropdownLabel", IDS_LANGUAGE_DROPDOWN_LABEL); + builder->Add("keyboardDropdownTitle", IDS_KEYBOARD_DROPDOWN_TITLE); + builder->Add("keyboardDropdownLabel", IDS_KEYBOARD_DROPDOWN_LABEL); +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/demo_preferences_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/demo_preferences_screen_handler.h new file mode 100644 index 00000000000..2c11c3a970e --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/demo_preferences_screen_handler.h @@ -0,0 +1,40 @@ +// Copyright (c) 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DEMO_PREFERENCES_SCREEN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DEMO_PREFERENCES_SCREEN_HANDLER_H_ + +#include "chrome/browser/chromeos/login/screens/demo_preferences_screen_view.h" +#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" + +namespace chromeos { + +class DemoPreferencesScreen; + +// WebUI implementation of DemoPreferencesScreenView. +class DemoPreferencesScreenHandler : public BaseScreenHandler, + public DemoPreferencesScreenView { + public: + DemoPreferencesScreenHandler(); + ~DemoPreferencesScreenHandler() override; + + // DemoPreferencesScreenView: + void Show() override; + void Hide() override; + void Bind(DemoPreferencesScreen* screen) override; + + // BaseScreenHandler: + void Initialize() override; + void DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) override; + + private: + DemoPreferencesScreen* screen_ = nullptr; + + DISALLOW_COPY_AND_ASSIGN(DemoPreferencesScreenHandler); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DEMO_PREFERENCES_SCREEN_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.cc index 048e993ee7b..dfd1bba9c94 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.cc @@ -1,12 +1,17 @@ -// Copyright (c) 2018 The Chromium Authors. All rights reserved. +// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h" +#include "base/command_line.h" +#include "base/values.h" #include "chrome/browser/chromeos/login/oobe_screen.h" #include "chrome/browser/chromeos/login/screens/demo_setup_screen.h" #include "chrome/browser/chromeos/login/wizard_controller.h" +#include "chrome/grit/generated_resources.h" +#include "chromeos/chromeos_switches.h" +#include "components/login/localized_values_builder.h" namespace { @@ -37,9 +42,31 @@ void DemoSetupScreenHandler::Bind(DemoSetupScreen* screen) { BaseScreenHandler::SetBaseScreen(screen); } +void DemoSetupScreenHandler::OnSetupFinished(bool is_success, + const std::string& message) { + CallJS("onSetupFinished", is_success, message); +} + void DemoSetupScreenHandler::Initialize() {} void DemoSetupScreenHandler::DeclareLocalizedValues( - ::login::LocalizedValuesBuilder* builder) {} + ::login::LocalizedValuesBuilder* builder) { + builder->Add("demoSetupProgressScreenTitle", + IDS_OOBE_DEMO_SETUP_PROGRESS_SCREEN_TITLE); + builder->Add("demoSetupErrorScreenTitle", + IDS_OOBE_DEMO_SETUP_ERROR_SCREEN_TITLE); + builder->Add("demoSetupErrorScreenSubtitle", + IDS_OOBE_DEMO_SETUP_ERROR_SCREEN_SUBTITLE); + builder->Add("demoSetupErrorScreenRetryButtonLabel", + IDS_OOBE_DEMO_SETUP_ERROR_SCREEN_RETRY_BUTTON_LABEL); +} + +void DemoSetupScreenHandler::GetAdditionalParameters( + base::DictionaryValue* dict) { + const bool is_offline_demo_mode_enabled = + base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kEnableOfflineDemoMode); + dict->SetBoolean("offlineDemoModeEnabled", is_offline_demo_mode_enabled); +} } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h index d75084d7c81..2acc8e02609 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h @@ -1,4 +1,4 @@ -// Copyright (c) 2018 The Chromium Authors. All rights reserved. +// 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. @@ -24,21 +24,15 @@ class DemoSetupScreenHandler : public BaseScreenHandler, void Show() override; void Hide() override; void Bind(DemoSetupScreen* screen) override; + void OnSetupFinished(bool is_success, const std::string& message) override; // BaseScreenHandler: void Initialize() override; void DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) override; + void GetAdditionalParameters(base::DictionaryValue* dict) override; private: - // Enumeration for UI states. These values have to be kept in sync with JS - // code in oobe_screen_demo_setup.js. - enum class UiState : int { - kError = -1, // Displaying error. - kDefault = 0, // Displaying initial UI. - kProcessing = 1, // Displaying setup in progress. - }; - DemoSetupScreen* screen_ = nullptr; DISALLOW_COPY_AND_ASSIGN(DemoSetupScreenHandler); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.cc index 6211c4fd4b2..136f9361bb8 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.cc @@ -34,7 +34,8 @@ void DeviceDisabledScreenHandler::Show() { } if (delegate_) { - CallJS("setEnrollmentDomain", delegate_->GetEnrollmentDomain()); + CallJS("setSerialNumberAndEnrollmentDomain", delegate_->GetSerialNumber(), + delegate_->GetEnrollmentDomain()); CallJS("setMessage", delegate_->GetMessage()); } ShowScreen(kScreenId); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_handler.cc new file mode 100644 index 00000000000..b24d74e6e82 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_handler.cc @@ -0,0 +1,19 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/login/discover/discover_handler.h" + +namespace { + +const char kDiscoverJsPrefix[] = "discover."; + +} // namespace + +namespace chromeos { + +DiscoverHandler::DiscoverHandler(const std::string& screen_name) { + set_call_js_prefix(kDiscoverJsPrefix + screen_name); +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_handler.h new file mode 100644 index 00000000000..d037bfdc315 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_handler.h @@ -0,0 +1,26 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_HANDLER_H_ + +#include <string> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" + +namespace chromeos { + +// Base class for Discover modules WebUI message handler. +class DiscoverHandler : public BaseWebUIHandler { + public: + explicit DiscoverHandler(const std::string& module_name); + ~DiscoverHandler() override = default; + + private: + DISALLOW_COPY_AND_ASSIGN(DiscoverHandler); +}; + +} // namespace chromeos +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_manager.cc b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_manager.cc new file mode 100644 index 00000000000..966871e92e0 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_manager.cc @@ -0,0 +1,43 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/login/discover/discover_manager.h" + +#include <algorithm> + +#include "base/logging.h" +#include "chrome/browser/ui/webui/chromeos/login/discover/discover_handler.h" +#include "chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_welcome.h" + +namespace chromeos { + +DiscoverManager::DiscoverManager() { + CreateModules(); +} + +DiscoverManager::~DiscoverManager() = default; + +bool DiscoverManager::IsCompleted() const { + // Returns true if all of the modules are completed. + return std::all_of(modules_.begin(), modules_.end(), + [](const auto& module_pair) { + return module_pair.second->IsCompleted(); + }); +} + +void DiscoverManager::CreateModules() { + modules_[DiscoverModuleWelcome::kModuleName] = + std::make_unique<DiscoverModuleWelcome>(); +} + +std::vector<std::unique_ptr<DiscoverHandler>> +DiscoverManager::CreateWebUIHandlers() const { + std::vector<std::unique_ptr<DiscoverHandler>> handlers; + for (const auto& module_pair : modules_) { + handlers.emplace_back(module_pair.second->CreateWebUIHandler()); + } + return handlers; +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_manager.h b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_manager.h new file mode 100644 index 00000000000..bd0fa047ce8 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_manager.h @@ -0,0 +1,46 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_MANAGER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_MANAGER_H_ + +#include <memory> +#include <string> +#include <unordered_map> + +#include "base/callback.h" +#include "base/macros.h" + +namespace chromeos { + +class DiscoverHandler; +class DiscoverModule; + +class DiscoverManager { + public: + using ModulesMap = + std::unordered_map<std::string, std::unique_ptr<DiscoverModule>>; + + DiscoverManager(); + ~DiscoverManager(); + + // Returns true if there are no modules to be displayed. + bool IsCompleted() const; + + // Returns vector of WebUI message handlers for visible modules. + std::vector<std::unique_ptr<DiscoverHandler>> CreateWebUIHandlers() const; + + const ModulesMap& get_modules() const { return modules_; } + + private: + // Creates all needed modules. + void CreateModules(); + ModulesMap modules_; + + DISALLOW_COPY_AND_ASSIGN(DiscoverManager); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_MANAGER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_module.h b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_module.h new file mode 100644 index 00000000000..add727f7049 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_module.h @@ -0,0 +1,38 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_MODULE_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_MODULE_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" + +namespace chromeos { + +class DiscoverHandler; + +class DiscoverModule { + public: + DiscoverModule() = default; + + virtual ~DiscoverModule() = default; + + // Returns true if module is completed + virtual bool IsCompleted() const = 0; + + // Creates and returns WebUI handler for the module. + virtual std::unique_ptr<DiscoverHandler> CreateWebUIHandler() const = 0; + + // Module is also expected to provide static method: + // static const char* kModuleName; + + private: + DISALLOW_COPY_AND_ASSIGN(DiscoverModule); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_MODULE_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_ui.cc new file mode 100644 index 00000000000..553853e4189 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_ui.cc @@ -0,0 +1,41 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/login/discover/discover_ui.h" + +#include "chrome/browser/browser_process.h" +#include "chrome/browser/ui/webui/chromeos/login/discover/discover_handler.h" +#include "chrome/browser/ui/webui/chromeos/login/discover/discover_manager.h" +#include "content/public/browser/web_ui.h" + +namespace chromeos { + +DiscoverUI::DiscoverUI() {} + +DiscoverUI::~DiscoverUI() {} + +void DiscoverUI::RegisterMessages(content::WebUI* web_ui) { + std::vector<std::unique_ptr<DiscoverHandler>> handlers = + g_browser_process->platform_part() + ->GetDiscoverManager() + ->CreateWebUIHandlers(); + for (auto& handler : handlers) { + handlers_.push_back(handler.get()); + web_ui->AddMessageHandler(std::move(handler)); + } + initialized_ = true; +} + +void DiscoverUI::GetAdditionalParameters(base::DictionaryValue* dict) { + CHECK(initialized_); + for (DiscoverHandler* handler : handlers_) { + handler->GetLocalizedStrings(dict); + } +} + +void DiscoverUI::Show() { + // TODO. +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_ui.h b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_ui.h new file mode 100644 index 00000000000..55a7058b4a9 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_ui.h @@ -0,0 +1,51 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_UI_H_ + +#include <vector> + +#include "base/macros.h" + +namespace base { +class DictionaryValue; +} + +namespace content { +class WebUI; +} + +namespace chromeos { + +class DiscoverHandler; + +class DiscoverUI { + public: + DiscoverUI(); + + ~DiscoverUI(); + + // Register WebUI handlers + void RegisterMessages(content::WebUI* web_ui); + + // Returns localized strings and data. + void GetAdditionalParameters(base::DictionaryValue* dict); + + void Show(); + + private: + bool initialized_ = false; + + // Non-owninng. + // Handler are owned by WebUI, but we need to keep this list to be able to + // to refresh string resources. + std::vector<DiscoverHandler*> handlers_; + + DISALLOW_COPY_AND_ASSIGN(DiscoverUI); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_DISCOVER_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_welcome.cc b/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_welcome.cc new file mode 100644 index 00000000000..ff9c37f20c6 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_welcome.cc @@ -0,0 +1,67 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_welcome.h" + +#include "chrome/browser/ui/webui/chromeos/login/discover/discover_handler.h" +#include "chrome/grit/generated_resources.h" +#include "components/login/localized_values_builder.h" +#include "ui/chromeos/devicetype_utils.h" + +namespace chromeos { + +namespace { + +class DiscoverModuleWelcomeHandler : public DiscoverHandler { + public: + DiscoverModuleWelcomeHandler(); + ~DiscoverModuleWelcomeHandler() override = default; + + private: + // BaseWebUIHandler: implementation + void DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) override; + void Initialize() override; + void RegisterMessages() override; + + DISALLOW_COPY_AND_ASSIGN(DiscoverModuleWelcomeHandler); +}; + +DiscoverModuleWelcomeHandler::DiscoverModuleWelcomeHandler() + : DiscoverHandler(DiscoverModuleWelcome::kModuleName) {} + +void DiscoverModuleWelcomeHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) { + builder->Add("discoverWelcomeGetStarted", IDS_DISCOVER_WELCOME_GET_STARTED); + builder->Add("discoverWelcomeLater", IDS_DISCOVER_WELCOME_LATER); + builder->AddF("discoverWelcomeTitle", IDS_DISCOVER_WELCOME_TITLE, + ui::GetChromeOSDeviceName()); + builder->AddF("discoverWelcomeSubTitle", IDS_DISCOVER_WELCOME_SUBTITLE, + ui::GetChromeOSDeviceName()); +} + +void DiscoverModuleWelcomeHandler::Initialize() {} + +void DiscoverModuleWelcomeHandler::RegisterMessages() {} + +} // anonymous namespace + +/* ***************************************************************** */ +/* Discover Welcome module implementation below. */ + +const char DiscoverModuleWelcome::kModuleName[] = "welcome"; + +DiscoverModuleWelcome::DiscoverModuleWelcome() = default; +DiscoverModuleWelcome::~DiscoverModuleWelcome() = default; + +bool DiscoverModuleWelcome::IsCompleted() const { + return false; +} + +std::unique_ptr<DiscoverHandler> DiscoverModuleWelcome::CreateWebUIHandler() + const { + return std::make_unique<DiscoverModuleWelcomeHandler>(); +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_welcome.h b/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_welcome.h new file mode 100644 index 00000000000..bdde6246ce2 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_welcome.h @@ -0,0 +1,32 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_MODULES_DISCOVER_MODULE_WELCOME_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_MODULES_DISCOVER_MODULE_WELCOME_H_ + +#include <memory> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/login/discover/discover_module.h" + +namespace chromeos { + +class DiscoverModuleWelcome : public DiscoverModule { + public: + DiscoverModuleWelcome(); + ~DiscoverModuleWelcome() override; + + // DiscoverModule: + bool IsCompleted() const override; + std::unique_ptr<DiscoverHandler> CreateWebUIHandler() const override; + + // Module name. + static const char kModuleName[]; + + private: + DISALLOW_COPY_AND_ASSIGN(DiscoverModuleWelcome); +}; + +} // namespace chromeos +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_MODULES_DISCOVER_MODULE_WELCOME_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/discover_screen_handler.cc new file mode 100644 index 00000000000..62ef00b6d58 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover_screen_handler.cc @@ -0,0 +1,50 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/login/discover_screen_handler.h" + +#include "chrome/browser/chromeos/login/screens/discover_screen.h" + +namespace { + +const char kJsScreenPath[] = "login.DiscoverScreen"; + +} // namespace + +namespace chromeos { + +DiscoverScreenHandler::DiscoverScreenHandler() : BaseScreenHandler(kScreenId) { + set_call_js_prefix(kJsScreenPath); +} + +DiscoverScreenHandler::~DiscoverScreenHandler() {} + +void DiscoverScreenHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) {} + +void DiscoverScreenHandler::RegisterMessages() { + BaseWebUIHandler::RegisterMessages(); + discover_ui_.RegisterMessages(web_ui()); +} + +void DiscoverScreenHandler::GetAdditionalParameters( + base::DictionaryValue* dict) { + discover_ui_.GetAdditionalParameters(dict); +} + +void DiscoverScreenHandler::Bind(DiscoverScreen* screen) { + screen_ = screen; + BaseScreenHandler::SetBaseScreen(screen); +} + +void DiscoverScreenHandler::Hide() {} + +void DiscoverScreenHandler::Initialize() {} + +void DiscoverScreenHandler::Show() { + ShowScreen(kScreenId); + discover_ui_.Show(); +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/discover_screen_handler.h new file mode 100644 index 00000000000..dee6d7c6944 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover_screen_handler.h @@ -0,0 +1,46 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_SCREEN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_SCREEN_HANDLER_H_ + +#include "base/macros.h" +#include "chrome/browser/chromeos/login/screens/discover_screen_view.h" +#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" +#include "chrome/browser/ui/webui/chromeos/login/discover/discover_ui.h" + +namespace chromeos { + +class DiscoverScreen; + +// The sole implementation of the DiscoverScreenView, using WebUI. +class DiscoverScreenHandler : public BaseScreenHandler, + public DiscoverScreenView { + public: + DiscoverScreenHandler(); + ~DiscoverScreenHandler() override; + + // BaseScreenHandler: + void DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) override; + void GetAdditionalParameters(base::DictionaryValue* dict) override; + void RegisterMessages() override; + + // DiscoverScreenView: + void Bind(DiscoverScreen* screen) override; + void Hide() override; + void Initialize() override; + void Show() override; + + private: + DiscoverScreen* screen_ = nullptr; + + DiscoverUI discover_ui_; + + DISALLOW_COPY_AND_ASSIGN(DiscoverScreenHandler); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DISCOVER_SCREEN_HANDLER_H_ 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 442b4f9a8e6..2f4c2f8318c 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 @@ -9,8 +9,10 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/files/file_util.h" +#include "base/json/json_reader.h" #include "base/logging.h" #include "base/macros.h" +#include "base/metrics/histogram_functions.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" @@ -57,6 +59,9 @@ const char kEnrollmentModeUIForced[] = "forced"; const char kEnrollmentModeUIManual[] = "manual"; const char kEnrollmentModeUIRecovery[] = "recovery"; +constexpr char kActiveDirectoryJoinHistogram[] = + "Enterprise.ActiveDirectoryJoin"; + // Converts |mode| to a mode identifier for the UI. std::string EnrollmentModeToUIMode(policy::EnrollmentConfig::Mode mode) { switch (mode) { @@ -114,15 +119,18 @@ std::string GetEnterpriseDisplayDomain() { } constexpr struct { + const char* id; int title_id; int subtitle_id; authpolicy::KerberosEncryptionTypes encryption_types; } kEncryptionTypes[] = { - {IDS_AD_ENCRYPTION_STRONG_TITLE, IDS_AD_ENCRYPTION_STRONG_SUBTITLE, + {"strong", IDS_AD_ENCRYPTION_STRONG_TITLE, + IDS_AD_ENCRYPTION_STRONG_SUBTITLE, authpolicy::KerberosEncryptionTypes::ENC_TYPES_STRONG}, - {IDS_AD_ENCRYPTION_ALL_TITLE, IDS_AD_ENCRYPTION_ALL_SUBTITLE, + {"all", IDS_AD_ENCRYPTION_ALL_TITLE, IDS_AD_ENCRYPTION_ALL_SUBTITLE, authpolicy::KerberosEncryptionTypes::ENC_TYPES_ALL}, - {IDS_AD_ENCRYPTION_LEGACY_TITLE, IDS_AD_ENCRYPTION_LEGACY_SUBTITLE, + {"legacy", IDS_AD_ENCRYPTION_LEGACY_TITLE, + IDS_AD_ENCRYPTION_LEGACY_SUBTITLE, authpolicy::KerberosEncryptionTypes::ENC_TYPES_LEGACY}}; std::unique_ptr<base::ListValue> GetEncryptionTypesList() { @@ -136,7 +144,7 @@ std::unique_ptr<base::ListValue> GetEncryptionTypesList() { enc_option->SetKey( "subtitle", base::Value(l10n_util::GetStringUTF16(enc_types.subtitle_id))); - enc_option->SetKey("value", base::Value(enc_types.encryption_types)); + enc_option->SetKey("value", base::Value(enc_types.id)); enc_option->SetKey( "selected", base::Value(default_types == enc_types.encryption_types)); encryption_list->Append(std::move(enc_option)); @@ -144,6 +152,16 @@ std::unique_ptr<base::ListValue> GetEncryptionTypesList() { return encryption_list; } +authpolicy::KerberosEncryptionTypes TranslateEncryptionTypesString( + const std::string& string_id) { + for (const auto& enc_types : kEncryptionTypes) { + if (enc_types.id == string_id) + return enc_types.encryption_types; + } + NOTREACHED(); + return authpolicy::KerberosEncryptionTypes::ENC_TYPES_STRONG; +} + } // namespace // EnrollmentScreenHandler, public ------------------------------ @@ -178,6 +196,8 @@ void EnrollmentScreenHandler::RegisterMessages() { &EnrollmentScreenHandler::HandleCompleteLogin); AddCallback("oauthEnrollAdCompleteLogin", &EnrollmentScreenHandler::HandleAdCompleteLogin); + AddCallback("oauthEnrollAdUnlockConfiguration", + &EnrollmentScreenHandler::HandleAdUnlockConfiguration); AddCallback("oauthEnrollRetry", &EnrollmentScreenHandler::HandleRetry); AddCallback("frameLoadingCompleted", @@ -223,14 +243,28 @@ void EnrollmentScreenHandler::ShowLicenseTypeSelectionScreen( } void EnrollmentScreenHandler::ShowActiveDirectoryScreen( + const std::string& domain_join_config, const std::string& machine_name, const std::string& username, authpolicy::ErrorType error) { observe_network_failure_ = false; + if (active_directory_join_type_ == ActiveDirectoryDomainJoinType::COUNT) { + active_directory_join_type_ = + ActiveDirectoryDomainJoinType::WITHOUT_CONFIGURATION; + } + + if (!domain_join_config.empty()) { + active_directory_domain_join_config_ = domain_join_config; + show_unlock_password_ = true; + active_directory_join_type_ = + ActiveDirectoryDomainJoinType::NOT_USING_CONFIGURATION; + } switch (error) { case authpolicy::ERROR_NONE: { - CallJS("invalidateAd", machine_name, username, - static_cast<int>(ActiveDirectoryErrorState::NONE)); + CallJS("setAdJoinParams", std::string() /* machineName */, + std::string() /* userName */, + static_cast<int>(ActiveDirectoryErrorState::NONE), + show_unlock_password_); ShowStep(kEnrollmentStepAdJoin); return; } @@ -240,31 +274,34 @@ void EnrollmentScreenHandler::ShowActiveDirectoryScreen( return; case authpolicy::ERROR_PARSE_UPN_FAILED: case authpolicy::ERROR_BAD_USER_NAME: - CallJS("invalidateAd", machine_name, username, - static_cast<int>(ActiveDirectoryErrorState::BAD_USERNAME)); + CallJS("setAdJoinParams", machine_name, username, + static_cast<int>(ActiveDirectoryErrorState::BAD_USERNAME), + show_unlock_password_); ShowStep(kEnrollmentStepAdJoin); return; case authpolicy::ERROR_BAD_PASSWORD: - CallJS("invalidateAd", machine_name, username, - static_cast<int>(ActiveDirectoryErrorState::BAD_PASSWORD)); + CallJS("setAdJoinParams", machine_name, username, + static_cast<int>(ActiveDirectoryErrorState::BAD_AUTH_PASSWORD), + show_unlock_password_); ShowStep(kEnrollmentStepAdJoin); return; case authpolicy::ERROR_MACHINE_NAME_TOO_LONG: - CallJS( - "invalidateAd", machine_name, username, - static_cast<int>(ActiveDirectoryErrorState::MACHINE_NAME_TOO_LONG)); + CallJS("setAdJoinParams", machine_name, username, + static_cast<int>(ActiveDirectoryErrorState::MACHINE_NAME_TOO_LONG), + show_unlock_password_); ShowStep(kEnrollmentStepAdJoin); return; case authpolicy::ERROR_INVALID_MACHINE_NAME: - CallJS("invalidateAd", machine_name, username, - static_cast<int>(ActiveDirectoryErrorState::MACHINE_NAME_INVALID)); + CallJS("setAdJoinParams", machine_name, username, + static_cast<int>(ActiveDirectoryErrorState::MACHINE_NAME_INVALID), + show_unlock_password_); ShowStep(kEnrollmentStepAdJoin); return; case authpolicy::ERROR_PASSWORD_EXPIRED: ShowError(IDS_AD_PASSWORD_EXPIRED, true); return; case authpolicy::ERROR_JOIN_ACCESS_DENIED: - ShowError(IDS_AD_USER_DENIED_TO_JOIN_MACHINE, true); + ShowError(IDS_AD_USER_DENIED_TO_JOIN_DEVICE, true); return; case authpolicy::ERROR_USER_HIT_JOIN_QUOTA: ShowError(IDS_AD_USER_HIT_JOIN_QUOTA, true); @@ -272,9 +309,6 @@ void EnrollmentScreenHandler::ShowActiveDirectoryScreen( case authpolicy::ERROR_OU_DOES_NOT_EXIST: ShowError(IDS_AD_OU_DOES_NOT_EXIST, true); return; - case authpolicy::ERROR_INVALID_OU: - ShowError(IDS_AD_OU_INVALID, true); - return; case authpolicy::ERROR_OU_ACCESS_DENIED: ShowError(IDS_AD_OU_ACCESS_DENIED, true); return; @@ -477,6 +511,12 @@ void EnrollmentScreenHandler::ShowEnrollmentStatus( case policy::EnrollmentStatus::LICENSE_REQUEST_FAILED: ShowError(IDS_ENTERPRISE_ENROLLMENT_ERROR_LICENSE_REQUEST, false); return; + case policy::EnrollmentStatus::OFFLINE_POLICY_LOAD_FAILED: + case policy::EnrollmentStatus::OFFLINE_POLICY_DECODING_FAILED: + // OFFLINE_POLICY_LOAD_FAILED and OFFLINE_POLICY_DECODING_FAILED happen + // only within MODE_OFFLINE_DEMO flow, which shouldn't happen here. + NOTREACHED(); + return; } NOTREACHED(); } @@ -500,6 +540,10 @@ void EnrollmentScreenHandler::DeclareLocalizedValues( builder->Add("oauthEnrollSkip", IDS_ENTERPRISE_ENROLLMENT_SKIP); builder->AddF("oauthEnrollSuccess", IDS_ENTERPRISE_ENROLLMENT_SUCCESS, ui::GetChromeOSDeviceName()); + builder->Add("oauthEnrollSuccessTitle", + IDS_ENTERPRISE_ENROLLMENT_SUCCESS_TITLE); + builder->Add("enrollmentSuccessIllustrationTitle", + IDS_ENTERPRISE_ENROLLMENT_SUCCESS_ILLUSTRATION_TITLE); builder->Add("oauthEnrollDeviceInformation", IDS_ENTERPRISE_ENROLLMENT_DEVICE_INFORMATION); builder->Add("oauthEnrollExplainAttributeLink", @@ -513,17 +557,25 @@ void EnrollmentScreenHandler::DeclareLocalizedValues( builder->Add("oauthEnrollWorking", IDS_ENTERPRISE_ENROLLMENT_WORKING_MESSAGE); // Do not use AddF for this string as it will be rendered by the JS code. builder->Add("oauthEnrollAbeSuccess", IDS_ENTERPRISE_ENROLLMENT_ABE_SUCCESS); - builder->Add("oauthEnrollAdMachineNameInput", - IDS_AD_MACHINE_NAME_INPUT_LABEL); + builder->Add("oauthEnrollAdMachineNameInput", IDS_AD_DEVICE_NAME_INPUT_LABEL); + builder->Add("oauthEnrollAdMachineNameInputRegex", + IDS_AD_DEVICE_NAME_REGEX_INPUT_LABEL); builder->Add("oauthEnrollAdDomainJoinWelcomeMessage", IDS_AD_DOMAIN_JOIN_WELCOME_MESSAGE); builder->Add("adEnrollmentLoginUsername", IDS_AD_ENROLLMENT_LOGIN_USER); builder->Add("adLoginInvalidUsername", IDS_AD_INVALID_USERNAME); builder->Add("adLoginPassword", IDS_AD_LOGIN_PASSWORD); builder->Add("adLoginInvalidPassword", IDS_AD_INVALID_PASSWORD); - builder->Add("adJoinErrorMachineNameInvalid", IDS_AD_MACHINENAME_INVALID); - builder->Add("adJoinErrorMachineNameTooLong", IDS_AD_MACHINENAME_TOO_LONG); + builder->Add("adJoinErrorMachineNameInvalid", IDS_AD_DEVICE_NAME_INVALID); + builder->Add("adJoinErrorMachineNameTooLong", IDS_AD_DEVICE_NAME_TOO_LONG); + builder->Add("adJoinErrorMachineNameDoesntMatchRegex", + IDS_AD_DEVICE_NAME_DOESNT_MATCH_REGEX); builder->Add("adJoinMoreOptions", IDS_AD_MORE_OPTIONS_BUTTON); + builder->Add("adUnlockConfig", IDS_AD_UNLOCK_CONFIG); + builder->Add("adUnlockButton", IDS_AD_UNLOCK_CONFIG_UNLOCK_BUTTON); + builder->Add("adUnlockPassword", IDS_AD_UNLOCK_CONFIG_PASSWORD); + builder->Add("adUnlockIncorrectPassword", IDS_AD_UNLOCK_INCORRECT_PASSWORD); + builder->Add("adUnlockPasswordSkip", IDS_AD_UNLOCK_PASSWORD_SKIP); builder->Add("adJoinOrgUnit", IDS_AD_ORG_UNIT_HINT); builder->Add("adJoinCancel", IDS_AD_CANCEL_BUTTON); builder->Add("adJoinConfirm", IDS_AD_CONFIRM_BUTTON); @@ -540,6 +592,7 @@ void EnrollmentScreenHandler::DeclareLocalizedValues( builder->Add("licenseCountTemplate", IDS_ENTERPRISE_ENROLLMENT_LICENSES_REMAINING_TEMPLATE); builder->Add("selectEncryption", IDS_AD_ENCRYPTION_SELECTION_SELECT); + builder->Add("selectConfiguration", IDS_AD_CONFIG_SELECTION_SELECT); } void EnrollmentScreenHandler::GetAdditionalParameters( @@ -556,6 +609,35 @@ bool EnrollmentScreenHandler::IsEnrollmentScreenHiddenByError() const { error_screen_->GetParentScreen() == kScreenId); } +void EnrollmentScreenHandler::OnAdConfigurationUnlocked( + std::string unlocked_data) { + if (unlocked_data.empty()) { + CallJS("setAdJoinParams", std::string() /* machineName */, + std::string() /* userName */, + static_cast<int>(ActiveDirectoryErrorState::BAD_UNLOCK_PASSWORD), + show_unlock_password_); + return; + } + std::unique_ptr<base::ListValue> options = + base::ListValue::From(base::JSONReader::Read( + unlocked_data, base::JSONParserOptions::JSON_ALLOW_TRAILING_COMMAS)); + if (!options) { + ShowError(IDS_AD_JOIN_CONFIG_NOT_PARSED, true); + show_unlock_password_ = false; + CallJS("setAdJoinConfiguration", base::ListValue()); + return; + } + base::DictionaryValue custom; + custom.SetKey( + "name", + base::Value(l10n_util::GetStringUTF8(IDS_AD_CONFIG_SELECTION_CUSTOM))); + options->GetList().push_back(std::move(custom)); + show_unlock_password_ = false; + active_directory_join_type_ = + ActiveDirectoryDomainJoinType::USING_CONFIGURATION; + CallJS("setAdJoinConfiguration", *options); +} + void EnrollmentScreenHandler::UpdateState(NetworkError::ErrorReason reason) { UpdateStateInternal(reason, false); } @@ -657,6 +739,16 @@ void EnrollmentScreenHandler::HandleToggleFakeEnrollment() { void EnrollmentScreenHandler::HandleClose(const std::string& reason) { DCHECK(controller_); + if (active_directory_join_type_ != ActiveDirectoryDomainJoinType::COUNT) { + DCHECK(g_browser_process->platform_part() + ->browser_policy_connector_chromeos() + ->IsActiveDirectoryManaged()); + // Record Active Directory join type in case of successful enrollment and + // domain join. + base::UmaHistogramEnumeration(kActiveDirectoryJoinHistogram, + active_directory_join_type_, + ActiveDirectoryDomainJoinType::COUNT); + } if (reason == "cancel") { controller_->OnCancel(); @@ -679,13 +771,23 @@ void EnrollmentScreenHandler::HandleCompleteLogin( void EnrollmentScreenHandler::HandleAdCompleteLogin( const std::string& machine_name, const std::string& distinguished_name, - int encryption_types, + const std::string& encryption_types, const std::string& user_name, const std::string& password) { observe_network_failure_ = false; + show_unlock_password_ = false; DCHECK(controller_); controller_->OnActiveDirectoryCredsProvided( - machine_name, distinguished_name, encryption_types, user_name, password); + machine_name, distinguished_name, + TranslateEncryptionTypesString(encryption_types), user_name, password); +} + +void EnrollmentScreenHandler::HandleAdUnlockConfiguration( + const std::string& password) { + AuthPolicyLoginHelper::DecryptConfiguration( + active_directory_domain_join_config_, password, + base::BindOnce(&EnrollmentScreenHandler::OnAdConfigurationUnlocked, + weak_ptr_factory_.GetWeakPtr())); } void EnrollmentScreenHandler::HandleRetry() { 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 f34bde1bd4c..a954443ded3 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 @@ -29,7 +29,21 @@ enum class ActiveDirectoryErrorState { MACHINE_NAME_INVALID = 1, MACHINE_NAME_TOO_LONG = 2, BAD_USERNAME = 3, - BAD_PASSWORD = 4, + BAD_AUTH_PASSWORD = 4, + BAD_UNLOCK_PASSWORD = 5, +}; + +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum class ActiveDirectoryDomainJoinType { + // Configuration is not set on the domain. + WITHOUT_CONFIGURATION = 0, + // Configuration is set but was not unlocked during domain join. + NOT_USING_CONFIGURATION = 1, + // Configuration is set and was unlocked during domain join. + USING_CONFIGURATION = 2, + // Number of elements in the enum. Should be last. + COUNT, }; // WebUIMessageHandler implementation which handles events occurring on the @@ -55,7 +69,8 @@ class EnrollmentScreenHandler void ShowSigninScreen() override; void ShowLicenseTypeSelectionScreen( const base::DictionaryValue& license_types) override; - void ShowActiveDirectoryScreen(const std::string& machine_name, + void ShowActiveDirectoryScreen(const std::string& domain_join_config, + const std::string& machine_name, const std::string& username, authpolicy::ErrorType error) override; void ShowAttributePromptScreen(const std::string& asset_id, @@ -85,9 +100,10 @@ class EnrollmentScreenHandler const std::string& auth_code); void HandleAdCompleteLogin(const std::string& machine_name, const std::string& distinguished_name, - int encryption_types, + const std::string& encryption_types, const std::string& user_name, const std::string& password); + void HandleAdUnlockConfiguration(const std::string& password); void HandleRetry(); void HandleFrameLoadingCompleted(); void HandleDeviceAttributesProvided(const std::string& asset_id, @@ -130,6 +146,9 @@ class EnrollmentScreenHandler // enrollment sign-in page. bool IsEnrollmentScreenHiddenByError() const; + // Called after configuration seed was unlocked. + void OnAdConfigurationUnlocked(std::string unlocked_data); + // Keeps the controller for this view. Controller* controller_ = nullptr; @@ -138,6 +157,15 @@ class EnrollmentScreenHandler // The enrollment configuration. policy::EnrollmentConfig config_; + // Active Directory configuration in the form of encrypted binary data. + std::string active_directory_domain_join_config_; + + ActiveDirectoryDomainJoinType active_directory_join_type_ = + ActiveDirectoryDomainJoinType::COUNT; + + // Whether unlock password input step should be shown. + bool show_unlock_password_ = false; + // True if screen was not shown yet. bool first_show_ = true; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.cc index ffa5c4b099d..22f1eba88cd 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.cc @@ -6,6 +6,7 @@ #include "base/time/time.h" #include "chrome/browser/chromeos/login/screens/error_screen.h" +#include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/login/localized_values_builder.h" @@ -104,6 +105,9 @@ void ErrorScreenHandler::DeclareLocalizedValues( builder->Add("configureCertsButton", IDS_MANAGE_CERTIFICATES); builder->Add("continueButton", IDS_NETWORK_SELECTION_CONTINUE_BUTTON); builder->Add("okButton", IDS_APP_OK); + builder->Add("proxySettingsMenuName", IDS_PROXY_SETTINGS_MENU_NAME); + builder->Add("addWiFiNetworkMenuName", IDS_ADD_WI_FI_NETWORK_MENU_NAME); + network_element::AddLocalizedValuesToBuilder(builder); } void ErrorScreenHandler::Initialize() { @@ -117,11 +121,6 @@ void ErrorScreenHandler::Initialize() { } } -void ErrorScreenHandler::OnConnectToNetworkRequested() { - if (showing_ && screen_) - screen_->OnUserAction(ErrorScreen::kUserActionConnectRequested); -} - void ErrorScreenHandler::HandleHideCaptivePortal() { if (screen_) screen_->HideCaptivePortal(); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.h index f29d0da24a9..6569d585528 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.h @@ -9,14 +9,11 @@ #include "chrome/browser/chromeos/login/screens/error_screen.h" #include "chrome/browser/chromeos/login/screens/network_error_view.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" -#include "chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h" namespace chromeos { // A class that handles the WebUI hooks in error screen. -class ErrorScreenHandler : public BaseScreenHandler, - public NetworkErrorView, - public NetworkDropdownHandler::Observer { +class ErrorScreenHandler : public BaseScreenHandler, public NetworkErrorView { public: ErrorScreenHandler(); ~ErrorScreenHandler() override; @@ -37,9 +34,6 @@ class ErrorScreenHandler : public BaseScreenHandler, ::login::LocalizedValuesBuilder* builder) override; void Initialize() override; - // NetworkDropdownHandler: - void OnConnectToNetworkRequested() override; - // WebUI message handlers. void HandleHideCaptivePortal(); 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 d2be8e2f957..c23bcb22134 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 @@ -9,80 +9,24 @@ #include "base/macros.h" #include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/help_app_launcher.h" #include "chrome/browser/chromeos/login/helper.h" #include "chrome/browser/chromeos/login/oobe_screen.h" #include "chrome/browser/chromeos/login/screens/core_oobe_view.h" #include "chrome/browser/chromeos/login/screens/eula_screen.h" -#include "chrome/browser/chromeos/login/ui/login_display_webui.h" -#include "chrome/browser/chromeos/login/ui/login_web_dialog.h" -#include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" -#include "chrome/grit/locale_settings.h" #include "components/login/localized_values_builder.h" #include "components/strings/grit/components_strings.h" -#include "content/public/browser/web_contents.h" #include "rlz/buildflags/buildflags.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/views/widget/widget.h" #include "url/gurl.h" namespace { - constexpr char kJsScreenPath[] = "login.EulaScreen"; - -// Helper class to tweak display details of credits pages in the context -// of OOBE/EULA step. -class CreditsWebDialog : public chromeos::LoginWebDialog { - public: - CreditsWebDialog(Profile* profile, - gfx::NativeWindow parent_window, - int title_id, - const GURL& url) - : chromeos::LoginWebDialog(profile, NULL, parent_window, - l10n_util::GetStringUTF16(title_id), - url) { - } - - void OnLoadingStateChanged(content::WebContents* source) override { - chromeos::LoginWebDialog::OnLoadingStateChanged(source); - // Remove visual elements that we can handle in EULA page. - bool is_loading = source->IsLoading(); - if (!is_loading && source->GetWebUI()) { - source->GetWebUI()->CallJavascriptFunctionUnsafe( - "(function () {" - " document.body.classList.toggle('dialog', true);" - " keyboard.initializeKeyboardFlow(false);" - "})"); - } - } - - private: - DISALLOW_COPY_AND_ASSIGN(CreditsWebDialog); -}; - -void ShowCreditsDialog(Profile* profile, - gfx::NativeWindow parent_window, - int title_id, - const GURL& credits_url) { - CreditsWebDialog* dialog = new CreditsWebDialog(profile, - parent_window, - title_id, - credits_url); - dialog->SetDialogSize(l10n_util::GetLocalizedContentsWidthInPixels( - IDS_CREDITS_APP_DIALOG_WIDTH_PIXELS), - l10n_util::GetLocalizedContentsWidthInPixels( - IDS_CREDITS_APP_DIALOG_HEIGHT_PIXELS)); - dialog->Show(); - // The dialog object will be deleted on dialog close. } -} // namespace - namespace chromeos { EulaScreenHandler::EulaScreenHandler(CoreOobeView* core_oobe_view) @@ -156,9 +100,6 @@ void EulaScreenHandler::DeclareLocalizedValues( base::StringPrintf(chrome::kOnlineEulaURLPath, g_browser_process->GetApplicationLocale().c_str())); - builder->Add("chromeCreditsLink", IDS_ABOUT_VERSION_LICENSE_EULA); - builder->Add("chromeosCreditsLink", IDS_ABOUT_CROS_VERSION_LICENSE_EULA); - /* MD-OOBE */ builder->Add("oobeEulaSectionTitle", IDS_OOBE_EULA_SECTION_TITLE); builder->Add("oobeEulaIframeLabel", IDS_OOBE_EULA_IFRAME_LABEL); @@ -168,10 +109,6 @@ void EulaScreenHandler::DeclareLocalizedValues( void EulaScreenHandler::DeclareJSCallbacks() { AddCallback("eulaOnLearnMore", &EulaScreenHandler::HandleOnLearnMore); - AddCallback("eulaOnChromeOSCredits", - &EulaScreenHandler::HandleOnChromeOSCredits); - AddCallback("eulaOnChromeCredits", &EulaScreenHandler::HandleOnChromeCredits); - AddCallback("eulaOnLearnMore", &EulaScreenHandler::HandleOnLearnMore); AddCallback("eulaOnInstallationSettingsPopupOpened", &EulaScreenHandler::HandleOnInstallationSettingsPopupOpened); } @@ -190,11 +127,6 @@ void EulaScreenHandler::Initialize() { core_oobe_view_->SetUsageStats(screen_->IsUsageStatsEnabled()); - // This OEM EULA is a file:// URL which we're unable to load in iframe. - // Instead if it's defined we use chrome://terms/oem that will load same file. - if (!screen_->GetOemEulaUrl().is_empty()) - core_oobe_view_->SetOemEulaUrl(chrome::kChromeUITermsOemURL); - if (show_on_init_) { Show(); show_on_init_ = false; @@ -211,24 +143,6 @@ void EulaScreenHandler::HandleOnLearnMore() { help_app_->ShowHelpTopic(HelpAppLauncher::HELP_STATS_USAGE); } -void EulaScreenHandler::HandleOnChromeOSCredits() { - ShowCreditsDialog( - Profile::FromBrowserContext( - web_ui()->GetWebContents()->GetBrowserContext()), - GetNativeWindow(), - IDS_ABOUT_CROS_VERSION_LICENSE_EULA, - GURL(chrome::kChromeUIOSCreditsURL)); -} - -void EulaScreenHandler::HandleOnChromeCredits() { - ShowCreditsDialog( - Profile::FromBrowserContext( - web_ui()->GetWebContents()->GetBrowserContext()), - GetNativeWindow(), - IDS_ABOUT_VERSION_LICENSE_EULA, - GURL(chrome::kChromeUICreditsURL)); -} - void EulaScreenHandler::HandleOnInstallationSettingsPopupOpened() { if (screen_) screen_->InitiatePasswordFetch(); 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 a0830d4c6e9..e7dc2517322 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 @@ -49,8 +49,6 @@ class EulaScreenHandler : public EulaView, private: // JS messages handlers. void HandleOnLearnMore(); - void HandleOnChromeCredits(); - void HandleOnChromeOSCredits(); void HandleOnInstallationSettingsPopupOpened(); void UpdateLocalizedValues(::login::SecureModuleUsed secure_module_used); 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 67624d3155c..0d06906c4be 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 @@ -37,7 +37,6 @@ #include "chrome/browser/chromeos/policy/temp_certs_cache_nss.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chrome/browser/io_thread.h" #include "chrome/browser/lifetime/browser_shutdown.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/profiles/profile.h" @@ -52,11 +51,11 @@ #include "chrome/grit/generated_resources.h" #include "chrome/installer/util/google_update_settings.h" #include "chromeos/chromeos_switches.h" +#include "chromeos/dbus/util/version_loader.h" #include "chromeos/login/auth/authpolicy_login_helper.h" #include "chromeos/login/auth/user_context.h" #include "chromeos/settings/cros_settings_names.h" #include "chromeos/system/devicetype.h" -#include "chromeos/system/version_loader.h" #include "components/login/localized_values_builder.h" #include "components/policy/proto/chrome_device_policy.pb.h" #include "components/prefs/pref_service.h" @@ -68,6 +67,8 @@ #include "content/public/browser/render_frame_host.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/gaia_urls.h" +#include "mojo/public/cpp/bindings/callback_helpers.h" +#include "services/network/public/mojom/network_context.mojom.h" #include "ui/base/ime/chromeos/input_method_manager.h" #include "ui/base/ime/chromeos/input_method_util.h" #include "ui/base/l10n/l10n_util.h" @@ -109,12 +110,12 @@ policy::DeviceMode GetDeviceMode() { } GaiaScreenMode GetGaiaScreenMode(const std::string& email, bool use_offline) { - if (GetDeviceMode() == policy::DEVICE_MODE_ENTERPRISE_AD) - return GAIA_SCREEN_MODE_AD; - if (use_offline) return GAIA_SCREEN_MODE_OFFLINE; + if (GetDeviceMode() == policy::DEVICE_MODE_ENTERPRISE_AD) + return GAIA_SCREEN_MODE_AD; + int authentication_behavior = 0; CrosSettings::Get()->GetInteger(kLoginAuthenticationBehavior, &authentication_behavior); @@ -196,16 +197,6 @@ void RecordSAMLScrapingVerificationResultInHistogram(bool success) { UMA_HISTOGRAM_BOOLEAN("ChromeOS.SAML.Scraping.VerificationResult", success); } -// The Task posted to PostTaskAndReply in StartClearingDnsCache on the IO -// thread. -void ClearDnsCache(IOThread* io_thread) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - if (browser_shutdown::IsTryingToQuit()) - return; - - io_thread->ClearHostCache(base::Callback<bool(const std::string&)>()); -} - void PushFrontIMIfNotExists(const std::string& input_method, std::vector<std::string>* input_methods) { if (input_method.empty()) @@ -254,6 +245,19 @@ user_manager::UserType CalculateUserType(const AccountId& account_id) { return user_manager::USER_TYPE_REGULAR; } + +std::string GetAdErrorMessage(authpolicy::ErrorType error) { + switch (error) { + case authpolicy::ERROR_NETWORK_PROBLEM: + return l10n_util::GetStringUTF8(IDS_AD_AUTH_NETWORK_ERROR); + case authpolicy::ERROR_KDC_DOES_NOT_SUPPORT_ENCRYPTION_TYPE: + return l10n_util::GetStringUTF8(IDS_AD_AUTH_NOT_SUPPORTED_ENCRYPTION); + default: + DLOG(WARNING) << "Unhandled error code: " << error; + return l10n_util::GetStringUTF8(IDS_AD_AUTH_UNKNOWN_ERROR); + } +} + } // namespace // A class that's used to specify the way how Gaia should be loaded. @@ -409,10 +413,15 @@ void GaiaScreenHandler::LoadGaiaWithPartitionAndVersionAndConsent( const AccountId& owner_account_id = user_manager::UserManager::Get()->GetOwnerAccountId(); params.SetBoolean("hasDeviceOwner", owner_account_id.is_valid()); - if (owner_account_id.is_valid() && - user_manager::UserManager::Get()->FindUser(owner_account_id)->GetType() == - user_manager::UserType::USER_TYPE_CHILD) { - params.SetString("obfuscatedOwnerId", owner_account_id.GetGaiaId()); + if (owner_account_id.is_valid()) { + // Some Autotest policy tests appear to wipe the user list in Local State + // but preserve a policy file referencing an owner: https://crbug.com/850139 + const user_manager::User* owner_user = + user_manager::UserManager::Get()->FindUser(owner_account_id); + if (owner_user && + owner_user->GetType() == user_manager::UserType::USER_TYPE_CHILD) { + params.SetString("obfuscatedOwnerId", owner_account_id.GetGaiaId()); + } } params.SetString("chromeType", GetChromeType()); @@ -565,10 +574,11 @@ void GaiaScreenHandler::RegisterMessages() { AddCallback("cancelAdAuthentication", &GaiaScreenHandler::HandleCancelActiveDirectoryAuth); AddRawCallback("showAddUser", &GaiaScreenHandler::HandleShowAddUser); - AddCallback("updateGaiaDialogSize", - &GaiaScreenHandler::HandleUpdateGaiaDialogSize); - AddCallback("updateGaiaDialogVisibility", - &GaiaScreenHandler::HandleUpdateGaiaDialogVisibility); + AddCallback("getIsSamlUserPasswordless", + &GaiaScreenHandler::HandleGetIsSamlUserPasswordless); + AddCallback("updateOobeDialogSize", + &GaiaScreenHandler::HandleUpdateOobeDialogSize); + AddCallback("hideOobeDialog", &GaiaScreenHandler::HandleHideOobeDialog); // Allow UMA metrics collection from JS. web_ui()->AddMessageHandler(std::make_unique<MetricsHandler>()); @@ -694,14 +704,13 @@ void GaiaScreenHandler::DoAdAuth( break; case authpolicy::ERROR_BAD_PASSWORD: CallJS("invalidateAd", username, - static_cast<int>(ActiveDirectoryErrorState::BAD_PASSWORD)); + static_cast<int>(ActiveDirectoryErrorState::BAD_AUTH_PASSWORD)); break; default: - DLOG(WARNING) << "Unhandled error code: " << error; CallJS("invalidateAd", username, static_cast<int>(ActiveDirectoryErrorState::NONE)); core_oobe_view_->ShowSignInError( - 0, l10n_util::GetStringUTF8(IDS_AD_AUTH_UNKNOWN_ERROR), std::string(), + 0, GetAdErrorMessage(error), std::string(), HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT); } } @@ -805,16 +814,14 @@ void GaiaScreenHandler::HandleGaiaUIReady() { LoginDisplayHost::default_host()->OnGaiaScreenReady(); } -void GaiaScreenHandler::HandleUpdateGaiaDialogSize(int width, int height) { +void GaiaScreenHandler::HandleUpdateOobeDialogSize(int width, int height) { if (LoginDisplayHost::default_host()) - LoginDisplayHost::default_host()->UpdateGaiaDialogSize(width, height); + LoginDisplayHost::default_host()->UpdateOobeDialogSize(width, height); } -void GaiaScreenHandler::HandleUpdateGaiaDialogVisibility(bool visible) { - if (LoginDisplayHost::default_host()) { - LoginDisplayHost::default_host()->UpdateGaiaDialogVisibility(visible, - base::nullopt); - } +void GaiaScreenHandler::HandleHideOobeDialog() { + if (LoginDisplayHost::default_host()) + LoginDisplayHost::default_host()->HideOobeDialog(); } void GaiaScreenHandler::HandleShowAddUser(const base::ListValue* args) { @@ -833,6 +840,18 @@ void GaiaScreenHandler::HandleShowAddUser(const base::ListValue* args) { OnShowAddUser(); } +void GaiaScreenHandler::HandleGetIsSamlUserPasswordless( + const std::string& callback_id, + const std::string& typed_email, + const std::string& gaia_id) { + AllowJavascript(); + // TODO(emaxx,https://crbug.com/826417): Determine the result value based on + // known_user properties if the user already existed, or the + // DeviceSamlLoginAuthenticationType policy if that's a new user. + ResolveJavascriptCallback(base::Value(callback_id), + base::Value(false) /* isSamlUserPasswordless */); +} + void GaiaScreenHandler::OnShowAddUser() { signin_screen_handler_->is_account_picker_showing_first_time_ = false; lock_screen_utils::EnforcePolicyInputMethods(std::string()); @@ -862,6 +881,19 @@ void GaiaScreenHandler::DoCompleteLogin(const std::string& gaia_id, user ? UserContext(*user) : UserContext(CalculateUserType(account_id), account_id); user_context.SetKey(Key(password)); + // Save the user's plaintext password for possible authentication to a + // network. If the user's OpenNetworkConfiguration policy contains a + // ${PASSWORD} variable, then the user's password will be used to authenticate + // to the specified network. + // + // The user's password needs to be saved in memory until the policy can be + // examined. When the policy comes in, if it does not contain the ${PASSWORD} + // variable, the user's password will be discarded. If it contains the + // password, it will be sent to the session manager, which will then save it + // in a keyring so it can be retrieved for authenticating to the network. + // + // More details can be found in https://crbug.com/386606 + user_context.SetPasswordKey(Key(password)); user_context.SetAuthFlow(using_saml ? UserContext::AUTH_FLOW_GAIA_WITH_SAML : UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML); @@ -878,15 +910,23 @@ void GaiaScreenHandler::DoCompleteLogin(const std::string& gaia_id, } void GaiaScreenHandler::StartClearingDnsCache() { - if (dns_clear_task_running_ || !g_browser_process->io_thread()) + if (dns_clear_task_running_ || + !g_browser_process->system_network_context_manager()) { return; + } dns_cleared_ = false; - BrowserThread::PostTaskAndReply( - BrowserThread::IO, FROM_HERE, - base::BindOnce(&ClearDnsCache, g_browser_process->io_thread()), - base::BindOnce(&GaiaScreenHandler::OnDnsCleared, - weak_factory_.GetWeakPtr())); + + g_browser_process->system_network_context_manager() + ->GetContext() + ->ClearHostCache(nullptr /* filter */, + // Need to ensure that even if the network service + // crashes, OnDnsCleared() is invoked. + mojo::WrapCallbackWithDropHandler( + base::BindOnce(&GaiaScreenHandler::OnDnsCleared, + weak_factory_.GetWeakPtr()), + base::BindOnce(&GaiaScreenHandler::OnDnsCleared, + weak_factory_.GetWeakPtr()))); dns_clear_task_running_ = true; } @@ -915,27 +955,6 @@ void GaiaScreenHandler::OnCookiesCleared( on_clear_callback.Run(); } -void GaiaScreenHandler::ShowSigninScreenForTest(const std::string& username, - const std::string& password, - const std::string& services) { - VLOG(2) << "ShowSigninScreenForTest for user " << username - << ", frame_state=" << frame_state(); - - test_user_ = username; - test_pass_ = password; - test_services_ = services; - test_expects_complete_login_ = true; - - // Submit login form for test if gaia is ready. If gaia is loading, login - // will be attempted in HandleLoginWebuiReady after gaia is ready. Otherwise, - // reload gaia then follow the loading case. - if (frame_state() == GaiaScreenHandler::FRAME_STATE_LOADED) { - SubmitLoginFormForTest(); - } else if (frame_state() != GaiaScreenHandler::FRAME_STATE_LOADING) { - OnShowAddUser(); - } -} - void GaiaScreenHandler::SubmitLoginFormForTest() { VLOG(2) << "Submit login form for test, user=" << test_user_; @@ -989,6 +1008,27 @@ void GaiaScreenHandler::ShowGaiaAsync( } } +void GaiaScreenHandler::ShowSigninScreenForTest(const std::string& username, + const std::string& password, + const std::string& services) { + VLOG(2) << "ShowSigninScreenForTest for user " << username + << ", frame_state=" << frame_state(); + + test_user_ = username; + test_pass_ = password; + test_services_ = services; + test_expects_complete_login_ = true; + + // Submit login form for test if gaia is ready. If gaia is loading, login + // will be attempted in HandleLoginWebuiReady after gaia is ready. Otherwise, + // reload gaia then follow the loading case. + if (frame_state() == GaiaScreenHandler::FRAME_STATE_LOADED) { + SubmitLoginFormForTest(); + } else if (frame_state() != GaiaScreenHandler::FRAME_STATE_LOADING) { + OnShowAddUser(); + } +} + void GaiaScreenHandler::CancelShowGaiaAsync() { show_when_dns_and_cookies_cleared_ = false; } 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 ca864555dfd..84306fde47f 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 @@ -53,6 +53,9 @@ class GaiaScreenHandler : public BaseScreenHandler, void MaybePreloadAuthExtension() override; void DisableRestrictiveProxyCheckForTest() override; void ShowGaiaAsync(const base::Optional<AccountId>& account_id) override; + void ShowSigninScreenForTest(const std::string& username, + const std::string& password, + const std::string& services) override; private: // TODO (xiaoyinh): remove this dependency. @@ -128,9 +131,12 @@ class GaiaScreenHandler : public BaseScreenHandler, void HandleIdentifierEntered(const std::string& account_identifier); void HandleAuthExtensionLoaded(); - void HandleUpdateGaiaDialogSize(int width, int height); - void HandleUpdateGaiaDialogVisibility(bool visible); + void HandleUpdateOobeDialogSize(int width, int height); + void HandleHideOobeDialog(); void HandleShowAddUser(const base::ListValue* args); + void HandleGetIsSamlUserPasswordless(const std::string& callback_id, + const std::string& typed_email, + const std::string& gaia_id); void OnShowAddUser(); // Really handles the complete login message. @@ -158,11 +164,6 @@ class GaiaScreenHandler : public BaseScreenHandler, authpolicy::ErrorType error, const authpolicy::ActiveDirectoryAccountInfo& account_info); - // Show sign-in screen for the given credentials. - // Should match the same method in SigninScreenHandler. - void ShowSigninScreenForTest(const std::string& username, - const std::string& password, - const std::string& services); // Attempts login for test. void SubmitLoginFormForTest(); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.cc b/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.cc deleted file mode 100644 index accfc0f7ec1..00000000000 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.cc +++ /dev/null @@ -1,217 +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/chromeos/login/network_dropdown.h" - -#include <memory> -#include <string> -#include <utility> - -#include "ash/system/network/network_icon.h" -#include "ash/system/network/network_icon_animation.h" -#include "base/macros.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" -#include "base/values.h" -#include "chrome/browser/chromeos/login/ui/login_display_host.h" -#include "chrome/browser/ui/webui/chromeos/internet_detail_dialog.h" -#include "chromeos/network/network_state_handler.h" -#include "content/public/browser/web_ui.h" -#include "ui/base/models/menu_model.h" -#include "ui/base/webui/web_ui_util.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/image/image_skia.h" - -namespace { - -// Timeout between consecutive requests to network library for network -// scan. -const int kNetworkScanIntervalSecs = 60; - -} // namespace - -namespace chromeos { - -// WebUI specific implementation of the NetworkMenu class. -class NetworkMenuWebUI : public NetworkMenu { - public: - NetworkMenuWebUI(NetworkMenu::Delegate* delegate, content::WebUI* web_ui); - - // NetworkMenu override: - void UpdateMenu() override; - - // Called when item with command |id| is chosen. - void OnItemChosen(int id); - - private: - // Converts menu model into the ListValue, ready for passing to WebUI. - std::unique_ptr<base::ListValue> ConvertMenuModel(ui::MenuModel* model); - - // WebUI where network menu is located. - content::WebUI* web_ui_; - - DISALLOW_COPY_AND_ASSIGN(NetworkMenuWebUI); -}; - -// NetworkMenuWebUI ------------------------------------------------------------ - -NetworkMenuWebUI::NetworkMenuWebUI(NetworkMenu::Delegate* delegate, - content::WebUI* web_ui) - : NetworkMenu(delegate), - web_ui_(web_ui) { -} - -void NetworkMenuWebUI::UpdateMenu() { - NetworkMenu::UpdateMenu(); - if (web_ui_) { - std::unique_ptr<base::ListValue> list(ConvertMenuModel(GetMenuModel())); - web_ui_->CallJavascriptFunctionUnsafe("cr.ui.DropDown.updateNetworks", - *list); - } -} - -void NetworkMenuWebUI::OnItemChosen(int id) { - int index; - ui::MenuModel* model = GetMenuModel(); - if (!ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) - return; - model->ActivatedAt(index); -} - -std::unique_ptr<base::ListValue> NetworkMenuWebUI::ConvertMenuModel( - ui::MenuModel* model) { - auto list = std::make_unique<base::ListValue>(); - for (int i = 0; i < model->GetItemCount(); ++i) { - ui::MenuModel::ItemType type = model->GetTypeAt(i); - int id; - if (type == ui::MenuModel::TYPE_SEPARATOR) - id = -2; - else - id = model->GetCommandIdAt(i); - auto item = std::make_unique<base::DictionaryValue>(); - item->SetInteger("id", id); - base::string16 label = model->GetLabelAt(i); - base::ReplaceSubstringsAfterOffset(&label, 0, base::ASCIIToUTF16("&&"), - base::ASCIIToUTF16("&")); - item->SetString("label", label); - gfx::Image icon; - if (model->GetIconAt(i, &icon)) { - SkBitmap icon_bitmap = icon.ToImageSkia()->GetRepresentation( - web_ui_->GetDeviceScaleFactor()).sk_bitmap(); - item->SetString("icon", webui::GetBitmapDataUrl(icon_bitmap)); - } - if (id >= 0) { - item->SetBoolean("enabled", model->IsEnabledAt(i)); - const gfx::FontList* font_list = model->GetLabelFontListAt(i); - if (font_list) - item->SetBoolean("bold", - font_list->GetFontWeight() == gfx::Font::Weight::BOLD); - } - if (type == ui::MenuModel::TYPE_SUBMENU) - item->Set("sub", ConvertMenuModel(model->GetSubmenuModelAt(i))); - list->Append(std::move(item)); - } - return list; -} - -// NetworkDropdown ------------------------------------------------------------- - -NetworkDropdown::NetworkDropdown(View* view, content::WebUI* web_ui, bool oobe) - : view_(view), web_ui_(web_ui), oobe_(oobe) { - DCHECK(view_); - network_menu_.reset(new NetworkMenuWebUI(this, web_ui)); - DCHECK(NetworkHandler::IsInitialized()); - NetworkStateHandler* handler = NetworkHandler::Get()->network_state_handler(); - handler->RequestScan(NetworkTypePattern::WiFi()); - handler->AddObserver(this, FROM_HERE); - Refresh(); - network_scan_timer_.Start( - FROM_HERE, - base::TimeDelta::FromSeconds(kNetworkScanIntervalSecs), - this, &NetworkDropdown::RequestNetworkScan); -} - -NetworkDropdown::~NetworkDropdown() { - ash::network_icon::NetworkIconAnimation::GetInstance()->RemoveObserver(this); - if (NetworkHandler::IsInitialized()) { - NetworkHandler::Get()->network_state_handler()->RemoveObserver( - this, FROM_HERE); - } -} - -void NetworkDropdown::OnItemChosen(int id) { - network_menu_->OnItemChosen(id); -} - -gfx::NativeWindow NetworkDropdown::GetNativeWindow() const { - return LoginDisplayHost::default_host()->GetNativeWindow(); -} - -void NetworkDropdown::OpenButtonOptions() { - // Empty string opens the internet detail dialog for the default network. - InternetDetailDialog::ShowDialog(""); -} - -bool NetworkDropdown::ShouldOpenButtonOptions() const { - return !oobe_; -} - -void NetworkDropdown::OnConnectToNetworkRequested() { - view_->OnConnectToNetworkRequested(); -} - -void NetworkDropdown::DefaultNetworkChanged(const NetworkState* network) { - Refresh(); -} - -void NetworkDropdown::NetworkConnectionStateChanged( - const NetworkState* network) { - Refresh(); -} - -void NetworkDropdown::NetworkListChanged() { - Refresh(); -} - -void NetworkDropdown::NetworkIconChanged() { - SetNetworkIconAndText(); -} - -void NetworkDropdown::Refresh() { - SetNetworkIconAndText(); - network_menu_->UpdateMenu(); -} - -void NetworkDropdown::SetNetworkIconAndText() { - base::string16 text; - gfx::ImageSkia icon_image; - bool animating = false; - ash::network_icon::GetDefaultNetworkImageAndLabel( - ash::network_icon::ICON_TYPE_LIST, &icon_image, &text, &animating); - if (animating) { - ash::network_icon::NetworkIconAnimation::GetInstance()->AddObserver(this); - } else { - ash::network_icon::NetworkIconAnimation::GetInstance()->RemoveObserver( - this); - } - SkBitmap icon_bitmap = icon_image.GetRepresentation( - web_ui_->GetDeviceScaleFactor()).sk_bitmap(); - std::string icon_str; - if (!icon_image.isNull()) - icon_str = webui::GetBitmapDataUrl(icon_bitmap); - base::Value title(text); - base::Value icon(icon_str); - web_ui_->CallJavascriptFunctionUnsafe("cr.ui.DropDown.updateNetworkTitle", - title, icon); -} - -void NetworkDropdown::RequestNetworkScan() { - NetworkHandler::Get()->network_state_handler()->RequestScan( - NetworkTypePattern::WiFi()); - Refresh(); -} - -} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.h b/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.h deleted file mode 100644 index 3eaddd0025c..00000000000 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.h +++ /dev/null @@ -1,87 +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_CHROMEOS_LOGIN_NETWORK_DROPDOWN_H_ -#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_NETWORK_DROPDOWN_H_ - -#include <memory> - -#include "ash/system/network/network_icon_animation_observer.h" -#include "base/macros.h" -#include "base/timer/timer.h" -#include "chrome/browser/chromeos/status/network_menu.h" -#include "chromeos/network/network_state_handler_observer.h" -#include "ui/gfx/native_widget_types.h" - -namespace content { -class WebUI; -} - -namespace chromeos { - -class NetworkMenuWebUI; -class NetworkState; - -// Class which implements network dropdown menu using WebUI. -class NetworkDropdown : public NetworkMenu::Delegate, - public NetworkStateHandlerObserver, - public ash::network_icon::AnimationObserver { - public: - class View { - public: - virtual ~View() {} - virtual void OnConnectToNetworkRequested() = 0; - }; - - NetworkDropdown(View* view, content::WebUI* web_ui, bool oobe); - ~NetworkDropdown() override; - - // This method should be called, when item with the given id is chosen. - void OnItemChosen(int id); - - // NetworkMenu::Delegate - gfx::NativeWindow GetNativeWindow() const override; - void OpenButtonOptions() override; - bool ShouldOpenButtonOptions() const override; - void OnConnectToNetworkRequested() override; - - // NetworkStateHandlerObserver - void DefaultNetworkChanged(const NetworkState* network) override; - void NetworkConnectionStateChanged(const NetworkState* network) override; - void NetworkListChanged() override; - - // network_icon::AnimationObserver - void NetworkIconChanged() override; - - // Refreshes control state. Usually there's no need to do it manually - // as control refreshes itself on network state change. - // Should be called on language change. - void Refresh(); - - private: - void SetNetworkIconAndText(); - - // Request a network scan and refreshes control state. Should be called - // by |network_scan_timer_| only. - void RequestNetworkScan(); - - // The Network menu. - std::unique_ptr<NetworkMenuWebUI> network_menu_; - - View* view_; - - content::WebUI* web_ui_; - - // Is the dropdown shown on one of the OOBE screens. - bool oobe_; - - // Timer used to periodically force network scan. - base::RepeatingTimer network_scan_timer_; - - DISALLOW_COPY_AND_ASSIGN(NetworkDropdown); -}; - -} // namespace chromeos - -#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_NETWORK_DROPDOWN_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.cc index 11d88571163..d85e146e9bb 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.cc @@ -4,29 +4,18 @@ #include "chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h" -#include "chrome/browser/chromeos/login/ui/login_display_webui.h" -#include "chrome/browser/chromeos/options/network_config_view.h" #include "chrome/browser/ui/webui/chromeos/internet_config_dialog.h" #include "chrome/browser/ui/webui/chromeos/internet_detail_dialog.h" -#include "chrome/browser/ui/webui/chromeos/login/network_dropdown.h" -#include "chrome/grit/generated_resources.h" #include "chromeos/chromeos_switches.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/network_type_pattern.h" -#include "components/login/localized_values_builder.h" #include "components/onc/onc_constants.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace { -const char kJsScreenPath[] = "cr.ui.DropDown"; - // JS API callbacks names. -const char kJsApiNetworkItemChosen[] = "networkItemChosen"; -const char kJsApiNetworkDropdownShow[] = "networkDropdownShow"; -const char kJsApiNetworkDropdownHide[] = "networkDropdownHide"; -const char kJsApiNetworkDropdownRefresh[] = "networkDropdownRefresh"; const char kJsApiLaunchInternetDetailDialog[] = "launchInternetDetailDialog"; const char kJsApiLaunchAddWiFiNetworkDialog[] = "launchAddWiFiNetworkDialog"; const char kJsApiShowNetworkConfig[] = "showNetworkConfig"; @@ -36,40 +25,16 @@ const char kJsApiShowNetworkDetails[] = "showNetworkDetails"; namespace chromeos { -NetworkDropdownHandler::NetworkDropdownHandler() { - set_call_js_prefix(kJsScreenPath); -} - -NetworkDropdownHandler::~NetworkDropdownHandler() {} - -void NetworkDropdownHandler::AddObserver(Observer* observer) { - if (observer && !observers_.HasObserver(observer)) - observers_.AddObserver(observer); -} +NetworkDropdownHandler::NetworkDropdownHandler() = default; -void NetworkDropdownHandler::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} +NetworkDropdownHandler::~NetworkDropdownHandler() = default; void NetworkDropdownHandler::DeclareLocalizedValues( - ::login::LocalizedValuesBuilder* builder) { - builder->Add("selectNetwork", IDS_NETWORK_SELECTION_SELECT); - builder->Add("selectAnotherNetwork", IDS_ANOTHER_NETWORK_SELECTION_SELECT); -} + ::login::LocalizedValuesBuilder* builder) {} void NetworkDropdownHandler::Initialize() {} void NetworkDropdownHandler::RegisterMessages() { - AddCallback(kJsApiNetworkItemChosen, - &NetworkDropdownHandler::HandleNetworkItemChosen); - AddCallback(kJsApiNetworkDropdownShow, - &NetworkDropdownHandler::HandleNetworkDropdownShow); - AddCallback(kJsApiNetworkDropdownHide, - &NetworkDropdownHandler::HandleNetworkDropdownHide); - AddCallback(kJsApiNetworkDropdownRefresh, - &NetworkDropdownHandler::HandleNetworkDropdownRefresh); - - // MD-OOBE AddCallback(kJsApiLaunchInternetDetailDialog, &NetworkDropdownHandler::HandleLaunchInternetDetailDialog); AddCallback(kJsApiLaunchAddWiFiNetworkDialog, @@ -93,12 +58,8 @@ void NetworkDropdownHandler::HandleLaunchAddWiFiNetworkDialog() { handler->SetTechnologyEnabled(NetworkTypePattern::WiFi(), true, network_handler::ErrorCallback()); } - if (chromeos::switches::IsNetworkSettingsConfigEnabled()) { - chromeos::InternetConfigDialog::ShowDialogForNetworkType( - ::onc::network_type::kWiFi); - } else { - NetworkConfigView::ShowForType(shill::kTypeWifi); - } + chromeos::InternetConfigDialog::ShowDialogForNetworkType( + ::onc::network_type::kWiFi); } void NetworkDropdownHandler::HandleShowNetworkDetails( @@ -123,42 +84,7 @@ void NetworkDropdownHandler::HandleShowNetworkConfig( const base::ListValue* args) { std::string guid; args->GetString(0, &guid); - if (chromeos::switches::IsNetworkSettingsConfigEnabled()) - chromeos::InternetConfigDialog::ShowDialogForNetworkId(guid); - else - NetworkConfigView::ShowForNetworkId(guid); -} - -void NetworkDropdownHandler::OnConnectToNetworkRequested() { - for (Observer& observer : observers_) - observer.OnConnectToNetworkRequested(); -} - -void NetworkDropdownHandler::HandleNetworkItemChosen(double id) { - if (dropdown_.get()) { - dropdown_->OnItemChosen(static_cast<int>(id)); - } else { - // It could happen with very low probability but still keep NOTREACHED to - // detect if it starts happening all the time. - NOTREACHED(); - } -} - -void NetworkDropdownHandler::HandleNetworkDropdownShow( - const std::string& element_id, - bool oobe) { - dropdown_.reset(new NetworkDropdown(this, web_ui(), oobe)); -} - -void NetworkDropdownHandler::HandleNetworkDropdownHide() { - dropdown_.reset(); -} - -void NetworkDropdownHandler::HandleNetworkDropdownRefresh() { - // Since language change is async, - // we may in theory be on another screen during this call. - if (dropdown_.get()) - dropdown_->Refresh(); + chromeos::InternetConfigDialog::ShowDialogForNetworkId(guid); } } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h index 72d8b13d7df..1cf2b0eb9a7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h @@ -9,27 +9,16 @@ #include <string> #include "base/macros.h" -#include "base/observer_list.h" #include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" -#include "chrome/browser/ui/webui/chromeos/login/network_dropdown.h" namespace chromeos { -class NetworkDropdownHandler : public BaseWebUIHandler, - public NetworkDropdown::View { +// Class for handling network configuration UI events in loggin/oobe WebUI. +class NetworkDropdownHandler : public BaseWebUIHandler { public: - class Observer { - public: - virtual ~Observer() {} - virtual void OnConnectToNetworkRequested() = 0; - }; - NetworkDropdownHandler(); ~NetworkDropdownHandler() override; - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - // BaseScreenHandler implementation: void DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) override; @@ -39,28 +28,11 @@ class NetworkDropdownHandler : public BaseWebUIHandler, void RegisterMessages() override; private: - // NetworkDropdown::Actor implementation: - void OnConnectToNetworkRequested() override; - - // Handles choosing of the network menu item. - void HandleNetworkItemChosen(double id); - // Handles network drop-down showing. - void HandleNetworkDropdownShow(const std::string& element_id, - bool oobe); - // Handles network drop-down hiding. - void HandleNetworkDropdownHide(); - // Handles network drop-down refresh. - void HandleNetworkDropdownRefresh(); - void HandleLaunchInternetDetailDialog(); void HandleLaunchAddWiFiNetworkDialog(); void HandleShowNetworkDetails(const base::ListValue* args); void HandleShowNetworkConfig(const base::ListValue* args); - std::unique_ptr<NetworkDropdown> dropdown_; - - base::ObserverList<Observer> observers_; - DISALLOW_COPY_AND_ASSIGN(NetworkDropdownHandler); }; 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 de69ed2ca08..939f64a69a9 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,10 +6,12 @@ #include <stdint.h> -#include "ash/display/window_tree_host_manager.h" -#include "ash/shell.h" -#include "base/stl_util.h" +#include "ash/public/interfaces/constants.mojom.h" +#include "base/strings/string_number_conversions.h" +#include "chrome/browser/ui/ash/ash_util.h" #include "content/public/browser/browser_thread.h" +#include "content/public/common/service_manager_connection.h" +#include "services/service_manager/public/cpp/connector.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/events/devices/input_device_manager.h" @@ -37,7 +39,14 @@ bool IsWhiteListedVendorId(uint16_t vendor_id) { } // namespace OobeDisplayChooser::OobeDisplayChooser() - : scoped_observer_(this), weak_ptr_factory_(this) {} + : scoped_observer_(this), weak_ptr_factory_(this) { + // |connector| may be null in tests. + auto* connector = ash_util::GetServiceManagerConnector(); + if (connector) { + connector->BindInterface(ash::mojom::kServiceName, + &cros_display_config_ptr_); + } +} OobeDisplayChooser::~OobeDisplayChooser() {} @@ -82,8 +91,11 @@ void OobeDisplayChooser::MoveToTouchDisplay() { input_device_manager->GetTouchscreenDevices()) { if (IsWhiteListedVendorId(device.vendor_id) && device.target_display_id != display::kInvalidDisplayId) { - ash::Shell::Get()->window_tree_host_manager()->SetPrimaryDisplayId( - device.target_display_id); + auto config_properties = ash::mojom::DisplayConfigProperties::New(); + config_properties->set_primary = true; + cros_display_config_ptr_->SetDisplayProperties( + base::Int64ToString(device.target_display_id), + std::move(config_properties), base::DoNothing()); break; } } 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 c606294f5d2..02ff8686537 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,6 +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 "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" @@ -25,6 +26,11 @@ class OobeDisplayChooser : public ui::InputDeviceEventObserver { // Must be called on the BrowserThread::UI thread. void TryToPlaceUiOnTouchDisplay(); + void set_cros_display_config_ptr_for_test( + ash::mojom::CrosDisplayConfigControllerPtr cros_display_config_ptr) { + cros_display_config_ptr_ = std::move(cros_display_config_ptr); + } + private: // Calls MoveToTouchDisplay() if touch device list is ready, otherwise adds an // observer that calls MoveToTouchDisplay() once ready. @@ -39,6 +45,7 @@ class OobeDisplayChooser : public ui::InputDeviceEventObserver { ScopedObserver<ui::InputDeviceManager, ui::InputDeviceEventObserver> scoped_observer_; + ash::mojom::CrosDisplayConfigControllerPtr cros_display_config_ptr_; base::WeakPtrFactory<OobeDisplayChooser> weak_ptr_factory_; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc index 76621b4241e..641f57d2c23 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc @@ -11,6 +11,8 @@ #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "base/run_loop.h" +#include "base/strings/string_number_conversions.h" +#include "mojo/public/cpp/bindings/binding.h" #include "services/ui/public/cpp/input_devices/input_device_client_test_api.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/display/display.h" @@ -25,6 +27,52 @@ namespace chromeos { namespace { +class TestCrosDisplayConfig : public ash::mojom::CrosDisplayConfigController { + public: + TestCrosDisplayConfig() : binding_(this) {} + + ash::mojom::CrosDisplayConfigControllerPtr CreateInterfacePtrAndBind() { + ash::mojom::CrosDisplayConfigControllerPtr ptr; + binding_.Bind(mojo::MakeRequest(&ptr)); + return ptr; + } + + // ash::mojom::CrosDisplayConfigController: + void AddObserver(ash::mojom::CrosDisplayConfigObserverAssociatedPtrInfo + observer) override {} + void GetDisplayLayoutInfo(GetDisplayLayoutInfoCallback callback) override {} + void SetDisplayLayoutInfo(ash::mojom::DisplayLayoutInfoPtr info, + SetDisplayLayoutInfoCallback callback) override {} + void GetDisplayUnitInfoList( + bool single_unified, + GetDisplayUnitInfoListCallback callback) override {} + void SetDisplayProperties(const std::string& id, + ash::mojom::DisplayConfigPropertiesPtr properties, + SetDisplayPropertiesCallback callback) override { + if (properties->set_primary) { + int64_t display_id; + base::StringToInt64(id, &display_id); + ash::Shell::Get()->window_tree_host_manager()->SetPrimaryDisplayId( + display_id); + } + std::move(callback).Run(ash::mojom::DisplayConfigResult::kSuccess); + } + void SetUnifiedDesktopEnabled(bool enabled) override {} + void OverscanCalibration(const std::string& display_id, + ash::mojom::DisplayConfigOperation op, + const base::Optional<gfx::Insets>& delta, + OverscanCalibrationCallback callback) override {} + void TouchCalibration(const std::string& display_id, + ash::mojom::DisplayConfigOperation op, + ash::mojom::TouchCalibrationPtr calibration, + TouchCalibrationCallback callback) override {} + + private: + mojo::Binding<ash::mojom::CrosDisplayConfigController> binding_; + + DISALLOW_COPY_AND_ASSIGN(TestCrosDisplayConfig); +}; + class OobeDisplayChooserTest : public ash::AshTestBase { public: OobeDisplayChooserTest() : ash::AshTestBase() {} @@ -36,10 +84,21 @@ class OobeDisplayChooserTest : public ash::AshTestBase { // ash::AshTestBase: void SetUp() override { ash::AshTestBase::SetUp(); + + cros_display_config_ = std::make_unique<TestCrosDisplayConfig>(); + display_chooser_ = std::make_unique<OobeDisplayChooser>(); + display_chooser_->set_cros_display_config_ptr_for_test( + cros_display_config_->CreateInterfacePtrAndBind()); + ui::InputDeviceClientTestApi().OnDeviceListsComplete(); } + OobeDisplayChooser* display_chooser() { return display_chooser_.get(); } + private: + std::unique_ptr<TestCrosDisplayConfig> cros_display_config_; + std::unique_ptr<OobeDisplayChooser> display_chooser_; + DISALLOW_COPY_AND_ASSIGN(OobeDisplayChooserTest); }; @@ -83,9 +142,8 @@ TEST_F(OobeDisplayChooserTest, PreferTouchAsPrimary) { touchscreen.target_display_id = display_info[1].id(); ui::InputDeviceClientTestApi().SetTouchscreenDevices({touchscreen}, true); - OobeDisplayChooser display_chooser; EXPECT_EQ(1, GetPrimaryDisplay()); - display_chooser.TryToPlaceUiOnTouchDisplay(); + display_chooser()->TryToPlaceUiOnTouchDisplay(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(2, GetPrimaryDisplay()); } @@ -119,9 +177,8 @@ TEST_F(OobeDisplayChooserTest, DontSwitchFromTouch) { display_manager()->OnNativeDisplaysChanged(display_info); base::RunLoop().RunUntilIdle(); - OobeDisplayChooser display_chooser; EXPECT_EQ(1, GetPrimaryDisplay()); - display_chooser.TryToPlaceUiOnTouchDisplay(); + display_chooser()->TryToPlaceUiOnTouchDisplay(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, GetPrimaryDisplay()); } 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 68d2d6caf88..4a80138f5a7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc @@ -19,6 +19,7 @@ #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chromeos/login/enrollment/auto_enrollment_check_screen_view.h" #include "chrome/browser/chromeos/login/enrollment/enrollment_screen_view.h" +#include "chrome/browser/chromeos/login/screens/demo_preferences_screen_view.h" #include "chrome/browser/chromeos/login/screens/demo_setup_screen_view.h" #include "chrome/browser/chromeos/login/screens/error_screen.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" @@ -29,17 +30,19 @@ #include "chrome/browser/extensions/signin/gaia_auth_extension_loader.h" #include "chrome/browser/extensions/tab_helper.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/ash/ash_util.h" #include "chrome/browser/ui/webui/about_ui.h" #include "chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h" +#include "chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/arc_kiosk_splash_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/auto_enrollment_check_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/controller_pairing_screen_handler.h" +#include "chrome/browser/ui/webui/chromeos/login/demo_preferences_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.h" +#include "chrome/browser/ui/webui/chromeos/login/discover_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h" @@ -52,7 +55,6 @@ #include "chrome/browser/ui/webui/chromeos/login/kiosk_autolaunch_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h" -#include "chrome/browser/ui/webui/chromeos/login/network_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h" #include "chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.h" @@ -67,6 +69,7 @@ #include "chrome/browser/ui/webui/chromeos/login/user_image_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/voice_interaction_value_prop_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.h" +#include "chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/user_image_source.h" #include "chrome/browser/ui/webui/test_files_request_filter.h" @@ -86,6 +89,7 @@ #include "content/public/browser/web_ui_data_source.h" #include "content/public/common/content_switches.h" #include "ui/base/resource/resource_bundle.h" +#include "ui/base/ui_base_features.h" #include "ui/base/webui/web_ui_util.h" #include "ui/display/display.h" #include "ui/events/devices/input_device.h" @@ -123,6 +127,9 @@ const char kArcPlaystoreJSPath[] = "playstore.js"; const char kArcPlaystoreLogoPath[] = "playstore.svg"; const char kProductLogoPath[] = "product-logo.png"; +const char kRecommendAppListViewJSPath[] = "recommend_app_list_view.js"; +const char kRecommendAppListViewHTMLPath[] = "recommend_app_list_view.html"; + #if defined(GOOGLE_CHROME_BUILD) const char kLogo24PX1XSvgPath[] = "logo_24px-1x.svg"; const char kLogo24PX2XSvgPath[] = "logo_24px-2x.svg"; @@ -182,6 +189,11 @@ content::WebUIDataSource* CreateOobeUIDataSource( source->AddResourcePath(kArcPlaystoreLogoPath, IDR_ARC_SUPPORT_PLAYSTORE_LOGO); + source->AddResourcePath(kRecommendAppListViewJSPath, + IDR_ARC_SUPPORT_RECOMMEND_APP_LIST_VIEW_JS); + source->AddResourcePath(kRecommendAppListViewHTMLPath, + IDR_ARC_SUPPORT_RECOMMEND_APP_LIST_VIEW_HTML); + // Required for Assistant OOBE. source->AddResourcePath(kArcAssistantLogoPath, IDR_ASSISTANT_LOGO_PNG); @@ -252,14 +264,12 @@ OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url) core_handler_ = core_handler.get(); AddWebUIHandler(std::move(core_handler)); - auto network_dropdown_handler = std::make_unique<NetworkDropdownHandler>(); - network_dropdown_handler_ = network_dropdown_handler.get(); - AddWebUIHandler(std::move(network_dropdown_handler)); + AddWebUIHandler(std::make_unique<NetworkDropdownHandler>()); AddScreenHandler(std::make_unique<UpdateScreenHandler>()); if (display_type_ == kOobeDisplay) - AddScreenHandler(std::make_unique<NetworkScreenHandler>(core_handler_)); + AddScreenHandler(std::make_unique<WelcomeScreenHandler>(core_handler_)); AddScreenHandler(std::make_unique<EnableDebuggingScreenHandler>()); @@ -284,7 +294,6 @@ OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url) AddScreenHandler(std::make_unique<HIDDetectionScreenHandler>(core_handler_)); AddScreenHandler(std::make_unique<ErrorScreenHandler>()); - network_dropdown_handler_->AddObserver(GetView<ErrorScreenHandler>()); error_screen_.reset(new ErrorScreen(nullptr, GetView<ErrorScreenHandler>())); ErrorScreen* error_screen = error_screen_.get(); @@ -301,12 +310,18 @@ OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url) AddScreenHandler(std::make_unique<RecommendAppsScreenHandler>()); + AddScreenHandler(std::make_unique<AppDownloadingScreenHandler>()); + AddScreenHandler(std::make_unique<UserImageScreenHandler>()); AddScreenHandler(std::make_unique<UserBoardScreenHandler>()); AddScreenHandler(std::make_unique<DemoSetupScreenHandler>()); + AddScreenHandler(std::make_unique<DemoPreferencesScreenHandler>()); + + AddScreenHandler(std::make_unique<DiscoverScreenHandler>()); + policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); ActiveDirectoryPasswordChangeScreenHandler* @@ -385,22 +400,19 @@ OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url) content::WebContents* contents = web_ui->GetWebContents(); extensions::TabHelper::CreateForWebContents(contents); - // TODO(felixe): Display iteration and primary display selection not supported - // in Mash. See http://crbug.com/720917. - if (!ash_util::IsRunningInMash() && IsRemoraRequisitioned()) + if (IsRemoraRequisitioned()) oobe_display_chooser_ = std::make_unique<OobeDisplayChooser>(); } OobeUI::~OobeUI() { - network_dropdown_handler_->RemoveObserver(GetView<ErrorScreenHandler>()); } CoreOobeView* OobeUI::GetCoreOobeView() { return core_handler_; } -NetworkView* OobeUI::GetNetworkView() { - return GetView<NetworkScreenHandler>(); +WelcomeView* OobeUI::GetWelcomeView() { + return GetView<WelcomeScreenHandler>(); } EulaView* OobeUI::GetEulaView() { @@ -427,6 +439,10 @@ DemoSetupScreenView* OobeUI::GetDemoSetupScreenView() { return GetView<DemoSetupScreenHandler>(); } +DemoPreferencesScreenView* OobeUI::GetDemoPreferencesScreenView() { + return GetView<DemoPreferencesScreenHandler>(); +} + KioskAutolaunchScreenView* OobeUI::GetKioskAutolaunchScreenView() { return GetView<KioskAutolaunchScreenHandler>(); } @@ -451,6 +467,10 @@ RecommendAppsScreenView* OobeUI::GetRecommendAppsScreenView() { return GetView<RecommendAppsScreenHandler>(); } +AppDownloadingScreenView* OobeUI::GetAppDownloadingScreenView() { + return GetView<AppDownloadingScreenHandler>(); +} + WrongHWIDScreenView* OobeUI::GetWrongHWIDScreenView() { return GetView<WrongHWIDScreenHandler>(); } @@ -525,6 +545,10 @@ ArcKioskSplashScreenView* OobeUI::GetArcKioskSplashScreenView() { return GetView<ArcKioskSplashScreenHandler>(); } +DiscoverScreenView* OobeUI::GetDiscoverScreenView() { + return GetView<DiscoverScreenHandler>(); +} + void OobeUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) { for (BaseWebUIHandler* handler : webui_handlers_) handler->GetLocalizedStrings(localized_strings); @@ -545,9 +569,6 @@ void OobeUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) { bool new_kiosk_ui = KioskAppMenuHandler::EnableNewKioskUI(); localized_strings->SetString("newKioskUI", new_kiosk_ui ? "on" : "off"); - oobe_ui_md_mode_ = - g_browser_process->local_state()->GetBoolean(prefs::kOobeMdMode); - localized_strings->SetString("newOobeUI", oobe_ui_md_mode_ ? "on" : "off"); localized_strings->SetString( "showViewsLock", ash::switches::IsUsingViewsLock() ? "on" : "off"); localized_strings->SetString( @@ -664,8 +685,11 @@ void OobeUI::ShowSigninScreen(const LoginScreenContext& context, signin_screen_handler_->SetNativeWindowDelegate(native_window_delegate); LoginScreenContext actual_context(context); - actual_context.set_oobe_ui(core_handler_->show_oobe_ui()); - signin_screen_handler_->Show(actual_context); + signin_screen_handler_->Show(actual_context, core_handler_->show_oobe_ui()); +} + +void OobeUI::ForwardAccelerator(std::string accelerator_name) { + core_handler_->ForwardAccelerator(accelerator_name); } void OobeUI::ResetSigninScreenHandlerDelegate() { @@ -682,17 +706,6 @@ void OobeUI::RemoveObserver(Observer* observer) { observer_list_.RemoveObserver(observer); } -void OobeUI::UpdateLocalizedStringsIfNeeded() { - if (oobe_ui_md_mode_ == - g_browser_process->local_state()->GetBoolean(prefs::kOobeMdMode)) { - return; - } - - base::DictionaryValue localized_strings; - GetLocalizedStrings(&localized_strings); - static_cast<CoreOobeView*>(core_handler_)->ReloadContent(localized_strings); -} - void OobeUI::OnDisplayConfigurationChanged() { if (oobe_display_chooser_) oobe_display_chooser_->TryToPlaceUiOnTouchDisplay(); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h index 88212363233..65a907ecbf2 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h @@ -25,6 +25,7 @@ class DictionaryValue; } // namespace base namespace chromeos { +class AppDownloadingScreenView; class AppLaunchSplashScreenView; class ArcKioskSplashScreenView; class ArcTermsOfServiceScreenView; @@ -38,6 +39,7 @@ class EncryptionMigrationScreenView; class EnrollmentScreenView; class EulaView; class ErrorScreen; +class DiscoverScreenView; class GaiaView; class HIDDetectionView; class HostPairingScreenView; @@ -46,9 +48,8 @@ class KioskAutolaunchScreenView; class KioskEnableScreenView; class LoginScreenContext; class NativeWindowDelegate; -class NetworkDropdownHandler; class NetworkStateInformer; -class NetworkView; +class WelcomeView; class OobeDisplayChooser; class RecommendAppsScreenView; class SigninScreenHandler; @@ -56,6 +57,7 @@ class SigninScreenHandlerDelegate; class SupervisedUserCreationScreenHandler; class ResetView; class DemoSetupScreenView; +class DemoPreferencesScreenView; class SyncConsentScreenView; class TermsOfServiceScreenView; class UserBoardView; @@ -100,19 +102,21 @@ class OobeUI : public content::WebUIController, ~OobeUI() override; CoreOobeView* GetCoreOobeView(); - NetworkView* GetNetworkView(); + WelcomeView* GetWelcomeView(); EulaView* GetEulaView(); UpdateView* GetUpdateView(); EnableDebuggingScreenView* GetEnableDebuggingScreenView(); EnrollmentScreenView* GetEnrollmentScreenView(); ResetView* GetResetView(); DemoSetupScreenView* GetDemoSetupScreenView(); + DemoPreferencesScreenView* GetDemoPreferencesScreenView(); KioskAutolaunchScreenView* GetKioskAutolaunchScreenView(); KioskEnableScreenView* GetKioskEnableScreenView(); TermsOfServiceScreenView* GetTermsOfServiceScreenView(); SyncConsentScreenView* GetSyncConsentScreenView(); ArcTermsOfServiceScreenView* GetArcTermsOfServiceScreenView(); RecommendAppsScreenView* GetRecommendAppsScreenView(); + AppDownloadingScreenView* GetAppDownloadingScreenView(); UserImageView* GetUserImageView(); ErrorScreen* GetErrorScreen(); WrongHWIDScreenView* GetWrongHWIDScreenView(); @@ -130,6 +134,7 @@ class OobeUI : public content::WebUIController, UpdateRequiredView* GetUpdateRequiredScreenView(); GaiaView* GetGaiaScreenView(); UserBoardView* GetUserBoardView(); + DiscoverScreenView* GetDiscoverScreenView(); // ShutdownPolicyHandler::Delegate void OnShutdownPolicyChanged(bool reboot_on_shutdown) override; @@ -162,6 +167,9 @@ class OobeUI : public content::WebUIController, SigninScreenHandlerDelegate* delegate, NativeWindowDelegate* native_window_delegate); + // Forwards an accelerator to the webui to be handled. + void ForwardAccelerator(std::string accelerator_name); + // Resets the delegate set in ShowSigninScreen. void ResetSigninScreenHandlerDelegate(); @@ -183,10 +191,6 @@ class OobeUI : public content::WebUIController, return network_state_informer_.get(); } - // Does ReloadContent() if needed (for example, if material design mode has - // changed). - void UpdateLocalizedStringsIfNeeded(); - // Re-evaluate OOBE display placement. void OnDisplayConfigurationChanged(); @@ -221,10 +225,6 @@ class OobeUI : public content::WebUIController, // Reference to CoreOobeHandler that handles common requests of Oobe page. CoreOobeHandler* core_handler_ = nullptr; - // Reference to NetworkDropdownHandler that handles interaction with - // network dropdown. - NetworkDropdownHandler* network_dropdown_handler_ = nullptr; - SupervisedUserCreationScreenHandler* supervised_user_creation_screen_view_ = nullptr; // Reference to SigninScreenHandler that handles sign-in screen requests and @@ -250,10 +250,6 @@ class OobeUI : public content::WebUIController, // calls. bool ready_ = false; - // This flag stores material-design mode (on/off) of currently displayed UI. - // If different version of UI is required, UI is updated. - bool oobe_ui_md_mode_ = false; - // Callbacks to notify when JS part is fully loaded and ready to accept calls. std::vector<base::Closure> ready_callbacks_; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.cc index 43a9addf12e..b55e82564a8 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.cc @@ -4,14 +4,25 @@ #include "chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.h" +#include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/login/screens/recommend_apps_screen.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/app_list/arc/arc_fast_app_reinstall_starter.h" +#include "chrome/grit/component_extension_resources.h" #include "chrome/grit/generated_resources.h" +#include "components/arc/arc_prefs.h" #include "components/login/localized_values_builder.h" +#include "ui/base/resource/resource_bundle.h" namespace { const char kJsScreenPath[] = "login.RecommendAppsScreen"; +constexpr const char kUserActionSkip[] = "recommendAppsSkip"; +constexpr const char kUserActionRetry[] = "recommendAppsRetry"; +constexpr const char kUserActionInstall[] = "recommendAppsInstall"; + } // namespace namespace chromeos { @@ -21,7 +32,10 @@ RecommendAppsScreenHandler::RecommendAppsScreenHandler() set_call_js_prefix(kJsScreenPath); } -RecommendAppsScreenHandler::~RecommendAppsScreenHandler() {} +RecommendAppsScreenHandler::~RecommendAppsScreenHandler() { + for (auto& observer : observer_list_) + observer.OnViewDestroyed(this); +} void RecommendAppsScreenHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) { @@ -31,10 +45,27 @@ void RecommendAppsScreenHandler::DeclareLocalizedValues( IDS_LOGIN_RECOMMEND_APPS_SCREEN_DESCRIPTION); builder->Add("recommendAppsSkip", IDS_LOGIN_RECOMMEND_APPS_SKIP); builder->Add("recommendAppsInstall", IDS_LOGIN_RECOMMEND_APPS_INSTALL); + builder->Add("recommendAppsRetry", IDS_LOGIN_RECOMMEND_APPS_RETRY); + builder->Add("recommendAppsLoading", IDS_LOGIN_RECOMMEND_APPS_SCREEN_LOADING); + builder->Add("recommendAppsError", IDS_LOGIN_RECOMMEND_APPS_SCREEN_ERROR); } void RecommendAppsScreenHandler::RegisterMessages() { BaseScreenHandler::RegisterMessages(); + AddCallback(kUserActionSkip, &RecommendAppsScreenHandler::HandleSkip); + AddCallback(kUserActionRetry, &RecommendAppsScreenHandler::HandleRetry); + AddRawCallback(kUserActionInstall, + &RecommendAppsScreenHandler::HandleInstall); +} + +void RecommendAppsScreenHandler::AddObserver( + RecommendAppsScreenViewObserver* observer) { + observer_list_.AddObserver(observer); +} + +void RecommendAppsScreenHandler::RemoveObserver( + RecommendAppsScreenViewObserver* observer) { + observer_list_.RemoveObserver(observer); } void RecommendAppsScreenHandler::Bind(RecommendAppsScreen* screen) { @@ -44,10 +75,60 @@ void RecommendAppsScreenHandler::Bind(RecommendAppsScreen* screen) { void RecommendAppsScreenHandler::Show() { ShowScreen(kScreenId); + + Profile* profile = ProfileManager::GetActiveUserProfile(); + pref_service_ = profile->GetPrefs(); } void RecommendAppsScreenHandler::Hide() {} void RecommendAppsScreenHandler::Initialize() {} +void RecommendAppsScreenHandler::LoadAppListInUI(const base::Value& app_list) { + if (!page_is_ready()) { + CallJS("showError"); + return; + } + const ui::ResourceBundle& resource_bundle = + ui::ResourceBundle::GetSharedInstance(); + base::StringPiece app_list_webview = resource_bundle.GetRawDataResource( + IDR_ARC_SUPPORT_RECOMMEND_APP_LIST_VIEW_HTML); + CallJS("setWebview", app_list_webview.as_string()); + CallJS("loadAppList", app_list); +} + +void RecommendAppsScreenHandler::OnLoadError() { + CallJS("showError"); +} + +void RecommendAppsScreenHandler::OnLoadSuccess(const base::Value& app_list) { + LoadAppListInUI(app_list); +} + +void RecommendAppsScreenHandler::HandleSkip() { + for (auto& observer : observer_list_) + observer.OnSkip(); +} + +void RecommendAppsScreenHandler::HandleRetry() { + for (auto& observer : observer_list_) + observer.OnRetry(); +} + +void RecommendAppsScreenHandler::HandleInstall(const base::ListValue* args) { + pref_service_->Set(arc::prefs::kArcFastAppReinstallPackages, *args); + + arc::ArcFastAppReinstallStarter* fast_app_reinstall_starter = + arc::ArcSessionManager::Get()->fast_app_resintall_starter(); + if (fast_app_reinstall_starter) { + fast_app_reinstall_starter->OnAppsSelectionFinished(); + } else { + LOG(ERROR) + << "Cannot complete Fast App Reinstall flow. Starter is not available."; + } + + for (auto& observer : observer_list_) + observer.OnInstall(); +} + } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.h index db4fe4987b9..c813764aeb6 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.h @@ -6,8 +6,10 @@ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_RECOMMEND_APPS_SCREEN_HANDLER_H_ #include "base/macros.h" +#include "base/values.h" #include "chrome/browser/chromeos/login/screens/recommend_apps_screen_view.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" +#include "components/prefs/pref_service.h" namespace chromeos { @@ -26,6 +28,8 @@ class RecommendAppsScreenHandler : public BaseScreenHandler, void RegisterMessages() override; // RecommendAppsScreenView: + void AddObserver(RecommendAppsScreenViewObserver* observer) override; + void RemoveObserver(RecommendAppsScreenViewObserver* observer) override; void Bind(RecommendAppsScreen* screen) override; void Show() override; void Hide() override; @@ -34,8 +38,23 @@ class RecommendAppsScreenHandler : public BaseScreenHandler, // BaseScreenHandler: void Initialize() override; + // RecommendAppsScreenView: + void OnLoadError() override; + void OnLoadSuccess(const base::Value& app_list) override; + + // Call the JS function to load the list of apps in the WebView. + void LoadAppListInUI(const base::Value& app_list); + + void HandleSkip(); + void HandleRetry(); + void HandleInstall(const base::ListValue* args); + RecommendAppsScreen* screen_ = nullptr; + PrefService* pref_service_; + + base::ObserverList<RecommendAppsScreenViewObserver, true> observer_list_; + DISALLOW_COPY_AND_ASSIGN(RecommendAppsScreenHandler); }; 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 7fb22d7fea1..fe182a0e43d 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 @@ -37,11 +37,11 @@ #include "chrome/browser/browser_process_platform_part_chromeos.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h" -#include "chrome/browser/chromeos/ash_config.h" #include "chrome/browser/chromeos/language_preferences.h" #include "chrome/browser/chromeos/lock_screen_apps/state_controller.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service.h" #include "chrome/browser/chromeos/login/error_screens_histogram_helper.h" +#include "chrome/browser/chromeos/login/help_app_launcher.h" #include "chrome/browser/chromeos/login/hwid_checker.h" #include "chrome/browser/chromeos/login/lock/screen_locker.h" #include "chrome/browser/chromeos/login/lock/webui_screen_locker.h" @@ -70,6 +70,7 @@ #include "chrome/browser/lifetime/browser_shutdown.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_metrics.h" +#include "chrome/browser/ui/ash/ime_controller_client.h" #include "chrome/browser/ui/ash/session_controller_client.h" #include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chrome/browser/ui/ash/wallpaper_controller_client.h" @@ -113,6 +114,7 @@ #include "ui/base/ime/chromeos/input_method_manager.h" #include "ui/base/ime/chromeos/input_method_util.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/base/ui_base_features.h" #include "ui/base/webui/web_ui_util.h" #include "ui/chromeos/devicetype_utils.h" #include "ui/gfx/color_analysis.h" @@ -245,23 +247,7 @@ ash::mojom::UserInfoPtr GetUserInfoForAccount(const AccountId& account_id) { // LoginScreenContext implementation ------------------------------------------ -LoginScreenContext::LoginScreenContext() { - Init(); -} - -LoginScreenContext::LoginScreenContext(const base::ListValue* args) { - Init(); - - if (!args || args->GetSize() == 0) - return; - std::string email; - if (args->GetString(0, &email)) - email_ = email; -} - -void LoginScreenContext::Init() { - oobe_ui_ = false; -} +LoginScreenContext::LoginScreenContext() = default; // SigninScreenHandler implementation ------------------------------------------ @@ -329,7 +315,7 @@ SigninScreenHandler::SigninScreenHandler( WallpaperControllerClient::Get()->AddObserver(std::move(ptr_info)); // TODO(tbarzic): This is needed for login UI - remove it when login switches // to views implementation (or otherwise, make it work under mash). - if (GetAshConfig() != ash::Config::MASH) + if (features::IsAshInBrowserProcess()) detachable_base_observer_.Add(ash::Shell::Get()->detachable_base_handler()); } @@ -344,7 +330,8 @@ SigninScreenHandler::~SigninScreenHandler() { chromeos::input_method::InputMethodManager::Get()->GetImeKeyboard(); if (keyboard) keyboard->RemoveObserver(this); - lock_screen_utils::StopEnforcingPolicyInputMethods(); + if (ImeControllerClient::Get()) // Can be null in tests. + ImeControllerClient::Get()->SetImesManagedByPolicy(false); weak_factory_.InvalidateWeakPtrs(); if (delegate_) delegate_->SetWebUIHandler(nullptr); @@ -515,6 +502,8 @@ void SigninScreenHandler::DeclareLocalizedValues( void SigninScreenHandler::RegisterMessages() { AddCallback("authenticateUser", &SigninScreenHandler::HandleAuthenticateUser); + AddCallback("completeOfflineAuthentication", + &SigninScreenHandler::HandleCompleteOfflineAuthentication); AddCallback("launchIncognito", &SigninScreenHandler::HandleLaunchIncognito); AddCallback("showSupervisedUserCreationScreen", &SigninScreenHandler::HandleShowSupervisedUserCreationScreen); @@ -577,11 +566,12 @@ void SigninScreenHandler::RegisterMessages() { &SigninScreenHandler::HandleNewNoteLaunchAnimationDone); } -void SigninScreenHandler::Show(const LoginScreenContext& context) { +void SigninScreenHandler::Show(const LoginScreenContext& context, + bool oobe_ui) { CHECK(delegate_); // Just initialize internal fields from context and call ShowImpl(). - oobe_ui_ = context.oobe_ui(); + oobe_ui_ = oobe_ui; std::string email; email = context.email(); @@ -1074,12 +1064,6 @@ void SigninScreenHandler::ShowPasswordChangedDialog(bool show_password_error, core_oobe_view_->ShowPasswordChangedScreen(show_password_error, email); } -void SigninScreenHandler::ShowSigninScreenForTest(const std::string& username, - const std::string& password, - const std::string& services) { - gaia_screen_handler_->ShowSigninScreenForTest(username, password, services); -} - void SigninScreenHandler::ShowWhitelistCheckFailedError() { gaia_screen_handler_->ShowWhitelistCheckFailedError(); } @@ -1208,6 +1192,12 @@ void SigninScreenHandler::UpdateAddButtonStatus() { void SigninScreenHandler::HandleAuthenticateUser(const AccountId& account_id, const std::string& password, bool authenticated_by_pin) { + AuthenticateExistingUser(account_id, password, authenticated_by_pin); +} + +void SigninScreenHandler::AuthenticateExistingUser(const AccountId& account_id, + const std::string& password, + bool authenticated_by_pin) { if (!delegate_) return; DCHECK_EQ(account_id.GetUserEmail(), @@ -1218,7 +1208,7 @@ void SigninScreenHandler::HandleAuthenticateUser(const AccountId& account_id, DCHECK(user); UserContext user_context; if (!user) { - LOG(ERROR) << "HandleAuthenticateUser: User not found! account type=" + LOG(ERROR) << "AuthenticateExistingUser: User not found! account type=" << AccountId::AccountTypeToString(account_id.GetAccountType()); const user_manager::UserType user_type = (account_id.GetAccountType() == AccountType::ACTIVE_DIRECTORY) @@ -1245,6 +1235,28 @@ void SigninScreenHandler::HandleAuthenticateUser(const AccountId& account_id, UpdatePinKeyboardState(account_id); } +void SigninScreenHandler::HandleCompleteOfflineAuthentication( + const std::string& email, + const std::string& password) { + const std::string sanitized_email = gaia::SanitizeEmail(email); + const AccountId account_id = user_manager::known_user::GetAccountId( + sanitized_email, std::string() /* id */, AccountType::UNKNOWN); + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(account_id); + if (!user) { + LOG(ERROR) + << "HandleCompleteOfflineAuthentication: User not found! account type=" + << AccountId::AccountTypeToString(account_id.GetAccountType()); + LoginDisplayHost::default_host()->GetLoginDisplay()->ShowError( + IDS_LOGIN_ERROR_OFFLINE_FAILED_NETWORK_NOT_CONNECTED, 1, + HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT); + return; + } + + AuthenticateExistingUser(account_id, password, + false /* authenticated_by_pin */); +} + void SigninScreenHandler::HandleLaunchIncognito() { UserContext context(user_manager::USER_TYPE_GUEST, EmptyAccountId()); if (delegate_) @@ -1457,13 +1469,13 @@ void SigninScreenHandler::HandleCancelUserAdding() { void SigninScreenHandler::HandleMigrateUserData( const std::string& old_password) { - if (delegate_) - delegate_->MigrateUserData(old_password); + if (LoginDisplayHost::default_host()) + LoginDisplayHost::default_host()->MigrateUserData(old_password); } void SigninScreenHandler::HandleResyncUserData() { - if (delegate_) - delegate_->ResyncUserData(); + if (LoginDisplayHost::default_host()) + LoginDisplayHost::default_host()->ResyncUserData(); } void SigninScreenHandler::HandleLoginUIStateChanged(const std::string& source, @@ -1687,10 +1699,11 @@ bool SigninScreenHandler::AllWhitelistedUsersPresent() { } void SigninScreenHandler::CancelPasswordChangedFlowInternal() { - if (delegate_) { + if (delegate_) ShowImpl(); - delegate_->CancelPasswordChangedFlow(); - } + + if (LoginDisplayHost::default_host()) + LoginDisplayHost::default_host()->CancelPasswordChangedFlow(); } bool SigninScreenHandler::IsGaiaVisible() const { @@ -1752,7 +1765,7 @@ void SigninScreenHandler::OnDetachableBaseRequiresUpdateChanged( bool requires_update) {} void SigninScreenHandler::UpdateDetachableBaseChangedError() { - if (GetAshConfig() == ash::Config::MASH) + if (!features::IsAshInBrowserProcess()) return; auto pairing_status = 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 5afec4168ec..847fbad247d 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 @@ -81,19 +81,13 @@ class UserContext; class LoginScreenContext { public: LoginScreenContext(); - explicit LoginScreenContext(const base::ListValue* args); void set_email(const std::string& email) { email_ = email; } const std::string& email() const { return email_; } - void set_oobe_ui(bool oobe_ui) { oobe_ui_ = oobe_ui; } - bool oobe_ui() const { return oobe_ui_; } - private: - void Init(); - + // Optional email to prefill in gaia signin. std::string email_; - bool oobe_ui_; }; // An interface for WebUILoginDisplay to call SigninScreenHandler. @@ -114,12 +108,6 @@ class LoginDisplayWebUIHandler { virtual void ShowSigninUI(const std::string& email) = 0; virtual void ShowPasswordChangedDialog(bool show_password_error, const std::string& email) = 0; - // Show sign-in screen for the given credentials. - // |services| - list of services returned by userInfo call as JSON array. - // Should be empty array for regular user: "[]". - virtual void ShowSigninScreenForTest(const std::string& username, - const std::string& password, - const std::string& services) = 0; virtual void ShowWhitelistCheckFailedError() = 0; virtual void ShowUnrecoverableCrypthomeErrorDialog() = 0; virtual void LoadUsers(const user_manager::UserList& users, @@ -132,18 +120,6 @@ class LoginDisplayWebUIHandler { // An interface for SigninScreenHandler to call WebUILoginDisplay. class SigninScreenHandlerDelegate { public: - // --------------- Password change flow methods. - // Cancels current password changed flow. - virtual void CancelPasswordChangedFlow() = 0; - - // Decrypt cryptohome using user provided |old_password| - // and migrate to new password. - virtual void MigrateUserData(const std::string& old_password) = 0; - - // Ignore password change, remove existing cryptohome and - // force full sync of user data. - virtual void ResyncUserData() = 0; - // --------------- Sign in/out methods. // Sign in using username and password specified as a part of |user_context|. // Used for both known and new users. @@ -250,7 +226,7 @@ class SigninScreenHandler input_method::InputMethodManager::State* ime_state); // Shows the sign in screen. - void Show(const LoginScreenContext& context); + void Show(const LoginScreenContext& context, bool oobe_ui); // Sets delegate to be used by the handler. It is guaranteed that valid // delegate is set before Show() method will be called. @@ -305,6 +281,7 @@ class SigninScreenHandler friend class GaiaScreenHandler; friend class ReportDnsCacheClearedOnUIThread; friend class SupervisedUserCreationScreenHandler; + friend class LoginDisplayHostMojo; void ShowImpl(); @@ -345,9 +322,6 @@ class SigninScreenHandler void ShowPasswordChangedDialog(bool show_password_error, const std::string& email) override; void ShowErrorScreen(LoginDisplay::SigninError error_id) override; - void ShowSigninScreenForTest(const std::string& username, - const std::string& password, - const std::string& services) override; void ShowWhitelistCheckFailedError() override; void ShowUnrecoverableCrypthomeErrorDialog() override; void LoadUsers(const user_manager::UserList& users, @@ -387,6 +361,8 @@ class SigninScreenHandler void HandleAuthenticateUser(const AccountId& account_id, const std::string& password, bool authenticated_by_pin); + void HandleCompleteOfflineAuthentication(const std::string& email, + const std::string& password); void HandleAttemptUnlock(const std::string& username); void HandleLaunchIncognito(); void HandleLaunchPublicSession(const AccountId& account_id, @@ -434,6 +410,11 @@ class SigninScreenHandler void HandleNewNoteLaunchAnimationDone(); void HandleCloseLockScreenApp(); + // Implements user sign-in. + void AuthenticateExistingUser(const AccountId& account_id, + const std::string& password, + bool authenticated_by_pin); + // Sends the list of |keyboard_layouts| available for the |locale| that is // currently selected for the public session identified by |user_id|. void SendPublicSessionKeyboardLayouts( diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.cc index 1441c130baa..dbc5fed3484 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.cc @@ -4,14 +4,55 @@ #include "chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h" +#include "base/strings/utf_string_conversions.h" #include "chrome/browser/chromeos/login/screens/sync_consent_screen.h" #include "chrome/grit/generated_resources.h" #include "components/login/localized_values_builder.h" +#include "ui/base/l10n/l10n_util.h" namespace { const char kJsScreenPath[] = "login.SyncConsentScreen"; +// This helper function gets strings from WebUI and a set of known string +// resource ids, and converts strings back to IDs. It CHECKs if string is not +// found in resources. +void GetConsentIDs(const std::unordered_set<int>& known_ids, + const login::StringList& consent_description, + const std::string& consent_confirmation, + std::vector<int>* consent_description_ids, + int* consent_confirmation_id) { + std::unordered_map<std::string, int> known_strings; + for (const int& id : known_ids) { + // When the strings are passed to the HTML, the Unicode NBSP symbol + // (\u00A0) will be automatically replaced with " ". This change must + // be mirrored in the string-to-ids map. Note that "\u00A0" is actually two + // characters, so we must use base::ReplaceSubstrings* rather than + // base::ReplaceChars. + // TODO(alemate): Find a more elegant solution. + std::string sanitized_string = + base::UTF16ToUTF8(l10n_util::GetStringUTF16(id)); + base::ReplaceSubstringsAfterOffset(&sanitized_string, 0, + "\u00A0" /* NBSP */, " "); + + known_strings[sanitized_string] = id; + } + // The strings returned by the WebUI are not free-form, they must belong into + // a pre-determined set of strings (stored in |string_to_grd_id_map_|). As + // this has privacy and legal implications, CHECK the integrity of the strings + // received from the renderer process before recording the consent. + for (const std::string& text : consent_description) { + auto iter = known_strings.find(text); + CHECK(iter != known_strings.end()) << "Unexpected string:\n" << text; + consent_description_ids->push_back(iter->second); + } + + auto iter = known_strings.find(consent_confirmation); + CHECK(iter != known_strings.end()) << "Unexpected string:\n" + << consent_confirmation; + *consent_confirmation_id = iter->second; +} + } // namespace namespace chromeos { @@ -23,55 +64,78 @@ SyncConsentScreenHandler::SyncConsentScreenHandler() SyncConsentScreenHandler::~SyncConsentScreenHandler() {} +void SyncConsentScreenHandler::RememberLocalizedValue( + const std::string& name, + const int resource_id, + ::login::LocalizedValuesBuilder* builder) { + CHECK(known_string_ids_.count(resource_id) == 0); + known_string_ids_.insert(resource_id); + builder->Add(name, resource_id); +} + void SyncConsentScreenHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) { - builder->Add("syncConsentScreenTitle", IDS_LOGIN_SYNC_CONSENT_SCREEN_TITLE); - builder->Add("syncConsentScreenChromeSyncName", - IDS_LOGIN_SYNC_CONSENT_SCREEN_CHROME_SYNC_NAME); - builder->Add("syncConsentScreenChromeSyncDescription", - IDS_LOGIN_SYNC_CONSENT_SCREEN_CHROME_SYNC_DESCRIPTION); - builder->Add("syncConsentScreenPersonalizeGoogleServicesName", - IDS_LOGIN_SYNC_CONSENT_SCREEN_PERSONALIZE_GOOGLE_SERVICES_NAME); - builder->Add( + known_string_ids_.clear(); + + RememberLocalizedValue("syncConsentScreenTitle", + IDS_LOGIN_SYNC_CONSENT_SCREEN_TITLE, builder); + RememberLocalizedValue("syncConsentScreenChromeSyncName", + IDS_LOGIN_SYNC_CONSENT_SCREEN_CHROME_SYNC_NAME, + builder); + RememberLocalizedValue("syncConsentScreenChromeSyncDescription", + IDS_LOGIN_SYNC_CONSENT_SCREEN_CHROME_SYNC_DESCRIPTION, + builder); + RememberLocalizedValue( + "syncConsentScreenPersonalizeGoogleServicesName", + IDS_LOGIN_SYNC_CONSENT_SCREEN_PERSONALIZE_GOOGLE_SERVICES_NAME, builder); + RememberLocalizedValue( "syncConsentScreenPersonalizeGoogleServicesDescription", - IDS_LOGIN_SYNC_CONSENT_SCREEN_PERSONALIZE_GOOGLE_SERVICES_DESCRIPTION); - builder->Add("syncConsentReviewSyncOptionsText", - IDS_LOGIN_SYNC_CONSENT_SCREEN_REVIEW_SYNC_OPTIONS_LATER); - - builder->Add("syncConsentNewScreenTitle", - IDS_LOGIN_SYNC_CONSENT_GET_GOOGLE_SMARTS); - builder->Add("syncConsentNewBookmarksDesc", - IDS_LOGIN_SYNC_CONSENT_YOUR_BOOKMARKS_ON_ALL_DEVICES); - builder->Add("syncConsentNewServicesDesc", - IDS_LOGIN_SYNC_CONSENT_PERSONALIZED_GOOGLE_SERVICES); - builder->Add("syncConsentNewImproveChrome", - IDS_LOGIN_SYNC_CONSENT_IMPROVE_CHROME); - builder->Add("syncConsentNewGoogleMayUse", - IDS_LOGIN_SYNC_CONSENT_GOOGLE_MAY_USE); - builder->Add("syncConsentNewMoreOptions", - IDS_LOGIN_SYNC_CONSENT_MORE_OPTIONS); - builder->Add("syncConsentNewYesIAmIn", IDS_LOGIN_SYNC_CONSENT_YES_I_AM_IN); - builder->Add("syncConsentNewSyncOptions", - IDS_LOGIN_SYNC_CONSENT_SYNC_OPTIONS); - builder->Add("syncConsentNewSyncOptionsSubtitle", - IDS_LOGIN_SYNC_CONSENT_SYNC_OPTIONS_SUBTITLE); - builder->Add("syncConsentNewChooseOption", - IDS_LOGIN_SYNC_CONSENT_CHOOSE_OPTION); - builder->Add("syncConsentNewOptionReview", - IDS_LOGIN_SYNC_CONSENT_OPTION_REVIEW); - builder->Add("syncConsentNewOptionReviewDsc", - IDS_LOGIN_SYNC_CONSENT_OPTION_REVIEW_DSC); - builder->Add("syncConsentNewOptionJustSync", - IDS_LOGIN_SYNC_CONSENT_OPTION_JUST_SYNC); - builder->Add("syncConsentNewOptionJustSyncDsc", - IDS_LOGIN_SYNC_CONSENT_OPTION_JUST_SYNC_DSC); - builder->Add("syncConsentNewOptionSyncAndPersonalization", - IDS_LOGIN_SYNC_CONSENT_OPTION_SYNC_AND_PERSONALIZATION); - builder->Add("syncConsentNewOptionSyncAndPersonalizationDsc", - IDS_LOGIN_SYNC_CONSENT_OPTION_SYNC_AND_PERSONALIZATION_DSC); - - builder->Add("syncConsentAcceptAndContinue", - IDS_LOGIN_SYNC_CONSENT_SCREEN_ACCEPT_AND_CONTINUE); + IDS_LOGIN_SYNC_CONSENT_SCREEN_PERSONALIZE_GOOGLE_SERVICES_DESCRIPTION, + builder); + RememberLocalizedValue( + "syncConsentReviewSyncOptionsText", + IDS_LOGIN_SYNC_CONSENT_SCREEN_REVIEW_SYNC_OPTIONS_LATER, builder); + + RememberLocalizedValue("syncConsentNewScreenTitle", + IDS_LOGIN_SYNC_CONSENT_GET_GOOGLE_SMARTS, builder); + RememberLocalizedValue("syncConsentNewBookmarksDesc", + IDS_LOGIN_SYNC_CONSENT_YOUR_BOOKMARKS_ON_ALL_DEVICES, + builder); + RememberLocalizedValue("syncConsentNewServicesDesc", + IDS_LOGIN_SYNC_CONSENT_PERSONALIZED_GOOGLE_SERVICES, + builder); + RememberLocalizedValue("syncConsentNewImproveChrome", + IDS_LOGIN_SYNC_CONSENT_IMPROVE_CHROME, builder); + RememberLocalizedValue("syncConsentNewGoogleMayUse", + IDS_LOGIN_SYNC_CONSENT_GOOGLE_MAY_USE, builder); + RememberLocalizedValue("syncConsentNewMoreOptions", + IDS_LOGIN_SYNC_CONSENT_MORE_OPTIONS, builder); + RememberLocalizedValue("syncConsentNewYesIAmIn", + IDS_LOGIN_SYNC_CONSENT_YES_I_AM_IN, builder); + RememberLocalizedValue("syncConsentNewSyncOptions", + IDS_LOGIN_SYNC_CONSENT_SYNC_OPTIONS, builder); + RememberLocalizedValue("syncConsentNewSyncOptionsSubtitle", + IDS_LOGIN_SYNC_CONSENT_SYNC_OPTIONS_SUBTITLE, builder); + RememberLocalizedValue("syncConsentNewChooseOption", + IDS_LOGIN_SYNC_CONSENT_CHOOSE_OPTION, builder); + RememberLocalizedValue("syncConsentNewOptionReview", + IDS_LOGIN_SYNC_CONSENT_OPTION_REVIEW, builder); + RememberLocalizedValue("syncConsentNewOptionReviewDsc", + IDS_LOGIN_SYNC_CONSENT_OPTION_REVIEW_DSC, builder); + RememberLocalizedValue("syncConsentNewOptionJustSync", + IDS_LOGIN_SYNC_CONSENT_OPTION_JUST_SYNC, builder); + RememberLocalizedValue("syncConsentNewOptionJustSyncDsc", + IDS_LOGIN_SYNC_CONSENT_OPTION_JUST_SYNC_DSC, builder); + RememberLocalizedValue("syncConsentNewOptionSyncAndPersonalization", + IDS_LOGIN_SYNC_CONSENT_OPTION_SYNC_AND_PERSONALIZATION, + builder); + RememberLocalizedValue( + "syncConsentNewOptionSyncAndPersonalizationDsc", + IDS_LOGIN_SYNC_CONSENT_OPTION_SYNC_AND_PERSONALIZATION_DSC, builder); + + RememberLocalizedValue("syncConsentAcceptAndContinue", + IDS_LOGIN_SYNC_CONSENT_SCREEN_ACCEPT_AND_CONTINUE, + builder); } void SyncConsentScreenHandler::Bind(SyncConsentScreen* screen) { @@ -91,6 +155,13 @@ void SyncConsentScreenHandler::SetThrobberVisible(bool visible) { void SyncConsentScreenHandler::Initialize() {} +void SyncConsentScreenHandler::RegisterMessages() { + AddPrefixedCallback("continueAndReview", + &SyncConsentScreenHandler::HandleContinueAndReview); + AddPrefixedCallback("continueWithDefaults", + &SyncConsentScreenHandler::HandleContinueWithDefaults); +} + void SyncConsentScreenHandler::GetAdditionalParameters( base::DictionaryValue* parameters) { parameters->Set("syncConsentMakeBetter", @@ -98,4 +169,40 @@ void SyncConsentScreenHandler::GetAdditionalParameters( BaseScreenHandler::GetAdditionalParameters(parameters); } +void SyncConsentScreenHandler::HandleContinueAndReview( + const login::StringList& consent_description, + const std::string& consent_confirmation) { + std::vector<int> consent_description_ids; + int consent_confirmation_id; + GetConsentIDs(known_string_ids_, consent_description, consent_confirmation, + &consent_description_ids, &consent_confirmation_id); + screen_->OnContinueAndReview(consent_description_ids, + consent_confirmation_id); + + SyncConsentScreen::SyncConsentScreenTestDelegate* test_delegate = + screen_->GetDelegateForTesting(); + if (test_delegate) { + test_delegate->OnConsentRecordedStrings(consent_description, + consent_confirmation); + } +} + +void SyncConsentScreenHandler::HandleContinueWithDefaults( + const login::StringList& consent_description, + const std::string& consent_confirmation) { + std::vector<int> consent_description_ids; + int consent_confirmation_id; + GetConsentIDs(known_string_ids_, consent_description, consent_confirmation, + &consent_description_ids, &consent_confirmation_id); + screen_->OnContinueWithDefaults(consent_description_ids, + consent_confirmation_id); + + SyncConsentScreen::SyncConsentScreenTestDelegate* test_delegate = + screen_->GetDelegateForTesting(); + if (test_delegate) { + test_delegate->OnConsentRecordedStrings(consent_description, + consent_confirmation); + } +} + } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h index 38cfde328c7..a961210c085 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h @@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_SYNC_CONSENT_SCREEN_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_SYNC_CONSENT_SCREEN_HANDLER_H_ +#include <unordered_set> + #include "base/macros.h" #include "chrome/browser/chromeos/login/screens/sync_consent_screen_view.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" @@ -33,8 +35,24 @@ class SyncConsentScreenHandler : public BaseScreenHandler, private: // BaseScreenHandler: void Initialize() override; + void RegisterMessages() override; void GetAdditionalParameters(base::DictionaryValue* parameters) override; + // WebUI message handlers + void HandleContinueAndReview(const ::login::StringList& consent_description, + const std::string& consent_confirmation); + void HandleContinueWithDefaults( + const ::login::StringList& consent_description, + const std::string& consent_confirmation); + + // Adds resource |resource_id| both to |builder| and to |known_string_ids_|. + void RememberLocalizedValue(const std::string& name, + const int resource_id, + ::login::LocalizedValuesBuilder* builder); + + // Resource IDs of the displayed strings. + std::unordered_set<int> known_string_ids_; + SyncConsentScreen* screen_ = nullptr; DISALLOW_COPY_AND_ASSIGN(SyncConsentScreenHandler); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc index a1afa85efa7..c727fca87fe 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc @@ -21,6 +21,7 @@ #include "chrome/common/pref_names.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" +#include "components/language/core/browser/pref_names.h" #include "components/language/core/common/locale_util.h" #include "components/login/localized_values_builder.h" #include "components/prefs/pref_service.h" @@ -87,7 +88,7 @@ void TermsOfServiceScreenHandler::Show() { ->GetProfileByUserUnsafe( user_manager::UserManager::Get()->GetActiveUser()) ->GetPrefs() - ->GetString(prefs::kApplicationLocale); + ->GetString(language::prefs::kApplicationLocale); language::ConvertToActualUILocale(&locale); if (locale.empty() || locale == g_browser_process->GetApplicationLocale()) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.cc index 8225c73c1ea..1b3047e9864 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/webui/chromeos/login/network_screen_handler.h" +#include "chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.h" #include <stddef.h> @@ -20,7 +20,7 @@ #include "chrome/browser/chromeos/customization/customization_document.h" #include "chrome/browser/chromeos/idle_detector.h" #include "chrome/browser/chromeos/login/screens/core_oobe_view.h" -#include "chrome/browser/chromeos/login/screens/network_screen.h" +#include "chrome/browser/chromeos/login/screens/welcome_screen.h" #include "chrome/browser/chromeos/login/ui/input_events_blocker.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h" @@ -46,28 +46,28 @@ namespace { -const char kJsScreenPath[] = "login.NetworkScreen"; +const char kJsScreenPath[] = "login.WelcomeScreen"; } // namespace namespace chromeos { -// NetworkScreenHandler, public: ----------------------------------------------- +// WelcomeScreenHandler, public: ----------------------------------------------- -NetworkScreenHandler::NetworkScreenHandler(CoreOobeView* core_oobe_view) +WelcomeScreenHandler::WelcomeScreenHandler(CoreOobeView* core_oobe_view) : BaseScreenHandler(kScreenId), core_oobe_view_(core_oobe_view) { set_call_js_prefix(kJsScreenPath); DCHECK(core_oobe_view_); } -NetworkScreenHandler::~NetworkScreenHandler() { +WelcomeScreenHandler::~WelcomeScreenHandler() { if (screen_) screen_->OnViewDestroyed(this); } -// NetworkScreenHandler, NetworkScreenView implementation: --------------------- +// WelcomeScreenHandler, WelcomeScreenView implementation: --------------------- -void NetworkScreenHandler::Show() { +void WelcomeScreenHandler::Show() { if (!page_is_ready()) { show_on_init_ = true; return; @@ -92,54 +92,52 @@ void NetworkScreenHandler::Show() { handler->SetTechnologyEnabled(NetworkTypePattern::Physical(), true, chromeos::network_handler::ErrorCallback()); - base::DictionaryValue network_screen_params; - network_screen_params.SetBoolean("isDeveloperMode", - base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kSystemDevMode)); - ShowScreenWithData(kScreenId, &network_screen_params); + base::DictionaryValue welcome_screen_params; + welcome_screen_params.SetBoolean( + "isDeveloperMode", base::CommandLine::ForCurrentProcess()->HasSwitch( + chromeos::switches::kSystemDevMode)); + ShowScreenWithData(kScreenId, &welcome_screen_params); core_oobe_view_->InitDemoModeDetection(); } -void NetworkScreenHandler::Hide() { -} +void WelcomeScreenHandler::Hide() {} -void NetworkScreenHandler::Bind(NetworkScreen* screen) { +void WelcomeScreenHandler::Bind(WelcomeScreen* screen) { screen_ = screen; BaseScreenHandler::SetBaseScreen(screen_); } -void NetworkScreenHandler::Unbind() { +void WelcomeScreenHandler::Unbind() { screen_ = nullptr; BaseScreenHandler::SetBaseScreen(nullptr); } -void NetworkScreenHandler::ShowError(const base::string16& message) { +void WelcomeScreenHandler::ShowError(const base::string16& message) { CallJS("showError", message); } -void NetworkScreenHandler::ClearErrors() { +void WelcomeScreenHandler::ClearErrors() { if (page_is_ready()) core_oobe_view_->ClearErrors(); } -void NetworkScreenHandler::StopDemoModeDetection() { +void WelcomeScreenHandler::StopDemoModeDetection() { core_oobe_view_->StopDemoModeDetection(); } -void NetworkScreenHandler::ShowConnectingStatus( +void WelcomeScreenHandler::ShowConnectingStatus( bool connecting, - const base::string16& network_id) { -} + const base::string16& network_id) {} -void NetworkScreenHandler::ReloadLocalizedContent() { +void WelcomeScreenHandler::ReloadLocalizedContent() { base::DictionaryValue localized_strings; GetOobeUI()->GetLocalizedStrings(&localized_strings); core_oobe_view_->ReloadContent(localized_strings); } -// NetworkScreenHandler, BaseScreenHandler implementation: -------------------- +// WelcomeScreenHandler, BaseScreenHandler implementation: -------------------- -void NetworkScreenHandler::DeclareLocalizedValues( +void WelcomeScreenHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) { if (system::InputDeviceSettings::Get()->ForceKeyboardDrivenUINavigation()) builder->Add("networkScreenGreeting", IDS_REMORA_CONFIRM_MESSAGE); @@ -147,16 +145,11 @@ void NetworkScreenHandler::DeclareLocalizedValues( builder->Add("networkScreenGreeting", IDS_WELCOME_SCREEN_GREETING); builder->Add("networkScreenTitle", IDS_WELCOME_SCREEN_TITLE); - builder->Add("selectLanguage", IDS_LANGUAGE_SELECTION_SELECT); - builder->Add("selectKeyboard", IDS_KEYBOARD_SELECTION_SELECT); - builder->Add("selectNetwork", IDS_NETWORK_SELECTION_SELECT); - builder->Add("selectTimezone", IDS_OPTIONS_SETTINGS_TIMEZONE_DESCRIPTION); - builder->Add("timezoneDropdownLabel", IDS_TIMEZONE_DROPDOWN_LABEL); - builder->Add("proxySettings", IDS_OPTIONS_PROXIES_CONFIGURE_BUTTON); builder->Add("continueButton", IDS_NETWORK_SELECTION_CONTINUE_BUTTON); - builder->Add("debuggingFeaturesLink", IDS_NETWORK_ENABLE_DEV_FEATURES_LINK); - // MD-OOBE + // MD-OOBE (oobe-welcome-md) + builder->Add("debuggingFeaturesLink", IDS_NETWORK_ENABLE_DEV_FEATURES_LINK); + builder->Add("timezoneDropdownLabel", IDS_TIMEZONE_DROPDOWN_LABEL); builder->Add("oobeOKButtonText", IDS_OOBE_OK_BUTTON_TEXT); builder->Add("welcomeNextButtonText", IDS_OOBE_WELCOME_NEXT_BUTTON_TEXT); builder->Add("languageButtonLabel", IDS_LANGUAGE_BUTTON_LABEL); @@ -204,7 +197,7 @@ void NetworkScreenHandler::DeclareLocalizedValues( network_element::AddLocalizedValuesToBuilder(builder); } -void NetworkScreenHandler::GetAdditionalParameters( +void WelcomeScreenHandler::GetAdditionalParameters( base::DictionaryValue* dict) { const std::string application_locale = g_browser_process->GetApplicationLocale(); @@ -264,7 +257,7 @@ void NetworkScreenHandler::GetAdditionalParameters( dict->Set("timezoneList", GetTimezoneList()); } -void NetworkScreenHandler::Initialize() { +void WelcomeScreenHandler::Initialize() { if (show_on_init_) { show_on_init_ = false; Show(); @@ -275,10 +268,10 @@ void NetworkScreenHandler::Initialize() { ReloadLocalizedContent(); } -// NetworkScreenHandler, private: ---------------------------------------------- +// WelcomeScreenHandler, private: ---------------------------------------------- // static -std::unique_ptr<base::ListValue> NetworkScreenHandler::GetTimezoneList() { +std::unique_ptr<base::ListValue> WelcomeScreenHandler::GetTimezoneList() { std::string current_timezone_id; CrosSettings::Get()->GetString(kSystemTimezone, ¤t_timezone_id); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.h index cbf4f71202d..73157f50225 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.h @@ -1,9 +1,9 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_NETWORK_SCREEN_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_NETWORK_SCREEN_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_WELCOME_SCREEN_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_WELCOME_SCREEN_HANDLER_H_ #include <memory> #include <string> @@ -11,7 +11,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "chrome/browser/chromeos/base/locale_util.h" -#include "chrome/browser/chromeos/login/screens/network_view.h" +#include "chrome/browser/chromeos/login/screens/welcome_view.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "ui/base/ime/chromeos/component_extension_ime_manager.h" #include "ui/base/ime/chromeos/input_method_manager.h" @@ -25,18 +25,18 @@ namespace chromeos { class CoreOobeView; -// WebUI implementation of NetworkScreenView. It is used to interact with +// WebUI implementation of WelcomeScreenView. It is used to interact with // the welcome screen (part of the page) of the OOBE. -class NetworkScreenHandler : public NetworkView, public BaseScreenHandler { +class WelcomeScreenHandler : public WelcomeView, public BaseScreenHandler { public: - explicit NetworkScreenHandler(CoreOobeView* core_oobe_view); - ~NetworkScreenHandler() override; + explicit WelcomeScreenHandler(CoreOobeView* core_oobe_view); + ~WelcomeScreenHandler() override; private: - // NetworkView implementation: + // WelcomeView implementation: void Show() override; void Hide() override; - void Bind(NetworkScreen* screen) override; + void Bind(WelcomeScreen* screen) override; void Unbind() override; void ShowError(const base::string16& message) override; void ClearErrors() override; @@ -55,7 +55,7 @@ class NetworkScreenHandler : public NetworkView, public BaseScreenHandler { static std::unique_ptr<base::ListValue> GetTimezoneList(); CoreOobeView* core_oobe_view_ = nullptr; - NetworkScreen* screen_ = nullptr; + WelcomeScreen* screen_ = nullptr; // Keeps whether screen should be shown right after initialization. bool show_on_init_ = false; @@ -63,9 +63,9 @@ class NetworkScreenHandler : public NetworkView, public BaseScreenHandler { // Position of the network control. gfx::Point network_control_pos_; - DISALLOW_COPY_AND_ASSIGN(NetworkScreenHandler); + DISALLOW_COPY_AND_ASSIGN(WelcomeScreenHandler); }; } // namespace chromeos -#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_NETWORK_SCREEN_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_WELCOME_SCREEN_HANDLER_H_ 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 3d489b5408d..5ed83ce27d5 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 @@ -24,9 +24,8 @@ constexpr int kDialogHeightPx = 640; constexpr int kDialogWidthPx = 768; void AddMultiDeviceSetupStrings(content::WebUIDataSource* html_source) { - // TODO(jordynass): Add translations for other strings appearing in the - // dialog by adding new name/translation pairs to |kLocalizedStrings| below. - // String definitions belong in //chrome/app/chromeos_strings.grdp. + // TODO(jordynass): Translate the newly added strings from + // //chrome/app/chromeos_strings.grdp. static constexpr struct { const char* name; int id; @@ -46,7 +45,10 @@ void AddMultiDeviceSetupStrings(content::WebUIDataSource* html_source) { {"setupSucceededPageMessage", IDS_MULTIDEVICE_SETUP_SETUP_SUCCEEDED_PAGE_MESSAGE}, {"startSetupPageHeader", IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_HEADER}, - {"startSetupPageMessage", IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_MESSAGE}, + {"startSetupPageMessagePart1", + IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_MESSAGE_PART_1}, + {"startSetupPageMessagePart2", + IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_MESSAGE_PART_2}, {"title", IDS_MULTIDEVICE_SETUP_DIALOG_TITLE}, {"tryAgain", IDS_MULTIDEVICE_SETUP_TRY_AGAIN_LABEL}, }; 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 1951ce7a687..17412d46064 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 @@ -63,6 +63,7 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { IDS_ONC_CELLULAR_APN_ACCESS_POINT_NAME}, {"OncCellular-APN-AccessPointName_none", IDS_ONC_CELLULAR_APN_ACCESS_POINT_NAME_NONE}, + {"OncCellular-APN-Authentication", IDS_ONC_CELLULAR_APN_AUTHENTICATION}, {"OncCellular-APN-Password", IDS_ONC_CELLULAR_APN_PASSWORD}, {"OncCellular-APN-Username", IDS_ONC_CELLULAR_APN_USERNAME}, {"OncCellular-ActivationState", IDS_ONC_CELLULAR_ACTIVATION_STATE}, @@ -302,9 +303,8 @@ void AddErrorLocalizedStrings(content::WebUIDataSource* html_source) { {NetworkConnectionHandler::kErrorPassphraseRequired, IDS_NETWORK_ERROR_PASSPHRASE_REQUIRED}, {"networkErrorUnknown", IDS_NETWORK_ERROR_UNKNOWN}, - // TODO(stevenjb): Move this id to settings_strings.grdp: {"networkErrorNotHardwareBacked", - IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_REQUIRE_HARDWARE_BACKED}, + IDS_SETTINGS_INTERNET_NETWORK_REQUIRE_HARDWARE_BACKED}, }; for (const auto& entry : localized_strings) html_source->AddLocalizedString(entry.name, entry.id); diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc index 26d8445e314..5fa8641e58a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc @@ -12,8 +12,8 @@ #include "base/memory/weak_ptr.h" #include "base/strings/stringprintf.h" #include "base/values.h" -#include "chrome/browser/chromeos/options/network_config_view.h" #include "chrome/browser/extensions/tab_helper.h" +#include "chrome/browser/ui/webui/chromeos/internet_config_dialog.h" #include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" @@ -205,10 +205,7 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler { void AddNetwork(const base::ListValue* args) { std::string onc_type; args->GetString(0, &onc_type); - std::string shill_type = (onc_type == ::onc::network_type::kVPN) - ? shill::kTypeVPN - : shill::kTypeWifi; - NetworkConfigView::ShowForType(shill_type); + InternetConfigDialog::ShowDialogForNetworkType(onc_type); } base::WeakPtrFactory<NetworkConfigMessageHandler> weak_ptr_factory_; 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 6868a46961e..aa7400cb37d 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 @@ -4,7 +4,6 @@ #include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" #include "ash/public/cpp/shell_window_ids.h" -#include "chrome/browser/chromeos/options/network_config_view.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_dialogs.h" #include "components/session_manager/core/session_manager.h" @@ -66,13 +65,6 @@ bool SystemWebDialogDelegate::ShouldShowDialogTitle() const { } void SystemWebDialogDelegate::ShowSystemDialog(bool is_minimal_style) { - // NetworkConfigView does not interact well with web dialogs. For now, do - // not show the dialog while NetworkConfigView is shown: crbug.com/791955. - // TODO(stevenjb): Remove this when NetworkConfigView is deprecated. - if (NetworkConfigView::HasInstance()) { - delete this; - return; - } content::BrowserContext* browser_context = ProfileManager::GetActiveUserProfile(); int container_id = GetDialogModalType() == ui::MODAL_TYPE_NONE diff --git a/chromium/chrome/browser/ui/webui/components_ui.cc b/chromium/chrome/browser/ui/webui/components_ui.cc index 8a5db7e83b4..a3a4fe9b9b3 100644 --- a/chromium/chrome/browser/ui/webui/components_ui.cc +++ b/chromium/chrome/browser/ui/webui/components_ui.cc @@ -41,6 +41,8 @@ content::WebUIDataSource* CreateComponentsUIHTMLSource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIComponentsHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->AddLocalizedString("componentsTitle", IDS_COMPONENTS_TITLE); source->AddLocalizedString("componentsNoneInstalled", IDS_COMPONENTS_NONE_INSTALLED); @@ -164,8 +166,9 @@ ComponentsUI::~ComponentsUI() { void ComponentsUI::OnDemandUpdate(const std::string& component_id) { component_updater::ComponentUpdateService* cus = g_browser_process->component_updater(); - cus->GetOnDemandUpdater().OnDemandUpdate(component_id, - component_updater::Callback()); + cus->GetOnDemandUpdater().OnDemandUpdate( + component_id, component_updater::OnDemandUpdater::Priority::FOREGROUND, + component_updater::Callback()); } // static diff --git a/chromium/chrome/browser/ui/webui/conflicts/OWNERS b/chromium/chrome/browser/ui/webui/conflicts/OWNERS new file mode 100644 index 00000000000..4495bb1abea --- /dev/null +++ b/chromium/chrome/browser/ui/webui/conflicts/OWNERS @@ -0,0 +1 @@ +file://chrome/browser/conflicts/OWNERS diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc new file mode 100644 index 00000000000..ab34217d8cc --- /dev/null +++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc @@ -0,0 +1,328 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/conflicts/conflicts_handler.h" + +#include <utility> + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/feature_list.h" +#include "base/strings/string16.h" +#include "base/strings/string_number_conversions.h" +#include "base/values.h" +#include "base/win/windows_version.h" +#include "chrome/browser/conflicts/module_database_win.h" +#include "chrome/browser/conflicts/module_info_win.h" +#include "chrome/common/chrome_features.h" +#include "chrome/grit/generated_resources.h" +#include "content/public/browser/web_ui.h" +#include "ui/base/l10n/l10n_util.h" + +#if defined(GOOGLE_CHROME_BUILD) +#include "chrome/browser/conflicts/incompatible_applications_updater_win.h" +#include "chrome/browser/conflicts/module_blacklist_cache_updater_win.h" +#endif + +namespace { + +#if defined(GOOGLE_CHROME_BUILD) +std::string GetModuleStatusString( + const ModuleInfoKey& module_key, + IncompatibleApplicationsUpdater* incompatible_applications_updater, + ModuleBlacklistCacheUpdater* module_blacklist_cache_updater) { + DCHECK(incompatible_applications_updater || module_blacklist_cache_updater); + + // Strings used twice. + constexpr char kNotLoaded[] = "Not loaded"; + constexpr char kAllowedInputMethodEditor[] = "Allowed - Input method editor"; + constexpr char kAllowedMatchingCertificate[] = + "Allowed - Matching certificate"; + constexpr char kAllowedSameDirectory[] = "Allowed - In executable directory"; + constexpr char kAllowedMicrosoftModule[] = "Allowed - Microsoft module"; + constexpr char kAllowedWhitelisted[] = "Allowed - Whitelisted"; + + // The blocking status is shown over the warning status. + if (module_blacklist_cache_updater) { + using BlockingDecision = + ModuleBlacklistCacheUpdater::ModuleBlockingDecision; + + BlockingDecision blocking_decision = + module_blacklist_cache_updater->GetModuleBlockingDecision(module_key); + + switch (blocking_decision) { + case BlockingDecision::kNotLoaded: + return kNotLoaded; + case BlockingDecision::kAllowedIME: + return kAllowedInputMethodEditor; + case BlockingDecision::kAllowedSameCertificate: + return kAllowedMatchingCertificate; + case BlockingDecision::kAllowedSameDirectory: + return kAllowedSameDirectory; + case BlockingDecision::kAllowedMicrosoft: + return kAllowedMicrosoftModule; + case BlockingDecision::kAllowedWhitelisted: + return kAllowedWhitelisted; + case BlockingDecision::kTolerated: + // This is a module explicitely allowed to load by the Module List + // component. But it is still valid for a potential warning, and so the + // warning status is used instead. + if (incompatible_applications_updater) + break; + return "Tolerated - Will be blocked in the future"; + case BlockingDecision::kBlacklisted: + return "Disallowed - Added to the blacklist"; + case BlockingDecision::kBlocked: + return "Disallowed - Blocked"; + case BlockingDecision::kUnknown: + NOTREACHED(); + break; + } + } + + if (incompatible_applications_updater) { + using WarningDecision = + IncompatibleApplicationsUpdater::ModuleWarningDecision; + + WarningDecision warning_decision = + incompatible_applications_updater->GetModuleWarningDecision(module_key); + + switch (warning_decision) { + case WarningDecision::kNotLoaded: + return kNotLoaded; + case WarningDecision::kAllowedIME: + return kAllowedInputMethodEditor; + case WarningDecision::kAllowedShellExtension: + return "Tolerated - Shell extension"; + case WarningDecision::kAllowedSameCertificate: + return kAllowedMatchingCertificate; + case WarningDecision::kAllowedSameDirectory: + return kAllowedSameDirectory; + case WarningDecision::kAllowedMicrosoft: + return kAllowedMicrosoftModule; + case WarningDecision::kAllowedWhitelisted: + return kAllowedWhitelisted; + case WarningDecision::kNoTiedApplication: + return "Tolerated - Could not tie to an installed application"; + case WarningDecision::kIncompatible: + return "Incompatible"; + case WarningDecision::kAddedToBlacklist: + case WarningDecision::kUnknown: + NOTREACHED(); + break; + } + } + + return std::string(); +} +#endif // defined(GOOGLE_CHROME_BUILD) + +} // namespace + +ConflictsHandler::ConflictsHandler() : weak_ptr_factory_(this) {} + +ConflictsHandler::~ConflictsHandler() { + if (module_list_) + ModuleDatabase::GetInstance()->RemoveObserver(this); +} + +void ConflictsHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "requestModuleList", + base::BindRepeating(&ConflictsHandler::HandleRequestModuleList, + base::Unretained(this))); +} + +void ConflictsHandler::OnNewModuleFound(const ModuleInfoKey& module_key, + const ModuleInfoData& module_data) { + DCHECK(module_list_); + + auto data = std::make_unique<base::DictionaryValue>(); + + data->SetString("third_party_module_status", std::string()); +#if defined(GOOGLE_CHROME_BUILD) + if (ModuleDatabase::GetInstance()->third_party_conflicts_manager()) { + auto* incompatible_applications_updater = + ModuleDatabase::GetInstance() + ->third_party_conflicts_manager() + ->incompatible_applications_updater(); + auto* module_blacklist_cache_updater = + ModuleDatabase::GetInstance() + ->third_party_conflicts_manager() + ->module_blacklist_cache_updater(); + + data->SetString( + "third_party_module_status", + GetModuleStatusString(module_key, incompatible_applications_updater, + module_blacklist_cache_updater)); + } +#endif // defined(GOOGLE_CHROME_BUILD) + + std::string type_string; + if (module_data.module_properties & ModuleInfoData::kPropertyShellExtension) + type_string = "Shell extension"; + if (module_data.module_properties & ModuleInfoData::kPropertyBlocked) { + if (!type_string.empty()) + type_string += ", "; + type_string += "blocked"; + } + data->SetString("type_description", type_string); + + const auto& inspection_result = *module_data.inspection_result; + data->SetString("location", inspection_result.location); + data->SetString("name", inspection_result.basename); + data->SetString("product_name", inspection_result.product_name); + data->SetString("description", inspection_result.description); + data->SetString("version", inspection_result.version); + data->SetString("digital_signer", inspection_result.certificate_info.subject); + data->SetString("code_id", GenerateCodeId(module_key)); + + module_list_->Append(std::move(data)); +} + +void ConflictsHandler::OnModuleDatabaseIdle() { + DCHECK(module_list_); + DCHECK(!module_list_callback_id_.empty()); + + ModuleDatabase::GetInstance()->RemoveObserver(this); + + base::DictionaryValue results; + results.SetInteger("moduleCount", module_list_->GetSize()); + results.Set("moduleList", std::move(module_list_)); + + // Third-party conflicts status. + ThirdPartyFeaturesStatus third_party_features_status = + third_party_features_status_.value(); + results.SetBoolean("thirdPartyFeatureEnabled", + IsThirdPartyFeatureEnabled(third_party_features_status)); + results.SetString( + "thirdPartyFeatureStatus", + GetThirdPartyFeaturesStatusString(third_party_features_status)); + + AllowJavascript(); + ResolveJavascriptCallback(base::Value(module_list_callback_id_), results); +} + +void ConflictsHandler::HandleRequestModuleList(const base::ListValue* args) { + // Make sure the JS doesn't call 'requestModuleList' more than once. + // TODO(739291): It would be better to kill the renderer instead of the + // browser for malformed messages. + CHECK(!module_list_); + + CHECK_EQ(1U, args->GetSize()); + CHECK(args->GetString(0, &module_list_callback_id_)); + +#if defined(GOOGLE_CHROME_BUILD) + // If the ThirdPartyConflictsManager instance exists, wait until it is fully + // initialized before retrieving the list of modules. + auto* third_party_conflicts_manager = + ModuleDatabase::GetInstance()->third_party_conflicts_manager(); + if (third_party_conflicts_manager) { + third_party_conflicts_manager->ForceInitialization( + base::BindRepeating(&ConflictsHandler::OnManagerInitializationComplete, + weak_ptr_factory_.GetWeakPtr())); + return; + } + + // Figure out why the manager instance doesn't exist. + if (!ModuleDatabase::IsThirdPartyBlockingPolicyEnabled()) + third_party_features_status_ = kPolicyDisabled; + + if (!base::FeatureList::IsEnabled(features::kThirdPartyModulesBlocking) && + !IncompatibleApplicationsUpdater::IsWarningEnabled()) { + third_party_features_status_ = kFeatureDisabled; + } + + // The above 2 cases are the only possible reasons why the manager wouldn't + // exist. + DCHECK(third_party_features_status_.has_value()); +#else // defined(GOOGLE_CHROME_BUILD) + third_party_features_status_ = kNonGoogleChromeBuild; +#endif + + GetListOfModules(); +} + +#if defined(GOOGLE_CHROME_BUILD) +void ConflictsHandler::OnManagerInitializationComplete( + ThirdPartyConflictsManager::State state) { + switch (state) { + case ThirdPartyConflictsManager::State::kModuleListInvalidFailure: + third_party_features_status_ = kModuleListInvalid; + break; + case ThirdPartyConflictsManager::State::kNoModuleListAvailableFailure: + third_party_features_status_ = kNoModuleListAvailable; + break; + case ThirdPartyConflictsManager::State::kWarningInitialized: + third_party_features_status_ = kWarningInitialized; + break; + case ThirdPartyConflictsManager::State::kBlockingInitialized: + third_party_features_status_ = kBlockingInitialized; + break; + case ThirdPartyConflictsManager::State::kWarningAndBlockingInitialized: + third_party_features_status_ = kWarningAndBlockingInitialized; + break; + case ThirdPartyConflictsManager::State::kDestroyed: + // Turning off the feature via group policy is the only way to have the + // manager destroyed. + third_party_features_status_ = kPolicyDisabled; + break; + } + + GetListOfModules(); +} +#endif // defined(GOOGLE_CHROME_BUILD) + +void ConflictsHandler::GetListOfModules() { + // The request is handled asynchronously, filling up the |module_list_|, + // and will callback via OnModuleDatabaseIdle() on completion. + module_list_ = std::make_unique<base::ListValue>(); + + auto* module_database = ModuleDatabase::GetInstance(); + module_database->IncreaseInspectionPriority(); + module_database->AddObserver(this); +} + +// static +bool ConflictsHandler::IsThirdPartyFeatureEnabled( + ThirdPartyFeaturesStatus status) { + return status == kWarningInitialized || status == kBlockingInitialized || + status == kWarningAndBlockingInitialized; +} + +// static +std::string ConflictsHandler::GetThirdPartyFeaturesStatusString( + ThirdPartyFeaturesStatus status) { + switch (status) { + case ThirdPartyFeaturesStatus::kNonGoogleChromeBuild: + return "The third-party features are not available in non-Google Chrome " + "builds."; + case ThirdPartyFeaturesStatus::kPolicyDisabled: + return "The ThirdPartyBlockingEnabled group policy is disabled."; + case ThirdPartyFeaturesStatus::kFeatureDisabled: + if (base::win::GetVersion() < base::win::VERSION_WIN10) + return "The ThirdPartyModulesBlocking feature is disabled."; + + return "Both the IncompatibleApplicationsWarning and " + "ThirdPartyModulesBlocking features are disabled."; + case ThirdPartyFeaturesStatus::kModuleListInvalid: + return "Disabled - The Module List component version is invalid."; + case ThirdPartyFeaturesStatus::kNoModuleListAvailable: + return "Disabled - There is no Module List version available."; + case ThirdPartyFeaturesStatus::kWarningInitialized: + DCHECK_GE(base::win::GetVersion(), base::win::VERSION_WIN10); + return "The IncompatibleApplicationsWarning feature is enabled, while " + "the ThirdPartyModulesBlocking feature is disabled."; + case ThirdPartyFeaturesStatus::kBlockingInitialized: + if (base::win::GetVersion() < base::win::VERSION_WIN10) + return "The ThirdPartyModulesBlocking feature is enabled."; + + return "The ThirdPartyModulesBlocking feature is enabled, while the " + "IncompatibleApplicationsWarning feature is disabled."; + case ThirdPartyFeaturesStatus::kWarningAndBlockingInitialized: + DCHECK_GE(base::win::GetVersion(), base::win::VERSION_WIN10); + return "Both the IncompatibleApplicationsWarning and " + "ThirdPartyModulesBlocking features are enabled"; + } +} diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h new file mode 100644 index 00000000000..51f0630e035 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h @@ -0,0 +1,96 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CONFLICTS_CONFLICTS_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CONFLICTS_CONFLICTS_HANDLER_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/conflicts/module_database_observer_win.h" +#include "content/public/browser/web_ui_message_handler.h" + +#if defined(GOOGLE_CHROME_BUILD) +#include "chrome/browser/conflicts/third_party_conflicts_manager_win.h" +#endif + +namespace base { +class Listvalue; +} + +// This class takes care of sending the list of all loaded modules to the +// chrome://conflicts WebUI page when it is requested. +class ConflictsHandler : public content::WebUIMessageHandler, + public ModuleDatabaseObserver { + public: + ConflictsHandler(); + ~ConflictsHandler() override; + + private: + enum ThirdPartyFeaturesStatus { + // The third-party features are not available in non-Google Chrome builds. + kNonGoogleChromeBuild, + // The ThirdPartyBlockingEnabled group policy is disabled. + kPolicyDisabled, + // Both the IncompatibleApplicationsWarning and the + // ThirdPartyModulesBlocking features are disabled. + kFeatureDisabled, + // The Module List version received is invalid. + kModuleListInvalid, + // There is no Module List version available. + kNoModuleListAvailable, + // Only the IncompatibleApplicationsWarning feature is initialized. + kWarningInitialized, + // Only the ThirdPartyModulesBlocking feature is initialized. + kBlockingInitialized, + // Both the IncompatibleApplicationsWarning and the + // ThirdPartyModulesBlocking feature are initialized. + kWarningAndBlockingInitialized, + }; + + // content::WebUIMessageHandler: + void RegisterMessages() override; + + // ModuleDatabaseObserver: + void OnNewModuleFound(const ModuleInfoKey& module_key, + const ModuleInfoData& module_data) override; + void OnModuleDatabaseIdle() override; + + // Callback for the "requestModuleList" message. + void HandleRequestModuleList(const base::ListValue* args); + +#if defined(GOOGLE_CHROME_BUILD) + // Invoked when the ThirdPartyConflictsManager initialization state is + // available. + void OnManagerInitializationComplete(ThirdPartyConflictsManager::State state); +#endif + + // Registers this instance to the ModuleDatabase to retrieve the list of + // modules via the ModuleDatabaseObserver API. + void GetListOfModules(); + + // Returns true if one of the third-party features is enabled and active. + static bool IsThirdPartyFeatureEnabled(ThirdPartyFeaturesStatus status); + + // Returns the status string of the third-party features. + static std::string GetThirdPartyFeaturesStatusString( + ThirdPartyFeaturesStatus status); + + // The ID of the callback that will get invoked with the module list. + std::string module_list_callback_id_; + + // Temporarily holds the module list while the modules are being + // enumerated. + std::unique_ptr<base::ListValue> module_list_; + + base::Optional<ThirdPartyFeaturesStatus> third_party_features_status_; + + base::WeakPtrFactory<ConflictsHandler> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(ConflictsHandler); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_CONFLICTS_CONFLICTS_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_ui.cc b/chromium/chrome/browser/ui/webui/conflicts/conflicts_ui.cc new file mode 100644 index 00000000000..38b4f7f1cc1 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_ui.cc @@ -0,0 +1,57 @@ +// 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/conflicts/conflicts_ui.h" + +#include <memory> + +#include "base/memory/ref_counted_memory.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/conflicts/conflicts_handler.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/theme_resources.h" +#include "components/strings/grit/components_strings.h" +#include "content/public/browser/web_ui_data_source.h" +#include "ui/base/resource/resource_bundle.h" + +namespace { + +content::WebUIDataSource* CreateConflictsUIHTMLSource() { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(chrome::kChromeUIConflictsHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); + + source->AddResourcePath("conflicts.js", IDR_ABOUT_CONFLICTS_JS); + source->SetDefaultResource(IDR_ABOUT_CONFLICTS_HTML); + return source; +} + +} // namespace + +/////////////////////////////////////////////////////////////////////////////// +// +// ConflictsUI +// +/////////////////////////////////////////////////////////////////////////////// + +ConflictsUI::ConflictsUI(content::WebUI* web_ui) + : content::WebUIController(web_ui) { + web_ui->AddMessageHandler(std::make_unique<ConflictsHandler>()); + + // Set up the about:conflicts source. + Profile* profile = Profile::FromWebUI(web_ui); + content::WebUIDataSource::Add(profile, CreateConflictsUIHTMLSource()); +} + +// static +base::RefCountedMemory* ConflictsUI::GetFaviconResourceBytes( + ui::ScaleFactor scale_factor) { + return static_cast<base::RefCountedMemory*>( + ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( + IDR_CONFLICT_FAVICON, scale_factor)); +} diff --git a/chromium/chrome/browser/ui/webui/conflicts_ui.h b/chromium/chrome/browser/ui/webui/conflicts/conflicts_ui.h index c13d471ed2a..64599d53899 100644 --- a/chromium/chrome/browser/ui/webui/conflicts_ui.h +++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_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_CONFLICTS_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_CONFLICTS_UI_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_CONFLICTS_CONFLICTS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_CONFLICTS_CONFLICTS_UI_H_ #include "base/macros.h" #include "content/public/browser/web_ui_controller.h" @@ -25,4 +25,4 @@ class ConflictsUI : public content::WebUIController { DISALLOW_COPY_AND_ASSIGN(ConflictsUI); }; -#endif // CHROME_BROWSER_UI_WEBUI_CONFLICTS_UI_H_ +#endif // CHROME_BROWSER_UI_WEBUI_CONFLICTS_CONFLICTS_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/conflicts_handler.cc b/chromium/chrome/browser/ui/webui/conflicts_handler.cc deleted file mode 100644 index ee1e739dae9..00000000000 --- a/chromium/chrome/browser/ui/webui/conflicts_handler.cc +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/conflicts_handler.h" - -#include <memory> -#include <utility> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/strings/string16.h" -#include "base/strings/string_number_conversions.h" -#include "base/values.h" -#include "chrome/grit/generated_resources.h" -#include "content/public/browser/web_ui.h" -#include "ui/base/l10n/l10n_util.h" - -ConflictsHandler::ConflictsHandler() : observer_(this) {} -ConflictsHandler::~ConflictsHandler() = default; - -void ConflictsHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "requestModuleList", - base::BindRepeating(&ConflictsHandler::HandleRequestModuleList, - base::Unretained(this))); -} - -void ConflictsHandler::OnScanCompleted() { - SendModuleList(); - observer_.Remove(EnumerateModulesModel::GetInstance()); -} - -void ConflictsHandler::HandleRequestModuleList(const base::ListValue* args) { - auto* model = EnumerateModulesModel::GetInstance(); - // Make sure the JS doesn't call 'requestModuleList' more than once. - // TODO(739291): It would be better to kill the renderer instead of the - // browser for malformed messages. - CHECK(!observer_.IsObserving(model)); - - CHECK_EQ(1U, args->GetSize()); - CHECK(args->GetString(0, &module_list_callback_id_)); - - // The request is handled asynchronously, and will callback via - // OnScanCompleted on completion. - observer_.Add(model); - - // Ask the scan to be performed immediately, and not in background mode. - // This ensures the results are available ASAP for the UI. - model->ScanNow(false); -} - -void ConflictsHandler::SendModuleList() { - auto* loaded_modules = EnumerateModulesModel::GetInstance(); - std::unique_ptr<base::ListValue> list = loaded_modules->GetModuleList(); - - // Add the section title and the total count for bad modules found. - int confirmed_bad = loaded_modules->confirmed_bad_modules_detected(); - int suspected_bad = loaded_modules->suspected_bad_modules_detected(); - base::string16 table_title; - if (!confirmed_bad && !suspected_bad) { - table_title += l10n_util::GetStringFUTF16( - IDS_CONFLICTS_CHECK_PAGE_TABLE_TITLE_SUFFIX_ONE, - base::IntToString16(list->GetSize())); - } else { - table_title += l10n_util::GetStringFUTF16( - IDS_CONFLICTS_CHECK_PAGE_TABLE_TITLE_SUFFIX_TWO, - base::IntToString16(list->GetSize()), - base::IntToString16(confirmed_bad), base::IntToString16(suspected_bad)); - } - base::DictionaryValue results; - results.Set("moduleList", std::move(list)); - results.SetString("modulesTableTitle", table_title); - - AllowJavascript(); - ResolveJavascriptCallback(base::Value(module_list_callback_id_), results); -} diff --git a/chromium/chrome/browser/ui/webui/conflicts_handler.h b/chromium/chrome/browser/ui/webui/conflicts_handler.h deleted file mode 100644 index 495aea7b8a8..00000000000 --- a/chromium/chrome/browser/ui/webui/conflicts_handler.h +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_CONFLICTS_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_CONFLICTS_HANDLER_H_ - -#include <string> - -#include "base/macros.h" -#include "base/scoped_observer.h" -#include "chrome/browser/win/enumerate_modules_model.h" -#include "content/public/browser/web_ui_message_handler.h" - -// This class takes care of sending the list of all loaded modules to the -// chrome://conflicts WebUI page when it is requested. -class ConflictsHandler : public content::WebUIMessageHandler, - public EnumerateModulesModel::Observer { - public: - ConflictsHandler(); - ~ConflictsHandler() override; - - private: - // content::WebUIMessageHandler: - void RegisterMessages() override; - - // EnumerateModulesModel::Observer: - void OnScanCompleted() override; - - // Callback for the "requestModuleList" message. - void HandleRequestModuleList(const base::ListValue* args); - - // Sends the module list back to the WebUI page. - void SendModuleList(); - - ScopedObserver<EnumerateModulesModel, EnumerateModulesModel::Observer> - observer_; - - // The ID of the callback that will get invoked with the module list. - std::string module_list_callback_id_; - - DISALLOW_COPY_AND_ASSIGN(ConflictsHandler); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_CONFLICTS_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/conflicts_ui.cc b/chromium/chrome/browser/ui/webui/conflicts_ui.cc deleted file mode 100644 index 82f83cb41a6..00000000000 --- a/chromium/chrome/browser/ui/webui/conflicts_ui.cc +++ /dev/null @@ -1,81 +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/conflicts_ui.h" - -#include <memory> - -#include "base/memory/ref_counted_memory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/conflicts_handler.h" -#include "chrome/browser/ui/webui/module_database_conflicts_handler.h" -#include "chrome/common/chrome_features.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/theme_resources.h" -#include "components/strings/grit/components_strings.h" -#include "content/public/browser/web_ui_data_source.h" -#include "ui/base/resource/resource_bundle.h" - -namespace { - -content::WebUIDataSource* CreateConflictsUIHTMLSource() { - content::WebUIDataSource* source = - content::WebUIDataSource::Create(chrome::kChromeUIConflictsHost); - - source->AddLocalizedString("loadingMessage", IDS_CONFLICTS_LOADING_MESSAGE); - source->AddLocalizedString("modulesLongTitle", - IDS_CONFLICTS_CHECK_PAGE_TITLE_LONG); - source->AddLocalizedString("modulesBlurb", IDS_CONFLICTS_EXPLANATION_TEXT); - source->AddLocalizedString("moduleSuspectedBad", - IDS_CONFLICTS_CHECK_WARNING_SUSPECTED); - source->AddLocalizedString("moduleConfirmedBad", - IDS_CONFLICTS_CHECK_WARNING_CONFIRMED); - source->AddLocalizedString("helpCenterLink", IDS_LEARN_MORE); - source->AddLocalizedString("investigatingText", - IDS_CONFLICTS_CHECK_INVESTIGATING); - source->AddLocalizedString("modulesNoneLoaded", - IDS_CONFLICTS_NO_MODULES_LOADED); - source->AddLocalizedString("headerSoftware", IDS_CONFLICTS_HEADER_SOFTWARE); - source->AddLocalizedString("headerSignedBy", IDS_CONFLICTS_HEADER_SIGNED_BY); - source->AddLocalizedString("headerLocation", IDS_CONFLICTS_HEADER_LOCATION); - source->AddLocalizedString("headerVersion", IDS_CONFLICTS_HEADER_VERSION); - source->AddLocalizedString("headerHelpTip", IDS_CONFLICTS_HEADER_HELP_TIP); - source->SetJsonPath("strings.js"); - source->AddResourcePath("conflicts.js", IDR_ABOUT_CONFLICTS_JS); - source->SetDefaultResource(IDR_ABOUT_CONFLICTS_HTML); - return source; -} - -} // namespace - -/////////////////////////////////////////////////////////////////////////////// -// -// ConflictsUI -// -/////////////////////////////////////////////////////////////////////////////// - -ConflictsUI::ConflictsUI(content::WebUI* web_ui) - : content::WebUIController(web_ui) { - if (base::FeatureList::IsEnabled(features::kModuleDatabase)) { - web_ui->AddMessageHandler( - std::make_unique<ModuleDatabaseConflictsHandler>()); - } else { - web_ui->AddMessageHandler(std::make_unique<ConflictsHandler>()); - } - - // Set up the about:conflicts source. - Profile* profile = Profile::FromWebUI(web_ui); - content::WebUIDataSource::Add(profile, CreateConflictsUIHTMLSource()); -} - -// static -base::RefCountedMemory* ConflictsUI::GetFaviconResourceBytes( - ui::ScaleFactor scale_factor) { - return static_cast<base::RefCountedMemory*>( - ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( - IDR_CONFLICT_FAVICON, scale_factor)); -} diff --git a/chromium/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc b/chromium/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc index af018abc976..5a36e498cb4 100644 --- a/chromium/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc +++ b/chromium/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc @@ -45,7 +45,7 @@ ConstrainedWebDialogDelegateBase::ConstrainedWebDialogDelegateBase( content::RendererPreferences* prefs = web_contents_->GetMutableRendererPrefs(); renderer_preferences_util::UpdateFromSystemSettings( - prefs, Profile::FromBrowserContext(browser_context), web_contents_); + prefs, Profile::FromBrowserContext(browser_context)); web_contents_->GetRenderViewHost()->SyncRendererPrefs(); diff --git a/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc index f5bb7fcc979..c09a674dd44 100644 --- a/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc @@ -93,10 +93,11 @@ class ConstrainedWebDialogBrowserTest : public InProcessBrowserTest { return false; } + base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated(), + FROM_HERE, run_loop.QuitClosure(), base::TimeDelta::FromMilliseconds(20)); - content::RunMessageLoop(); + run_loop.Run(); } return true; } diff --git a/chromium/chrome/browser/ui/webui/devtools_ui.cc b/chromium/chrome/browser/ui/webui/devtools_ui.cc index a130596ccc9..1d45948ef09 100644 --- a/chromium/chrome/browser/ui/webui/devtools_ui.cc +++ b/chromium/chrome/browser/ui/webui/devtools_ui.cc @@ -271,9 +271,9 @@ void DevToolsDataSource::StartRemoteDataRequest( cookies_store: "user" setting: "This feature cannot be disabled by settings." chrome_policy { - DeveloperToolsDisabled { + DeveloperToolsAvailability { policy_options {mode: MANDATORY} - DeveloperToolsDisabled: true + DeveloperToolsAvailability: 2 } } })"); @@ -310,9 +310,9 @@ void DevToolsDataSource::StartCustomDataRequest( cookies_store: "user" setting: "This feature cannot be disabled by settings." chrome_policy { - DeveloperToolsDisabled { + DeveloperToolsAvailability { policy_options {mode: MANDATORY} - DeveloperToolsDisabled: true + DeveloperToolsAvailability: 2 } } })"); diff --git a/chromium/chrome/browser/ui/webui/discards/BUILD.gn b/chromium/chrome/browser/ui/webui/discards/BUILD.gn index a33645ed5b3..62abc88819e 100644 --- a/chromium/chrome/browser/ui/webui/discards/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/discards/BUILD.gn @@ -9,5 +9,9 @@ if (is_win || is_mac || is_desktop_linux || is_chromeos) { sources = [ "discards.mojom", ] + + public_deps = [ + "//chrome/browser/resource_coordinator:mojo_bindings", + ] } } diff --git a/chromium/chrome/browser/ui/webui/discards/discards.mojom b/chromium/chrome/browser/ui/webui/discards/discards.mojom index 5fe64a8b3ca..64f0d0eb1c4 100644 --- a/chromium/chrome/browser/ui/webui/discards/discards.mojom +++ b/chromium/chrome/browser/ui/webui/discards/discards.mojom @@ -4,6 +4,8 @@ module mojom; +import "chrome/browser/resource_coordinator/lifecycle_unit_state.mojom"; + // Identical to content::Visibility. enum LifecycleUnitVisibility { HIDDEN = 0, @@ -20,16 +22,18 @@ struct TabDiscardsInfo { string title; // The visibility of the LifecycleUnit. LifecycleUnitVisibility visibility; - // If the tab is currently using media functionality (casting, WebRTC, playing - // audio, etc) this is true. - bool is_media; - // If the tab is currently discarded, this is true. - bool is_discarded; - // If the tab is currently frozen, this is true. - // TODO(fmeawad): is_discarded and is_frozen are mutually exclusive, instead - // of representing each individually, we should add a "lifecycle_state" field - // instead. - bool is_frozen; + // The loading state of the LifecycleUnit. + LifecycleUnitLoadingState loading_state; + // The state of the LifecycleUnit. + LifecycleUnitState state; + // Whether the tab can be frozen. + bool can_freeze; + // List of human-readable reasons why a tab can't be frozen. + array<string> cannot_freeze_reasons; + // Whether the tab can be discarded. + bool can_discard; + // List of human-readable reasons why a tab can't be discarded. + array<string> cannot_discard_reasons; // The number of times this tab has been discarded in the current browser // session. int32 discard_count; @@ -50,6 +54,8 @@ struct TabDiscardsInfo { bool has_reactivation_score; // Tab Ranker reactivation score, if |has_reactivation_score| is true. double reactivation_score; + // Site engagement score. + double site_engagement_score; }; // Interface for providing information about discards. Lives in the browser @@ -73,6 +79,9 @@ interface DiscardsDetailsProvider { // Freezes a tab given its |tab_id|. FreezeById(int32 tab_id); + // Loads a tab given its |tab_id|. + LoadById(int32 tab_id); + // Discards the least important tab. If |urgent| is specified the unload // handlers will not be run, and the tab will be unloaded with prejudice. // This can fail to discard a tab if no tabs are currently considered diff --git a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc index c61409079e2..5aaf01c15d1 100644 --- a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc +++ b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc @@ -11,9 +11,11 @@ #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/resource_coordinator/discard_reason.h" #include "chrome/browser/resource_coordinator/lifecycle_unit.h" +#include "chrome/browser/resource_coordinator/lifecycle_unit_state.mojom.h" #include "chrome/browser/resource_coordinator/tab_activity_watcher.h" #include "chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h" #include "chrome/browser/resource_coordinator/tab_manager.h" @@ -21,6 +23,8 @@ #include "chrome/browser/ui/webui/discards/discards.mojom.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/browser_resources.h" +#include "content/public/browser/navigation_controller.h" +#include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" @@ -60,6 +64,26 @@ resource_coordinator::LifecycleUnit* GetLifecycleUnitById(int32_t id) { return nullptr; } +double GetSiteEngagementScore(content::WebContents* contents) { + // Get the active navigation entry. Restored tabs should always have one. + auto& controller = contents->GetController(); + const int current_entry_index = controller.GetCurrentEntryIndex(); + + // A WebContents which hasn't navigated yet does not have a NavigationEntry. + if (current_entry_index == -1) + return 0; + + auto* nav_entry = controller.GetEntryAtIndex(current_entry_index); + DCHECK(nav_entry); + + auto* engagement_svc = SiteEngagementService::Get( + Profile::FromBrowserContext(contents->GetBrowserContext())); + double engagement = + engagement_svc->GetDetails(nav_entry->GetURL()).total_score; + + return engagement; +} + class DiscardsDetailsProviderImpl : public mojom::DiscardsDetailsProvider { public: // This instance is deleted when the supplied pipe is destroyed. @@ -96,9 +120,15 @@ class DiscardsDetailsProviderImpl : public mojom::DiscardsDetailsProvider { info->title = base::UTF16ToUTF8(lifecycle_unit->GetTitle()); info->visibility = GetLifecycleUnitVisibility(lifecycle_unit->GetVisibility()); - info->is_media = tab_lifecycle_unit_external->IsMediaTab(); - info->is_frozen = tab_lifecycle_unit_external->IsFrozen(); - info->is_discarded = tab_lifecycle_unit_external->IsDiscarded(); + info->loading_state = lifecycle_unit->GetLoadingState(); + info->state = lifecycle_unit->GetState(); + resource_coordinator::DecisionDetails freeze_details; + info->can_freeze = lifecycle_unit->CanFreeze(&freeze_details); + info->cannot_freeze_reasons = freeze_details.GetFailureReasonStrings(); + resource_coordinator::DecisionDetails discard_details; + info->can_discard = lifecycle_unit->CanDiscard( + resource_coordinator::DiscardReason::kProactive, &discard_details); + info->cannot_discard_reasons = discard_details.GetFailureReasonStrings(); info->discard_count = tab_lifecycle_unit_external->GetDiscardCount(); info->utility_rank = rank++; const base::TimeTicks last_focused_time = @@ -117,6 +147,7 @@ class DiscardsDetailsProviderImpl : public mojom::DiscardsDetailsProvider { info->has_reactivation_score = reactivation_score.has_value(); if (info->has_reactivation_score) info->reactivation_score = reactivation_score.value(); + info->site_engagement_score = GetSiteEngagementScore(contents); infos.push_back(std::move(info)); } @@ -152,6 +183,12 @@ class DiscardsDetailsProviderImpl : public mojom::DiscardsDetailsProvider { lifecycle_unit->Freeze(); } + void LoadById(int32_t id) override { + auto* lifecycle_unit = GetLifecycleUnitById(id); + if (lifecycle_unit) + lifecycle_unit->Load(); + } + void Discard(bool urgent, DiscardCallback callback) override { resource_coordinator::TabManager* tab_manager = g_browser_process->GetTabManager(); @@ -177,6 +214,9 @@ DiscardsUI::DiscardsUI(content::WebUI* web_ui) // Full paths (relative to src) are important for Mojom generated files. source->AddResourcePath("chrome/browser/ui/webui/discards/discards.mojom.js", IDR_ABOUT_DISCARDS_MOJO_JS); + source->AddResourcePath( + "chrome/browser/resource_coordinator/lifecycle_unit_state.mojom.js", + IDR_ABOUT_DISCARDS_LIFECYCLE_UNIT_STATE_MOJO_JS); source->SetDefaultResource(IDR_ABOUT_DISCARDS_HTML); Profile* profile = Profile::FromWebUI(web_ui); diff --git a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc index 2afd8eb0cfd..c1398cda519 100644 --- a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc @@ -22,6 +22,8 @@ DomainReliabilityInternalsUI::DomainReliabilityInternalsUI( : content::WebUIController(web_ui) { content::WebUIDataSource* html_source = content::WebUIDataSource::Create( chrome::kChromeUIDomainReliabilityInternalsHost); + html_source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); html_source->AddResourcePath("domain_reliability_internals.css", IDR_DOMAIN_RELIABILITY_INTERNALS_CSS); html_source->AddResourcePath("domain_reliability_internals.js", 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 83db485d3ec..4208aeecdc8 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 @@ -19,6 +19,8 @@ DownloadInternalsUI::DownloadInternalsUI(content::WebUI* web_ui) // chrome://download-internals source. content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUIDownloadInternalsHost); + html_source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); // Required resources. html_source->SetJsonPath("strings.js"); diff --git a/chromium/chrome/browser/ui/webui/eoc_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/eoc_internals/BUILD.gn new file mode 100644 index 00000000000..b00810f0a35 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/eoc_internals/BUILD.gn @@ -0,0 +1,11 @@ +# 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. + +import("//mojo/public/tools/bindings/mojom.gni") + +mojom("mojo_bindings") { + sources = [ + "eoc_internals.mojom", + ] +} diff --git a/chromium/chrome/browser/ui/webui/eoc_internals/OWNERS b/chromium/chrome/browser/ui/webui/eoc_internals/OWNERS new file mode 100644 index 00000000000..2d4c4676b66 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/eoc_internals/OWNERS @@ -0,0 +1,4 @@ +file://components/ntp_snippets/OWNERS + +per-file *.mojom=set noparent +per-file *.mojom=file://ipc/SECURITY_OWNERS diff --git a/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals.mojom b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals.mojom new file mode 100644 index 00000000000..0feaff1d0d6 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals.mojom @@ -0,0 +1,102 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module eoc_internals.mojom; + +// Distillation of results from a server request for page suggestions. +struct SuggestionResult { + // The URL of the page that the suggestions are for. + string url; + + // The conditions under which the peek was displayed. + PeekConditions peek_conditions; + + // The suggestions for the page. + array<Suggestion> suggestions; +}; + +// Tracks the server-defined parameters for when to show the peek bar. +struct PeekConditions { + // A measure of confidence that auto-peek should be enabled for this response + // in the range [0, 1]. + float confidence; + + // The percentage of the page that the user scrolls required for an auto + // peek to occur. + float page_scroll_percentage; + + // The minimum time (seconds) the user spends on the page required for + // auto peek. + float minimum_seconds_on_page; + + // The maximum number of auto peeks that we can show for this page. + int64 maximum_number_of_peeks; +}; + +// Models a single suggestion. +struct Suggestion { + // The URL for the suggestion. + string url; + + // Title displayed in the suggestion sheet. + string title; + + // Name of the publisher. + string publisher_name; + + // Text snippet displayed on the sheet. + string snippet; + + // The ID of the image displayed for this suggestion. + string image_id; + + // The ID of the favicon for the suggested URL. + string favicon_image_id; +}; + +// Metrics event that was constructed for a page. +struct MetricEvent { + // The URL which the metrics event is for. + string url; + + // Did the sheet peek show. + bool sheet_peeked; + + // Was the toolbar button shown. + bool button_shown; + + // If the peek was closed without being opened. + bool sheet_opened; + + // If the sheet was opened from the peek. + bool sheet_closed; + + // If any suggestion was clicked on from the sheet. + bool any_suggestion_taken; + + // If any suggestion was downloaded from the sheet. + bool any_suggestion_downloaded; +}; + +// Browser interface for the page. Consists of calls for data and hooks for +// interactivity. +interface PageHandler { + // Get a key/value mapping of properties. + GetProperties() => (map<string, string> properties); + + // Change the triggering time to the given duration. + SetTriggerTime(int64 seconds); + + // Get cached metrics. + GetCachedMetricEvents() => (array<MetricEvent> metrics); + + // Clear the cached metrics. + ClearCachedMetricEvents() => (); + + // Get the cached suggestion results. + GetCachedSuggestionResults() => (array<SuggestionResult> results); + + // Clear the cached suggestions. + ClearCachedSuggestionResults() => (); +}; diff --git a/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_page_handler.cc new file mode 100644 index 00000000000..8d533f08310 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_page_handler.cc @@ -0,0 +1,157 @@ +// 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/eoc_internals/eoc_internals_page_handler.h" + +#include <string> +#include <vector> + +#include "base/containers/flat_map.h" +#include "chrome/browser/android/chrome_feature_list.h" +#include "components/ntp_snippets/contextual/contextual_suggestions_cache.h" +#include "components/ntp_snippets/contextual/contextual_suggestions_features.h" +#include "components/ntp_snippets/contextual/contextual_suggestions_fetch.h" +#include "components/ntp_snippets/contextual/contextual_suggestions_result.h" + +using contextual_suggestions::ContextualContentSuggestionsService; +using contextual_suggestions::ContextualSuggestionsCache; +using contextual_suggestions::ContextualSuggestionsDebuggingReporter; +using contextual_suggestions::ContextualSuggestionsFetch; +using contextual_suggestions::ContextualSuggestionsResult; + +namespace { +bool AreChromeFlagsSetup() { + return (base::FeatureList::IsEnabled( + contextual_suggestions::kContextualSuggestionsBottomSheet) || + base::FeatureList::IsEnabled( + contextual_suggestions::kContextualSuggestionsButton)) && + base::FeatureList::IsEnabled(chrome::android::kChromeModernDesign); +} + +std::string GetAreChromeFlagsSetupString() { + return AreChromeFlagsSetup() ? "true" : "false"; +} +} // namespace + +EocInternalsPageHandler::EocInternalsPageHandler( + eoc_internals::mojom::PageHandlerRequest request, + ContextualContentSuggestionsService* contextual_content_suggestions_service) + : binding_(this, std::move(request)), + contextual_content_suggestions_service_( + contextual_content_suggestions_service) {} + +EocInternalsPageHandler::~EocInternalsPageHandler() {} + +void EocInternalsPageHandler::GetProperties(GetPropertiesCallback callback) { + base::flat_map<std::string, std::string> properties; + // TODO(wylieb): Find the actual time when it's moved to c++ and configurable, + // see b/838748 for more details. + // TODO(wylieb): Instead of having a map<string, string>, move this to a mojo + // struct and populate the fields to html in javascript. + properties["time-to-trigger"] = "2"; + properties["chrome-flags-setup"] = GetAreChromeFlagsSetupString(); + properties["fetch-endpoint-url"] = + ContextualSuggestionsFetch::GetFetchEndpoint(); + std::move(callback).Run(properties); +} + +void EocInternalsPageHandler::SetTriggerTime(int64_t seconds) { + // TODO(wylieb): Implement this when updating triggering time manually is + // supported. +} + +void EocInternalsPageHandler::GetCachedMetricEvents( + GetCachedMetricEventsCallback callback) { + std::vector<eoc_internals::mojom::MetricEventPtr> metric_events; + if (contextual_content_suggestions_service_ == nullptr) { + std::move(callback).Run(std::move(metric_events)); + return; + } + + ContextualSuggestionsDebuggingReporter* debugging_reporter = + contextual_content_suggestions_service_->GetDebuggingReporter(); + // Events will be ordered from oldest -> newest. + // TODO(wylieb): Consider storing a timestamp along with metric events so that + // clear ordering and sorting can be used. + for (auto debug_event : debugging_reporter->GetEvents()) { + auto metric_event = eoc_internals::mojom::MetricEvent::New(); + metric_event->url = debug_event.url; + metric_event->sheet_peeked = debug_event.sheet_peeked; + metric_event->button_shown = debug_event.button_shown; + metric_event->sheet_opened = debug_event.sheet_opened; + metric_event->sheet_closed = debug_event.sheet_closed; + metric_event->any_suggestion_taken = debug_event.any_suggestion_taken; + metric_event->any_suggestion_downloaded = + debug_event.any_suggestion_downloaded; + metric_events.push_back(std::move(metric_event)); + } + std::move(callback).Run(std::move(metric_events)); +} + +void EocInternalsPageHandler::ClearCachedMetricEvents( + ClearCachedMetricEventsCallback callback) { + if (!AreChromeFlagsSetup()) { + std::move(callback).Run(); + return; + } + + contextual_content_suggestions_service_->GetDebuggingReporter() + ->ClearEvents(); + std::move(callback).Run(); +} + +void EocInternalsPageHandler::GetCachedSuggestionResults( + GetCachedSuggestionResultsCallback callback) { + std::vector<eoc_internals::mojom::SuggestionResultPtr> suggestion_results; + if (contextual_content_suggestions_service_ == nullptr) { + std::move(callback).Run(std::move(suggestion_results)); + return; + } + + base::flat_map<GURL, ContextualSuggestionsResult> result_map = + contextual_content_suggestions_service_ + ->GetAllCachedResultsForDebugging(); + + for (auto iter = result_map.begin(); iter != result_map.end(); iter++) { + auto suggestion_result = eoc_internals::mojom::SuggestionResult::New(); + suggestion_result->url = iter->first.spec(); + + auto peek_conditions = eoc_internals::mojom::PeekConditions::New(); + peek_conditions->confidence = iter->second.peek_conditions.confidence; + peek_conditions->page_scroll_percentage = + iter->second.peek_conditions.page_scroll_percentage; + peek_conditions->minimum_seconds_on_page = + iter->second.peek_conditions.minimum_seconds_on_page; + peek_conditions->maximum_number_of_peeks = + iter->second.peek_conditions.maximum_number_of_peeks; + suggestion_result->peek_conditions = std::move(peek_conditions); + + for (const auto& cluster : iter->second.clusters) { + for (const auto& contextual_suggestion : cluster.suggestions) { + auto suggestion = eoc_internals::mojom::Suggestion::New(); + suggestion->url = contextual_suggestion.url.spec(); + suggestion->title = contextual_suggestion.title; + suggestion->publisher_name = contextual_suggestion.publisher_name; + suggestion->snippet = contextual_suggestion.snippet; + suggestion->image_id = contextual_suggestion.image_id; + suggestion->favicon_image_id = contextual_suggestion.favicon_image_id; + suggestion_result->suggestions.push_back(std::move(suggestion)); + } + } + + suggestion_results.push_back(std::move(suggestion_result)); + } + + std::move(callback).Run(std::move(suggestion_results)); +} + +void EocInternalsPageHandler::ClearCachedSuggestionResults( + ClearCachedSuggestionResultsCallback callback) { + if (!AreChromeFlagsSetup()) { + std::move(callback).Run(); + return; + } + + contextual_content_suggestions_service_->ClearCachedResultsForDebugging(); + std::move(callback).Run(); +} diff --git a/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_page_handler.h b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_page_handler.h new file mode 100644 index 00000000000..e852c44e0b6 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_page_handler.h @@ -0,0 +1,39 @@ +// 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_EOC_INTERNALS_EOC_INTERNALS_PAGE_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_EOC_INTERNALS_EOC_INTERNALS_PAGE_HANDLER_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/eoc_internals/eoc_internals.mojom.h" +#include "components/ntp_snippets/contextual/contextual_content_suggestions_service.h" +#include "mojo/public/cpp/bindings/binding.h" + +// Concrete implementation of eoc_internals::mojom::PageHandler. +class EocInternalsPageHandler : public eoc_internals::mojom::PageHandler { + public: + EocInternalsPageHandler( + eoc_internals::mojom::PageHandlerRequest request, + contextual_suggestions::ContextualContentSuggestionsService* + contextual_content_suggestions_service); + ~EocInternalsPageHandler() override; + + private: + // eoc_internals::mojom::EocInternalsPageHandler + void GetProperties(GetPropertiesCallback) override; + void SetTriggerTime(int64_t seconds) override; + void GetCachedMetricEvents(GetCachedMetricEventsCallback) override; + void ClearCachedMetricEvents(ClearCachedMetricEventsCallback) override; + void GetCachedSuggestionResults(GetCachedSuggestionResultsCallback) override; + void ClearCachedSuggestionResults( + ClearCachedSuggestionResultsCallback) override; + + mojo::Binding<eoc_internals::mojom::PageHandler> binding_; + contextual_suggestions::ContextualContentSuggestionsService* + contextual_content_suggestions_service_; + + DISALLOW_COPY_AND_ASSIGN(EocInternalsPageHandler); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_EOC_INTERNALS_EOC_INTERNALS_PAGE_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.cc b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.cc new file mode 100644 index 00000000000..9c7edd3706b --- /dev/null +++ b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.cc @@ -0,0 +1,48 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.h" + +#include "build/build_config.h" +#include "chrome/browser/ntp_snippets/contextual_content_suggestions_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/eoc_internals/eoc_internals_page_handler.h" +#include "chrome/common/url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "content/public/browser/web_ui_data_source.h" + +#if defined(OS_ANDROID) +#include "chrome/browser/android/chrome_feature_list.h" +#endif + +using contextual_suggestions::ContextualContentSuggestionsService; + +EocInternalsUI::EocInternalsUI(content::WebUI* web_ui) + : ui::MojoWebUIController(web_ui) { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(chrome::kChromeUIEocInternalsHost); + + source->AddResourcePath("eoc_internals.css", IDR_EOC_INTERNALS_CSS); + source->AddResourcePath("eoc_internals.js", IDR_EOC_INTERNALS_JS); + source->AddResourcePath("eoc_internals.mojom.js", IDR_EOC_INTERNALS_MOJO_JS); + source->SetDefaultResource(IDR_EOC_INTERNALS_HTML); + source->UseGzip(); + + Profile* profile = Profile::FromWebUI(web_ui); + contextual_content_suggestions_service_ = + ContextualContentSuggestionsServiceFactory::GetForProfile(profile); + content::WebUIDataSource::Add(profile, source); + // This class is the caller of the callback when an observer interface is + // triggered. So this base::Unretained is safe. + AddHandlerToRegistry(base::BindRepeating( + &EocInternalsUI::BindEocInternalsPageHandler, base::Unretained(this))); +} + +EocInternalsUI::~EocInternalsUI() {} + +void EocInternalsUI::BindEocInternalsPageHandler( + eoc_internals::mojom::PageHandlerRequest request) { + page_handler_.reset(new EocInternalsPageHandler( + std::move(request), contextual_content_suggestions_service_)); +} diff --git a/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.h b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.h new file mode 100644 index 00000000000..3650cf0882b --- /dev/null +++ b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.h @@ -0,0 +1,34 @@ +// 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_EOC_INTERNALS_EOC_INTERNALS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_EOC_INTERNALS_EOC_INTERNALS_UI_H_ + +#include <memory> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/eoc_internals/eoc_internals.mojom.h" +#include "chrome/browser/ui/webui/eoc_internals/eoc_internals_page_handler.h" +#include "ui/webui/mojo_web_ui_controller.h" + +// UI controller for chrome://eoc-internals, hooks up a concrete implementation +// of eoc_internals::mojom::PageHandler to requests for that page handler +// that will come from the frontend. +class EocInternalsUI : public ui::MojoWebUIController { + public: + explicit EocInternalsUI(content::WebUI* web_ui); + ~EocInternalsUI() override; + + private: + void BindEocInternalsPageHandler( + eoc_internals::mojom::PageHandlerRequest request); + + std::unique_ptr<EocInternalsPageHandler> page_handler_; + contextual_suggestions::ContextualContentSuggestionsService* + contextual_content_suggestions_service_; + + DISALLOW_COPY_AND_ASSIGN(EocInternalsUI); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_EOC_INTERNALS_EOC_INTERNALS_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc index 8f10e4d7c59..77af9957f7b 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc @@ -114,9 +114,6 @@ std::string GetLoadTimeClasses(bool in_dev_mode) { content::WebUIDataSource* CreateMdExtensionsSource(bool in_dev_mode) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIExtensionsHost); - source->OverrideContentSecurityPolicyScriptSrc( - "script-src chrome://resources 'self';"); - source->SetJsonPath("strings.js"); constexpr LocalizedString localized_strings[] = { @@ -161,6 +158,13 @@ content::WebUIDataSource* CreateMdExtensionsSource(bool in_dev_mode) { {"openChromeWebStore", IDS_MD_EXTENSIONS_SIDEBAR_OPEN_CHROME_WEB_STORE}, {"keyboardShortcuts", IDS_MD_EXTENSIONS_SIDEBAR_KEYBOARD_SHORTCUTS}, {"incognitoInfoWarning", IDS_EXTENSIONS_INCOGNITO_WARNING}, + {"itemHostPermissionsHeading", + IDS_MD_EXTENSIONS_ITEM_HOST_PERMISSIONS_HEADING}, + {"itemHostAccessOnClick", IDS_MD_EXTENSIONS_HOST_ACCESS_ON_CLICK}, + {"itemHostAccessOnSpecificSites", + IDS_MD_EXTENSIONS_HOST_ACCESS_ON_SPECIFIC_SITES}, + {"itemHostAccessOnAllSites", IDS_MD_EXTENSIONS_HOST_ACCESS_ON_ALL_SITES}, + {"itemAllowedHosts", IDS_EXTENSIONS_ITEM_ALLOWED_HOSTS}, {"itemId", IDS_MD_EXTENSIONS_ITEM_ID}, {"itemInspectViews", IDS_MD_EXTENSIONS_ITEM_INSPECT_VIEWS}, // NOTE: This text reads "<n> more". It's possible that it should be using diff --git a/chromium/chrome/browser/ui/webui/fileicon_source.cc b/chromium/chrome/browser/ui/webui/fileicon_source.cc index d78389fdce9..da3b8a64b3e 100644 --- a/chromium/chrome/browser/ui/webui/fileicon_source.cc +++ b/chromium/chrome/browser/ui/webui/fileicon_source.cc @@ -27,10 +27,10 @@ typedef std::map<std::string, IconLoader::IconSize> QueryIconSizeMap; const char kFileIconPath[] = "fileicon"; // URL parameter specifying icon size. -const char kIconSize[] = "iconsize"; +const char kIconSizeParameter[] = "iconsize"; // URL parameter specifying scale factor. -const char kScaleFactor[] = "scale"; +const char kScaleFactorParameter[] = "scale"; // Assuming the url is of the form '/path?query', convert the path portion into // a FilePath and return the resulting |file_path| and |query|. The path @@ -70,9 +70,9 @@ void ParseQueryParams(const std::string& query, base::SplitStringIntoKeyValuePairs(query, '=', '&', ¶meters); for (base::StringPairs::const_iterator iter = parameters.begin(); iter != parameters.end(); ++iter) { - if (icon_size && iter->first == kIconSize) + if (icon_size && iter->first == kIconSizeParameter) *icon_size = SizeStringToIconSize(iter->second); - else if (scale_factor && iter->first == kScaleFactor) + else if (scale_factor && iter->first == kScaleFactorParameter) webui::ParseScaleFactor(iter->second, scale_factor); } } diff --git a/chromium/chrome/browser/ui/webui/flags_ui.cc b/chromium/chrome/browser/ui/webui/flags_ui.cc index eca2c98b7fe..e79e5fcc715 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui.cc +++ b/chromium/chrome/browser/ui/webui/flags_ui.cc @@ -59,6 +59,8 @@ namespace { content::WebUIDataSource* CreateFlagsUIHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIFlagsHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->AddLocalizedString(flags_ui::kFlagsRestartNotice, IDS_FLAGS_UI_RELAUNCH_NOTICE); diff --git a/chromium/chrome/browser/ui/webui/flash_ui.cc b/chromium/chrome/browser/ui/webui/flash_ui.cc index 625921b65da..2fdf9142f2a 100644 --- a/chromium/chrome/browser/ui/webui/flash_ui.cc +++ b/chromium/chrome/browser/ui/webui/flash_ui.cc @@ -30,6 +30,7 @@ #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/channel_info.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" @@ -59,6 +60,7 @@ using content::GpuDataManager; using content::PluginService; using content::WebContents; using content::WebUIMessageHandler; +using webui::webui_util::AddPair; namespace { @@ -67,6 +69,8 @@ const char kFlashPlugin[] = "Flash plugin"; content::WebUIDataSource* CreateFlashUIHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIFlashHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->AddLocalizedString("loadingMessage", IDS_FLASH_LOADING_MESSAGE); source->AddLocalizedString("flashLongTitle", IDS_FLASH_TITLE_MESSAGE); @@ -322,7 +326,8 @@ void FlashDOMHandler::MaybeRespondToPage() { // GPU information. AddPair(list.get(), base::string16(), "--- GPU information ---"); - gpu::GPUInfo gpu_info = GpuDataManager::GetInstance()->GetGPUInfo(); + const gpu::GPUInfo gpu_info = GpuDataManager::GetInstance()->GetGPUInfo(); + const gpu::GPUInfo::GPUDevice& active_gpu = gpu_info.active_gpu(); std::string reason; if (!GpuDataManager::GetInstance()->GpuAccessAllowed(&reason)) { @@ -355,12 +360,13 @@ void FlashDOMHandler::MaybeRespondToPage() { AddPair(list.get(), base::string16(), "--- GPU driver, more information ---"); AddPair(list.get(), ASCIIToUTF16("Vendor Id"), - base::StringPrintf("0x%04x", gpu_info.gpu.vendor_id)); + base::StringPrintf("0x%04x", active_gpu.vendor_id)); AddPair(list.get(), ASCIIToUTF16("Device Id"), - base::StringPrintf("0x%04x", gpu_info.gpu.device_id)); - AddPair(list.get(), ASCIIToUTF16("Driver vendor"), gpu_info.driver_vendor); - AddPair(list.get(), ASCIIToUTF16("Driver version"), gpu_info.driver_version); - AddPair(list.get(), ASCIIToUTF16("Driver date"), gpu_info.driver_date); + base::StringPrintf("0x%04x", active_gpu.device_id)); + AddPair(list.get(), ASCIIToUTF16("Driver vendor"), active_gpu.driver_vendor); + AddPair(list.get(), ASCIIToUTF16("Driver version"), + active_gpu.driver_version); + AddPair(list.get(), ASCIIToUTF16("Driver date"), active_gpu.driver_date); AddPair(list.get(), ASCIIToUTF16("Pixel shader version"), gpu_info.pixel_shader_version); AddPair(list.get(), ASCIIToUTF16("Vertex shader version"), diff --git a/chromium/chrome/browser/ui/webui/foreign_session_handler.cc b/chromium/chrome/browser/ui/webui/foreign_session_handler.cc index aa938b1a909..67f9a2e08dc 100644 --- a/chromium/chrome/browser/ui/webui/foreign_session_handler.cc +++ b/chromium/chrome/browser/ui/webui/foreign_session_handler.cc @@ -34,7 +34,6 @@ #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" -#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/time_format.h" #include "ui/base/webui/web_ui_util.h" @@ -111,15 +110,6 @@ std::unique_ptr<base::DictionaryValue> BuildWindowData( // Please update it whenever you add or remove any keys here. dictionary->SetString("type", "window"); dictionary->SetDouble("timestamp", modification_time.ToInternalValue()); - const base::TimeDelta last_synced = base::Time::Now() - modification_time; - // If clock skew leads to a future time, or we last synced less than a minute - // ago, output "Just now". - dictionary->SetString( - "userVisibleTimestamp", - last_synced < base::TimeDelta::FromMinutes(1) - ? l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW) - : ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED, - ui::TimeFormat::LENGTH_SHORT, last_synced)); dictionary->SetInteger("sessionId", window_id.id()); return dictionary; diff --git a/chromium/chrome/browser/ui/webui/help/version_updater.h b/chromium/chrome/browser/ui/webui/help/version_updater.h index 2bfc0d51f94..ad34cb0c53f 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater.h +++ b/chromium/chrome/browser/ui/webui/help/version_updater.h @@ -52,15 +52,22 @@ class VersionUpdater { EolStatusCallback; #endif - // Used to update the client of status changes. int parameter is the progress - // and should only be non-zero for the UPDATING state. - // std::string parameter is the version of the available update and should be - // empty string when update is not available. - // int64_t parameter is the size in bytes of the available update and should - // be 0 when update is not available. - // base::string16 parameter is a message explaining a failure. - typedef base::Callback< - void(Status, int, const std::string&, int64_t, const base::string16&)> + // Used to update the client of status changes. + // |status| is the current state of the update. + // |progress| should only be non-zero for the UPDATING state. + // |rollback| indicates whether the update is actually a rollback, which + // requires wiping the device upon reboot. + // |version| is the version of the available update and should be empty string + // when update is not available. + // |update_size| is the size of the available update in bytes and should be 0 + // when update is not available. + // |message| is a message explaining a failure. + typedef base::Callback<void(Status status, + int progress, + bool rollback, + const std::string& version, + int64_t update_size, + const base::string16& message)> StatusCallback; // Used to show or hide the promote UI elements. Mac-only. diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_basic.cc b/chromium/chrome/browser/ui/webui/help/version_updater_basic.cc index 8cb85a35079..796d0a5a9f4 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_basic.cc +++ b/chromium/chrome/browser/ui/webui/help/version_updater_basic.cc @@ -11,9 +11,10 @@ void VersionUpdaterBasic::CheckForUpdate( const StatusCallback& status_callback, const PromoteCallback&) { if (UpgradeDetector::GetInstance()->notify_upgrade()) - status_callback.Run(NEARLY_UPDATED, 0, std::string(), 0, base::string16()); + status_callback.Run(NEARLY_UPDATED, 0, false, std::string(), 0, + base::string16()); else - status_callback.Run(DISABLED, 0, std::string(), 0, base::string16()); + status_callback.Run(DISABLED, 0, false, std::string(), 0, base::string16()); } VersionUpdater* VersionUpdater::Create(content::WebContents* web_contents) { 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 815a49eb16d..66060e64fa7 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc +++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc @@ -106,7 +106,7 @@ base::string16 GetConnectionTypeAsUTF16(const chromeos::NetworkState* network) { bool EnsureCanUpdate(bool interactive, const VersionUpdater::StatusCallback& callback) { if (IsAutoUpdateDisabled()) { - callback.Run(VersionUpdater::DISABLED_BY_ADMIN, 0, std::string(), 0, + callback.Run(VersionUpdater::DISABLED_BY_ADMIN, 0, false, std::string(), 0, l10n_util::GetStringUTF16(IDS_UPGRADE_DISABLED_BY_POLICY)); return false; } @@ -120,13 +120,13 @@ bool EnsureCanUpdate(bool interactive, // to a network for which updates are disallowed. NetworkStatus status = GetNetworkStatus(interactive, network); if (status == NETWORK_STATUS_OFFLINE) { - callback.Run(VersionUpdater::FAILED_OFFLINE, 0, std::string(), 0, + callback.Run(VersionUpdater::FAILED_OFFLINE, 0, false, std::string(), 0, l10n_util::GetStringUTF16(IDS_UPGRADE_OFFLINE)); return false; } else if (status == NETWORK_STATUS_DISALLOWED) { base::string16 message = l10n_util::GetStringFUTF16( IDS_UPGRADE_DISALLOWED, GetConnectionTypeAsUTF16(network)); - callback.Run(VersionUpdater::FAILED_CONNECTION_TYPE_DISALLOWED, 0, + callback.Run(VersionUpdater::FAILED_CONNECTION_TYPE_DISALLOWED, 0, false, std::string(), 0, message); return false; } @@ -221,7 +221,7 @@ void VersionUpdaterCros::OnSetUpdateOverCellularOneTimePermission( // TODO(weidongg/691108): invoke callback to signal about page to show // appropriate error message. LOG(ERROR) << "Error setting update over cellular one time permission."; - callback_.Run(VersionUpdater::FAILED, 0, std::string(), 0, + callback_.Run(VersionUpdater::FAILED, 0, false, std::string(), 0, base::string16()); } } @@ -325,7 +325,8 @@ void VersionUpdaterCros::UpdateStatusChanged( break; } - callback_.Run(my_status, progress, version, size, message); + callback_.Run(my_status, progress, status.is_rollback, version, size, + message); last_operation_ = status.status; if (check_for_update_when_idle_ && @@ -339,5 +340,5 @@ void VersionUpdaterCros::OnUpdateCheck( // If version updating is not implemented, this binary is the most up-to-date // possible with respect to automatic updating. if (result == UpdateEngineClient::UPDATE_RESULT_NOTIMPLEMENTED) - callback_.Run(UPDATED, 0, std::string(), 0, base::string16()); + callback_.Run(UPDATED, 0, false, std::string(), 0, base::string16()); } 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 2e47406c229..587ec32394c 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 @@ -33,6 +33,7 @@ namespace { void CheckNotification(VersionUpdater::Status /* status */, int /* progress */, + bool /* rollback */, const std::string& /* version */, int64_t /* size */, const base::string16& /* message */) {} diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_mac.mm b/chromium/chrome/browser/ui/webui/help/version_updater_mac.mm index 243d5624542..e339760732f 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_mac.mm +++ b/chromium/chrome/browser/ui/webui/help/version_updater_mac.mm @@ -108,7 +108,8 @@ void VersionUpdaterMac::CheckForUpdate( } else { // There is no glue, or the application is on a read-only filesystem. // Updates and promotions are impossible. - status_callback_.Run(DISABLED, 0, std::string(), 0, base::string16()); + status_callback_.Run(DISABLED, 0, false, std::string(), 0, + base::string16()); } } @@ -235,7 +236,7 @@ void VersionUpdaterMac::UpdateStatus(NSDictionary* dictionary) { } if (!status_callback_.is_null()) - status_callback_.Run(status, 0, std::string(), 0, message); + status_callback_.Run(status, 0, false, std::string(), 0, message); PromotionState promotion_state; if (!promote_callback_.is_null()) { 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 861526eea8a..a09e5751176 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_win.cc +++ b/chromium/chrome/browser/ui/webui/help/version_updater_win.cc @@ -29,7 +29,7 @@ void VersionUpdaterWin::CheckForUpdate(const StatusCallback& callback, // There is no supported integration with Google Update for Chromium. callback_ = callback; - callback_.Run(CHECKING, 0, std::string(), 0, base::string16()); + callback_.Run(CHECKING, 0, false, std::string(), 0, base::string16()); DoBeginUpdateCheck(false /* !install_update_if_possible */); } @@ -50,18 +50,18 @@ void VersionUpdaterWin::OnUpdateCheckComplete( // Notify the caller that the update is now beginning and initiate it. DoBeginUpdateCheck(true /* install_update_if_possible */); - callback_.Run(UPDATING, 0, std::string(), 0, base::string16()); + callback_.Run(UPDATING, 0, false, std::string(), 0, base::string16()); } void VersionUpdaterWin::OnUpgradeProgress(int progress, const base::string16& new_version) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - callback_.Run(UPDATING, progress, std::string(), 0, base::string16()); + callback_.Run(UPDATING, progress, false, std::string(), 0, base::string16()); } void VersionUpdaterWin::OnUpgradeComplete(const base::string16& new_version) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - callback_.Run(NEARLY_UPDATED, 0, std::string(), 0, base::string16()); + callback_.Run(NEARLY_UPDATED, 0, false, std::string(), 0, base::string16()); } void VersionUpdaterWin::OnError(GoogleUpdateErrorCode error_code, @@ -92,7 +92,7 @@ void VersionUpdaterWin::OnError(GoogleUpdateErrorCode error_code, } break; } - callback_.Run(status, 0, std::string(), 0, message); + callback_.Run(status, 0, false, std::string(), 0, message); } void VersionUpdaterWin::DoBeginUpdateCheck(bool install_update_if_possible) { @@ -104,7 +104,7 @@ void VersionUpdaterWin::DoBeginUpdateCheck(bool install_update_if_possible) { } void VersionUpdaterWin::OnPendingRestartCheck(bool is_update_pending_restart) { - callback_.Run(is_update_pending_restart ? NEARLY_UPDATED : UPDATED, 0, + callback_.Run(is_update_pending_restart ? NEARLY_UPDATED : UPDATED, 0, false, std::string(), 0, base::string16()); } diff --git a/chromium/chrome/browser/ui/webui/identity_internals_ui.cc b/chromium/chrome/browser/ui/webui/identity_internals_ui.cc index ecd1b1f2407..5e0382505cc 100644 --- a/chromium/chrome/browser/ui/webui/identity_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/identity_internals_ui.cc @@ -276,8 +276,9 @@ IdentityInternalsTokenRevoker::IdentityInternalsTokenRevoker( const std::string& access_token, Profile* profile, IdentityInternalsUIMessageHandler* consumer) - : fetcher_(this, GaiaConstants::kChromeSource, - profile->GetRequestContext()), + : fetcher_(this, + GaiaConstants::kChromeSource, + profile->GetURLLoaderFactory()), extension_id_(extension_id), access_token_(access_token), consumer_(consumer) { diff --git a/chromium/chrome/browser/ui/webui/inspect_ui.cc b/chromium/chrome/browser/ui/webui/inspect_ui.cc index 42524631a82..e777221fc77 100644 --- a/chromium/chrome/browser/ui/webui/inspect_ui.cc +++ b/chromium/chrome/browser/ui/webui/inspect_ui.cc @@ -38,41 +38,42 @@ using content::WebUIMessageHandler; namespace { -const char kInitUICommand[] = "init-ui"; -const char kInspectCommand[] = "inspect"; -const char kInspectFallbackCommand[] = "inspect-fallback"; -const char kInspectAdditionalCommand[] = "inspect-additional"; -const char kActivateCommand[] = "activate"; -const char kCloseCommand[] = "close"; -const char kReloadCommand[] = "reload"; -const char kOpenCommand[] = "open"; -const char kInspectBrowser[] = "inspect-browser"; -const char kLocalHost[] = "localhost"; - -const char kDiscoverUsbDevicesEnabledCommand[] = +const char kInspectUiInitUICommand[] = "init-ui"; +const char kInspectUiInspectCommand[] = "inspect"; +const char kInspectUiInspectFallbackCommand[] = "inspect-fallback"; +const char kInspectUiInspectAdditionalCommand[] = "inspect-additional"; +const char kInspectUiActivateCommand[] = "activate"; +const char kInspectUiCloseCommand[] = "close"; +const char kInspectUiReloadCommand[] = "reload"; +const char kInspectUiOpenCommand[] = "open"; +const char kInspectUiInspectBrowser[] = "inspect-browser"; +const char kInspectUiLocalHost[] = "localhost"; + +const char kInspectUiDiscoverUsbDevicesEnabledCommand[] = "set-discover-usb-devices-enabled"; -const char kPortForwardingEnabledCommand[] = +const char kInspectUiPortForwardingEnabledCommand[] = "set-port-forwarding-enabled"; -const char kPortForwardingConfigCommand[] = "set-port-forwarding-config"; -const char kDiscoverTCPTargetsEnabledCommand[] = +const char kInspectUiPortForwardingConfigCommand[] = + "set-port-forwarding-config"; +const char kInspectUiDiscoverTCPTargetsEnabledCommand[] = "set-discover-tcp-targets-enabled"; -const char kTCPDiscoveryConfigCommand[] = "set-tcp-discovery-config"; -const char kOpenNodeFrontendCommand[] = "open-node-frontend"; +const char kInspectUiTCPDiscoveryConfigCommand[] = "set-tcp-discovery-config"; +const char kInspectUiOpenNodeFrontendCommand[] = "open-node-frontend"; -const char kPortForwardingDefaultPort[] = "8080"; -const char kPortForwardingDefaultLocation[] = "localhost:8080"; +const char kInspectUiPortForwardingDefaultPort[] = "8080"; +const char kInspectUiPortForwardingDefaultLocation[] = "localhost:8080"; -const char kNameField[] = "name"; -const char kUrlField[] = "url"; -const char kIsAdditionalField[] = "isAdditional"; +const char kInspectUiNameField[] = "name"; +const char kInspectUiUrlField[] = "url"; +const char kInspectUiIsAdditionalField[] = "isAdditional"; void GetUiDevToolsTargets(base::ListValue& targets) { for (const auto& client_pair : ui_devtools::UiDevToolsServer::GetClientNamesAndUrls()) { auto target_data = std::make_unique<base::DictionaryValue>(); - target_data->SetString(kNameField, client_pair.first); - target_data->SetString(kUrlField, client_pair.second); - target_data->SetBoolean(kIsAdditionalField, true); + target_data->SetString(kInspectUiNameField, client_pair.first); + target_data->SetString(kInspectUiUrlField, client_pair.second); + target_data->SetBoolean(kInspectUiIsAdditionalField, true); targets.Append(std::move(target_data)); } } @@ -111,69 +112,69 @@ class InspectMessageHandler : public WebUIMessageHandler { void InspectMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - kInitUICommand, + kInspectUiInitUICommand, base::BindRepeating(&InspectMessageHandler::HandleInitUICommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kInspectCommand, + kInspectUiInspectCommand, base::BindRepeating(&InspectMessageHandler::HandleInspectCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kInspectFallbackCommand, + kInspectUiInspectFallbackCommand, base::BindRepeating(&InspectMessageHandler::HandleInspectFallbackCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kInspectAdditionalCommand, + kInspectUiInspectAdditionalCommand, base::BindRepeating( &InspectMessageHandler::HandleInspectAdditionalCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kActivateCommand, + kInspectUiActivateCommand, base::BindRepeating(&InspectMessageHandler::HandleActivateCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kCloseCommand, + kInspectUiCloseCommand, base::BindRepeating(&InspectMessageHandler::HandleCloseCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kDiscoverUsbDevicesEnabledCommand, + kInspectUiDiscoverUsbDevicesEnabledCommand, base::BindRepeating(&InspectMessageHandler::HandleBooleanPrefChanged, base::Unretained(this), &prefs::kDevToolsDiscoverUsbDevicesEnabled[0])); web_ui()->RegisterMessageCallback( - kPortForwardingEnabledCommand, + kInspectUiPortForwardingEnabledCommand, base::BindRepeating(&InspectMessageHandler::HandleBooleanPrefChanged, base::Unretained(this), &prefs::kDevToolsPortForwardingEnabled[0])); web_ui()->RegisterMessageCallback( - kPortForwardingConfigCommand, + kInspectUiPortForwardingConfigCommand, base::BindRepeating( &InspectMessageHandler::HandlePortForwardingConfigCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kDiscoverTCPTargetsEnabledCommand, + kInspectUiDiscoverTCPTargetsEnabledCommand, base::BindRepeating(&InspectMessageHandler::HandleBooleanPrefChanged, base::Unretained(this), &prefs::kDevToolsDiscoverTCPTargetsEnabled[0])); web_ui()->RegisterMessageCallback( - kTCPDiscoveryConfigCommand, + kInspectUiTCPDiscoveryConfigCommand, base::BindRepeating( &InspectMessageHandler::HandleTCPDiscoveryConfigCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kOpenNodeFrontendCommand, + kInspectUiOpenNodeFrontendCommand, base::BindRepeating(&InspectMessageHandler::HandleOpenNodeFrontendCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kReloadCommand, + kInspectUiReloadCommand, base::BindRepeating(&InspectMessageHandler::HandleReloadCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kOpenCommand, + kInspectUiOpenCommand, base::BindRepeating(&InspectMessageHandler::HandleOpenCommand, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kInspectBrowser, + kInspectUiInspectBrowser, base::BindRepeating(&InspectMessageHandler::HandleInspectBrowserCommand, base::Unretained(this))); } @@ -437,7 +438,7 @@ void InspectUI::InspectBrowserWithCustomFrontend( const GURL& frontend_url) { if (!frontend_url.SchemeIs(content::kChromeUIScheme) && !frontend_url.SchemeIs(content::kChromeDevToolsScheme) && - frontend_url.host() != kLocalHost) { + frontend_url.host() != kInspectUiLocalHost) { return; } @@ -608,8 +609,8 @@ void InspectUI::SetPortForwardingDefaults() { return; base::DictionaryValue default_config; - default_config.SetString( - kPortForwardingDefaultPort, kPortForwardingDefaultLocation); + default_config.SetString(kInspectUiPortForwardingDefaultPort, + kInspectUiPortForwardingDefaultLocation); prefs->Set(prefs::kDevToolsPortForwardingConfig, default_config); } 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 da4c18dd61f..a1312af72e2 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,6 +19,7 @@ #include "base/test/scoped_command_line.h" #include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" +#include "base/time/default_clock.h" #include "build/build_config.h" #include "chrome/browser/flag_descriptions.h" #include "chrome/browser/net/nqe/ui_network_quality_estimator_service.h" @@ -29,7 +30,8 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "components/previews/content/previews_io_data.h" +#include "components/blacklist/opt_out_blacklist/opt_out_blacklist_data.h" +#include "components/previews/content/previews_decider_impl.h" #include "components/previews/content/previews_ui_service.h" #include "components/previews/core/previews_features.h" #include "components/previews/core/previews_logger.h" @@ -211,16 +213,21 @@ class TestUINetworkQualityEstimatorService }; // A dummy class to setup PreviewsUIService. -class TestPreviewsIOData : public previews::PreviewsIOData { +class TestPreviewsDeciderImpl : public previews::PreviewsDeciderImpl { public: - TestPreviewsIOData() : PreviewsIOData(nullptr, nullptr) {} + TestPreviewsDeciderImpl() + : PreviewsDeciderImpl(nullptr, + nullptr, + base::DefaultClock::GetInstance()) {} - // previews::PreviewsIOData: + // previews::PreviewsDeciderImpl: void Initialize( base::WeakPtr<previews::PreviewsUIService> previews_ui_service, - std::unique_ptr<previews::PreviewsOptOutStore> opt_out_store, + std::unique_ptr<blacklist::OptOutStore> opt_out_store, std::unique_ptr<previews::PreviewsOptimizationGuide> previews_opt_guide, - const previews::PreviewsIsEnabledCallback& is_enabled_callback) override { + const previews::PreviewsIsEnabledCallback& is_enabled_callback, + blacklist::BlacklistData::AllowedTypesAndVersions allowed_types) + override { // Do nothing. } }; @@ -228,14 +235,15 @@ class TestPreviewsIOData : public previews::PreviewsIOData { // Mocked TestPreviewsService for testing InterventionsInternalsPageHandler. class TestPreviewsUIService : public previews::PreviewsUIService { public: - TestPreviewsUIService(TestPreviewsIOData* io_data, + TestPreviewsUIService(TestPreviewsDeciderImpl* previews_decider_impl, std::unique_ptr<previews::PreviewsLogger> logger) - : PreviewsUIService(io_data, + : PreviewsUIService(previews_decider_impl, nullptr, /* io_task_runner */ nullptr, /* previews_opt_out_store */ nullptr, /* previews_opt_guide */ base::Bind(&MockedPreviewsIsEnabled), - std::move(logger)), + std::move(logger), + blacklist::BlacklistData::AllowedTypesAndVersions()), blacklist_ignored_(false) {} ~TestPreviewsUIService() override {} @@ -260,7 +268,7 @@ class InterventionsInternalsPageHandlerTest : public testing::Test { ~InterventionsInternalsPageHandlerTest() override {} void SetUp() override { - TestPreviewsIOData io_data; + TestPreviewsDeciderImpl io_data; std::unique_ptr<TestPreviewsLogger> logger = std::make_unique<TestPreviewsLogger>(); logger_ = logger.get(); diff --git a/chromium/chrome/browser/ui/webui/invalidations_ui.cc b/chromium/chrome/browser/ui/webui/invalidations_ui.cc index f9daad69d7e..6f9b8f27936 100644 --- a/chromium/chrome/browser/ui/webui/invalidations_ui.cc +++ b/chromium/chrome/browser/ui/webui/invalidations_ui.cc @@ -19,6 +19,8 @@ content::WebUIDataSource* CreateInvalidationsHTMLSource() { // This method does not fire when refreshing the page content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIInvalidationsHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->AddResourcePath("about_invalidations.js", IDR_ABOUT_INVALIDATIONS_JS); source->SetDefaultResource(IDR_ABOUT_INVALIDATIONS_HTML); source->UseGzip(); @@ -35,4 +37,3 @@ InvalidationsUI::InvalidationsUI(content::WebUI* web_ui) } InvalidationsUI::~InvalidationsUI() { } - diff --git a/chromium/chrome/browser/ui/webui/local_discovery/OWNERS b/chromium/chrome/browser/ui/webui/local_discovery/OWNERS index 4633094760d..3b8d2d087bc 100644 --- a/chromium/chrome/browser/ui/webui/local_discovery/OWNERS +++ b/chromium/chrome/browser/ui/webui/local_discovery/OWNERS @@ -1,4 +1,3 @@ -gene@chromium.org -vitalybuka@chromium.org +file://cloud_print/OWNERS # COMPONENT: Services>CloudPrint diff --git a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc index 90ee886c403..2488a4195d1 100644 --- a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc @@ -12,6 +12,7 @@ #include "base/compiler_specific.h" #include "base/location.h" #include "base/macros.h" +#include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" @@ -20,6 +21,8 @@ #include "chrome/browser/media/router/providers/cast/dual_media_sink_service.h" #include "chrome/browser/media/router/test/noop_dual_media_sink_service.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" @@ -36,6 +39,9 @@ #include "net/url_request/url_request_status.h" #include "net/url_request/url_request_test_util.h" #include "services/identity/public/cpp/identity_test_utils.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" +#include "services/network/test/test_url_loader_factory.h" #if defined(OS_CHROMEOS) #include "chrome/common/pref_names.h" @@ -347,10 +353,12 @@ class MockableFakeURLFetcherCreator { class LocalDiscoveryUITest : public WebUIBrowserTest { public: - LocalDiscoveryUITest() : fake_fetcher_factory_( - &fetcher_impl_factory_, - fake_url_fetcher_creator_.callback()) { - } + LocalDiscoveryUITest() + : test_shared_loader_factory_( + base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( + &test_url_loader_factory_)), + fake_fetcher_factory_(&fetcher_impl_factory_, + fake_url_fetcher_creator_.callback()) {} ~LocalDiscoveryUITest() override { } @@ -377,6 +385,11 @@ class LocalDiscoveryUITest : public WebUIBrowserTest { &TestMessageLoopCondition::Signal)) .WillRepeatedly(Return()); + test_url_loader_factory_.AddResponse( + GaiaUrls::GetInstance()->oauth2_token_url().spec(), kResponseGaiaToken); + test_url_loader_factory_.AddResponse( + GaiaUrls::GetInstance()->oauth_user_info_url().spec(), kResponseGaiaId); + fake_fetcher_factory().SetFakeResponse( GURL(kURLInfo), kResponseInfo, @@ -433,10 +446,16 @@ class LocalDiscoveryUITest : public WebUIBrowserTest { kSampleUser); AddLibrary(base::FilePath(FILE_PATH_LITERAL("local_discovery_ui_test.js"))); + + ChromeSigninClient* signin_client = static_cast<ChromeSigninClient*>( + ChromeSigninClientFactory::GetForProfile( + ProfileManager::GetActiveUserProfile())); + signin_client->SetURLLoaderFactoryForTest(test_shared_loader_factory_); } void TearDownOnMainThread() override { test_service_discovery_client_ = nullptr; + test_shared_loader_factory_->Detach(); WebUIBrowserTest::TearDownOnMainThread(); } @@ -483,6 +502,10 @@ class LocalDiscoveryUITest : public WebUIBrowserTest { scoped_refptr<TestServiceDiscoveryClient> test_service_discovery_client_; TestMessageLoopCondition condition_devices_listed_; + network::TestURLLoaderFactory test_url_loader_factory_; + scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> + test_shared_loader_factory_; + net::URLFetcherImplFactory fetcher_impl_factory_; StrictMock<MockableFakeURLFetcherCreator> fake_url_fetcher_creator_; net::FakeURLFetcherFactory fake_fetcher_factory_; @@ -521,8 +544,7 @@ IN_PROC_BROWSER_TEST_F(LocalDiscoveryUITest, AddRowTest) { IN_PROC_BROWSER_TEST_F(LocalDiscoveryUITest, RegisterTest) { TestMessageLoopCondition condition_token_claimed; - ui_test_utils::NavigateToURL(browser(), GURL( - chrome::kChromeUIDevicesURL)); + ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIDevicesURL)); condition_devices_listed().Wait(); test_service_discovery_client()->SimulateReceive( diff --git a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc index 8517d881ae0..1ad7ece153e 100644 --- a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc @@ -20,8 +20,7 @@ #include "chrome/browser/printing/cloud_print/privet_device_lister_impl.h" #include "chrome/browser/printing/cloud_print/privet_http_asynchronous_factory.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/chrome_pages.h" @@ -29,7 +28,6 @@ #include "chrome/grit/generated_resources.h" #include "components/cloud_devices/common/cloud_devices_urls.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/profile_oauth2_token_service.h" #include "content/public/browser/web_ui.h" #include "printing/buildflags/buildflags.h" #include "ui/base/l10n/l10n_util.h" @@ -104,10 +102,10 @@ LocalDiscoveryUIHandler::LocalDiscoveryUIHandler() LocalDiscoveryUIHandler::~LocalDiscoveryUIHandler() { Profile* profile = Profile::FromWebUI(web_ui()); - SigninManagerBase* signin_manager = - SigninManagerFactory::GetInstance()->GetForProfile(profile); - if (signin_manager) - signin_manager->RemoveObserver(this); + identity::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile(profile); + if (identity_manager) + identity_manager->RemoveObserver(this); ResetCurrentRegistration(); SetIsVisible(false); } @@ -174,10 +172,10 @@ void LocalDiscoveryUIHandler::HandleStart(const base::ListValue* args) { cloud_print::PrivetHTTPAsynchronousFactory::CreateInstance( profile->GetRequestContext()); - SigninManagerBase* signin_manager = - SigninManagerFactory::GetInstance()->GetForProfile(profile); - if (signin_manager) - signin_manager->AddObserver(this); + identity::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile(profile); + if (identity_manager) + identity_manager->AddObserver(this); } privet_lister_->Start(); @@ -403,14 +401,13 @@ void LocalDiscoveryUIHandler::OnDeviceListUnavailable() { CheckListingDone(); } -void LocalDiscoveryUIHandler::GoogleSigninSucceeded( - const std::string& account_id, - const std::string& username) { +void LocalDiscoveryUIHandler::OnPrimaryAccountSet( + const AccountInfo& primary_account_info) { CheckUserLoggedIn(); } -void LocalDiscoveryUIHandler::GoogleSignedOut(const std::string& account_id, - const std::string& username) { +void LocalDiscoveryUIHandler::OnPrimaryAccountCleared( + const AccountInfo& previous_primary_account_info) { CheckUserLoggedIn(); } @@ -457,12 +454,12 @@ void LocalDiscoveryUIHandler::SetIsVisible(bool visible) { std::string LocalDiscoveryUIHandler::GetSyncAccount() const { Profile* profile = Profile::FromWebUI(web_ui()); - SigninManagerBase* signin_manager = - SigninManagerFactory::GetForProfileIfExists(profile); + identity::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile(profile); std::string email; - if (signin_manager) - email = signin_manager->GetAuthenticatedAccountInfo().email; + if (identity_manager && identity_manager->HasPrimaryAccount()) + email = identity_manager->GetPrimaryAccountInfo().email; return email; } @@ -514,19 +511,12 @@ std::unique_ptr<GCDApiFlow> LocalDiscoveryUIHandler::CreateApiFlow() { if (!profile) return std::unique_ptr<GCDApiFlow>(); - ProfileOAuth2TokenService* token_service = - ProfileOAuth2TokenServiceFactory::GetForProfile(profile); - if (!token_service) + identity::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile(profile); + if (!(identity_manager && identity_manager->HasPrimaryAccount())) return std::unique_ptr<GCDApiFlow>(); - SigninManagerBase* signin_manager = - SigninManagerFactory::GetInstance()->GetForProfile(profile); - if (!signin_manager) - return std::unique_ptr<GCDApiFlow>(); - - return GCDApiFlow::Create(profile->GetRequestContext(), - token_service, - signin_manager->GetAuthenticatedAccountId()); + return GCDApiFlow::Create(profile->GetRequestContext(), identity_manager); } bool LocalDiscoveryUIHandler::IsUserSupervisedOrOffTheRecord() { diff --git a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h index 29baef1168a..cca4463919c 100644 --- a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h @@ -14,9 +14,9 @@ #include "chrome/browser/printing/cloud_print/cloud_print_printer_list.h" #include "chrome/browser/printing/cloud_print/privet_device_lister.h" #include "chrome/browser/printing/cloud_print/privet_http.h" -#include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/web_ui_message_handler.h" #include "printing/buildflags/buildflags.h" +#include "services/identity/public/cpp/identity_manager.h" #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS) #define CLOUD_PRINT_CONNECTOR_UI_AVAILABLE @@ -43,7 +43,7 @@ class LocalDiscoveryUIHandler public cloud_print::PrivetRegisterOperation::Delegate, public cloud_print::PrivetDeviceLister::Delegate, public cloud_print::CloudPrintPrinterList::Delegate, - public SigninManagerBase::Observer { + public identity::IdentityManager::Observer { public: LocalDiscoveryUIHandler(); ~LocalDiscoveryUIHandler() override; @@ -78,11 +78,10 @@ class LocalDiscoveryUIHandler const cloud_print::CloudPrintPrinterList::DeviceList& devices) override; void OnDeviceListUnavailable() override; - // SigninManagerBase::Observer implementation. - void GoogleSigninSucceeded(const std::string& account_id, - const std::string& username) override; - void GoogleSignedOut(const std::string& account_id, - const std::string& username) override; + // identity::IdentityManager::Observer implementation. + void OnPrimaryAccountSet(const AccountInfo& primary_account_info) override; + void OnPrimaryAccountCleared( + const AccountInfo& previous_primary_account_info) override; private: using DeviceDescriptionMap = diff --git a/chromium/chrome/browser/ui/webui/log_web_ui_url_browsertest.cc b/chromium/chrome/browser/ui/webui/log_web_ui_url_browsertest.cc index 386eaa68968..47835d2bbe6 100644 --- a/chromium/chrome/browser/ui/webui/log_web_ui_url_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/log_web_ui_url_browsertest.cc @@ -10,7 +10,7 @@ #include "base/hash.h" #include "base/macros.h" -#include "base/test/histogram_tester.h" +#include "base/test/metrics/histogram_tester.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" diff --git a/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc b/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc index ca694958bb6..06195fc97ab 100644 --- a/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc +++ b/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc @@ -38,8 +38,6 @@ void AddLocalizedString(content::WebUIDataSource* source, content::WebUIDataSource* CreateMdBookmarksUIHTMLSource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIBookmarksHost); - source->OverrideContentSecurityPolicyScriptSrc( - "script-src chrome://resources 'self';"); // Localized strings (alphabetical order). AddLocalizedString(source, "addBookmarkTitle", diff --git a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc index b6e37fc3e92..e67023efae2 100644 --- a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc +++ b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc @@ -37,6 +37,9 @@ #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_manager.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/render_view_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" @@ -61,6 +64,7 @@ enum DownloadsDOMEvent { DOWNLOADS_DOM_EVENT_CLEAR_ALL = 9, DOWNLOADS_DOM_EVENT_OPEN_FOLDER = 10, DOWNLOADS_DOM_EVENT_RESUME = 11, + DOWNLOADS_DOM_EVENT_RETRY_DOWNLOAD = 12, DOWNLOADS_DOM_EVENT_MAX }; @@ -105,6 +109,10 @@ void MdDownloadsDOMHandler::RegisterMessages() { base::BindRepeating(&MdDownloadsDOMHandler::HandleSaveDangerous, weak_ptr_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( + "retryDownload", + base::BindRepeating(&MdDownloadsDOMHandler::HandleRetryDownload, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( "discardDangerous", base::BindRepeating(&MdDownloadsDOMHandler::HandleDiscardDangerous, weak_ptr_factory_.GetWeakPtr())); @@ -201,6 +209,11 @@ void MdDownloadsDOMHandler::HandleSaveDangerous(const base::ListValue* args) { ShowDangerPrompt(file); } +void MdDownloadsDOMHandler::HandleRetryDownload(const base::ListValue* args) { + CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_RETRY_DOWNLOAD); + RetryDownload(args); +} + void MdDownloadsDOMHandler::HandleDiscardDangerous( const base::ListValue* args) { CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DISCARD_DANGEROUS); @@ -438,3 +451,49 @@ void MdDownloadsDOMHandler::RemoveDownloadInArgs(const base::ListValue* args) { downloads.push_back(file); RemoveDownloads(downloads); } + +void MdDownloadsDOMHandler::RetryDownload(const base::ListValue* args) { + download::DownloadItem* file = GetDownloadByValue(args); + if (!file) + return; + content::WebContents* web_contents = GetWebUIWebContents(); + content::RenderFrameHost* render_frame_host = web_contents->GetMainFrame(); + const GURL url = file->GetURL(); + + content::StoragePartition* storage_partition = + content::BrowserContext::GetStoragePartition( + web_contents->GetBrowserContext(), + render_frame_host->GetSiteInstance()); + + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("md_downloads_dom_handler", R"( + semantics { + sender: "The downloads page." + description: "Retrying a download." + trigger: + "The user selects the 'Retry' button for a cancelled download on " + "the downloads page." + data: "None." + destination: WEBSITE + } + policy { + cookies_allowed: YES + cookies_store: "user" + setting: + "This feature cannot be disabled by settings, but it's only " + "triggered by user request." + policy_exception_justification: "Not implemented." + })"); + + auto dl_params = std::make_unique<download::DownloadUrlParameters>( + url, render_frame_host->GetProcess()->GetID(), + render_frame_host->GetRenderViewHost()->GetRoutingID(), + render_frame_host->GetRoutingID(), + storage_partition->GetURLRequestContext(), traffic_annotation); + dl_params->set_content_initiated(true); + dl_params->set_initiator(url::Origin::Create(GURL("chrome://downloads"))); + dl_params->set_download_source(download::DownloadSource::FROM_RENDERER); + + content::BrowserContext::GetDownloadManager(web_contents->GetBrowserContext()) + ->DownloadUrl(std::move(dl_params)); +} diff --git a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.h b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.h index cdfc1342bb3..5b3c41d4f3e 100644 --- a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.h +++ b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.h @@ -60,6 +60,10 @@ class MdDownloadsDOMHandler : public content::WebContentsObserver, // wishes to save a dangerous file. void HandleSaveDangerous(const base::ListValue* args); + // Callback for the "retryDownload" message - specifies that the user wishes + // to download an item again. + void HandleRetryDownload(const base::ListValue* args); + // Callback for the "discardDangerous" message - specifies that the user // wishes to discard (remove) a dangerous file. void HandleDiscardDangerous(const base::ListValue* args); @@ -141,6 +145,9 @@ class MdDownloadsDOMHandler : public content::WebContentsObserver, // Removes the download specified by an ID from JavaScript in |args|. void RemoveDownloadInArgs(const base::ListValue* args); + // Retry the download specified by an ID from JavaScript in |args|. + void RetryDownload(const base::ListValue* args); + // Checks whether a download's file was removed from its original location. void CheckForRemovedFiles(); diff --git a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc index 24b156b5a91..e3938ed4ed6 100644 --- a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc +++ b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc @@ -41,8 +41,6 @@ namespace { content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIDownloadsHost); - source->OverrideContentSecurityPolicyScriptSrc( - "script-src chrome://resources 'self';"); source->AddLocalizedString("title", IDS_DOWNLOAD_TITLE); source->AddLocalizedString("searchResultsFor", IDS_SEARCH_RESULTS); diff --git a/chromium/chrome/browser/ui/webui/md_history_ui.cc b/chromium/chrome/browser/ui/webui/md_history_ui.cc index 3ea15760f4f..de8af30aaad 100644 --- a/chromium/chrome/browser/ui/webui/md_history_ui.cc +++ b/chromium/chrome/browser/ui/webui/md_history_ui.cc @@ -15,7 +15,7 @@ #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/webui/browsing_history_handler.h" #include "chrome/browser/ui/webui/foreign_session_handler.h" #include "chrome/browser/ui/webui/history_login_handler.h" @@ -27,10 +27,10 @@ #include "chrome/grit/locale_settings.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_manager.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/identity/public/cpp/identity_manager.h" #include "ui/base/l10n/l10n_util.h" namespace { @@ -39,9 +39,9 @@ constexpr char kIsUserSignedInKey[] = "isUserSignedIn"; constexpr char kShowMenuPromoKey[] = "showMenuPromo"; bool IsUserSignedIn(Profile* profile) { - SigninManagerBase* signin_manager = - SigninManagerFactory::GetForProfile(profile); - return signin_manager && signin_manager->IsAuthenticated(); + identity::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile(profile); + return identity_manager && identity_manager->HasPrimaryAccount(); } bool MenuPromoShown(Profile* profile) { @@ -52,8 +52,6 @@ content::WebUIDataSource* CreateMdHistoryUIHTMLSource(Profile* profile, bool use_test_title) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIHistoryHost); - source->OverrideContentSecurityPolicyScriptSrc( - "script-src chrome://resources 'self';"); // Localized strings (alphabetical order). source->AddLocalizedString("bookmarked", IDS_HISTORY_ENTRY_BOOKMARKED); diff --git a/chromium/chrome/browser/ui/webui/media_router/OWNERS b/chromium/chrome/browser/ui/webui/media_router/OWNERS index 2d837dee815..fda51ea2bfc 100644 --- a/chromium/chrome/browser/ui/webui/media_router/OWNERS +++ b/chromium/chrome/browser/ui/webui/media_router/OWNERS @@ -1,5 +1,3 @@ -amp@chromium.org -imcheng@chromium.org -mfoltz@chromium.org +file://chrome/browser/media/router/OWNERS # COMPONENT: Internals>Cast>UI diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc index 95425a5989d..d49923de6a1 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc @@ -16,7 +16,6 @@ #include "base/trace_event/trace_event.h" #include "build/build_config.h" #include "chrome/browser/media/router/issue_manager.h" -#include "chrome/browser/media/router/issues_observer.h" #include "chrome/browser/media/router/media_router.h" #include "chrome/browser/media/router/media_router_factory.h" #include "chrome/browser/media/router/media_router_metrics.h" @@ -63,135 +62,6 @@ namespace media_router { -// This class calls to refresh the UI when the highest priority issue is -// updated. -class MediaRouterUI::UIIssuesObserver : public IssuesObserver { - public: - UIIssuesObserver(IssueManager* issue_manager, MediaRouterUI* ui) - : IssuesObserver(issue_manager), ui_(ui) { - DCHECK(ui); - } - - ~UIIssuesObserver() override {} - - // IssuesObserver implementation. - void OnIssue(const Issue& issue) override { ui_->SetIssue(issue); } - void OnIssuesCleared() override { ui_->ClearIssue(); } - - private: - // Reference back to the owning MediaRouterUI instance. - MediaRouterUI* ui_; - - DISALLOW_COPY_AND_ASSIGN(UIIssuesObserver); -}; - -// Observes a WebContents and requests fullscreening of its first -// video element. The request is sent after the WebContents is loaded and tab -// capture has begun. Marked final to prevent inheritance so delete calls are -// contained to scenarios documented below. -class MediaRouterUI::WebContentsFullscreenOnLoadedObserver final - : public content::WebContentsObserver { - public: - WebContentsFullscreenOnLoadedObserver(const GURL& file_url, - content::WebContents* web_contents) - : file_url_(file_url), capture_poll_timer_(false, false) { - DCHECK(file_url_.SchemeIsFile()); - DCHECK(fullscreen_request_time_.is_null()); - - // If the WebContents is loading, start listening, otherwise just call the - // fullscreen function. - - // This class destroys itself in the following situations (at least one of - // which will occur): - // * after loading is complete and, - // ** capture has begun and fullscreen requested, - // ** kMaxSecondsToWaitForCapture seconds have passed without capture, - // * another navigation is started, - // * the WebContents is destroyed. - if (web_contents->IsLoading()) { - Observe(web_contents); - } else { - FullScreenFirstVideoElement(web_contents); - } - } - ~WebContentsFullscreenOnLoadedObserver() override {} - - // content::WebContentsObserver implementation. - void DidStopLoading() override { - FullScreenFirstVideoElement(web_contents()); - } - - void DidStartNavigation( - content::NavigationHandle* navigation_handle) override { - // If the user takes over and navigates away from the file, stop listening. - // (It is possible however for this listener to be created before the - // navigation to the requested file triggers, so provided we're still on the - // same URL, go ahead and keep listening). - if (file_url_ != navigation_handle->GetURL()) { - delete this; - } - } - - void WebContentsDestroyed() override { - // If the WebContents is destroyed we will never trigger and need to clean - // up. - delete this; - } - - private: - const GURL file_url_; - - // Time intervals used by the logic that detects if capture has started. - const int kMaxSecondsToWaitForCapture = 10; - const int kPollIntervalInSeconds = 1; - - // The time at which fullscreen was requested. - base::TimeTicks fullscreen_request_time_; - - // Poll timer to monitor the capturer count when fullscreening local files. - // - // TODO(crbug.com/540965): Add a method to WebContentsObserver to report - // capturer count changes and get rid of this polling-based approach. - base::Timer capture_poll_timer_; - - // Sends a request for full screen to the WebContents targeted at the first - // video element. The request is only sent after capture has begun. - void FullScreenFirstVideoElement(content::WebContents* web_contents) { - if (file_url_ != web_contents->GetLastCommittedURL()) { - // The user has navigated before the casting started. Do not attempt to - // fullscreen and cleanup. - return; - } - - fullscreen_request_time_ = base::TimeTicks::Now(); - FullscreenIfContentCaptured(web_contents); - } - - void FullscreenIfContentCaptured(content::WebContents* web_contents) { - if (web_contents->IsBeingCaptured()) { - content::mojom::FullscreenVideoElementHandlerAssociatedPtr client; - web_contents->GetMainFrame() - ->GetRemoteAssociatedInterfaces() - ->GetInterface(&client); - client->RequestFullscreenVideoElement(); - delete this; - return; - } else if (base::TimeTicks::Now() - fullscreen_request_time_ > - base::TimeDelta::FromSeconds(kMaxSecondsToWaitForCapture)) { - // If content capture hasn't started within the timeout skip fullscreen. - DLOG(WARNING) << "Capture of local content did not start within timeout"; - delete this; - return; - } - - capture_poll_timer_.Start( - FROM_HERE, base::TimeDelta::FromSeconds(kPollIntervalInSeconds), - base::BindRepeating( - &WebContentsFullscreenOnLoadedObserver::FullscreenIfContentCaptured, - base::Unretained(this), web_contents)); - } -}; - MediaRouterUI::MediaRouterUI(content::WebUI* web_ui) : ConstrainedWebDialogUI(web_ui), ui_initialized_(false), @@ -231,36 +101,7 @@ void MediaRouterUI::OnUIInitialized() { // TODO(imcheng): We should be able to instantiate |issue_observer_| during // InitCommon by storing an initial Issue in this class. // Register for Issue updates. - issues_observer_ = - std::make_unique<UIIssuesObserver>(GetIssueManager(), this); - issues_observer_->Init(); -} - -bool MediaRouterUI::CreateRoute(const MediaSink::Id& sink_id, - MediaCastMode cast_mode) { - // Default the tab casting the content to the initiator, and change if - // necessary. - content::WebContents* tab_contents = initiator(); - - base::Optional<RouteParameters> params; - if (cast_mode == MediaCastMode::LOCAL_FILE) { - GURL url = media_router_file_dialog_->GetLastSelectedFileUrl(); - tab_contents = OpenTabWithUrl(url); - params = GetLocalFileRouteParameters(sink_id, url, tab_contents); - } else { - params = GetRouteParameters(sink_id, cast_mode); - } - if (!params) { - SendIssueForUnableToCast(cast_mode); - return false; - } - - GetIssueManager()->ClearNonBlockingIssues(); - GetMediaRouter()->CreateRoute(params->source_id, sink_id, params->origin, - tab_contents, - std::move(params->route_response_callbacks), - params->timeout, params->incognito); - return true; + StartObservingIssues(); } bool MediaRouterUI::ConnectRoute(const MediaSink::Id& sink_id, @@ -279,22 +120,6 @@ bool MediaRouterUI::ConnectRoute(const MediaSink::Id& sink_id, return true; } -void MediaRouterUI::AddIssue(const IssueInfo& issue) { - GetIssueManager()->AddIssue(issue); -} - -void MediaRouterUI::ClearIssue(const Issue::Id& issue_id) { - GetIssueManager()->ClearIssue(issue_id); -} - -void MediaRouterUI::OpenFileDialog() { - if (!media_router_file_dialog_) { - media_router_file_dialog_ = std::make_unique<MediaRouterFileDialog>(this); - } - - media_router_file_dialog_->OpenFileDialog(GetBrowser()); -} - void MediaRouterUI::SearchSinksAndCreateRoute( const MediaSink::Id& sink_id, const std::string& search_criteria, @@ -427,7 +252,7 @@ void MediaRouterUI::InitForTest( void MediaRouterUI::InitForTest( std::unique_ptr<MediaRouterFileDialog> file_dialog) { - media_router_file_dialog_ = std::move(file_dialog); + set_media_router_file_dialog_for_test(std::move(file_dialog)); } MediaRouterUI::UIMediaRouteControllerObserver::UIMediaRouteControllerObserver( @@ -450,40 +275,17 @@ void MediaRouterUI::UIMediaRouteControllerObserver::OnControllerInvalidated() { ui_->OnRouteControllerInvalidated(); } -Browser* MediaRouterUI::GetBrowser() { - CHECK(initiator()); - return chrome::FindBrowserWithWebContents(initiator()); -} - -content::WebContents* MediaRouterUI::OpenTabWithUrl(const GURL url) { - // Check if the current page is a new tab. If so open file in current page. - // If not then open a new page. - if (initiator()->GetVisibleURL() == chrome::kChromeUINewTabURL) { - content::NavigationController::LoadURLParams load_params(url); - load_params.transition_type = ui::PAGE_TRANSITION_GENERATED; - initiator()->GetController().LoadURLWithParams(load_params); - return initiator(); - } else { - return chrome::AddSelectedTabWithURL(GetBrowser(), url, - ui::PAGE_TRANSITION_LINK); - } -} - void MediaRouterUI::FileDialogFileSelected( const ui::SelectedFileInfo& file_info) { handler_->UserSelectedLocalMediaFile(file_info.display_name); } -void MediaRouterUI::FileDialogSelectionFailed(const IssueInfo& issue) { - AddIssue(issue); -} - -void MediaRouterUI::SetIssue(const Issue& issue) { +void MediaRouterUI::OnIssue(const Issue& issue) { if (ui_initialized_) handler_->UpdateIssue(issue); } -void MediaRouterUI::ClearIssue() { +void MediaRouterUI::OnIssueCleared() { if (ui_initialized_) handler_->ClearIssue(); } @@ -522,12 +324,6 @@ void MediaRouterUI::OnRouteResponseReceived( SendIssueForRouteTimeout(cast_mode, presentation_request_source_name); } -void MediaRouterUI::MaybeReportFileInformation( - const RouteRequestResult& result) { - if (result.result_code() == RouteRequestResult::OK) - media_router_file_dialog_->MaybeReportLastSelectedFileInformation(); -} - void MediaRouterUI::HandleCreateSessionRequestRouteResponse( const RouteRequestResult&) { Close(); @@ -540,47 +336,7 @@ void MediaRouterUI::OnSearchSinkResponseReceived( handler_->ReturnSearchResult(found_sink_id); CreateRoute(found_sink_id, cast_mode); -} - -void MediaRouterUI::SendIssueForRouteTimeout( - MediaCastMode cast_mode, - const base::string16& presentation_request_source_name) { - std::string issue_title; - switch (cast_mode) { - case PRESENTATION: - DLOG_IF(ERROR, presentation_request_source_name.empty()) - << "Empty presentation request source name."; - issue_title = - l10n_util::GetStringFUTF8(IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT, - presentation_request_source_name); - break; - case TAB_MIRROR: - issue_title = l10n_util::GetStringUTF8( - IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT_FOR_TAB); - break; - case DESKTOP_MIRROR: - issue_title = l10n_util::GetStringUTF8( - IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT_FOR_DESKTOP); - break; - default: - NOTREACHED(); - } - - AddIssue(IssueInfo(issue_title, IssueInfo::Action::DISMISS, - IssueInfo::Severity::NOTIFICATION)); -} - -void MediaRouterUI::SendIssueForUnableToCast(MediaCastMode cast_mode) { - // For a generic error, claim a tab error unless it was specifically desktop - // mirroring. - std::string issue_title = - (cast_mode == MediaCastMode::DESKTOP_MIRROR) - ? l10n_util::GetStringUTF8( - IDS_MEDIA_ROUTER_ISSUE_UNABLE_TO_CAST_DESKTOP) - : l10n_util::GetStringUTF8( - IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT_FOR_TAB); - AddIssue(IssueInfo(issue_title, IssueInfo::Action::DISMISS, - IssueInfo::Severity::WARNING)); + MediaRouterMetrics::RecordSearchSinkOutcome(!found_sink_id.empty()); } void MediaRouterUI::InitCommon(content::WebContents* initiator) { @@ -608,53 +364,6 @@ void MediaRouterUI::OnDefaultPresentationRemoved() { UpdateCastModes(); } -base::Optional<RouteParameters> MediaRouterUI::GetLocalFileRouteParameters( - const MediaSink::Id& sink_id, - const GURL& file_url, - content::WebContents* tab_contents) { - RouteParameters params; - SessionID::id_type tab_id = SessionTabHelper::IdForTab(tab_contents).id(); - params.source_id = MediaSourceForTab(tab_id).id(); - - // Use a placeholder URL as origin for local file casting, which is - // essentially mirroring. - params.origin = url::Origin::Create(GURL(chrome::kChromeUIMediaRouterURL)); - - params.route_response_callbacks.push_back(base::BindOnce( - &MediaRouterUI::OnRouteResponseReceived, weak_factory_.GetWeakPtr(), - current_route_request_id(), sink_id, MediaCastMode::LOCAL_FILE, - base::UTF8ToUTF16(GetTruncatedPresentationRequestSourceName()))); - - params.route_response_callbacks.push_back( - base::BindOnce(&MediaRouterUIBase::MaybeReportCastingSource, - weak_factory_.GetWeakPtr(), MediaCastMode::LOCAL_FILE)); - - params.route_response_callbacks.push_back(base::BindOnce( - &MediaRouterUI::MaybeReportFileInformation, weak_factory_.GetWeakPtr())); - - params.route_response_callbacks.push_back( - base::BindOnce(&MediaRouterUI::FullScreenFirstVideoElement, - weak_factory_.GetWeakPtr(), file_url, tab_contents)); - - params.timeout = GetRouteRequestTimeout(MediaCastMode::LOCAL_FILE); - CHECK(initiator()); - params.incognito = initiator()->GetBrowserContext()->IsOffTheRecord(); - - return base::make_optional(std::move(params)); -} - -// TODO(crbug.com/792547): Refactor FullScreenFirstVideoElement() and -// MaybeReportFileInformation() into a local media casting specific location -// instead of here in the main ui. -void MediaRouterUI::FullScreenFirstVideoElement( - const GURL& file_url, - content::WebContents* web_contents, - const RouteRequestResult& result) { - if (result.result_code() == RouteRequestResult::OK) { - new WebContentsFullscreenOnLoadedObserver(file_url, web_contents); - } -} - void MediaRouterUI::UpdateCastModes() { // Gets updated cast modes from |query_result_manager()| and forwards it to // UI. @@ -697,10 +406,6 @@ void MediaRouterUI::UpdateMediaRouteStatus(const MediaStatus& status) { handler_->UpdateMediaRouteStatus(status); } -IssueManager* MediaRouterUI::GetIssueManager() { - return GetMediaRouter()->GetIssueManager(); -} - void MediaRouterUI::UpdateSinks() { if (ui_initialized_) handler_->UpdateSinks(GetEnabledSinks()); diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h index 5c75e2dc411..acf5fe70e64 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h @@ -9,30 +9,19 @@ #include "base/strings/string16.h" #include "chrome/browser/media/router/mojo/media_route_controller.h" #include "chrome/browser/ui/media_router/media_cast_mode.h" -#include "chrome/browser/ui/media_router/media_router_file_dialog.h" #include "chrome/browser/ui/media_router/media_router_ui_base.h" #include "chrome/browser/ui/webui/constrained_web_dialog_ui.h" #include "chrome/common/media_router/media_route.h" #include "chrome/common/media_router/media_sink.h" -namespace ui { -struct SelectedFileInfo; -} - namespace media_router { struct MediaStatus; -class Issue; -class IssueManager; -class IssuesObserver; class MediaRouterWebUIMessageHandler; class RouteRequestResult; // Functions as an intermediary between MediaRouter and WebUI Cast dialog. -class MediaRouterUI - : public MediaRouterUIBase, - public ConstrainedWebDialogUI, - public MediaRouterFileDialog::MediaRouterFileDialogDelegate { +class MediaRouterUI : public MediaRouterUIBase, public ConstrainedWebDialogUI { public: // |web_ui| owns this object and is used to initialize the base class. explicit MediaRouterUI(content::WebUI* web_ui); @@ -44,23 +33,10 @@ class MediaRouterUI // Notifies this instance that the UI has been initialized. virtual void OnUIInitialized(); - // MediaRouterUIBase: - bool CreateRoute(const MediaSink::Id& sink_id, - MediaCastMode cast_mode) override; - // Calls MediaRouter to join the given route. bool ConnectRoute(const MediaSink::Id& sink_id, const MediaRoute::Id& route_id); - // Calls MediaRouter to add the given issue. - void AddIssue(const IssueInfo& issue); - - // Calls MediaRouter to clear the given issue. - void ClearIssue(const Issue::Id& issue_id); - - // Called to open a file dialog with the media_router_ui file dialog handler. - void OpenFileDialog(); - // Calls MediaRouter to search route providers for sinks matching // |search_criteria| with the source that is currently associated with // |cast_mode|. The user's domain |domain| is also used. @@ -80,7 +56,7 @@ class MediaRouterUI // Returns the hostname of the PresentationRequest's parent frame URL. virtual std::string GetPresentationRequestSourceName() const; bool HasPendingRouteRequest() const { - return current_route_request_id() != -1; + return current_route_request().has_value(); } const std::vector<MediaRoute::Id>& joinable_route_ids() const { return joinable_route_ids_; @@ -149,7 +125,6 @@ class MediaRouterUI UpdateSinksWhenDialogMovesToAnotherDisplay); class UIIssuesObserver; - class WebContentsFullscreenOnLoadedObserver; class UIMediaRouteControllerObserver : public MediaRouteController::Observer { public: @@ -168,21 +143,11 @@ class MediaRouterUI DISALLOW_COPY_AND_ASSIGN(UIMediaRouteControllerObserver); }; - // Retrieves the browser associated with this UI. - Browser* GetBrowser(); - - // Opens the URL in a tab, returns the tab it was opened in. - content::WebContents* OpenTabWithUrl(const GURL url); - // MediaRouterFileDialogDelegate: void FileDialogFileSelected(const ui::SelectedFileInfo& file_info) override; - void FileDialogSelectionFailed(const IssueInfo& issue) override; - // Called by |issues_observer_| when the top issue has changed. - // If the UI is already initialized, notifies |handler_| to update the UI. - // Ignored if the UI is not yet initialized. - void SetIssue(const Issue& issue); - void ClearIssue(); + void OnIssue(const Issue& issue) override; + void OnIssueCleared() override; void OnRoutesUpdated( const std::vector<MediaRoute>& routes, @@ -195,10 +160,6 @@ class MediaRouterUI const base::string16& presentation_request_source_name, const RouteRequestResult& result) override; - // Sends a request to the file dialog to log UMA stats for the file that was - // cast if the result is successful. - void MaybeReportFileInformation(const RouteRequestResult& result); - void HandleCreateSessionRequestRouteResponse( const RouteRequestResult&) override; @@ -207,14 +168,6 @@ class MediaRouterUI void OnSearchSinkResponseReceived(MediaCastMode cast_mode, const MediaSink::Id& found_sink_id); - // Creates and sends an issue if route creation timed out. - void SendIssueForRouteTimeout( - MediaCastMode cast_mode, - const base::string16& presentation_request_source_name); - - // Creates and sends an issue if casting fails for any other reason. - void SendIssueForUnableToCast(MediaCastMode cast_mode); - void InitCommon(content::WebContents* initiator) override; // PresentationServiceDelegateImpl::DefaultPresentationObserver: @@ -222,17 +175,6 @@ class MediaRouterUI const content::PresentationRequest& presentation_request) override; void OnDefaultPresentationRemoved() override; - // Populates route-related parameters for CreateRoute() when doing file - // casting. - base::Optional<RouteParameters> GetLocalFileRouteParameters( - const MediaSink::Id& sink_id, - const GURL& file_url, - content::WebContents* tab_contents); - - void FullScreenFirstVideoElement(const GURL& file_url, - content::WebContents* web_contents, - const RouteRequestResult& result); - // Updates the set of supported cast modes and sends the updated set to // |handler_|. void UpdateCastModes(); @@ -253,9 +195,6 @@ class MediaRouterUI // handler of a media status update for the route currently shown in the UI. void UpdateMediaRouteStatus(const MediaStatus& status); - // Returns the IssueManager associated with |router_|. - IssueManager* GetIssueManager(); - void UpdateSinks() override; MediaRouter* GetMediaRouter() const override; @@ -264,8 +203,6 @@ class MediaRouterUI // only after it has deleted |this|. MediaRouterWebUIMessageHandler* handler_ = nullptr; - std::unique_ptr<IssuesObserver> issues_observer_; - // Set to true by |handler_| when the UI has been initialized. bool ui_initialized_; @@ -281,10 +218,6 @@ class MediaRouterUI // updates. std::unique_ptr<UIMediaRouteControllerObserver> route_controller_observer_; - // The dialog that handles opening the file dialog and validating and - // returning the results. - std::unique_ptr<MediaRouterFileDialog> media_router_file_dialog_; - // If set, a cast mode that is required to be shown first. base::Optional<MediaCastMode> forced_cast_mode_; diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service.cc index 99597ff78cb..1726d12f796 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service.cc @@ -7,16 +7,33 @@ #include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h" +#include "chrome/common/pref_names.h" +#include "components/prefs/pref_change_registrar.h" +#include "components/user_prefs/user_prefs.h" namespace media_router { MediaRouterUIService::MediaRouterUIService(Profile* profile) - : action_controller_(new MediaRouterActionController(profile)) {} + : MediaRouterUIService(profile, nullptr) {} + +MediaRouterUIService::MediaRouterUIService( + Profile* profile, + std::unique_ptr<MediaRouterActionController> action_controller) + : profile_(profile), + action_controller_(std::move(action_controller)), + profile_pref_registrar_(std::make_unique<PrefChangeRegistrar>()) { + profile_pref_registrar_->Init(profile->GetPrefs()); + profile_pref_registrar_->Add( + ::prefs::kEnableMediaRouter, + base::BindRepeating(&MediaRouterUIService::ConfigureService, + base::Unretained(this))); + ConfigureService(); +} MediaRouterUIService::~MediaRouterUIService() {} void MediaRouterUIService::Shutdown() { - action_controller_.reset(); + DisableService(); } // static @@ -28,4 +45,27 @@ MediaRouterActionController* MediaRouterUIService::action_controller() { return action_controller_.get(); } +void MediaRouterUIService::AddObserver(Observer* observer) { + observers_.AddObserver(observer); +} + +void MediaRouterUIService::RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); +} + +void MediaRouterUIService::ConfigureService() { + if (!MediaRouterEnabled(profile_)) { + DisableService(); + } else if (!action_controller_ && MediaRouterEnabled(profile_)) { + action_controller_ = + std::make_unique<MediaRouterActionController>(profile_); + } +} + +void MediaRouterUIService::DisableService() { + for (auto& observer : observers_) + observer.OnServiceDisabled(); + action_controller_.reset(); +} + } // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service.h b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service.h index 5a4c3338f5c..313be0e33f6 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service.h +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service.h @@ -6,9 +6,11 @@ #include <memory> +#include "base/observer_list.h" #include "chrome/browser/ui/toolbar/media_router_action_controller.h" #include "components/keyed_service/core/keyed_service.h" +class PrefChangeRegistrar; class Profile; namespace media_router { @@ -17,7 +19,16 @@ namespace media_router { // for the Media Router toolbar action. class MediaRouterUIService : public KeyedService { public: + class Observer { + public: + virtual void OnServiceDisabled() = 0; + }; + explicit MediaRouterUIService(Profile* profile); + // Used by tests to inject an action controller. + MediaRouterUIService( + Profile* profile, + std::unique_ptr<MediaRouterActionController> action_controller); ~MediaRouterUIService() override; // KeyedService: @@ -27,10 +38,20 @@ class MediaRouterUIService : public KeyedService { virtual MediaRouterActionController* action_controller(); + void AddObserver(Observer* observer); + void RemoveObserver(Observer* observer); + private: friend class MediaRouterUIBrowserTest; + void ConfigureService(); + void DisableService(); + + Profile* profile_; std::unique_ptr<MediaRouterActionController> action_controller_; + std::unique_ptr<PrefChangeRegistrar> profile_pref_registrar_; + + base::ObserverList<Observer> observers_; DISALLOW_COPY_AND_ASSIGN(MediaRouterUIService); }; diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.cc index bcd926cb963..98c0f0eeb07 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.cc @@ -5,7 +5,6 @@ #include "chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h" #include "chrome/browser/media/router/media_router_factory.h" -#include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/toolbar/toolbar_actions_model_factory.h" #include "chrome/browser/ui/webui/media_router/media_router_ui_service.h" @@ -47,9 +46,7 @@ BrowserContext* MediaRouterUIServiceFactory::GetBrowserContextToUse( KeyedService* MediaRouterUIServiceFactory::BuildServiceInstanceFor( BrowserContext* context) const { - return MediaRouterEnabled(context) - ? new MediaRouterUIService(Profile::FromBrowserContext(context)) - : nullptr; + return new MediaRouterUIService(Profile::FromBrowserContext(context)); } bool MediaRouterUIServiceFactory::ServiceIsCreatedWithBrowserContext() const { diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h index b5328f5a491..10d57611301 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory.h @@ -28,7 +28,9 @@ class MediaRouterUIServiceFactory : public BrowserContextKeyedServiceFactory { friend struct base::DefaultSingletonTraits<MediaRouterUIServiceFactory>; FRIEND_TEST_ALL_PREFIXES(MediaRouterUIServiceFactoryUnitTest, CreateService); FRIEND_TEST_ALL_PREFIXES(MediaRouterUIServiceFactoryUnitTest, - DoNotCreateServiceWhenDisabled); + DoNotCreateActionControllerWhenDisabled); + FRIEND_TEST_ALL_PREFIXES(MediaRouterUIServiceFactoryUnitTest, + DisablingMediaRouting); MediaRouterUIServiceFactory(); ~MediaRouterUIServiceFactory() override; diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory_unittest.cc index f66afd74352..22005542e82 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory_unittest.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_service_factory_unittest.cc @@ -16,8 +16,19 @@ #include "chrome/test/base/testing_profile.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/test_browser_thread_bundle.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +namespace { + +class MockMediaRouterUIServiceObserver + : public media_router::MediaRouterUIService::Observer { + public: + MOCK_METHOD0(OnServiceDisabled, void()); +}; + +} // namespace + namespace media_router { class MediaRouterUIServiceFactoryUnitTest : public testing::Test { @@ -59,12 +70,34 @@ TEST_F(MediaRouterUIServiceFactoryUnitTest, CreateService) { ASSERT_TRUE(service->action_controller()); } -TEST_F(MediaRouterUIServiceFactoryUnitTest, DoNotCreateServiceWhenDisabled) { +TEST_F(MediaRouterUIServiceFactoryUnitTest, + DoNotCreateActionControllerWhenDisabled) { + profile_->GetTestingPrefService()->SetManagedPref( + prefs::kEnableMediaRouter, std::make_unique<base::Value>(false)); + std::unique_ptr<MediaRouterUIService> service( + static_cast<MediaRouterUIService*>( + MediaRouterUIServiceFactory::GetInstance()->BuildServiceInstanceFor( + profile_.get()))); + ASSERT_TRUE(service); + EXPECT_EQ(nullptr, service->action_controller()); +} + +TEST_F(MediaRouterUIServiceFactoryUnitTest, DisablingMediaRouting) { + std::unique_ptr<MediaRouterUIService> service( + static_cast<MediaRouterUIService*>( + MediaRouterUIServiceFactory::GetInstance()->BuildServiceInstanceFor( + profile_.get()))); + ASSERT_TRUE(service); + ASSERT_TRUE(service->action_controller()); + + MockMediaRouterUIServiceObserver mock_observer; + service->AddObserver(&mock_observer); + EXPECT_CALL(mock_observer, OnServiceDisabled).Times(testing::Exactly(1)); + profile_->GetTestingPrefService()->SetManagedPref( prefs::kEnableMediaRouter, std::make_unique<base::Value>(false)); - EXPECT_EQ(nullptr, - MediaRouterUIServiceFactory::GetInstance()->BuildServiceInstanceFor( - profile_.get())); + EXPECT_EQ(nullptr, service->action_controller()); + service->RemoveObserver(&mock_observer); } } // namespace media_router diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc index 0a5bb0b2885..c3e43a9ef84 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc @@ -19,7 +19,7 @@ #include "base/values.h" #include "chrome/browser/media/router/media_router_metrics.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/webui/media_router/media_router_ui.h" #include "chrome/common/chrome_features.h" @@ -28,9 +28,9 @@ #include "components/browser_sync/profile_sync_service.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/web_ui.h" #include "extensions/common/constants.h" +#include "services/identity/public/cpp/identity_manager.h" #include "ui/base/l10n/l10n_util.h" namespace media_router { @@ -610,7 +610,7 @@ void MediaRouterWebUIMessageHandler::OnAcknowledgeFirstRunFlow( const base::ListValue* args) { DVLOG(1) << "OnAcknowledgeFirstRunFlow"; Profile::FromWebUI(web_ui())->GetPrefs()->SetBoolean( - prefs::kMediaRouterFirstRunFlowAcknowledged, true); + ::prefs::kMediaRouterFirstRunFlowAcknowledged, true); bool enabled_cloud_services = false; // Do not set the relevant cloud services prefs if the user was not shown @@ -621,9 +621,9 @@ void MediaRouterWebUIMessageHandler::OnAcknowledgeFirstRunFlow( } PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs(); - pref_service->SetBoolean(prefs::kMediaRouterEnableCloudServices, + pref_service->SetBoolean(::prefs::kMediaRouterEnableCloudServices, enabled_cloud_services); - pref_service->SetBoolean(prefs::kMediaRouterCloudServicesPrefSet, true); + pref_service->SetBoolean(::prefs::kMediaRouterCloudServicesPrefSet, true); } void MediaRouterWebUIMessageHandler::OnActOnIssue(const base::ListValue* args) { @@ -645,7 +645,7 @@ void MediaRouterWebUIMessageHandler::OnActOnIssue(const base::ListValue* args) { static_cast<IssueInfo::Action>(action_type_num); if (ActOnIssueType(action_type, args_dict)) DVLOG(1) << "ActOnIssueType failed for Issue ID " << issue_id; - media_router_ui_->ClearIssue(issue_id); + media_router_ui_->RemoveIssue(issue_id); } void MediaRouterWebUIMessageHandler::OnJoinRoute(const base::ListValue* args) { @@ -737,8 +737,7 @@ void MediaRouterWebUIMessageHandler::OnReportClickedSinkIndex( DVLOG(1) << "Unable to extract args."; return; } - base::UmaHistogramSparse("MediaRouter.Ui.Action.StartLocalPosition", - std::min(index, 100)); + MediaRouterMetrics::RecordStartRouteDeviceIndex(index); } void MediaRouterWebUIMessageHandler::OnReportFilter(const base::ListValue*) { @@ -800,9 +799,8 @@ void MediaRouterWebUIMessageHandler::OnReportRouteCreation( DVLOG(1) << "Unable to extract args."; return; } - - UMA_HISTOGRAM_BOOLEAN("MediaRouter.Ui.Action.StartLocalSessionSuccessful", - route_created_successfully); + MediaRouterMetrics::RecordStartLocalSessionSuccessful( + route_created_successfully); } void MediaRouterWebUIMessageHandler::OnReportRouteCreationOutcome( @@ -841,7 +839,7 @@ void MediaRouterWebUIMessageHandler::OnReportSinkCount( DVLOG(1) << "Unable to extract args."; return; } - UMA_HISTOGRAM_COUNTS_100("MediaRouter.Ui.Device.Count", sink_count); + MediaRouterMetrics::RecordDeviceCount(sink_count); } void MediaRouterWebUIMessageHandler::OnReportTimeToClickSink( @@ -852,8 +850,8 @@ void MediaRouterWebUIMessageHandler::OnReportTimeToClickSink( DVLOG(1) << "Unable to extract args."; return; } - UMA_HISTOGRAM_TIMES("MediaRouter.Ui.Action.StartLocal.Latency", - base::TimeDelta::FromMillisecondsD(time_to_click)); + MediaRouterMetrics::RecordStartLocalSessionLatency( + base::TimeDelta::FromMillisecondsD(time_to_click)); } void MediaRouterWebUIMessageHandler::OnReportWebUIRouteControllerLoaded( @@ -876,8 +874,8 @@ void MediaRouterWebUIMessageHandler::OnReportTimeToInitialActionClose( DVLOG(1) << "Unable to extract args."; return; } - UMA_HISTOGRAM_TIMES("MediaRouter.Ui.Action.CloseLatency", - base::TimeDelta::FromMillisecondsD(time_to_close)); + MediaRouterMetrics::RecordCloseDialogLatency( + base::TimeDelta::FromMillisecondsD(time_to_close)); } void MediaRouterWebUIMessageHandler::OnSearchSinksAndCreateRoute( @@ -1068,23 +1066,25 @@ void MediaRouterWebUIMessageHandler::MaybeUpdateFirstRunFlowData() { PrefService* pref_service = profile->GetPrefs(); bool first_run_flow_acknowledged = - pref_service->GetBoolean(prefs::kMediaRouterFirstRunFlowAcknowledged); + pref_service->GetBoolean(::prefs::kMediaRouterFirstRunFlowAcknowledged); bool show_cloud_pref = false; // Cloud services preference is shown if user is logged in. If the user // enables sync after acknowledging the first run flow, this is treated as // the user opting into Google services, including cloud services, if the // browser is a Chrome branded build. - if (!pref_service->GetBoolean(prefs::kMediaRouterCloudServicesPrefSet)) { - SigninManagerBase* signin_manager = - SigninManagerFactory::GetForProfile(profile); - if (signin_manager && signin_manager->IsAuthenticated()) { + if (!pref_service->GetBoolean(::prefs::kMediaRouterCloudServicesPrefSet)) { + identity::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile(profile); + if (identity_manager && identity_manager->HasPrimaryAccount()) { // If the user had previously acknowledged the first run flow without // being shown the cloud services option, and is now logged in with sync // enabled, turn on cloud services. if (first_run_flow_acknowledged && ProfileSyncServiceFactory::GetForProfile(profile)->IsSyncActive()) { - pref_service->SetBoolean(prefs::kMediaRouterEnableCloudServices, true); - pref_service->SetBoolean(prefs::kMediaRouterCloudServicesPrefSet, true); + pref_service->SetBoolean(::prefs::kMediaRouterEnableCloudServices, + true); + pref_service->SetBoolean(::prefs::kMediaRouterCloudServicesPrefSet, + true); // Return early since the first run flow won't be surfaced. return; } @@ -1112,10 +1112,10 @@ void MediaRouterWebUIMessageHandler::MaybeUpdateFirstRunFlowData() { } AccountInfo MediaRouterWebUIMessageHandler::GetAccountInfo() { - SigninManagerBase* signin_manager = - SigninManagerFactory::GetForProfile(Profile::FromWebUI(web_ui())); - return signin_manager ? signin_manager->GetAuthenticatedAccountInfo() - : AccountInfo(); + identity::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile(Profile::FromWebUI(web_ui())); + return identity_manager ? identity_manager->GetPrimaryAccountInfo() + : AccountInfo(); } int MediaRouterWebUIMessageHandler::CurrentCastModeForRouteId( diff --git a/chromium/chrome/browser/ui/webui/module_database_conflicts_handler.cc b/chromium/chrome/browser/ui/webui/module_database_conflicts_handler.cc deleted file mode 100644 index aedb109d472..00000000000 --- a/chromium/chrome/browser/ui/webui/module_database_conflicts_handler.cc +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/module_database_conflicts_handler.h" - -#include <utility> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/strings/string16.h" -#include "base/strings/string_number_conversions.h" -#include "base/values.h" -#include "chrome/browser/conflicts/module_database_win.h" -#include "chrome/browser/conflicts/module_info_win.h" -#include "chrome/grit/generated_resources.h" -#include "content/public/browser/web_ui.h" -#include "ui/base/l10n/l10n_util.h" - -ModuleDatabaseConflictsHandler::ModuleDatabaseConflictsHandler() = default; - -ModuleDatabaseConflictsHandler::~ModuleDatabaseConflictsHandler() { - if (module_list_) - ModuleDatabase::GetInstance()->RemoveObserver(this); -} - -void ModuleDatabaseConflictsHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "requestModuleList", - base::BindRepeating( - &ModuleDatabaseConflictsHandler::HandleRequestModuleList, - base::Unretained(this))); -} - -void ModuleDatabaseConflictsHandler::OnNewModuleFound( - const ModuleInfoKey& module_key, - const ModuleInfoData& module_data) { - DCHECK(module_list_); - - auto data = std::make_unique<base::DictionaryValue>(); - - // TODO(pmonette): Set the status when conflicting module detection is added. - constexpr int kGoodStatus = 1; - data->SetInteger("status", kGoodStatus); - - base::string16 type_string; - if (module_data.module_types & ModuleInfoData::kTypeShellExtension) - type_string = L"Shell extension"; - data->SetString("type_description", type_string); - - const auto& inspection_result = *module_data.inspection_result; - data->SetString("location", inspection_result.location); - data->SetString("name", inspection_result.basename); - data->SetString("product_name", inspection_result.product_name); - data->SetString("description", inspection_result.description); - data->SetString("version", inspection_result.version); - data->SetString("digital_signer", inspection_result.certificate_info.subject); - - module_list_->Append(std::move(data)); -} - -void ModuleDatabaseConflictsHandler::OnModuleDatabaseIdle() { - DCHECK(module_list_); - DCHECK(!module_list_callback_id_.empty()); - - ModuleDatabase::GetInstance()->RemoveObserver(this); - - // Add the section title and the total count for bad modules found. - // TODO(pmonette): Add the number of conflicts when conflicting module - // detection is added. - base::string16 table_title = l10n_util::GetStringFUTF16( - IDS_CONFLICTS_CHECK_PAGE_TABLE_TITLE_SUFFIX_ONE, - base::IntToString16(module_list_->GetSize())); - - base::DictionaryValue results; - results.SetString("modulesTableTitle", table_title); - results.Set("moduleList", std::move(module_list_)); - - AllowJavascript(); - ResolveJavascriptCallback(base::Value(module_list_callback_id_), results); -} - -void ModuleDatabaseConflictsHandler::HandleRequestModuleList( - const base::ListValue* args) { - // Make sure the JS doesn't call 'requestModuleList' more than once. - // TODO(739291): It would be better to kill the renderer instead of the - // browser for malformed messages. - CHECK(!module_list_); - - CHECK_EQ(1U, args->GetSize()); - CHECK(args->GetString(0, &module_list_callback_id_)); - - // The request is handled asynchronously, filling up the |module_list_|, - // and will callback via OnModuleDatabaseIdle() on completion. - module_list_ = std::make_unique<base::ListValue>(); - - auto* module_database = ModuleDatabase::GetInstance(); - module_database->IncreaseInspectionPriority(); - module_database->AddObserver(this); -} diff --git a/chromium/chrome/browser/ui/webui/module_database_conflicts_handler.h b/chromium/chrome/browser/ui/webui/module_database_conflicts_handler.h deleted file mode 100644 index e27de653840..00000000000 --- a/chromium/chrome/browser/ui/webui/module_database_conflicts_handler.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_MODULE_DATABASE_CONFLICTS_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_MODULE_DATABASE_CONFLICTS_HANDLER_H_ - -#include <memory> -#include <string> - -#include "base/macros.h" -#include "chrome/browser/conflicts/module_database_observer_win.h" -#include "content/public/browser/web_ui_message_handler.h" - -namespace base { -class Listvalue; -} - -// This class takes care of sending the list of all loaded modules to the -// chrome://conflicts WebUI page when it is requested. It replaces -// ConflictsHandler when the ModuleDatabase feature is enabled. -class ModuleDatabaseConflictsHandler : public content::WebUIMessageHandler, - public ModuleDatabaseObserver { - public: - ModuleDatabaseConflictsHandler(); - ~ModuleDatabaseConflictsHandler() override; - - private: - // content::WebUIMessageHandler: - void RegisterMessages() override; - - // ModuleDatabaseObserver: - void OnNewModuleFound(const ModuleInfoKey& module_key, - const ModuleInfoData& module_data) override; - void OnModuleDatabaseIdle() override; - - // Callback for the "requestModuleList" message. - void HandleRequestModuleList(const base::ListValue* args); - - // The ID of the callback that will get invoked with the module list. - std::string module_list_callback_id_; - - // Temporarily holds the module list while the modules are being - // enumerated. - std::unique_ptr<base::ListValue> module_list_; - - DISALLOW_COPY_AND_ASSIGN(ModuleDatabaseConflictsHandler); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_MODULE_DATABASE_CONFLICTS_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/nacl_ui.cc b/chromium/chrome/browser/ui/webui/nacl_ui.cc index 2a5b2237eb4..49b29dfe600 100644 --- a/chromium/chrome/browser/ui/webui/nacl_ui.cc +++ b/chromium/chrome/browser/ui/webui/nacl_ui.cc @@ -28,6 +28,7 @@ #include "build/build_config.h" #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" @@ -53,13 +54,15 @@ using base::UserMetricsAction; using content::BrowserThread; using content::PluginService; using content::WebUIMessageHandler; +using webui::webui_util::AddPair; namespace { content::WebUIDataSource* CreateNaClUIHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUINaClHost); - + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->SetJsonPath("strings.js"); source->AddResourcePath("about_nacl.css", IDR_ABOUT_NACL_CSS); source->AddResourcePath("about_nacl.js", IDR_ABOUT_NACL_JS); @@ -155,17 +158,6 @@ void NaClDomHandler::RegisterMessages() { base::Unretained(this))); } -// Helper functions for collecting a list of key-value pairs that will -// be displayed. -void AddPair(base::ListValue* list, - const base::string16& key, - const base::string16& value) { - std::unique_ptr<base::DictionaryValue> results(new base::DictionaryValue()); - results->SetString("key", key); - results->SetString("value", value); - list->Append(std::move(results)); -} - // Generate an empty data-pair which acts as a line break. void AddLineBreak(base::ListValue* list) { AddPair(list, ASCIIToUTF16(""), ASCIIToUTF16("")); diff --git a/chromium/chrome/browser/ui/webui/net_internals/DEPS b/chromium/chrome/browser/ui/webui/net_internals/DEPS index 5f9d86d4586..060df380685 100644 --- a/chromium/chrome/browser/ui/webui/net_internals/DEPS +++ b/chromium/chrome/browser/ui/webui/net_internals/DEPS @@ -1,4 +1,5 @@ include_rules = [ "+components/onc", "+components/user_manager", + "+services/network/expect_ct_reporter.h", ] 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 12c2eb2e127..34960e3e654 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 @@ -38,7 +38,6 @@ #include "chrome/browser/net/chrome_network_delegate.h" #include "chrome/browser/net/net_export_helper.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ssl/chrome_expect_ct_reporter.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/url_constants.h" @@ -73,6 +72,7 @@ #include "net/proxy_resolution/proxy_resolution_service.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" +#include "services/network/expect_ct_reporter.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/file_manager/filesystem_api_util.h" @@ -139,31 +139,6 @@ std::string HashesToBase64String(const net::HashValueVector& hashes) { return str; } -bool Base64StringToHashes(const std::string& hashes_str, - net::HashValueVector* hashes) { - hashes->clear(); - std::vector<std::string> vector_hash_str = base::SplitString( - hashes_str, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - - for (size_t i = 0; i != vector_hash_str.size(); ++i) { - std::string hash_str; - base::RemoveChars(vector_hash_str[i], " \t\r\n", &hash_str); - net::HashValue hash; - // Skip past unrecognized hash algos - // But return false on malformatted input - if (hash_str.empty()) - return false; - if (hash_str.compare(0, 5, "sha1/") != 0 && - hash_str.compare(0, 7, "sha256/") != 0) { - continue; - } - if (!hash.FromString(hash_str)) - return false; - hashes->push_back(hash); - } - return true; -} - // Returns the http network session for |context| if there is one. // Otherwise, returns NULL. net::HttpNetworkSession* GetHttpNetworkSession( @@ -176,6 +151,8 @@ net::HttpNetworkSession* GetHttpNetworkSession( content::WebUIDataSource* CreateNetInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUINetInternalsHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->SetDefaultResource(IDR_NET_INTERNALS_INDEX_HTML); source->AddResourcePath("index.js", IDR_NET_INTERNALS_INDEX_JS); @@ -387,7 +364,7 @@ class NetInternalsMessageHandler::IOThreadImpl // local variable so that it lives long enough to receive the result of // sending a report, which is delivered to the JavaScript via a JavaScript // command. - std::unique_ptr<ChromeExpectCTReporter> expect_ct_reporter_; + std::unique_ptr<network::ExpectCTReporter> expect_ct_reporter_; DISALLOW_COPY_AND_ASSIGN(IOThreadImpl); }; @@ -810,8 +787,7 @@ void NetInternalsMessageHandler::IOThreadImpl::OnHSTSQuery( void NetInternalsMessageHandler::IOThreadImpl::OnHSTSAdd( const base::ListValue* list) { - // |list| should be: [<domain to query>, <STS include subdomains>, <PKP - // include subdomains>, <key pins>]. + // |list| should be: [<domain to query>, <STS include subdomains>] std::string domain; bool result = list->GetString(0, &domain); DCHECK(result); @@ -823,12 +799,6 @@ void NetInternalsMessageHandler::IOThreadImpl::OnHSTSAdd( bool sts_include_subdomains; result = list->GetBoolean(1, &sts_include_subdomains); DCHECK(result); - bool pkp_include_subdomains; - result = list->GetBoolean(2, &pkp_include_subdomains); - DCHECK(result); - std::string hashes_str; - result = list->GetString(3, &hashes_str); - DCHECK(result); net::TransportSecurityState* transport_security_state = GetMainContext()->transport_security_state(); @@ -836,15 +806,7 @@ void NetInternalsMessageHandler::IOThreadImpl::OnHSTSAdd( return; base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000); - net::HashValueVector hashes; - if (!hashes_str.empty()) { - if (!Base64StringToHashes(hashes_str, &hashes)) - return; - } - transport_security_state->AddHSTS(domain, expiry, sts_include_subdomains); - transport_security_state->AddHPKP(domain, expiry, pkp_include_subdomains, - hashes, GURL()); } void NetInternalsMessageHandler::IOThreadImpl::OnExpectCTQuery( @@ -937,7 +899,7 @@ void NetInternalsMessageHandler::IOThreadImpl::OnExpectCTTestReport( std::make_unique<base::Value>("success"); std::unique_ptr<base::Value> failure = std::make_unique<base::Value>("failure"); - expect_ct_reporter_ = std::make_unique<ChromeExpectCTReporter>( + expect_ct_reporter_ = std::make_unique<network::ExpectCTReporter>( GetMainContext(), base::Bind( &NetInternalsMessageHandler::IOThreadImpl::SendJavascriptCommand, 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 ac58f8b1ce6..1cee0ce0600 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 @@ -123,6 +123,12 @@ class NetInternalsTest::MessageHandler : public content::WebUIMessageHandler { private: void RegisterMessages() override; + void RegisterMessage(const std::string& message, + const content::WebUI::MessageCallback& handler); + + void HandleMessage(const content::WebUI::MessageCallback& handler, + const base::ListValue* data); + // Runs NetInternalsTest.callback with the given value. void RunJavascriptCallback(base::Value* value); @@ -188,57 +194,69 @@ NetInternalsTest::MessageHandler::MessageHandler( } void NetInternalsTest::MessageHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( + RegisterMessage( "getTestServerURL", base::BindRepeating(&NetInternalsTest::MessageHandler::GetTestServerURL, base::Unretained(this))); - web_ui()->RegisterMessageCallback( + RegisterMessage( "addCacheEntry", base::BindRepeating(&NetInternalsTest::MessageHandler::AddCacheEntry, base::Unretained(this))); - web_ui()->RegisterMessageCallback( + RegisterMessage( "changeNetwork", base::BindRepeating(&NetInternalsTest::MessageHandler::ChangeNetwork, base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "loadPage", - base::BindRepeating(&NetInternalsTest::MessageHandler::LoadPage, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( + RegisterMessage("loadPage", base::BindRepeating( + &NetInternalsTest::MessageHandler::LoadPage, + base::Unretained(this))); + RegisterMessage( "prerenderPage", base::BindRepeating(&NetInternalsTest::MessageHandler::PrerenderPage, base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "navigateToPrerender", - base::BindRepeating( - &NetInternalsTest::MessageHandler::NavigateToPrerender, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "createIncognitoBrowser", - base::BindRepeating( - &NetInternalsTest::MessageHandler::CreateIncognitoBrowser, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "closeIncognitoBrowser", - base::BindRepeating( - &NetInternalsTest::MessageHandler::CloseIncognitoBrowser, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "getNetLogFileContents", - base::BindRepeating( - &NetInternalsTest::MessageHandler::GetNetLogFileContents, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( + RegisterMessage("navigateToPrerender", + base::BindRepeating( + &NetInternalsTest::MessageHandler::NavigateToPrerender, + base::Unretained(this))); + RegisterMessage("createIncognitoBrowser", + base::BindRepeating( + &NetInternalsTest::MessageHandler::CreateIncognitoBrowser, + base::Unretained(this))); + RegisterMessage("closeIncognitoBrowser", + base::BindRepeating( + &NetInternalsTest::MessageHandler::CloseIncognitoBrowser, + base::Unretained(this))); + RegisterMessage("getNetLogFileContents", + base::BindRepeating( + &NetInternalsTest::MessageHandler::GetNetLogFileContents, + base::Unretained(this))); + RegisterMessage( "setUpTestReportURI", base::BindRepeating(&NetInternalsTest::MessageHandler::SetUpTestReportURI, base::Unretained(this))); - web_ui()->RegisterMessageCallback( + RegisterMessage( "enableDataReductionProxy", base::BindRepeating( &NetInternalsTest::MessageHandler::EnableDataReductionProxy, base::Unretained(this))); } +void NetInternalsTest::MessageHandler::RegisterMessage( + const std::string& message, + const content::WebUI::MessageCallback& handler) { + web_ui()->RegisterMessageCallback( + message, + base::BindRepeating(&NetInternalsTest::MessageHandler::HandleMessage, + base::Unretained(this), handler)); +} + +void NetInternalsTest::MessageHandler::HandleMessage( + const content::WebUI::MessageCallback& handler, + const base::ListValue* data) { + // The handler might run a nested loop to wait for something. + base::MessageLoopCurrent::ScopedNestableTaskAllower nestable_task_allower; + handler.Run(data); +} + void NetInternalsTest::MessageHandler::RunJavascriptCallback( base::Value* value) { web_ui()->CallJavascriptFunctionUnsafe("NetInternalsTest.callback", *value); 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 a073ddf6153..d9cac60b0b5 100644 --- a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc +++ b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc @@ -101,7 +101,8 @@ AppLauncherHandler::AppInstallInfo::AppInstallInfo() {} AppLauncherHandler::AppInstallInfo::~AppInstallInfo() {} -AppLauncherHandler::AppLauncherHandler(ExtensionService* extension_service) +AppLauncherHandler::AppLauncherHandler( + extensions::ExtensionService* extension_service) : extension_service_(extension_service), ignore_changes_(false), attempted_bookmark_app_install_(false), @@ -111,10 +112,9 @@ AppLauncherHandler::~AppLauncherHandler() { ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))->RemoveObserver(this); } -void AppLauncherHandler::CreateAppInfo( - const Extension* extension, - ExtensionService* service, - base::DictionaryValue* value) { +void AppLauncherHandler::CreateAppInfo(const Extension* extension, + extensions::ExtensionService* service, + base::DictionaryValue* value) { // The items which are to be written into |value| are also described in // chrome/browser/resources/ntp4/page_list_view.js in @typedef for AppInfo. // Please update it whenever you add or remove any keys here. @@ -823,7 +823,7 @@ void AppLauncherHandler::ExtensionEnableFlowAborted(bool user_initiated) { extension_service_->GetExtensionById(extension_id_prompting_, true); std::string histogram_name = user_initiated ? "ReEnableCancel" : "ReEnableAbort"; - ExtensionService::RecordPermissionMessagesHistogram( + extensions::ExtensionService::RecordPermissionMessagesHistogram( extension, histogram_name.c_str()); extension_enable_flow_.reset(); diff --git a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.h b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.h index 156b8b4fafa..5e9bf46b6e0 100644 --- a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.h +++ b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.h @@ -24,10 +24,13 @@ #include "extensions/common/extension.h" class ExtensionEnableFlow; -class ExtensionService; class PrefChangeRegistrar; class Profile; +namespace extensions { +class ExtensionService; +} + namespace favicon_base { struct FaviconImageResult; } @@ -44,14 +47,13 @@ class AppLauncherHandler public content::NotificationObserver, public extensions::ExtensionRegistryObserver { public: - explicit AppLauncherHandler(ExtensionService* extension_service); + explicit AppLauncherHandler(extensions::ExtensionService* extension_service); ~AppLauncherHandler() override; // Populate a dictionary with the information from an extension. - static void CreateAppInfo( - const extensions::Extension* extension, - ExtensionService* service, - base::DictionaryValue* value); + static void CreateAppInfo(const extensions::Extension* extension, + extensions::ExtensionService* service, + base::DictionaryValue* value); // Registers values (strings etc.) for the page. static void GetLocalizedValues(Profile* profile, @@ -177,7 +179,7 @@ class AppLauncherHandler // The apps are represented in the extensions model, which // outlives us since it's owned by our containing profile. - ExtensionService* const extension_service_; + extensions::ExtensionService* const extension_service_; // We monitor changes to the extension system so that we can reload the apps // when necessary. diff --git a/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc b/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc index d71fefdb9a4..3c2af7b1a72 100644 --- a/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc +++ b/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc @@ -16,7 +16,7 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" @@ -34,13 +34,13 @@ #include "components/bookmarks/common/bookmark_pref_names.h" #include "components/google/core/browser/google_util.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_manager.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/render_process_host.h" #include "extensions/common/extension.h" #include "extensions/common/extension_urls.h" +#include "services/identity/public/cpp/identity_manager.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/template_expressions.h" @@ -457,7 +457,7 @@ void NTPResourceCache::CreateNewTabHTML() { load_time_data.SetBoolean( "isUserSignedIn", - SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated()); + IdentityManagerFactory::GetForProfile(profile_)->HasPrimaryAccount()); // Load the new tab page appropriate for this build. base::StringPiece new_tab_html( diff --git a/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache_factory.cc b/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache_factory.cc index 1f9b0d1002e..cdd8d431388 100644 --- a/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache_factory.cc +++ b/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache_factory.cc @@ -6,7 +6,7 @@ #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/webui/ntp/ntp_resource_cache.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" @@ -26,7 +26,7 @@ NTPResourceCacheFactory::NTPResourceCacheFactory() : BrowserContextKeyedServiceFactory( "NTPResourceCache", BrowserContextDependencyManager::GetInstance()) { - DependsOn(SigninManagerFactory::GetInstance()); + DependsOn(IdentityManagerFactory::GetInstance()); DependsOn(ThemeServiceFactory::GetInstance()); } diff --git a/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc b/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc index 7915180992d..1f3766c23c8 100644 --- a/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc @@ -7,6 +7,7 @@ #include <memory> #include "base/bind.h" +#include "build/build_config.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/top_sites_factory.h" #include "chrome/browser/ntp_tiles/chrome_most_visited_sites_factory.h" @@ -18,6 +19,7 @@ #include "components/grit/components_resources.h" #include "components/history/core/browser/top_sites.h" #include "components/image_fetcher/core/image_fetcher_impl.h" +#include "components/ntp_tiles/constants.h" #include "components/ntp_tiles/icon_cacher.h" #include "components/ntp_tiles/most_visited_sites.h" #include "components/ntp_tiles/webui/ntp_tiles_internals_message_handler.h" @@ -85,6 +87,8 @@ bool ChromeNTPTilesInternalsMessageHandlerClient::DoesSourceExist( #else return false; #endif + case ntp_tiles::TileSource::CUSTOM_LINKS: + return ntp_tiles::IsCustomLinksEnabled(); } NOTREACHED(); return false; @@ -115,6 +119,8 @@ void ChromeNTPTilesInternalsMessageHandlerClient::CallJavascriptFunctionVector( content::WebUIDataSource* CreateNTPTilesInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUINTPTilesInternalsHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->AddResourcePath("ntp_tiles_internals.js", IDR_NTP_TILES_INTERNALS_JS); source->AddResourcePath("ntp_tiles_internals.css", 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 9ca918dd9d7..9c5f03fa560 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 @@ -387,7 +387,7 @@ void OfflineInternalsUIMessageHandler::HandleDownloadArchive( if (prefetch_service_) { prefetch_service_->GetPrefetchDownloader()->StartDownload( - base::GenerateGUID(), name); + base::GenerateGUID(), name, std::string()); } } diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom b/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom index 0506e5324df..9fe3b572e48 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom @@ -43,6 +43,9 @@ struct OmniboxResult { bool done; // Time delta since the request was started, in milliseconds. int32 time_since_omnibox_started_ms; + // The inferred metrics::OmniboxInputType of the request represented as a + // string. + string type; string host; bool is_typed_host; array<AutocompleteMatch> combined_results; 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 f56b9c74919..d6c5b06681c 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc @@ -130,6 +130,7 @@ void OmniboxPageHandler::OnResultChanged(bool default_match_changed) { const base::string16 host = input_.text().substr(input_.parts().host.begin, input_.parts().host.len); result->host = base::UTF16ToUTF8(host); + result->type = AutocompleteInput::TypeToString(input_.type()); bool is_typed_host; if (!LookupIsTypedHost(host, &is_typed_host)) is_typed_host = false; diff --git a/chromium/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc index c58d6c2c0b2..48ee22746b2 100644 --- a/chromium/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/policy_tool_ui_browsertest.cc @@ -466,7 +466,13 @@ IN_PROC_BROWSER_TEST_F(PolicyToolUITest, MAYBE_CreatingSessionFiles) { EXPECT_TRUE(PathExists(GetSessionPath(FILE_PATH_LITERAL("сессия")))); } -IN_PROC_BROWSER_TEST_F(PolicyToolUITest, ImportingSession) { +// Flaky on Win buildbots. See crbug.com/842405. +#if defined(OS_WIN) +#define MAYBE_ImportingSession DISABLED_ImportingSession +#else +#define MAYBE_ImportingSession ImportingSession +#endif +IN_PROC_BROWSER_TEST_F(PolicyToolUITest, MAYBE_ImportingSession) { ui_test_utils::NavigateToURL(browser(), GURL("chrome://policy-tool")); // Set up policy values and put them in the session file. @@ -851,4 +857,4 @@ IN_PROC_BROWSER_TEST_F(PolicyToolUITest, EXPECT_TRUE(CheckPolicyStatus( "ManagedBookmarks", "[{\"attribute\": \"value\"}]", l10n_util::GetStringUTF8(IDS_POLICY_TOOL_INVALID_TYPE))); -}
\ No newline at end of file +} diff --git a/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc index 4379ed2d749..933bab52f6d 100644 --- a/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc @@ -16,8 +16,12 @@ #include "base/run_loop.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" +#include "build/build_config.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/test_extension_system.h" +#include "chrome/browser/policy/profile_policy_connector_factory.h" +#include "chrome/browser/policy/schema_registry_service.h" +#include "chrome/browser/policy/schema_registry_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -28,6 +32,7 @@ #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_namespace.h" #include "components/policy/core/common/policy_types.h" #include "components/policy/core/common/schema.h" #include "components/policy/policy_constants.h" @@ -48,28 +53,74 @@ using testing::_; namespace { +// Allows waiting until the policy schema for a |PolicyNamespace| has been made +// available by a |Profile|'s |SchemaRegistry|. +class PolicySchemaAvailableWaiter : public policy::SchemaRegistry::Observer { + public: + PolicySchemaAvailableWaiter(Profile* profile, + const policy::PolicyNamespace& policy_namespace) + : registry_(policy::SchemaRegistryServiceFactory::GetForContext(profile) + ->registry()), + policy_namespace_(policy_namespace) {} + + ~PolicySchemaAvailableWaiter() override { registry_->RemoveObserver(this); } + + // Starts waiting for a policy schema to be available for the + // |policy_namespace_| that has been passed to the constructor. Returns + // immediately if the policy schema is already available. + void Wait() { + if (RegistryHasSchemaForNamespace()) + return; + registry_->AddObserver(this); + run_loop_.Run(); + } + + private: + bool RegistryHasSchemaForNamespace() { + const policy::ComponentMap* map = + registry_->schema_map()->GetComponents(policy_namespace_.domain); + if (!map) + return false; + return map->find(policy_namespace_.component_id) != map->end(); + } + + // policy::SchemaRegistry::Observer: + void OnSchemaRegistryUpdated(bool has_new_schemas) override { + if (RegistryHasSchemaForNamespace()) + run_loop_.Quit(); + } + + policy::SchemaRegistry* const registry_; + const policy::PolicyNamespace policy_namespace_; + base::RunLoop run_loop_; + + DISALLOW_COPY_AND_ASSIGN(PolicySchemaAvailableWaiter); +}; + std::vector<std::string> PopulateExpectedPolicy( const std::string& name, const std::string& value, const std::string& source, - const policy::PolicyMap::Entry* metadata, + const policy::PolicyMap::Entry* policy_map_entry, bool unknown) { std::vector<std::string> expected_policy; // Populate expected scope. - if (metadata) { + if (policy_map_entry) { expected_policy.push_back(l10n_util::GetStringUTF8( - metadata->scope == policy::POLICY_SCOPE_MACHINE ? - IDS_POLICY_SCOPE_DEVICE : IDS_POLICY_SCOPE_USER)); + policy_map_entry->scope == policy::POLICY_SCOPE_MACHINE + ? IDS_POLICY_SCOPE_DEVICE + : IDS_POLICY_SCOPE_USER)); } else { expected_policy.push_back(std::string()); } // Populate expected level. - if (metadata) { + if (policy_map_entry) { expected_policy.push_back(l10n_util::GetStringUTF8( - metadata->level == policy::POLICY_LEVEL_RECOMMENDED ? - IDS_POLICY_LEVEL_RECOMMENDED : IDS_POLICY_LEVEL_MANDATORY)); + policy_map_entry->level == policy::POLICY_LEVEL_RECOMMENDED + ? IDS_POLICY_LEVEL_RECOMMENDED + : IDS_POLICY_LEVEL_MANDATORY)); } else { expected_policy.push_back(std::string()); } @@ -85,7 +136,7 @@ std::vector<std::string> PopulateExpectedPolicy( // Populate expected status. if (unknown) expected_policy.push_back(l10n_util::GetStringUTF8(IDS_POLICY_UNKNOWN)); - else if (metadata) + else if (policy_map_entry) expected_policy.push_back(l10n_util::GetStringUTF8(IDS_POLICY_OK)); else expected_policy.push_back(l10n_util::GetStringUTF8(IDS_POLICY_UNSET)); @@ -101,11 +152,14 @@ void SetExpectedPolicy(base::DictionaryValue* expected, const std::string& level, const std::string& scope, const std::string& source, + const std::string& error, const base::Value& value) { const char prefix[] = "chromePolicies"; expected->SetPath({prefix, name.c_str(), "level"}, base::Value(level)); expected->SetPath({prefix, name.c_str(), "scope"}, base::Value(scope)); expected->SetPath({prefix, name.c_str(), "source"}, base::Value(source)); + if (!error.empty()) + expected->SetPath({prefix, name.c_str(), "error"}, base::Value(error)); expected->SetPath({prefix, name.c_str(), "value"}, value.Clone()); } @@ -124,7 +178,11 @@ class PolicyUITest : public InProcessBrowserTest { // InProcessBrowserTest implementation. void SetUpInProcessBrowserTestFixture() override; - void UpdateProviderPolicy(const policy::PolicyMap& policy); + // Uses the |MockConfiguratonPolicyProvider| installed for testing to publish + // |policy| for |policy_namespace|. + void UpdateProviderPolicyForNamespace( + const policy::PolicyNamespace& policy_namespace, + const policy::PolicyMap& policy); void VerifyPolicies(const std::vector<std::vector<std::string> >& expected); @@ -188,6 +246,8 @@ void PolicyUITest::SetUpInProcessBrowserTestFixture() { EXPECT_CALL(provider_, IsInitializationComplete(_)) .WillRepeatedly(Return(true)); policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_); + policy::ProfilePolicyConnectorFactory::GetInstance()->PushProviderForTesting( + &provider_); // Create a directory for testing exporting policies. ASSERT_TRUE(export_policies_test_dir.CreateUniqueTempDir()); @@ -196,10 +256,13 @@ void PolicyUITest::SetUpInProcessBrowserTestFixture() { export_policies_test_dir.GetPath().AppendASCII(filename); } -void PolicyUITest::UpdateProviderPolicy(const policy::PolicyMap& policy) { - provider_.UpdateChromePolicy(policy); - base::RunLoop loop; - loop.RunUntilIdle(); +void PolicyUITest::UpdateProviderPolicyForNamespace( + const policy::PolicyNamespace& policy_namespace, + const policy::PolicyMap& policy) { + std::unique_ptr<policy::PolicyBundle> bundle = + std::make_unique<policy::PolicyBundle>(); + bundle->Get(policy_namespace).CopyFrom(policy); + provider_.UpdatePolicy(std::move(bundle)); } void PolicyUITest::VerifyPolicies( @@ -303,14 +366,15 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, WritePoliciesToJSONFile) { policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_PLATFORM, popups_blocked_for_urls.CreateDeepCopy(), nullptr); SetExpectedPolicy(&expected_values, policy::key::kPopupsBlockedForUrls, - "mandatory", "machine", "sourcePlatform", + "mandatory", "machine", "sourcePlatform", std::string(), popups_blocked_for_urls); values.Set(policy::key::kDefaultImagesSetting, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD, std::make_unique<base::Value>(2), nullptr); SetExpectedPolicy(&expected_values, policy::key::kDefaultImagesSetting, - "mandatory", "machine", "sourceCloud", base::Value(2)); + "mandatory", "machine", "sourceCloud", std::string(), + base::Value(2)); // This also checks that we save complex policies correctly. base::DictionaryValue unknown_policy; @@ -324,14 +388,15 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, WritePoliciesToJSONFile) { policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, unknown_policy.CreateDeepCopy(), nullptr); SetExpectedPolicy(&expected_values, kUnknownPolicy, "recommended", "user", - "sourceCloud", unknown_policy); + "sourceCloud", l10n_util::GetStringUTF8(IDS_POLICY_UNKNOWN), + unknown_policy); // Set the extension policies to an empty dictionary as we haven't added any // such policies. expected_values.SetDictionary("extensionPolicies", std::make_unique<base::DictionaryValue>()); - UpdateProviderPolicy(values); + provider_.UpdateChromePolicy(values); // Check writing those policies to a newly created file. VerifyExportingPolicies(expected_values); @@ -343,25 +408,27 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, WritePoliciesToJSONFile) { std::string(policy::key::kDefaultImagesSetting), nullptr); +#if !defined(OS_CHROMEOS) // This also checks that we bypass the policy that blocks file selection - // dialogs. + // dialogs. This is a desktop only policy. values.Set(policy::key::kAllowFileSelectionDialogs, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_PLATFORM, std::make_unique<base::Value>(false), nullptr); SetExpectedPolicy(&expected_values, policy::key::kAllowFileSelectionDialogs, - "mandatory", "machine", "sourcePlatform", + "mandatory", "machine", "sourcePlatform", std::string(), base::Value(false)); +#endif popups_blocked_for_urls.AppendString("ddd"); values.Set(policy::key::kPopupsBlockedForUrls, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_PLATFORM, popups_blocked_for_urls.CreateDeepCopy(), nullptr); SetExpectedPolicy(&expected_values, policy::key::kPopupsBlockedForUrls, - "mandatory", "machine", "sourcePlatform", + "mandatory", "machine", "sourcePlatform", std::string(), popups_blocked_for_urls); - UpdateProviderPolicy(values); + provider_.UpdateChromePolicy(values); // Check writing changed policies to the same file (should overwrite the // contents). @@ -432,7 +499,7 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, SendPolicyValues) { std::make_unique<base::Value>("blub"), nullptr); expected_values[kUnknownPolicyWithDots] = "blub"; - UpdateProviderPolicy(values); + provider_.UpdateChromePolicy(values); // Expect that the policy table contains, in order: // * All known policies whose value has been set, in alphabetical order. @@ -481,10 +548,20 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, ExtensionLoadAndSendPolicy) { base::ScopedTempDir temp_dir_; ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - const std::string newly_added_policy_name = "new_policy"; - std::string json_data = "{\"type\": \"object\",\"properties\": {\"" + - newly_added_policy_name + - "\": { \"type\": \"string\"}}}"; + const std::string kNewPolicyName = "new_policy"; + const std::string kSensitivePolicyName = "sensitive_policy"; + std::string json_data = R"({ + "type": "object", + "properties": { + "new_policy": { + "type": "string" + }, + "sensitive_policy": { + "type": "string", + "sensitiveValue": true + } + } + })"; const std::string schema_file = "schema.json"; base::FilePath schema_path = temp_dir_.GetPath().AppendASCII(schema_file); @@ -505,27 +582,53 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, ExtensionLoadAndSendPolicy) { builder.SetManifest(manifest.Build()); // Install extension. - ExtensionService* service = extensions::ExtensionSystem::Get( - browser()->profile())->extension_service(); - EXPECT_CALL(provider_, RefreshPolicies()); - service->OnExtensionInstalled(builder.Build().get(), syncer::StringOrdinal(), - 0); - - std::vector<std::vector<std::string>> expected_policies; + extensions::ExtensionService* service = + extensions::ExtensionSystem::Get(browser()->profile()) + ->extension_service(); + scoped_refptr<extensions::Extension> extension = builder.Build(); + service->OnExtensionInstalled(extension.get(), syncer::StringOrdinal(), 0); + const policy::PolicyNamespace extension_policy_namespace( + policy::POLICY_DOMAIN_EXTENSIONS, extension->id()); + PolicySchemaAvailableWaiter(browser()->profile(), extension_policy_namespace) + .Wait(); + + std::vector<std::vector<std::string>> expected_chrome_policies; policy::Schema chrome_schema = policy::Schema::Wrap(policy::GetChromeSchemaData()); ASSERT_TRUE(chrome_schema.valid()); for (policy::Schema::Iterator it = chrome_schema.GetPropertiesIterator(); !it.IsAtEnd(); it.Advance()) { - expected_policies.push_back( - PopulateExpectedPolicy( - it.key(), std::string(), std::string(), nullptr, false)); + expected_chrome_policies.push_back(PopulateExpectedPolicy( + it.key(), std::string(), std::string(), nullptr, false)); } - // Add newly added policy to expected policy list. + // Add extension policy to expected policy list. + std::vector<std::vector<std::string>> expected_policies = + expected_chrome_policies; expected_policies.push_back(PopulateExpectedPolicy( - newly_added_policy_name, std::string(), std::string(), nullptr, false)); + kNewPolicyName, std::string(), std::string(), nullptr, false)); + expected_policies.push_back(PopulateExpectedPolicy( + kSensitivePolicyName, std::string(), std::string(), nullptr, false)); // Verify if policy UI includes policy that extension have. VerifyPolicies(expected_policies); + + policy::PolicyMap values; + values.Set(kNewPolicyName, policy::POLICY_LEVEL_MANDATORY, + policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, + std::make_unique<base::Value>("value1"), nullptr); + values.Set(kSensitivePolicyName, policy::POLICY_LEVEL_MANDATORY, + policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, + std::make_unique<base::Value>("value2"), nullptr); + UpdateProviderPolicyForNamespace(extension_policy_namespace, values); + + // Add extension policy with values to expected policy list. + std::vector<std::vector<std::string>> expected_policies_with_values = + expected_chrome_policies; + expected_policies_with_values.push_back(PopulateExpectedPolicy( + kNewPolicyName, "value1", "Cloud", values.Get(kNewPolicyName), false)); + expected_policies_with_values.push_back( + PopulateExpectedPolicy(kSensitivePolicyName, "********", "Cloud", + values.Get(kSensitivePolicyName), false)); + VerifyPolicies(expected_policies_with_values); } diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc index d322dd5ac8c..cd3a8df1cd2 100644 --- a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc @@ -735,12 +735,11 @@ void PolicyUIHandler::SendPolicyNames() const { } void PolicyUIHandler::SendPolicyValues() const { - std::unique_ptr<base::DictionaryValue> all_policies = - policy::GetAllPolicyValuesAsDictionary( - web_ui()->GetWebContents()->GetBrowserContext(), - true /* with_user_policies */, true /* convert_values */); + base::Value all_policies = policy::GetAllPolicyValuesAsDictionary( + web_ui()->GetWebContents()->GetBrowserContext(), + true /* with_user_policies */, true /* convert_values */); web_ui()->CallJavascriptFunctionUnsafe("policy.Page.setPolicyValues", - *all_policies); + all_policies); } void PolicyUIHandler::SendStatus() const { @@ -773,20 +772,26 @@ void PolicyUIHandler::HandleInitialized(const base::ListValue* args) { void PolicyUIHandler::HandleReloadPolicies(const base::ListValue* args) { #if defined(OS_CHROMEOS) - // Allow user to manually fetch remote commands, in case invalidation - // service is not working properly. - // TODO(binjin): evaluate and possibly remove this after invalidation - // service is landed and tested. http://crbug.com/480982 - policy::CloudPolicyManager* manager = + // Allow user to manually fetch remote commands. Useful for testing or when + // the invalidation service is not working properly. + policy::CloudPolicyManager* const device_manager = g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->GetDeviceCloudPolicyManager(); - // Active Directory management has no CloudPolicyManager. - if (manager) { - policy::RemoteCommandsService* remote_commands_service = - manager->core()->remote_commands_service(); - if (remote_commands_service) - remote_commands_service->FetchRemoteCommands(); + Profile* const profile = Profile::FromWebUI(web_ui()); + policy::CloudPolicyManager* const user_manager = + policy::UserPolicyManagerFactoryChromeOS::GetCloudPolicyManagerForProfile( + profile); + + // Fetch both device and user remote commands. + for (policy::CloudPolicyManager* manager : {device_manager, user_manager}) { + // Active Directory management has no CloudPolicyManager. + if (manager) { + policy::RemoteCommandsService* const remote_commands_service = + manager->core()->remote_commands_service(); + if (remote_commands_service) + remote_commands_service->FetchRemoteCommands(); + } } #endif GetPolicyService()->RefreshPolicies(base::Bind( @@ -802,7 +807,7 @@ void PolicyUIHandler::WritePoliciesToJSONFile( const base::FilePath& path) const { std::string json_policies = policy::GetAllPolicyValuesAsJSON( web_ui()->GetWebContents()->GetBrowserContext(), - true /* with_user_policies */); + true /* with_user_policies */, false /* with device identity */); base::PostTaskWithTraits( FROM_HERE, diff --git a/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.cc new file mode 100644 index 00000000000..d8093487285 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.cc @@ -0,0 +1,42 @@ +// 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/print_preview/cloud_printer_handler.h" + +#include <memory> + +#include "base/bind.h" +#include "base/callback.h" +#include "base/values.h" + +CloudPrinterHandler::CloudPrinterHandler() {} + +CloudPrinterHandler::~CloudPrinterHandler() {} + +void CloudPrinterHandler::Reset() {} + +void CloudPrinterHandler::StartGetPrinters( + const AddedPrintersCallback& added_printers_callback, + GetPrintersDoneCallback done_callback) { + // TODO(https://crbug.com/829414): Actually retrieve the printers + std::move(done_callback).Run(); +} + +void CloudPrinterHandler::StartGetCapability(const std::string& destination_id, + GetCapabilityCallback callback) { + // TODO(https://crbug.com/829414): Get capabilities. + std::move(callback).Run(nullptr); +} + +void CloudPrinterHandler::StartPrint( + const std::string& destination_id, + const std::string& capability, + const base::string16& job_title, + const std::string& ticket_json, + const gfx::Size& page_size, + const scoped_refptr<base::RefCountedMemory>& print_data, + PrintCallback callback) { + // TODO(https://crbug.com/829414): Print to cloud print + NOTIMPLEMENTED(); +} diff --git a/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.h new file mode 100644 index 00000000000..64d469a07bc --- /dev/null +++ b/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.h @@ -0,0 +1,38 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_CLOUD_PRINTER_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_CLOUD_PRINTER_HANDLER_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/print_preview/printer_handler.h" + +// Implementation of PrinterHandler interface +class CloudPrinterHandler : public PrinterHandler { + public: + CloudPrinterHandler(); + + ~CloudPrinterHandler() override; + + // PrinterHandler implementation: + void Reset() override; + void StartGetPrinters(const AddedPrintersCallback& added_printers_callback, + GetPrintersDoneCallback done_callback) override; + void StartGetCapability(const std::string& destination_id, + GetCapabilityCallback calback) override; + void StartPrint(const std::string& destination_id, + const std::string& capability, + const base::string16& job_title, + const std::string& ticket_json, + const gfx::Size& page_size, + const scoped_refptr<base::RefCountedMemory>& print_data, + PrintCallback callback) override; + + private: + DISALLOW_COPY_AND_ASSIGN(CloudPrinterHandler); +}; +#endif // CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_CLOUD_PRINTER_HANDLER_H_ 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 5b128dc114d..b753712af06 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 @@ -79,8 +79,7 @@ LocalPrinterHandlerChromeos::LocalPrinterHandlerChromeos( content::WebContents* preview_web_contents) : preview_web_contents_(preview_web_contents), printers_manager_( - CupsPrintersManagerFactory::GetInstance()->GetForBrowserContext( - profile)), + CupsPrintersManagerFactory::GetForBrowserContext(profile)), printer_configurer_(chromeos::PrinterConfigurer::Create(profile)), weak_factory_(this) { // Construct the CupsPrintJobManager to listen for printing events. 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 a09caf94453..97f9d542885 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 @@ -4,16 +4,13 @@ #include "chrome/browser/ui/webui/print_preview/pdf_printer_handler.h" -#include <memory> -#include <string> #include <utility> #include "base/callback.h" #include "base/command_line.h" +#include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/i18n/file_util_icu.h" -#include "base/memory/ref_counted.h" -#include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/task_scheduler/post_task.h" @@ -39,6 +36,7 @@ #include "printing/units.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/size.h" +#include "url/gurl.h" namespace { @@ -62,11 +60,11 @@ gfx::Size GetDefaultPdfMediaSizeMicrons() { return gfx::Size(); } gfx::Size pdf_media_size = printing_context->GetPdfPaperSizeDeviceUnits(); - float deviceMicronsPerDeviceUnit = - (printing::kHundrethsMMPerInch * 10.0f) / + float device_microns_per_device_unit = + static_cast<float>(printing::kMicronsPerInch) / printing_context->settings().device_units_per_inch(); - return gfx::Size(pdf_media_size.width() * deviceMicronsPerDeviceUnit, - pdf_media_size.height() * deviceMicronsPerDeviceUnit); + return gfx::Size(pdf_media_size.width() * device_microns_per_device_unit, + pdf_media_size.height() * device_microns_per_device_unit); } std::unique_ptr<base::DictionaryValue> GetPdfCapabilities( diff --git a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h index ffa4bb4e528..0fb1a7b0315 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h +++ b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h @@ -8,8 +8,6 @@ #include <memory> #include <string> -#include "base/callback.h" -#include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/strings/string16.h" @@ -17,6 +15,7 @@ #include "ui/shell_dialogs/select_file_dialog.h" namespace base { +class FilePath; class RefCountedMemory; } 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 07e885d8b19..7ce766e59dd 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 @@ -16,6 +16,7 @@ #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/containers/flat_map.h" +#include "base/feature_list.h" #include "base/i18n/number_formatting.h" #include "base/json/json_reader.h" #include "base/lazy_instance.h" @@ -35,6 +36,7 @@ #include "chrome/browser/printing/print_view_manager.h" #include "chrome/browser/printing/printer_manager_dialog.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/signin/gaia_cookie_manager_service_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" @@ -47,6 +49,7 @@ #include "chrome/browser/ui/webui/print_preview/printer_handler.h" #include "chrome/browser/ui/webui/print_preview/sticky_settings.h" #include "chrome/common/buildflags.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/cloud_print/cloud_print_constants.h" #include "chrome/common/crash_keys.h" @@ -320,10 +323,9 @@ void ReportPrintSettingsStats(const base::DictionaryValue& settings) { ReportPrintSettingHistogram(SCALING); } - int num_pages_per_sheet = 1; - if (settings.GetInteger(printing::kSettingPagesPerSheet, - &num_pages_per_sheet) && - num_pages_per_sheet != 1) { + int pages_per_sheet = 1; + if (settings.GetInteger(printing::kSettingPagesPerSheet, &pages_per_sheet) && + pages_per_sheet != 1) { ReportPrintSettingHistogram(PAGES_PER_SHEET); } @@ -589,6 +591,7 @@ void PrintPreviewHandler::OnJavascriptDisallowed() { // Normally the handler and print preview will be destroyed together, but // this is necessary for refresh or navigation from the chrome://print page. weak_factory_.InvalidateWeakPtrs(); + preview_callbacks_.clear(); UnregisterForGaiaCookieChanges(); } @@ -600,6 +603,37 @@ PrintPreviewUI* PrintPreviewHandler::print_preview_ui() const { return static_cast<PrintPreviewUI*>(web_ui()->GetController()); } +bool PrintPreviewHandler::ShouldReceiveRendererMessage(int request_id) { + if (!IsJavascriptAllowed()) { + BadMessageReceived(); + return false; + } + + if (!base::ContainsKey(preview_callbacks_, request_id)) { + BadMessageReceived(); + return false; + } + + return true; +} + +std::string PrintPreviewHandler::GetCallbackId(int request_id) { + std::string result; + if (!IsJavascriptAllowed()) { + BadMessageReceived(); + return result; + } + + auto it = preview_callbacks_.find(request_id); + if (it == preview_callbacks_.end()) { + BadMessageReceived(); + return result; + } + result = it->second; + preview_callbacks_.erase(it); + return result; +} + void PrintPreviewHandler::HandleGetPrinters(const base::ListValue* args) { std::string callback_id; CHECK(args->GetString(0, &callback_id)); @@ -680,7 +714,8 @@ void PrintPreviewHandler::HandleGetPreview(const base::ListValue* args) { settings->GetInteger(printing::kPreviewRequestID, &request_id); CHECK_GT(request_id, -1); - preview_callbacks_.push(callback_id); + CHECK(!base::ContainsKey(preview_callbacks_, request_id)); + preview_callbacks_[request_id] = callback_id; print_preview_ui()->OnPrintPreviewRequest(request_id); // Add an additional key in order to identify |print_preview_ui| later on // when calling PrintPreviewUI::GetCurrentPrintPreviewStatus() on the IO @@ -1078,7 +1113,8 @@ void PrintPreviewHandler::SendCloudPrintEnabled() { Profile* profile = Profile::FromBrowserContext( preview_web_contents()->GetBrowserContext()); PrefService* prefs = profile->GetPrefs(); - if (prefs->GetBoolean(prefs::kCloudPrintSubmitEnabled)) { + if (prefs->GetBoolean(prefs::kCloudPrintSubmitEnabled) && + !base::FeatureList::IsEnabled(features::kCloudPrinterHandler)) { FireWebUIListener( "use-cloud-print", base::Value(GURL(cloud_devices::GetCloudPrintURL()).spec()), @@ -1117,50 +1153,41 @@ void PrintPreviewHandler::OnAddAccountToCookieCompleted( } void PrintPreviewHandler::OnPrintPreviewReady(int preview_uid, int request_id) { - if (request_id < 0 || preview_callbacks_.empty() || !IsJavascriptAllowed()) { - // invalid ID or extra message - BadMessageReceived(); + std::string callback_id = GetCallbackId(request_id); + if (callback_id.empty()) return; - } - ResolveJavascriptCallback(base::Value(preview_callbacks_.front()), - base::Value(preview_uid)); - preview_callbacks_.pop(); + ResolveJavascriptCallback(base::Value(callback_id), base::Value(preview_uid)); } -void PrintPreviewHandler::OnPrintPreviewFailed() { - if (preview_callbacks_.empty() || !IsJavascriptAllowed()) { - BadMessageReceived(); +void PrintPreviewHandler::OnPrintPreviewFailed(int request_id) { + std::string callback_id = GetCallbackId(request_id); + if (callback_id.empty()) return; - } if (!reported_failed_preview_) { reported_failed_preview_ = true; ReportUserActionHistogram(PREVIEW_FAILED); } - RejectJavascriptCallback(base::Value(preview_callbacks_.front()), + RejectJavascriptCallback(base::Value(callback_id), base::Value("PREVIEW_FAILED")); - preview_callbacks_.pop(); } -void PrintPreviewHandler::OnInvalidPrinterSettings() { - if (preview_callbacks_.empty() || !IsJavascriptAllowed()) { - BadMessageReceived(); +void PrintPreviewHandler::OnInvalidPrinterSettings(int request_id) { + std::string callback_id = GetCallbackId(request_id); + if (callback_id.empty()) return; - } - RejectJavascriptCallback(base::Value(preview_callbacks_.front()), + RejectJavascriptCallback(base::Value(callback_id), base::Value("SETTINGS_INVALID")); - preview_callbacks_.pop(); } void PrintPreviewHandler::SendPrintPresetOptions(bool disable_scaling, int copies, - int duplex) { - if (preview_callbacks_.empty() || !IsJavascriptAllowed()) { - BadMessageReceived(); + int duplex, + int request_id) { + if (!ShouldReceiveRendererMessage(request_id)) return; - } FireWebUIListener("print-preset-options", base::Value(disable_scaling), base::Value(copies), base::Value(duplex)); @@ -1169,10 +1196,8 @@ void PrintPreviewHandler::SendPrintPresetOptions(bool disable_scaling, void PrintPreviewHandler::SendPageCountReady(int page_count, int request_id, int fit_to_page_scaling) { - if (preview_callbacks_.empty() || !IsJavascriptAllowed()) { - BadMessageReceived(); + if (!ShouldReceiveRendererMessage(request_id)) return; - } FireWebUIListener("page-count-ready", base::Value(page_count), base::Value(request_id), base::Value(fit_to_page_scaling)); @@ -1180,11 +1205,10 @@ void PrintPreviewHandler::SendPageCountReady(int page_count, void PrintPreviewHandler::SendPageLayoutReady( const base::DictionaryValue& layout, - bool has_custom_page_size_style) { - if (preview_callbacks_.empty() || !IsJavascriptAllowed()) { - BadMessageReceived(); + bool has_custom_page_size_style, + int request_id) { + if (!ShouldReceiveRendererMessage(request_id)) return; - } FireWebUIListener("page-layout-ready", layout, base::Value(has_custom_page_size_style)); @@ -1193,29 +1217,19 @@ void PrintPreviewHandler::SendPageLayoutReady( void PrintPreviewHandler::SendPagePreviewReady(int page_index, int preview_uid, int preview_response_id) { - if (!IsJavascriptAllowed()) { - BadMessageReceived(); + if (!ShouldReceiveRendererMessage(preview_response_id)) return; - } FireWebUIListener("page-preview-ready", base::Value(page_index), base::Value(preview_uid), base::Value(preview_response_id)); } -void PrintPreviewHandler::OnPrintPreviewCancelled() { - if (!IsJavascriptAllowed()) { - BadMessageReceived(); - return; - } - - if (preview_callbacks_.empty()) { - BadMessageReceived(); +void PrintPreviewHandler::OnPrintPreviewCancelled(int request_id) { + std::string callback_id = GetCallbackId(request_id); + if (callback_id.empty()) return; - } - RejectJavascriptCallback(base::Value(preview_callbacks_.front()), - base::Value("CANCELLED")); - preview_callbacks_.pop(); + RejectJavascriptCallback(base::Value(callback_id), base::Value("CANCELLED")); } void PrintPreviewHandler::OnPrintRequestCancelled() { @@ -1269,6 +1283,14 @@ PrinterHandler* PrintPreviewHandler::GetPrinterHandler( } return local_printer_handler_.get(); } + if (printer_type == PrinterType::kCloudPrinter) { + // This printer handler is currently experimental. Ensure it is never + // created unless the flag is enabled. + CHECK(base::FeatureList::IsEnabled(features::kCloudPrinterHandler)); + if (!cloud_printer_handler_) + cloud_printer_handler_ = PrinterHandler::CreateForCloudPrinters(); + return cloud_printer_handler_.get(); + } NOTREACHED(); return nullptr; } @@ -1328,8 +1350,7 @@ void PrintPreviewHandler::OnPrintResult(const std::string& callback_id, void PrintPreviewHandler::RegisterForGaiaCookieChanges() { DCHECK(!gaia_cookie_manager_service_); Profile* profile = Profile::FromWebUI(web_ui()); - if (signin::IsAccountConsistencyMirrorEnabled() && - !profile->IsOffTheRecord()) { + if (AccountConsistencyModeManager::IsMirrorEnabledForProfile(profile)) { gaia_cookie_manager_service_ = GaiaCookieManagerServiceFactory::GetForProfile(profile); if (gaia_cookie_manager_service_) 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 27d7caa30c3..a6b34ca8b66 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 @@ -5,10 +5,10 @@ #ifndef CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_PRINT_PREVIEW_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_PRINT_PREVIEW_HANDLER_H_ +#include <map> #include <memory> #include <string> -#include "base/containers/queue.h" #include "base/files/file_path.h" #include "base/gtest_prod_util.h" #include "base/macros.h" @@ -42,7 +42,8 @@ enum PrinterType { kPrivetPrinter, kExtensionPrinter, kPdfPrinter, - kLocalPrinter + kLocalPrinter, + kCloudPrinter }; } // namespace printing @@ -65,14 +66,17 @@ class PrintPreviewHandler const std::string& account_id, const GoogleServiceAuthError& error) override; - // Called when print preview failed. - void OnPrintPreviewFailed(); + // Called when print preview failed. |request_id| identifies the request that + // failed. + void OnPrintPreviewFailed(int request_id); - // Called when print preview is cancelled due to a new request. - void OnPrintPreviewCancelled(); + // Called when print preview is cancelled due to a new request. |request_id| + // identifies the cancelled request. + void OnPrintPreviewCancelled(int request_id); - // Called when printer settings were invalid. - void OnInvalidPrinterSettings(); + // Called when printer settings were invalid. |request_id| identifies the + // request that requested the printer with invalid settings. + void OnInvalidPrinterSettings(int request_id); // Called when print preview is ready. void OnPrintPreviewReady(int preview_uid, int request_id); @@ -81,7 +85,10 @@ class PrintPreviewHandler void OnPrintRequestCancelled(); // Send the print preset options from the document. - void SendPrintPresetOptions(bool disable_scaling, int copies, int duplex); + void SendPrintPresetOptions(bool disable_scaling, + int copies, + int duplex, + int request_id); // Send the print preview page count and fit to page scaling void SendPageCountReady(int page_count, @@ -90,7 +97,8 @@ class PrintPreviewHandler // Send the default page layout void SendPageLayoutReady(const base::DictionaryValue& layout, - bool has_custom_page_size_style); + bool has_custom_page_size_style, + int request_id); // Notify the WebUI that the page preview is ready. void SendPagePreviewReady(int page_index, @@ -148,6 +156,18 @@ class PrintPreviewHandler PrintPreviewUI* print_preview_ui() const; + // Whether the the handler should be receiving messages from the renderer to + // forward to the Print Preview JS in response to preview request with id + // |request_id|. Kills the renderer if the handler should not be receiving + // messages, or if |request_id| does not correspond to an outstanding request. + bool ShouldReceiveRendererMessage(int request_id); + + // Gets the preview callback id associated with |request_id| and removes it + // from the |preview_callbacks_| map. Returns an empty string and kills the + // renderer if no callback is found, the handler should not be receiving + // messages, or if |request_id| is invalid. + std::string GetCallbackId(int request_id); + // Gets the list of printers. First element of |args| is the Javascript // callback, second element of |args| is the printer type to fetch. void HandleGetPrinters(const base::ListValue* args); @@ -304,6 +324,10 @@ class PrintPreviewHandler // cookie changes. GaiaCookieManagerService* gaia_cookie_manager_service_; + // Handles requests for cloud printers. Created lazily by calling + // GetPrinterHandler(). + std::unique_ptr<PrinterHandler> cloud_printer_handler_; + // Handles requests for extension printers. Created lazily by calling // GetPrinterHandler(). std::unique_ptr<PrinterHandler> extension_printer_handler_; @@ -320,7 +344,8 @@ class PrintPreviewHandler // GetPrinterHandler(). std::unique_ptr<PrinterHandler> local_printer_handler_; - base::queue<std::string> preview_callbacks_; + // Maps preview request ids to callbacks. + std::map<int, std::string> preview_callbacks_; base::WeakPtrFactory<PrintPreviewHandler> weak_factory_; 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 281cbfbf549..7e4bffcd685 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 @@ -270,7 +270,7 @@ class PrintPreviewHandlerTest : public testing::Test { web_ui(), std::move(preview_handler)); preview_ui->SetInitiatorTitle( base::ASCIIToUTF16(printing::kDummyInitiatorName)); - web_ui()->SetController(preview_ui.release()); + web_ui()->SetController(std::move(preview_ui)); } ~PrintPreviewHandlerTest() override { @@ -630,7 +630,7 @@ TEST_F(PrintPreviewHandlerTest, SendPreviewUpdates) { layout.SetKey(printing::kSettingPrintableAreaY, base::Value(17)); layout.SetKey(printing::kSettingPrintableAreaWidth, base::Value(578)); layout.SetKey(printing::kSettingPrintableAreaHeight, base::Value(734)); - handler()->SendPageLayoutReady(layout, false); + handler()->SendPageLayoutReady(layout, false, preview_request_id); // Verify that page-layout-ready webUI event was fired. AssertWebUIEventFired(*web_ui()->call_data().back(), "page-layout-ready"); @@ -653,7 +653,8 @@ TEST_F(PrintPreviewHandlerTest, SendPreviewUpdates) { // None of these should work since there has been no new preview request. // Check that there are no new web UI messages sent. size_t message_count = web_ui()->call_data().size(); - handler()->SendPageLayoutReady(base::DictionaryValue(), false); + handler()->SendPageLayoutReady(base::DictionaryValue(), false, + preview_request_id); EXPECT_EQ(message_count, web_ui()->call_data().size()); handler()->SendPageCountReady(1, 0, -1); EXPECT_EQ(message_count, web_ui()->call_data().size()); 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 9be9474eb72..4d571af9601 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 @@ -51,6 +51,7 @@ #include "printing/page_size_margins.h" #include "printing/print_job_constants.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/base/ui_base_features.h" #include "ui/gfx/geometry/rect.h" #include "ui/web_dialogs/web_dialog_delegate.h" #include "ui/web_dialogs/web_dialog_ui.h" @@ -419,6 +420,11 @@ void AddPrintPreviewFlags(content::WebUIDataSource* source, Profile* profile) { bool nup_printing_enabled = base::FeatureList::IsEnabled(features::kNupPrinting); source->AddBoolean("pagesPerSheetEnabled", nup_printing_enabled); + + bool cloud_printer_handler_enabled = + base::FeatureList::IsEnabled(features::kCloudPrinterHandler); + source->AddBoolean("cloudPrinterHandlerEnabled", + cloud_printer_handler_enabled); } void SetupPrintPreviewPlugin(content::WebUIDataSource* source) { @@ -578,7 +584,8 @@ PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui) Profile* profile = Profile::FromWebUI(web_ui); bool new_print_preview_enabled = - base::FeatureList::IsEnabled(features::kNewPrintPreview); + base::FeatureList::IsEnabled(features::kNewPrintPreview) || + base::FeatureList::IsEnabled(features::kExperimentalUi); if (new_print_preview_enabled) { content::WebUIDataSource::Add(profile, CreateNewPrintPreviewUISource(profile)); @@ -639,15 +646,15 @@ void PrintPreviewUI::SetInitialParams( } // static -void PrintPreviewUI::GetCurrentPrintPreviewStatus(int32_t preview_ui_id, - int request_id, - bool* cancel) { +void PrintPreviewUI::GetCurrentPrintPreviewStatus( + const PrintHostMsg_PreviewIds& ids, + bool* cancel) { int current_id = -1; - if (!g_print_preview_request_id_map.Get().Get(preview_ui_id, ¤t_id)) { + if (!g_print_preview_request_id_map.Get().Get(ids.ui_id, ¤t_id)) { *cancel = true; return; } - *cancel = (request_id != current_id); + *cancel = (ids.request_id != current_id); } int32_t PrintPreviewUI::GetIDForPrintPreviewUI() const { @@ -680,8 +687,8 @@ void PrintPreviewUI::OnInitiatorClosed() { } } -void PrintPreviewUI::OnPrintPreviewCancelled() { - handler_->OnPrintPreviewCancelled(); +void PrintPreviewUI::OnPrintPreviewCancelled(int request_id) { + handler_->OnPrintPreviewCancelled(request_id); } void PrintPreviewUI::OnPrintPreviewRequest(int request_id) { @@ -693,17 +700,20 @@ void PrintPreviewUI::OnPrintPreviewRequest(int request_id) { } void PrintPreviewUI::OnDidGetPreviewPageCount( - const PrintHostMsg_DidGetPreviewPageCount_Params& params) { + const PrintHostMsg_DidGetPreviewPageCount_Params& params, + int request_id) { DCHECK_GT(params.page_count, 0); if (g_testing_delegate) g_testing_delegate->DidGetPreviewPageCount(params.page_count); - handler_->SendPageCountReady(params.page_count, params.preview_request_id, + handler_->SendPageCountReady(params.page_count, request_id, params.fit_to_page_scaling); } void PrintPreviewUI::OnDidGetDefaultPageLayout( - const PageSizeMargins& page_layout, const gfx::Rect& printable_area, - bool has_custom_page_size_style) { + const PageSizeMargins& page_layout, + const gfx::Rect& printable_area, + bool has_custom_page_size_style, + int request_id) { if (page_layout.margin_top < 0 || page_layout.margin_left < 0 || page_layout.margin_bottom < 0 || page_layout.margin_right < 0 || page_layout.content_width < 0 || page_layout.content_height < 0 || @@ -725,7 +735,7 @@ void PrintPreviewUI::OnDidGetDefaultPageLayout( printable_area.width()); layout.SetInteger(printing::kSettingPrintableAreaHeight, printable_area.height()); - handler_->SendPageLayoutReady(layout, has_custom_page_size_style); + handler_->SendPageLayoutReady(layout, has_custom_page_size_style, request_id); } void PrintPreviewUI::OnDidPreviewPage(int page_number, @@ -758,12 +768,12 @@ void PrintPreviewUI::OnCancelPendingPreviewRequest() { g_print_preview_request_id_map.Get().Set(id_, -1); } -void PrintPreviewUI::OnPrintPreviewFailed() { - handler_->OnPrintPreviewFailed(); +void PrintPreviewUI::OnPrintPreviewFailed(int request_id) { + handler_->OnPrintPreviewFailed(request_id); } -void PrintPreviewUI::OnInvalidPrinterSettings() { - handler_->OnInvalidPrinterSettings(); +void PrintPreviewUI::OnInvalidPrinterSettings(int request_id) { + handler_->OnInvalidPrinterSettings(request_id); } void PrintPreviewUI::OnHidePreviewDialog() { @@ -796,9 +806,10 @@ void PrintPreviewUI::OnClosePrintPreviewDialog() { } void PrintPreviewUI::OnSetOptionsFromDocument( - const PrintHostMsg_SetOptionsFromDocument_Params& params) { + const PrintHostMsg_SetOptionsFromDocument_Params& params, + int request_id) { handler_->SendPrintPresetOptions(params.is_scaling_disabled, params.copies, - params.duplex); + params.duplex, request_id); } // static diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.h b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.h index 87d879753fe..336b9b82b34 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.h +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.h @@ -19,6 +19,7 @@ class PrintPreviewHandler; struct PrintHostMsg_DidGetPreviewPageCount_Params; +struct PrintHostMsg_PreviewIds; struct PrintHostMsg_RequestPrintPreview_Params; struct PrintHostMsg_SetOptionsFromDocument_Params; @@ -74,11 +75,10 @@ class PrintPreviewUI : public ConstrainedWebDialogUI { content::WebContents* print_preview_dialog, const PrintHostMsg_RequestPrintPreview_Params& params); - // Determines whether to cancel a print preview request based on - // |preview_ui_id| and |request_id|. + // Determines whether to cancel a print preview request based on the request + // and ui ids in |ids|. // Can be called from any thread. - static void GetCurrentPrintPreviewStatus(int32_t preview_ui_id, - int request_id, + static void GetCurrentPrintPreviewStatus(const PrintHostMsg_PreviewIds& ids, bool* cancel); // Returns an id to uniquely identify this PrintPreviewUI. @@ -89,13 +89,15 @@ class PrintPreviewUI : public ConstrainedWebDialogUI { // Notifies the Web UI about the page count of the request preview. void OnDidGetPreviewPageCount( - const PrintHostMsg_DidGetPreviewPageCount_Params& params); + const PrintHostMsg_DidGetPreviewPageCount_Params& params, + int request_id); // Notifies the Web UI of the default page layout according to the currently // selected printer and page size. void OnDidGetDefaultPageLayout(const printing::PageSizeMargins& page_layout, const gfx::Rect& printable_area, - bool has_custom_page_size_style); + bool has_custom_page_size_style, + int request_id); // Notifies the Web UI that the 0-based page |page_number| has been rendered. // |preview_request_id| indicates wich request resulted in this response. @@ -107,23 +109,25 @@ class PrintPreviewUI : public ConstrainedWebDialogUI { void OnPreviewDataIsAvailable(int expected_pages_count, int preview_request_id); - // Notifies the Web UI that the print preview failed to render. - void OnPrintPreviewFailed(); + // Notifies the Web UI that the print preview failed to render for the request + // with id = |request_id|. + void OnPrintPreviewFailed(int request_id); // Notified the Web UI that this print preview dialog's RenderProcess has been // closed, which may occur for several reasons, e.g. tab closure or crash. void OnPrintPreviewDialogClosed(); - // Notifies the Web UI that the preview request was cancelled. - void OnPrintPreviewCancelled(); + // Notifies the Web UI that the preview request identified by |request_id| + // was cancelled. + void OnPrintPreviewCancelled(int request_id); // Notifies the Web UI that initiator is closed, so we can disable all the // controls that need the initiator for generating the preview data. void OnInitiatorClosed(); // Notifies the Web UI that the printer is unavailable or its settings are - // invalid. - void OnInvalidPrinterSettings(); + // invalid. |request_id| is the preview request id with the invalid printer. + void OnInvalidPrinterSettings(int request_id); // Notifies the Web UI to cancel the pending preview request. virtual void OnCancelPendingPreviewRequest(); @@ -136,7 +140,8 @@ class PrintPreviewUI : public ConstrainedWebDialogUI { // Notifies the WebUI to set print preset options from source PDF. void OnSetOptionsFromDocument( - const PrintHostMsg_SetOptionsFromDocument_Params& params); + const PrintHostMsg_SetOptionsFromDocument_Params& params, + int request_id); // Allows tests to wait until the print preview dialog is loaded. class TestingDelegate { diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc index 02e979f5559..4f8c3977135 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc @@ -17,6 +17,7 @@ #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "components/prefs/pref_service.h" +#include "components/printing/common/print_messages.h" #include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/site_instance.h" @@ -203,7 +204,8 @@ TEST_F(PrintPreviewUIUnitTest, GetCurrentPrintPreviewStatus) { // Test with invalid |preview_ui_addr|. bool cancel = false; const int32_t kInvalidId = -5; - preview_ui->GetCurrentPrintPreviewStatus(kInvalidId, 0, &cancel); + preview_ui->GetCurrentPrintPreviewStatus( + PrintHostMsg_PreviewIds(0, kInvalidId), &cancel); EXPECT_TRUE(cancel); const int kFirstRequestId = 1000; @@ -213,24 +215,24 @@ TEST_F(PrintPreviewUIUnitTest, GetCurrentPrintPreviewStatus) { // Test with kFirstRequestId. preview_ui->OnPrintPreviewRequest(kFirstRequestId); cancel = true; - preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kFirstRequestId, - &cancel); + preview_ui->GetCurrentPrintPreviewStatus( + PrintHostMsg_PreviewIds(kFirstRequestId, preview_ui_addr), &cancel); EXPECT_FALSE(cancel); cancel = false; - preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kSecondRequestId, - &cancel); + preview_ui->GetCurrentPrintPreviewStatus( + PrintHostMsg_PreviewIds(kSecondRequestId, preview_ui_addr), &cancel); EXPECT_TRUE(cancel); // Test with kSecondRequestId. preview_ui->OnPrintPreviewRequest(kSecondRequestId); cancel = false; - preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kFirstRequestId, - &cancel); + preview_ui->GetCurrentPrintPreviewStatus( + PrintHostMsg_PreviewIds(kFirstRequestId, preview_ui_addr), &cancel); EXPECT_TRUE(cancel); cancel = true; - preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kSecondRequestId, - &cancel); + preview_ui->GetCurrentPrintPreviewStatus( + PrintHostMsg_PreviewIds(kSecondRequestId, preview_ui_addr), &cancel); EXPECT_FALSE(cancel); } diff --git a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.cc index af0d09391cb..4ce4aca1707 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.cc @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/print_preview/printer_handler.h" #include "build/buildflag.h" +#include "chrome/browser/ui/webui/print_preview/cloud_printer_handler.h" #include "chrome/browser/ui/webui/print_preview/extension_printer_handler.h" #include "chrome/browser/ui/webui/print_preview/pdf_printer_handler.h" #include "chrome/common/buildflags.h" @@ -20,6 +21,11 @@ #endif // static +std::unique_ptr<PrinterHandler> PrinterHandler::CreateForCloudPrinters() { + return std::make_unique<CloudPrinterHandler>(); +} + +// static std::unique_ptr<PrinterHandler> PrinterHandler::CreateForExtensionPrinters( Profile* profile) { return std::make_unique<ExtensionPrinterHandler>(profile); diff --git a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h index 66f5f29df0c..666a368452b 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h +++ b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h @@ -60,6 +60,10 @@ class PrinterHandler { using GetPrinterInfoCallback = base::OnceCallback<void(const base::DictionaryValue& printer_info)>; + // Creates an instance of a PrinterHandler for cloud printers. + // Note: Implementation currently empty, see https://crbug.com/829414 + static std::unique_ptr<PrinterHandler> CreateForCloudPrinters(); + // Creates an instance of a PrinterHandler for extension printers. static std::unique_ptr<PrinterHandler> CreateForExtensionPrinters( Profile* profile); diff --git a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc index be5aedb2f8c..77e5b23a2f3 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc @@ -19,10 +19,10 @@ #include "base/timer/timer.h" #include "chrome/browser/printing/cloud_print/privet_constants.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/webui/print_preview/print_preview_utils.h" #include "chrome/common/chrome_switches.h" -#include "components/signin/core/browser/signin_manager.h" +#include "services/identity/public/cpp/identity_manager.h" #include "ui/gfx/geometry/size.h" namespace { @@ -251,11 +251,11 @@ void PrivetPrinterHandler::StartPrint( privet_local_print_operation_->SetPageSize(page_size); privet_local_print_operation_->SetData(print_data); - SigninManagerBase* signin_manager = - SigninManagerFactory::GetForProfileIfExists(profile_); - if (signin_manager) { + identity::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfileIfExists(profile_); + if (identity_manager) { privet_local_print_operation_->SetUsername( - signin_manager->GetAuthenticatedAccountInfo().email); + identity_manager->GetPrimaryAccountInfo().email); } privet_local_print_operation_->Start(); 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 5aa829a4eeb..c13d5fb59d5 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 @@ -7,11 +7,12 @@ #include "base/metrics/histogram_functions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/safe_browsing/chrome_password_protection_service.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" +#include "components/safe_browsing/password_protection/password_protection_service.h" #include "components/strings/grit/components_strings.h" +#include "components/url_formatter/url_formatter.h" #include "components/user_prefs/user_prefs.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_entry.h" @@ -20,6 +21,11 @@ #include "mojo/public/cpp/bindings/binding.h" #include "ui/base/l10n/l10n_util.h" +namespace safe_browsing { +using PasswordReuseEvent = + safe_browsing::LoginReputationClientRequest::PasswordReuseEvent; +} + namespace { constexpr char kStringTypeUMAName[] = "PasswordProtection.InterstitialString"; @@ -39,8 +45,11 @@ class ResetPasswordHandlerImpl : public mojom::ResetPasswordHandler { public: ResetPasswordHandlerImpl( content::WebContents* web_contents, + safe_browsing::ReusedPasswordType password_type, mojo::InterfaceRequest<mojom::ResetPasswordHandler> request) - : web_contents_(web_contents), binding_(this, std::move(request)) { + : web_contents_(web_contents), + password_type_(password_type), + binding_(this, std::move(request)) { DCHECK(web_contents); } @@ -54,23 +63,52 @@ class ResetPasswordHandlerImpl : public mojom::ResetPasswordHandler { ChromePasswordProtectionService::GetPasswordProtectionService(profile); if (service) { service->OnUserAction( - web_contents_, safe_browsing::PasswordProtectionService::INTERSTITIAL, + web_contents_, password_type_, + safe_browsing::PasswordProtectionService::INTERSTITIAL, safe_browsing::PasswordProtectionService::CHANGE_PASSWORD); } } private: content::WebContents* web_contents_; + safe_browsing::ReusedPasswordType password_type_; mojo::Binding<mojom::ResetPasswordHandler> binding_; DISALLOW_COPY_AND_ASSIGN(ResetPasswordHandlerImpl); }; +// Gets the reused password type from post data, or returns +// REUSED_PASSWORD_TYPE_UNKNOWN if post data is not available. +safe_browsing::ReusedPasswordType GetPasswordType( + content::WebContents* web_contents) { + content::NavigationEntry* nav_entry = + web_contents->GetController().GetPendingEntry(); + if (!nav_entry || !nav_entry->GetHasPostData()) + return safe_browsing::PasswordReuseEvent::REUSED_PASSWORD_TYPE_UNKNOWN; + auto& post_data = nav_entry->GetPostData()->elements()->at(0); + int post_data_int = -1; + if (base::StringToInt(std::string(post_data.bytes(), post_data.length()), + &post_data_int)) { + return static_cast<safe_browsing::ReusedPasswordType>(post_data_int); + } + + return safe_browsing::PasswordReuseEvent::REUSED_PASSWORD_TYPE_UNKNOWN; +} + +// Properly format host name based on text direction. +base::string16 GetFormattedHostName(const std::string host_name) { + base::string16 host = url_formatter::IDNToUnicode(host_name); + if (base::i18n::IsRTL()) + base::i18n::WrapStringWithLTRFormatting(&host); + return host; +} + } // namespace ResetPasswordUI::ResetPasswordUI(content::WebUI* web_ui) : ui::MojoWebUIController(web_ui) { base::DictionaryValue load_time_data; + password_type_ = GetPasswordType(web_ui->GetWebContents()); PopulateStrings(web_ui->GetWebContents(), &load_time_data); std::unique_ptr<content::WebUIDataSource> html_source( content::WebUIDataSource::Create(chrome::kChromeUIResetPasswordHost)); @@ -93,39 +131,47 @@ ResetPasswordUI::~ResetPasswordUI() {} void ResetPasswordUI::BindResetPasswordHandler( mojom::ResetPasswordHandlerRequest request) { ui_handler_ = std::make_unique<ResetPasswordHandlerImpl>( - web_ui()->GetWebContents(), std::move(request)); + web_ui()->GetWebContents(), password_type_, std::move(request)); } void ResetPasswordUI::PopulateStrings(content::WebContents* web_contents, base::DictionaryValue* load_time_data) { - content::NavigationEntry* nav_entry = - web_contents->GetController().GetPendingEntry(); std::string org_name = safe_browsing::ChromePasswordProtectionService:: GetPasswordProtectionService( Profile::FromBrowserContext(web_contents->GetBrowserContext())) - ->GetOrganizationName(); - bool has_referrer = nav_entry->GetReferrer().url.is_valid(); - int heading_string_id = has_referrer ? IDS_RESET_PASSWORD_WARNING_HEADING - : IDS_RESET_PASSWORD_HEADING; + ->GetOrganizationName(password_type_); + bool known_password_type = + password_type_ != + safe_browsing::PasswordReuseEvent::REUSED_PASSWORD_TYPE_UNKNOWN; + if (!known_password_type) { + base::UmaHistogramEnumeration( + safe_browsing::kInterstitialActionByUserNavigationHistogram, + safe_browsing::PasswordProtectionService::SHOWN, + safe_browsing::PasswordProtectionService::MAX_ACTION); + } + int heading_string_id = known_password_type + ? IDS_RESET_PASSWORD_WARNING_HEADING + : IDS_RESET_PASSWORD_HEADING; base::string16 explanation_paragraph_string; if (org_name.empty()) { explanation_paragraph_string = l10n_util::GetStringUTF16( - has_referrer ? IDS_RESET_PASSWORD_WARNING_EXPLANATION_PARAGRAPH - : IDS_RESET_PASSWORD_EXPLANATION_PARAGRAPH); + known_password_type ? IDS_RESET_PASSWORD_WARNING_EXPLANATION_PARAGRAPH + : IDS_RESET_PASSWORD_EXPLANATION_PARAGRAPH); base::UmaHistogramEnumeration( kStringTypeUMAName, - has_referrer ? WARNING_NO_ORG_NAME : GENERIC_NO_ORG_NAME, + known_password_type ? WARNING_NO_ORG_NAME : GENERIC_NO_ORG_NAME, STRING_TYPE_COUNT); } else { + base::string16 formatted_org_name = GetFormattedHostName(org_name); explanation_paragraph_string = l10n_util::GetStringFUTF16( - has_referrer + known_password_type ? IDS_RESET_PASSWORD_WARNING_EXPLANATION_PARAGRAPH_WITH_ORG_NAME : IDS_RESET_PASSWORD_EXPLANATION_PARAGRAPH_WITH_ORG_NAME, - base::UTF8ToUTF16(org_name)); + formatted_org_name); base::UmaHistogramEnumeration( kStringTypeUMAName, - has_referrer ? WARNING_WITH_ORG_NAME : GENERIC_WITH_ORG_NAME, + known_password_type ? WARNING_WITH_ORG_NAME : GENERIC_WITH_ORG_NAME, STRING_TYPE_COUNT); } diff --git a/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.h b/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.h index 41234d359f4..3519b553200 100644 --- a/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.h +++ b/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.h @@ -6,6 +6,7 @@ #define CHROME_BROWSER_UI_WEBUI_RESET_PASSWORD_RESET_PASSWORD_UI_H_ #include "base/macros.h" +#include "chrome/browser/safe_browsing/chrome_password_protection_service.h" #include "chrome/browser/ui/webui/reset_password/reset_password.mojom.h" #include "ui/webui/mojo_web_ui_controller.h" @@ -30,6 +31,7 @@ class ResetPasswordUI : public ui::MojoWebUIController { base::DictionaryValue* load_time_data); std::unique_ptr<mojom::ResetPasswordHandler> ui_handler_; + safe_browsing::ReusedPasswordType password_type_; DISALLOW_COPY_AND_ASSIGN(ResetPasswordUI); }; diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.cc b/chromium/chrome/browser/ui/webui/settings/about_handler.cc index 8bd560132b1..067049dbd29 100644 --- a/chromium/chrome/browser/ui/webui/settings/about_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/about_handler.cc @@ -66,6 +66,7 @@ #include "chrome/browser/ui/webui/help/version_updater_chromeos.h" #include "chromeos/chromeos_switches.h" #include "chromeos/dbus/power_manager_client.h" +#include "chromeos/dbus/util/version_loader.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/system/statistics_provider.h" @@ -321,6 +322,11 @@ AboutHandler* AboutHandler::Create(content::WebUIDataSource* html_source, IDS_ABOUT_CROS_VERSION_LICENSE, base::ASCIIToUTF16(chrome::kChromeUIOSCreditsURL)); html_source->AddString("aboutProductOsLicense", os_license); + base::string16 os_with_linux_license = l10n_util::GetStringFUTF16( + IDS_ABOUT_CROS_WITH_LINUX_VERSION_LICENSE, + base::ASCIIToUTF16(chrome::kChromeUIOSCreditsURL)); + html_source->AddString("aboutProductOsWithLinuxLicense", + os_with_linux_license); html_source->AddBoolean("aboutEnterpriseManaged", IsEnterpriseManaged()); base::Time build_time = base::SysInfo::GetLsbReleaseTime(); @@ -646,6 +652,7 @@ void AboutHandler::RequestUpdate() { void AboutHandler::SetUpdateStatus(VersionUpdater::Status status, int progress, + bool rollback, const std::string& version, int64_t size, const base::string16& message) { @@ -656,6 +663,7 @@ void AboutHandler::SetUpdateStatus(VersionUpdater::Status status, event->SetString("status", UpdateStatusToString(status)); event->SetString("message", message); event->SetInteger("progress", progress); + event->SetBoolean("rollback", rollback); event->SetString("version", version); // DictionaryValue does not support int64_t, so convert to string. event->SetString("size", base::Int64ToString(size)); diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.h b/chromium/chrome/browser/ui/webui/settings/about_handler.h index 3cbfa4a8d4b..4c8ae08a292 100644 --- a/chromium/chrome/browser/ui/webui/settings/about_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/about_handler.h @@ -22,7 +22,6 @@ #if defined(OS_CHROMEOS) #include "base/task/cancelable_task_tracker.h" #include "chrome/browser/chromeos/tpm_firmware_update.h" -#include "chromeos/system/version_loader.h" #endif // defined(OS_CHROMEOS) namespace base { @@ -128,6 +127,7 @@ class AboutHandler : public settings::SettingsPageUIHandler, // Callback method which forwards status updates to the page. void SetUpdateStatus(VersionUpdater::Status status, int progress, + bool rollback, const std::string& version, int64_t size, const base::string16& fail_message); 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 6d64f7bbd08..090962aebcf 100644 --- a/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc @@ -54,6 +54,8 @@ void ChangePasswordHandler::HandleInitialize(const base::ListValue* args) { void ChangePasswordHandler::HandleChangePassword(const base::ListValue* args) { service_->OnUserAction( web_ui()->GetWebContents(), + safe_browsing::LoginReputationClientRequest::PasswordReuseEvent:: + SIGN_IN_PASSWORD, safe_browsing::PasswordProtectionService::CHROME_SETTINGS, safe_browsing::PasswordProtectionService::CHANGE_PASSWORD); } diff --git a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc index f07c59b79c0..271e31ac2b6 100644 --- a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc @@ -44,24 +44,27 @@ std::unique_ptr<base::ListValue> GetFilesAsListStorage( return value; } -// Returns a ListValue containing a copy of the registry keys stored in -// |registry_keys|. -std::unique_ptr<base::ListValue> GetRegistryKeysAsListStorage( - const std::set<base::string16>& registry_keys) { +// Returns a ListValue containing a copy of the strings stored in |string_set|. +std::unique_ptr<base::ListValue> GetStringSetAsListStorage( + const std::set<base::string16>& string_set) { auto value = std::make_unique<base::ListValue>(); - for (const base::string16& key : registry_keys) - value->AppendString(key); + for (const base::string16& string : string_set) + value->AppendString(string); return value; } base::DictionaryValue GetScannerResultsAsDictionary( - const safe_browsing::ChromeCleanerScannerResults& scanner_results) { + const safe_browsing::ChromeCleanerScannerResults& scanner_results, + Profile* profile) { base::DictionaryValue value; value.SetList("files", GetFilesAsListStorage(scanner_results.files_to_delete())); value.SetList("registryKeys", - GetRegistryKeysAsListStorage(scanner_results.registry_keys())); + GetStringSetAsListStorage(scanner_results.registry_keys())); + std::set<base::string16> extensions; + scanner_results.FetchExtensionNames(profile, &extensions); + value.SetList("extensions", GetStringSetAsListStorage(extensions)); return value; } @@ -178,7 +181,7 @@ void ChromeCleanupHandler::OnInfected( const safe_browsing::ChromeCleanerScannerResults& scanner_results) { FireWebUIListener("chrome-cleanup-on-infected", base::Value(is_powered_by_partner), - GetScannerResultsAsDictionary(scanner_results)); + GetScannerResultsAsDictionary(scanner_results, profile_)); } void ChromeCleanupHandler::OnCleaning( @@ -186,7 +189,7 @@ void ChromeCleanupHandler::OnCleaning( const safe_browsing::ChromeCleanerScannerResults& scanner_results) { FireWebUIListener("chrome-cleanup-on-cleaning", base::Value(is_powered_by_partner), - GetScannerResultsAsDictionary(scanner_results)); + GetScannerResultsAsDictionary(scanner_results, profile_)); } void ChromeCleanupHandler::OnRebootRequired() { @@ -194,14 +197,9 @@ void ChromeCleanupHandler::OnRebootRequired() { } void ChromeCleanupHandler::OnLogsEnabledChanged(bool logs_enabled) { - // Logs are considered managed if the logs themselves are managed or if the - // entire cleanup feature is disabled by policy. - PrefService* local_state = g_browser_process->local_state(); - bool is_managed = !controller_->IsAllowedByPolicy() || - (local_state && local_state->IsManagedPreference( - prefs::kSwReporterReportingEnabled)); FireWebUIListener("chrome-cleanup-upload-permission-change", - base::Value(is_managed), base::Value(logs_enabled)); + base::Value(controller_->IsReportingManagedByPolicy()), + base::Value(logs_enabled)); } void ChromeCleanupHandler::OnLogsEnabledPrefChanged() { 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 aba28c25d50..46968303b50 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 @@ -14,6 +14,7 @@ #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h" #include "chromeos/account_manager/account_manager.h" #include "chromeos/account_manager/account_manager_factory.h" #include "components/signin/core/browser/account_tracker_service.h" @@ -29,15 +30,28 @@ AccountManagerUIHandler::AccountManagerUIHandler( AccountTrackerService* account_tracker_service) : account_manager_(account_manager), account_tracker_service_(account_tracker_service), - weak_factory_(this) {} + weak_factory_(this) { + DCHECK(account_manager_); + DCHECK(account_tracker_service_); -AccountManagerUIHandler::~AccountManagerUIHandler() = default; + account_manager_->AddObserver(this); + account_tracker_service_->AddObserver(this); +} + +AccountManagerUIHandler::~AccountManagerUIHandler() { + account_manager_->RemoveObserver(this); + account_tracker_service_->RemoveObserver(this); +} void AccountManagerUIHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getAccounts", base::BindRepeating(&AccountManagerUIHandler::HandleGetAccounts, weak_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "addAccount", + base::BindRepeating(&AccountManagerUIHandler::HandleAddAccount, + weak_factory_.GetWeakPtr())); } void AccountManagerUIHandler::HandleGetAccounts(const base::ListValue* args) { @@ -71,6 +85,12 @@ void AccountManagerUIHandler::GetAccountsCallbackHandler( account_tracker_service_->FindAccountInfoByGaiaId(account_key.id); DCHECK(!account_info.IsEmpty()); + if (account_info.full_name.empty()) { + // Account info has not been fully fetched yet from GAIA. Ignore this + // account. + continue; + } + base::DictionaryValue account; account.SetString("fullName", account_info.full_name); account.SetString("email", account_info.email); @@ -96,9 +116,52 @@ void AccountManagerUIHandler::GetAccountsCallbackHandler( ResolveJavascriptCallback(callback_id, accounts); } +void AccountManagerUIHandler::HandleAddAccount(const base::ListValue* args) { + AllowJavascript(); + InlineLoginHandlerDialogChromeOS::Show(); +} + void AccountManagerUIHandler::OnJavascriptAllowed() {} void AccountManagerUIHandler::OnJavascriptDisallowed() {} +// |AccountManager::Observer| overrides. +// Note: We need to listen on |AccountManager| in addition to +// |AccountTrackerService| because there is no guarantee that |AccountManager| +// (our source of truth) will have a newly added account by the time +// |AccountTrackerService| has it. +void AccountManagerUIHandler::OnTokenUpserted( + const AccountManager::AccountKey& account_key) { + RefreshUI(); +} + +void AccountManagerUIHandler::OnAccountRemoved( + const AccountManager::AccountKey& account_key) { + RefreshUI(); +} + +// |AccountTrackerService::Observer| overrides. +// For newly added accounts, |AccountTrackerService| may take some time to +// fetch user's full name and account image. Whenever that is completed, we +// may need to update the UI with this new set of information. +// Note that we may be listening to |AccountTrackerService| but we still +// consider |AccountManager| to be the source of truth for account list. +void AccountManagerUIHandler::OnAccountUpdated(const AccountInfo& info) { + RefreshUI(); +} + +void AccountManagerUIHandler::OnAccountImageUpdated( + const std::string& account_id, + const gfx::Image& image) { + RefreshUI(); +} + +void AccountManagerUIHandler::OnAccountRemoved(const AccountInfo& account_key) { +} + +void AccountManagerUIHandler::RefreshUI() { + FireWebUIListener("accounts-changed"); +} + } // namespace settings } // namespace chromeos 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 95316717231..078a51cb189 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 @@ -5,19 +5,21 @@ #ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_ACCOUNT_MANAGER_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_ACCOUNT_MANAGER_HANDLER_H_ +#include <string> #include <vector> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "chromeos/account_manager/account_manager.h" - -class AccountTrackerService; +#include "components/signin/core/browser/account_tracker_service.h" namespace chromeos { namespace settings { -class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler { +class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler, + public AccountManager::Observer, + public AccountTrackerService::Observer { public: // Accepts non-owning pointers to |AccountManager| and // |AccountTrackerService|. Both of these must outlive |this| instance. @@ -30,15 +32,33 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler { void OnJavascriptAllowed() override; void OnJavascriptDisallowed() override; + // |AccountManager::Observer| overrides. + // |AccountManager| is considered to be the source of truth for account + // information. + void OnTokenUpserted(const AccountManager::AccountKey& account_key) override; + void OnAccountRemoved(const AccountManager::AccountKey& account_key) override; + + // |AccountTrackerService::Observer| overrides. + void OnAccountUpdated(const AccountInfo& info) override; + void OnAccountImageUpdated(const std::string& account_id, + const gfx::Image& image) override; + void OnAccountRemoved(const AccountInfo& account_key) override; + private: // WebUI "getAccounts" message callback. void HandleGetAccounts(const base::ListValue* args); + // WebUI "addAccount" message callback. + void HandleAddAccount(const base::ListValue* args); + // |AccountManager::GetAccounts| callback. void GetAccountsCallbackHandler( base::Value callback_id, std::vector<AccountManager::AccountKey> account_keys); + // Refreshes the UI. + void RefreshUI(); + // A non-owning pointer to |AccountManager|. AccountManager* const account_manager_; 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 1a3824cb28e..20b842fa019 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 @@ -57,14 +57,20 @@ void AndroidAppsHandler::OnJavascriptDisallowed() { void AndroidAppsHandler::OnAppRegistered( const std::string& app_id, const ArcAppListPrefs::AppInfo& app_info) { - OnAppChanged(app_id); + HandleAppChanged(app_id); +} + +void AndroidAppsHandler::OnAppStatesChanged( + const std::string& app_id, + const ArcAppListPrefs::AppInfo& app_info) { + HandleAppChanged(app_id); } void AndroidAppsHandler::OnAppRemoved(const std::string& app_id) { - OnAppChanged(app_id); + HandleAppChanged(app_id); } -void AndroidAppsHandler::OnAppChanged(const std::string& app_id) { +void AndroidAppsHandler::HandleAppChanged(const std::string& app_id) { if (app_id != arc::kSettingsAppId) return; SendAndroidAppsInfo(); 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 94d6e16c132..cb89bc38224 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 @@ -37,17 +37,19 @@ class AndroidAppsHandler : public ::settings::SettingsPageUIHandler, void OnJavascriptDisallowed() override; // ArcAppListPrefs::Observer - void OnAppRemoved(const std::string& app_id) override; void OnAppRegistered(const std::string& app_id, const ArcAppListPrefs::AppInfo& app_info) override; + void OnAppStatesChanged(const std::string& app_id, + const ArcAppListPrefs::AppInfo& app_info) override; + void OnAppRemoved(const std::string& app_id) override; // arc::ArcSessionManager::Observer: void OnArcPlayStoreEnabledChanged(bool enabled) override; private: std::unique_ptr<base::DictionaryValue> BuildAndroidAppsInfo(); - void OnAppChanged(const std::string& app_id); void HandleRequestAndroidAppsInfo(const base::ListValue* args); + void HandleAppChanged(const std::string& app_id); void SendAndroidAppsInfo(); void ShowAndroidAppsSettings(const base::ListValue* args); void ShowAndroidManageAppLinks(const base::ListValue* args); 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 03a08cad53e..4b100018022 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc @@ -31,12 +31,14 @@ void CrostiniHandler::RegisterMessages() { void CrostiniHandler::HandleRequestCrostiniInstallerView( const base::ListValue* args) { AllowJavascript(); - ShowCrostiniInstallerView(Profile::FromWebUI(web_ui())); + ShowCrostiniInstallerView(Profile::FromWebUI(web_ui()), + CrostiniUISurface::kSettings); } void CrostiniHandler::HandleRequestRemoveCrostini(const base::ListValue* args) { AllowJavascript(); - ShowCrostiniUninstallerView(Profile::FromWebUI(web_ui())); + ShowCrostiniUninstallerView(Profile::FromWebUI(web_ui()), + CrostiniUISurface::kSettings); } } // namespace settings 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 98fc7863982..3c61e3ba330 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 @@ -220,8 +220,7 @@ CupsPrintersHandler::CupsPrintersHandler(content::WebUI* webui) ppd_provider_(CreatePpdProvider(profile_)), printer_configurer_(PrinterConfigurer::Create(profile_)), printers_manager_( - CupsPrintersManagerFactory::GetInstance()->GetForBrowserContext( - profile_)), + CupsPrintersManagerFactory::GetForBrowserContext(profile_)), printers_manager_observer_(this), weak_factory_(this) {} @@ -334,7 +333,8 @@ void CupsPrintersHandler::HandleUpdateCupsPrinter(const base::ListValue* args) { // TODO(xdai): Replace "on-add-cups-printer" callback with Promise resolve // function. - FireWebUIListener("on-add-cups-printer", base::Value(true), + FireWebUIListener("on-add-cups-printer", + base::Value(PrinterSetupResult::kSuccess), base::Value(printer_name)); } 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 04fe8449120..9b221939c81 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 @@ -24,6 +24,8 @@ #include "chrome/browser/browsing_data/browsing_data_local_storage_helper.h" #include "chrome/browser/browsing_data/browsing_data_service_worker_helper.h" #include "chrome/browser/chromeos/arc/arc_util.h" +#include "chrome/browser/chromeos/crostini/crostini_manager.h" +#include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/file_manager/path_util.h" #include "chrome/browser/platform_util.h" @@ -64,7 +66,7 @@ const int64_t kSpaceLowBytes = 1 * 1024 * 1024 * 1024; } // namespace -StorageHandler::StorageHandler() +StorageHandler::StorageHandler(Profile* profile) : browser_cache_size_(-1), has_browser_cache_size_(false), browser_site_data_size_(-1), @@ -73,7 +75,9 @@ StorageHandler::StorageHandler() updating_drive_cache_size_(false), updating_browsing_data_size_(false), updating_android_size_(false), + updating_crostini_size_(false), updating_other_users_size_(false), + profile_(profile), weak_ptr_factory_(this) {} StorageHandler::~StorageHandler() { @@ -106,26 +110,23 @@ void StorageHandler::HandleUpdateStorageInfo(const base::ListValue* args) { UpdateDownloadsSize(); UpdateDriveCacheSize(); UpdateBrowsingDataSize(); - UpdateOtherUsersSize(); UpdateAndroidSize(); + UpdateCrostiniSize(); + UpdateOtherUsersSize(); } void StorageHandler::HandleOpenDownloads( const base::ListValue* unused_args) { - Profile* const profile = Profile::FromWebUI(web_ui()); const base::FilePath downloads_path = - file_manager::util::GetDownloadsFolderForProfile(profile); - platform_util::OpenItem( - profile, - downloads_path, - platform_util::OPEN_FOLDER, - platform_util::OpenOperationCallback()); + file_manager::util::GetDownloadsFolderForProfile(profile_); + platform_util::OpenItem(profile_, downloads_path, platform_util::OPEN_FOLDER, + platform_util::OpenOperationCallback()); } void StorageHandler::HandleOpenArcStorage( const base::ListValue* unused_args) { - auto* arc_storage_manager = arc::ArcStorageManager::GetForBrowserContext( - Profile::FromWebUI(web_ui())); + auto* arc_storage_manager = + arc::ArcStorageManager::GetForBrowserContext(profile_); if (arc_storage_manager) arc_storage_manager->OpenPrivateVolumeSettings(); } @@ -133,17 +134,20 @@ void StorageHandler::HandleOpenArcStorage( void StorageHandler::HandleClearDriveCache( const base::ListValue* unused_args) { drive::FileSystemInterface* const file_system = - drive::util::GetFileSystemByProfile(Profile::FromWebUI(web_ui())); + drive::util::GetFileSystemByProfile(profile_); file_system->FreeDiskSpaceIfNeededFor( std::numeric_limits<int64_t>::max(), // Removes as much as possible. base::Bind(&StorageHandler::OnClearDriveCacheDone, weak_ptr_factory_.GetWeakPtr())); } +void StorageHandler::OnClearDriveCacheDone(bool /*success*/) { + UpdateDriveCacheSize(); +} + void StorageHandler::UpdateSizeStat() { - Profile* const profile = Profile::FromWebUI(web_ui()); const base::FilePath downloads_path = - file_manager::util::GetDownloadsFolderForProfile(profile); + file_manager::util::GetDownloadsFolderForProfile(profile_); int64_t* total_size = new int64_t(0); int64_t* available_size = new int64_t(0); @@ -179,9 +183,8 @@ void StorageHandler::UpdateDownloadsSize() { return; updating_downloads_size_ = true; - Profile* const profile = Profile::FromWebUI(web_ui()); const base::FilePath downloads_path = - file_manager::util::GetDownloadsFolderForProfile(profile); + file_manager::util::GetDownloadsFolderForProfile(profile_); base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, @@ -197,17 +200,17 @@ void StorageHandler::OnGetDownloadsSize(int64_t size) { } void StorageHandler::UpdateDriveCacheSize() { - if (updating_drive_cache_size_) - return; - drive::FileSystemInterface* const file_system = - drive::util::GetFileSystemByProfile(Profile::FromWebUI(web_ui())); + drive::util::GetFileSystemByProfile(profile_); if (!file_system) return; - // Shows the item "Offline cache" and start calculating size. - FireWebUIListener("storage-drive-enabled-changed", base::Value(true)); + if (updating_drive_cache_size_) + return; updating_drive_cache_size_ = true; + + // Shows the item "Offline cache" and starts calculating size. + FireWebUIListener("storage-drive-enabled-changed", base::Value(true)); file_system->CalculateCacheSize(base::Bind( &StorageHandler::OnGetDriveCacheSize, weak_ptr_factory_.GetWeakPtr())); } @@ -225,35 +228,33 @@ void StorageHandler::UpdateBrowsingDataSize() { has_browser_cache_size_ = false; has_browser_site_data_size_ = false; - Profile* const profile = Profile::FromWebUI(web_ui()); // Fetch the size of http cache in browsing data. - // ConditionalCacheCountingHelper deletes itself when it is done. - browsing_data::ConditionalCacheCountingHelper::CreateForRange( - content::BrowserContext::GetDefaultStoragePartition(profile), - base::Time(), base::Time::Max()) - ->CountAndDestroySelfWhenFinished(base::Bind( - &StorageHandler::OnGetCacheSize, weak_ptr_factory_.GetWeakPtr())); + browsing_data::ConditionalCacheCountingHelper::Count( + content::BrowserContext::GetDefaultStoragePartition(profile_), + base::Time(), base::Time::Max(), + base::BindOnce(&StorageHandler::OnGetCacheSize, + weak_ptr_factory_.GetWeakPtr())); // Fetch the size of site data in browsing data. if (!site_data_size_collector_.get()) { content::StoragePartition* storage_partition = - content::BrowserContext::GetDefaultStoragePartition(profile); + content::BrowserContext::GetDefaultStoragePartition(profile_); site_data_size_collector_.reset(new SiteDataSizeCollector( storage_partition->GetPath(), - new BrowsingDataCookieHelper(profile->GetRequestContext()), - new BrowsingDataDatabaseHelper(profile), - new BrowsingDataLocalStorageHelper(profile), - new BrowsingDataAppCacheHelper(profile), + new BrowsingDataCookieHelper(storage_partition), + new BrowsingDataDatabaseHelper(profile_), + new BrowsingDataLocalStorageHelper(profile_), + new BrowsingDataAppCacheHelper(profile_), new BrowsingDataIndexedDBHelper( storage_partition->GetIndexedDBContext()), BrowsingDataFileSystemHelper::Create( storage_partition->GetFileSystemContext()), - BrowsingDataChannelIDHelper::Create(profile->GetRequestContext()), + BrowsingDataChannelIDHelper::Create(profile_->GetRequestContext()), new BrowsingDataServiceWorkerHelper( storage_partition->GetServiceWorkerContext()), new BrowsingDataCacheStorageHelper( storage_partition->GetCacheStorageContext()), - BrowsingDataFlashLSOHelper::Create(profile))); + BrowsingDataFlashLSOHelper::Create(profile_))); } site_data_size_collector_->Fetch( base::Bind(&StorageHandler::OnGetBrowsingDataSize, @@ -288,6 +289,66 @@ void StorageHandler::OnGetBrowsingDataSize(bool is_site_data, int64_t size) { } } +void StorageHandler::UpdateAndroidSize() { + if (!arc::IsArcPlayStoreEnabledForProfile(profile_) || + arc::IsArcOptInVerificationDisabled()) { + return; + } + + if (updating_android_size_) + return; + updating_android_size_ = true; + + // Shows the item "Android apps and cache" and starts calculating size. + FireWebUIListener("storage-android-enabled-changed", base::Value(true)); + + bool success = false; + auto* arc_storage_manager = + arc::ArcStorageManager::GetForBrowserContext(profile_); + if (arc_storage_manager) { + success = arc_storage_manager->GetApplicationsSize(base::BindOnce( + &StorageHandler::OnGetAndroidSize, weak_ptr_factory_.GetWeakPtr())); + } + if (!success) + updating_android_size_ = false; +} + +void StorageHandler::OnGetAndroidSize(bool succeeded, + arc::mojom::ApplicationsSizePtr size) { + base::string16 size_string; + if (succeeded) { + uint64_t total_bytes = size->total_code_bytes + size->total_data_bytes + + size->total_cache_bytes; + size_string = ui::FormatBytes(total_bytes); + } else { + size_string = l10n_util::GetStringUTF16(IDS_SETTINGS_STORAGE_SIZE_UNKNOWN); + } + updating_android_size_ = false; + FireWebUIListener("storage-android-size-changed", base::Value(size_string)); +} + +void StorageHandler::UpdateCrostiniSize() { + if (!IsCrostiniEnabled(profile_)) { + return; + } + + if (updating_crostini_size_) + return; + updating_crostini_size_ = true; + + crostini::CrostiniManager::GetInstance()->ListVmDisks( + CryptohomeIdForProfile(profile_), + base::BindOnce(&StorageHandler::OnGetCrostiniSize, + weak_ptr_factory_.GetWeakPtr())); +} + +void StorageHandler::OnGetCrostiniSize(crostini::ConciergeClientResult result, + int64_t size) { + updating_crostini_size_ = false; + FireWebUIListener("storage-crostini-size-changed", + base::Value(ui::FormatBytes(size))); +} + void StorageHandler::UpdateOtherUsersSize() { if (updating_other_users_size_) return; @@ -333,48 +394,5 @@ void StorageHandler::OnGetOtherUserSize( } } -void StorageHandler::UpdateAndroidSize() { - if (updating_android_size_) - return; - updating_android_size_ = true; - - Profile* const profile = Profile::FromWebUI(web_ui()); - if (!arc::IsArcPlayStoreEnabledForProfile(profile) || - arc::IsArcOptInVerificationDisabled()) { - return; - } - - // Shows the item "Android apps and cache" and start calculating size. - FireWebUIListener("storage-android-enabled-changed", base::Value(true)); - bool success = false; - auto* arc_storage_manager = - arc::ArcStorageManager::GetForBrowserContext(profile); - if (arc_storage_manager) { - success = arc_storage_manager->GetApplicationsSize(base::BindOnce( - &StorageHandler::OnGetAndroidSize, weak_ptr_factory_.GetWeakPtr())); - } - if (!success) - updating_android_size_ = false; -} - -void StorageHandler::OnGetAndroidSize(bool succeeded, - arc::mojom::ApplicationsSizePtr size) { - base::string16 size_string; - if (succeeded) { - uint64_t total_bytes = size->total_code_bytes + - size->total_data_bytes + - size->total_cache_bytes; - size_string = ui::FormatBytes(total_bytes); - } else { - size_string = l10n_util::GetStringUTF16(IDS_SETTINGS_STORAGE_SIZE_UNKNOWN); - } - updating_android_size_ = false; - FireWebUIListener("storage-android-size-changed", base::Value(size_string)); -} - -void StorageHandler::OnClearDriveCacheDone(bool success) { - UpdateDriveCacheSize(); -} - } // 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 48f3d5b5875..8d5f7b04ceb 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,6 +19,12 @@ #include "components/arc/storage_manager/arc_storage_manager.h" #include "components/user_manager/user.h" +class Profile; + +namespace crostini { +enum class ConciergeClientResult; +} // namespace crostini + namespace chromeos { namespace settings { @@ -32,7 +38,7 @@ class StorageHandler : public ::settings::SettingsPageUIHandler { STORAGE_SPACE_CRITICALLY_LOW = 2, }; - StorageHandler(); + explicit StorageHandler(Profile* profile); ~StorageHandler() override; // SettingsPageUIHandler implementation. @@ -47,6 +53,9 @@ class StorageHandler : public ::settings::SettingsPageUIHandler { void HandleOpenArcStorage(const base::ListValue* unused_args); void HandleClearDriveCache(const base::ListValue* unused_args); + // Callback called when clearing Drive cache is done. + void OnClearDriveCacheDone(bool success); + // Requests updating disk space information. void UpdateSizeStat(); @@ -74,20 +83,24 @@ class StorageHandler : public ::settings::SettingsPageUIHandler { // Callback to update the UI about the size of browsing data. void OnGetBrowsingDataSize(bool is_site_data, int64_t size); - // Requests updating the total size of other users' data. - void UpdateOtherUsersSize(); - - // Callback to save the fetched user sizes and update the UI. - void OnGetOtherUserSize(base::Optional<cryptohome::BaseReply> reply); - // Requests updating the space size used by Android apps and cache. void UpdateAndroidSize(); // Callback to update the UI about Android apps and cache. void OnGetAndroidSize(bool succeeded, arc::mojom::ApplicationsSizePtr size); - // Callback called when clearing Drive cache is done. - void OnClearDriveCacheDone(bool success); + // Requests updating the space size used by Crostini VMs and their apps and + // cache. + void UpdateCrostiniSize(); + + // Callback to update the UI about Crostini VMs and their apps and cache. + void OnGetCrostiniSize(crostini::ConciergeClientResult result, int64_t size); + + // Requests updating the total size of other users' data. + void UpdateOtherUsersSize(); + + // Callback to save the fetched user sizes and update the UI. + void OnGetOtherUserSize(base::Optional<cryptohome::BaseReply> reply); // Total size of cache data in browsing data. int64_t browser_cache_size_; @@ -101,6 +114,9 @@ class StorageHandler : public ::settings::SettingsPageUIHandler { // True if we have already received the size of site data. bool has_browser_site_data_size_; + // Helper to compute the total size of all types of site date. + std::unique_ptr<SiteDataSizeCollector> site_data_size_collector_; + // The list of other users whose directory sizes will be accumulated as the // size of "Other users". user_manager::UserList other_users_; @@ -108,16 +124,15 @@ class StorageHandler : public ::settings::SettingsPageUIHandler { // Fetched sizes of user directories. std::vector<int64_t> user_sizes_; - // Helper to compute the total size of all types of site date. - std::unique_ptr<SiteDataSizeCollector> site_data_size_collector_; - // Flags indicating fetch operations for storage sizes are ongoing. bool updating_downloads_size_; bool updating_drive_cache_size_; bool updating_browsing_data_size_; bool updating_android_size_; + bool updating_crostini_size_; bool updating_other_users_size_; + Profile* const profile_; base::WeakPtrFactory<StorageHandler> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(StorageHandler); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc index 287e99313d6..f30ce4ca6d8 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc @@ -22,7 +22,7 @@ namespace { class FakeEasyUnlockService : public EasyUnlockService { public: explicit FakeEasyUnlockService(Profile* profile) - : EasyUnlockService(profile), + : EasyUnlockService(profile, nullptr /* secure_channel_client */), turn_off_status_(IDLE), is_allowed_(true), is_enabled_(false) {} 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 8367559e562..8dc3a46c55f 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc @@ -9,12 +9,12 @@ #include "base/bind.h" #include "base/values.h" -#include "chrome/browser/chromeos/options/network_config_view.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/tether/tether_service.h" #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_event_log.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "components/arc/arc_bridge_service.h" @@ -33,8 +33,8 @@ namespace chromeos { namespace { -const char kAddNetworkMessage[] = "addNetwork"; -const char kConfigureNetworkMessage[] = "configureNetwork"; +const char kAddThirdPartyVpnMessage[] = "addThirdPartyVpn"; +const char kConfigureThirdPartyVpnMessage[] = "configureThirdPartyVpn"; const char kRequestArcVpnProviders[] = "requestArcVpnProviders"; const char kSendArcVpnProviders[] = "sendArcVpnProviders"; const char kRequestGmsCoreNotificationsDisabledDeviceNames[] = @@ -42,13 +42,6 @@ const char kRequestGmsCoreNotificationsDisabledDeviceNames[] = const char kSendGmsCoreNotificationsDisabledDeviceNames[] = "sendGmsCoreNotificationsDisabledDeviceNames"; -std::string ServicePathFromGuid(const std::string& guid) { - const NetworkState* network = - NetworkHandler::Get()->network_state_handler()->GetNetworkStateFromGuid( - guid); - return network ? network->path() : ""; -} - Profile* GetProfileForPrimaryUser() { return ProfileHelper::Get()->GetProfileByUser( user_manager::UserManager::Get()->GetPrimaryUser()); @@ -93,14 +86,13 @@ InternetHandler::~InternetHandler() { } void InternetHandler::RegisterMessages() { - // TODO(stevenjb): Eliminate once network configuration UI is integrated - // into settings. web_ui()->RegisterMessageCallback( - kAddNetworkMessage, base::BindRepeating(&InternetHandler::AddNetwork, - base::Unretained(this))); + kAddThirdPartyVpnMessage, + base::BindRepeating(&InternetHandler::AddThirdPartyVpn, + base::Unretained(this))); web_ui()->RegisterMessageCallback( - kConfigureNetworkMessage, - base::BindRepeating(&InternetHandler::ConfigureNetwork, + kConfigureThirdPartyVpnMessage, + base::BindRepeating(&InternetHandler::ConfigureThirdPartyVpn, base::Unretained(this))); web_ui()->RegisterMessageCallback( kRequestArcVpnProviders, @@ -142,85 +134,81 @@ void InternetHandler::OnGmsCoreNotificationStateChanged() { SetGmsCoreNotificationsDisabledDeviceNames(); } -void InternetHandler::AddNetwork(const base::ListValue* args) { - std::string onc_type; - if (args->GetSize() < 1 || !args->GetString(0, &onc_type)) { - NOTREACHED() << "Invalid args for: " << kAddNetworkMessage; +void InternetHandler::AddThirdPartyVpn(const base::ListValue* args) { + std::string app_id; + if (args->GetSize() < 1 || !args->GetString(0, &app_id)) { + NOTREACHED() << "Invalid args for: " << kAddThirdPartyVpnMessage; + return; + } + if (app_id.empty()) { + NET_LOG(ERROR) << "Empty app id for " << kAddThirdPartyVpnMessage; + return; + } + if (profile_ != GetProfileForPrimaryUser()) { + NET_LOG(ERROR) << "Only the primary user can add VPNs"; return; } - if (onc_type == ::onc::network_type::kVPN) { - std::string app_id; - if (args->GetSize() >= 2) - args->GetString(1, &app_id); - if (app_id.empty()) { - // Show the "add network" dialog for the built-in OpenVPN/L2TP provider. - NetworkConfigView::ShowForType(shill::kTypeVPN); - return; - } - // Request to launch Arc VPN provider. - const auto* arc_app_list_prefs = ArcAppListPrefs::Get(profile_); - if (arc_app_list_prefs && arc_app_list_prefs->GetApp(app_id)) { - arc::LaunchApp(profile_, app_id, ui::EF_NONE); - return; - } - // Request that the third-party VPN provider identified by |provider_id| - // show its "add network" dialog. - VpnServiceFactory::GetForBrowserContext(GetProfileForPrimaryUser()) - ->SendShowAddDialogToExtension(app_id); - } else if (onc_type == ::onc::network_type::kWiFi) { - NetworkConfigView::ShowForType(shill::kTypeWifi); - } else { - LOG(ERROR) << "Unsupported type for: " << kAddNetworkMessage; + // Request to launch Arc VPN provider. + const auto* arc_app_list_prefs = ArcAppListPrefs::Get(profile_); + if (arc_app_list_prefs && arc_app_list_prefs->GetApp(app_id)) { + arc::LaunchApp(profile_, app_id, ui::EF_NONE, + arc::UserInteractionType::APP_STARTED_FROM_SETTINGS); + return; } + + // Request that the third-party VPN provider identified by |provider_id| + // show its "add network" dialog. + VpnServiceFactory::GetForBrowserContext(GetProfileForPrimaryUser()) + ->SendShowAddDialogToExtension(app_id); } -void InternetHandler::ConfigureNetwork(const base::ListValue* args) { +void InternetHandler::ConfigureThirdPartyVpn(const base::ListValue* args) { std::string guid; if (args->GetSize() < 1 || !args->GetString(0, &guid)) { - NOTREACHED() << "Invalid args for: " << kConfigureNetworkMessage; + NOTREACHED() << "Invalid args for: " << kConfigureThirdPartyVpnMessage; return; } - - const std::string service_path = ServicePathFromGuid(guid); - if (service_path.empty()) { - LOG(ERROR) << "Network not found: " << guid; + if (profile_ != GetProfileForPrimaryUser()) { + NET_LOG(ERROR) << "Only the primary user can configure VPNs"; return; } const NetworkState* network = - NetworkHandler::Get()->network_state_handler()->GetNetworkState( - service_path); + NetworkHandler::Get()->network_state_handler()->GetNetworkStateFromGuid( + guid); if (!network) { - LOG(ERROR) << "Network not found with service_path: " << service_path; + NET_LOG(ERROR) << "ConfigureThirdPartyVpn: Network not found: " << guid; + return; + } + if (network->type() != shill::kTypeVPN) { + NET_LOG(ERROR) << "ConfigureThirdPartyVpn: Network is not a VPN: " << guid; return; } - if (network->type() == shill::kTypeVPN) { - if (profile_ != GetProfileForPrimaryUser()) - return; + if (network->vpn_provider_type() == shill::kProviderThirdPartyVpn) { + // Request that the third-party VPN provider used by the |network| show a + // configuration dialog for it. + VpnServiceFactory::GetForBrowserContext(profile_) + ->SendShowConfigureDialogToExtension(network->vpn_provider_id(), + network->name()); + return; + } - if (network->vpn_provider_type() == shill::kProviderThirdPartyVpn) { - // Request that the third-party VPN provider used by the |network| show a - // configuration dialog for it. - VpnServiceFactory::GetForBrowserContext(profile_) - ->SendShowConfigureDialogToExtension(network->vpn_provider_id(), - network->name()); - return; - } else if (network->vpn_provider_type() == shill::kProviderArcVpn) { - auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD( - arc::ArcServiceManager::Get()->arc_bridge_service()->net(), - ConfigureAndroidVpn); - if (!net_instance) { - LOG(ERROR) << "User requested VPN configuration but API is unavailable"; - return; - } - net_instance->ConfigureAndroidVpn(); + if (network->vpn_provider_type() == shill::kProviderArcVpn) { + auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD( + arc::ArcServiceManager::Get()->arc_bridge_service()->net(), + ConfigureAndroidVpn); + if (!net_instance) { + NET_LOG(ERROR) << "ConfigureThirdPartyVpn: API is unavailable"; return; } + net_instance->ConfigureAndroidVpn(); + return; } - NetworkConfigView::ShowForNetworkId(network->guid()); + NET_LOG(ERROR) << "ConfigureThirdPartyVpn: Unsupported VPN type: " + << network->vpn_provider_type() << " For: " << guid; } void InternetHandler::RequestArcVpnProviders(const base::ListValue* args) { 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 332d5dd8a5e..31ed7c90e43 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.h @@ -24,8 +24,6 @@ class GmsCoreNotificationsStateTracker; namespace settings { // Chrome OS Internet settings page UI handler. -// TODO(lgcheng/stevenjb): Rename this ThirdPartyVpnHandler once configuration -// is handled in the Settings UI (crbug.com/380937 class InternetHandler : public app_list::ArcVpnProviderManager::Observer, public chromeos::tether::GmsCoreNotificationsStateTracker::Observer, @@ -55,8 +53,8 @@ class InternetHandler friend class InternetHandlerTest; // Settings JS handlers. - void AddNetwork(const base::ListValue* args); - void ConfigureNetwork(const base::ListValue* args); + void AddThirdPartyVpn(const base::ListValue* args); + void ConfigureThirdPartyVpn(const base::ListValue* args); void RequestArcVpnProviders(const base::ListValue* args); void RequestGmsCoreNotificationsDisabledDeviceNames( const base::ListValue* args); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc new file mode 100644 index 00000000000..ca84973cd35 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc @@ -0,0 +1,38 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h" + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/logging.h" +#include "chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.h" +#include "content/public/browser/web_ui.h" + +namespace chromeos { + +namespace settings { + +MultideviceHandler::MultideviceHandler() = default; +MultideviceHandler::~MultideviceHandler() = default; + +void MultideviceHandler::OnJavascriptAllowed() {} +void MultideviceHandler::OnJavascriptDisallowed() {} + +void MultideviceHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "showMultiDeviceSetupDialog", + base::BindRepeating(&MultideviceHandler::HandleShowMultiDeviceSetupDialog, + base::Unretained(this))); +} + +void MultideviceHandler::HandleShowMultiDeviceSetupDialog( + const base::ListValue* args) { + DCHECK(args->empty()); + multidevice_setup::MultiDeviceSetupDialog::Show(); +} + +} // namespace settings + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h new file mode 100644 index 00000000000..3ab88522348 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h @@ -0,0 +1,38 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_MULTIDEVICE_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_MULTIDEVICE_HANDLER_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" + +namespace chromeos { + +namespace settings { + +// Chrome "Multidevice" (a.k.a. "Connected Devices") settings page UI handler. +class MultideviceHandler : public ::settings::SettingsPageUIHandler { + public: + MultideviceHandler(); + ~MultideviceHandler() override; + + // content::WebUIMessageHandler: + void RegisterMessages() override; + + // ::settings::SettingsPageUIHandler: + void OnJavascriptAllowed() override; + void OnJavascriptDisallowed() override; + + private: + void HandleShowMultiDeviceSetupDialog(const base::ListValue* args); + + DISALLOW_COPY_AND_ASSIGN(MultideviceHandler); +}; + +} // namespace settings + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_MULTIDEVICE_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.cc index 2b3ef9136d0..8a5af4ee012 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.cc @@ -16,6 +16,17 @@ namespace chromeos { namespace settings { +namespace { + +smb_client::SmbService* GetSmbService(Profile* profile) { + smb_client::SmbService* const service = smb_client::SmbService::Get(profile); + DCHECK(service); + + return service; +} + +} // namespace + SmbHandler::SmbHandler(Profile* profile) : profile_(profile), weak_ptr_factory_(this) {} @@ -25,32 +36,63 @@ void SmbHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "smbMount", base::BindRepeating(&SmbHandler::HandleSmbMount, base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "startDiscovery", base::BindRepeating(&SmbHandler::HandleStartDiscovery, + base::Unretained(this))); } void SmbHandler::HandleSmbMount(const base::ListValue* args) { - CHECK_EQ(3U, args->GetSize()); - std::string mountUrl; + CHECK_EQ(4U, args->GetSize()); + std::string mount_url; + std::string mount_name; std::string username; std::string password; - CHECK(args->GetString(0, &mountUrl)); - CHECK(args->GetString(1, &username)); - CHECK(args->GetString(2, &password)); + CHECK(args->GetString(0, &mount_url)); + CHECK(args->GetString(1, &mount_name)); + CHECK(args->GetString(2, &username)); + CHECK(args->GetString(3, &password)); - chromeos::smb_client::SmbService* const service = - chromeos::smb_client::SmbService::Get(profile_); + smb_client::SmbService* const service = GetSmbService(profile_); chromeos::file_system_provider::MountOptions mo; - mo.display_name = mountUrl; + mo.display_name = mount_name.empty() ? mount_url : mount_name; mo.writable = true; - service->Mount(mo, base::FilePath(mountUrl), username, password, - base::BindOnce(&SmbHandler::HandleSmbMountResponse, - weak_ptr_factory_.GetWeakPtr())); + auto mount_response = base::BindOnce(&SmbHandler::HandleSmbMountResponse, + weak_ptr_factory_.GetWeakPtr()); + auto mount_call = base::BindOnce( + &smb_client::SmbService::Mount, base::Unretained(service), mo, + base::FilePath(mount_url), username, password, std::move(mount_response)); + + if (host_discovery_done_) { + std::move(mount_call).Run(); + } else { + stored_mount_call_ = std::move(mount_call); + } } void SmbHandler::HandleSmbMountResponse(SmbMountResult result) { AllowJavascript(); - FireWebUIListener("on-add-smb-share", base::Value(result)); + FireWebUIListener("on-add-smb-share", base::Value(static_cast<int>(result))); +} + +void SmbHandler::HandleStartDiscovery(const base::ListValue* args) { + smb_client::SmbService* const service = GetSmbService(profile_); + + service->GatherSharesInNetwork(base::BindRepeating( + &SmbHandler::HandleGatherSharesResponse, weak_ptr_factory_.GetWeakPtr())); +} + +void SmbHandler::HandleGatherSharesResponse( + const std::vector<smb_client::SmbUrl>& shares_gathered) { + host_discovery_done_ = true; + if (!stored_mount_call_.is_null()) { + std::move(stored_mount_call_).Run(); + } + + // TODO(zentaro): Pass the shares discovered back to the UI. + // https://crbug.com/852199. } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.h index 315a302f144..fe6c85db64f 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_ +#include "base/callback_forward.h" #include "base/files/file.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -31,9 +32,18 @@ class SmbHandler : public ::settings::SettingsPageUIHandler { // WebUI call to mount an Smb Filesystem. void HandleSmbMount(const base::ListValue* args); + // WebUI call to start file share discovery on the network. + void HandleStartDiscovery(const base::ListValue* args); + // Callback handler for SmbMount. void HandleSmbMountResponse(SmbMountResult result); + // Callback handler for StartDiscovery. + void HandleGatherSharesResponse( + const std::vector<smb_client::SmbUrl>& shares_gathered); + + bool host_discovery_done_ = false; + base::OnceClosure stored_mount_call_; Profile* const profile_; base::WeakPtrFactory<SmbHandler> weak_ptr_factory_; diff --git a/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc b/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc index 7f5a1b27042..ad36ee33086 100644 --- a/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc @@ -29,8 +29,9 @@ void ExtensionControlHandler::HandleDisableExtension( const base::ListValue* args) { std::string extension_id; CHECK(args->GetString(0, &extension_id)); - ExtensionService* extension_service = extensions::ExtensionSystem::Get( - Profile::FromWebUI(web_ui()))->extension_service(); + extensions::ExtensionService* extension_service = + extensions::ExtensionSystem::Get(Profile::FromWebUI(web_ui())) + ->extension_service(); DCHECK(extension_service); extension_service->DisableExtension( extension_id, extensions::disable_reason::DISABLE_USER_ACTION); diff --git a/chromium/chrome/browser/ui/webui/settings/font_handler.cc b/chromium/chrome/browser/ui/webui/settings/font_handler.cc index 037d0a5b3a4..ffb8f495ab7 100644 --- a/chromium/chrome/browser/ui/webui/settings/font_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/font_handler.cc @@ -100,7 +100,7 @@ void FontHandler::HandleOpenAdvancedFontSettings( } const extensions::Extension* FontHandler::GetAdvancedFontSettingsExtension() { - ExtensionService* service = + extensions::ExtensionService* service = extensions::ExtensionSystem::Get(profile_)->extension_service(); if (!service->IsExtensionEnabled(kAdvancedFontSettingsExtensionId)) return nullptr; diff --git a/chromium/chrome/browser/ui/webui/settings/languages_handler.cc b/chromium/chrome/browser/ui/webui/settings/languages_handler.cc index 6ec6856e4d2..0346fa16e01 100644 --- a/chromium/chrome/browser/ui/webui/settings/languages_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/languages_handler.cc @@ -10,6 +10,7 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" +#include "components/language/core/browser/pref_names.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui.h" @@ -50,12 +51,12 @@ void LanguagesHandler::HandleGetProspectiveUILanguage( std::string locale; #if defined(OS_CHROMEOS) // On Chrome OS, an individual profile may have a preferred locale. - locale = profile_->GetPrefs()->GetString(prefs::kApplicationLocale); + locale = profile_->GetPrefs()->GetString(language::prefs::kApplicationLocale); #endif // defined(OS_CHROMEOS) if (locale.empty()) { - locale = - g_browser_process->local_state()->GetString(prefs::kApplicationLocale); + locale = g_browser_process->local_state()->GetString( + language::prefs::kApplicationLocale); } ResolveJavascriptCallback(*callback_id, base::Value(locale)); @@ -70,16 +71,16 @@ void LanguagesHandler::HandleSetProspectiveUILanguage( CHECK(args->GetString(0, &language_code)); #if defined(OS_CHROMEOS) - // check if prospectiveUILanguage is allowed by policy (AllowedLocales) - if (!chromeos::locale_util::IsAllowedLocale(language_code, - profile_->GetPrefs())) { + // check if prospectiveUILanguage is allowed by policy (AllowedUILocales) + if (!chromeos::locale_util::IsAllowedUILocale(language_code, + profile_->GetPrefs())) { return; } #endif #if defined(OS_WIN) PrefService* prefs = g_browser_process->local_state(); - prefs->SetString(prefs::kApplicationLocale, language_code); + prefs->SetString(language::prefs::kApplicationLocale, language_code); #elif defined(OS_CHROMEOS) // Secondary users and public session users cannot change the locale. user_manager::UserManager* user_manager = user_manager::UserManager::Get(); diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index 77f1c6afba4..65230a3aea7 100644 --- a/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc @@ -7,6 +7,7 @@ #include <string> #include "base/command_line.h" +#include "base/feature_list.h" #include "base/i18n/number_formatting.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" @@ -28,8 +29,10 @@ #include "chrome/grit/locale_settings.h" #include "components/autofill/core/browser/payments/payments_service_url.h" #include "components/autofill/core/common/autofill_constants.h" +#include "components/content_settings/core/common/features.h" #include "components/google/core/browser/google_util.h" -#include "components/password_manager/core/browser/password_manager_constants.h" +#include "components/omnibox/browser/omnibox_field_trial.h" +#include "components/password_manager/core/common/password_manager_features.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/signin/core/browser/signin_buildflags.h" #include "components/strings/grit/components_strings.h" @@ -52,6 +55,7 @@ #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h" #include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h" +#include "chromeos/chromeos_features.h" #include "chromeos/chromeos_switches.h" #include "components/arc/arc_util.h" #include "components/user_manager/user_manager.h" @@ -195,6 +199,7 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { {"delayBeforeClickShort", IDS_SETTINGS_DELAY_BEFORE_CLICK_SHORT}, {"delayBeforeClickLong", IDS_SETTINGS_DELAY_BEFORE_CLICK_LONG}, {"delayBeforeClickVeryLong", IDS_SETTINGS_DELAY_BEFORE_CLICK_VERY_LONG}, + {"dictationDescription", IDS_SETTINGS_ACCESSIBILITY_DICTATION_DESCRIPTION}, {"dictationLabel", IDS_SETTINGS_ACCESSIBILITY_DICTATION_LABEL}, {"onScreenKeyboardLabel", IDS_SETTINGS_ON_SCREEN_KEYBOARD_LABEL}, {"monoAudioLabel", IDS_SETTINGS_MONO_AUDIO_LABEL}, @@ -228,7 +233,6 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_ACCESSIBILITY_APPEARANCE_SETTINGS_TITLE}, {"appearanceSettingsDescription", IDS_SETTINGS_ACCESSIBILITY_APPEARANCE_SETTINGS_DESCRIPTION}, - {"keyboardHeading", IDS_SETTINGS_ACCESSIBILITY_KEYBOARD_HEADING}, {"keyboardAndTextInputHeading", IDS_SETTINGS_ACCESSIBILITY_KEYBOARD_AND_TEXT_INPUT_HEADING}, {"keyboardSettingsTitle", @@ -248,6 +252,7 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { {"textToSpeechVoices", IDS_SETTINGS_TEXT_TO_SPEECH_VOICES}, {"textToSpeechNoVoicesMessage", IDS_SETTINGS_TEXT_TO_SPEECH_NO_VOICES_MESSAGE}, + {"textToSpeechMoreLanguages", IDS_SETTINGS_TEXT_TO_SPEECH_MORE_LANGUAGES}, {"textToSpeechProperties", IDS_SETTINGS_TEXT_TO_SPEECH_PROPERTIES}, {"textToSpeechRate", IDS_SETTINGS_TEXT_TO_SPEECH_RATE}, {"textToSpeechRateMinimumLabel", @@ -273,7 +278,6 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { {"textToSpeechPreviewVoice", IDS_SETTINGS_TEXT_TO_SPEECH_PREVIEW_VOICE}, {"textToSpeechPreviewPlay", IDS_SETTINGS_TEXT_TO_SPEECH_PREVIEW_PLAY}, {"textToSpeechEngines", IDS_SETTINGS_TEXT_TO_SPEECH_ENGINES}, - {"textToSpeechInstallEngines", IDS_SETTINGS_TEXT_TO_SPEECH_INSTALL_ENGINES}, #endif }; AddLocalizedStringsBulk(html_source, localized_strings, @@ -330,6 +334,8 @@ void AddAboutStrings(content::WebUIDataSource* html_source) { {"aboutPlatformLabel", IDS_SETTINGS_ABOUT_PAGE_PLATFORM}, {"aboutRelaunchAndPowerwash", IDS_SETTINGS_ABOUT_PAGE_RELAUNCH_AND_POWERWASH}, + {"aboutRollbackInProgress", IDS_SETTINGS_UPGRADE_ROLLBACK_IN_PROGRESS}, + {"aboutRollbackSuccess", IDS_SETTINGS_UPGRADE_ROLLBACK_SUCCESS}, {"aboutUpgradeUpdatingChannelSwitch", IDS_SETTINGS_UPGRADE_UPDATING_CHANNEL_SWITCH}, {"aboutUpgradeSuccessChannelSwitch", @@ -388,13 +394,17 @@ void AddAboutStrings(content::WebUIDataSource* html_source) { void AddCrostiniStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"crostiniPageTitle", IDS_SETTINGS_CROSTINI_TITLE}, - {"crostiniSubtext", IDS_SETTINGS_CROSTINI_SUBTEXT}, {"crostiniPageLabel", IDS_SETTINGS_CROSTINI_LABEL}, {"crostiniEnable", IDS_SETTINGS_TURN_ON}, {"crostiniRemove", IDS_SETTINGS_CROSTINI_REMOVE}, }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); + html_source->AddString( + "crostiniSubtext", + l10n_util::GetStringFUTF16( + IDS_SETTINGS_CROSTINI_SUBTEXT, + GetHelpUrlWithBoard(chrome::kLinuxAppsLearnMoreURL))); } void AddAndroidAppStrings(content::WebUIDataSource* html_source) { @@ -501,21 +511,6 @@ void AddChangePasswordStrings(content::WebUIDataSource* html_source) { void AddClearBrowsingDataStrings(content::WebUIDataSource* html_source, Profile* profile) { - int clear_cookies_summary_msg_id = - IDS_SETTINGS_CLEAR_COOKIES_AND_SITE_DATA_SUMMARY_BASIC; - -#if defined(OS_CHROMEOS) - if (AccountConsistencyModeManager::IsMirrorEnabledForProfile(profile)) { - clear_cookies_summary_msg_id = - IDS_SETTINGS_CLEAR_COOKIES_AND_SITE_DATA_SUMMARY_BASIC_WITH_EXCEPTION; - } -#else // !defined(OS_CHROMEOS) - if (AccountConsistencyModeManager::IsDiceEnabledForProfile(profile)) { - clear_cookies_summary_msg_id = - IDS_SETTINGS_CLEAR_COOKIES_AND_SITE_DATA_SUMMARY_BASIC_WITH_EXCEPTION; - } -#endif - LocalizedString localized_strings[] = { {"clearTimeRange", IDS_SETTINGS_CLEAR_PERIOD_TITLE}, {"clearBrowsingHistory", IDS_SETTINGS_CLEAR_BROWSING_HISTORY}, @@ -524,7 +519,10 @@ void AddClearBrowsingDataStrings(content::WebUIDataSource* html_source, {"clearDownloadHistory", IDS_SETTINGS_CLEAR_DOWNLOAD_HISTORY}, {"clearCache", IDS_SETTINGS_CLEAR_CACHE}, {"clearCookies", IDS_SETTINGS_CLEAR_COOKIES}, - {"clearCookiesSummary", clear_cookies_summary_msg_id}, + {"clearCookiesSummary", + IDS_SETTINGS_CLEAR_COOKIES_AND_SITE_DATA_SUMMARY_BASIC}, + {"clearCookiesSummarySignedIn", + IDS_SETTINGS_CLEAR_COOKIES_AND_SITE_DATA_SUMMARY_BASIC_WITH_EXCEPTION}, {"clearCookiesCounter", IDS_DEL_COOKIES_COUNTER}, {"clearCookiesFlash", IDS_SETTINGS_CLEAR_COOKIES_FLASH}, {"clearPasswords", IDS_SETTINGS_CLEAR_PASSWORDS}, @@ -539,11 +537,6 @@ void AddClearBrowsingDataStrings(content::WebUIDataSource* html_source, {"historyDeletionDialogTitle", IDS_CLEAR_BROWSING_DATA_HISTORY_NOTICE_TITLE}, {"historyDeletionDialogOK", IDS_CLEAR_BROWSING_DATA_HISTORY_NOTICE_OK}, - {"importantSitesSubtitleCookies", - IDS_SETTINGS_IMPORTANT_SITES_SUBTITLE_COOKIES}, - {"importantSitesSubtitleCookiesAndCache", - IDS_SETTINGS_IMPORTANT_SITES_SUBTITLE_COOKIES_AND_CACHE}, - {"importantSitesConfirm", IDS_SETTINGS_IMPORTANT_SITES_CONFIRM}, {"notificationWarning", IDS_SETTINGS_NOTIFICATION_WARNING}, }; @@ -751,7 +744,7 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { display::HasExternalTouchscreenDevice()); html_source->AddBoolean("nightLightFeatureEnabled", - ash::switches::IsNightLightEnabled()); + ash::features::IsNightLightEnabled()); LocalizedString storage_strings[] = { {"storageTitle", IDS_SETTINGS_STORAGE_TITLE}, @@ -761,6 +754,7 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { {"storageItemDriveCache", IDS_SETTINGS_STORAGE_ITEM_DRIVE_CACHE}, {"storageItemBrowsingData", IDS_SETTINGS_STORAGE_ITEM_BROWSING_DATA}, {"storageItemAndroid", IDS_SETTINGS_STORAGE_ITEM_ANDROID}, + {"storageItemCrostini", IDS_SETTINGS_STORAGE_ITEM_CROSTINI}, {"storageItemOtherUsers", IDS_SETTINGS_STORAGE_ITEM_OTHER_USERS}, {"storageSizeComputing", IDS_SETTINGS_STORAGE_SIZE_CALCULATING}, {"storageSizeUnknown", IDS_SETTINGS_STORAGE_SIZE_UNKNOWN}, @@ -823,6 +817,7 @@ void AddDownloadsStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_DOWNLOADS_SMB_SHARES_LEARN_MORE_LABEL}, {"addSmbShare", IDS_SETTINGS_DOWNLOADS_SMB_SHARES_ADD_SHARE}, {"smbShareUrl", IDS_SETTINGS_DOWNLOADS_ADD_SHARE_URL}, + {"smbShareName", IDS_SETTINGS_DOWNLOADS_ADD_SHARE_NAME}, {"smbShareUsername", IDS_SETTINGS_DOWNLOADS_ADD_SHARE_USERNAME}, {"smbSharePassword", IDS_SETTINGS_DOWNLOADS_ADD_SHARE_PASSWORD}, {"smbShareAddedSuccessfulMessage", @@ -857,6 +852,8 @@ void AddChromeCleanupStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"chromeCleanupPageTitle", IDS_SETTINGS_RESET_CLEAN_UP_COMPUTER_PAGE_TITLE}, + {"chromeCleanupDetailsExtensions", + IDS_SETTINGS_RESET_CLEANUP_DETAILS_EXTENSIONS}, {"chromeCleanupDetailsFilesAndPrograms", IDS_SETTINGS_RESET_CLEANUP_DETAILS_FILES_AND_PROGRAMS}, {"chromeCleanupDetailsRegistryEntries", @@ -1242,8 +1239,6 @@ void AddInternetStrings(content::WebUIDataSource* html_source) { AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); - html_source->AddBoolean("networkSettingsConfig", - chromeos::switches::IsNetworkSettingsConfigEnabled()); html_source->AddString("networkGoogleNameserversLearnMoreUrl", chrome::kGoogleNameserversLearnMoreURL); html_source->AddString( @@ -1273,6 +1268,8 @@ void AddLanguagesStrings(content::WebUIDataSource* html_source) { {"inputMethodEnabled", IDS_SETTINGS_LANGUAGES_INPUT_METHOD_ENABLED}, {"inputMethodsExpandA11yLabel", IDS_SETTINGS_LANGUAGES_INPUT_METHODS_EXPAND_ACCESSIBILITY_LABEL}, + {"inputMethodsManagedbyPolicy", + IDS_SETTINGS_LANGUAGES_INPUT_METHODS_MANAGED_BY_POLICY}, {"manageInputMethods", IDS_SETTINGS_LANGUAGES_INPUT_METHODS_MANAGE}, {"manageInputMethodsPageTitle", IDS_SETTINGS_LANGUAGES_MANAGE_INPUT_METHODS_TITLE}, @@ -1381,10 +1378,13 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"passwordsAndAutofillPageTitle", IDS_SETTINGS_PASSWORDS_AND_AUTOFILL_PAGE_TITLE}, - {"autofill", IDS_SETTINGS_AUTOFILL}, {"googlePayments", IDS_SETTINGS_GOOGLE_PAYMENTS}, {"googlePaymentsCached", IDS_SETTINGS_GOOGLE_PAYMENTS_CACHED}, {"autofillFormsLabel", IDS_SETTINGS_AUTOFILL_TOGGLE_LABEL}, + {"enableProfilesLabel", + IDS_SETTINGS_AUTOFILL_ENABLE_PROFILES_TOGGLE_LABEL}, + {"enableCreditCardsLabel", + IDS_SETTINGS_AUTOFILL_ENABLE_CREDIT_CARDS_TOGGLE_LABEL}, {"addresses", IDS_SETTINGS_AUTOFILL_ADDRESSES_HEADING}, {"addAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_ADD_TITLE}, {"editAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_EDIT_TITLE}, @@ -1392,7 +1392,6 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) { {"addressPhone", IDS_SETTINGS_AUTOFILL_ADDRESSES_PHONE}, {"addressEmail", IDS_SETTINGS_AUTOFILL_ADDRESSES_EMAIL}, {"removeAddress", IDS_SETTINGS_ADDRESS_REMOVE}, - {"creditCards", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_HEADING}, {"removeCreditCard", IDS_SETTINGS_CREDIT_CARD_REMOVE}, {"clearCreditCard", IDS_SETTINGS_CREDIT_CARD_CLEAR}, {"creditCardType", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_TYPE_COLUMN_LABEL}, @@ -1406,7 +1405,6 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) { {"addCreditCardTitle", IDS_SETTINGS_ADD_CREDIT_CARD_TITLE}, {"canMakePaymentToggleLabel", IDS_SETTINGS_CAN_MAKE_PAYMENT_TOGGLE_LABEL}, {"autofillDetail", IDS_SETTINGS_AUTOFILL_DETAIL}, - {"passwords", IDS_SETTINGS_PASSWORDS}, {"passwordsSavePasswordsLabel", IDS_SETTINGS_PASSWORDS_SAVE_PASSWORDS_TOGGLE_LABEL}, {"passwordsAutosigninLabel", @@ -1427,8 +1425,6 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) { {"editPasswordUsernameLabel", IDS_SETTINGS_PASSWORDS_USERNAME}, {"editPasswordPasswordLabel", IDS_SETTINGS_PASSWORDS_PASSWORD}, {"noAddressesFound", IDS_SETTINGS_ADDRESS_NONE}, - {"noCreditCardsFound", IDS_SETTINGS_CREDIT_CARD_NONE}, - {"noCreditCardsPolicy", IDS_SETTINGS_CREDIT_CARD_DISABLED}, {"noPasswordsFound", IDS_SETTINGS_PASSWORDS_NONE}, {"noExceptionsFound", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_NONE}, {"import", IDS_PASSWORD_MANAGER_IMPORT_BUTTON}, @@ -1452,12 +1448,31 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) { {"exportPasswordsFailTipsAnotherFolder", IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ANOTHER_FOLDER}}; + // TODO(https://crbug.com/854562): Integrate these strings into the + // |localized_strings| array once Autofill Home is fully launched. + if (base::FeatureList::IsEnabled(password_manager::features::kAutofillHome)) { + html_source->AddLocalizedString("autofill", + IDS_SETTINGS_AUTOFILL_AUTOFILL_HOME); + html_source->AddLocalizedString("passwords", + IDS_SETTINGS_PASSWORDS_AUTOFILL_HOME); + html_source->AddLocalizedString("creditCards", + IDS_SETTINGS_AUTOFILL_PAYMENT_METHODS); + html_source->AddLocalizedString("noCreditCardsFound", + IDS_SETTINGS_PAYMENT_METHODS_NONE); + } else { + html_source->AddLocalizedString("autofill", IDS_SETTINGS_AUTOFILL); + html_source->AddLocalizedString("passwords", IDS_SETTINGS_PASSWORDS); + html_source->AddLocalizedString("creditCards", + IDS_SETTINGS_AUTOFILL_CREDIT_CARD_HEADING); + html_source->AddLocalizedString("noCreditCardsFound", + IDS_SETTINGS_CREDIT_CARD_NONE); + } + html_source->AddString( "managePasswordsLabel", l10n_util::GetStringFUTF16( IDS_SETTINGS_PASSWORDS_MANAGE_PASSWORDS, - base::ASCIIToUTF16( - password_manager::kPasswordManagerAccountDashboardURL))); + l10n_util::GetStringUTF16(IDS_PASSWORDS_WEB_LINK))); html_source->AddString("passwordManagerLearnMoreURL", chrome::kPasswordManagerLearnMoreURL); html_source->AddString("manageAddressesUrl", @@ -1477,6 +1492,7 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"accountManagerPageTitle", IDS_SETTINGS_ACCOUNT_MANAGER_PAGE_TITLE}, {"accountManagerDescription", IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION}, {"accountListHeader", IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER}, + {"addAccountLabel", IDS_SETTINGS_ACCOUNT_MANAGER_ADD_ACCOUNT_LABEL}, {"configureFingerprintTitle", IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_TITLE}, {"configureFingerprintInstructionLocateScannerStep", IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER}, @@ -1586,6 +1602,7 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { #endif // defined(OS_CHROMEOS) #if BUILDFLAG(ENABLE_DICE_SUPPORT) {"peopleSignIn", IDS_SETTINGS_PEOPLE_SIGN_IN}, + {"peopleSignOut", IDS_SETTINGS_PEOPLE_SIGN_OUT}, {"peopleSignInPrompt", IDS_SETTINGS_PEOPLE_SIGN_IN_PROMPT}, {"peopleSignInPromptSecondaryWithNoAccount", IDS_SETTINGS_PEOPLE_SIGN_IN_PROMPT_SECONDARY_WITH_NO_ACCOUNT}, @@ -1595,23 +1612,22 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"syncAsName", IDS_SETTINGS_PEOPLE_SYNC_AS_NAME}, {"syncingTo", IDS_SETTINGS_PEOPLE_SYNCING_TO_ACCOUNT}, {"turnOffSync", IDS_SETTINGS_PEOPLE_SYNC_TURN_OFF}, + {"signInAgain", IDS_SYNC_ERROR_USER_MENU_SIGNIN_AGAIN_BUTTON}, {"syncNotWorking", IDS_SETTINGS_PEOPLE_SYNC_NOT_WORKING}, {"syncPaused", IDS_SETTINGS_PEOPLE_SYNC_PAUSED}, {"syncSignInPromptWithAccount", IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_ACCOUNT}, {"syncSignInPromptWithNoAccount", IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_NO_ACCOUNT}, - {"syncSignInPromptSecondary", IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_SECONDARY}, #endif {"syncUnifiedConsentToggleTitle", IDS_SETTINGS_PEOPLE_SYNC_UNIFIED_CONSENT_TOGGLE_TITLE}, - {"syncUnifiedConsentToggleSubtitle", - IDS_SETTINGS_PEOPLE_SYNC_UNIFIED_CONSENT_TOGGLE_SUBTITLE}, {"syncOverview", IDS_SETTINGS_SYNC_OVERVIEW}, + {"syncDisabled", IDS_PROFILES_DICE_SYNC_DISABLED_TITLE}, {"syncDisabledByAdministrator", IDS_SETTINGS_SYNC_DISABLED_BY_ADMINISTRATOR}, {"syncSignin", IDS_SETTINGS_SYNC_SIGNIN}, - {"syncDisconnect", IDS_SETTINGS_SYNC_DISCONNECT}, + {"syncDisconnect", IDS_SETTINGS_PEOPLE_SIGN_OUT}, {"syncDisconnectTitle", IDS_SETTINGS_SYNC_DISCONNECT_TITLE}, {"syncDisconnectDeleteProfile", IDS_SETTINGS_SYNC_DISCONNECT_DELETE_PROFILE}, @@ -1623,18 +1639,24 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_SETTINGS_SYNC_DISCONNECT_DELETE_PROFILE_WARNING_WITH_COUNTS_PLURAL}, {"deleteProfileWarningWithoutCounts", IDS_SETTINGS_SYNC_DISCONNECT_DELETE_PROFILE_WARNING_WITHOUT_COUNTS}, - {"syncDisconnectExplanation", IDS_SETTINGS_SYNC_DISCONNECT_EXPLANATION}, {"syncDisconnectConfirm", IDS_SETTINGS_SYNC_DISCONNECT_CONFIRM}, - {"sync", IDS_SETTINGS_SYNC}, - {"syncDescription", IDS_SETTINGS_SYNC_DESCRIPTION}, - {"personalizationSectionLabel", IDS_SETTINGS_PERSONALIZATION_SECTION_LABEL}, - {"personalizationSectionDesc", IDS_SETTINGS_PERSONALIZATION_SECTION_DESC}, - {"personalizationExpandA11yLabel", - IDS_SETTINGS_PERSONALIZATION_SECTION_ACCESSIBILITY_LABEL}, + {"sync", IsUnifiedConsentEnabled(profile) + ? IDS_SETTINGS_SYNC_UNIFIED_CONSENT + : IDS_SETTINGS_SYNC}, + {"syncDescription", IsUnifiedConsentEnabled(profile) + ? IDS_SETTINGS_SYNC_DESCRIPTION_UNIFIED_CONSENT + : IDS_SETTINGS_SYNC_DESCRIPTION}, + {"nonPersonalizedServicesSectionLabel", + IDS_SETTINGS_NON_PERSONALIZED_SERVICES_SECTION_LABEL}, + {"nonPersonalizedServicesSectionDesc", + IDS_SETTINGS_NON_PERSONALIZED_SERVICES_SECTION_DESC}, + {"nonPersonalizedServicesExpandA11yLabel", + IDS_SETTINGS_NON_PERSONALIZED_SERVICES_SECTION_ACCESSIBILITY_LABEL}, {"syncExpandA11yLabel", IDS_SETTINGS_SYNC_SECTION_ACCESSIBILITY_LABEL}, - {"syncAndPersonalization", IDS_SETTINGS_SYNC_SYNC_AND_PERSONALIZATION}, + {"syncAndNonPersonalizedServices", + IDS_SETTINGS_SYNC_SYNC_AND_NON_PERSONALIZED_SERVICES}, {"syncPageTitle", IsUnifiedConsentEnabled(profile) - ? IDS_SETTINGS_SYNC_SYNC_AND_PERSONALIZATION + ? IDS_SETTINGS_SYNC_SYNC_AND_NON_PERSONALIZED_SERVICES : IDS_SETTINGS_SYNC_PAGE_TITLE}, {"syncLoading", IDS_SETTINGS_SYNC_LOADING}, {"syncTimeout", IDS_SETTINGS_SYNC_TIMEOUT}, @@ -1650,8 +1672,10 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"bookmarksCheckboxLabel", IDS_SETTINGS_BOOKMARKS_CHECKBOX_LABEL}, {"passwordsCheckboxLabel", IDS_SETTINGS_PASSWORDS_CHECKBOX_LABEL}, {"openTabsCheckboxLabel", IDS_SETTINGS_OPEN_TABS_CHECKBOX_LABEL}, - {"enablePaymentsIntegrationCheckboxLabel", - IDS_SETTINGS_ENABLE_PAYMENTS_INTEGRATION_CHECKBOX_LABEL}, + {"userEventsCheckboxLabel", IDS_SETTINGS_USER_EVENTS_CHECKBOX_LABEL}, + {"userEventsCheckboxText", IDS_SETTINGS_USER_EVENTS_CHECKBOX_TEXT}, + {"driveSuggestPref", IDS_DRIVE_SUGGEST_PREF}, + {"driveSuggestPrefDesc", IDS_DRIVE_SUGGEST_PREF_DESC}, {"manageSyncedDataTitle", IDS_SETTINGS_MANAGE_SYNCED_DATA_TITLE}, {"encryptionOptionsTitle", IDS_SETTINGS_ENCRYPTION_OPTIONS}, {"syncDataEncryptedText", IDS_SETTINGS_SYNC_DATA_ENCRYPTED_TEXT}, @@ -1667,12 +1691,23 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"submitPassphraseButton", IDS_SETTINGS_SUBMIT_PASSPHRASE}, {"personalizeGoogleServicesTitle", IDS_SETTINGS_PERSONALIZE_GOOGLE_SERVICES_TITLE}, - {"personalizeGoogleServicesText", - IDS_SETTINGS_PERSONALIZE_GOOGLE_SERVICES_TEXT}, + {"existingPassphraseTitle", IDS_SETTINGS_EXISTING_PASSPHRASE_TITLE}, }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); + // TODO(https://crbug.com/854562): Integrate these strings into the + // |localized_strings| array once Autofill Home is fully launched. + if (base::FeatureList::IsEnabled(password_manager::features::kAutofillHome)) { + html_source->AddLocalizedString( + "enablePaymentsIntegrationCheckboxLabel", + IDS_SETTINGS_ENABLE_PAYMENTS_INTEGRATION_CHECKBOX_LABEL_AUTOFILL_HOME); + } else { + html_source->AddLocalizedString( + "enablePaymentsIntegrationCheckboxLabel", + IDS_SETTINGS_ENABLE_PAYMENTS_INTEGRATION_CHECKBOX_LABEL); + } + // Format numbers to be used on the pin keyboard. for (int j = 0; j <= 9; j++) { html_source->AddString("pinKeyboard" + base::IntToString(j), @@ -1712,8 +1747,11 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { base::ASCIIToUTF16(sync_dashboard_url))); html_source->AddString( "passphraseResetHint", - l10n_util::GetStringFUTF8(IDS_SETTINGS_PASSPHRASE_RESET_HINT, - base::ASCIIToUTF16(sync_dashboard_url))); + l10n_util::GetStringFUTF8( + IsUnifiedConsentEnabled(profile) + ? IDS_SETTINGS_PASSPHRASE_RESET_HINT_UNIFIED_CONSENT + : IDS_SETTINGS_PASSPHRASE_RESET_HINT, + base::ASCIIToUTF16(sync_dashboard_url))); html_source->AddString( "passphraseRecover", l10n_util::GetStringFUTF8(IDS_SETTINGS_PASSPHRASE_RECOVER, @@ -1733,8 +1771,11 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { // The syncDisconnect text differs depending on Dice-enabledness. if (AccountConsistencyModeManager::IsDiceEnabledForProfile(profile)) { LocalizedString sync_disconnect_strings[] = { - {"syncDisconnect", IDS_SETTINGS_TURN_OFF_SYNC_DIALOG_CONFIRM}, - {"syncDisconnectTitle", IDS_SETTINGS_TURN_OFF_SYNC_DIALOG_TITLE}, + {"syncDisconnect", IDS_SETTINGS_PEOPLE_SYNC_TURN_OFF}, + {"syncDisconnectTitle", + IsUnifiedConsentEnabled(profile) + ? IDS_SETTINGS_TURN_OFF_SYNC_AND_SIGN_OUT_DIALOG_TITLE_UNIFIED_CONSENT + : IDS_SETTINGS_TURN_OFF_SYNC_AND_SIGN_OUT_DIALOG_TITLE}, {"syncDisconnectDeleteProfile", IDS_SETTINGS_TURN_OFF_SYNC_DIALOG_CHECKBOX}, {"syncDisconnectConfirm", @@ -1742,6 +1783,18 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { }; AddLocalizedStringsBulk(html_source, sync_disconnect_strings, arraysize(sync_disconnect_strings)); + + if (IsUnifiedConsentEnabled(profile)) { + html_source->AddLocalizedString( + "syncDisconnectExplanation", + IDS_SETTINGS_SYNC_DISCONNECT_AND_SIGN_OUT_EXPLANATION_UNIFIED_CONSENT); + } else { + html_source->AddString( + "syncDisconnectExplanation", + l10n_util::GetStringFUTF8( + IDS_SETTINGS_SYNC_DISCONNECT_AND_SIGN_OUT_EXPLANATION, + base::ASCIIToUTF16(sync_dashboard_url))); + } } #endif @@ -1756,6 +1809,10 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { html_source->AddBoolean( "changePictureVideoModeEnabled", base::FeatureList::IsEnabled(features::kChangePictureVideoMode)); + + html_source->AddBoolean( + "driveSuggestAvailable", + base::FeatureList::IsEnabled(omnibox::kDocumentProvider)); } void AddPrintingStrings(content::WebUIDataSource* html_source) { @@ -1882,7 +1939,18 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source, {"clearBrowsingData", IDS_SETTINGS_CLEAR_BROWSING_DATA}, {"clearBrowsingDataDescription", IDS_SETTINGS_CLEAR_DATA_DESCRIPTION}, {"titleAndCount", IDS_SETTINGS_TITLE_AND_COUNT}, - {"syncAndPersonalizationLink", IDS_SETTINGS_PRIVACY_MORE_SETTINGS}, + {"safeBrowsingEnableExtendedReporting", + IDS_SETTINGS_SAFEBROWSING_ENABLE_REPORTING}, + {"safeBrowsingEnableExtendedReportingDesc", + IDS_SETTINGS_SAFEBROWSING_ENABLE_REPORTING_DESC}, + {"safeBrowsingEnableProtection", + IDS_SETTINGS_SAFEBROWSING_ENABLEPROTECTION}, + {"safeBrowsingEnableProtectionDesc", + IDS_SETTINGS_SAFEBROWSING_ENABLEPROTECTION_DESC}, + {"urlKeyedAnonymizedDataCollection", + IDS_SETTINGS_ENABLE_URL_KEYED_ANONYMIZED_DATA_COLLECTION}, + {"urlKeyedAnonymizedDataCollectionDesc", + IDS_SETTINGS_ENABLE_URL_KEYED_ANONYMIZED_DATA_COLLECTION_DESC}, }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); @@ -1894,10 +1962,6 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source, {"searchSuggestPref", IDS_SETTINGS_SUGGEST_PREF_UNIFIED_CONSENT}, {"searchSuggestPrefDesc", IDS_SETTINGS_SUGGEST_PREF_DESC_UNIFIED_CONSENT}, - {"safeBrowsingEnableExtendedReporting", - IDS_SETTINGS_SAFEBROWSING_ENABLE_REPORTING_UNIFIED_CONSENT}, - {"safeBrowsingEnableExtendedReportingDesc", - IDS_SETTINGS_SAFEBROWSING_ENABLE_REPORTING_DESC_UNIFIED_CONSENT}, {"networkPredictionEnabled", IDS_SETTINGS_NETWORK_PREDICTION_ENABLED_LABEL_UNIFIED_CONSENT}, {"networkPredictionEnabledDesc", @@ -1905,13 +1969,11 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source, {"linkDoctorPref", IDS_SETTINGS_LINKDOCTOR_PREF_UNIFIED_CONSENT}, {"linkDoctorPrefDesc", IDS_SETTINGS_LINKDOCTOR_PREF_DESC_UNIFIED_CONSENT}, - {"safeBrowsingEnableProtection", - IDS_SETTINGS_SAFEBROWSING_ENABLEPROTECTION_UNIFIED_CONSENT}, - {"safeBrowsingEnableProtectionDesc", - IDS_SETTINGS_SAFEBROWSING_ENABLEPROTECTION_DESC_UNIFIED_CONSENT}, {"spellingPref", IDS_SETTINGS_SPELLING_PREF_UNIFIED_CONSENT}, {"spellingDescription", IDS_SETTINGS_SPELLING_DESCRIPTION_UNIFIED_CONSENT}, + {"syncAndPersonalizationLink", + IDS_SETTINGS_PRIVACY_MORE_SETTINGS_UNIFIED_CONSENT}, {"enableLogging", IDS_SETTINGS_ENABLE_LOGGING_UNIFIED_CONSENT}, {"enableLoggingDesc", IDS_SETTINGS_ENABLE_LOGGING_DESC_UNIFIED_CONSENT}, }; @@ -1921,17 +1983,14 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source, LocalizedString conditional_localized_strings[] = { {"searchSuggestPref", IDS_SETTINGS_SUGGEST_PREF}, {"searchSuggestPrefDesc", IDS_SETTINGS_EMPTY_STRING}, - {"safeBrowsingEnableExtendedReportingDesc", IDS_SETTINGS_EMPTY_STRING}, {"networkPredictionEnabled", IDS_SETTINGS_NETWORK_PREDICTION_ENABLED_LABEL}, {"networkPredictionEnabledDesc", IDS_SETTINGS_EMPTY_STRING}, {"linkDoctorPref", IDS_SETTINGS_LINKDOCTOR_PREF}, {"linkDoctorPrefDesc", IDS_SETTINGS_EMPTY_STRING}, - {"safeBrowsingEnableProtection", - IDS_SETTINGS_SAFEBROWSING_ENABLEPROTECTION}, - {"safeBrowsingEnableProtectionDesc", IDS_SETTINGS_EMPTY_STRING}, {"spellingPref", IDS_SETTINGS_SPELLING_PREF}, {"spellingDescription", IDS_SETTINGS_SPELLING_DESCRIPTION}, + {"syncAndPersonalizationLink", IDS_SETTINGS_PRIVACY_MORE_SETTINGS}, #if defined(OS_CHROMEOS) {"enableLogging", IDS_SETTINGS_ENABLE_LOGGING_DIAGNOSTIC_AND_USAGE_DATA}, #else @@ -1941,19 +2000,12 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source, }; AddLocalizedStringsBulk(html_source, conditional_localized_strings, arraysize(conditional_localized_strings)); - - html_source->AddLocalizedString( - "safeBrowsingEnableExtendedReporting", - safe_browsing::ChooseOptInTextResource( - *profile->GetPrefs(), - IDS_SETTINGS_SAFEBROWSING_ENABLE_EXTENDED_REPORTING, - IDS_SETTINGS_SAFEBROWSING_ENABLE_SCOUT_REPORTING)); } - html_source->AddBoolean( - "importantSitesInCbd", - base::FeatureList::IsEnabled(features::kImportantSitesInCbd)); - + html_source->AddString("syncAndGoogleServicesLearnMoreURL", + IsUnifiedConsentEnabled(profile) + ? chrome::kSyncAndGoogleServicesLearnMoreURL + : ""); html_source->AddString( "improveBrowsingExperience", l10n_util::GetStringFUTF16( @@ -2027,6 +2079,8 @@ void AddSearchStrings(content::WebUIDataSource* html_source, Profile* profile) { html_source->AddString("searchExplanation", search_explanation_text); #if defined(OS_CHROMEOS) html_source->AddBoolean("enableVoiceInteraction", is_assistant_allowed); + html_source->AddBoolean("enableAssistant", + chromeos::switches::IsAssistantEnabled()); #endif } @@ -2067,6 +2121,10 @@ void AddGoogleAssistantStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_CONTEXT}, {"googleAssistantEnableContextDescription", IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_CONTEXT_DESCRIPTION}, + {"googleAssistantEnableHotword", + IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD}, + {"googleAssistantEnableHotwordDescription", + IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD_DESCRIPTION}, {"googleAssistantSettings", IDS_SETTINGS_GOOGLE_ASSISTANT_SETTINGS}, }; AddLocalizedStringsBulk(html_source, localized_strings, @@ -2089,7 +2147,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, {"cookieFlashLso", IDS_SETTINGS_COOKIES_FLASH_LSO}, {"cookieLocalStorage", IDS_SETTINGS_COOKIES_LOCAL_STORAGE}, {"cookieMediaLicense", IDS_SETTINGS_COOKIES_MEDIA_LICENSE}, - {"cookiePlural", IDS_SETTINGS_COOKIES_PLURAL_COOKIES}, {"cookieServiceWorker", IDS_SETTINGS_COOKIES_SERVICE_WORKER}, {"cookieSharedWorker", IDS_SETTINGS_COOKIES_SHARED_WORKER}, {"embeddedOnAnyHost", IDS_SETTINGS_EXCEPTIONS_EMBEDDED_ON_ANY_HOST}, @@ -2156,6 +2213,12 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, {"siteSettingsAllSites", IDS_SETTINGS_SITE_SETTINGS_ALL_SITES}, {"siteSettingsAllSitesDescription", IDS_SETTINGS_SITE_SETTINGS_ALL_SITES_DESCRIPTION}, + {"siteSettingsAllSitesSearch", IDS_SETTINGS_SITE_SETTINGS_ALL_SITES_SEARCH}, + {"siteSettingsAllSitesSort", IDS_SETTINGS_SITE_SETTINGS_ALL_SITES_SORT}, + {"siteSettingsAllSitesSortMethodName", + IDS_SETTINGS_SITE_SETTINGS_ALL_SITES_SORT_METHOD_NAME}, + {"siteSettingsSiteRepresentationSeparator", + IDS_SETTINGS_SITE_SETTINGS_SITE_REPRESENTATION_SEPARATOR}, {"siteSettingsAutomaticDownloads", IDS_SETTINGS_SITE_SETTINGS_AUTOMATIC_DOWNLOADS}, {"siteSettingsBackgroundSync", IDS_SETTINGS_SITE_SETTINGS_BACKGROUND_SYNC}, @@ -2326,11 +2389,19 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, {"siteSettingsCookieSearch", IDS_SETTINGS_SITE_SETTINGS_COOKIE_SEARCH}, {"siteSettingsCookieSubpage", IDS_SETTINGS_SITE_SETTINGS_COOKIE_SUBPAGE}, {"siteSettingsDelete", IDS_SETTINGS_SITE_SETTINGS_DELETE}, + {"siteSettingsSiteClearStorage", + IDS_SETTINGS_SITE_SETTINGS_SITE_CLEAR_STORAGE}, + {"siteSettingsSiteClearStorageConfirmation", + IDS_SETTINGS_SITE_SETTINGS_SITE_CLEAR_STORAGE_CONFIRMATION}, + {"siteSettingsSiteClearStorageDialogTitle", + IDS_SETTINGS_SITE_SETTINGS_SITE_CLEAR_STORAGE_DIALOG_TITLE}, + {"siteSettingsSiteGroupResetDialogTitle", + IDS_SETTINGS_SITE_SETTINGS_SITE_GROUP_RESET_DIALOG_TITLE}, + {"siteSettingsSiteGroupResetConfirmation", + IDS_SETTINGS_SITE_SETTINGS_SITE_GROUP_RESET_CONFIRMATION}, {"siteSettingsSiteResetAll", IDS_SETTINGS_SITE_SETTINGS_SITE_RESET_ALL}, {"siteSettingsSiteResetConfirmation", IDS_SETTINGS_SITE_SETTINGS_SITE_RESET_CONFIRMATION}, - {"siteSettingsSiteResetDialogTitle", - IDS_SETTINGS_SITE_SETTINGS_SITE_RESET_DIALOG_TITLE}, {"thirdPartyCookie", IDS_SETTINGS_SITE_SETTINGS_THIRD_PARTY_COOKIE}, {"thirdPartyCookieSublabel", IDS_SETTINGS_SITE_SETTINGS_THIRD_PARTY_COOKIE_SUBLABEL}, @@ -2365,7 +2436,7 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, html_source->AddBoolean( "enableSafeBrowsingSubresourceFilter", base::FeatureList::IsEnabled( - subresource_filter::kSafeBrowsingSubresourceFilterExperimentalUI)); + subresource_filter::kSafeBrowsingSubresourceFilter)); html_source->AddBoolean( "enableSoundContentSetting", @@ -2383,12 +2454,20 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, "enablePaymentHandlerContentSetting", base::FeatureList::IsEnabled(features::kServiceWorkerPaymentApps)); + html_source->AddBoolean( + "enableEphemeralFlashPermission", + base::FeatureList::IsEnabled( + content_settings::features::kEnableEphemeralFlashPermission)); + if (PluginUtils::ShouldPreferHtmlOverPlugins( HostContentSettingsMapFactory::GetForProfile(profile))) { LocalizedString flash_strings[] = { {"siteSettingsFlashAskFirst", IDS_SETTINGS_SITE_SETTINGS_ASK_FIRST}, {"siteSettingsFlashAskFirstRecommended", IDS_SETTINGS_SITE_SETTINGS_ASK_FIRST_RECOMMENDED}, + {"siteSettingsFlashPermissionsEphemeral", + IDS_SETTINGS_SITE_SETTINGS_FLASH_PERMISSIONS_ARE_EPHEMERAL}, + }; AddLocalizedStringsBulk(html_source, flash_strings, arraysize(flash_strings)); @@ -2398,6 +2477,8 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_SITE_SETTINGS_FLASH_DETECT_IMPORTANT}, {"siteSettingsFlashAskFirstRecommended", IDS_SETTINGS_SITE_SETTINGS_FLASH_DETECT_IMPORTANT_RECOMMENDED}, + {"siteSettingsFlashPermissionsEphemeral", + IDS_SETTINGS_SITE_SETTINGS_FLASH_PERMISSIONS_ARE_EPHEMERAL}, }; AddLocalizedStringsBulk(html_source, flash_strings, arraysize(flash_strings)); @@ -2476,14 +2557,50 @@ void AddWebContentStrings(content::WebUIDataSource* html_source) { void AddMultideviceStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"multidevicePageTitle", IDS_SETTINGS_MULTIDEVICE}, - {"smsConnect", IDS_SETTINGS_MULTIDEVICE_SMS_CONNECT}, - {"smsConnectSummary", IDS_SETTINGS_MULTIDEVICE_SMS_CONNECT_SUMMARY}, + {"multideviceSetupButton", IDS_SETTINGS_MULTIDEVICE_SETUP_BUTTON}, + {"multideviceVerifyButton", IDS_SETTINGS_MULTIDEVICE_VERIFY_BUTTON}, + {"multideviceSetupItemHeading", + IDS_SETTINGS_MULTIDEVICE_SETUP_ITEM_HEADING}, + {"multideviceEnabled", IDS_SETTINGS_MULTIDEVICE_ENABLED}, + {"multideviceDisabled", IDS_SETTINGS_MULTIDEVICE_DISABLED}, + {"multideviceSmartLockItemTitle", IDS_SETTINGS_EASY_UNLOCK_SECTION_TITLE}, + {"multideviceInstantTetheringItemTitle", + IDS_SETTINGS_MULTIDEVICE_INSTANT_TETHERING}, + {"multideviceAndroidMessagesItemTitle", + IDS_SETTINGS_MULTIDEVICE_ANDROID_MESSAGES}, + {"multideviceAndroidMessagesItemSummary", + IDS_SETTINGS_MULTIDEVICE_ANDROID_MESSAGES_SUMMARY}, + {"multideviceForgetDevice", IDS_SETTINGS_MULTIDEVICE_FORGET_THIS_DEVICE}, + {"multideviceForgetDeviceSummary", + IDS_SETTINGS_MULTIDEVICE_FORGET_THIS_DEVICE_EXPLANATION}, }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); - html_source->AddBoolean("enableMultideviceSettings", - base::FeatureList::IsEnabled(features::kMultidevice)); + html_source->AddBoolean( + "enableMultideviceSettings", + base::FeatureList::IsEnabled( + chromeos::features::kEnableUnifiedMultiDeviceSettings)); + html_source->AddString( + "multideviceVerificationText", + l10n_util::GetStringFUTF16( + IDS_SETTINGS_MULTIDEVICE_VERIFICATION_TEXT, + GetHelpUrlWithBoard(chrome::kMultiDeviceLearnMoreURL))); + html_source->AddString( + "multideviceCouldNotConnect", + l10n_util::GetStringFUTF16( + IDS_SETTINGS_MULTIDEVICE_COULD_NOT_CONNECT, + GetHelpUrlWithBoard(chrome::kMultiDeviceLearnMoreURL))); + html_source->AddString( + "multideviceSetupSummary", + l10n_util::GetStringFUTF16( + IDS_SETTINGS_MULTIDEVICE_SETUP_SUMMARY, + GetHelpUrlWithBoard(chrome::kMultiDeviceLearnMoreURL))); + html_source->AddString( + "multideviceSmartLockItemSummary", + l10n_util::GetStringFUTF16( + IDS_SETTINGS_MULTIDEVICE_SMART_LOCK_SUMMARY, + GetHelpUrlWithBoard(chrome::kEasyUnlockLearnMoreUrl))); } #endif diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc index c7ca00e9642..e2feea6212e 100644 --- a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc +++ b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc @@ -75,7 +75,6 @@ #include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_utils.h" #include "chrome/browser/signin/account_tracker_service_factory.h" -#include "chrome/browser/ui/ash/ash_util.h" #include "chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h" @@ -92,17 +91,19 @@ #include "chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/internet_handler.h" +#include "chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/smb_handler.h" #include "chrome/common/chrome_switches.h" #include "chromeos/account_manager/account_manager.h" #include "chromeos/account_manager/account_manager_factory.h" #include "chromeos/chromeos_switches.h" #include "components/arc/arc_util.h" +#include "ui/base/ui_base_features.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" #include "chrome/browser/ui/webui/settings/settings_manage_profile_handler.h" #include "chrome/browser/ui/webui/settings/system_handler.h" -#include "components/signin/core/browser/profile_management_switches.h" #endif // defined(OS_CHROMEOS) #if defined(USE_NSS_CERTS) @@ -182,15 +183,19 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) AddSettingsPageUIHandler( std::make_unique<chromeos::settings::AndroidAppsHandler>(profile)); - chromeos::AccountManagerFactory* factory = - g_browser_process->platform_part()->GetAccountManagerFactory(); - chromeos::AccountManager* account_manager = - factory->GetAccountManager(profile->GetPath().value()); - DCHECK(account_manager); - AddSettingsPageUIHandler( - std::make_unique<chromeos::settings::AccountManagerUIHandler>( - account_manager, - AccountTrackerServiceFactory::GetInstance()->GetForProfile(profile))); + if (!profile->IsGuestSession()) { + chromeos::AccountManagerFactory* factory = + g_browser_process->platform_part()->GetAccountManagerFactory(); + chromeos::AccountManager* account_manager = + factory->GetAccountManager(profile->GetPath().value()); + DCHECK(account_manager); + + AddSettingsPageUIHandler( + std::make_unique<chromeos::settings::AccountManagerUIHandler>( + account_manager, + AccountTrackerServiceFactory::GetInstance()->GetForProfile( + profile))); + } AddSettingsPageUIHandler( std::make_unique<chromeos::settings::ChangePictureHandler>()); if (IsCrostiniUIAllowedForProfile(profile)) { @@ -201,18 +206,21 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) std::make_unique<chromeos::settings::CupsPrintersHandler>(web_ui)); AddSettingsPageUIHandler( std::make_unique<chromeos::settings::FingerprintHandler>(profile)); - if (chromeos::switches::IsVoiceInteractionEnabled()) { + if (chromeos::switches::IsVoiceInteractionEnabled() || + chromeos::switches::IsAssistantEnabled()) { AddSettingsPageUIHandler( std::make_unique<chromeos::settings::GoogleAssistantHandler>(profile)); } AddSettingsPageUIHandler( std::make_unique<chromeos::settings::KeyboardHandler>()); AddSettingsPageUIHandler( + std::make_unique<chromeos::settings::MultideviceHandler>()); + AddSettingsPageUIHandler( std::make_unique<chromeos::settings::PointerHandler>()); AddSettingsPageUIHandler( std::make_unique<chromeos::settings::SmbHandler>(profile)); AddSettingsPageUIHandler( - std::make_unique<chromeos::settings::StorageHandler>()); + std::make_unique<chromeos::settings::StorageHandler>(profile)); AddSettingsPageUIHandler( std::make_unique<chromeos::settings::StylusHandler>()); AddSettingsPageUIHandler( @@ -230,8 +238,6 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUISettingsHost); - html_source->OverrideContentSecurityPolicyScriptSrc( - "script-src chrome://resources 'self';"); #if defined(OS_WIN) AddSettingsPageUIHandler(std::make_unique<ChromeCleanupHandler>(profile)); @@ -310,20 +316,27 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) html_source->AddBoolean("havePlayStoreApp", arc::IsPlayStoreAvailable()); // TODO(mash): Support Chrome power settings in Mash. crbug.com/644348 - bool enable_power_settings = !ash_util::IsRunningInMash(); + bool enable_power_settings = features::IsAshInBrowserProcess(); html_source->AddBoolean("enablePowerSettings", enable_power_settings); if (enable_power_settings) { AddSettingsPageUIHandler(std::make_unique<chromeos::settings::PowerHandler>( profile->GetPrefs())); } #else // !defined(OS_CHROMEOS) - html_source->AddBoolean("diceEnabled", - signin::IsDiceEnabledForProfile(profile->GetPrefs())); + html_source->AddBoolean( + "diceEnabled", + AccountConsistencyModeManager::IsDiceEnabledForProfile(profile)); #endif // defined(OS_CHROMEOS) html_source->AddBoolean("unifiedConsentEnabled", IsUnifiedConsentEnabled(profile)); + // TODO(jdoerrie): https://crbug.com/854562. + // Remove once Autofill Home is launched. + html_source->AddBoolean( + "autofillHomeEnabled", + base::FeatureList::IsEnabled(password_manager::features::kAutofillHome)); + html_source->AddBoolean("showImportPasswords", base::FeatureList::IsEnabled( password_manager::features::kPasswordImport)); diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.cc b/chromium/chrome/browser/ui/webui/settings/people_handler.cc index 75d91f07c7c..d33f651f224 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.cc @@ -21,6 +21,7 @@ #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/signin/chrome_signin_helper.h" +#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_error_controller_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/signin/signin_promo.h" @@ -42,6 +43,7 @@ #include "components/browser_sync/profile_sync_service.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/profile_management_switches.h" +#include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_error_controller.h" #include "components/signin/core/browser/signin_header_helper.h" #include "components/signin/core/browser/signin_metrics.h" @@ -251,9 +253,8 @@ void PeopleHandler::RegisterMessages() { base::Unretained(this))); #else web_ui()->RegisterMessageCallback( - "SyncSetupStopSyncing", - base::BindRepeating(&PeopleHandler::HandleStopSyncing, - base::Unretained(this))); + "SyncSetupSignout", base::BindRepeating(&PeopleHandler::HandleSignout, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "SyncSetupStartSignIn", base::BindRepeating(&PeopleHandler::HandleStartSignin, @@ -614,10 +615,12 @@ void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { ProfileSyncService* service = GetSyncService(); - // Just let the page open for now, even when the user's not signed in. + // Just let the page open for now, even when the user's not signed in or sync + // is disabled. // TODO(scottchen): finish the UI for signed-out users // (https://crbug.com/800972). - if (IsUnifiedConsentEnabled(profile_) && IsProfileAuthNeededOrHasErrors()) { + if (IsUnifiedConsentEnabled(profile_) && + (IsProfileAuthNeededOrHasErrors() || !service)) { if (service && !sync_blocker_) sync_blocker_ = service->GetSetupInProgressHandle(); @@ -708,19 +711,30 @@ void PeopleHandler::HandleStartSignin(const base::ListValue* args) { DisplayGaiaLogin(signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); } -void PeopleHandler::HandleStopSyncing(const base::ListValue* args) { +void PeopleHandler::HandleSignout(const base::ListValue* args) { bool delete_profile = false; args->GetBoolean(0, &delete_profile); - if (!SigninManagerFactory::GetForProfile(profile_)->IsSignoutProhibited()) { - if (GetSyncService()) - ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS); - - signin_metrics::SignoutDelete delete_metric = - delete_profile ? signin_metrics::SignoutDelete::DELETED - : signin_metrics::SignoutDelete::KEEPING; - SigninManagerFactory::GetForProfile(profile_) - ->SignOut(signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric); + SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_); + if (signin_manager->IsSignoutProhibited()) { + // If the user cannot signout, the profile must be destroyed. + DCHECK(delete_profile); + } else { + if (signin_manager->IsAuthenticated()) { + if (GetSyncService()) + ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS); + + signin_metrics::SignoutDelete delete_metric = + delete_profile ? signin_metrics::SignoutDelete::DELETED + : signin_metrics::SignoutDelete::KEEPING; + signin_manager->SignOutAndRemoveAllAccounts( + signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric); + } else { + DCHECK(!delete_profile) + << "Deleting the profile should only be offered the user is syncing."; + ProfileOAuth2TokenServiceFactory::GetForProfile(profile_) + ->RevokeAllCredentials(); + } } if (delete_profile) { @@ -877,10 +891,13 @@ PeopleHandler::GetSyncStatusDictionary() { // makes Profile::IsSyncAllowed() false. ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_); + bool disallowed_by_policy = + service && service->HasDisableReason( + syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY); sync_status->SetBoolean("signinAllowed", signin->IsSigninAllowed()); sync_status->SetBoolean("syncSystemEnabled", (service != nullptr)); sync_status->SetBoolean("setupInProgress", - service && !service->IsManaged() && + service && !disallowed_by_policy && service->IsFirstSetupInProgress() && signin->IsAuthenticated()); @@ -896,7 +913,12 @@ PeopleHandler::GetSyncStatusDictionary() { sync_status->SetBoolean("hasError", status_has_error); sync_status->SetString("statusAction", GetSyncErrorAction(action_type)); - sync_status->SetBoolean("managed", service && service->IsManaged()); + sync_status->SetBoolean("managed", disallowed_by_policy); + sync_status->SetBoolean( + "disabled", + !service || disallowed_by_policy || + service->HasDisableReason( + syncer::SyncService::DISABLE_REASON_PLATFORM_OVERRIDE)); sync_status->SetBoolean("signedIn", signin->IsAuthenticated()); sync_status->SetString("signedInUsername", signin_ui_util::GetAuthenticatedUsername(signin)); diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.h b/chromium/chrome/browser/ui/webui/settings/people_handler.h index b39378b9726..bfedcdc900e 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.h @@ -174,7 +174,7 @@ class PeopleHandler : public SettingsPageUIHandler, void HandleRequestPinLoginState(const base::ListValue* args); #endif void HandleStartSignin(const base::ListValue* args); - void HandleStopSyncing(const base::ListValue* args); + void HandleSignout(const base::ListValue* args); void HandleGetSyncStatus(const base::ListValue* args); void HandleManageOtherPeople(const base::ListValue* args); 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 8964c907cb6..58a9f2b000a 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc @@ -106,6 +106,7 @@ std::string GetConfiguration(const base::DictionaryValue* extra_values, result.SetBoolean("tabsSynced", types.Has(syncer::PROXY_TABS)); result.SetBoolean("themesSynced", types.Has(syncer::THEMES)); result.SetBoolean("typedUrlsSynced", types.Has(syncer::TYPED_URLS)); + result.SetBoolean("userEventsSynced", types.Has(syncer::USER_EVENTS)); result.SetBoolean("paymentsIntegrationEnabled", false); std::string args; base::JSONWriter::Write(result, &args); @@ -153,6 +154,7 @@ void CheckConfigDataTypeArguments(const base::DictionaryValue* dictionary, CheckBool(dictionary, "tabsSynced", types.Has(syncer::PROXY_TABS)); CheckBool(dictionary, "themesSynced", types.Has(syncer::THEMES)); CheckBool(dictionary, "typedUrlsSynced", types.Has(syncer::TYPED_URLS)); + CheckBool(dictionary, "userEventsSynced", types.Has(syncer::USER_EVENTS)); } } // namespace @@ -233,7 +235,8 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { // Setup the expectations for calls made when displaying the config page. void SetDefaultExpectationsForConfigPage() { - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly(Return(syncer::SyncService::DISABLE_REASON_NONE)); EXPECT_CALL(*mock_pss_, GetRegisteredDataTypes()) .WillRepeatedly(Return(GetAllTypes())); EXPECT_CALL(*mock_pss_, GetPreferredDataTypes()) @@ -333,7 +336,9 @@ TEST_F(PeopleHandlerFirstSigninTest, DisplayBasicLogin) { // Test that the HandleStartSignin call enables JavaScript. handler_->DisallowJavascript(); - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly( + Return(syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); // Ensure that the user is not signed in before calling |HandleStartSignin()|. SigninManager* manager = SigninManager::FromSigninManagerBase(mock_signin_); @@ -356,7 +361,9 @@ TEST_F(PeopleHandlerFirstSigninTest, DisplayBasicLogin) { } TEST_F(PeopleHandlerTest, ShowSyncSetupWhenNotSignedIn) { - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly( + Return(syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); handler_->HandleShowSetupUI(nullptr); @@ -372,7 +379,9 @@ TEST_F(PeopleHandlerTest, ShowSyncSetupWhenNotSignedIn) { // Verifies that the sync setup is terminated correctly when the // sync is disabled. TEST_F(PeopleHandlerTest, HandleSetupUIWhenSyncDisabled) { - EXPECT_CALL(*mock_pss_, IsManaged()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly( + Return(syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY)); handler_->HandleShowSetupUI(nullptr); // Sync setup is closed when sync is disabled. @@ -385,7 +394,8 @@ TEST_F(PeopleHandlerTest, HandleSetupUIWhenSyncDisabled) { // Verifies that the handler correctly handles a cancellation when // it is displaying the spinner to the user. TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndCancel) { - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly(Return(syncer::SyncService::DISABLE_REASON_NONE)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); error_ = GoogleServiceAuthError::AuthErrorNone(); EXPECT_CALL(*mock_pss_, IsEngineInitialized()).WillRepeatedly(Return(false)); @@ -409,8 +419,9 @@ TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndCancel) { // to showing a configuration page when sync setup completes successfully. TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndSyncStartupCompleted) { - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly(Return(syncer::SyncService::DISABLE_REASON_NONE)); error_ = GoogleServiceAuthError::AuthErrorNone(); // Sync engine is stopped initially, and will start up. EXPECT_CALL(*mock_pss_, IsEngineInitialized()).WillRepeatedly(Return(false)); @@ -446,7 +457,8 @@ TEST_F(PeopleHandlerTest, // user has continued on. TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndCancelAfterSigninSuccess) { - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly(Return(syncer::SyncService::DISABLE_REASON_NONE)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); error_ = GoogleServiceAuthError::AuthErrorNone(); EXPECT_CALL(*mock_pss_, IsEngineInitialized()) @@ -469,7 +481,8 @@ TEST_F(PeopleHandlerTest, } TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndSigninFailed) { - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly(Return(syncer::SyncService::DISABLE_REASON_NONE)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); error_ = GoogleServiceAuthError::AuthErrorNone(); EXPECT_CALL(*mock_pss_, IsEngineInitialized()).WillRepeatedly(Return(false)); @@ -526,20 +539,11 @@ class PeopleHandlerNonCrosTest : public PeopleHandlerTest { PeopleHandlerNonCrosTest() {} }; -TEST_F(PeopleHandlerNonCrosTest, HandleGaiaAuthFailure) { - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); - EXPECT_CALL(*mock_pss_, HasUnrecoverableError()) - .WillRepeatedly(Return(false)); - EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); - // Open the web UI. - handler_->HandleShowSetupUI(nullptr); - - ASSERT_FALSE(handler_->is_configuring_sync()); -} - // TODO(kochi): We need equivalent tests for ChromeOS. TEST_F(PeopleHandlerNonCrosTest, UnrecoverableErrorInitializingSync) { - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly( + Return(syncer::SyncService::DISABLE_REASON_UNRECOVERABLE_ERROR)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); // Open the web UI. handler_->HandleShowSetupUI(nullptr); @@ -548,7 +552,9 @@ TEST_F(PeopleHandlerNonCrosTest, UnrecoverableErrorInitializingSync) { } TEST_F(PeopleHandlerNonCrosTest, GaiaErrorInitializingSync) { - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly( + Return(syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); // Open the web UI. handler_->HandleShowSetupUI(nullptr); @@ -767,7 +773,8 @@ TEST_F(PeopleHandlerTest, ShowSigninOnAuthError) { FakeAuthStatusProvider provider( SigninErrorControllerFactory::GetForProfile(profile())); provider.SetAuthError(kTestUser, error_); - EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(true)); + EXPECT_CALL(*mock_pss_, GetDisableReasons()) + .WillRepeatedly(Return(syncer::SyncService::DISABLE_REASON_NONE)); EXPECT_CALL(*mock_pss_, IsPassphraseRequired()) .WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) @@ -819,6 +826,7 @@ TEST_F(PeopleHandlerTest, ShowSetupSyncEverything) { CheckBool(dictionary, "tabsRegistered", true); CheckBool(dictionary, "themesRegistered", true); CheckBool(dictionary, "typedUrlsRegistered", true); + CheckBool(dictionary, "userEventsRegistered", true); CheckBool(dictionary, "paymentsIntegrationEnabled", true); CheckBool(dictionary, "passphraseRequired", false); CheckBool(dictionary, "passphraseTypeIsCustom", false); diff --git a/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc b/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc index d43930fb1e8..56b43446319 100644 --- a/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc @@ -47,9 +47,6 @@ void SafeBrowsingHandler::RegisterMessages() { void SafeBrowsingHandler::OnJavascriptAllowed() { profile_pref_registrar_.Init(prefs_); profile_pref_registrar_.Add( - prefs::kSafeBrowsingExtendedReportingEnabled, - base::Bind(&SafeBrowsingHandler::OnPrefChanged, base::Unretained(this))); - profile_pref_registrar_.Add( prefs::kSafeBrowsingScoutReportingEnabled, base::Bind(&SafeBrowsingHandler::OnPrefChanged, base::Unretained(this))); } @@ -76,8 +73,7 @@ void SafeBrowsingHandler::HandleSetSafeBrowsingExtendedReportingEnabled( } void SafeBrowsingHandler::OnPrefChanged(const std::string& pref_name) { - DCHECK(pref_name == prefs::kSafeBrowsingExtendedReportingEnabled || - pref_name == prefs::kSafeBrowsingScoutReportingEnabled); + DCHECK(pref_name == prefs::kSafeBrowsingScoutReportingEnabled); FireWebUIListener("safe-browsing-extended-reporting-change", GetSberStateDictionaryValue(*prefs_)); 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 878159e995c..be2b79caa67 100644 --- a/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc @@ -18,7 +18,6 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/search_engines/ui_thread_search_terms_data.h" -#include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/ui/search_engines/template_url_table_model.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" @@ -26,7 +25,6 @@ #include "components/prefs/pref_service.h" #include "components/search_engines/template_url.h" #include "components/search_engines/template_url_service.h" -#include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/web_ui.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" @@ -34,8 +32,8 @@ #include "extensions/common/extension.h" namespace { -// The following strings need to match with the IDs of the paper-input elements -// at settings/search_engines_page/add_search_engine_dialog.html. +// The following strings need to match with the IDs of the text input elements +// at settings/search_engines_page/search_engine_dialog.html. const char kSearchEngineField[] = "searchEngine"; const char kKeywordField[] = "keyword"; const char kQueryUrlField[] = "queryUrl"; diff --git a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc index c1442684021..871a956100d 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc @@ -17,8 +17,6 @@ #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h" #include "chrome/browser/browsing_data/counters/browsing_data_counter_factory.h" #include "chrome/browser/browsing_data/counters/browsing_data_counter_utils.h" -#include "chrome/browser/engagement/important_sites_usage_counter.h" -#include "chrome/browser/engagement/important_sites_util.h" #include "chrome/browser/history/web_history_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" @@ -42,7 +40,6 @@ #include "chrome/browser/feature_engagement/incognito_window/incognito_window_tracker_factory.h" #endif -using ImportantReason = ImportantSitesUtil::ImportantReason; using BrowsingDataType = browsing_data::BrowsingDataType; namespace { @@ -67,13 +64,6 @@ const char* kCounterPrefsBasic[] = { browsing_data::prefs::kDeleteCacheBasic, }; -const char kRegisterableDomainField[] = "registerableDomain"; -const char kReasonBitField[] = "reasonBitfield"; -const char kExampleOriginField[] = "exampleOrigin"; -const char kIsCheckedField[] = "isChecked"; -const char kStorageSizeField[] = "storageSize"; -const char kHasNotificationsField[] = "hasNotifications"; - } // namespace namespace settings { @@ -97,11 +87,6 @@ void ClearBrowsingDataHandler::RegisterMessages() { base::Unretained(this))); web_ui()->RegisterMessageCallback( - "getImportantSites", - base::BindRepeating(&ClearBrowsingDataHandler::HandleGetImportantSites, - base::Unretained(this))); - - web_ui()->RegisterMessageCallback( "initializeClearBrowsingData", base::BindRepeating(&ClearBrowsingDataHandler::HandleInitialize, base::Unretained(this))); @@ -144,27 +129,23 @@ void ClearBrowsingDataHandler::OnJavascriptDisallowed() { void ClearBrowsingDataHandler::HandleClearBrowsingDataForTest() { // HandleClearBrowsingData takes in a ListValue as its only parameter. The // ListValue must contain four values: web_ui callback ID, a list of data - // types that the user cleared from the clear browsing data UI, time period of - // the data to be cleared, and important sites to remove. + // types that the user cleared from the clear browsing data UI and time period + // of the data to be cleared. std::unique_ptr<base::ListValue> data_types = std::make_unique<base::ListValue>(); data_types->AppendString("browser.clear_data.browsing_history"); - std::unique_ptr<base::ListValue> important_sites = - std::make_unique<base::ListValue>(); - base::ListValue list_args; list_args.AppendString("webui_callback_id"); list_args.Append(std::move(data_types)); list_args.AppendInteger(1u); - list_args.Append(std::move(important_sites)); HandleClearBrowsingData(&list_args); } void ClearBrowsingDataHandler::HandleClearBrowsingData( const base::ListValue* args) { - CHECK_EQ(4U, args->GetSize()); + CHECK_EQ(3U, args->GetSize()); std::string webui_callback_id; CHECK(args->GetString(0, &webui_callback_id)); @@ -270,11 +251,6 @@ void ClearBrowsingDataHandler::HandleClearBrowsingData( int period_selected; CHECK(args->GetInteger(2, &period_selected)); - const base::ListValue* important_sites = nullptr; - CHECK(args->GetList(3, &important_sites)); - std::unique_ptr<content::BrowsingDataFilterBuilder> filter_builder = - ProcessImportantSites(important_sites); - content::BrowsingDataRemover* remover = content::BrowserContext::GetBrowsingDataRemover(profile_); @@ -285,8 +261,11 @@ void ClearBrowsingDataHandler::HandleClearBrowsingData( static_cast<browsing_data::TimePeriod>(period_selected); browsing_data_important_sites_util::Remove( - remove_mask, origin_mask, time_period, std::move(filter_builder), remover, - std::move(callback)); + remove_mask, origin_mask, time_period, + content::BrowsingDataFilterBuilder::Create( + content::BrowsingDataFilterBuilder::BLACKLIST), + remover, std::move(callback)); + #if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) feature_engagement::IncognitoWindowTrackerFactory::GetInstance() ->GetForProfile(profile_) @@ -294,46 +273,6 @@ void ClearBrowsingDataHandler::HandleClearBrowsingData( #endif } -std::unique_ptr<content::BrowsingDataFilterBuilder> -ClearBrowsingDataHandler::ProcessImportantSites( - const base::ListValue* important_sites) { - std::vector<std::string> excluding_domains; - std::vector<int32_t> excluding_domain_reasons; - std::vector<std::string> ignoring_domains; - std::vector<int32_t> ignoring_domain_reasons; - for (const auto& item : *important_sites) { - const base::DictionaryValue* site = nullptr; - CHECK(item.GetAsDictionary(&site)); - bool is_checked = false; - CHECK(site->GetBoolean(kIsCheckedField, &is_checked)); - std::string domain; - CHECK(site->GetString(kRegisterableDomainField, &domain)); - int domain_reason = -1; - CHECK(site->GetInteger(kReasonBitField, &domain_reason)); - if (is_checked) { // Selected important sites should be deleted. - ignoring_domains.push_back(domain); - ignoring_domain_reasons.push_back(domain_reason); - } else { // Unselected sites should be kept. - excluding_domains.push_back(domain); - excluding_domain_reasons.push_back(domain_reason); - } - } - - if (!excluding_domains.empty() || !ignoring_domains.empty()) { - ImportantSitesUtil::RecordBlacklistedAndIgnoredImportantSites( - profile_->GetOriginalProfile(), excluding_domains, - excluding_domain_reasons, ignoring_domains, ignoring_domain_reasons); - } - - std::unique_ptr<content::BrowsingDataFilterBuilder> filter_builder( - content::BrowsingDataFilterBuilder::Create( - content::BrowsingDataFilterBuilder::BLACKLIST)); - for (const std::string& domain : excluding_domains) { - filter_builder->AddRegisterableDomain(domain); - } - return filter_builder; -} - void ClearBrowsingDataHandler::OnClearingTaskFinished( const std::string& webui_callback_id, const base::flat_set<BrowsingDataType>& data_types) { @@ -365,59 +304,6 @@ void ClearBrowsingDataHandler::OnClearingTaskFinished( base::Value(show_notice)); } -void ClearBrowsingDataHandler::HandleGetImportantSites( - const base::ListValue* args) { - AllowJavascript(); - std::string callback_id; - CHECK(args->GetString(0, &callback_id)); - DCHECK(base::FeatureList::IsEnabled(features::kImportantSitesInCbd)); - - Profile* profile = profile_->GetOriginalProfile(); - bool important_sites_dialog_disabled = - ImportantSitesUtil::IsDialogDisabled(profile); - - if (important_sites_dialog_disabled) { - ResolveJavascriptCallback(base::Value(callback_id), base::ListValue()); - return; - } - - std::vector<ImportantSitesUtil::ImportantDomainInfo> important_sites = - ImportantSitesUtil::GetImportantRegisterableDomains( - profile, ImportantSitesUtil::kMaxImportantSites); - content::StoragePartition* partition = - content::BrowserContext::GetDefaultStoragePartition(profile); - storage::QuotaManager* quota_manager = partition->GetQuotaManager(); - content::DOMStorageContext* dom_storage = partition->GetDOMStorageContext(); - - ImportantSitesUsageCounter::GetUsage( - std::move(important_sites), quota_manager, dom_storage, - base::BindOnce(&ClearBrowsingDataHandler::OnFetchImportantSitesFinished, - weak_ptr_factory_.GetWeakPtr(), callback_id)); -} - -void ClearBrowsingDataHandler::OnFetchImportantSitesFinished( - const std::string& callback_id, - std::vector<ImportantSitesUtil::ImportantDomainInfo> important_sites) { - base::ListValue important_sites_list; - - for (const auto& info : important_sites) { - auto entry = std::make_unique<base::DictionaryValue>(); - entry->SetString(kRegisterableDomainField, info.registerable_domain); - // The |reason_bitfield| is only passed to Javascript to be logged - // from |HandleClearBrowsingData|. - entry->SetInteger(kReasonBitField, info.reason_bitfield); - entry->SetString(kExampleOriginField, info.example_origin.spec()); - // Initially all sites are selected for deletion. - entry->SetBoolean(kIsCheckedField, true); - entry->SetString(kStorageSizeField, ui::FormatBytes(info.usage)); - bool has_notifications = - (info.reason_bitfield & (1 << ImportantReason::NOTIFICATIONS)) != 0; - entry->SetBoolean(kHasNotificationsField, has_notifications); - important_sites_list.Append(std::move(entry)); - } - ResolveJavascriptCallback(base::Value(callback_id), important_sites_list); -} - void ClearBrowsingDataHandler::HandleInitialize(const base::ListValue* args) { AllowJavascript(); const base::Value* callback_id; @@ -447,7 +333,8 @@ void ClearBrowsingDataHandler::UpdateSyncState() { base::Value(signin_manager && signin_manager->IsAuthenticated()), base::Value(sync_service_ && sync_service_->IsSyncActive() && sync_service_->GetActiveDataTypes().Has( - syncer::HISTORY_DELETE_DIRECTIVES))); + syncer::HISTORY_DELETE_DIRECTIVES)), + base::Value(ShouldShowCookieException(profile_))); } void ClearBrowsingDataHandler::RefreshHistoryNotice() { diff --git a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h index f135b0172af..40fcfa0b06f 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h @@ -12,7 +12,6 @@ #include "base/containers/flat_set.h" #include "base/macros.h" #include "base/scoped_observer.h" -#include "chrome/browser/engagement/important_sites_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "components/browser_sync/profile_sync_service.h" @@ -24,7 +23,6 @@ class ListValue; } namespace content { -class BrowsingDataFilterBuilder; class WebUI; } @@ -49,10 +47,6 @@ class ClearBrowsingDataHandler : public SettingsPageUIHandler, // Clears browsing data, called by Javascript. void HandleClearBrowsingData(const base::ListValue* value); - // Parses a ListValue with important site information and creates a - // BrowsingDataFilterBuilder. - std::unique_ptr<content::BrowsingDataFilterBuilder> ProcessImportantSites( - const base::ListValue* important_sites); // Called when a clearing task finished. |webui_callback_id| is provided // by the WebUI action that initiated it. @@ -60,13 +54,6 @@ class ClearBrowsingDataHandler : public SettingsPageUIHandler, const std::string& webui_callback_id, const base::flat_set<browsing_data::BrowsingDataType>& data_types); - // Get important sites, called by Javascript. - void HandleGetImportantSites(const base::ListValue* value); - - void OnFetchImportantSitesFinished( - const std::string& callback_id, - std::vector<ImportantSitesUtil::ImportantDomainInfo> sites); - // Initializes the dialog UI. Called by JavaScript when the DOM is ready. void HandleInitialize(const base::ListValue* args); 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 2017d6c1fee..9150748cdba 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 @@ -52,11 +52,6 @@ int GetCategoryLabelID(CookieTreeNode::DetailedInfo::NodeType node_type) { } kCategoryLabels[] = { // Multiple keys (node_type) may have the same value (id). - {CookieTreeNode::DetailedInfo::TYPE_COOKIES, - IDS_SETTINGS_COOKIES_SINGLE_COOKIE}, - {CookieTreeNode::DetailedInfo::TYPE_COOKIE, - IDS_SETTINGS_COOKIES_SINGLE_COOKIE}, - {CookieTreeNode::DetailedInfo::TYPE_DATABASES, IDS_SETTINGS_COOKIES_DATABASE_STORAGE}, {CookieTreeNode::DetailedInfo::TYPE_DATABASE, @@ -179,6 +174,10 @@ void CookiesViewHandler::RegisterMessages() { base::BindRepeating(&CookiesViewHandler::HandleGetCookieDetails, base::Unretained(this))); web_ui()->RegisterMessageCallback( + "localData.getNumCookiesString", + base::BindRepeating(&CookiesViewHandler::HandleGetNumCookiesString, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "localData.removeCookie", base::BindRepeating(&CookiesViewHandler::HandleRemove, base::Unretained(this))); @@ -268,8 +267,8 @@ void CookiesViewHandler::EnsureCookiesTreeModelCreated() { storage_partition->GetCacheStorageContext(); storage::FileSystemContext* file_system_context = storage_partition->GetFileSystemContext(); - LocalDataContainer* container = new LocalDataContainer( - new BrowsingDataCookieHelper(profile->GetRequestContext()), + auto container = std::make_unique<LocalDataContainer>( + new BrowsingDataCookieHelper(storage_partition), new BrowsingDataDatabaseHelper(profile), new BrowsingDataLocalStorageHelper(profile), /*session_storage_helper=*/nullptr, @@ -284,9 +283,8 @@ void CookiesViewHandler::EnsureCookiesTreeModelCreated() { new BrowsingDataCacheStorageHelper(cache_storage_context), BrowsingDataFlashLSOHelper::Create(profile), BrowsingDataMediaLicenseHelper::Create(file_system_context)); - cookies_tree_model_.reset( - new CookiesTreeModel(container, - profile->GetExtensionSpecialStoragePolicy())); + cookies_tree_model_ = std::make_unique<CookiesTreeModel>( + std::move(container), profile->GetExtensionSpecialStoragePolicy()); cookies_tree_model_->AddCookiesTreeObserver(this); } } @@ -311,6 +309,61 @@ void CookiesViewHandler::HandleGetCookieDetails(const base::ListValue* args) { SendCookieDetails(node); } +void CookiesViewHandler::HandleGetNumCookiesString( + const base::ListValue* args) { + CHECK_EQ(2U, args->GetSize()); + std::string callback_id; + CHECK(args->GetString(0, &callback_id)); + base::string16 etld_plus1; + CHECK(args->GetString(1, &etld_plus1)); + + AllowJavascript(); + CHECK(cookies_tree_model_.get()); + // This method is only interested in the number of cookies, so don't save the + // filter and keep the existing |sorted_sites_| list. + if (etld_plus1 != filter_) + cookies_tree_model_->UpdateSearchResults(etld_plus1); + + int num_cookies = 0; + const CookieTreeNode* root = cookies_tree_model_->GetRoot(); + for (int i = 0; i < root->child_count(); ++i) { + const CookieTreeNode* site = root->GetChild(i); + const base::string16& title = site->GetTitle(); + if (!base::EndsWith(title, etld_plus1, + base::CompareCase::INSENSITIVE_ASCII)) { + continue; + } + + for (int j = 0; j < site->child_count(); ++j) { + const CookieTreeNode* category = site->GetChild(j); + if (category->GetDetailedInfo().node_type != + CookieTreeNode::DetailedInfo::TYPE_COOKIES) { + continue; + } + + for (int k = 0; k < category->child_count(); ++k) { + if (category->GetChild(k)->GetDetailedInfo().node_type != + CookieTreeNode::DetailedInfo::TYPE_COOKIE) { + continue; + } + + ++num_cookies; + } + } + } + + if (etld_plus1 != filter_) { + // Restore the original |filter_|. + cookies_tree_model_->UpdateSearchResults(filter_); + } + const base::string16 string = + num_cookies > 0 ? l10n_util::GetPluralStringFUTF16( + IDS_SETTINGS_SITE_SETTINGS_NUM_COOKIES, num_cookies) + : base::string16(); + + ResolveJavascriptCallback(base::Value(callback_id), base::Value(string)); +} + void CookiesViewHandler::HandleGetDisplayList(const base::ListValue* args) { CHECK(request_.callback_id_.empty()); CHECK_EQ(2U, args->GetSize()); @@ -418,32 +471,35 @@ void CookiesViewHandler::SendLocalDataList(const CookieTreeNode* parent) { std::unique_ptr<base::ListValue> site_list(new base::ListValue); for (int i = 0; i < list_item_count; ++i) { const CookieTreeNode* site = parent->GetChild(sorted_sites_[i].second); - std::string description; + base::string16 description; for (int k = 0; k < site->child_count(); ++k) { - const CookieTreeNode* category = site->GetChild(k); - const auto node_type = category->GetDetailedInfo().node_type; - if (node_type == CookieTreeNode::DetailedInfo::TYPE_QUOTA) { - // TODO(crbug.com/642955): Omit quota values until bug is addressed. - continue; - } - int ids_value = GetCategoryLabelID(node_type); - if (!ids_value) { - // If we don't have a label to call it by, don't show it. Please add - // a label ID if an expected category is not appearing in the UI. - continue; - } if (description.size()) { - description += ", "; + description += base::ASCIIToUTF16(", "); } + const CookieTreeNode* category = site->GetChild(k); + const auto node_type = category->GetDetailedInfo().node_type; int item_count = category->child_count(); - if (category->GetDetailedInfo().node_type == - CookieTreeNode::DetailedInfo::TYPE_COOKIES && - item_count > 1) { - description += - l10n_util::GetStringFUTF8(IDS_SETTINGS_COOKIES_PLURAL_COOKIES, - base::FormatNumber(item_count)); - } else { - description += l10n_util::GetStringUTF8(ids_value); + switch (node_type) { + case CookieTreeNode::DetailedInfo::TYPE_QUOTA: + // TODO(crbug.com/642955): Omit quota values until bug is addressed. + continue; + case CookieTreeNode::DetailedInfo::TYPE_COOKIE: + DCHECK_EQ(0, item_count); + item_count = 1; + FALLTHROUGH; + case CookieTreeNode::DetailedInfo::TYPE_COOKIES: + description += l10n_util::GetPluralStringFUTF16( + IDS_SETTINGS_SITE_SETTINGS_NUM_COOKIES, item_count); + break; + default: + int ids_value = GetCategoryLabelID(node_type); + if (!ids_value) { + // If we don't have a label to call it by, don't show it. Please add + // a label ID if an expected category is not appearing in the UI. + continue; + } + description += l10n_util::GetStringUTF16(ids_value); + break; } } std::unique_ptr<base::DictionaryValue> list_info(new base::DictionaryValue); 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 6cc8458645a..0b742577c16 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 @@ -61,6 +61,9 @@ class CookiesViewHandler : public SettingsPageUIHandler, // Retrieve cookie details for a specific site. void HandleGetCookieDetails(const base::ListValue* args); + // Gets the number of cookies formatted in a plural string, given a site. + void HandleGetNumCookiesString(const base::ListValue* args); + // Remove all sites data. void HandleRemoveAll(const base::ListValue* args); diff --git a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc index 5a68d2419c3..721518a1f17 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc @@ -24,7 +24,6 @@ #include "chrome/browser/profiles/profile_shortcut_manager.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/profiles/profiles_state.h" -#include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" @@ -32,7 +31,6 @@ #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/signin/core/browser/profile_management_switches.h" -#include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_ui.h" diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc index 10862aa2adc..fa89523712c 100644 --- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc @@ -5,7 +5,9 @@ #include "chrome/browser/ui/webui/settings/site_settings_handler.h" #include <algorithm> +#include <map> #include <memory> +#include <set> #include <string> #include <utility> @@ -22,6 +24,7 @@ #include "chrome/browser/infobars/infobar_service.h" #include "chrome/browser/permissions/chooser_context_base.h" #include "chrome/browser/permissions/permission_decision_auto_blocker.h" +#include "chrome/browser/permissions/permission_manager.h" #include "chrome/browser/permissions/permission_uma_util.h" #include "chrome/browser/permissions/permission_util.h" #include "chrome/browser/profiles/profile.h" @@ -61,6 +64,8 @@ namespace settings { namespace { +constexpr char kEffectiveTopLevelDomainPlus1Name[] = "etldPlus1"; +constexpr char kOriginList[] = "origins"; constexpr char kZoom[] = "zoom"; // Return an appropriate API Permission ID for the given string name. @@ -112,6 +117,38 @@ void AddExceptionsGrantedByHostedApps(content::BrowserContext* context, } } +// Whether |pattern| applies to a single origin. +bool PatternAppliesToSingleOrigin(const ContentSettingPatternSource& pattern) { + const GURL url(pattern.primary_pattern.ToString()); + // Default settings and other patterns apply to multiple origins. + if (url::Origin::Create(url).unique()) + return false; + // Embedded content settings only when |url| is embedded in another origin, so + // ignore non-wildcard secondary patterns that are different to the primary. + if (pattern.primary_pattern != pattern.secondary_pattern && + pattern.secondary_pattern != ContentSettingsPattern::Wildcard()) { + return false; + } + return true; +} + +// Groups |url| into sets of eTLD+1s in |site_group_map|, assuming |url| is an +// origin. +void CreateOrAppendSiteGroupEntry( + std::map<std::string, std::set<std::string>>* site_group_map, + const GURL& url) { + std::string etld_plus1_string = + net::registry_controlled_domains::GetDomainAndRegistry( + url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); + auto entry = site_group_map->find(etld_plus1_string); + if (entry == site_group_map->end()) { + site_group_map->emplace(etld_plus1_string, + std::set<std::string>({url.spec()})); + } else { + entry->second.insert(url.spec()); + } +} + } // namespace @@ -149,6 +186,10 @@ void SiteSettingsHandler::RegisterMessages() { &SiteSettingsHandler::HandleGetDefaultValueForContentType, base::Unretained(this))); web_ui()->RegisterMessageCallback( + "getAllSites", + base::BindRepeating(&SiteSettingsHandler::HandleGetAllSites, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "getExceptionList", base::BindRepeating(&SiteSettingsHandler::HandleGetExceptionList, base::Unretained(this))); @@ -280,7 +321,7 @@ void SiteSettingsHandler::OnContentSettingChanged( const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, - std::string resource_identifier) { + const std::string& resource_identifier) { if (!site_settings::HasRegisteredGroupName(content_type)) return; @@ -486,6 +527,92 @@ void SiteSettingsHandler::HandleGetDefaultValueForContentType( ResolveJavascriptCallback(*callback_id, category); } +void SiteSettingsHandler::HandleGetAllSites(const base::ListValue* args) { + AllowJavascript(); + + CHECK_EQ(2U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + const base::ListValue* types; + CHECK(args->GetList(1, &types)); + + // Convert |types| to a list of ContentSettingsTypes. + std::vector<ContentSettingsType> content_types; + for (size_t i = 0; i < types->GetSize(); ++i) { + std::string type; + types->GetString(i, &type); + content_types.push_back( + site_settings::ContentSettingsTypeFromGroupName(type)); + } + + // Incognito contains incognito content settings plus non-incognito content + // settings. Thus if it exists, just get exceptions for the incognito profile. + Profile* profile = profile_; + if (profile_->HasOffTheRecordProfile() && + profile_->GetOffTheRecordProfile() != profile_) { + profile = profile_->GetOffTheRecordProfile(); + } + DCHECK(profile); + HostContentSettingsMap* map = + HostContentSettingsMapFactory::GetForProfile(profile); + std::map<std::string, std::set<std::string>> all_sites_map; + + // TODO(https://crbug.com/835712): Assess performance of this method for + // unusually large numbers of stored content settings. + + // Retrieve a list of embargoed settings to check separately. This ensures + // that only settings included in |content_types| will be listed in all sites. + ContentSettingsForOneType embargo_settings; + map->GetSettingsForOneType(CONTENT_SETTINGS_TYPE_PERMISSION_AUTOBLOCKER_DATA, + std::string(), &embargo_settings); + PermissionManager* permission_manager = PermissionManager::Get(profile); + for (const ContentSettingPatternSource& e : embargo_settings) { + for (ContentSettingsType content_type : content_types) { + if (PermissionUtil::IsPermission(content_type)) { + const GURL url(e.primary_pattern.ToString()); + // Add |url| to the set if there are any embargo settings. + PermissionResult result = + permission_manager->GetPermissionStatus(content_type, url, url); + if (result.source == PermissionStatusSource::MULTIPLE_DISMISSALS || + result.source == PermissionStatusSource::MULTIPLE_IGNORES) { + CreateOrAppendSiteGroupEntry(&all_sites_map, url); + break; + } + } + } + } + + // Convert |types| to a list of ContentSettingsTypes. + for (ContentSettingsType content_type : content_types) { + // TODO(https://crbug.com/835712): Add extension content settings, plus + // sites that use any non-zero amount of storage. + + ContentSettingsForOneType entries; + map->GetSettingsForOneType(content_type, std::string(), &entries); + for (const ContentSettingPatternSource& e : entries) { + if (PatternAppliesToSingleOrigin(e)) + CreateOrAppendSiteGroupEntry(&all_sites_map, + GURL(e.primary_pattern.ToString())); + } + } + + // Convert |all_sites_map| to a list of base::DictionaryValues. + base::Value result(base::Value::Type::LIST); + for (const auto& entry : all_sites_map) { + // eTLD+1 is the effective top level domain + 1. + base::Value site_group(base::Value::Type::DICTIONARY); + site_group.SetKey(kEffectiveTopLevelDomainPlus1Name, + base::Value(entry.first)); + base::Value origin_list(base::Value::Type::LIST); + for (const std::string& origin : entry.second) { + origin_list.GetList().emplace_back(origin); + } + site_group.SetKey(kOriginList, std::move(origin_list)); + result.GetList().push_back(std::move(site_group)); + } + ResolveJavascriptCallback(*callback_id, result); +} + void SiteSettingsHandler::HandleGetExceptionList(const base::ListValue* args) { AllowJavascript(); diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h index 9c78d451b85..3f5b4a470ad 100644 --- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h @@ -60,7 +60,7 @@ class SiteSettingsHandler : public SettingsPageUIHandler, void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, - std::string resource_identifier) override; + const std::string& resource_identifier) override; // content::NotificationObserver: void Observe(int type, @@ -84,6 +84,7 @@ class SiteSettingsHandler : public SettingsPageUIHandler, FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetOriginPermissions); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetForInvalidURLs); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Incognito); + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAllSites); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Origins); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Patterns); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ZoomLevels); @@ -108,6 +109,10 @@ class SiteSettingsHandler : public SettingsPageUIHandler, void HandleSetDefaultValueForContentType(const base::ListValue* args); void HandleGetDefaultValueForContentType(const base::ListValue* args); + // Returns a list of sites, grouped by their effective top level domain plus + // 1, affected by any of the content settings specified in |args|. + void HandleGetAllSites(const base::ListValue* args); + // Returns the list of site exceptions for a given content settings type. void HandleGetExceptionList(const base::ListValue* args); 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 6efafe49981..2b1e3700934 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 @@ -7,12 +7,14 @@ #include <memory> #include <string> -#include "base/test/histogram_tester.h" +#include "base/test/metrics/histogram_tester.h" +#include "base/test/simple_test_clock.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/browser/infobars/infobar_service.h" +#include "chrome/browser/permissions/permission_decision_auto_blocker.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/webui/site_settings_helper.h" @@ -64,10 +66,11 @@ class FlashContentSettingsChangeWaiter : public content_settings::Observer { } // content_settings::Observer: - void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern, - const ContentSettingsPattern& secondary_pattern, - ContentSettingsType content_type, - std::string resource_identifier) override { + void OnContentSettingChanged( + const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsType content_type, + const std::string& resource_identifier) override { if (content_type == CONTENT_SETTINGS_TYPE_PLUGINS) Proceed(); } @@ -355,6 +358,169 @@ TEST_F(SiteSettingsHandlerTest, GetAndSetDefault) { site_settings::SiteSettingSource::kDefault, 3U); } +TEST_F(SiteSettingsHandlerTest, GetAllSites) { + base::ListValue get_all_sites_args; + get_all_sites_args.AppendString(kCallbackId); + base::Value category_list(base::Value::Type::LIST); + category_list.GetList().emplace_back(kNotifications); + category_list.GetList().emplace_back(kFlash); + get_all_sites_args.GetList().push_back(std::move(category_list)); + + // Test all sites is empty when there are no preferences. + handler()->HandleGetAllSites(&get_all_sites_args); + EXPECT_EQ(1U, web_ui()->call_data().size()); + + { + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + EXPECT_EQ("cr.webUIResponse", data.function_name()); + EXPECT_EQ(kCallbackId, data.arg1()->GetString()); + ASSERT_TRUE(data.arg2()->GetBool()); + + const base::Value::ListStorage& site_groups = data.arg3()->GetList(); + EXPECT_EQ(0UL, site_groups.size()); + } + + // Add a couple of exceptions and check they appear in all sites. + HostContentSettingsMap* map = + HostContentSettingsMapFactory::GetForProfile(profile()); + const GURL url1("http://example.com"); + const GURL url2("https://other.example.com"); + map->SetContentSettingDefaultScope(url1, url1, + CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + std::string(), CONTENT_SETTING_BLOCK); + map->SetContentSettingDefaultScope(url2, url2, CONTENT_SETTINGS_TYPE_PLUGINS, + std::string(), CONTENT_SETTING_ALLOW); + handler()->HandleGetAllSites(&get_all_sites_args); + + { + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + EXPECT_EQ("cr.webUIResponse", data.function_name()); + EXPECT_EQ(kCallbackId, data.arg1()->GetString()); + ASSERT_TRUE(data.arg2()->GetBool()); + + const base::Value::ListStorage& site_groups = data.arg3()->GetList(); + EXPECT_EQ(1UL, site_groups.size()); + for (const base::Value& site_group : site_groups) { + const std::string& etld_plus1_string = + site_group.FindKey("etldPlus1")->GetString(); + const base::Value::ListStorage& origin_list = + site_group.FindKey("origins")->GetList(); + EXPECT_EQ("example.com", etld_plus1_string); + EXPECT_EQ(2UL, origin_list.size()); + EXPECT_EQ(url1.spec(), origin_list[0].GetString()); + EXPECT_EQ(url2.spec(), origin_list[1].GetString()); + } + } + + // Add an additional exception belonging to a different eTLD+1. + const GURL url3("https://example2.net"); + map->SetContentSettingDefaultScope(url3, url3, CONTENT_SETTINGS_TYPE_PLUGINS, + std::string(), CONTENT_SETTING_BLOCK); + handler()->HandleGetAllSites(&get_all_sites_args); + + { + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + EXPECT_EQ("cr.webUIResponse", data.function_name()); + + EXPECT_EQ(kCallbackId, data.arg1()->GetString()); + ASSERT_TRUE(data.arg2()->GetBool()); + + const base::Value::ListStorage& site_groups = data.arg3()->GetList(); + EXPECT_EQ(2UL, site_groups.size()); + for (const base::Value& site_group : site_groups) { + const std::string& etld_plus1_string = + site_group.FindKey("etldPlus1")->GetString(); + const base::Value::ListStorage& origin_list = + site_group.FindKey("origins")->GetList(); + if (etld_plus1_string == "example2.net") { + EXPECT_EQ(1UL, origin_list.size()); + EXPECT_EQ(url3.spec(), origin_list[0].GetString()); + } else { + EXPECT_EQ("example.com", etld_plus1_string); + } + } + } + + // Test embargoed settings also appear. + PermissionDecisionAutoBlocker* auto_blocker = + PermissionDecisionAutoBlocker::GetForProfile(profile()); + const GURL url4("https://example2.co.uk"); + for (int i = 0; i < 3; ++i) { + auto_blocker->RecordDismissAndEmbargo(url4, + CONTENT_SETTINGS_TYPE_NOTIFICATIONS); + } + EXPECT_EQ( + CONTENT_SETTING_BLOCK, + auto_blocker->GetEmbargoResult(url4, CONTENT_SETTINGS_TYPE_NOTIFICATIONS) + .content_setting); + handler()->HandleGetAllSites(&get_all_sites_args); + + { + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + EXPECT_EQ("cr.webUIResponse", data.function_name()); + EXPECT_EQ(kCallbackId, data.arg1()->GetString()); + ASSERT_TRUE(data.arg2()->GetBool()); + + const base::Value::ListStorage& site_groups = data.arg3()->GetList(); + EXPECT_EQ(3UL, site_groups.size()); + } + + // Add an expired embargo setting to a) an existing eTLD+1 group and b) a new + // eTLD+1 group. + base::SimpleTestClock clock; + clock.SetNow(base::Time::Now()); + auto_blocker->SetClockForTesting(&clock); + for (int i = 0; i < 3; ++i) { + auto_blocker->RecordDismissAndEmbargo(url3, + CONTENT_SETTINGS_TYPE_NOTIFICATIONS); + } + EXPECT_EQ( + CONTENT_SETTING_BLOCK, + auto_blocker->GetEmbargoResult(url3, CONTENT_SETTINGS_TYPE_NOTIFICATIONS) + .content_setting); + clock.Advance(base::TimeDelta::FromDays(8)); + EXPECT_EQ( + CONTENT_SETTING_ASK, + auto_blocker->GetEmbargoResult(url3, CONTENT_SETTINGS_TYPE_NOTIFICATIONS) + .content_setting); + + { + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + EXPECT_EQ("cr.webUIResponse", data.function_name()); + EXPECT_EQ(kCallbackId, data.arg1()->GetString()); + ASSERT_TRUE(data.arg2()->GetBool()); + + const base::Value::ListStorage& site_groups = data.arg3()->GetList(); + EXPECT_EQ(3UL, site_groups.size()); + } + + clock.SetNow(base::Time::Now()); + const GURL url5("http://test.example5.com"); + for (int i = 0; i < 3; ++i) { + auto_blocker->RecordDismissAndEmbargo(url5, + CONTENT_SETTINGS_TYPE_NOTIFICATIONS); + } + EXPECT_EQ( + CONTENT_SETTING_BLOCK, + auto_blocker->GetEmbargoResult(url5, CONTENT_SETTINGS_TYPE_NOTIFICATIONS) + .content_setting); + clock.Advance(base::TimeDelta::FromDays(8)); + EXPECT_EQ( + CONTENT_SETTING_ASK, + auto_blocker->GetEmbargoResult(url5, CONTENT_SETTINGS_TYPE_NOTIFICATIONS) + .content_setting); + + { + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + EXPECT_EQ("cr.webUIResponse", data.function_name()); + EXPECT_EQ(kCallbackId, data.arg1()->GetString()); + ASSERT_TRUE(data.arg2()->GetBool()); + + const base::Value::ListStorage& site_groups = data.arg3()->GetList(); + EXPECT_EQ(3UL, site_groups.size()); + } +} + TEST_F(SiteSettingsHandlerTest, Origins) { const std::string google("https://www.google.com:443"); const std::string uma_base("WebsiteSettings.Menu.PermissionChanged"); diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc index 44cfc2fa7f9..0984278d7eb 100644 --- a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc @@ -14,6 +14,7 @@ #include "chrome/browser/speech/tts_controller.h" #include "chrome/browser/speech/tts_controller_impl.h" #include "chrome/common/extensions/extension_constants.h" +#include "chrome/grit/generated_resources.h" #include "content/public/browser/web_ui.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_registry.h" @@ -29,6 +30,9 @@ void TtsHandler::HandleGetAllTtsVoiceData(const base::ListValue* args) { } void TtsHandler::HandleGetTtsExtensions(const base::ListValue* args) { + // Ensure the built in tts engine is loaded to be able to respond to messages. + TtsExtensionEngine::GetInstance()->LoadBuiltInTtsExtension( + Profile::FromWebUI(web_ui())); base::ListValue responses; Profile* profile = Profile::FromWebUI(web_ui()); extensions::ExtensionRegistry* registry = @@ -48,19 +52,18 @@ void TtsHandler::HandleGetTtsExtensions(const base::ListValue* args) { continue; } base::DictionaryValue response; - response.SetPath({"name"}, base::Value(extension->name())); - response.SetPath({"extensionId"}, base::Value(extension_id)); + response.SetString("name", extension->name()); + response.SetString("extensionId", extension_id); if (extensions::OptionsPageInfo::HasOptionsPage(extension)) { - response.SetPath( - {"optionsPage"}, - base::Value( - extensions::OptionsPageInfo::GetOptionsPage(extension).spec())); + response.SetString( + "optionsPage", + + extensions::OptionsPageInfo::GetOptionsPage(extension).spec()); } responses.GetList().push_back(std::move(response)); } - CallJavascriptFunction("cr.webUIListenerCallback", - base::Value("tts-extensions-updated"), responses); + FireWebUIListener("tts-extensions-updated", responses); } void TtsHandler::OnVoicesChanged() { @@ -72,21 +75,28 @@ void TtsHandler::OnVoicesChanged() { for (const auto& voice : voices) { base::DictionaryValue response; int language_score = GetVoiceLangMatchScore(&voice, app_locale); - std::string language_code = l10n_util::GetLanguage(voice.lang); - response.SetPath({"name"}, base::Value(voice.name)); - response.SetPath({"languageCode"}, base::Value(language_code)); - response.SetPath({"fullLanguageCode"}, base::Value(voice.lang)); - response.SetPath({"languageScore"}, base::Value(language_score)); - response.SetPath({"extensionId"}, base::Value(voice.extension_id)); - response.SetPath( - {"displayLanguage"}, - base::Value(l10n_util::GetDisplayNameForLocale( - language_code, g_browser_process->GetApplicationLocale(), true))); + std::string language_code; + if (voice.lang.empty()) { + language_code = "noLanguageCode"; + response.SetString( + "displayLanguage", + l10n_util::GetStringUTF8(IDS_TEXT_TO_SPEECH_SETTINGS_NO_LANGUAGE)); + } else { + language_code = l10n_util::GetLanguage(voice.lang); + response.SetString( + "displayLanguage", + l10n_util::GetDisplayNameForLocale( + language_code, g_browser_process->GetApplicationLocale(), true)); + } + response.SetString("name", voice.name); + response.SetString("languageCode", language_code); + response.SetString("fullLanguageCode", voice.lang); + response.SetInteger("languageScore", language_score); + response.SetString("extensionId", voice.extension_id); responses.GetList().push_back(std::move(response)); } AllowJavascript(); - CallJavascriptFunction("cr.webUIListenerCallback", - base::Value("all-voice-data-updated"), responses); + FireWebUIListener("all-voice-data-updated", responses); // Also refresh the TTS extensions in case they have changed. HandleGetTtsExtensions(nullptr); 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 3773b85e3c8..fcf3c8d6c03 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 @@ -22,9 +22,11 @@ #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/signin/signin_util.h" +#include "chrome/browser/signin/unified_consent_helper.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_delegate_impl.h" #include "chrome/browser/ui/webui/signin/signin_utils_desktop.h" +#include "chrome/browser/unified_consent/unified_consent_service_factory.h" #include "components/browser_sync/profile_sync_service.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/prefs/pref_service.h" @@ -35,6 +37,8 @@ #include "components/signin/core/browser/signin_metrics.h" #include "components/signin/core/browser/signin_pref_names.h" #include "components/sync/base/sync_prefs.h" +#include "components/unified_consent/unified_consent_service.h" +#include "content/public/browser/storage_partition.h" #include "net/url_request/url_request_context_getter.h" namespace { @@ -65,7 +69,6 @@ DiceTurnSyncOnHelper::DiceTurnSyncOnHelper( account_info_(GetAccountInfo(profile, account_id)), weak_pointer_factory_(this) { DCHECK(delegate_); - DCHECK(signin::IsDicePrepareMigrationEnabled()); DCHECK(profile_); // Should not start syncing if the profile is already authenticated DCHECK(!signin_manager_->IsAuthenticated()); @@ -251,8 +254,10 @@ void DiceTurnSyncOnHelper::LoadPolicyWithCachedCredentials() { policy::UserPolicySigninService* policy_service = policy::UserPolicySigninServiceFactory::GetForProfile(profile_); policy_service->FetchPolicyForSignedInUser( - account_info_.GetAccountId(), dm_token_, client_id_, + AccountIdFromAccountInfo(account_info_), dm_token_, client_id_, profile_->GetRequestContext(), + content::BrowserContext::GetDefaultStoragePartition(profile_) + ->GetURLLoaderFactoryForBrowserProcess(), base::Bind(&DiceTurnSyncOnHelper::OnPolicyFetchComplete, weak_pointer_factory_.GetWeakPtr())); } @@ -374,12 +379,15 @@ void DiceTurnSyncOnHelper::FinishSyncSetupAndDelete( LoginUIService::SyncConfirmationUIClosedResult result) { switch (result) { case LoginUIService::CONFIGURE_SYNC_FIRST: + EnableUnifiedConsentIfNeeded(); delegate_->ShowSyncSettings(); break; case LoginUIService::SYNC_WITH_DEFAULT_SETTINGS: { browser_sync::ProfileSyncService* sync_service = GetProfileSyncService(); - if (sync_service) + if (sync_service) { sync_service->SetFirstSetupComplete(); + EnableUnifiedConsentIfNeeded(); + } break; } case LoginUIService::ABORT_SIGNIN: @@ -400,3 +408,10 @@ void DiceTurnSyncOnHelper::AbortAndDelete() { } delete this; } + +void DiceTurnSyncOnHelper::EnableUnifiedConsentIfNeeded() { + if (IsUnifiedConsentEnabled(profile_)) { + UnifiedConsentServiceFactory::GetForProfile(profile_) + ->SetUnifiedConsentGiven(true); + } +} diff --git a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h index 28af6e6555a..5f706f75bdc 100644 --- a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h +++ b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h @@ -186,6 +186,10 @@ class DiceTurnSyncOnHelper : public SyncStartupTracker::Observer { // Aborts the flow and deletes this object. void AbortAndDelete(); + // This function enables all unified consent services when the unified consent + // feature is enabled. + void EnableUnifiedConsentIfNeeded(); + std::unique_ptr<Delegate> delegate_; Profile* profile_; SigninManager* signin_manager_; 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 b65a4205471..cfd7e7c2862 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 @@ -21,10 +21,14 @@ #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h" #include "chrome/browser/signin/fake_signin_manager_builder.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" +#include "chrome/browser/signin/scoped_account_consistency.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/signin/test_signin_client_builder.h" +#include "chrome/browser/signin/unified_consent_helper.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_test_util.h" +#include "chrome/browser/unified_consent/unified_consent_service_factory.h" +#include "chrome/browser/unified_consent/unified_consent_test_util.h" #include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" @@ -33,16 +37,21 @@ #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/scoped_account_consistency.h" #include "components/signin/core/browser/signin_metrics.h" #include "components/signin/core/browser/signin_pref_names.h" +#include "components/unified_consent/scoped_unified_consent.h" +#include "components/unified_consent/unified_consent_service.h" #include "content/public/test/test_browser_thread_bundle.h" +#include "google_apis/gaia/google_service_auth_error.h" +#include "net/url_request/url_request_context_getter.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::AtLeast; using ::testing::Return; +using ::testing::ReturnRef; -class DiceTurnSyncOnHelperTest; +class DiceTurnSyncOnHelperTestBase; namespace { @@ -64,7 +73,7 @@ const signin_metrics::Reason kSigninReason = class TestDiceTurnSyncOnHelperDelegate : public DiceTurnSyncOnHelper::Delegate { public: explicit TestDiceTurnSyncOnHelperDelegate( - DiceTurnSyncOnHelperTest* test_fixture); + DiceTurnSyncOnHelperTestBase* test_fixture); ~TestDiceTurnSyncOnHelperDelegate() override; private: @@ -85,7 +94,7 @@ class TestDiceTurnSyncOnHelperDelegate : public DiceTurnSyncOnHelper::Delegate { void ShowSigninPageInNewProfile(Profile* new_profile, const std::string& username) override; - DiceTurnSyncOnHelperTest* test_fixture_; + DiceTurnSyncOnHelperTestBase* test_fixture_; }; // Simple ProfileManager creating testing profiles. @@ -130,6 +139,7 @@ class FakeUserPolicySigninService : public policy::UserPolicySigninService { nullptr, signin_manager, nullptr, + nullptr, oauth2_token_service) {} void set_dm_token(const std::string& dm_token) { dm_token_ = dm_token; } @@ -155,6 +165,7 @@ class FakeUserPolicySigninService : public policy::UserPolicySigninService { const std::string& dm_token, const std::string& client_id, scoped_refptr<net::URLRequestContextGetter> profile_request_context, + scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory, const PolicyFetchCallback& callback) override { callback.Run(true); } @@ -168,10 +179,12 @@ class FakeUserPolicySigninService : public policy::UserPolicySigninService { } // namespace -class DiceTurnSyncOnHelperTest : public testing::Test { +class DiceTurnSyncOnHelperTestBase : public testing::Test { public: - DiceTurnSyncOnHelperTest() - : local_state_(TestingBrowserProcess::GetGlobal()) { + DiceTurnSyncOnHelperTestBase() + : local_state_(TestingBrowserProcess::GetGlobal()) {} + + void SetUp() override { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); TestingBrowserProcess::GetGlobal()->SetProfileManager( new UnittestProfileManager(temp_dir_.GetPath())); @@ -189,6 +202,9 @@ class DiceTurnSyncOnHelperTest : public testing::Test { profile_builder.AddTestingFactory( policy::UserPolicySigninServiceFactory::GetInstance(), &FakeUserPolicySigninService::Build); + profile_builder.AddTestingFactory( + UnifiedConsentServiceFactory::GetInstance(), + &BuildUnifiedConsentServiceForTesting); profile_ = profile_builder.Build(); account_tracker_service_ = AccountTrackerServiceFactory::GetForProfile(profile()); @@ -202,7 +218,7 @@ class DiceTurnSyncOnHelperTest : public testing::Test { EXPECT_TRUE(token_service_->RefreshTokenIsAvailable(account_id_)); } - ~DiceTurnSyncOnHelperTest() override { + ~DiceTurnSyncOnHelperTestBase() override { DCHECK(delegate_destroyed_); // Destroy extra profiles. TestingBrowserProcess::GetGlobal()->SetProfileManager(nullptr); @@ -244,27 +260,22 @@ class DiceTurnSyncOnHelperTest : public testing::Test { browser_sync::ProfileSyncServiceMock* sync_service_mock = GetProfileSyncServiceMock(); EXPECT_CALL(*sync_service_mock, GetSetupInProgressHandle()).Times(1); - EXPECT_CALL(*sync_service_mock, CanSyncStart()) - .Times(AtLeast(0)) - .WillRepeatedly(Return(true)); - EXPECT_CALL(*sync_service_mock, IsEngineInitialized()) - .Times(AtLeast(0)) - .WillRepeatedly(Return(true)); + ON_CALL(*sync_service_mock, GetDisableReasons()) + .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); + ON_CALL(*sync_service_mock, IsEngineInitialized()) + .WillByDefault(Return(true)); } void SetExpectationsForSyncStartupPending() { browser_sync::ProfileSyncServiceMock* sync_service_mock = GetProfileSyncServiceMock(); EXPECT_CALL(*sync_service_mock, GetSetupInProgressHandle()).Times(1); - EXPECT_CALL(*sync_service_mock, CanSyncStart()) - .Times(AtLeast(0)) - .WillRepeatedly(Return(true)); - EXPECT_CALL(*sync_service_mock, IsEngineInitialized()) - .Times(AtLeast(0)) - .WillRepeatedly(Return(false)); - EXPECT_CALL(*sync_service_mock, waiting_for_auth()) - .Times(AtLeast(0)) - .WillRepeatedly(Return(true)); + ON_CALL(*sync_service_mock, GetDisableReasons()) + .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); + ON_CALL(*sync_service_mock, IsEngineInitialized()) + .WillByDefault(Return(false)); + ON_CALL(*sync_service_mock, GetAuthError()) + .WillByDefault(ReturnRef(kNoAuthError)); } void CheckDelegateCalls() { @@ -366,7 +377,6 @@ class DiceTurnSyncOnHelperTest : public testing::Test { bool expected_sync_settings_shown_ = false; private: - signin::ScopedAccountConsistencyDicePrepareMigration scoped_dice; content::TestBrowserThreadBundle thread_bundle_; base::ScopedTempDir temp_dir_; ScopedTestingLocalState local_state_; @@ -387,12 +397,39 @@ class DiceTurnSyncOnHelperTest : public testing::Test { std::string new_profile_username_; bool sync_confirmation_shown_ = false; bool sync_settings_shown_ = false; + + // Note: This needs to be a member variable for testing::ReturnRef. + const GoogleServiceAuthError kNoAuthError = + GoogleServiceAuthError::AuthErrorNone(); +}; + +// Test class with only DicePrepareMigration enabled. +class DiceTurnSyncOnHelperTest : public DiceTurnSyncOnHelperTestBase { + public: + DiceTurnSyncOnHelperTest() = default; + + private: + ScopedAccountConsistencyDicePrepareMigration scoped_dice_; +}; + +// Test class with Dice and UnifiedConsent enabled. +class DiceTurnSyncOnHelperTestWithUnifiedConsent + : public DiceTurnSyncOnHelperTestBase { + public: + DiceTurnSyncOnHelperTestWithUnifiedConsent() + : scoped_unified_consent_( + unified_consent::UnifiedConsentFeatureState::kEnabledNoBump) {} + ~DiceTurnSyncOnHelperTestWithUnifiedConsent() override {} + + private: + ScopedAccountConsistencyDice scoped_dice_; + unified_consent::ScopedUnifiedConsent scoped_unified_consent_; }; // TestDiceTurnSyncOnHelperDelegate implementation. TestDiceTurnSyncOnHelperDelegate::TestDiceTurnSyncOnHelperDelegate( - DiceTurnSyncOnHelperTest* test_fixture) + DiceTurnSyncOnHelperTestBase* test_fixture) : test_fixture_(test_fixture) {} TestDiceTurnSyncOnHelperDelegate::~TestDiceTurnSyncOnHelperDelegate() { @@ -664,6 +701,30 @@ TEST_F(DiceTurnSyncOnHelperTest, ShowSyncDialogForEndConsumerAccount) { CheckDelegateCalls(); } +// Tests that the user enabled unified consent, +TEST_F(DiceTurnSyncOnHelperTestWithUnifiedConsent, + ShowSyncDialogForEndConsumerAccount_UnifiedConsentEnabled) { + ASSERT_TRUE(IsUnifiedConsentEnabled(profile())); + // Set expectations. + expected_sync_confirmation_shown_ = true; + sync_confirmation_result_ = LoginUIService::SyncConfirmationUIClosedResult:: + SYNC_WITH_DEFAULT_SETTINGS; + SetExpectationsForSyncStartupCompleted(); + EXPECT_CALL(*GetProfileSyncServiceMock(), SetFirstSetupComplete()).Times(1); + + // Signin flow. + EXPECT_FALSE(signin_manager()->IsAuthenticated()); + CreateDiceTurnOnSyncHelper( + DiceTurnSyncOnHelper::SigninAbortedMode::REMOVE_ACCOUNT); + + // Check expectations. + EXPECT_TRUE(token_service()->RefreshTokenIsAvailable(account_id())); + EXPECT_EQ(account_id(), signin_manager()->GetAuthenticatedAccountId()); + CheckDelegateCalls(); + EXPECT_TRUE(UnifiedConsentServiceFactory::GetForProfile(profile()) + ->IsUnifiedConsentGiven()); +} + // For enterprise user, tests that the user is signed in only after Sync engine // starts. // Regression test for http://crbug.com/812546 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 6edb4d36f30..0738564db13 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/signin/inline_login_handler.h" #include <limits.h> +#include <string> #include "base/bind.h" #include "base/metrics/user_metrics.h" @@ -32,6 +33,9 @@ #include "google_apis/gaia/gaia_urls.h" #include "net/base/url_util.h" +const char kSignInPromoQueryKeyShowAccountManagement[] = + "showAccountManagement"; + InlineLoginHandler::InlineLoginHandler() : weak_ptr_factory_(this) {} InlineLoginHandler::~InlineLoginHandler() {} @@ -173,7 +177,7 @@ void InlineLoginHandler::HandleSwitchToFullTabMessage( main_frame_url = net::AppendOrReplaceQueryParameter( main_frame_url, signin::kSignInPromoQueryKeyAutoClose, "1"); main_frame_url = net::AppendOrReplaceQueryParameter( - main_frame_url, signin::kSignInPromoQueryKeyShowAccountManagement, "1"); + main_frame_url, kSignInPromoQueryKeyShowAccountManagement, "1"); main_frame_url = net::AppendOrReplaceQueryParameter( main_frame_url, signin::kSignInPromoQueryKeyForceKeepData, "1"); if (base::FeatureList::IsEnabled( @@ -206,8 +210,10 @@ void InlineLoginHandler::HandleDialogClose(const base::ListValue* args) { if (browser) browser->signin_view_controller()->CloseModalSignin(); +#if !defined(OS_CHROMEOS) // Does nothing if user manager is not showing. UserManagerProfileDialog::HideDialog(); +#endif // !defined(OS_CHROMEOS) } void InlineLoginHandler::CloseDialogFromJavascript() { 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 6df77ac1c3c..58abbe7bafc 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h @@ -17,6 +17,8 @@ namespace signin_metrics { enum class AccessPoint; } +extern const char kSignInPromoQueryKeyShowAccountManagement[]; + // The base class handler for the inline login WebUI. class InlineLoginHandler : public content::WebUIMessageHandler { public: @@ -28,7 +30,7 @@ class InlineLoginHandler : public content::WebUIMessageHandler { protected: // Enum for gaia auth mode, must match AuthMode defined in - // chrome/browser/resources/gaia_auth_host/gaia_auth_host.js. + // chrome/browser/resources/gaia_auth_host/authenticator.js. enum AuthMode { kDefaultAuthMode = 0, kOfflineAuthMode = 1, 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 new file mode 100644 index 00000000000..35d3c1e7e66 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc @@ -0,0 +1,149 @@ +// 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/signin/inline_login_handler_chromeos.h" + +#include <string> + +#include "base/logging.h" +#include "base/macros.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "base/values.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/signin/account_tracker_service_factory.h" +#include "chrome/browser/ui/webui/signin/inline_login_handler.h" +#include "chromeos/account_manager/account_manager.h" +#include "chromeos/account_manager/account_manager_factory.h" +#include "components/signin/core/browser/account_tracker_service.h" +#include "google_apis/gaia/gaia_constants.h" +#include "google_apis/gaia/gaia_urls.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" + +namespace chromeos { +namespace { + +// A helper class for completing the inline login flow. Primarily, it is +// responsible for exchanging the auth code, obtained after a successful user +// sign in, for OAuth tokens and subsequently populating Chrome OS +// AccountManager with these tokens. +// This object is supposed to be used in a one-shot fashion and it deletes +// itself after its work is complete. +class SigninHelper : public GaiaAuthConsumer { + public: + SigninHelper( + Profile* profile, + chromeos::AccountManager* account_manager, + const base::RepeatingClosure& close_dialog_closure, + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, + const std::string& gaia_id, + const std::string& email, + const std::string& auth_code) + : profile_(profile), + account_manager_(account_manager), + close_dialog_closure_(close_dialog_closure), + email_(email), + gaia_auth_fetcher_(this, + GaiaConstants::kChromeSource, + url_loader_factory) { + account_key_ = chromeos::AccountManager::AccountKey{ + gaia_id, chromeos::account_manager::AccountType::ACCOUNT_TYPE_GAIA}; + + gaia_auth_fetcher_.StartAuthCodeForOAuth2TokenExchange(auth_code); + } + + ~SigninHelper() override = default; + + // GaiaAuthConsumer overrides. + void OnClientOAuthSuccess(const ClientOAuthResult& result) override { + // TODO(sinhak): Do not depend on Profile unnecessarily. A Profile should + // call |AccountTrackerServiceFactory| for the list of accounts it wants to + // pull from |AccountManager|, not the other way round. Remove this when we + // release multi Profile on Chrome OS and have the infra in place to do + // this. + // Account info needs to be seeded before the OAuth2TokenService chain can + // use it. Do this before anything else. + AccountTrackerServiceFactory::GetForProfile(profile_)->SeedAccountInfo( + account_key_.id, email_); + + account_manager_->UpsertToken(account_key_, result.refresh_token); + + close_dialog_closure_.Run(); + base::SequencedTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); + } + + void OnClientOAuthFailure(const GoogleServiceAuthError& error) override { + // TODO(sinhak): Display an error. + close_dialog_closure_.Run(); + base::SequencedTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); + } + + private: + // A non-owning pointer to Profile. + Profile* const profile_; + // A non-owning pointer to Chrome OS AccountManager. + chromeos::AccountManager* const account_manager_; + // A closure to close the hosting dialog window. + base::RepeatingClosure close_dialog_closure_; + // The user's AccountKey for which |this| object has been created. + chromeos::AccountManager::AccountKey account_key_; + // The user's email for which |this| object has been created. + const std::string email_; + // Used for exchanging auth code for OAuth tokens. + GaiaAuthFetcher gaia_auth_fetcher_; + + DISALLOW_COPY_AND_ASSIGN(SigninHelper); +}; + +} // namespace + +InlineLoginHandlerChromeOS::InlineLoginHandlerChromeOS( + const base::RepeatingClosure& close_dialog_closure) + : close_dialog_closure_(close_dialog_closure) {} + +InlineLoginHandlerChromeOS::~InlineLoginHandlerChromeOS() = default; + +void InlineLoginHandlerChromeOS::SetExtraInitParams( + base::DictionaryValue& params) { + const GaiaUrls* const gaia_urls = GaiaUrls::GetInstance(); + params.SetKey("service", base::Value("chromiumsync")); + params.SetKey("isNewGaiaFlow", base::Value(true)); + params.SetKey("clientId", base::Value(gaia_urls->oauth2_chrome_client_id())); + + const GURL& url = gaia_urls->embedded_setup_chromeos_url(2U); + params.SetKey("gaiaPath", base::Value(url.path().substr(1))); + + params.SetKey("constrained", base::Value("1")); + params.SetKey("flow", base::Value("addaccount")); +} + +void InlineLoginHandlerChromeOS::CompleteLogin(const base::ListValue* args) { + const base::DictionaryValue* auth_data = nullptr; + CHECK(args->GetDictionary(0, &auth_data)); + + const std::string& auth_code = auth_data->FindKey("authCode")->GetString(); + CHECK(!auth_code.empty()); + const std::string& gaia_id = auth_data->FindKey("gaiaId")->GetString(); + CHECK(!gaia_id.empty()); + const std::string& email = auth_data->FindKey("email")->GetString(); + CHECK(!email.empty()); + + // TODO(sinhak): Do not depend on Profile unnecessarily. + Profile* profile = Profile::FromWebUI(web_ui()); + + // TODO(sinhak): Do not depend on Profile unnecessarily. When multiprofile on + // Chrome OS is released, get rid of |AccountManagerFactory| and get + // AccountManager directly from |g_browser_process|. + chromeos::AccountManager* account_manager = + g_browser_process->platform_part() + ->GetAccountManagerFactory() + ->GetAccountManager(profile->GetPath().value()); + + // SigninHelper deletes itself after its work is done. + new SigninHelper(profile, account_manager, close_dialog_closure_, + account_manager->GetUrlLoaderFactory(), gaia_id, email, + auth_code); +} + +} // namespace chromeos 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 new file mode 100644 index 00000000000..5844d592c34 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h @@ -0,0 +1,33 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_CHROMEOS_H_ +#define CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_CHROMEOS_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/signin/inline_login_handler.h" +#include "chromeos/account_manager/account_manager.h" +#include "google_apis/gaia/gaia_auth_consumer.h" +#include "google_apis/gaia/gaia_auth_fetcher.h" + +namespace chromeos { + +class InlineLoginHandlerChromeOS : public InlineLoginHandler { + public: + explicit InlineLoginHandlerChromeOS( + const base::RepeatingClosure& close_dialog_closure); + ~InlineLoginHandlerChromeOS() override; + + // InlineLoginHandler overrides. + void SetExtraInitParams(base::DictionaryValue& params) override; + void CompleteLogin(const base::ListValue* args) override; + + private: + base::RepeatingClosure close_dialog_closure_; + DISALLOW_COPY_AND_ASSIGN(InlineLoginHandlerChromeOS); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_CHROMEOS_H_ diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.cc new file mode 100644 index 00000000000..035f5a54a7f --- /dev/null +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.cc @@ -0,0 +1,43 @@ +// 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/signin/inline_login_handler_dialog_chromeos.h" + +#include <string> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" +#include "chrome/common/webui_url_constants.h" + +namespace chromeos { + +// static +void InlineLoginHandlerDialogChromeOS::Show() { + // Will be deleted by |SystemWebDialogDelegate::OnDialogClosed|. + InlineLoginHandlerDialogChromeOS* dialog = + new InlineLoginHandlerDialogChromeOS(); + dialog->ShowSystemDialog(false /* is_minimal_style */); +} + +InlineLoginHandlerDialogChromeOS::InlineLoginHandlerDialogChromeOS() + : SystemWebDialogDelegate(GURL(chrome::kChromeUIChromeSigninURL), + base::string16() /* title */) {} + +InlineLoginHandlerDialogChromeOS::~InlineLoginHandlerDialogChromeOS() = default; + +std::string InlineLoginHandlerDialogChromeOS::GetDialogArgs() const { + return std::string(); +} + +bool InlineLoginHandlerDialogChromeOS::ShouldShowDialogTitle() const { + return false; +} + +void InlineLoginHandlerDialogChromeOS::GetDialogSize(gfx::Size* size) const { + constexpr int kSigninDialogWidth = 800; + constexpr int kSigninDialogHeight = 700; + size->SetSize(kSigninDialogWidth, kSigninDialogHeight); +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h new file mode 100644 index 00000000000..a03b1647d75 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h @@ -0,0 +1,34 @@ +// 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_SIGNIN_INLINE_LOGIN_HANDLER_DIALOG_CHROMEOS_H_ +#define CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_DIALOG_CHROMEOS_H_ + +#include <string> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" + +namespace chromeos { + +class InlineLoginHandlerDialogChromeOS : public SystemWebDialogDelegate { + public: + static void Show(); + + protected: + InlineLoginHandlerDialogChromeOS(); + ~InlineLoginHandlerDialogChromeOS() override; + + // ui::WebDialogDelegate overrides + void GetDialogSize(gfx::Size* size) const override; + std::string GetDialogArgs() const override; + bool ShouldShowDialogTitle() const override; + + private: + DISALLOW_COPY_AND_ASSIGN(InlineLoginHandlerDialogChromeOS); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_DIALOG_CHROMEOS_H_ 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 3cb823c1204..b9b1305bba4 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 @@ -29,6 +29,7 @@ #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/signin/about_signin_internals_factory.h" +#include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/signin/account_tracker_service_factory.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/local_auth.h" @@ -138,11 +139,27 @@ void UnlockProfileAndHideLoginUI(const base::FilePath profile_path, UserManager::Hide(); } +// Returns true if the showAccountManagement parameter in the given url is set +// to true. +bool ShouldShowAccountManagement(const GURL& url, bool is_mirror_enabled) { + if (!is_mirror_enabled) + return false; + + std::string value; + if (net::GetValueForKeyInQuery(url, kSignInPromoQueryKeyShowAccountManagement, + &value)) { + int enabled = 0; + if (base::StringToInt(value, &enabled) && enabled == 1) + return true; + } + return false; +} + } // namespace InlineSigninHelper::InlineSigninHelper( base::WeakPtr<InlineLoginHandlerImpl> handler, - net::URLRequestContextGetter* getter, + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, Profile* profile, Profile::CreateStatus create_status, const GURL& current_url, @@ -155,7 +172,9 @@ InlineSigninHelper::InlineSigninHelper( bool choose_what_to_sync, bool confirm_untrusted_signin, bool is_force_sign_in_with_usermanager) - : gaia_auth_fetcher_(this, GaiaConstants::kChromeSource, getter), + : gaia_auth_fetcher_(this, + GaiaConstants::kChromeSource, + url_loader_factory), handler_(handler), profile_(profile), create_status_(create_status), @@ -237,7 +256,7 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( PasswordStoreFactory::GetForProfile(profile_, ServiceAccessType::EXPLICIT_ACCESS); if (password_store && !primary_email.empty()) { - password_store->SaveSyncPasswordHash( + password_store->SaveGaiaPasswordHash( primary_email, base::UTF8ToUTF16(password_), password_manager::metrics_util::SyncPasswordHashChange:: SAVED_ON_CHROME_SIGNIN); @@ -254,10 +273,12 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( if (signin::IsAutoCloseEnabledInURL(current_url_)) { // Close the gaia sign in tab via a task to make sure we aren't in the // middle of any webui handler code. + bool show_account_management = ShouldShowAccountManagement( + current_url_, + AccountConsistencyModeManager::IsMirrorEnabledForProfile(profile_)); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&InlineLoginHandlerImpl::CloseTab, handler_, - signin::ShouldShowAccountManagement(current_url_))); + FROM_HERE, base::BindOnce(&InlineLoginHandlerImpl::CloseTab, handler_, + show_account_management)); } if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION || @@ -705,8 +726,9 @@ void InlineLoginHandlerImpl::FinishCompleteLogin( // InlineSigninHelper will delete itself. new InlineSigninHelper( - handler_weak_ptr, params.partition->GetURLRequestContext(), profile, - status, params.url, params.email, params.gaia_id, params.password, + handler_weak_ptr, + params.partition->GetURLLoaderFactoryForBrowserProcess(), profile, status, + params.url, params.email, params.gaia_id, params.password, params.session_index, params.auth_code, signin_scoped_device_id, params.choose_what_to_sync, params.confirm_untrusted_signin, params.is_force_sign_in_with_usermanager); @@ -761,11 +783,14 @@ void InlineLoginHandlerImpl::SyncStarterCallback( if (result == OneClickSigninSyncStarter::SYNC_SETUP_FAILURE) { RedirectToNtpOrAppsPage(contents, access_point); } else if (auto_close) { + bool show_account_management = ShouldShowAccountManagement( + current_url, + AccountConsistencyModeManager::IsMirrorEnabledForProfile( + Profile::FromBrowserContext(contents->GetBrowserContext()))); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&InlineLoginHandlerImpl::CloseTab, - weak_factory_.GetWeakPtr(), - signin::ShouldShowAccountManagement(current_url))); + weak_factory_.GetWeakPtr(), show_account_management)); } else { RedirectToNtpOrAppsPageIfNecessary(contents, access_point); } diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.h b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.h index 5ee5ba81e03..fb2d86fd6e3 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.h +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.h @@ -11,6 +11,7 @@ #include "base/files/file_path.h" #include "base/gtest_prod_util.h" #include "base/macros.h" +#include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/sync/one_click_signin_sync_starter.h" #include "chrome/browser/ui/webui/signin/inline_login_handler.h" @@ -18,6 +19,10 @@ #include "content/public/browser/web_contents_observer.h" #include "google_apis/gaia/gaia_auth_consumer.h" +namespace network { +class SharedURLLoaderFactory; +} + // Implementation for the inline login WebUI handler on desktop Chrome. Once // CrOS migrates to the same webview approach as desktop Chrome, much of the // code in this class should move to its base class |InlineLoginHandler|. @@ -122,22 +127,26 @@ class InlineLoginHandlerImpl : public InlineLoginHandler, // InlineLoginHandlerImpl is destryed once the UI is closed. class InlineSigninHelper : public GaiaAuthConsumer { public: - InlineSigninHelper(base::WeakPtr<InlineLoginHandlerImpl> handler, - net::URLRequestContextGetter* getter, - Profile* profile, - Profile::CreateStatus create_status, - const GURL& current_url, - const std::string& email, - const std::string& gaia_id, - const std::string& password, - const std::string& session_index, - const std::string& auth_code, - const std::string& signin_scoped_device_id, - bool choose_what_to_sync, - bool confirm_untrusted_signin, - bool is_force_sign_in_with_usermanager); + InlineSigninHelper( + base::WeakPtr<InlineLoginHandlerImpl> handler, + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, + Profile* profile, + Profile::CreateStatus create_status, + const GURL& current_url, + const std::string& email, + const std::string& gaia_id, + const std::string& password, + const std::string& session_index, + const std::string& auth_code, + const std::string& signin_scoped_device_id, + bool choose_what_to_sync, + bool confirm_untrusted_signin, + bool is_force_sign_in_with_usermanager); ~InlineSigninHelper() override; + protected: + GaiaAuthFetcher* GetGaiaAuthFetcherForTest() { return &gaia_auth_fetcher_; } + private: // Handles cross account sign in error. If the supplied |email| does not match // the last signed in email of the current profile, then Chrome will show a 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 fc903e8e5dd..3f0c38f29f8 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc @@ -13,7 +13,6 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/webui/metrics_handler.h" -#include "chrome/browser/ui/webui/signin/inline_login_handler_impl.h" #include "chrome/browser/ui/webui/test_files_request_filter.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" @@ -25,6 +24,12 @@ #include "content/public/browser/web_ui_data_source.h" #include "content/public/common/content_switches.h" +#if defined(OS_CHROMEOS) +#include "chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h" +#else +#include "chrome/browser/ui/webui/signin/inline_login_handler_impl.h" +#endif // defined(OS_CHROMEOS) + namespace { content::WebUIDataSource* CreateWebUIDataSource() { @@ -54,14 +59,24 @@ content::WebUIDataSource* CreateWebUIDataSource() { return source; } -} // empty namespace +} // namespace InlineLoginUI::InlineLoginUI(content::WebUI* web_ui) : WebDialogUI(web_ui), - auth_extension_(Profile::FromWebUI(web_ui)) { + auth_extension_(Profile::FromWebUI(web_ui)), + weak_factory_(this) { Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource::Add(profile, CreateWebUIDataSource()); + +#if defined(OS_CHROMEOS) + web_ui->AddMessageHandler( + std::make_unique<chromeos::InlineLoginHandlerChromeOS>( + base::BindRepeating(&WebDialogUIBase::CloseDialog, + weak_factory_.GetWeakPtr(), nullptr /* args */))); +#else web_ui->AddMessageHandler(std::make_unique<InlineLoginHandlerImpl>()); +#endif // defined(OS_CHROMEOS) + web_ui->AddMessageHandler(std::make_unique<MetricsHandler>()); content::WebContents* contents = web_ui->GetWebContents(); diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h index 8863b9c26b4..c5842a3eaf8 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h @@ -6,6 +6,7 @@ #define CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_UI_H_ #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "chrome/browser/extensions/signin/scoped_gaia_auth_extension.h" #include "ui/web_dialogs/web_dialog_ui.h" @@ -25,6 +26,7 @@ class InlineLoginUI : public ui::WebDialogUI { private: ScopedGaiaAuthExtension auth_extension_; + base::WeakPtrFactory<InlineLoginUI> weak_factory_; DISALLOW_COPY_AND_ASSIGN(InlineLoginUI); }; diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_ui_browsertest.cc index 0a14718d1d8..6e672bea55e 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui_browsertest.cc @@ -58,7 +58,9 @@ #include "google_apis/gaia/gaia_switches.h" #include "google_apis/gaia/gaia_urls.h" #include "net/base/url_util.h" +#include "net/dns/mock_host_resolver.h" #include "net/http/http_response_headers.h" +#include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" @@ -153,7 +155,7 @@ class MockInlineSigninHelper : public InlineSigninHelper { public: MockInlineSigninHelper( base::WeakPtr<InlineLoginHandlerImpl> handler, - net::URLRequestContextGetter* getter, + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, Profile* profile, const GURL& current_url, const std::string& email, @@ -175,13 +177,15 @@ class MockInlineSigninHelper : public InlineSigninHelper { OneClickSigninSyncStarter::StartSyncMode, OneClickSigninSyncStarter::ConfirmationRequired)); + GaiaAuthFetcher* GetGaiaAuthFetcher() { return GetGaiaAuthFetcherForTest(); } + private: DISALLOW_COPY_AND_ASSIGN(MockInlineSigninHelper); }; MockInlineSigninHelper::MockInlineSigninHelper( base::WeakPtr<InlineLoginHandlerImpl> handler, - net::URLRequestContextGetter* getter, + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, Profile* profile, const GURL& current_url, const std::string& email, @@ -193,7 +197,7 @@ MockInlineSigninHelper::MockInlineSigninHelper( bool choose_what_to_sync, bool confirm_untrusted_signin) : InlineSigninHelper(handler, - getter, + url_loader_factory, profile, Profile::CreateStatus::CREATE_STATUS_INITIALIZED, current_url, @@ -213,7 +217,7 @@ class MockSyncStarterInlineSigninHelper : public InlineSigninHelper { public: MockSyncStarterInlineSigninHelper( base::WeakPtr<InlineLoginHandlerImpl> handler, - net::URLRequestContextGetter* getter, + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, Profile* profile, const GURL& current_url, const std::string& email, @@ -240,7 +244,7 @@ class MockSyncStarterInlineSigninHelper : public InlineSigninHelper { MockSyncStarterInlineSigninHelper::MockSyncStarterInlineSigninHelper( base::WeakPtr<InlineLoginHandlerImpl> handler, - net::URLRequestContextGetter* getter, + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, Profile* profile, const GURL& current_url, const std::string& email, @@ -253,7 +257,7 @@ MockSyncStarterInlineSigninHelper::MockSyncStarterInlineSigninHelper( bool confirm_untrusted_signin, bool is_force_sign_in_with_usermanager) : InlineSigninHelper(handler, - getter, + url_loader_factory, profile, Profile::CreateStatus::CREATE_STATUS_INITIALIZED, current_url, @@ -454,7 +458,7 @@ IN_PROC_BROWSER_TEST_F(InlineLoginUIBrowserTest, CanOfferNoSigninCookies) { class InlineLoginHelperBrowserTest : public InProcessBrowserTest { public: - InlineLoginHelperBrowserTest() {} + InlineLoginHelperBrowserTest() = default; void SetUpInProcessBrowserTestFixture() override { will_create_browser_context_services_subscription_ = @@ -475,7 +479,42 @@ class InlineLoginHelperBrowserTest : public InProcessBrowserTest { context, &BuildFakeProfileOAuth2TokenService); } + void SetUp() override { + // Don't spin up the IO thread yet since no threads are allowed while + // spawning sandbox host process. See crbug.com/322732. + ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); + + InProcessBrowserTest::SetUp(); + } + + void SetUpCommandLine(base::CommandLine* command_line) override { + const GURL& base_url = embedded_test_server()->base_url(); + command_line->AppendSwitchASCII(::switches::kGaiaUrl, base_url.spec()); + command_line->AppendSwitchASCII(::switches::kLsoUrl, base_url.spec()); + command_line->AppendSwitchASCII(::switches::kGoogleApisUrl, + base_url.spec()); + } + void SetUpOnMainThread() override { + InProcessBrowserTest::SetUpOnMainThread(); + + host_resolver()->AddRule("*", "127.0.0.1"); + + deprecated_client_login_to_oauth2_response_ = + std::make_unique<net::test_server::ControllableHttpResponse>( + embedded_test_server(), + GaiaUrls::GetInstance() + ->deprecated_client_login_to_oauth2_url() + .path(), + /*relative_url_is_prefix=*/true); + oauth2_token_exchange_success_ = + std::make_unique<net::test_server::ControllableHttpResponse>( + embedded_test_server(), + GaiaUrls::GetInstance()->oauth2_token_url().path(), + /*relative_url_is_prefix=*/true); + + embedded_test_server()->StartAcceptingConnections(); + // Grab references to the fake signin manager and token service. Profile* profile = browser()->profile(); signin_manager_ = static_cast<FakeSigninManagerForTesting*>( @@ -487,27 +526,20 @@ class InlineLoginHelperBrowserTest : public InProcessBrowserTest { ASSERT_TRUE(token_service_); } - void SimulateStartCookieForOAuthLoginTokenExchangeSuccess( + void SimulateStartCookieForOAuthLoginTokenExchangeSuccess( const std::string& cookie_string) { - net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - scoped_refptr<net::HttpResponseHeaders> reponse_headers = - new net::HttpResponseHeaders(""); - reponse_headers->AddCookie(cookie_string); - fetcher->set_status(net::URLRequestStatus()); - fetcher->set_response_code(net::HTTP_OK); - fetcher->set_response_headers(reponse_headers); - fetcher->delegate()->OnURLFetchComplete(fetcher); + deprecated_client_login_to_oauth2_response_->WaitForRequest(); + deprecated_client_login_to_oauth2_response_->Send( + net::HTTP_OK, "text/html; charset=utf-8", "", {cookie_string}); + deprecated_client_login_to_oauth2_response_->Done(); } void SimulateStartAuthCodeForOAuth2TokenExchangeSuccess( const std::string& json_response) { - net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - fetcher->set_status(net::URLRequestStatus()); - fetcher->set_response_code(net::HTTP_OK); - fetcher->SetResponseString(json_response); - fetcher->delegate()->OnURLFetchComplete(fetcher); + oauth2_token_exchange_success_->WaitForRequest(); + oauth2_token_exchange_success_->Send( + net::HTTP_OK, "application/json; charset=utf-8", json_response); + oauth2_token_exchange_success_->Done(); } void SimulateOnClientOAuthSuccess(GaiaAuthConsumer* consumer, @@ -519,9 +551,19 @@ class InlineLoginHelperBrowserTest : public InProcessBrowserTest { FakeSigninManagerForTesting* signin_manager() { return signin_manager_; } FakeProfileOAuth2TokenService* token_service() { return token_service_; } + scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory() { + return content::BrowserContext::GetDefaultStoragePartition( + browser()->profile()) + ->GetURLLoaderFactoryForBrowserProcess(); + } + + protected: + std::unique_ptr<net::test_server::ControllableHttpResponse> + deprecated_client_login_to_oauth2_response_; + std::unique_ptr<net::test_server::ControllableHttpResponse> + oauth2_token_exchange_success_; private: - net::TestURLFetcherFactory url_fetcher_factory_; FakeSigninManagerForTesting* signin_manager_; FakeProfileOAuth2TokenService* token_service_; std::unique_ptr< @@ -531,52 +573,57 @@ class InlineLoginHelperBrowserTest : public InProcessBrowserTest { DISALLOW_COPY_AND_ASSIGN(InlineLoginHelperBrowserTest); }; -// Test signin helper calls correct fetcher methods when called with a -// session index. +// Test signin helper calls correct fetcher methods when called with a session +// index. IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, WithSessionIndex) { base::WeakPtr<InlineLoginHandlerImpl> handler; - MockInlineSigninHelper helper(handler, - browser()->profile()->GetRequestContext(), - browser()->profile(), - GURL(), - "foo@gmail.com", - "gaiaid-12345", - "password", - "0", // session index from above + MockInlineSigninHelper helper(handler, test_shared_loader_factory(), + browser()->profile(), GURL(), "foo@gmail.com", + "gaiaid-12345", "password", + "0", // session index from above std::string(), // auth code std::string(), - false, // choose what to sync + false, // choose what to sync false); // confirm untrusted signin - EXPECT_CALL(helper, OnClientOAuthSuccess(_)); + base::RunLoop run_loop; + EXPECT_CALL(helper, OnClientOAuthSuccess(_)) + .WillOnce(testing::InvokeWithoutArgs([&run_loop]() { run_loop.Quit(); })); SimulateStartCookieForOAuthLoginTokenExchangeSuccess( - "secure; httponly; oauth_code=code"); + "oauth_code=code; secure; httponly"); + SimulateStartAuthCodeForOAuth2TokenExchangeSuccess( - "{\"access_token\": \"access_token\", \"expires_in\": 1234567890," - " \"refresh_token\": \"refresh_token\"}"); + R"({ + "access_token": "access_token", + "expires_in": 1234567890, + "refresh_token": "refresh_token" + })"); + run_loop.Run(); } // Test signin helper calls correct fetcher methods when called with an // auth code. IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, WithAuthCode) { base::WeakPtr<InlineLoginHandlerImpl> handler; - MockInlineSigninHelper helper(handler, - browser()->profile()->GetRequestContext(), - browser()->profile(), - GURL(), - "foo@gmail.com", - "gaiaid-12345", - "password", - "", // session index + MockInlineSigninHelper helper(handler, test_shared_loader_factory(), + browser()->profile(), GURL(), "foo@gmail.com", + "gaiaid-12345", "password", + "", // session index "auth_code", // auth code std::string(), - false, // choose what to sync + false, // choose what to sync false); // confirm untrusted signin - EXPECT_CALL(helper, OnClientOAuthSuccess(_)); + base::RunLoop run_loop; + EXPECT_CALL(helper, OnClientOAuthSuccess(_)) + .WillOnce(testing::InvokeWithoutArgs([&run_loop]() { run_loop.Quit(); })); SimulateStartAuthCodeForOAuth2TokenExchangeSuccess( - "{\"access_token\": \"access_token\", \"expires_in\": 1234567890," - " \"refresh_token\": \"refresh_token\"}"); + R"({ + "access_token": "access_token", + "expires_in": 1234567890, + "refresh_token": "refresh_token" + })"); + run_loop.Run(); } // Test signin helper creates sync starter with correct confirmation when @@ -592,7 +639,10 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, // do need the RunUntilIdle() at the end. MockSyncStarterInlineSigninHelper* helper = new MockSyncStarterInlineSigninHelper( - handler, browser()->profile()->GetRequestContext(), + handler, + content::BrowserContext::GetDefaultStoragePartition( + browser()->profile()) + ->GetURLLoaderFactoryForBrowserProcess(), browser()->profile(), url, "foo@gmail.com", "gaiaid-12345", "password", "", // session index @@ -637,9 +687,8 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, // do need the RunUntilIdle() at the end. MockSyncStarterInlineSigninHelper* helper = new MockSyncStarterInlineSigninHelper( - handler, browser()->profile()->GetRequestContext(), - browser()->profile(), url, "foo@gmail.com", "gaiaid-12345", - "password", + handler, test_shared_loader_factory(), browser()->profile(), url, + "foo@gmail.com", "gaiaid-12345", "password", "", // session index "auth_code", // auth code std::string(), @@ -669,9 +718,8 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, // do need the RunUntilIdle() at the end. MockSyncStarterInlineSigninHelper* helper = new MockSyncStarterInlineSigninHelper( - handler, browser()->profile()->GetRequestContext(), - browser()->profile(), url, "foo@gmail.com", "gaiaid-12345", - "password", + handler, test_shared_loader_factory(), browser()->profile(), url, + "foo@gmail.com", "gaiaid-12345", "password", "", // session index "auth_code", // auth code std::string(), @@ -702,9 +750,8 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, // do need the RunUntilIdle() at the end. MockSyncStarterInlineSigninHelper* helper = new MockSyncStarterInlineSigninHelper( - handler, browser()->profile()->GetRequestContext(), - browser()->profile(), url, "foo@gmail.com", "gaiaid-12345", - "password", + handler, test_shared_loader_factory(), browser()->profile(), url, + "foo@gmail.com", "gaiaid-12345", "password", "", // session index "auth_code", // auth code std::string(), @@ -733,7 +780,7 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, // possible values of access_point=, reason=. GURL url("chrome://chrome-signin/?access_point=3&reason=2"); base::WeakPtr<InlineLoginHandlerImpl> handler; - InlineSigninHelper helper(handler, browser()->profile()->GetRequestContext(), + InlineSigninHelper helper(handler, test_shared_loader_factory(), browser()->profile(), Profile::CreateStatus::CREATE_STATUS_INITIALIZED, url, "foo@gmail.com", "gaiaid-12345", "password", @@ -758,7 +805,7 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, // possible values of access_point=, reason=. GURL url("chrome://chrome-signin/?access_point=10&reason=1"); base::WeakPtr<InlineLoginHandlerImpl> handler; - InlineSigninHelper helper(handler, browser()->profile()->GetRequestContext(), + InlineSigninHelper helper(handler, test_shared_loader_factory(), browser()->profile(), Profile::CreateStatus::CREATE_STATUS_INITIALIZED, url, "foo@gmail.com", "gaiaid-12345", "password", @@ -782,9 +829,9 @@ IN_PROC_BROWSER_TEST_F(InlineLoginHelperBrowserTest, // do need the RunUntilIdle() at the end. MockSyncStarterInlineSigninHelper* helper = new MockSyncStarterInlineSigninHelper( - handler, browser()->profile()->GetRequestContext(), - browser()->profile(), url, "foo@gmail.com", "gaiaid-12345", - "password", "", "auth_code", std::string(), false, false, true); + handler, test_shared_loader_factory(), browser()->profile(), url, + "foo@gmail.com", "gaiaid-12345", "password", "", "auth_code", + std::string(), false, false, true); EXPECT_CALL( *helper, CreateSyncStarter(_, _, "refresh_token", 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 7082a0335c6..cf0bf54fbfd 100644 --- a/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc +++ b/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc @@ -22,6 +22,7 @@ #if !defined(OS_CHROMEOS) #include "base/scoped_observer.h" +#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/signin/unified_consent_helper.h" #include "chrome/browser/sync/profile_sync_service_factory.h" @@ -30,14 +31,19 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_list_observer.h" #include "chrome/browser/ui/user_manager.h" +#include "chrome/browser/unified_consent/unified_consent_service_factory.h" +#include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/sync/base/sync_prefs.h" +#include "components/unified_consent/pref_names.h" +#include "components/unified_consent/unified_consent_service.h" // The sync consent bump is shown after startup when a profile's browser // instance becomes active or when there is already an active instance. // It is only shown when |ShouldShowConsentBumpFor(profile)| returns true for a // given profile |profile|. class ConsentBumpActivator : public BrowserListObserver, - public LoginUIService::Observer { + public LoginUIService::Observer, + public OAuth2TokenService::Observer { public: // Creates a ConsentBumpActivator for |profile| which is owned by // |login_ui_service|. @@ -45,9 +51,41 @@ class ConsentBumpActivator : public BrowserListObserver, : login_ui_service_(login_ui_service), profile_(profile), scoped_browser_list_observer_(this), - scoped_login_ui_service_observer_(this) { + scoped_login_ui_service_observer_(this), + scoped_token_service_observer_(this) { + ProfileOAuth2TokenService* token_service = + ProfileOAuth2TokenServiceFactory::GetForProfile(profile_); + if (token_service->AreAllCredentialsLoaded()) + OnRefreshTokensLoaded(); + else + scoped_token_service_observer_.Add(token_service); + } + + // OAuth2TokenService::Observer: + void OnRefreshTokensLoaded() override { + scoped_token_service_observer_.RemoveAll(); + + SigninManager* signin_manager = + SigninManagerFactory::GetForProfile(profile_); + ProfileOAuth2TokenService* token_service = + ProfileOAuth2TokenServiceFactory::GetForProfile(profile_); + + // Avoid showing the consent bump if the refresh token is missing or is in + // an permanent auth error state. When the tokens are loaded, this + // corresponds to the case when the refresh token was invalidated + // client-side after the user signed out of a Google website (e.g. the user + // signed out of Gmail). + if (token_service->RefreshTokenHasError( + signin_manager->GetAuthenticatedAccountId())) { + unified_consent::UnifiedConsentService* consent_service = + UnifiedConsentServiceFactory::GetForProfile(profile_); + consent_service->RecordConsentBumpSuppressReason( + unified_consent::ConsentBumpSuppressReason::kSyncPaused); + return; + } + // Check if there is already an active browser window for |profile|. - Browser* active_browser = chrome::FindLastActiveWithProfile(profile); + Browser* active_browser = chrome::FindLastActiveWithProfile(profile_); if (active_browser) OnBrowserSetLastActive(active_browser); else @@ -75,20 +113,25 @@ class ConsentBumpActivator : public BrowserListObserver, LoginUIService::SyncConfirmationUIClosedResult result) override { scoped_login_ui_service_observer_.RemoveAll(); - // TODO(crbug.com/819909): Record that consent bump was shown. + unified_consent::UnifiedConsentService* consent_service = + UnifiedConsentServiceFactory::GetForProfile(profile_); + + consent_service->MarkConsentBumpShown(); switch (result) { case LoginUIService::CONFIGURE_SYNC_FIRST: + // Opt into Unity and open settings page to make configurations. + consent_service->SetUnifiedConsentGiven(true); chrome::ShowSettingsSubPage(selected_browser_, chrome::kSyncSetupSubPage); break; case LoginUIService::SYNC_WITH_DEFAULT_SETTINGS: - // User gave unified consent. - // TODO(crbug.com/819909): Use unity service to record unified consent / - // set pref. + // Opt into Unity with default configuration. + consent_service->SetUnifiedConsentGiven(true); break; case LoginUIService::ABORT_SIGNIN: // "Make no changes" was selected. + DCHECK(!consent_service->IsUnifiedConsentGiven()); break; } } @@ -96,21 +139,20 @@ class ConsentBumpActivator : public BrowserListObserver, // This should only be called after the browser has been set up, otherwise // this might crash because the profile has not been fully initialized yet. static bool ShouldShowConsentBumpFor(Profile* profile) { - if (!profile->IsSyncAllowed() || !IsUnifiedConsentBumpEnabled(profile)) + if (!profile->IsSyncAllowed() || !IsUnifiedConsentBumpEnabled(profile) || + !ProfileSyncServiceFactory::HasProfileSyncService(profile)) return false; - // TODO(crbug.com/819909): Check if the consent bump or sync confirmation - // has been shown already. (Unity service) - - if (!ProfileSyncServiceFactory::HasProfileSyncService(profile)) + unified_consent::UnifiedConsentService* consent_service = + UnifiedConsentServiceFactory::GetForProfile(profile); + if (!consent_service->ShouldShowConsentBump()) return false; + sync_ui_util::MessageType sync_status = sync_ui_util::GetStatus( profile, ProfileSyncServiceFactory::GetForProfile(profile), *SigninManagerFactory::GetForProfile(profile)); - syncer::SyncPrefs prefs(profile->GetPrefs()); - return sync_status == sync_ui_util::SYNCED && - prefs.HasKeepEverythingSynced(); + return sync_status == sync_ui_util::SYNCED; } private: @@ -122,6 +164,8 @@ class ConsentBumpActivator : public BrowserListObserver, scoped_browser_list_observer_; ScopedObserver<LoginUIService, ConsentBumpActivator> scoped_login_ui_service_observer_; + ScopedObserver<OAuth2TokenService, ConsentBumpActivator> + scoped_token_service_observer_; // Used for the action handling of the consent bump. Browser* selected_browser_ = nullptr; diff --git a/chromium/chrome/browser/ui/webui/signin/login_ui_service_factory.cc b/chromium/chrome/browser/ui/webui/signin/login_ui_service_factory.cc index a36f3c07aba..dea7a64e3af 100644 --- a/chromium/chrome/browser/ui/webui/signin/login_ui_service_factory.cc +++ b/chromium/chrome/browser/ui/webui/signin/login_ui_service_factory.cc @@ -7,9 +7,11 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/webui/signin/login_ui_service.h" +#include "chrome/browser/unified_consent/unified_consent_service_factory.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_manager.h" @@ -20,6 +22,8 @@ LoginUIServiceFactory::LoginUIServiceFactory() BrowserContextDependencyManager::GetInstance()) { DependsOn(SigninManagerFactory::GetInstance()); DependsOn(ProfileSyncServiceFactory::GetInstance()); + DependsOn(ProfileOAuth2TokenServiceFactory::GetInstance()); + DependsOn(UnifiedConsentServiceFactory::GetInstance()); } LoginUIServiceFactory::~LoginUIServiceFactory() {} @@ -35,14 +39,6 @@ LoginUIServiceFactory* LoginUIServiceFactory::GetInstance() { return base::Singleton<LoginUIServiceFactory>::get(); } -// static -base::Closure LoginUIServiceFactory::GetShowLoginPopupCallbackForProfile( - Profile* profile) { - return base::Bind( - &LoginUIService::ShowLoginPopup, - base::Unretained(LoginUIServiceFactory::GetForProfile(profile))); -} - KeyedService* LoginUIServiceFactory::BuildServiceInstanceFor( content::BrowserContext* profile) const { return new LoginUIService(static_cast<Profile*>(profile)); diff --git a/chromium/chrome/browser/ui/webui/signin/login_ui_service_factory.h b/chromium/chrome/browser/ui/webui/signin/login_ui_service_factory.h index f6defd3a23e..69c79efc417 100644 --- a/chromium/chrome/browser/ui/webui/signin/login_ui_service_factory.h +++ b/chromium/chrome/browser/ui/webui/signin/login_ui_service_factory.h @@ -25,11 +25,6 @@ class LoginUIServiceFactory : public BrowserContextKeyedServiceFactory { // Returns an instance of the LoginUIServiceFactory singleton. static LoginUIServiceFactory* GetInstance(); - // Helper method that returns a closure displaying the login popup for - // |profile|. - // This closure must not be called after the LoginUIService is destroyed. - static base::Closure GetShowLoginPopupCallbackForProfile(Profile* profile); - private: friend struct base::DefaultSingletonTraits<LoginUIServiceFactory>; diff --git a/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.cc b/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.cc index c05633a4ec6..a787163eff1 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.cc @@ -22,17 +22,17 @@ namespace { // Dialog size. -const int kDialogWidth = 512; -const int kDialogMinHeight = 200; -const int kDialogMaxHeight = 700; +const int kSigninEmailConfirmationDialogWidth = 512; +const int kSigninEmailConfirmationDialogMinHeight = 200; +const int kSigninEmailConfirmationDialogMaxHeight = 700; // Dialog action key; -const char kActionKey[] = "action"; +const char kSigninEmailConfirmationActionKey[] = "action"; // Dialog action values. -const char kActionCancel[] = "cancel"; -const char kActionCreateNewUser[] = "createNewUser"; -const char kActionStartSync[] = "startSync"; +const char kSigninEmailConfirmationActionCancel[] = "cancel"; +const char kSigninEmailConfirmationActionCreateNewUser[] = "createNewUser"; +const char kSigninEmailConfirmationActionStartSync[] = "startSync"; } // namespace @@ -92,8 +92,10 @@ void SigninEmailConfirmationDialog::AskForConfirmation( } void SigninEmailConfirmationDialog::ShowDialog() { - gfx::Size min_size(kDialogWidth, kDialogMinHeight); - gfx::Size max_size(kDialogWidth, kDialogMaxHeight); + gfx::Size min_size(kSigninEmailConfirmationDialogWidth, + kSigninEmailConfirmationDialogMinHeight); + gfx::Size max_size(kSigninEmailConfirmationDialogWidth, + kSigninEmailConfirmationDialogMaxHeight); ConstrainedWebDialogDelegate* dialog_delegate = ShowConstrainedWebDialogWithAutoResize(profile_, this, web_contents_, min_size, max_size); @@ -157,7 +159,7 @@ void SigninEmailConfirmationDialog::GetDialogSize(gfx::Size* size) const { // horizontally when it appears. Avoid setting a dialog height in here as // this dialog auto-resizes. if (size->IsEmpty()) - size->set_width(kDialogWidth); + size->set_width(kSigninEmailConfirmationDialogWidth); } std::string SigninEmailConfirmationDialog::GetDialogArgs() const { @@ -176,12 +178,13 @@ void SigninEmailConfirmationDialog::OnDialogClosed( base::DictionaryValue::From(base::JSONReader::Read(json_retval))); if (ret_value) { std::string action_string; - if (ret_value->GetString(kActionKey, &action_string)) { - if (action_string == kActionCancel) { + if (ret_value->GetString(kSigninEmailConfirmationActionKey, + &action_string)) { + if (action_string == kSigninEmailConfirmationActionCancel) { action = CLOSE; - } else if (action_string == kActionCreateNewUser) { + } else if (action_string == kSigninEmailConfirmationActionCreateNewUser) { action = CREATE_NEW_USER; - } else if (action_string == kActionStartSync) { + } else if (action_string == kSigninEmailConfirmationActionStartSync) { action = START_SYNC; } else { NOTREACHED() << "Unexpected action value [" << action_string << "]"; 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 e4718068ef1..1fb615c2036 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc @@ -7,18 +7,21 @@ #include <vector> #include "base/bind.h" +#include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/consent_auditor/consent_auditor_factory.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/signin/account_tracker_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/unified_consent_helper.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/signin_view_controller_delegate.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/browser/ui/webui/signin/signin_utils.h" #include "chrome/browser/ui/webui/signin/sync_confirmation_ui.h" +#include "chrome/common/webui_url_constants.h" #include "components/consent_auditor/consent_auditor.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/avatar_icon_util.h" @@ -27,15 +30,30 @@ #include "content/public/browser/web_ui.h" #include "url/gurl.h" +namespace { +// Used for UMA. Do not reorder, append new values at the end. +enum class UnifiedConsentBumpAction { + kOptIn = 0, + kMoreOptionsOptIn = 1, + kMoreOptionsSettings = 2, + kMoreOptionsNoChanges = 3, + kAbort = 4, + + kMaxValue = kAbort +}; +} // namespace + const int kProfileImageSize = 128; SyncConfirmationHandler::SyncConfirmationHandler( Browser* browser, - const std::unordered_map<std::string, int>& string_to_grd_id_map) + const std::unordered_map<std::string, int>& string_to_grd_id_map, + consent_auditor::Feature consent_feature) : profile_(browser->profile()), browser_(browser), did_user_explicitly_interact(false), - string_to_grd_id_map_(string_to_grd_id_map) { + string_to_grd_id_map_(string_to_grd_id_map), + consent_feature_(consent_feature) { DCHECK(profile_); DCHECK(browser_); BrowserList::AddObserver(this); @@ -49,7 +67,12 @@ SyncConfirmationHandler::~SyncConfirmationHandler() { // sync confirmation dialog are taken by the user. if (!did_user_explicitly_interact) { HandleUndo(nullptr); - base::RecordAction(base::UserMetricsAction("Signin_Abort_Signin")); + if (IsUnifiedConsentBumpDialog()) { + UMA_HISTOGRAM_ENUMERATION("UnifiedConsent.ConsentBump.Action", + UnifiedConsentBumpAction::kAbort); + } else { + base::RecordAction(base::UserMetricsAction("Signin_Abort_Signin")); + } } } @@ -119,8 +142,8 @@ void SyncConfirmationHandler::RecordConsent(const base::ListValue* args) { ConsentAuditorFactory::GetForProfile(profile_)->RecordGaiaConsent( SigninManagerFactory::GetForProfile(profile_) ->GetAuthenticatedAccountId(), - consent_auditor::Feature::CHROME_SYNC, consent_text_ids, - consent_confirmation_id, consent_auditor::ConsentStatus::GIVEN); + consent_feature_, consent_text_ids, consent_confirmation_id, + consent_auditor::ConsentStatus::GIVEN); } void SyncConfirmationHandler::SetUserImageURL(const std::string& picture_url) { @@ -154,18 +177,22 @@ void SyncConfirmationHandler::OnAccountUpdated(const AccountInfo& info) { void SyncConfirmationHandler::CloseModalSigninWindow( LoginUIService::SyncConfirmationUIClosedResult result) { - switch (result) { - case LoginUIService::CONFIGURE_SYNC_FIRST: - base::RecordAction( - base::UserMetricsAction("Signin_Signin_WithAdvancedSyncSettings")); - break; - case LoginUIService::SYNC_WITH_DEFAULT_SETTINGS: - base::RecordAction( - base::UserMetricsAction("Signin_Signin_WithDefaultSyncSettings")); - break; - case LoginUIService::ABORT_SIGNIN: - base::RecordAction(base::UserMetricsAction("Signin_Undo_Signin")); - break; + if (!IsUnifiedConsentBumpDialog()) { + // Metrics for the unified consent bump are recorded directly from + // javascript. + switch (result) { + case LoginUIService::CONFIGURE_SYNC_FIRST: + base::RecordAction( + base::UserMetricsAction("Signin_Signin_WithAdvancedSyncSettings")); + break; + case LoginUIService::SYNC_WITH_DEFAULT_SETTINGS: + base::RecordAction( + base::UserMetricsAction("Signin_Signin_WithDefaultSyncSettings")); + break; + case LoginUIService::ABORT_SIGNIN: + base::RecordAction(base::UserMetricsAction("Signin_Undo_Signin")); + break; + } } LoginUIServiceFactory::GetForProfile(profile_)->SyncConfirmationUIClosed( result); @@ -205,3 +232,8 @@ void SyncConfirmationHandler::HandleInitializedWithSize( // workaround. web_ui()->CallJavascriptFunctionUnsafe("sync.confirmation.clearFocus"); } + +bool SyncConfirmationHandler::IsUnifiedConsentBumpDialog() { + return web_ui()->GetWebContents()->GetVisibleURL() == + chrome::kChromeUISyncConsentBumpURL; +} diff --git a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.h b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.h index 8cab0b742a7..3eb4b5bb536 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.h +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.h @@ -11,6 +11,7 @@ #include "base/macros.h" #include "chrome/browser/ui/browser_list_observer.h" #include "chrome/browser/ui/webui/signin/login_ui_service.h" +#include "components/consent_auditor/consent_auditor.h" #include "components/signin/core/browser/account_tracker_service.h" #include "content/public/browser/web_ui_message_handler.h" @@ -27,7 +28,8 @@ class SyncConfirmationHandler : public content::WebUIMessageHandler, // mapped to their GRD IDs. explicit SyncConfirmationHandler( Browser* browser, - const std::unordered_map<std::string, int>& string_to_grd_id_map); + const std::unordered_map<std::string, int>& string_to_grd_id_map, + consent_auditor::Feature consent_feature); ~SyncConfirmationHandler() override; // content::WebUIMessageHandler: @@ -80,6 +82,10 @@ class SyncConfirmationHandler : public content::WebUIMessageHandler, void CloseModalSigninWindow( LoginUIService::SyncConfirmationUIClosedResult result); + // Returns true if this is a unified consent bump dialog, and false if this is + // a regular sync confirmation. + bool IsUnifiedConsentBumpDialog(); + private: Profile* profile_; @@ -93,6 +99,9 @@ class SyncConfirmationHandler : public content::WebUIMessageHandler, // and their respective GRD IDs. std::unordered_map<std::string, int> string_to_grd_id_map_; + // Contains the features to use when the user consent decision is recorded. + consent_auditor::Feature consent_feature_; + DISALLOW_COPY_AND_ASSIGN(SyncConfirmationHandler); }; 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 d9b4a32ca2e..f9d193e5ae2 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 @@ -8,7 +8,10 @@ #include <unordered_map> #include <vector> -#include "base/test/user_action_tester.h" +#include "base/bind_helpers.h" +#include "base/scoped_observer.h" +#include "base/test/metrics/histogram_tester.h" +#include "base/test/metrics/user_action_tester.h" #include "base/values.h" #include "chrome/browser/consent_auditor/consent_auditor_factory.h" #include "chrome/browser/consent_auditor/consent_auditor_test_utils.h" @@ -21,7 +24,10 @@ #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/ui/webui/signin/login_ui_service.h" +#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/browser/ui/webui/signin/sync_confirmation_ui.h" +#include "chrome/common/webui_url_constants.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/dialog_test_browser_window.h" #include "chrome/test/base/testing_profile.h" @@ -46,7 +52,9 @@ class TestingSyncConfirmationHandler : public SyncConfirmationHandler { Browser* browser, content::WebUI* web_ui, std::unordered_map<std::string, int> string_to_grd_id_map) - : SyncConfirmationHandler(browser, string_to_grd_id_map) { + : SyncConfirmationHandler(browser, + string_to_grd_id_map, + consent_auditor::Feature::CHROME_SYNC) { set_web_ui(web_ui); } @@ -56,48 +64,14 @@ class TestingSyncConfirmationHandler : public SyncConfirmationHandler { using SyncConfirmationHandler::HandleGoToSettings; using SyncConfirmationHandler::RecordConsent; using SyncConfirmationHandler::SetUserImageURL; + using SyncConfirmationHandler::IsUnifiedConsentBumpDialog; private: DISALLOW_COPY_AND_ASSIGN(TestingSyncConfirmationHandler); }; -class TestingOneClickSigninSyncStarter : public OneClickSigninSyncStarter { - public: - TestingOneClickSigninSyncStarter(Profile* profile, - Browser* browser, - const std::string& gaia_id, - const std::string& email, - const std::string& password, - const std::string& refresh_token, - signin_metrics::AccessPoint access_point, - signin_metrics::Reason signin_reason, - ProfileMode profile_mode, - StartSyncMode start_mode, - ConfirmationRequired display_confirmation, - Callback callback) - : OneClickSigninSyncStarter(profile, - browser, - gaia_id, - email, - password, - refresh_token, - access_point, - signin_reason, - profile_mode, - start_mode, - display_confirmation, - callback) {} - - protected: - void ShowSyncSetupSettingsSubpage() override { - // Intentionally don't open a tab to settings. - } - - private: - DISALLOW_COPY_AND_ASSIGN(TestingOneClickSigninSyncStarter); -}; - -class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest { +class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest, + public LoginUIService::Observer { public: static const char kConsentText1[]; static const char kConsentText2[]; @@ -106,7 +80,12 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest { static const char kConsentText5[]; SyncConfirmationHandlerTest() - : did_user_explicitly_interact(false), web_ui_(new content::TestWebUI) {} + : did_user_explicitly_interact(false), + on_sync_confirmation_ui_closed_called_(false), + sync_confirmation_ui_closed_result_(LoginUIService::ABORT_SIGNIN), + web_ui_(new content::TestWebUI), + login_ui_service_observer_(this) {} + void SetUp() override { BrowserWithTestWindowTest::SetUp(); chrome::NewTab(browser()); @@ -119,34 +98,42 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest { sync_confirmation_ui_.reset(new SyncConfirmationUI(web_ui())); web_ui()->AddMessageHandler(std::move(handler)); - // This dialog assumes the signin flow was completed, which kicks off the - // SigninManager. - new TestingOneClickSigninSyncStarter( - profile(), browser(), "gaia", "foo@example.com", "password", - "refresh_token", signin_metrics::AccessPoint::ACCESS_POINT_UNKNOWN, - signin_metrics::Reason::REASON_UNKNOWN_REASON, - OneClickSigninSyncStarter::CURRENT_PROFILE, - OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS, - OneClickSigninSyncStarter::NO_CONFIRMATION, - OneClickSigninSyncStarter::Callback()); + signin_manager()->StartSignInWithRefreshToken("refresh_token", "gaia", + "foo@example.com", "password", + base::DoNothing()); + signin_manager()->CompletePendingSignin(); + login_ui_service_observer_.Add( + LoginUIServiceFactory::GetForProfile(profile())); + + EXPECT_FALSE(handler_->IsUnifiedConsentBumpDialog()); } void TearDown() override { + bool is_unified_consent_bump_dialog = + handler_->IsUnifiedConsentBumpDialog(); + + login_ui_service_observer_.RemoveAll(); sync_confirmation_ui_.reset(); web_ui_.reset(); BrowserWithTestWindowTest::TearDown(); - if (did_user_explicitly_interact) { + if (!did_user_explicitly_interact && is_unified_consent_bump_dialog) { + const int kAbort = 4; + histogram_tester_.ExpectUniqueSample("UnifiedConsent.ConsentBump.Action", + kAbort, 1); EXPECT_EQ(0, user_action_tester()->GetActionCount("Signin_Abort_Signin")); } else { - EXPECT_EQ(1, user_action_tester()->GetActionCount("Signin_Abort_Signin")); + histogram_tester_.ExpectTotalCount("UnifiedConsent.ConsentBump.Action", + 0); } - } - TestingSyncConfirmationHandler* handler() { - return handler_; + EXPECT_EQ( + did_user_explicitly_interact || is_unified_consent_bump_dialog ? 0 : 1, + user_action_tester()->GetActionCount("Signin_Abort_Signin")); } + TestingSyncConfirmationHandler* handler() { return handler_; } + content::TestWebUI* web_ui() { return web_ui_.get(); } @@ -174,7 +161,7 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest { ConsentAuditorFactory::GetForProfile(profile())); } - // BrowserWithTestWindowTest + // BrowserWithTestWindowTest: BrowserWindow* CreateBrowserWindow() override { return new DialogTestBrowserWindow; } @@ -197,8 +184,18 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest { return string_to_grd_id_map_; } + // LoginUIService::Observer: + void OnSyncConfirmationUIClosed( + LoginUIService::SyncConfirmationUIClosedResult result) override { + on_sync_confirmation_ui_closed_called_ = true; + sync_confirmation_ui_closed_result_ = result; + } + protected: bool did_user_explicitly_interact; + bool on_sync_confirmation_ui_closed_called_; + LoginUIService::SyncConfirmationUIClosedResult + sync_confirmation_ui_closed_result_; private: std::unique_ptr<content::TestWebUI> web_ui_; @@ -206,6 +203,9 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest { TestingSyncConfirmationHandler* handler_; // Not owned. base::UserActionTester user_action_tester_; std::unordered_map<std::string, int> string_to_grd_id_map_; + ScopedObserver<LoginUIService, LoginUIService::Observer> + login_ui_service_observer_; + base::HistogramTester histogram_tester_; DISALLOW_COPY_AND_ASSIGN(SyncConfirmationHandlerTest); }; @@ -331,16 +331,11 @@ TEST_F(SyncConfirmationHandlerTest, } TEST_F(SyncConfirmationHandlerTest, TestHandleUndo) { - EXPECT_FALSE(sync()->IsFirstSetupComplete()); - EXPECT_TRUE(sync()->IsFirstSetupInProgress()); - handler()->HandleUndo(nullptr); did_user_explicitly_interact = true; - EXPECT_FALSE(sync()->IsFirstSetupInProgress()); - EXPECT_FALSE(sync()->IsFirstSetupComplete()); - EXPECT_FALSE( - SigninManagerFactory::GetForProfile(profile())->IsAuthenticated()); + EXPECT_TRUE(on_sync_confirmation_ui_closed_called_); + EXPECT_EQ(LoginUIService::ABORT_SIGNIN, sync_confirmation_ui_closed_result_); EXPECT_EQ(1, user_action_tester()->GetActionCount("Signin_Undo_Signin")); EXPECT_EQ(0, user_action_tester()->GetActionCount( "Signin_Signin_WithDefaultSyncSettings")); @@ -348,6 +343,31 @@ TEST_F(SyncConfirmationHandlerTest, TestHandleUndo) { "Signin_Signin_WithAdvancedSyncSettings")); } +TEST_F(SyncConfirmationHandlerTest, TestConsentBump) { + // Enable the consent bump by setting the URL of the web ui. + NavigateAndCommit(&web_ui()->GetWebContents()->GetController(), + GURL(chrome::kChromeUISyncConsentBumpURL)); + EXPECT_TRUE(handler()->IsUnifiedConsentBumpDialog()); + + handler()->HandleUndo(nullptr); + did_user_explicitly_interact = true; + ASSERT_TRUE(on_sync_confirmation_ui_closed_called_); + ASSERT_EQ(LoginUIService::ABORT_SIGNIN, sync_confirmation_ui_closed_result_); + + // The regular sync confirmation metrics are not recorded for the consent + // bump. + EXPECT_EQ(0, user_action_tester()->GetActionCount("Signin_Undo_Signin")); +} + +TEST_F(SyncConfirmationHandlerTest, TestConsentBumpAbort) { + // Enable the consent bump by setting the URL of the web ui. + NavigateAndCommit(&web_ui()->GetWebContents()->GetController(), + GURL(chrome::kChromeUISyncConsentBumpURL)); + EXPECT_TRUE(handler()->IsUnifiedConsentBumpDialog()); + + // The histogram sample will be tested in TearDown(). +} + TEST_F(SyncConfirmationHandlerTest, TestHandleConfirm) { // The consent description consists of strings 1, 2, and 4. base::ListValue consent_description; @@ -366,16 +386,12 @@ TEST_F(SyncConfirmationHandlerTest, TestHandleConfirm) { args.GetList().push_back(std::move(consent_description)); args.GetList().push_back(std::move(consent_confirmation)); - EXPECT_FALSE(sync()->IsFirstSetupComplete()); - EXPECT_TRUE(sync()->IsFirstSetupInProgress()); - handler()->HandleConfirm(&args); did_user_explicitly_interact = true; - EXPECT_FALSE(sync()->IsFirstSetupInProgress()); - EXPECT_TRUE(sync()->IsFirstSetupComplete()); - EXPECT_TRUE( - SigninManagerFactory::GetForProfile(profile())->IsAuthenticated()); + EXPECT_TRUE(on_sync_confirmation_ui_closed_called_); + EXPECT_EQ(LoginUIService::SYNC_WITH_DEFAULT_SETTINGS, + sync_confirmation_ui_closed_result_); EXPECT_EQ(0, user_action_tester()->GetActionCount("Signin_Undo_Signin")); EXPECT_EQ(1, user_action_tester()->GetActionCount( "Signin_Signin_WithDefaultSyncSettings")); @@ -383,8 +399,12 @@ TEST_F(SyncConfirmationHandlerTest, TestHandleConfirm) { "Signin_Signin_WithAdvancedSyncSettings")); // The corresponding string IDs get recorded. - std::vector<std::vector<int>> expected_id_vectors = {{1, 2, 4, 5}}; + std::vector<std::vector<int>> expected_id_vectors = {{1, 2, 4}}; + std::vector<int> expected_confirmation_ids = {5}; + EXPECT_EQ(expected_id_vectors, consent_auditor()->recorded_id_vectors()); + EXPECT_EQ(expected_confirmation_ids, + consent_auditor()->recorded_confirmation_ids()); EXPECT_EQ(signin_manager()->GetAuthenticatedAccountId(), consent_auditor()->account_id()); @@ -408,16 +428,12 @@ TEST_F(SyncConfirmationHandlerTest, TestHandleConfirmWithAdvancedSyncSettings) { args.GetList().push_back(std::move(consent_description)); args.GetList().push_back(std::move(consent_confirmation)); - EXPECT_FALSE(sync()->IsFirstSetupComplete()); - EXPECT_TRUE(sync()->IsFirstSetupInProgress()); - handler()->HandleGoToSettings(&args); did_user_explicitly_interact = true; - EXPECT_FALSE(sync()->IsFirstSetupInProgress()); - EXPECT_FALSE(sync()->IsFirstSetupComplete()); - EXPECT_TRUE( - SigninManagerFactory::GetForProfile(profile())->IsAuthenticated()); + EXPECT_TRUE(on_sync_confirmation_ui_closed_called_); + EXPECT_EQ(LoginUIService::CONFIGURE_SYNC_FIRST, + sync_confirmation_ui_closed_result_); EXPECT_EQ(0, user_action_tester()->GetActionCount("Signin_Undo_Signin")); EXPECT_EQ(0, user_action_tester()->GetActionCount( "Signin_Signin_WithDefaultSyncSettings")); @@ -425,8 +441,11 @@ TEST_F(SyncConfirmationHandlerTest, TestHandleConfirmWithAdvancedSyncSettings) { "Signin_Signin_WithAdvancedSyncSettings")); // The corresponding string IDs get recorded. - std::vector<std::vector<int>> expected_id_vectors = {{2, 3, 5, 2}}; + std::vector<std::vector<int>> expected_id_vectors = {{2, 3, 5}}; + std::vector<int> expected_confirmation_ids = {2}; EXPECT_EQ(expected_id_vectors, consent_auditor()->recorded_id_vectors()); + EXPECT_EQ(expected_confirmation_ids, + consent_auditor()->recorded_confirmation_ids()); EXPECT_EQ(signin_manager()->GetAuthenticatedAccountId(), consent_auditor()->account_id()); 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 0fd7181d995..48e1cd78036 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc @@ -10,7 +10,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/signin/account_consistency_mode_manager.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/unified_consent_helper.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/webui/signin/sync_confirmation_handler.h" @@ -18,15 +18,16 @@ #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" #include "components/signin/core/browser/avatar_icon_util.h" -#include "components/signin/core/browser/signin_manager.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/identity/public/cpp/identity_manager.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) - : SigninWebDialogUI(web_ui) { + : SigninWebDialogUI(web_ui), + consent_feature_(consent_auditor::Feature::CHROME_SYNC) { Profile* profile = Profile::FromWebUI(web_ui); bool is_sync_allowed = profile->IsSyncAllowed(); bool is_unified_consent_enabled = IsUnifiedConsentEnabled(profile); @@ -41,6 +42,8 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) int undo_button_ids = -1; if (is_unified_consent_enabled && is_sync_allowed) { source->SetDefaultResource(IDR_DICE_SYNC_CONFIRMATION_HTML); + source->AddResourcePath("icons.html", + IDR_DICE_SYNC_CONFIRMATION_ICONS_HTML); source->AddResourcePath("sync_confirmation_browser_proxy.html", IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_HTML); source->AddResourcePath("sync_confirmation_browser_proxy.js", @@ -84,8 +87,7 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) IDS_SYNC_CONFIRMATION_UNITY_OPTIONS_USE_DEFAULT_TITLE); AddStringResource(source, "syncConfirmationOptionsUseDefaultSubtitle", IDS_SYNC_CONFIRMATION_UNITY_OPTIONS_USE_DEFAULT_SUBTITLE); - AddStringResource(source, "syncConfirmationOptionsConfirmLabel", - IDS_SYNC_CONFIRMATION_UNITY_OPTIONS_CONFIRM_BUTTON_LABEL); + AddStringResource(source, "syncConfirmationOptionsConfirmLabel", IDS_OK); AddStringResource(source, "syncConfirmationOptionsBackLabel", IDS_SYNC_CONFIRMATION_UNITY_OPTIONS_BACK_BUTTON_LABEL); AddStringResource(source, "syncConsentBumpTitle", @@ -93,8 +95,8 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) constexpr int kAccountPictureSize = 68; std::string custom_picture_url = profiles::GetPlaceholderAvatarIconUrl(); - GURL account_picture_url(SigninManagerFactory::GetForProfile(profile) - ->GetAuthenticatedAccountInfo() + GURL account_picture_url(IdentityManagerFactory::GetForProfile(profile) + ->GetPrimaryAccountInfo() .picture_url); if (account_picture_url.is_valid()) { custom_picture_url = signin::GetAvatarImageURLWithOptions( @@ -107,6 +109,7 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) title_ids = IDS_SYNC_CONFIRMATION_UNITY_TITLE; confirm_button_ids = IDS_SYNC_CONFIRMATION_DICE_CONFIRM_BUTTON_LABEL; undo_button_ids = IDS_CANCEL; + consent_feature_ = consent_auditor::Feature::CHROME_UNIFIED_CONSENT; } else { source->SetDefaultResource(IDR_SYNC_CONFIRMATION_HTML); source->AddResourcePath("sync_confirmation.css", IDR_SYNC_CONFIRMATION_CSS); @@ -132,6 +135,7 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) : IDS_SYNC_CONFIRMATION_TITLE; confirm_button_ids = IDS_SYNC_CONFIRMATION_CONFIRM_BUTTON_LABEL; undo_button_ids = IDS_SYNC_CONFIRMATION_UNDO_BUTTON_LABEL; + consent_feature_ = consent_auditor::Feature::CHROME_SYNC; if (!is_sync_allowed) { title_ids = IDS_SYNC_DISABLED_CONFIRMATION_CHROME_SYNC_TITLE; confirm_button_ids = IDS_SYNC_DISABLED_CONFIRMATION_CONFIRM_BUTTON_LABEL; @@ -159,7 +163,7 @@ SyncConfirmationUI::~SyncConfirmationUI() {} void SyncConfirmationUI::InitializeMessageHandlerWithBrowser(Browser* browser) { web_ui()->AddMessageHandler(std::make_unique<SyncConfirmationHandler>( - browser, js_localized_string_to_ids_map_)); + browser, js_localized_string_to_ids_map_, consent_feature_)); } void SyncConfirmationUI::AddStringResource(content::WebUIDataSource* source, diff --git a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.h b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.h index 0763d791a89..a2b773e1b2d 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.h +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.h @@ -11,6 +11,7 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/signin/signin_web_dialog_ui.h" +#include "components/consent_auditor/consent_auditor.h" namespace content { class WebUIDataSource; @@ -43,6 +44,8 @@ class SyncConfirmationUI : public SigninWebDialogUI { std::unordered_map<std::string, int> js_localized_string_to_ids_map_; + consent_auditor::Feature consent_feature_; + DISALLOW_COPY_AND_ASSIGN(SyncConfirmationUI); }; 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 b2c1614bba8..e83ded59827 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 @@ -95,7 +95,7 @@ const char kJsApiUserManagerRemoveUserWarningLoadStats[] = "removeUserWarningLoadStats"; const char kJsApiUserManagerAreAllProfilesLocked[] = "areAllProfilesLocked"; -const size_t kAvatarIconSize = 180; +const size_t kSigninAvatarIconSize = 180; const int kMaxOAuthRetries = 3; std::string GetAvatarImage(const ProfileAttributesEntry* entry) { @@ -112,7 +112,8 @@ std::string GetAvatarImage(const ProfileAttributesEntry* entry) { profiles::GetPlaceholderAvatarIconResourceID()); } gfx::Image resized_image = profiles::GetSizedAvatarIcon( - avatar_image, is_gaia_picture, kAvatarIconSize, kAvatarIconSize); + avatar_image, is_gaia_picture, kSigninAvatarIconSize, + kSigninAvatarIconSize); return webui::GetBitmapDataUrl(resized_image.AsBitmap()); } @@ -165,12 +166,6 @@ void UrlHashHelper::OnBrowserRemoved(Browser* browser) { } void UrlHashHelper::ExecuteUrlHash() { - if (hash_ == profiles::kUserManagerSelectProfileAppLauncher) { - // TODO(crbug/821659): Clean up the desktop UserManager webui. - NOTIMPLEMENTED(); - return; - } - Browser* target_browser = browser_; if (!target_browser) { target_browser = chrome::FindLastActiveWithProfile(profile_); diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc index 8de7fc51908..a65c05cce6b 100644 --- a/chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc @@ -7,7 +7,7 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" -#include "base/test/histogram_tester.h" +#include "base/test/metrics/histogram_tester.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/profiles/profiles_state.h" diff --git a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc index b94b04d84b6..861389f5877 100644 --- a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc @@ -24,6 +24,8 @@ namespace { content::WebUIDataSource* CreateSignInInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUISignInInternalsHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->SetJsonPath("strings.js"); source->AddResourcePath("signin_internals.js", IDR_SIGNIN_INTERNALS_INDEX_JS); diff --git a/chromium/chrome/browser/ui/webui/site_settings_helper.cc b/chromium/chrome/browser/ui/webui/site_settings_helper.cc index de6fa116170..f7cfefa7fe5 100644 --- a/chromium/chrome/browser/ui/webui/site_settings_helper.cc +++ b/chromium/chrome/browser/ui/webui/site_settings_helper.cc @@ -161,7 +161,7 @@ SiteSettingSource CalculateSiteSettingSource( if (content_type == CONTENT_SETTINGS_TYPE_ADS && base::FeatureList::IsEnabled( - subresource_filter::kSafeBrowsingSubresourceFilterExperimentalUI)) { + subresource_filter::kSafeBrowsingSubresourceFilter)) { HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile(profile); if (map->GetWebsiteSetting(origin, GURL(), CONTENT_SETTINGS_TYPE_ADS_DATA, 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 3d36440c8cd..5b1f25e05fb 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 @@ -19,6 +19,8 @@ SnippetsInternalsUI::SnippetsInternalsUI(content::WebUI* web_ui) : ui::MojoWebUIController(web_ui), binding_(this) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUISnippetsInternalsHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->AddResourcePath("snippets_internals.css", IDR_SNIPPETS_INTERNALS_CSS); source->AddResourcePath("snippets_internals.js", IDR_SNIPPETS_INTERNALS_JS); source->AddResourcePath("snippets_internals.mojom.js", diff --git a/chromium/chrome/browser/ui/webui/supervised_user_internals_ui.cc b/chromium/chrome/browser/ui/webui/supervised_user_internals_ui.cc index 6cfad436a2d..ae96daf2e78 100644 --- a/chromium/chrome/browser/ui/webui/supervised_user_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/supervised_user_internals_ui.cc @@ -18,6 +18,8 @@ namespace { content::WebUIDataSource* CreateSupervisedUserInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create( chrome::kChromeUISupervisedUserInternalsHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->AddResourcePath("supervised_user_internals.js", IDR_SUPERVISED_USER_INTERNALS_JS); 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 d6aa8fc7887..039990ee7f7 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 @@ -29,7 +29,7 @@ namespace syncfs_internals { namespace { void ConvertExtensionStatusToDictionary( - const base::WeakPtr<ExtensionService>& extension_service, + const base::WeakPtr<extensions::ExtensionService>& extension_service, const base::Callback<void(const base::ListValue&)>& callback, const std::map<GURL, std::string>& status_map) { if (!extension_service) { @@ -87,7 +87,7 @@ void ExtensionStatusesHandler::GetExtensionStatusesAsDictionary( return; } - ExtensionService* extension_service = + extensions::ExtensionService* extension_service = extensions::ExtensionSystem::Get(profile)->extension_service(); if (!extension_service) { callback.Run(base::ListValue()); diff --git a/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js b/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js index ad8967328ea..273c0056480 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js +++ b/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js @@ -234,8 +234,7 @@ NETWORK_EVENT_DETAILS_2 = { }; TEST_F('SyncInternalsWebUITest', 'Uninitialized', function() { - assertNotEquals(null, chrome.sync.aboutInfo); - expectTrue(this.hasInDetails(false, 'Summary', 'Uninitialized')); + assertNotEquals(null, chrome.sync.aboutInfo); }); // Test that username is set correctly when the user is signed in or not. @@ -244,11 +243,13 @@ TEST_F('SyncInternalsWebUITest', 'Uninitialized', function() { GEN('#if defined(OS_CHROMEOS)'); TEST_F('SyncInternalsWebUITest', 'SignedIn', function() { assertNotEquals(null, chrome.sync.aboutInfo); + expectTrue(this.hasInDetails(true, 'Summary', 'Waiting for start request')); expectTrue(this.hasInDetails(true, 'Username', 'stub-user@example.com')); }); GEN('#else'); TEST_F('SyncInternalsWebUITest', 'SignedOut', function() { assertNotEquals(null, chrome.sync.aboutInfo); + expectTrue(this.hasInDetails(true, 'Summary', 'Disabled (Not signed in)')); expectTrue(this.hasInDetails(true, 'Username', '')); }); GEN('#endif // defined(OS_CHROMEOS)'); @@ -267,19 +268,31 @@ TEST_F('SyncInternalsWebUITest', 'LoadPastedAboutInfo', function() { }); TEST_F('SyncInternalsWebUITest', 'NetworkEventsTest', function() { - networkEvent1 = new Event('onProtocolEvent'); + let networkEvent1 = new Event('onProtocolEvent'); networkEvent1.details = NETWORK_EVENT_DETAILS_1; - networkEvent2 = new Event('onProtocolEvent'); + let networkEvent2 = new Event('onProtocolEvent'); networkEvent2.details = NETWORK_EVENT_DETAILS_2; chrome.sync.events.dispatchEvent(networkEvent1); chrome.sync.events.dispatchEvent(networkEvent2); - expectEquals(2, $('traffic-event-container').children.length); + // Make sure that both events arrived. + let eventCount = $('traffic-event-container').children.length; + assertGE(eventCount, 2); + + // Check that the event details are displayed. + let displayedEvent1 = $('traffic-event-container').children[eventCount - 2]; + let displayedEvent2 = $('traffic-event-container').children[eventCount - 1]; + expectTrue( + displayedEvent1.innerHTML.includes(NETWORK_EVENT_DETAILS_1.details)); + expectTrue(displayedEvent1.innerHTML.includes(NETWORK_EVENT_DETAILS_1.type)); + expectTrue( + displayedEvent2.innerHTML.includes(NETWORK_EVENT_DETAILS_2.details)); + expectTrue(displayedEvent2.innerHTML.includes(NETWORK_EVENT_DETAILS_2.type)); // Test that repeated events are not re-displayed. chrome.sync.events.dispatchEvent(networkEvent1); - expectEquals(2, $('traffic-event-container').children.length); + expectEquals(eventCount, $('traffic-event-container').children.length); }); TEST_F('SyncInternalsWebUITest', 'SearchTabDoesntChangeOnItemSelect', @@ -373,14 +386,15 @@ TEST_F('SyncInternalsWebUITest', 'EventLogTest', function() { // Verify that it is displayed in the events log. var syncEventsTable = $('sync-events'); - var firstRow = syncEventsTable.children[0]; + assertGE(syncEventsTable.children.length, 1); + var lastRow = syncEventsTable.children[syncEventsTable.children.length - 1]; // Makes some assumptions about column ordering. We'll need re-think this if // it turns out to be a maintenance burden. - assertEquals(4, firstRow.children.length); - var detailsText = firstRow.children[0].textContent; - var submoduleName = firstRow.children[1].textContent; - var eventName = firstRow.children[2].textContent; + assertEquals(4, lastRow.children.length); + var detailsText = lastRow.children[0].textContent; + var submoduleName = lastRow.children[1].textContent; + var eventName = lastRow.children[2].textContent; expectGE(submoduleName.indexOf('manager'), 0, 'submoduleName=' + submoduleName); diff --git a/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc b/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc index 9bd2b4ab217..49fe3b36d86 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc @@ -132,6 +132,16 @@ void SyncInternalsMessageHandler::RegisterMessages() { base::Unretained(this))); web_ui()->RegisterMessageCallback( + syncer::sync_ui_util::kRequestStart, + base::BindRepeating(&SyncInternalsMessageHandler::HandleRequestStart, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + syncer::sync_ui_util::kRequestStop, + base::BindRepeating(&SyncInternalsMessageHandler::HandleRequestStop, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( syncer::sync_ui_util::kTriggerRefresh, base::BindRepeating(&SyncInternalsMessageHandler::HandleTriggerRefresh, base::Unretained(this))); @@ -263,6 +273,28 @@ void SyncInternalsMessageHandler::HandleWriteUserEvent( user_event_service->RecordUserEvent(event_specifics); } +void SyncInternalsMessageHandler::HandleRequestStart( + const base::ListValue* args) { + DCHECK_EQ(0U, args->GetSize()); + + SyncService* service = GetSyncService(); + if (!service) + return; + + service->RequestStart(); +} + +void SyncInternalsMessageHandler::HandleRequestStop( + const base::ListValue* args) { + DCHECK_EQ(0U, args->GetSize()); + + SyncService* service = GetSyncService(); + if (!service) + return; + + service->RequestStop(SyncService::KEEP_DATA); +} + void SyncInternalsMessageHandler::HandleTriggerRefresh( const base::ListValue* args) { SyncService* service = GetSyncService(); diff --git a/chromium/chrome/browser/ui/webui/sync_internals_message_handler.h b/chromium/chrome/browser/ui/webui/sync_internals_message_handler.h index 336aa635bb5..6d721993633 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_message_handler.h +++ b/chromium/chrome/browser/ui/webui/sync_internals_message_handler.h @@ -68,6 +68,12 @@ class SyncInternalsMessageHandler : public content::WebUIMessageHandler, // Handler for writeUserEvent message. void HandleWriteUserEvent(const base::ListValue* args); + // Handler for requestStart message. + void HandleRequestStart(const base::ListValue* args); + + // Handler for requestStop message. + void HandleRequestStop(const base::ListValue* args); + // Handler for triggerRefresh message. void HandleTriggerRefresh(const base::ListValue* args); diff --git a/chromium/chrome/browser/ui/webui/sync_internals_ui.cc b/chromium/chrome/browser/ui/webui/sync_internals_ui.cc index 1f70e976da7..3c0e0f659b4 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/sync_internals_ui.cc @@ -19,6 +19,8 @@ namespace { content::WebUIDataSource* CreateSyncInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUISyncInternalsHost); + source->OverrideContentSecurityPolicyScriptSrc( + "script-src chrome://resources 'self' 'unsafe-eval';"); source->SetJsonPath("strings.js"); source->AddResourcePath(syncer::sync_ui_util::kSyncIndexJS, diff --git a/chromium/chrome/browser/ui/webui/system_info_ui.cc b/chromium/chrome/browser/ui/webui/system_info_ui.cc index b63bb2e4af6..cde5601016e 100644 --- a/chromium/chrome/browser/ui/webui/system_info_ui.cc +++ b/chromium/chrome/browser/ui/webui/system_info_ui.cc @@ -56,7 +56,7 @@ class SystemInfoUIHTMLSource : public content::URLDataSource{ return "text/html"; } std::string GetContentSecurityPolicyScriptSrc() const override { - // 'unsafe-inline' is added to script-src. + // 'unsafe-eval' and 'unsafe-inline' are added to script-src. return "script-src 'self' chrome://resources 'unsafe-eval' " "'unsafe-inline';"; } diff --git a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc index 366846e0b5d..5525c24d8fc 100644 --- a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc +++ b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc @@ -64,6 +64,10 @@ void TranslateInternalsHandler::RegisterMessages() { base::BindRepeating(&TranslateInternalsHandler::OnRemovePrefItem, base::Unretained(this))); web_ui()->RegisterMessageCallback( + "setRecentTargetLanguage", + base::BindRepeating(&TranslateInternalsHandler::OnSetRecentTargetLanguage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "requestInfo", base::BindRepeating(&TranslateInternalsHandler::OnRequestInfo, base::Unretained(this))); @@ -164,6 +168,24 @@ void TranslateInternalsHandler::OnRemovePrefItem(const base::ListValue* args) { SendPrefsToJs(); } +void TranslateInternalsHandler::OnSetRecentTargetLanguage( + const base::ListValue* args) { + content::WebContents* web_contents = web_ui()->GetWebContents(); + Profile* profile = + Profile::FromBrowserContext(web_contents->GetBrowserContext()); + PrefService* prefs = profile->GetOriginalProfile()->GetPrefs(); + std::unique_ptr<translate::TranslatePrefs> translate_prefs( + ChromeTranslateClient::CreateTranslatePrefs(prefs)); + + std::string new_value; + if (!args->GetString(0, &new_value)) + return; + + translate_prefs->SetRecentTargetLanguage(new_value); + + SendPrefsToJs(); +} + void TranslateInternalsHandler::OnOverrideCountry(const base::ListValue* args) { std::string country; if (args->GetString(0, &country)) { @@ -199,6 +221,7 @@ void TranslateInternalsHandler::SendPrefsToJs() { static const char* keys[] = { prefs::kOfferTranslateEnabled, + translate::TranslatePrefs::kPrefTranslateRecentTarget, translate::TranslatePrefs::kPrefTranslateBlockedLanguages, translate::TranslatePrefs::kPrefTranslateSiteBlacklist, translate::TranslatePrefs::kPrefTranslateWhitelists, diff --git a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.h b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.h index d33e75aa058..5affaa27251 100644 --- a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.h +++ b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.h @@ -59,6 +59,11 @@ class TranslateInternalsHandler : public content::WebUIMessageHandler, // when UI requests to remove an item in the preference. void OnRemovePrefItem(const base::ListValue* args); + // Handles the JavaScript message 'setRecentTargetLanguage'. This message is + // sent when the UI requests to change the 'translate_recent_target' + // preference. + void OnSetRecentTargetLanguage(const base::ListValue* args); + // Handles the Javascript message 'overrideCountry'. This message is sent // when UI requests to override the stored country. void OnOverrideCountry(const base::ListValue* country); diff --git a/chromium/chrome/browser/ui/webui/version_handler_chromeos.h b/chromium/chrome/browser/ui/webui/version_handler_chromeos.h index b924106d79e..e36377fc778 100644 --- a/chromium/chrome/browser/ui/webui/version_handler_chromeos.h +++ b/chromium/chrome/browser/ui/webui/version_handler_chromeos.h @@ -10,7 +10,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/webui/version_handler.h" -#include "chromeos/system/version_loader.h" +#include "chromeos/dbus/util/version_loader.h" // VersionHandlerChromeOS is responsible for loading the Chrome OS // version. diff --git a/chromium/chrome/browser/ui/webui/web_dialog_web_contents_delegate_unittest.cc b/chromium/chrome/browser/ui/webui/web_dialog_web_contents_delegate_unittest.cc index 5d7dea32cf1..c2232cd4b58 100644 --- a/chromium/chrome/browser/ui/webui/web_dialog_web_contents_delegate_unittest.cc +++ b/chromium/chrome/browser/ui/webui/web_dialog_web_contents_delegate_unittest.cc @@ -63,7 +63,6 @@ class WebDialogWebContentsDelegateTest : public BrowserWithTestWindowTest { TEST_F(WebDialogWebContentsDelegateTest, DoNothingMethodsTest) { // None of the following calls should do anything. - EXPECT_TRUE(test_web_contents_delegate_->IsPopupOrPanel(NULL)); history::HistoryAddPageArgs should_add_args( GURL(), base::Time::Now(), 0, 0, GURL(), history::RedirectList(), ui::PAGE_TRANSITION_TYPED, false, history::SOURCE_SYNCED, false, true); @@ -73,7 +72,7 @@ TEST_F(WebDialogWebContentsDelegateTest, DoNothingMethodsTest) { test_web_contents_delegate_->LoadingStateChanged(NULL, true); test_web_contents_delegate_->CloseContents(NULL); test_web_contents_delegate_->UpdateTargetURL(NULL, GURL()); - test_web_contents_delegate_->MoveContents(NULL, gfx::Rect()); + test_web_contents_delegate_->SetContentsBounds(NULL, gfx::Rect()); EXPECT_EQ(0, browser()->tab_strip_model()->count()); EXPECT_EQ(1U, chrome::GetTotalBrowserCount()); } diff --git a/chromium/chrome/browser/ui/webui/webui_util.cc b/chromium/chrome/browser/ui/webui/webui_util.cc new file mode 100644 index 00000000000..654538dde90 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/webui_util.cc @@ -0,0 +1,29 @@ +// 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/webui_util.h" + +#include "base/strings/utf_string_conversions.h" +#include "base/values.h" + +namespace webui { +namespace webui_util { + +void AddPair(base::ListValue* list, + const base::string16& key, + const base::string16& value) { + std::unique_ptr<base::DictionaryValue> results(new base::DictionaryValue()); + results->SetString("key", key); + results->SetString("value", value); + list->Append(std::move(results)); +} + +void AddPair(base::ListValue* list, + const base::string16& key, + const std::string& value) { + AddPair(list, key, base::UTF8ToUTF16(value)); +} + +} // namespace webui_util +} // namespace webui diff --git a/chromium/chrome/browser/ui/webui/webui_util.h b/chromium/chrome/browser/ui/webui/webui_util.h new file mode 100644 index 00000000000..b9d42796ed7 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/webui_util.h @@ -0,0 +1,26 @@ +// 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_WEBUI_UTIL_H_ +#define CHROME_BROWSER_UI_WEBUI_WEBUI_UTIL_H_ + +#include "base/values.h" + +namespace webui { +namespace webui_util { + +// Helper functions for collecting a list of key-value pairs that will +// be displayed. +void AddPair(base::ListValue* list, + const base::string16& key, + const base::string16& value); + +void AddPair(base::ListValue* list, + const base::string16& key, + const std::string& value); + +} // namespace webui_util +} // namespace webui + +#endif // CHROME_BROWSER_UI_WEBUI_WEBUI_UTIL_H_ diff --git a/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc b/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc index ae7ad18801f..ab0af8cfa9b 100644 --- a/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc @@ -143,7 +143,13 @@ IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, DisplayNone) { "testDisplayNone", base::Value(GetTestUrl("empty.html").spec()))); } -IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, ExecuteScriptCode) { +// TODO(crbug.com/861600) Flaky on CrOS trybots. +#if defined(OS_CHROMEOS) && !defined(NDEBUG) +#define MAYBE_ExecuteScriptCode DISABLED_ExecuteScriptCode +#else +#define MAYBE_ExecuteScriptCode ExecuteScriptCode +#endif +IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, MAYBE_ExecuteScriptCode) { ui_test_utils::NavigateToURL(browser(), GetWebViewEnabledWebUIURL()); ASSERT_TRUE(WebUIBrowserTest::RunJavascriptAsyncTest( @@ -203,9 +209,17 @@ IN_PROC_BROWSER_TEST_F( base::Value(GetTestUrl("empty.html").spec()))); } +#if defined(OS_CHROMEOS) && !defined(NDEBUG) +// TODO(crbug.com/859320) Fails on CrOS dbg with --enable-features=Mash. +#define MAYBE_AddContentScriptToOneWebViewShouldNotInjectToTheOtherWebView \ + DISABLED_AddContentScriptToOneWebViewShouldNotInjectToTheOtherWebView +#else +#define MAYBE_AddContentScriptToOneWebViewShouldNotInjectToTheOtherWebView \ + AddContentScriptToOneWebViewShouldNotInjectToTheOtherWebView +#endif IN_PROC_BROWSER_TEST_F( WebUIWebViewBrowserTest, - AddContentScriptToOneWebViewShouldNotInjectToTheOtherWebView) { + MAYBE_AddContentScriptToOneWebViewShouldNotInjectToTheOtherWebView) { ui_test_utils::NavigateToURL(browser(), GetWebViewEnabledWebUIURL()); ASSERT_TRUE(WebUIBrowserTest::RunJavascriptAsyncTest( @@ -228,8 +242,16 @@ IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, base::Value(GetTestUrl("empty.html").spec()))); } +#if defined(OS_CHROMEOS) && !defined(NDEBUG) +// TODO(crbug.com/859320) Fails on CrOS dbg with --enable-features=Mash. +#define MAYBE_AddContentScriptsWithNewWindowAPI \ + DISABLED_AddContentScriptsWithNewWindowAPI +#else +#define MAYBE_AddContentScriptsWithNewWindowAPI \ + AddContentScriptsWithNewWindowAPI +#endif IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, - AddContentScriptsWithNewWindowAPI) { + MAYBE_AddContentScriptsWithNewWindowAPI) { ui_test_utils::NavigateToURL(browser(), GetWebViewEnabledWebUIURL()); ASSERT_TRUE(WebUIBrowserTest::RunJavascriptAsyncTest( diff --git a/chromium/chrome/browser/ui/webui/welcome_handler.cc b/chromium/chrome/browser/ui/webui/welcome_handler.cc index cf7b8341c07..b092abfbbf9 100644 --- a/chromium/chrome/browser/ui/webui/welcome_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome_handler.cc @@ -7,15 +7,15 @@ #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/profile_chooser_constants.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/url_constants.h" -#include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_metrics.h" +#include "services/identity/public/cpp/identity_manager.h" #include "ui/base/page_transition_types.h" WelcomeHandler::WelcomeHandler(content::WebUI* web_ui) @@ -53,7 +53,7 @@ void WelcomeHandler::HandleActivateSignIn(const base::ListValue* args) { result_ = WelcomeResult::ATTEMPTED; base::RecordAction(base::UserMetricsAction("WelcomePage_SignInClicked")); - if (SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated()) { + if (IdentityManagerFactory::GetForProfile(profile_)->HasPrimaryAccount()) { // In general, this page isn't shown to signed-in users; however, if one // should arrive here, then opening the sign-in dialog will likely lead // to a crash. Thus, we just act like sign-in was "successful" and whisk diff --git a/chromium/chrome/browser/ui/webui/welcome_ui.cc b/chromium/chrome/browser/ui/webui/welcome_ui.cc index 16af7154fea..4bcca49cb97 100644 --- a/chromium/chrome/browser/ui/webui/welcome_ui.cc +++ b/chromium/chrome/browser/ui/webui/welcome_ui.cc @@ -5,8 +5,11 @@ #include "chrome/browser/ui/webui/welcome_ui.h" #include <memory> +#include <string> -#include "chrome/browser/profiles/profile.h" +#include "build/build_config.h" +#include "chrome/browser/favicon/favicon_service_factory.h" +#include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/ui/webui/welcome_handler.h" #include "chrome/common/pref_names.h" #include "chrome/grit/browser_resources.h" @@ -14,11 +17,20 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/profile_management_switches.h" +#include "components/sync/driver/sync_service.h" #include "content/public/browser/web_ui_data_source.h" #include "net/base/url_util.h" #include "ui/base/l10n/l10n_util.h" +#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#include "base/metrics/histogram_macros.h" +#include "chrome/browser/bookmarks/bookmark_model_factory.h" +#include "components/nux/show_promo_delegate.h" +#include "components/nux_google_apps/constants.h" +#include "components/nux_google_apps/google_apps_handler.h" +#include "content/public/browser/web_contents.h" +#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) + namespace { const bool kIsBranded = #if defined(GOOGLE_CHROME_BUILD) @@ -39,15 +51,15 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) return; } - // Store that this profile has been shown the Welcome page. - profile->GetPrefs()->SetBoolean(prefs::kHasSeenWelcomePage, true); + StorePageSeen(profile, url); web_ui->AddMessageHandler(std::make_unique<WelcomeHandler>(web_ui)); content::WebUIDataSource* html_source = content::WebUIDataSource::Create(url.host()); - bool is_dice = signin::IsDiceEnabledForProfile(profile->GetPrefs()); + bool is_dice = + AccountConsistencyModeManager::IsDiceEnabledForProfile(profile); // There are multiple possible configurations that affects the layout, but // first add resources that are shared across all layouts. @@ -98,7 +110,41 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) html_source->SetDefaultResource(IDR_WELCOME_HTML); } +#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) + if (base::FeatureList::IsEnabled(nux_google_apps::kNuxGoogleAppsFeature)) { + content::BrowserContext* browser_context = + web_ui->GetWebContents()->GetBrowserContext(); + web_ui->AddMessageHandler( + std::make_unique<nux_google_apps::GoogleAppsHandler>( + profile->GetPrefs(), + FaviconServiceFactory::GetForProfile( + profile, ServiceAccessType::EXPLICIT_ACCESS), + BookmarkModelFactory::GetForBrowserContext(browser_context))); + + nux_google_apps::GoogleAppsHandler::AddSources(html_source); + } +#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD + content::WebUIDataSource::Add(profile, html_source); } WelcomeUI::~WelcomeUI() {} + +void WelcomeUI::StorePageSeen(Profile* profile, const GURL& url) { +#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) + if (url.EqualsIgnoringRef(GURL(nux_google_apps::kNuxGoogleAppsUrl))) { + // Record that the new user experience page was visited. + profile->GetPrefs()->SetBoolean(prefs::kHasSeenGoogleAppsPromoPage, true); + + // Record UMA. + UMA_HISTOGRAM_ENUMERATION( + nux_google_apps::kGoogleAppsInteractionHistogram, + nux_google_apps::GoogleAppsInteraction::kPromptShown, + nux_google_apps::GoogleAppsInteraction::kCount); + return; + } +#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) + + // Store that this profile has been shown the Welcome page. + profile->GetPrefs()->SetBoolean(prefs::kHasSeenWelcomePage, true); +} diff --git a/chromium/chrome/browser/ui/webui/welcome_ui.h b/chromium/chrome/browser/ui/webui/welcome_ui.h index 4548d4d1697..7ff85eb9d42 100644 --- a/chromium/chrome/browser/ui/webui/welcome_ui.h +++ b/chromium/chrome/browser/ui/webui/welcome_ui.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_UI_H_ #define CHROME_BROWSER_UI_WEBUI_WELCOME_UI_H_ +#include "chrome/browser/profiles/profile.h" #include "content/public/browser/web_ui_controller.h" #include "url/gurl.h" @@ -16,6 +17,9 @@ class WelcomeUI : public content::WebUIController { public: WelcomeUI(content::WebUI* web_ui, const GURL& url); ~WelcomeUI() override; + + private: + void StorePageSeen(Profile* profile, const GURL& url); }; #endif // CHROME_BROWSER_UI_WEBUI_WELCOME_UI_H_ |