diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2019-02-13 15:05:36 +0100 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2019-02-14 10:33:47 +0000 |
commit | e684a3455bcc29a6e3e66a004e352dea4e1141e7 (patch) | |
tree | d55b4003bde34d7d05f558f02cfd82b2a66a7aac /chromium/chrome/browser/ui | |
parent | 2b94bfe47ccb6c08047959d1c26e392919550e86 (diff) | |
download | qtwebengine-chromium-e684a3455bcc29a6e3e66a004e352dea4e1141e7.tar.gz |
BASELINE: Update Chromium to 72.0.3626.110 and Ninja to 1.9.0
Change-Id: Ic57220b00ecc929a893c91f5cc552f5d3e99e922
Reviewed-by: Michael BrĂ¼ning <michael.bruning@qt.io>
Diffstat (limited to 'chromium/chrome/browser/ui')
207 files changed, 3818 insertions, 4351 deletions
diff --git a/chromium/chrome/browser/ui/BUILD.gn b/chromium/chrome/browser/ui/BUILD.gn index 40fc10af525..c57b1a02a1f 100644 --- a/chromium/chrome/browser/ui/BUILD.gn +++ b/chromium/chrome/browser/ui/BUILD.gn @@ -22,7 +22,7 @@ import("//ui/base/ui_features.gni") import("//ui/views/features.gni") config("ui_warnings") { - if (is_clang) { + if (is_mac) { # TODO(thakis): Remove this once http://crbug.com/383820 is figured out cflags = [ "-Wno-nonnull" ] } @@ -77,6 +77,8 @@ jumbo_split_static_library("ui") { "blocked_content/blocked_window_params.h", "blocked_content/list_item_position.cc", "blocked_content/list_item_position.h", + "blocked_content/popup_blocker.cc", + "blocked_content/popup_blocker.h", "blocked_content/popup_blocker_tab_helper.cc", "blocked_content/popup_blocker_tab_helper.h", "blocked_content/popup_opener_tab_helper.cc", @@ -89,8 +91,9 @@ jumbo_split_static_library("ui") { "blocked_content/scoped_visibility_tracker.h", "blocked_content/tab_under_navigation_throttle.cc", "blocked_content/tab_under_navigation_throttle.h", + "blocked_content/url_list_manager.cc", + "blocked_content/url_list_manager.h", "bookmarks/bookmark_bar.h", - "bookmarks/bookmark_bar_instructions_delegate.h", "bookmarks/bookmark_bubble_observer.h", "bookmarks/bookmark_editor.cc", "bookmarks/bookmark_editor.h", @@ -117,7 +120,6 @@ jumbo_split_static_library("ui") { "find_bar/find_notification_details.h", "find_bar/find_tab_helper.cc", "find_bar/find_tab_helper.h", - "forced_reauthentication_dialog.h", "interventions/framebust_block_message_delegate.cc", "interventions/framebust_block_message_delegate.h", "interventions/intervention_delegate.h", @@ -204,8 +206,8 @@ jumbo_split_static_library("ui") { "tab_modal_confirm_dialog.h", "tab_ui_helper.cc", "tab_ui_helper.h", - "toolbar/chrome_toolbar_model_delegate.cc", - "toolbar/chrome_toolbar_model_delegate.h", + "toolbar/chrome_location_bar_model_delegate.cc", + "toolbar/chrome_location_bar_model_delegate.h", "translate/language_combobox_model.cc", "translate/language_combobox_model.h", "translate/translate_bubble_model.h", @@ -376,6 +378,7 @@ jumbo_split_static_library("ui") { "//chrome/app/resources:platform_locale_settings", "//chrome/app/theme:chrome_unscaled_resources", "//chrome/app/theme:theme_resources", + "//chrome/app/vector_icons", "//chrome/browser:resource_prefetch_predictor_proto", "//chrome/browser/devtools", "//chrome/browser/engagement:mojo_bindings", @@ -383,6 +386,7 @@ jumbo_split_static_library("ui") { "//chrome/browser/profiling_host", "//chrome/browser/safe_browsing", "//chrome/browser/ssl:proto", + "//chrome/browser/ui/webui/app_management:mojo_bindings", "//chrome/browser/ui/webui/bluetooth_internals", "//chrome/browser/ui/webui/interventions_internals:mojo_bindings", "//chrome/browser/ui/webui/omnibox:mojo_bindings", @@ -438,6 +442,7 @@ jumbo_split_static_library("ui") { "//components/ntp_tiles", "//components/offline_pages/buildflags", "//components/omnibox/browser", + "//components/omnibox/browser:vector_icons", "//components/onc", "//components/password_manager/content/browser", "//components/password_manager/core/browser", @@ -477,8 +482,6 @@ jumbo_split_static_library("ui") { "//components/sync", "//components/sync_preferences", "//components/sync_sessions", - "//components/toolbar", - "//components/toolbar:vector_icons", "//components/tracing:startup_tracing", "//components/ui_devtools", "//components/ukm:ukm", @@ -589,6 +592,8 @@ jumbo_split_static_library("ui") { "android/autofill/autofill_logger_android.h", "android/autofill/autofill_popup_view_android.cc", "android/autofill/autofill_popup_view_android.h", + "android/autofill/card_name_fix_flow_view_android.cc", + "android/autofill/card_name_fix_flow_view_android.h", "android/autofill/card_unmask_prompt_view_android.cc", "android/autofill/card_unmask_prompt_view_android.h", "android/autofill/credit_card_scanner_view_android.cc", @@ -697,8 +702,8 @@ jumbo_split_static_library("ui") { "android/tab_model/tab_model_observer.h", "android/tab_model/tab_model_observer_jni_bridge.cc", "android/tab_model/tab_model_observer_jni_bridge.h", - "android/toolbar/toolbar_model_android.cc", - "android/toolbar/toolbar_model_android.h", + "android/toolbar/location_bar_model_android.cc", + "android/toolbar/location_bar_model_android.h", "android/usb_chooser_dialog_android.cc", "android/usb_chooser_dialog_android.h", "android/view_android_helper.cc", @@ -786,6 +791,8 @@ jumbo_split_static_library("ui") { "browser_list_observer.h", "browser_live_tab_context.cc", "browser_live_tab_context.h", + "browser_location_bar_model_delegate.cc", + "browser_location_bar_model_delegate.h", "browser_navigator.cc", "browser_navigator.h", "browser_otr_state.cc", @@ -800,8 +807,6 @@ jumbo_split_static_library("ui") { "browser_tabrestore.h", "browser_tabstrip.cc", "browser_tabstrip.h", - "browser_toolbar_model_delegate.cc", - "browser_toolbar_model_delegate.h", "browser_view_prefs.cc", "browser_view_prefs.h", "browser_window.h", @@ -822,6 +827,8 @@ jumbo_split_static_library("ui") { "content_settings/content_setting_bubble_model_delegate.h", "content_settings/content_setting_image_model.cc", "content_settings/content_setting_image_model.h", + "content_settings/content_setting_image_model_states.cc", + "content_settings/content_setting_image_model_states.h", "exclusive_access/exclusive_access_bubble.cc", "exclusive_access/exclusive_access_bubble.h", "exclusive_access/exclusive_access_bubble_hide_callback.h", @@ -869,6 +876,8 @@ jumbo_split_static_library("ui") { "layout_constants.h", "location_bar/location_bar.cc", "location_bar/location_bar.h", + "managed_ui.cc", + "managed_ui.h", "media_router/cast_dialog_controller.h", "media_router/cast_dialog_model.cc", "media_router/cast_dialog_model.h", @@ -1054,6 +1063,10 @@ jumbo_split_static_library("ui") { "unload_controller.h", "webui/app_launcher_login_handler.cc", "webui/app_launcher_login_handler.h", + "webui/app_management/app_management_page_handler.cc", + "webui/app_management/app_management_page_handler.h", + "webui/app_management/app_management_ui.cc", + "webui/app_management/app_management_ui.h", "webui/browsing_history_handler.cc", "webui/browsing_history_handler.h", "webui/chrome_web_contents_handler.cc", @@ -1168,8 +1181,6 @@ jumbo_split_static_library("ui") { "webui/settings/protocol_handlers_handler.h", "webui/settings/reset_settings_handler.cc", "webui/settings/reset_settings_handler.h", - "webui/settings/safe_browsing_handler.cc", - "webui/settings/safe_browsing_handler.h", "webui/settings/search_engines_handler.cc", "webui/settings/search_engines_handler.h", "webui/settings/settings_clear_browsing_data_handler.cc", @@ -1222,18 +1233,18 @@ jumbo_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", "//chrome/browser/resource_coordinator/tab_ranker", "//chrome/common:buildflags", "//chrome/common:search_mojom", + "//chrome/services/app_service/public/mojom", "//components/feedback/proto", "//components/keep_alive_registry", "//components/network_session_configurator/common", "//components/ui_metrics", - "//components/vector_icons", + "//components/url_formatter", "//components/vector_icons", "//components/web_modal", "//components/zoom", @@ -1258,8 +1269,13 @@ jumbo_split_static_library("ui") { if (enable_extensions) { deps += [ + "//chrome/browser/web_applications", + + # TODO(loyso): Erase these. crbug.com/877898. + "//chrome/browser/web_applications:web_applications_on_extensions", "//chrome/browser/web_applications/components", "//chrome/browser/web_applications/extensions", + "//google_apis/drive", ] } } @@ -1303,6 +1319,8 @@ jumbo_split_static_library("ui") { "ash/chrome_accessibility_delegate.h", "ash/chrome_browser_main_extra_parts_ash.cc", "ash/chrome_browser_main_extra_parts_ash.h", + "ash/chrome_keyboard_bounds_observer.cc", + "ash/chrome_keyboard_bounds_observer.h", "ash/chrome_keyboard_controller_client.cc", "ash/chrome_keyboard_controller_client.h", "ash/chrome_keyboard_ui.cc", @@ -1318,6 +1336,8 @@ jumbo_split_static_library("ui") { "ash/chrome_screenshot_grabber_test_observer.h", "ash/chrome_shell_delegate.cc", "ash/chrome_shell_delegate.h", + "ash/contained_shell_client.cc", + "ash/contained_shell_client.h", "ash/ime_controller_client.cc", "ash/ime_controller_client.h", "ash/ksv/keyboard_shortcut_viewer_util.cc", @@ -1374,8 +1394,6 @@ jumbo_split_static_library("ui") { "ash/multi_user/multi_user_window_manager_chromeos.h", "ash/multi_user/multi_user_window_manager_stub.cc", "ash/multi_user/multi_user_window_manager_stub.h", - "ash/multi_user/user_switch_animator_chromeos.cc", - "ash/multi_user/user_switch_animator_chromeos.h", "ash/network/data_promo_notification.cc", "ash/network/data_promo_notification.h", "ash/network/enrollment_dialog_view.cc", @@ -1438,10 +1456,6 @@ jumbo_split_static_library("ui") { "views/frame/browser_non_client_frame_view_ash.h", "views/frame/immersive_context_mus.cc", "views/frame/immersive_context_mus.h", - "views/frame/immersive_focus_watcher_mus.cc", - "views/frame/immersive_focus_watcher_mus.h", - "views/frame/immersive_handler_factory_mus.cc", - "views/frame/immersive_handler_factory_mus.h", "views/frame/immersive_mode_controller_ash.cc", "views/frame/immersive_mode_controller_ash.h", "views/frame/native_browser_frame_factory_chromeos.cc", @@ -1463,6 +1477,10 @@ jumbo_split_static_library("ui") { "views/select_file_dialog_extension.h", "views/select_file_dialog_extension_factory.cc", "views/select_file_dialog_extension_factory.h", + "views/touch_selection_menu_chromeos.cc", + "views/touch_selection_menu_chromeos.h", + "views/touch_selection_menu_runner_chromeos.cc", + "views/touch_selection_menu_runner_chromeos.h", "webui/chromeos/assistant_optin/assistant_optin_ui.cc", "webui/chromeos/assistant_optin/assistant_optin_ui.h", "webui/chromeos/assistant_optin/assistant_optin_utils.cc", @@ -1491,8 +1509,6 @@ jumbo_split_static_library("ui") { "webui/chromeos/internet_config_dialog.h", "webui/chromeos/internet_detail_dialog.cc", "webui/chromeos/internet_detail_dialog.h", - "webui/chromeos/keyboard_overlay_ui.cc", - "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", @@ -1635,6 +1651,12 @@ jumbo_split_static_library("ui") { "webui/chromeos/slow_trace_ui.h", "webui/chromeos/slow_ui.cc", "webui/chromeos/slow_ui.h", + "webui/chromeos/smb_shares/smb_handler.cc", + "webui/chromeos/smb_shares/smb_handler.h", + "webui/chromeos/smb_shares/smb_share_dialog.cc", + "webui/chromeos/smb_shares/smb_share_dialog.h", + "webui/chromeos/smb_shares/smb_shares_localized_strings_provider.cc", + "webui/chromeos/smb_shares/smb_shares_localized_strings_provider.h", "webui/chromeos/sys_internals/sys_internals_message_handler.cc", "webui/chromeos/sys_internals/sys_internals_message_handler.h", "webui/chromeos/sys_internals/sys_internals_ui.cc", @@ -1675,8 +1697,6 @@ jumbo_split_static_library("ui") { "webui/settings/chromeos/device_storage_handler.h", "webui/settings/chromeos/device_stylus_handler.cc", "webui/settings/chromeos/device_stylus_handler.h", - "webui/settings/chromeos/easy_unlock_settings_handler.cc", - "webui/settings/chromeos/easy_unlock_settings_handler.h", "webui/settings/chromeos/fingerprint_handler.cc", "webui/settings/chromeos/fingerprint_handler.h", "webui/settings/chromeos/google_assistant_handler.cc", @@ -1685,8 +1705,6 @@ jumbo_split_static_library("ui") { "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", @@ -1699,7 +1717,6 @@ jumbo_split_static_library("ui") { ] deps += [ "//ash", - "//ash:ash_with_content", "//ash/components/shortcut_viewer:lib", "//ash/components/shortcut_viewer/public/mojom", "//ash/public/cpp", @@ -1713,6 +1730,7 @@ jumbo_split_static_library("ui") { "//chromeos/components/proximity_auth/webui", "//chromeos/components/tether", "//chromeos/resources:resources_grit", + "//chromeos/services/assistant/public:feature_flags", "//chromeos/services/assistant/public/mojom", "//chromeos/services/assistant/public/proto:proto", "//chromeos/services/multidevice_setup/public/cpp:cpp", @@ -1729,6 +1747,7 @@ jumbo_split_static_library("ui") { "//components/login", "//components/session_manager/core", "//components/user_manager", + "//google_apis/drive", "//services/data_decoder/public/cpp", "//services/device/public/cpp:device_features", "//services/device/public/mojom", @@ -1769,6 +1788,8 @@ jumbo_split_static_library("ui") { "views/close_bubble_on_tab_activation_helper.h", "views/hats/hats_bubble_view.cc", "views/hats/hats_bubble_view.h", + "views/profiles/incognito_window_count_view.cc", + "views/profiles/incognito_window_count_view.h", "webui/discards/discards_ui.cc", "webui/discards/discards_ui.h", "webui/signin/inline_login_handler.cc", @@ -1801,6 +1822,8 @@ jumbo_split_static_library("ui") { "user_manager.h", "views/external_protocol_dialog.cc", "views/external_protocol_dialog.h", + "views/message_center/popups_only_ui_delegate.cc", + "views/message_center/popups_only_ui_delegate.h", "views/profiles/badged_profile_photo.cc", "views/profiles/badged_profile_photo.h", "views/profiles/dice_accounts_menu.cc", @@ -1843,12 +1866,18 @@ jumbo_split_static_library("ui") { "webui/signin/sync_confirmation_ui.h", "webui/signin/user_manager_screen_handler.cc", "webui/signin/user_manager_screen_handler.h", - - # TODO(scottchen): nux/set_as_default_handler is here because it depends - # on settings_default_browser_handler, but that deps currently can't - # be added in nux/BUILD.gn due to circular dependency. - # Should move back to nux/BUILD.gn once settings's build config is in - # a shareable location (e.g. ui/webui/settings/BUILD.gn). + "webui/welcome/nux/bookmark_handler.cc", + "webui/welcome/nux/bookmark_handler.h", + "webui/welcome/nux/bookmark_item.cc", + "webui/welcome/nux/bookmark_item.h", + "webui/welcome/nux/constants.cc", + "webui/welcome/nux/constants.h", + "webui/welcome/nux/email_handler.cc", + "webui/welcome/nux/email_handler.h", + "webui/welcome/nux/email_providers_list.cc", + "webui/welcome/nux/email_providers_list.h", + "webui/welcome/nux/google_apps_handler.cc", + "webui/welcome/nux/google_apps_handler.h", "webui/welcome/nux/set_as_default_handler.cc", "webui/welcome/nux/set_as_default_handler.h", "webui/welcome/nux_helper.cc", @@ -1859,15 +1888,7 @@ jumbo_split_static_library("ui") { "webui/welcome/welcome_ui.h", ] - # TODO(scottchen): Remove if-check once nux files are non-exclusive - # to windows. - if (is_win && is_chrome_branded) { - deps += [ - "//chrome/browser/ui/webui/welcome/nux:constants", - "//chrome/browser/ui/webui/welcome/nux:email_feature", - "//chrome/browser/ui/webui/welcome/nux:google_apps_feature", - ] - } + deps += [ "//components/country_codes" ] if (enable_dice_support) { sources += [ @@ -1914,12 +1935,10 @@ jumbo_split_static_library("ui") { if (is_mac) { sources += [ - "browser_commands_mac.cc", "browser_commands_mac.h", + "browser_commands_mac.mm", "browser_mac.cc", "browser_mac.h", - "certificate_viewer_mac.h", - "certificate_viewer_mac.mm", "cocoa/accelerator_utils_cocoa.mm", "cocoa/accelerators_cocoa.h", "cocoa/accelerators_cocoa.mm", @@ -1957,8 +1976,6 @@ jumbo_split_static_library("ui") { "cocoa/bookmarks/bookmark_menu_cocoa_controller.mm", "cocoa/browser_window_command_handler.h", "cocoa/browser_window_command_handler.mm", - "cocoa/certificate_viewer_mac_cocoa.h", - "cocoa/certificate_viewer_mac_cocoa.mm", "cocoa/chrome_command_dispatcher_delegate.h", "cocoa/chrome_command_dispatcher_delegate.mm", "cocoa/color_chooser_mac.h", @@ -1967,23 +1984,8 @@ jumbo_split_static_library("ui") { "cocoa/confirm_quit.h", "cocoa/confirm_quit_panel_controller.h", "cocoa/confirm_quit_panel_controller.mm", - "cocoa/constrained_window/constrained_window_control_utils.h", - "cocoa/constrained_window/constrained_window_control_utils.mm", - "cocoa/constrained_window/constrained_window_custom_sheet.h", - "cocoa/constrained_window/constrained_window_custom_sheet.mm", - "cocoa/constrained_window/constrained_window_mac.h", - "cocoa/constrained_window/constrained_window_mac.mm", - "cocoa/constrained_window/constrained_window_sheet.h", - "cocoa/constrained_window/constrained_window_sheet_controller.h", - "cocoa/constrained_window/constrained_window_sheet_controller.mm", - "cocoa/constrained_window/constrained_window_sheet_info.h", - "cocoa/constrained_window/constrained_window_sheet_info.mm", - "cocoa/constrained_window/constrained_window_web_dialog_sheet.h", - "cocoa/constrained_window/constrained_window_web_dialog_sheet.mm", "cocoa/dock_icon.h", "cocoa/dock_icon.mm", - "cocoa/drag_util.h", - "cocoa/drag_util.mm", "cocoa/first_run_dialog.h", "cocoa/first_run_dialog.mm", "cocoa/first_run_dialog_controller.h", @@ -2036,8 +2038,6 @@ jumbo_split_static_library("ui") { "cocoa/media_picker/desktop_media_picker_item.mm", "cocoa/native_window_tracker_cocoa.h", "cocoa/native_window_tracker_cocoa.mm", - "cocoa/notifications/message_center_bridge.h", - "cocoa/notifications/message_center_bridge.mm", "cocoa/nsmenuitem_additions.h", "cocoa/nsmenuitem_additions.mm", "cocoa/profiles/profile_menu_controller.h", @@ -2046,20 +2046,12 @@ jumbo_split_static_library("ui") { "cocoa/renderer_context_menu/render_view_context_menu_mac.mm", "cocoa/renderer_context_menu/render_view_context_menu_mac_cocoa.h", "cocoa/renderer_context_menu/render_view_context_menu_mac_cocoa.mm", - "cocoa/renderer_context_menu/render_view_context_menu_mac_views.h", - "cocoa/renderer_context_menu/render_view_context_menu_mac_views.mm", - "cocoa/restart_browser.h", - "cocoa/restart_browser.mm", "cocoa/scoped_menu_bar_lock.h", "cocoa/scoped_menu_bar_lock.mm", "cocoa/share_menu_controller.h", "cocoa/share_menu_controller.mm", "cocoa/simple_message_box_cocoa.h", "cocoa/simple_message_box_cocoa.mm", - "cocoa/single_web_contents_dialog_manager_cocoa.h", - "cocoa/single_web_contents_dialog_manager_cocoa.mm", - "cocoa/ssl_client_certificate_selector_cocoa.h", - "cocoa/ssl_client_certificate_selector_cocoa.mm", "cocoa/status_icons/status_icon_mac.h", "cocoa/status_icons/status_icon_mac.mm", "cocoa/status_icons/status_tray_mac.h", @@ -2076,16 +2068,10 @@ jumbo_split_static_library("ui") { "cocoa/touchbar/browser_window_touch_bar_controller.mm", "cocoa/touchbar/credit_card_autofill_touch_bar_controller.h", "cocoa/touchbar/credit_card_autofill_touch_bar_controller.mm", - "cocoa/touchbar/text_suggestions_touch_bar_controller.h", - "cocoa/touchbar/text_suggestions_touch_bar_controller.mm", "cocoa/touchbar/web_textfield_touch_bar_controller.h", "cocoa/touchbar/web_textfield_touch_bar_controller.mm", "cocoa/ui_localizer.h", "cocoa/ui_localizer.mm", - "cocoa/url_drop_target.h", - "cocoa/url_drop_target.mm", - "cocoa/web_contents_modal_dialog_host_cocoa.h", - "cocoa/web_contents_modal_dialog_host_cocoa.mm", "cocoa/window_size_autosaver.h", "cocoa/window_size_autosaver.mm", "views/apps/chrome_app_window_client_views_mac.mm", @@ -2093,8 +2079,6 @@ jumbo_split_static_library("ui") { "views/dropdown_bar_host_mac.mm", "views/frame/browser_frame_mac.h", "views/frame/browser_frame_mac.mm", - "views/frame/browser_native_widget_window_mac.h", - "views/frame/browser_native_widget_window_mac.mm", "views/frame/browser_non_client_frame_view_factory_mac.mm", "views/frame/browser_non_client_frame_view_mac.h", "views/frame/browser_non_client_frame_view_mac.mm", @@ -2131,19 +2115,12 @@ jumbo_split_static_library("ui") { if (is_win) { assert(toolkit_views) sources += [ - "desktop_ios_promotion/desktop_ios_promotion_bubble_controller.cc", - "desktop_ios_promotion/desktop_ios_promotion_bubble_controller.h", - "desktop_ios_promotion/desktop_ios_promotion_controller.cc", - "desktop_ios_promotion/desktop_ios_promotion_controller.h", - "desktop_ios_promotion/desktop_ios_promotion_util.cc", - "desktop_ios_promotion/desktop_ios_promotion_util.h", - "desktop_ios_promotion/desktop_ios_promotion_view.h", - "desktop_ios_promotion/sms_service.cc", - "desktop_ios_promotion/sms_service.h", - "desktop_ios_promotion/sms_service_factory.cc", - "desktop_ios_promotion/sms_service_factory.h", "network_profile_bubble.cc", "network_profile_bubble.h", + "startup/credential_provider_signin_dialog_win.cc", + "startup/credential_provider_signin_dialog_win.h", + "startup/credential_provider_signin_info_fetcher_win.cc", + "startup/credential_provider_signin_info_fetcher_win.h", "startup/default_browser_prompt_win.cc", "views/certificate_viewer_win.cc", "views/chrome_cleaner_dialog_win.cc", @@ -2155,10 +2132,6 @@ jumbo_split_static_library("ui") { "views/color_chooser_win.cc", "views/critical_notification_bubble_view.cc", "views/critical_notification_bubble_view.h", - "views/desktop_ios_promotion/desktop_ios_promotion_bubble_view.cc", - "views/desktop_ios_promotion/desktop_ios_promotion_bubble_view.h", - "views/desktop_ios_promotion/desktop_ios_promotion_footnote_view.cc", - "views/desktop_ios_promotion/desktop_ios_promotion_footnote_view.h", "views/frame/browser_desktop_window_tree_host.h", "views/frame/browser_desktop_window_tree_host_win.cc", "views/frame/browser_desktop_window_tree_host_win.h", @@ -2210,6 +2183,7 @@ jumbo_split_static_library("ui") { "//ui/views/controls/webview", ] deps += [ + "//chrome/credential_provider/common:common_constants", "//components/search_engines", "//third_party/iaccessible2", "//third_party/isimpledom", @@ -2331,17 +2305,19 @@ jumbo_split_static_library("ui") { "autofill/local_card_migration_bubble.h", "autofill/local_card_migration_bubble_controller_impl.cc", "autofill/local_card_migration_bubble_controller_impl.h", + "autofill/local_card_migration_controller_observer.h", "autofill/local_card_migration_dialog.h", "autofill/local_card_migration_dialog_controller_impl.cc", "autofill/local_card_migration_dialog_controller_impl.h", "autofill/local_card_migration_dialog_factory.h", "autofill/local_card_migration_dialog_state.h", + "autofill/manage_migration_ui_controller.cc", + "autofill/manage_migration_ui_controller.h", "autofill/save_card_bubble_controller_impl.cc", "autofill/save_card_bubble_controller_impl.h", "autofill/save_card_bubble_view.h", "autofill/save_card_ui.h", "bubble_anchor_util.h", - "desktop_ios_promotion/desktop_ios_promotion_footnote_delegate.h", # This test header is included because it contains forward declarations # needed for "friend" statements for use in tests. @@ -2378,6 +2354,8 @@ jumbo_split_static_library("ui") { "views/autofill/local_card_migration_bubble_views.h", "views/autofill/local_card_migration_dialog_view.cc", "views/autofill/local_card_migration_dialog_view.h", + "views/autofill/local_card_migration_error_dialog_view.cc", + "views/autofill/local_card_migration_error_dialog_view.h", "views/autofill/local_card_migration_icon_view.cc", "views/autofill/local_card_migration_icon_view.h", "views/autofill/migratable_card_view.cc", @@ -2394,8 +2372,6 @@ jumbo_split_static_library("ui") { "views/autofill/save_card_sign_in_promo_bubble_views.h", "views/autofill/view_util.cc", "views/autofill/view_util.h", - "views/bookmarks/bookmark_bar_instructions_view.cc", - "views/bookmarks/bookmark_bar_instructions_view.h", "views/bookmarks/bookmark_bar_view.cc", "views/bookmarks/bookmark_bar_view.h", "views/bookmarks/bookmark_bar_view_observer.h", @@ -2477,14 +2453,8 @@ jumbo_split_static_library("ui") { "views/extensions/pwa_confirmation_view.h", "views/extensions/web_app_info_image_source.cc", "views/extensions/web_app_info_image_source.h", - "views/feature_promos/bookmark_promo_bubble_view.cc", - "views/feature_promos/bookmark_promo_bubble_view.h", "views/feature_promos/feature_promo_bubble_view.cc", "views/feature_promos/feature_promo_bubble_view.h", - "views/feature_promos/incognito_window_promo_bubble_view.cc", - "views/feature_promos/incognito_window_promo_bubble_view.h", - "views/feature_promos/new_tab_promo_bubble_view.cc", - "views/feature_promos/new_tab_promo_bubble_view.h", "views/find_bar_host.cc", "views/find_bar_host.h", "views/find_bar_view.cc", @@ -2590,6 +2560,8 @@ jumbo_split_static_library("ui") { "views/login_view.h", "views/material_refresh_layout_provider.cc", "views/material_refresh_layout_provider.h", + "views/md_text_button_with_down_arrow.cc", + "views/md_text_button_with_down_arrow.h", "views/media_router/cast_dialog_helper.cc", "views/media_router/cast_dialog_helper.h", "views/media_router/cast_dialog_metrics.cc", @@ -2637,6 +2609,8 @@ jumbo_split_static_library("ui") { "views/overlay/control_image_button.h", "views/overlay/overlay_window_views.cc", "views/overlay/overlay_window_views.h", + "views/overlay/playback_image_button.cc", + "views/overlay/playback_image_button.h", "views/overlay/resize_handle_button.cc", "views/overlay/resize_handle_button.h", "views/page_action/page_action_icon_container_view.cc", @@ -2750,8 +2724,6 @@ jumbo_split_static_library("ui") { "views/session_crashed_bubble_view.h", "views/simple_message_box_views.cc", "views/simple_message_box_views.h", - "views/ssl_client_certificate_selector.cc", - "views/ssl_client_certificate_selector.h", "views/status_bubble_views.cc", "views/status_bubble_views.h", "views/subtle_notification_view.cc", @@ -2833,25 +2805,36 @@ jumbo_split_static_library("ui") { "views/translate/translate_icon_view.h", "views/update_recommended_message_box.cc", "views/update_recommended_message_box.h", + "views/webauthn/authenticator_ble_pin_entry_sheet_view.cc", + "views/webauthn/authenticator_ble_pin_entry_sheet_view.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/ble_device_selection_sheet_view.cc", + "views/webauthn/ble_device_selection_sheet_view.h", + "views/webauthn/ble_pin_entry_view.cc", + "views/webauthn/ble_pin_entry_view.h", + "views/webauthn/hover_list_view.cc", + "views/webauthn/hover_list_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", "views/webshare/webshare_target_picker_view.cc", "views/webshare/webshare_target_picker_view.h", "views_mode_controller.cc", "views_mode_controller.h", "webauthn/authenticator_request_sheet_model.h", + "webauthn/ble_device_hover_list_model.cc", + "webauthn/ble_device_hover_list_model.h", + "webauthn/hover_list_model.h", "webauthn/other_transports_menu_model.cc", "webauthn/other_transports_menu_model.h", "webauthn/sheet_models.cc", "webauthn/sheet_models.h", + "webauthn/transport_hover_list_model.cc", + "webauthn/transport_hover_list_model.h", "webauthn/transport_utils.cc", "webauthn/transport_utils.h", ] @@ -2907,15 +2890,17 @@ jumbo_split_static_library("ui") { "views/apps/native_app_window_frame_view_mac.h", "views/apps/native_app_window_frame_view_mac.mm", "views/chrome_views_delegate_mac.cc", - "views/frame/native_widget_mac_frameless_nswindow.h", - "views/frame/native_widget_mac_frameless_nswindow.mm", "views/policy/enterprise_startup_dialog_mac_util.h", "views/policy/enterprise_startup_dialog_mac_util.mm", + "views/ssl_client_certificate_selector_mac.h", + "views/ssl_client_certificate_selector_mac.mm", ] } else { sources += [ "views/create_application_shortcut_view.cc", "views/create_application_shortcut_view.h", + "views/ssl_client_certificate_selector.cc", + "views/ssl_client_certificate_selector.h", # TODO(ellyjones): Mus is not supported on Mac (there is no ui::Window # apart from aura::Window, which is also not supported). @@ -2931,11 +2916,7 @@ jumbo_split_static_library("ui") { } if (is_win) { - sources += [ - "views/chrome_views_delegate_win.cc", - "views/feature_promos/bookmark_bar_promo_bubble_view.cc", - "views/feature_promos/bookmark_bar_promo_bubble_view.h", - ] + sources += [ "views/chrome_views_delegate_win.cc" ] } if (is_win || is_desktop_linux) { @@ -2985,8 +2966,6 @@ jumbo_split_static_library("ui") { "views/outdated_upgrade_bubble_view.h", "views/policy/enterprise_startup_dialog_view.cc", "views/policy/enterprise_startup_dialog_view.h", - "views/profiles/forced_reauthentication_dialog_view.cc", - "views/profiles/forced_reauthentication_dialog_view.h", "views/relaunch_notification/relaunch_notification_controller_platform_impl_desktop.cc", "views/relaunch_notification/relaunch_notification_controller_platform_impl_desktop.h", "views/relaunch_notification/relaunch_recommended_bubble_view.cc", @@ -3070,8 +3049,6 @@ jumbo_split_static_library("ui") { "views/frame/browser_non_client_frame_view_factory_views.cc", "views/frame/desktop_browser_frame_aura.cc", "views/frame/desktop_browser_frame_aura.h", - "views/message_center/popups_only_ui_delegate.cc", - "views/message_center/popups_only_ui_delegate.h", ] } } @@ -3110,14 +3087,10 @@ jumbo_split_static_library("ui") { "app_list/extension_uninstaller.h", "app_list/md_icon_normalizer.cc", "app_list/md_icon_normalizer.h", - "app_list/search/answer_card/answer_card_contents.cc", - "app_list/search/answer_card/answer_card_contents.h", "app_list/search/answer_card/answer_card_result.cc", "app_list/search/answer_card/answer_card_result.h", "app_list/search/answer_card/answer_card_search_provider.cc", "app_list/search/answer_card/answer_card_search_provider.h", - "app_list/search/answer_card/answer_card_web_contents.cc", - "app_list/search/answer_card/answer_card_web_contents.h", "app_list/search/app_result.cc", "app_list/search/app_result.h", "app_list/search/app_search_provider.cc", @@ -3140,12 +3113,6 @@ jumbo_split_static_library("ui") { "app_list/search/common/json_response_fetcher.h", "app_list/search/common/url_icon_source.cc", "app_list/search/common/url_icon_source.h", - "app_list/search/common/webservice_cache.cc", - "app_list/search/common/webservice_cache.h", - "app_list/search/common/webservice_cache_factory.cc", - "app_list/search/common/webservice_cache_factory.h", - "app_list/search/common/webservice_search_provider.cc", - "app_list/search/common/webservice_search_provider.h", "app_list/search/dictionary_data_store.cc", "app_list/search/dictionary_data_store.h", "app_list/search/extension_app_result.cc", @@ -3170,20 +3137,12 @@ jumbo_split_static_library("ui") { "app_list/search/search_result_ranker/app_search_result_ranker.h", "app_list/search/search_util.cc", "app_list/search/search_util.h", - "app_list/search/search_webstore_result.cc", - "app_list/search/search_webstore_result.h", "app_list/search/settings_shortcut/settings_shortcut_metadata.cc", "app_list/search/settings_shortcut/settings_shortcut_metadata.h", "app_list/search/settings_shortcut/settings_shortcut_provider.cc", "app_list/search/settings_shortcut/settings_shortcut_provider.h", "app_list/search/settings_shortcut/settings_shortcut_result.cc", "app_list/search/settings_shortcut/settings_shortcut_result.h", - "app_list/search/webstore/webstore_installer.cc", - "app_list/search/webstore/webstore_installer.h", - "app_list/search/webstore/webstore_provider.cc", - "app_list/search/webstore/webstore_provider.h", - "app_list/search/webstore/webstore_result.cc", - "app_list/search/webstore/webstore_result.h", ] deps += [ # TODO(wutao): Put new icons resources to ash/public/cpp/vector_icons/ @@ -3198,6 +3157,10 @@ jumbo_split_static_library("ui") { if (is_chromeos) { sources += [ "app_icon_loader_delegate.h", + "app_list/app_service_app_item.cc", + "app_list/app_service_app_item.h", + "app_list/app_service_app_model_builder.cc", + "app_list/app_service_app_model_builder.h", "app_list/arc/arc_app_context_menu.cc", "app_list/arc/arc_app_context_menu.h", "app_list/arc/arc_app_dialog.h", @@ -3306,6 +3269,8 @@ jumbo_split_static_library("ui") { "ash/launcher/shelf_spinner_item_controller.h", "views/arc_app_dialog_view.cc", "views/arc_data_removal_dialog_view.cc", + "views/crostini/crostini_app_restart_view.cc", + "views/crostini/crostini_app_restart_view.h", "views/crostini/crostini_installer_view.cc", "views/crostini/crostini_installer_view.h", "views/crostini/crostini_uninstaller_view.cc", @@ -3313,7 +3278,10 @@ jumbo_split_static_library("ui") { "views/crostini/crostini_upgrade_view.cc", "views/crostini/crostini_upgrade_view.h", ] - deps += [ "//mash/common" ] + deps += [ + "//chrome/services/app_service/public/cpp:app_update", + "//mash/common", + ] } } @@ -3335,15 +3303,22 @@ jumbo_split_static_library("ui") { "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_desktop_in_product_help) { sources += [ - "in_product_help/reopen_tab_iph_trigger.cc", - "in_product_help/reopen_tab_iph_trigger.h", + "in_product_help/active_tab_tracker.cc", + "in_product_help/active_tab_tracker.h", + "in_product_help/in_product_help.h", + "in_product_help/reopen_tab_in_product_help.cc", + "in_product_help/reopen_tab_in_product_help.h", + "in_product_help/reopen_tab_in_product_help_factory.cc", + "in_product_help/reopen_tab_in_product_help_factory.h", + "in_product_help/reopen_tab_in_product_help_trigger.cc", + "in_product_help/reopen_tab_in_product_help_trigger.h", + "views/feature_promos/reopen_tab_promo_controller.cc", + "views/feature_promos/reopen_tab_promo_controller.h", ] } @@ -3597,9 +3572,9 @@ static_library("test_support") { "//chrome/app/theme:theme_resources", "//chrome/browser", "//chrome/browser/devtools", + "//components/omnibox/browser", "//components/password_manager/core/browser", "//components/sessions", - "//components/toolbar", "//components/translate/content/browser", "//content/public/browser", "//content/public/common", @@ -3678,3 +3653,16 @@ static_library("test_support") { deps += [ "//extensions/browser" ] } } + +if (is_chromeos) { + source_set("ash_test_support") { + check_includes = false + sources = [ + "ash/chrome_keyboard_controller_client_test_helper.cc", + "ash/chrome_keyboard_controller_client_test_helper.h", + ] + deps = [ + "//ash", + ] + } +} diff --git a/chromium/chrome/browser/ui/libgtkui/BUILD.gn b/chromium/chrome/browser/ui/libgtkui/BUILD.gn index ffe7eb80840..3a53a45048c 100644 --- a/chromium/chrome/browser/ui/libgtkui/BUILD.gn +++ b/chromium/chrome/browser/ui/libgtkui/BUILD.gn @@ -14,8 +14,6 @@ component("libgtkui") { "app_indicator_icon.h", "app_indicator_icon_menu.cc", "app_indicator_icon_menu.h", - "chrome_gtk_menu_subclasses.cc", - "chrome_gtk_menu_subclasses.h", "gtk_background_painter.cc", "gtk_background_painter.h", "gtk_event_loop.cc", diff --git a/chromium/chrome/browser/ui/webui/about_ui.cc b/chromium/chrome/browser/ui/webui/about_ui.cc index 6efb0ca7eb1..7c8ef823580 100644 --- a/chromium/chrome/browser/ui/webui/about_ui.cc +++ b/chromium/chrome/browser/ui/webui/about_ui.cc @@ -31,7 +31,7 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "base/task/post_task.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/thread.h" diff --git a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc index cff5e1ec488..13c4f3c1784 100644 --- a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc @@ -20,7 +20,7 @@ #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_metrics.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/signin_promo_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" @@ -32,13 +32,14 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/core/browser/signin_pref_names.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/page_zoom.h" #include "net/base/escape.h" +#include "services/identity/public/cpp/identity_manager.h" #include "skia/ext/image_operations.h" #include "third_party/skia/include/core/SkSurface.h" #include "ui/base/l10n/l10n_util.h" @@ -121,8 +122,8 @@ void AppLauncherLoginHandler::HandleShowSyncLoginUI( if (!signin::ShouldShowPromo(profile)) return; - std::string username = SigninManagerFactory::GetForProfile(profile) - ->GetAuthenticatedAccountInfo() + std::string username = IdentityManagerFactory::GetForProfile(profile) + ->GetPrimaryAccountInfo() .email; if (!username.empty()) return; @@ -196,9 +197,10 @@ void AppLauncherLoginHandler::UpdateLogin() { } else { #if !defined(OS_CHROMEOS) // Chromeos does not show this status header. - SigninManager* signin = SigninManagerFactory::GetForProfile( - profile->GetOriginalProfile()); - if (!profile->IsLegacySupervised() && signin->IsSigninAllowed()) { + bool is_signin_allowed = + profile->GetOriginalProfile()->GetPrefs()->GetBoolean( + prefs::kSigninAllowed); + if (!profile->IsLegacySupervised() && is_signin_allowed) { base::string16 signed_in_link = l10n_util::GetStringUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_LINK); signed_in_link = @@ -236,8 +238,9 @@ bool AppLauncherLoginHandler::ShouldShow(Profile* profile) { // UI and the avatar menu don't exist on that platform. return false; #else - SigninManager* signin = SigninManagerFactory::GetForProfile(profile); - return !profile->IsOffTheRecord() && signin && signin->IsSigninAllowed(); + bool is_signin_allowed = + profile->GetPrefs()->GetBoolean(prefs::kSigninAllowed); + return !profile->IsOffTheRecord() && is_signin_allowed; #endif } diff --git a/chromium/chrome/browser/ui/webui/app_management/BUILD.gn b/chromium/chrome/browser/ui/webui/app_management/BUILD.gn new file mode 100644 index 00000000000..1f743d881b5 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/app_management/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 = [ + "app_management.mojom", + ] +} diff --git a/chromium/chrome/browser/ui/webui/app_management/OWNERS b/chromium/chrome/browser/ui/webui/app_management/OWNERS new file mode 100644 index 00000000000..4829e5de205 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/app_management/OWNERS @@ -0,0 +1,6 @@ +per-file *.mojom=set noparent +per-file *.mojom=file://ipc/SECURITY_OWNERS + +calamity@chromium.org +dominickn@chromium.org +ericwilligers@chromium.org diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management.mojom b/chromium/chrome/browser/ui/webui/app_management/app_management.mojom new file mode 100644 index 00000000000..0525d25ff52 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/app_management/app_management.mojom @@ -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. + +module app_management.mojom; + +interface PageHandlerFactory { + CreatePageHandler(Page page, PageHandler& handler); +}; + +// Browser interface. +interface PageHandler { + GetApps(); +}; + +// Frontend interface. +interface Page { + OnAppsAdded(array<string> ids); +}; diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc new file mode 100644 index 00000000000..203ad321854 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc @@ -0,0 +1,21 @@ +// 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/app_management/app_management_page_handler.h" + +#include <utility> +#include <vector> + +AppManagementPageHandler::AppManagementPageHandler( + app_management::mojom::PageHandlerRequest request, + app_management::mojom::PagePtr page, + content::WebUI* web_ui) + : binding_(this, std::move(request)), page_(std::move(page)) {} + +AppManagementPageHandler::~AppManagementPageHandler() {} + +void AppManagementPageHandler::GetApps() { + std::vector<std::string> ids = {"test_id"}; + page_->OnAppsAdded(ids); +} diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h new file mode 100644 index 00000000000..76c45b6c216 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.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_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/app_management/app_management.mojom.h" +#include "mojo/public/cpp/bindings/binding.h" + +namespace content { +class WebUI; +} + +class AppManagementPageHandler : public app_management::mojom::PageHandler { + public: + AppManagementPageHandler(app_management::mojom::PageHandlerRequest request, + app_management::mojom::PagePtr page, + content::WebUI* web_ui); + ~AppManagementPageHandler() override; + + // app_management::mojom::PageHandler: + void GetApps() override; + + private: + mojo::Binding<app_management::mojom::PageHandler> binding_; + + app_management::mojom::PagePtr page_; + + DISALLOW_COPY_AND_ASSIGN(AppManagementPageHandler); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc new file mode 100644 index 00000000000..de431a58572 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc @@ -0,0 +1,84 @@ +// 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/app_management/app_management_ui.h" + +#include <utility> + +#include "base/bind.h" +#include "base/feature_list.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/app_management/app_management_page_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 "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" +#include "ui/base/resource/resource_bundle.h" + +namespace { + +content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(chrome::kChromeUIAppLauncherPageHost); + + source->AddResourcePath("app_management.mojom-lite.js", + IDR_APP_MANAGEMENT_MOJO_LITE_JS); + source->AddResourcePath("app.html", IDR_APP_MANAGEMENT_APP_HTML); + source->AddResourcePath("app.js", IDR_APP_MANAGEMENT_APP_JS); + source->AddResourcePath("browser_proxy.html", + IDR_APP_MANAGEMENT_BROWSER_PROXY_HTML); + source->AddResourcePath("browser_proxy.js", + IDR_APP_MANAGEMENT_BROWSER_PROXY_JS); + source->SetDefaultResource(IDR_APP_MANAGEMENT_INDEX_HTML); + + source->SetJsonPath("strings.js"); + + return source; +} + +} // namespace + +/////////////////////////////////////////////////////////////////////////////// +// +// AppManagementUI +// +/////////////////////////////////////////////////////////////////////////////// + +AppManagementUI::AppManagementUI(content::WebUI* web_ui) + : ui::MojoWebUIController(web_ui, true), page_factory_binding_(this) { + Profile* profile = Profile::FromWebUI(web_ui); + + // Set up the data source. + content::WebUIDataSource* source = CreateAppManagementUIHTMLSource(profile); + content::WebUIDataSource::Add(profile, source); + + AddHandlerToRegistry(base::BindRepeating( + &AppManagementUI::BindPageHandlerFactory, base::Unretained(this))); +} + +AppManagementUI::~AppManagementUI() = default; + +bool AppManagementUI::IsEnabled() { + return base::FeatureList::IsEnabled(features::kAppManagement); +} + +void AppManagementUI::BindPageHandlerFactory( + app_management::mojom::PageHandlerFactoryRequest request) { + if (page_factory_binding_.is_bound()) + page_factory_binding_.Unbind(); + + page_factory_binding_.Bind(std::move(request)); +} + +void AppManagementUI::CreatePageHandler( + app_management::mojom::PagePtr page, + app_management::mojom::PageHandlerRequest request) { + DCHECK(page); + + page_handler_.reset(new AppManagementPageHandler(std::move(request), + std::move(page), web_ui())); +} diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h new file mode 100644 index 00000000000..a0187ee104e --- /dev/null +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h @@ -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. + +#ifndef CHROME_BROWSER_UI_WEBUI_APP_MANAGEMENT_APP_MANAGEMENT_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_APP_MANAGEMENT_APP_MANAGEMENT_UI_H_ + +#include <memory> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/app_management/app_management.mojom.h" +#include "mojo/public/cpp/bindings/binding.h" +#include "ui/webui/mojo_web_ui_controller.h" + +class AppManagementPageHandler; + +class AppManagementUI : public ui::MojoWebUIController, + public app_management::mojom::PageHandlerFactory { + public: + explicit AppManagementUI(content::WebUI* web_ui); + ~AppManagementUI() override; + + static bool IsEnabled(); + + private: + void BindPageHandlerFactory( + app_management::mojom::PageHandlerFactoryRequest request); + + // app_management::mojom::PageHandlerFactory: + void CreatePageHandler( + app_management::mojom::PagePtr page, + app_management::mojom::PageHandlerRequest request) override; + + std::unique_ptr<AppManagementPageHandler> page_handler_; + mojo::Binding<app_management::mojom::PageHandlerFactory> + page_factory_binding_; + + DISALLOW_COPY_AND_ASSIGN(AppManagementUI); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_APP_MANAGEMENT_APP_MANAGEMENT_UI_H_ 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 dc91141d72f..ddabb2d0437 100644 --- a/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc @@ -22,6 +22,7 @@ #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_test_util.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/browser_sync/test_profile_sync_service.h" #include "components/history/core/browser/browsing_history_service.h" @@ -29,13 +30,10 @@ #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" #include "components/signin/core/browser/fake_signin_manager.h" #include "components/sync/base/model_type.h" -#include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "net/http/http_status_code.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace { @@ -104,40 +102,40 @@ class BrowsingHistoryHandlerWithWebUIForTesting } // namespace -class BrowsingHistoryHandlerTest : public ::testing::Test { +class BrowsingHistoryHandlerTest : public ChromeRenderViewHostTestHarness { public: void SetUp() override { - TestingProfile::Builder builder; - builder.AddTestingFactory( - ProfileOAuth2TokenServiceFactory::GetInstance(), - base::BindRepeating(&BuildFakeProfileOAuth2TokenService)); - builder.AddTestingFactory(SigninManagerFactory::GetInstance(), - base::BindRepeating(&BuildFakeSigninManagerBase)); - builder.AddTestingFactory(ProfileSyncServiceFactory::GetInstance(), - base::BindRepeating(&BuildFakeSyncService)); - builder.AddTestingFactory(WebHistoryServiceFactory::GetInstance(), - base::BindRepeating(&BuildFakeWebHistoryService)); - profile_ = builder.Build(); - profile_->CreateBookmarkModel(false); + ChromeRenderViewHostTestHarness::SetUp(); + profile()->CreateBookmarkModel(false); sync_service_ = static_cast<TestSyncService*>( - ProfileSyncServiceFactory::GetForProfile(profile_.get())); + ProfileSyncServiceFactory::GetForProfile(profile())); web_history_service_ = static_cast<history::FakeWebHistoryService*>( - WebHistoryServiceFactory::GetForProfile(profile_.get())); + WebHistoryServiceFactory::GetForProfile(profile())); - web_contents_ = content::WebContents::Create( - content::WebContents::CreateParams(profile_.get())); web_ui_.reset(new content::TestWebUI); - web_ui_->set_web_contents(web_contents_.get()); + web_ui_->set_web_contents(web_contents()); } void TearDown() override { - web_contents_.reset(); web_ui_.reset(); - profile_.reset(); + ChromeRenderViewHostTestHarness::TearDown(); } - Profile* profile() { return profile_.get(); } + content::BrowserContext* CreateBrowserContext() override { + TestingProfile::Builder builder; + builder.AddTestingFactory( + ProfileOAuth2TokenServiceFactory::GetInstance(), + base::BindRepeating(&BuildFakeProfileOAuth2TokenService)); + builder.AddTestingFactory( + SigninManagerFactory::GetInstance(), + base::BindRepeating(&BuildFakeSigninManagerForTesting)); + builder.AddTestingFactory(ProfileSyncServiceFactory::GetInstance(), + base::BindRepeating(&BuildFakeSyncService)); + builder.AddTestingFactory(WebHistoryServiceFactory::GetInstance(), + base::BindRepeating(&BuildFakeWebHistoryService)); + return builder.Build().release(); + } TestSyncService* sync_service() { return sync_service_; } history::WebHistoryService* web_history_service() { return web_history_service_; @@ -159,12 +157,9 @@ class BrowsingHistoryHandlerTest : public ::testing::Test { return std::move(service); } - content::TestBrowserThreadBundle thread_bundle_; - std::unique_ptr<TestingProfile> profile_; TestSyncService* sync_service_; history::FakeWebHistoryService* web_history_service_; std::unique_ptr<content::TestWebUI> web_ui_; - std::unique_ptr<content::WebContents> web_contents_; }; // Tests that BrowsingHistoryHandler is informed about WebHistoryService diff --git a/chromium/chrome/browser/ui/webui/certificates_handler.cc b/chromium/chrome/browser/ui/webui/certificates_handler.cc index 58f6be72e19..593258940f8 100644 --- a/chromium/chrome/browser/ui/webui/certificates_handler.cc +++ b/chromium/chrome/browser/ui/webui/certificates_handler.cc @@ -571,8 +571,8 @@ void CertificatesHandler::HandleExportPersonalPasswordSelected( selected_cert_list_[0].get(), kCryptoModulePasswordCertExport, net::HostPortPair(), // unused. GetParentWindow(), - base::Bind(&CertificatesHandler::ExportPersonalSlotsUnlocked, - base::Unretained(this))); + base::BindOnce(&CertificatesHandler::ExportPersonalSlotsUnlocked, + base::Unretained(this))); } void CertificatesHandler::ExportPersonalSlotsUnlocked() { @@ -708,8 +708,8 @@ void CertificatesHandler::HandleImportPersonalPasswordSelected( std::move(modules), kCryptoModulePasswordCertImport, net::HostPortPair(), // unused. GetParentWindow(), - base::Bind(&CertificatesHandler::ImportPersonalSlotUnlocked, - base::Unretained(this))); + base::BindOnce(&CertificatesHandler::ImportPersonalSlotUnlocked, + base::Unretained(this))); } void CertificatesHandler::ImportPersonalSlotUnlocked() { 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 a1727f46d11..5d978a4286e 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 @@ -22,6 +22,7 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/search/suggestions/suggestions_ui.h" #include "chrome/browser/ui/webui/about_ui.h" +#include "chrome/browser/ui/webui/app_management/app_management_ui.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h" #include "chrome/browser/ui/webui/components_ui.h" #include "chrome/browser/ui/webui/constrained_web_dialog_ui.h" @@ -82,7 +83,7 @@ #include "components/safe_browsing/web_ui/safe_browsing_ui.h" #include "components/security_interstitials/content/connection_help_ui.h" #include "components/security_interstitials/content/urls.h" -#include "components/signin/core/browser/profile_management_switches.h" +#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/signin_buildflags.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -134,7 +135,7 @@ #endif #if defined(OS_CHROMEOS) -#include "base/sys_info.h" +#include "base/system/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" @@ -147,7 +148,6 @@ #include "chrome/browser/ui/webui/chromeos/first_run/first_run_ui.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/keyboard_overlay_ui.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/browser/ui/webui/chromeos/mobile_setup_ui.h" #include "chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.h" @@ -156,6 +156,7 @@ #include "chrome/browser/ui/webui/chromeos/set_time_ui.h" #include "chrome/browser/ui/webui/chromeos/slow_trace_ui.h" #include "chrome/browser/ui/webui/chromeos/slow_ui.h" +#include "chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.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" @@ -264,23 +265,12 @@ 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, - 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); + chromeos::device_sync::DeviceSyncClientFactory::GetForProfile( + Profile::FromBrowserContext(browser_context)), + chromeos::secure_channel::SecureChannelClientProvider::GetInstance() + ->GetClient()); } #endif @@ -426,6 +416,12 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, * OS Specific #defines ***************************************************************************/ #if !defined(OS_ANDROID) + if (AppManagementUI::IsEnabled() && + url.host_piece() == chrome::kChromeUIAppLauncherPageHost && profile && + !profile->IsGuestSession()) { + return &NewWebUI<AppManagementUI>; + } + #if !defined(OS_CHROMEOS) // AppLauncherPage is not needed on Android or ChromeOS. if (url.host_piece() == chrome::kChromeUIAppLauncherPageHost && profile && @@ -433,7 +429,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, !profile->IsGuestSession()) { return &NewWebUI<AppLauncherPageUI>; } -#endif // defined(OS_CHROMEOS) +#endif // !defined(OS_CHROMEOS) if (profile->IsGuestSession() && (url.host_piece() == chrome::kChromeUIAppLauncherPageHost || @@ -485,8 +481,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<chromeos::DriveInternalsUI>; if (url.host_piece() == chrome::kChromeUIFirstRunHost) return &NewWebUI<chromeos::FirstRunUI>; - if (url.host_piece() == chrome::kChromeUIKeyboardOverlayHost) - return &NewWebUI<KeyboardOverlayUI>; if (url.host_piece() == chrome::kChromeUIMobileSetupHost) return &NewWebUI<chromeos::MobileSetupUI>; if (url.host_piece() == chrome::kChromeUIMultiDeviceSetupHost) @@ -509,6 +503,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<chromeos::SlowUI>; if (url.host_piece() == chrome::kChromeUISlowTraceHost) return &NewWebUI<chromeos::SlowTraceController>; + if (url.host_piece() == chrome::kChromeUISmbShareHost) + return &NewWebUI<chromeos::smb_dialog::SmbShareDialogUI>; if (url.host_piece() == chrome::kChromeUISysInternalsHost && SysInternalsUI::IsEnabled()) return &NewWebUI<SysInternalsUI>; diff --git a/chromium/chrome/browser/ui/webui/chromeos/DEPS b/chromium/chrome/browser/ui/webui/chromeos/DEPS index ef0d6e148d1..c1fd05f97b2 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/DEPS +++ b/chromium/chrome/browser/ui/webui/chromeos/DEPS @@ -1,6 +1,7 @@ include_rules = [ "+media/audio/sounds", "+services/device/public/mojom", + "+services/network", ] specific_include_rules = { 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 d20d4ac5bad..ea3301d2c47 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 @@ -11,12 +11,14 @@ #include "base/macros.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h" #include "chrome/browser/ui/browser_dialogs.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 "components/arc/arc_prefs.h" #include "components/prefs/pref_service.h" +#include "components/user_manager/user_manager.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" @@ -72,8 +74,12 @@ void AssistantOptInDialog::Show( int container_id = dialog->GetDialogModalType() == ui::MODAL_TYPE_NONE ? ash::kShellWindowId_DefaultContainer : ash::kShellWindowId_LockSystemModalContainer; - chrome::ShowWebDialogInContainer( + auto* window = chrome::ShowWebDialogInContainer( container_id, ProfileManager::GetActiveUserProfile(), dialog, true); + + MultiUserWindowManager::GetInstance()->SetWindowOwner( + window, + user_manager::UserManager::Get()->GetActiveUser()->GetAccountId()); } // static diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc index bfbed7e9d30..43c582bef06 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc @@ -6,14 +6,16 @@ #include "base/metrics/histogram_macros.h" #include "chrome/browser/consent_auditor/consent_auditor_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/webui/chromeos/user_image_source.h" #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" +#include "chromeos/services/assistant/public/features.h" #include "components/arc/arc_prefs.h" #include "components/consent_auditor/consent_auditor.h" #include "components/signin/core/browser/signin_manager_base.h" #include "components/user_manager/user_manager.h" +#include "services/identity/public/cpp/identity_manager.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" @@ -107,23 +109,28 @@ base::Value CreateGetMoreData(bool email_optin_needed, const assistant::EmailOptInUi& email_optin_ui) { base::Value get_more_data(base::Value::Type::LIST); - // Process hotword data. - base::Value hotword_data(base::Value::Type::DICTIONARY); - hotword_data.SetKey( - "title", - base::Value(l10n_util::GetStringUTF16(IDS_ASSISTANT_HOTWORD_TITLE))); - hotword_data.SetKey( - "description", - base::Value(l10n_util::GetStringUTF16(IDS_ASSISTANT_HOTWORD_DESC))); - hotword_data.SetKey("defaultEnabled", base::Value(true)); - hotword_data.SetKey( - "iconUri", - base::Value("https://www.gstatic.com/images/icons/material/system/" - "2x/mic_none_grey600_48dp.png")); - get_more_data.GetList().push_back(std::move(hotword_data)); + if (!base::FeatureList::IsEnabled( + assistant::features::kAssistantVoiceMatch)) { + // Process hotword data. + base::Value hotword_data(base::Value::Type::DICTIONARY); + hotword_data.SetKey("id", base::Value("hotword")); + hotword_data.SetKey( + "title", + base::Value(l10n_util::GetStringUTF16(IDS_ASSISTANT_HOTWORD_TITLE))); + hotword_data.SetKey( + "description", + base::Value(l10n_util::GetStringUTF16(IDS_ASSISTANT_HOTWORD_DESC))); + hotword_data.SetKey("defaultEnabled", base::Value(true)); + hotword_data.SetKey( + "iconUri", + base::Value("https://www.gstatic.com/images/icons/material/system/" + "2x/mic_none_grey600_48dp.png")); + get_more_data.GetList().push_back(std::move(hotword_data)); + } // Process screen context data. base::Value context_data(base::Value::Type::DICTIONARY); + context_data.SetKey("id", base::Value("context")); context_data.SetKey("title", base::Value(l10n_util::GetStringUTF16( IDS_ASSISTANT_SCREEN_CONTEXT_TITLE))); context_data.SetKey("description", base::Value(l10n_util::GetStringUTF16( @@ -138,6 +145,7 @@ base::Value CreateGetMoreData(bool email_optin_needed, // Process email optin data. if (email_optin_needed) { base::Value data(base::Value::Type::DICTIONARY); + data.SetKey("id", base::Value("email")); data.SetKey("title", base::Value(email_optin_ui.title())); data.SetKey("description", base::Value(email_optin_ui.description())); data.SetKey("defaultEnabled", @@ -208,10 +216,9 @@ using sync_pb::UserConsentTypes; void RecordActivityControlConsent(Profile* profile, std::string ui_audit_key, bool opted_in) { - SigninManagerBase* signin_manager = - SigninManagerFactory::GetForProfile(profile); - DCHECK(signin_manager->IsAuthenticated()); - std::string account_id = signin_manager->GetAuthenticatedAccountId(); + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); + DCHECK(identity_manager->HasPrimaryAccount()); + const std::string account_id = identity_manager->GetPrimaryAccountId(); UserConsentTypes::AssistantActivityControlConsent consent; consent.set_ui_audit_key(ui_audit_key); diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h index 01f918cbd65..f5013d204dd 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h @@ -20,17 +20,17 @@ namespace chromeos { // histogram and should be treated as append-only. enum AssistantOptInFlowStatus { FLOW_STARTED = 0, - ACTIVITY_CONTROL_SHOWN, - ACTIVITY_CONTROL_ACCEPTED, - ACTIVITY_CONTROL_SKIPPED, - THIRD_PARTY_SHOWN, - THIRD_PARTY_CONTINUED, - GET_MORE_SHOWN, - EMAIL_OPTED_IN, - EMAIL_OPTED_OUT, - GET_MORE_CONTINUED, - READY_SCREEN_SHOWN, - READY_SCREEN_CONTINUED, + ACTIVITY_CONTROL_SHOWN = 1, + ACTIVITY_CONTROL_ACCEPTED = 2, + ACTIVITY_CONTROL_SKIPPED = 3, + THIRD_PARTY_SHOWN = 4, + THIRD_PARTY_CONTINUED = 5, + GET_MORE_SHOWN = 6, + EMAIL_OPTED_IN = 7, + EMAIL_OPTED_OUT = 8, + GET_MORE_CONTINUED = 9, + READY_SCREEN_SHOWN = 10, + READY_SCREEN_CONTINUED = 11, // Magic constant used by the histogram macros. kMaxValue = READY_SCREEN_CONTINUED }; 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 0b288d0f111..52c1cc357e0 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc @@ -21,7 +21,7 @@ #include "base/strings/pattern.h" #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "base/task/post_task.h" #include "chrome/browser/chromeos/drive/debug_info_collector.h" #include "chrome/browser/chromeos/drive/drive_integration_service.h" @@ -32,6 +32,7 @@ #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" +#include "chromeos/chromeos_features.h" #include "components/drive/drive.pb.h" #include "components/drive/drive_api_util.h" #include "components/drive/drive_notification_manager.h" @@ -91,19 +92,16 @@ size_t LogMarkToLogLevelNameIndex(char mark) { // },...] // // The list is sorted by the path. -void GetGCacheContents(const base::FilePath& root_path, - base::ListValue* gcache_contents, - base::DictionaryValue* gcache_summary) { +std::pair<base::ListValue, base::DictionaryValue> GetGCacheContents( + const base::FilePath& root_path) { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); - DCHECK(gcache_contents); - DCHECK(gcache_summary); // Use this map to sort the result list by the path. std::map<base::FilePath, std::unique_ptr<base::DictionaryValue>> files; - const int options = (base::FileEnumerator::FILES | - base::FileEnumerator::DIRECTORIES | - base::FileEnumerator::SHOW_SYM_LINKS); + const int options = + (base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES | + base::FileEnumerator::SHOW_SYM_LINKS); base::FileEnumerator enumerator(root_path, true /* recursive */, options); int64_t total_size = 0; @@ -125,29 +123,19 @@ void GetGCacheContents(const base::FilePath& root_path, "last_modified", google_apis::util::FormatTimeAsStringLocaltime(last_modified)); // Print lower 9 bits in octal format. - entry->SetString( - "permission", - base::StringPrintf("%03o", info.stat().st_mode & 0x1ff)); + entry->SetString("permission", + base::StringPrintf("%03o", info.stat().st_mode & 0x1ff)); files[current] = std::move(entry); total_size += size; } - // Convert |files| into |gcache_contents|. + std::pair<base::ListValue, base::DictionaryValue> result; + // Convert |files| into response. for (auto& it : files) - gcache_contents->Append(std::move(it.second)); - - gcache_summary->SetDouble("total_size", total_size); -} - -// Gets the available disk space for the path |home_path|. -void GetFreeDiskSpace(const base::FilePath& home_path, - base::DictionaryValue* local_storage_summary) { - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); - DCHECK(local_storage_summary); - - const int64_t free_space = base::SysInfo::AmountOfFreeDiskSpace(home_path); - local_storage_summary->SetDouble("free_space", free_space); + result.first.Append(std::move(it.second)); + result.second.SetDouble("total_size", total_size); + return result; } // Formats |entry| into text. @@ -291,700 +279,649 @@ std::pair<ino_t, base::ListValue> GetServiceLogContents( class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { public: DriveInternalsWebUIHandler() - : last_sent_event_id_(-1), - weak_ptr_factory_(this) { - } + : last_sent_event_id_(-1), weak_ptr_factory_(this) {} ~DriveInternalsWebUIHandler() override {} private: - // WebUIMessageHandler override. - void RegisterMessages() override; - - // Returns a DriveIntegrationService. - drive::DriveIntegrationService* GetIntegrationService(); + void MaybeCallJavascript(const std::string& function, + base::Value data1, + base::Value data2 = {}) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + if (IsJavascriptAllowed()) { + CallJavascriptFunction(function, std::move(data1), std::move(data2)); + } + } - // Returns a DriveService instance. - drive::DriveServiceInterface* GetDriveService(); + // Hide or show a section of the page. + void SetSectionEnabled(const std::string& section, bool enable) { + MaybeCallJavascript("setSectionEnabled", base::Value(section), + base::Value(enable)); + } - // Returns a DebugInfoCollector instance. - drive::DebugInfoCollector* GetDebugInfoCollector(); + // WebUIMessageHandler override. + void RegisterMessages() override { + web_ui()->RegisterMessageCallback( + "pageLoaded", + base::BindRepeating(&DriveInternalsWebUIHandler::OnPageLoaded, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "periodicUpdate", + base::BindRepeating(&DriveInternalsWebUIHandler::OnPeriodicUpdate, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "clearAccessToken", + base::BindRepeating(&DriveInternalsWebUIHandler::ClearAccessToken, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "clearRefreshToken", + base::BindRepeating(&DriveInternalsWebUIHandler::ClearRefreshToken, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "resetDriveFileSystem", + base::BindRepeating(&DriveInternalsWebUIHandler::ResetDriveFileSystem, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "listFileEntries", + base::BindRepeating(&DriveInternalsWebUIHandler::ListFileEntries, + weak_ptr_factory_.GetWeakPtr())); + } // Called when the page is first loaded. - void OnPageLoaded(const base::ListValue* args); - - // Updates respective sections. - void UpdateDriveRelatedPreferencesSection(); - void UpdateConnectionStatusSection( - drive::DriveServiceInterface* drive_service); - void UpdateAboutResourceSection( - drive::DriveServiceInterface* drive_service); - void UpdateDeltaUpdateStatusSection( - drive::DebugInfoCollector* debug_info_collector); - void UpdateInFlightOperationsSection(drive::JobListInterface* job_list); - void UpdateGCacheContentsSection(); - void UpdateFileSystemContentsSection(); - void UpdateLocalStorageUsageSection(); - void UpdateCacheContentsSection( - drive::DebugInfoCollector* debug_info_collector); - void UpdateEventLogSection(); - void UpdateServiceLogSection(); - void UpdatePathConfigurationsSection(); - - // Called when GetGCacheContents() is complete. - void OnGetGCacheContents(base::ListValue* gcache_contents, - base::DictionaryValue* cache_summary); - - // Called when GetResourceEntryByPath() is complete. - void OnGetResourceEntryByPath(const base::FilePath& path, - drive::FileError error, - std::unique_ptr<drive::ResourceEntry> entry); - - // Called when ReadDirectoryByPath() is complete. - void OnReadDirectoryByPath( - const base::FilePath& parent_path, - drive::FileError error, - std::unique_ptr<drive::ResourceEntryVector> entries); - - // Called as the iterator for DebugInfoCollector::IterateFileCache(). - void UpdateCacheEntry(const std::string& local_id, - const drive::FileCacheEntry& cache_entry); - - // Called when GetFreeDiskSpace() is complete. - void OnGetFreeDiskSpace(base::DictionaryValue* local_storage_summary); - - // Called when GetAboutResource() call to DriveService is complete. - void OnGetAboutResource( - google_apis::DriveApiErrorCode status, - std::unique_ptr<google_apis::AboutResource> about_resource); - - // Callback for DebugInfoCollector::GetMetadata for delta update. - void OnGetFilesystemMetadataForDeltaUpdate( - const drive::FileSystemMetadata& metadata, - const std::map<std::string, drive::FileSystemMetadata>& - team_drive_metadata); + void OnPageLoaded(const base::ListValue* args) { + AllowJavascript(); + + drive::DriveIntegrationService* integration_service = + GetIntegrationService(); + // |integration_service| may be NULL in the guest/incognito mode. + if (!integration_service) + return; + + UpdateDriveRelatedPreferencesSection(); + UpdateGCacheContentsSection(); + UpdateLocalStorageUsageSection(); + UpdatePathConfigurationsSection(); + + UpdateConnectionStatusSection(); + UpdateAboutResourceSection(); + + UpdateDeltaUpdateStatusSection(); + UpdateCacheContentsSection(); + + UpdateInFlightOperationsSection(); + + // When the drive-internals page is reloaded by the reload key, the page + // content is recreated, but this WebUI object is not (instead, OnPageLoaded + // is called again). In that case, we have to forget the last sent ID here, + // and resent whole the logs to the page. + last_sent_event_id_ = -1; + UpdateEventLogSection(); + last_sent_line_number_ = 0; + service_log_file_inode_ = 0; + UpdateServiceLogSection(); + } // Called when the page requests periodic update. - void OnPeriodicUpdate(const base::ListValue* args); - - // Called when the corresponding button on the page is pressed. - void ClearAccessToken(const base::ListValue* args); - void ClearRefreshToken(const base::ListValue* args); - void ResetDriveFileSystem(const base::ListValue* args); - void ListFileEntries(const base::ListValue* args); + void OnPeriodicUpdate(const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); - // Called after file system reset for ResetDriveFileSystem is done. - void ResetFinished(bool success); - - // Called when service logs are read. - void OnServiceLogRead(std::pair<ino_t, base::ListValue>); + drive::DriveIntegrationService* integration_service = + GetIntegrationService(); + // |integration_service| may be NULL in the guest/incognito mode. + if (!integration_service) + return; - // The last event sent to the JavaScript side. - int last_sent_event_id_; + UpdateEventLogSection(); + UpdateServiceLogSection(); - // The last line of service log sent to the JS side. - int last_sent_line_number_; + UpdateInFlightOperationsSection(); + } - // The inode of the log file. - ino_t service_log_file_inode_; + // + // Updates respective sections. + // + void UpdateConnectionStatusSection() { + SetSectionEnabled("connection-status-section", true); + + std::string status; + switch (drive::util::GetDriveConnectionStatus(profile())) { + case drive::util::DRIVE_DISCONNECTED_NOSERVICE: + status = "no service"; + break; + case drive::util::DRIVE_DISCONNECTED_NONETWORK: + status = "no network"; + break; + case drive::util::DRIVE_DISCONNECTED_NOTREADY: + status = "not ready"; + break; + case drive::util::DRIVE_CONNECTED_METERED: + status = "metered"; + break; + case drive::util::DRIVE_CONNECTED: + status = "connected"; + break; + } - // Service log file is being parsed. - bool service_log_file_is_processing_ = false; + base::DictionaryValue connection_status; + connection_status.SetString("status", status); + drive::DriveNotificationManager* drive_notification_manager = + drive::DriveNotificationManagerFactory::FindForBrowserContext( + profile()); + connection_status.SetBoolean( + "push-notification-enabled", + drive_notification_manager + ? drive_notification_manager->push_notification_enabled() + : false); + auto* drive_service = GetDriveService(); + if (drive_service) { + connection_status.SetBoolean("has-refresh-token", + drive_service->HasRefreshToken()); + connection_status.SetBoolean("has-access-token", + drive_service->HasAccessToken()); + } - base::WeakPtrFactory<DriveInternalsWebUIHandler> weak_ptr_factory_; - DISALLOW_COPY_AND_ASSIGN(DriveInternalsWebUIHandler); -}; + MaybeCallJavascript("updateConnectionStatus", std::move(connection_status)); + } -void DriveInternalsWebUIHandler::OnGetAboutResource( - google_apis::DriveApiErrorCode status, - std::unique_ptr<google_apis::AboutResource> parsed_about_resource) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + void UpdateAboutResourceSection() { + if (IsDriveFsEnabled()) { + // TODO(crbug.com/896123): Maybe worth implementing. + SetSectionEnabled("account-information-section", false); + return; + } - if (status != google_apis::HTTP_SUCCESS) { - LOG(ERROR) << "Failed to get about resource"; - return; + SetSectionEnabled("account-information-section", true); + auto* drive_service = GetDriveService(); + if (drive_service) { + drive_service->GetAboutResource( + base::Bind(&DriveInternalsWebUIHandler::OnGetAboutResource, + weak_ptr_factory_.GetWeakPtr())); + } } - DCHECK(parsed_about_resource); - base::DictionaryValue about_resource; - about_resource.SetDouble("account-quota-total", - parsed_about_resource->quota_bytes_total()); - about_resource.SetDouble("account-quota-used", - parsed_about_resource->quota_bytes_used_aggregate()); - about_resource.SetDouble("account-largest-changestamp-remote", - parsed_about_resource->largest_change_id()); - about_resource.SetString("root-resource-id", - parsed_about_resource->root_folder_id()); - - web_ui()->CallJavascriptFunctionUnsafe("updateAboutResource", about_resource); -} + // Called when GetAboutResource() call to DriveService is complete. + void OnGetAboutResource( + google_apis::DriveApiErrorCode status, + std::unique_ptr<google_apis::AboutResource> about_resource) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); -void DriveInternalsWebUIHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "pageLoaded", - base::BindRepeating(&DriveInternalsWebUIHandler::OnPageLoaded, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback( - "periodicUpdate", - base::BindRepeating(&DriveInternalsWebUIHandler::OnPeriodicUpdate, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback( - "clearAccessToken", - base::BindRepeating(&DriveInternalsWebUIHandler::ClearAccessToken, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback( - "clearRefreshToken", - base::BindRepeating(&DriveInternalsWebUIHandler::ClearRefreshToken, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback( - "resetDriveFileSystem", - base::BindRepeating(&DriveInternalsWebUIHandler::ResetDriveFileSystem, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback( - "listFileEntries", - base::BindRepeating(&DriveInternalsWebUIHandler::ListFileEntries, - weak_ptr_factory_.GetWeakPtr())); -} + if (status != google_apis::HTTP_SUCCESS) { + LOG(ERROR) << "Failed to get about resource"; + return; + } + DCHECK(about_resource); -drive::DriveIntegrationService* -DriveInternalsWebUIHandler::GetIntegrationService() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + base::DictionaryValue data; + data.SetDouble("account-quota-total", about_resource->quota_bytes_total()); + data.SetDouble("account-quota-used", + about_resource->quota_bytes_used_aggregate()); + data.SetDouble("account-largest-changestamp-remote", + about_resource->largest_change_id()); + data.SetString("root-resource-id", about_resource->root_folder_id()); - Profile* profile = Profile::FromWebUI(web_ui()); - drive::DriveIntegrationService* service = - drive::DriveIntegrationServiceFactory::FindForProfile(profile); - if (!service || !service->is_enabled()) - return NULL; - return service; -} + MaybeCallJavascript("updateAboutResource", std::move(data)); + } -drive::DriveServiceInterface* DriveInternalsWebUIHandler::GetDriveService() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + void UpdateDeltaUpdateStatusSection() { + if (IsDriveFsEnabled()) { + // TODO(crbug.com/896123): Maybe worth implementing. + SetSectionEnabled("delta-update-status-section", false); + return; + } - Profile* profile = Profile::FromWebUI(web_ui()); - return drive::util::GetDriveServiceByProfile(profile); -} + SetSectionEnabled("delta-update-status-section", true); + auto* debug_info_collector = GetDebugInfoCollector(); + if (debug_info_collector) { + debug_info_collector->GetMetadata(base::Bind( + &DriveInternalsWebUIHandler::OnGetFilesystemMetadataForDeltaUpdate, + weak_ptr_factory_.GetWeakPtr())); + } + } -drive::DebugInfoCollector* DriveInternalsWebUIHandler::GetDebugInfoCollector() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + // Callback for DebugInfoCollector::GetMetadata for delta update. + void OnGetFilesystemMetadataForDeltaUpdate( + const drive::FileSystemMetadata& metadata, + const std::map<std::string, drive::FileSystemMetadata>& + team_drive_metadata) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + 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"); - drive::DriveIntegrationService* integration_service = GetIntegrationService(); - return integration_service ? - integration_service->debug_info_collector() : NULL; -} + items->Append(std::move(app_data)); -void DriveInternalsWebUIHandler::OnPageLoaded(const base::ListValue* args) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + 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)); + } - drive::DriveIntegrationService* integration_service = - GetIntegrationService(); - // |integration_service| may be NULL in the guest/incognito mode. - if (!integration_service) - return; - - UpdateDriveRelatedPreferencesSection(); - UpdateGCacheContentsSection(); - UpdateLocalStorageUsageSection(); - UpdatePathConfigurationsSection(); - - drive::DriveServiceInterface* drive_service = - integration_service->drive_service(); - if (drive_service) { - UpdateConnectionStatusSection(drive_service); - UpdateAboutResourceSection(drive_service); - } - - drive::DebugInfoCollector* debug_info_collector = - integration_service->debug_info_collector(); - if (debug_info_collector) { - UpdateDeltaUpdateStatusSection(debug_info_collector); - UpdateCacheContentsSection(debug_info_collector); - } - - 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 - // is called again). In that case, we have to forget the last sent ID here, - // and resent whole the logs to the page. - last_sent_event_id_ = -1; - UpdateEventLogSection(); - last_sent_line_number_ = 0; - service_log_file_inode_ = 0; - UpdateServiceLogSection(); -} + base::DictionaryValue delta_update_status; + delta_update_status.Set("items", std::move(items)); -void DriveInternalsWebUIHandler::UpdateDriveRelatedPreferencesSection() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + MaybeCallJavascript("updateDeltaUpdateStatus", + std::move(delta_update_status)); + } - const char* kDriveRelatedPreferences[] = { - drive::prefs::kDisableDrive, - drive::prefs::kDisableDriveOverCellular, - drive::prefs::kDisableDriveHostedFiles, - }; + void UpdateInFlightOperationsSection() { + if (IsDriveFsEnabled()) { + // TODO(crbug.com/896123): Maybe worth implementing. + SetSectionEnabled("in-flight-operations-section", false); + return; + } - Profile* profile = Profile::FromWebUI(web_ui()); - PrefService* pref_service = profile->GetPrefs(); + SetSectionEnabled("in-flight-operations-section", true); + auto* integration_service = GetIntegrationService(); + if (!integration_service) + return; + drive::JobListInterface* job_list = integration_service->job_list(); + if (!job_list) + return; + std::vector<drive::JobInfo> info_list = job_list->GetJobInfoList(); + + base::ListValue in_flight_operations; + for (size_t i = 0; i < info_list.size(); ++i) { + const drive::JobInfo& info = info_list[i]; + + auto dict = std::make_unique<base::DictionaryValue>(); + dict->SetInteger("id", info.job_id); + dict->SetString("type", drive::JobTypeToString(info.job_type)); + dict->SetString("file_path", info.file_path.AsUTF8Unsafe()); + dict->SetString("state", drive::JobStateToString(info.state)); + dict->SetDouble("progress_current", info.num_completed_bytes); + dict->SetDouble("progress_total", info.num_total_bytes); + in_flight_operations.Append(std::move(dict)); + } - base::ListValue preferences; - for (size_t i = 0; i < arraysize(kDriveRelatedPreferences); ++i) { - const std::string key = kDriveRelatedPreferences[i]; - // As of now, all preferences are boolean. - const std::string value = - (pref_service->GetBoolean(key.c_str()) ? "true" : "false"); - AppendKeyValue(&preferences, key, value); + MaybeCallJavascript("updateInFlightOperations", + std::move(in_flight_operations)); } - web_ui()->CallJavascriptFunctionUnsafe("updateDriveRelatedPreferences", - preferences); -} - -void DriveInternalsWebUIHandler::UpdateConnectionStatusSection( - drive::DriveServiceInterface* drive_service) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(drive_service); - - std::string status; - switch (drive::util::GetDriveConnectionStatus(Profile::FromWebUI(web_ui()))) { - case drive::util::DRIVE_DISCONNECTED_NOSERVICE: - status = "no service"; - break; - case drive::util::DRIVE_DISCONNECTED_NONETWORK: - status = "no network"; - break; - case drive::util::DRIVE_DISCONNECTED_NOTREADY: - status = "not ready"; - break; - case drive::util::DRIVE_CONNECTED_METERED: - status = "metered"; - break; - case drive::util::DRIVE_CONNECTED: - status = "connected"; - break; - } - - base::DictionaryValue connection_status; - connection_status.SetString("status", status); - connection_status.SetBoolean("has-refresh-token", - drive_service->HasRefreshToken()); - connection_status.SetBoolean("has-access-token", - drive_service->HasAccessToken()); - web_ui()->CallJavascriptFunctionUnsafe("updateConnectionStatus", - connection_status); -} + void UpdateFileSystemContentsSection() { + if (IsDriveFsEnabled()) { + SetSectionEnabled("file-system-contents-section", false); + return; + } -void DriveInternalsWebUIHandler::UpdateAboutResourceSection( - drive::DriveServiceInterface* drive_service) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(drive_service); + SetSectionEnabled("file-system-contents-section", true); + drive::DebugInfoCollector* debug_info_collector = GetDebugInfoCollector(); + if (!debug_info_collector) + return; - drive_service->GetAboutResource( - base::Bind(&DriveInternalsWebUIHandler::OnGetAboutResource, - weak_ptr_factory_.GetWeakPtr())); -} + // Start rendering the file system tree as text. + const base::FilePath root_path = drive::util::GetDriveGrandRootPath(); -void DriveInternalsWebUIHandler::ClearAccessToken(const base::ListValue* args) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + debug_info_collector->GetResourceEntry( + root_path, + base::BindOnce(&DriveInternalsWebUIHandler::OnGetResourceEntryByPath, + weak_ptr_factory_.GetWeakPtr(), root_path)); - drive::DriveServiceInterface* drive_service = GetDriveService(); - if (drive_service) - drive_service->ClearAccessToken(); -} + debug_info_collector->ReadDirectory( + root_path, + base::Bind(&DriveInternalsWebUIHandler::OnReadDirectoryByPath, + weak_ptr_factory_.GetWeakPtr(), root_path)); + } -void DriveInternalsWebUIHandler::ClearRefreshToken( - const base::ListValue* args) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + // Called when GetResourceEntryByPath() is complete. + void OnGetResourceEntryByPath(const base::FilePath& path, + drive::FileError error, + std::unique_ptr<drive::ResourceEntry> entry) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); - drive::DriveServiceInterface* drive_service = GetDriveService(); - if (drive_service) - drive_service->ClearRefreshToken(); -} + if (error == drive::FILE_ERROR_OK) { + DCHECK(entry.get()); + MaybeCallJavascript("updateFileSystemContents", + base::Value(FormatEntry(path, *entry) + "\n")); + } + } -void DriveInternalsWebUIHandler::ResetDriveFileSystem( - const base::ListValue* args) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + // Called when ReadDirectoryByPath() is complete. + void OnReadDirectoryByPath( + const base::FilePath& parent_path, + drive::FileError error, + std::unique_ptr<drive::ResourceEntryVector> entries) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + if (error == drive::FILE_ERROR_OK) { + DCHECK(entries.get()); + + drive::DebugInfoCollector* debug_info_collector = GetDebugInfoCollector(); + std::string file_system_as_text; + for (size_t i = 0; i < entries->size(); ++i) { + const drive::ResourceEntry& entry = (*entries)[i]; + const base::FilePath current_path = parent_path.Append( + base::FilePath::FromUTF8Unsafe(entry.base_name())); + + file_system_as_text.append(FormatEntry(current_path, entry) + "\n"); + + if (entry.file_info().is_directory()) { + debug_info_collector->ReadDirectory( + current_path, + base::Bind(&DriveInternalsWebUIHandler::OnReadDirectoryByPath, + weak_ptr_factory_.GetWeakPtr(), current_path)); + } + } - drive::DriveIntegrationService* integration_service = - GetIntegrationService(); - if (integration_service) { - integration_service->ClearCacheAndRemountFileSystem( - base::Bind(&DriveInternalsWebUIHandler::ResetFinished, - weak_ptr_factory_.GetWeakPtr())); + // There may be pending ReadDirectoryByPath() calls, but we can update + // the page with what we have now. This results in progressive + // updates, which is good for a large file system. + MaybeCallJavascript("updateFileSystemContents", + base::Value(file_system_as_text)); + } } -} - -void DriveInternalsWebUIHandler::ResetFinished(bool success) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - web_ui()->CallJavascriptFunctionUnsafe("updateResetStatus", - base::Value(success)); -} + void UpdatePathConfigurationsSection() { + SetSectionEnabled("path-configurations-section", true); + + base::ListValue paths; + AppendKeyValue(&paths, "Downloads", + file_manager::util::GetDownloadsFolderForProfile(profile()) + .AsUTF8Unsafe()); + const auto* integration_service = GetIntegrationService(); + if (integration_service) { + AppendKeyValue(&paths, "Drive", + integration_service->GetMountPointPath().AsUTF8Unsafe()); + } -void DriveInternalsWebUIHandler::ListFileEntries(const base::ListValue* args) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + const char* kPathPreferences[] = { + prefs::kSelectFileLastDirectory, prefs::kSaveFileDefaultDirectory, + prefs::kDownloadDefaultDirectory, + }; + for (size_t i = 0; i < base::size(kPathPreferences); ++i) { + const char* const key = kPathPreferences[i]; + AppendKeyValue(&paths, key, + profile()->GetPrefs()->GetFilePath(key).AsUTF8Unsafe()); + } - UpdateFileSystemContentsSection(); -} + MaybeCallJavascript("updatePathConfigurations", std::move(paths)); + } -void DriveInternalsWebUIHandler::UpdateDeltaUpdateStatusSection( - drive::DebugInfoCollector* debug_info_collector) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(debug_info_collector); + void UpdateLocalStorageUsageSection() { + SetSectionEnabled("local-metadata-section", true); + + // Propagate the amount of local free space in bytes. + base::FilePath home_path; + if (base::PathService::Get(base::DIR_HOME, &home_path)) { + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::BindOnce(&base::SysInfo::AmountOfFreeDiskSpace, home_path), + base::BindOnce(&DriveInternalsWebUIHandler::OnGetFreeDiskSpace, + weak_ptr_factory_.GetWeakPtr())); + } else { + LOG(ERROR) << "Home directory not found"; + } + } - debug_info_collector->GetMetadata( - base::Bind( - &DriveInternalsWebUIHandler::OnGetFilesystemMetadataForDeltaUpdate, - weak_ptr_factory_.GetWeakPtr())); -} + // Called when AmountOfFreeDiskSpace() is complete. + void OnGetFreeDiskSpace(int64_t free_space) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + base::DictionaryValue local_storage_summary; + local_storage_summary.SetDouble("free_space", free_space); + MaybeCallJavascript("updateLocalStorageUsage", + std::move(local_storage_summary)); + } -void DriveInternalsWebUIHandler::OnGetFilesystemMetadataForDeltaUpdate( - const drive::FileSystemMetadata& metadata, - const std::map<std::string, drive::FileSystemMetadata>& - team_drive_metadata) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + void UpdateDriveRelatedPreferencesSection() { + SetSectionEnabled("drive-related-preferences-section", true); + + const char* kDriveRelatedPreferences[] = { + drive::prefs::kDisableDrive, + drive::prefs::kDisableDriveOverCellular, + drive::prefs::kDriveFsWasLaunchedAtLeastOnce, + drive::prefs::kDriveFsPinnedMigrated, + }; + + PrefService* pref_service = profile()->GetPrefs(); + + base::ListValue preferences; + AppendKeyValue(&preferences, "DriveFS", + IsDriveFsEnabled() ? "true" : "false"); + for (size_t i = 0; i < base::size(kDriveRelatedPreferences); ++i) { + const std::string key = kDriveRelatedPreferences[i]; + // As of now, all preferences are boolean. + const std::string value = + (pref_service->GetBoolean(key.c_str()) ? "true" : "false"); + AppendKeyValue(&preferences, key, value); + } - Profile* profile = Profile::FromWebUI(web_ui()); - drive::DriveNotificationManager* drive_notification_manager = - drive::DriveNotificationManagerFactory::FindForBrowserContext(profile); - if (!drive_notification_manager) - return; - - base::DictionaryValue delta_update_status; - delta_update_status.SetBoolean( - "push-notification-enabled", - drive_notification_manager->push_notification_enabled()); - - 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)); + MaybeCallJavascript("updateDriveRelatedPreferences", + std::move(preferences)); } - delta_update_status.Set("items", std::move(items)); + void UpdateEventLogSection() { + SetSectionEnabled("event-log-section", true); - web_ui()->CallJavascriptFunctionUnsafe("updateDeltaUpdateStatus", - delta_update_status); -} - -void DriveInternalsWebUIHandler::UpdateInFlightOperationsSection( - drive::JobListInterface* job_list) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(job_list); + drive::DriveIntegrationService* integration_service = + GetIntegrationService(); + if (!integration_service) + return; - std::vector<drive::JobInfo> info_list = job_list->GetJobInfoList(); + const std::vector<drive::EventLogger::Event> log = + integration_service->event_logger()->GetHistory(); - base::ListValue in_flight_operations; - for (size_t i = 0; i < info_list.size(); ++i) { - const drive::JobInfo& info = info_list[i]; + base::ListValue list; + for (size_t i = 0; i < log.size(); ++i) { + // Skip events which were already sent. + if (log[i].id <= last_sent_event_id_) + continue; - auto dict = std::make_unique<base::DictionaryValue>(); - dict->SetInteger("id", info.job_id); - dict->SetString("type", drive::JobTypeToString(info.job_type)); - dict->SetString("file_path", info.file_path.AsUTF8Unsafe()); - dict->SetString("state", drive::JobStateToString(info.state)); - dict->SetDouble("progress_current", info.num_completed_bytes); - dict->SetDouble("progress_total", info.num_total_bytes); - in_flight_operations.Append(std::move(dict)); + const char* const severity = + kLogLevelName[SeverityToLogLevelNameIndex(log[i].severity)]; + AppendKeyValue( + &list, google_apis::util::FormatTimeAsStringLocaltime(log[i].when), + base::StrCat({"[", severity, "] ", log[i].what}), + base::StrCat({"log-", severity})); + last_sent_event_id_ = log[i].id; + } + if (!list.empty()) { + MaybeCallJavascript("updateEventLog", std::move(list)); + } } - web_ui()->CallJavascriptFunctionUnsafe("updateInFlightOperations", - in_flight_operations); -} -void DriveInternalsWebUIHandler::UpdateGCacheContentsSection() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + void UpdateServiceLogSection() { + if (!IsDriveFsEnabled()) { + SetSectionEnabled("service-log-section", false); + return; + } + SetSectionEnabled("service-log-section", true); - // Start updating the GCache contents section. - Profile* profile = Profile::FromWebUI(web_ui()); - const base::FilePath root_path = - drive::util::GetCacheRootPath(profile).DirName(); - base::ListValue* gcache_contents = new base::ListValue; - base::DictionaryValue* gcache_summary = new base::DictionaryValue; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::BindOnce(&GetGCacheContents, root_path, gcache_contents, - gcache_summary), - base::BindOnce(&DriveInternalsWebUIHandler::OnGetGCacheContents, - weak_ptr_factory_.GetWeakPtr(), - base::Owned(gcache_contents), - base::Owned(gcache_summary))); -} + if (service_log_file_is_processing_) + return; + service_log_file_is_processing_ = true; -void DriveInternalsWebUIHandler::UpdateFileSystemContentsSection() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + drive::DriveIntegrationService* integration_service = + GetIntegrationService(); + if (!integration_service) + return; + base::FilePath log_path = integration_service->GetDriveFsLogPath(); + if (log_path.empty()) + return; - drive::DebugInfoCollector* debug_info_collector = GetDebugInfoCollector(); - if (!debug_info_collector) - return; + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::BindOnce(&GetServiceLogContents, log_path, + service_log_file_inode_, last_sent_line_number_), + base::BindOnce(&DriveInternalsWebUIHandler::OnServiceLogRead, + weak_ptr_factory_.GetWeakPtr())); + } - // Start rendering the file system tree as text. - const base::FilePath root_path = drive::util::GetDriveGrandRootPath(); + // Called when service logs are read. + void OnServiceLogRead(std::pair<ino_t, base::ListValue> response) { + if (service_log_file_inode_ != response.first) { + service_log_file_inode_ = response.first; + last_sent_line_number_ = 0; + } + if (!response.second.empty()) { + last_sent_line_number_ += response.second.GetList().size(); + MaybeCallJavascript("updateServiceLog", std::move(response.second)); + } + service_log_file_is_processing_ = false; + } - debug_info_collector->GetResourceEntry( - root_path, - base::BindOnce(&DriveInternalsWebUIHandler::OnGetResourceEntryByPath, - weak_ptr_factory_.GetWeakPtr(), root_path)); + void UpdateCacheContentsSection() { + if (IsDriveFsEnabled()) { + // TODO(crbug.com/896123): Maybe worth implementing. + SetSectionEnabled("cache-contents-section", false); + return; + } + SetSectionEnabled("cache-contents-section", true); + + auto* debug_info_collector = GetDebugInfoCollector(); + if (debug_info_collector) { + debug_info_collector->IterateFileCache( + base::Bind(&DriveInternalsWebUIHandler::OnUpdateCacheEntry, + weak_ptr_factory_.GetWeakPtr()), + base::DoNothing()); + } + } - debug_info_collector->ReadDirectory( - root_path, - base::Bind(&DriveInternalsWebUIHandler::OnReadDirectoryByPath, - weak_ptr_factory_.GetWeakPtr(), - root_path)); -} + // Called as the iterator for DebugInfoCollector::IterateFileCache(). + void OnUpdateCacheEntry(const std::string& local_id, + const drive::FileCacheEntry& cache_entry) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + // Convert |cache_entry| into a dictionary. + base::DictionaryValue value; + value.SetString("local_id", local_id); + value.SetString("md5", cache_entry.md5()); + value.SetBoolean("is_present", cache_entry.is_present()); + value.SetBoolean("is_pinned", cache_entry.is_pinned()); + value.SetBoolean("is_dirty", cache_entry.is_dirty()); + + MaybeCallJavascript("updateCacheContents", std::move(value)); + } -void DriveInternalsWebUIHandler::UpdateLocalStorageUsageSection() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + void UpdateGCacheContentsSection() { + SetSectionEnabled("gcache-contents-section", true); - // Propagate the amount of local free space in bytes. - base::FilePath home_path; - if (base::PathService::Get(base::DIR_HOME, &home_path)) { - base::DictionaryValue* local_storage_summary = new base::DictionaryValue; - base::PostTaskWithTraitsAndReply( + const base::FilePath root_path = + drive::util::GetCacheRootPath(profile()).DirName(); + base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::BindOnce(&GetFreeDiskSpace, home_path, local_storage_summary), - base::BindOnce(&DriveInternalsWebUIHandler::OnGetFreeDiskSpace, - weak_ptr_factory_.GetWeakPtr(), - base::Owned(local_storage_summary))); - } else { - LOG(ERROR) << "Home directory not found"; + base::BindOnce(&GetGCacheContents, root_path), + base::BindOnce(&DriveInternalsWebUIHandler::OnGetGCacheContents, + weak_ptr_factory_.GetWeakPtr())); } -} -void DriveInternalsWebUIHandler::UpdateCacheContentsSection( - drive::DebugInfoCollector* debug_info_collector) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(debug_info_collector); + // Called when GetGCacheContents() is complete. + void OnGetGCacheContents( + std::pair<base::ListValue, base::DictionaryValue> response) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + MaybeCallJavascript("updateGCacheContents", std::move(response.first), + std::move(response.second)); + } - debug_info_collector->IterateFileCache( - base::Bind(&DriveInternalsWebUIHandler::UpdateCacheEntry, - weak_ptr_factory_.GetWeakPtr()), - base::DoNothing()); -} + // Called when the corresponding button on the page is pressed. + void ClearAccessToken(const base::ListValue* args) { + AllowJavascript(); -void DriveInternalsWebUIHandler::UpdateEventLogSection() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + drive::DriveServiceInterface* drive_service = GetDriveService(); + if (drive_service) + drive_service->ClearAccessToken(); + } - drive::DriveIntegrationService* integration_service = - GetIntegrationService(); - if (!integration_service) - return; - - const std::vector<drive::EventLogger::Event> log = - integration_service->event_logger()->GetHistory(); - - base::ListValue list; - for (size_t i = 0; i < log.size(); ++i) { - // Skip events which were already sent. - if (log[i].id <= last_sent_event_id_) - continue; - - const char* const severity = - kLogLevelName[SeverityToLogLevelNameIndex(log[i].severity)]; - AppendKeyValue(&list, - google_apis::util::FormatTimeAsStringLocaltime(log[i].when), - base::StrCat({"[", severity, "] ", log[i].what}), - base::StrCat({"log-", severity})); - last_sent_event_id_ = log[i].id; - } - if (!list.empty()) - web_ui()->CallJavascriptFunctionUnsafe("updateEventLog", list); -} + // Called when the corresponding button on the page is pressed. + void ClearRefreshToken(const base::ListValue* args) { + AllowJavascript(); -void DriveInternalsWebUIHandler::UpdateServiceLogSection() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + drive::DriveServiceInterface* drive_service = GetDriveService(); + if (drive_service) + drive_service->ClearRefreshToken(); + } - if (service_log_file_is_processing_) - return; - service_log_file_is_processing_ = true; - - drive::DriveIntegrationService* integration_service = GetIntegrationService(); - if (!integration_service) - return; - base::FilePath log_path = integration_service->GetDriveFsLogPath(); - if (log_path.empty()) - return; - - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::BindOnce(&GetServiceLogContents, log_path, service_log_file_inode_, - last_sent_line_number_), - base::BindOnce(&DriveInternalsWebUIHandler::OnServiceLogRead, + // Called when the corresponding button on the page is pressed. + void ResetDriveFileSystem(const base::ListValue* args) { + AllowJavascript(); + + drive::DriveIntegrationService* integration_service = + GetIntegrationService(); + if (integration_service) { + integration_service->ClearCacheAndRemountFileSystem( + base::Bind(&DriveInternalsWebUIHandler::ResetFinished, weak_ptr_factory_.GetWeakPtr())); -} - -void DriveInternalsWebUIHandler::OnServiceLogRead( - std::pair<ino_t, base::ListValue> response) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (service_log_file_inode_ != response.first) { - service_log_file_inode_ = response.first; - last_sent_line_number_ = 0; - } - if (!response.second.empty()) { - web_ui()->CallJavascriptFunctionUnsafe("updateServiceLog", response.second); - last_sent_line_number_ += response.second.GetList().size(); + } } - service_log_file_is_processing_ = false; -} - -void DriveInternalsWebUIHandler::UpdatePathConfigurationsSection() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - Profile* const profile = Profile::FromWebUI(web_ui()); - base::ListValue paths; + // Called when the corresponding button on the page is pressed. + void ListFileEntries(const base::ListValue* args) { + AllowJavascript(); - AppendKeyValue( - &paths, "Downloads", - file_manager::util::GetDownloadsFolderForProfile(profile).AsUTF8Unsafe()); - const auto* integration_service = GetIntegrationService(); - if (integration_service) { - AppendKeyValue(&paths, "Drive", - integration_service->GetMountPointPath().AsUTF8Unsafe()); + UpdateFileSystemContentsSection(); } - const char* kPathPreferences[] = { - prefs::kSelectFileLastDirectory, - prefs::kSaveFileDefaultDirectory, - prefs::kDownloadDefaultDirectory, - }; - for (size_t i = 0; i < arraysize(kPathPreferences); ++i) { - const char* const key = kPathPreferences[i]; - AppendKeyValue(&paths, key, - profile->GetPrefs()->GetFilePath(key).AsUTF8Unsafe()); + // Called after file system reset for ResetDriveFileSystem is done. + void ResetFinished(bool success) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + MaybeCallJavascript("updateResetStatus", base::Value(success)); } - web_ui()->CallJavascriptFunctionUnsafe("updatePathConfigurations", paths); -} - -void DriveInternalsWebUIHandler::OnGetGCacheContents( - base::ListValue* gcache_contents, - base::DictionaryValue* gcache_summary) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(gcache_contents); - DCHECK(gcache_summary); + Profile* profile() { return Profile::FromWebUI(web_ui()); } - web_ui()->CallJavascriptFunctionUnsafe("updateGCacheContents", - *gcache_contents, *gcache_summary); -} - -void DriveInternalsWebUIHandler::OnGetResourceEntryByPath( - const base::FilePath& path, - drive::FileError error, - std::unique_ptr<drive::ResourceEntry> entry) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (error == drive::FILE_ERROR_OK) { - DCHECK(entry.get()); - const base::Value value(FormatEntry(path, *entry) + "\n"); - web_ui()->CallJavascriptFunctionUnsafe("updateFileSystemContents", value); + // Returns a DriveIntegrationService. + drive::DriveIntegrationService* GetIntegrationService() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + drive::DriveIntegrationService* service = + drive::DriveIntegrationServiceFactory::FindForProfile(profile()); + if (!service || !service->is_enabled()) + return NULL; + return service; } -} - -void DriveInternalsWebUIHandler::OnReadDirectoryByPath( - const base::FilePath& parent_path, - drive::FileError error, - std::unique_ptr<drive::ResourceEntryVector> entries) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (error == drive::FILE_ERROR_OK) { - DCHECK(entries.get()); - - drive::DebugInfoCollector* debug_info_collector = GetDebugInfoCollector(); - std::string file_system_as_text; - for (size_t i = 0; i < entries->size(); ++i) { - const drive::ResourceEntry& entry = (*entries)[i]; - const base::FilePath current_path = parent_path.Append( - base::FilePath::FromUTF8Unsafe(entry.base_name())); - - file_system_as_text.append(FormatEntry(current_path, entry) + "\n"); - - if (entry.file_info().is_directory()) { - debug_info_collector->ReadDirectory( - current_path, - base::Bind(&DriveInternalsWebUIHandler::OnReadDirectoryByPath, - weak_ptr_factory_.GetWeakPtr(), - current_path)); - } - } - - // There may be pending ReadDirectoryByPath() calls, but we can update - // the page with what we have now. This results in progressive - // updates, which is good for a large file system. - const base::Value value(file_system_as_text); - web_ui()->CallJavascriptFunctionUnsafe("updateFileSystemContents", value); + // Returns a DriveService instance. + drive::DriveServiceInterface* GetDriveService() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + return drive::util::GetDriveServiceByProfile(profile()); } -} -void DriveInternalsWebUIHandler::UpdateCacheEntry( - const std::string& local_id, - const drive::FileCacheEntry& cache_entry) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - // Convert |cache_entry| into a dictionary. - base::DictionaryValue value; - value.SetString("local_id", local_id); - value.SetString("md5", cache_entry.md5()); - value.SetBoolean("is_present", cache_entry.is_present()); - value.SetBoolean("is_pinned", cache_entry.is_pinned()); - value.SetBoolean("is_dirty", cache_entry.is_dirty()); - - web_ui()->CallJavascriptFunctionUnsafe("updateCacheContents", value); -} + // Returns a DebugInfoCollector instance. + drive::DebugInfoCollector* GetDebugInfoCollector() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + drive::DriveIntegrationService* service = GetIntegrationService(); + return service ? service->debug_info_collector() : NULL; + } -void DriveInternalsWebUIHandler::OnGetFreeDiskSpace( - base::DictionaryValue* local_storage_summary) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(local_storage_summary); + // Whether DriveFS is enabled. + bool IsDriveFsEnabled() { + return base::FeatureList::IsEnabled(chromeos::features::kDriveFs); + } - web_ui()->CallJavascriptFunctionUnsafe("updateLocalStorageUsage", - *local_storage_summary); -} + // The last event sent to the JavaScript side. + int last_sent_event_id_; -void DriveInternalsWebUIHandler::OnPeriodicUpdate(const base::ListValue* args) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + // The last line of service log sent to the JS side. + int last_sent_line_number_; - drive::DriveIntegrationService* integration_service = - GetIntegrationService(); - // |integration_service| may be NULL in the guest/incognito mode. - if (!integration_service) - return; + // The inode of the log file. + ino_t service_log_file_inode_; - UpdateEventLogSection(); - UpdateServiceLogSection(); + // Service log file is being parsed. + bool service_log_file_is_processing_ = false; - drive::JobListInterface* job_list = integration_service->job_list(); - if (job_list) { - UpdateInFlightOperationsSection(job_list); - } -} + base::WeakPtrFactory<DriveInternalsWebUIHandler> weak_ptr_factory_; + DISALLOW_COPY_AND_ASSIGN(DriveInternalsWebUIHandler); +}; } // namespace diff --git a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc index 97562f89390..5b5c071700f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc @@ -4,7 +4,6 @@ #include "chrome/browser/ui/webui/chromeos/first_run/first_run_handler.h" -#include "ash/public/cpp/ash_features.h" #include "base/bind.h" #include "base/values.h" #include "chromeos/chromeos_switches.h" @@ -51,8 +50,6 @@ void FirstRunHandler::ShowStepPositioned(const std::string& name, step_params.SetKey( "voiceInteractionEnabled", base::Value(chromeos::switches::IsVoiceInteractionEnabled())); - step_params.SetKey("unifiedSystemTrayEnabled", - base::Value(ash::features::IsSystemTrayUnifiedEnabled())); web_ui()->CallJavascriptFunctionUnsafe("cr.FirstRun.showStep", step_params); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc deleted file mode 100644 index 3e457ff2461..00000000000 --- a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc +++ /dev/null @@ -1,465 +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/keyboard_overlay_ui.h" - -#include <stddef.h> - -#include <memory> - -#include "ash/shell.h" -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/command_line.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/strings/utf_string_conversions.h" -#include "base/values.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/url_constants.h" -#include "chrome/grit/browser_resources.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "chromeos/chromeos_switches.h" -#include "components/prefs/pref_service.h" -#include "components/strings/grit/components_strings.h" -#include "content/public/browser/page_navigator.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_contents_delegate.h" -#include "content/public/browser/web_ui.h" -#include "content/public/browser/web_ui_data_source.h" -#include "content/public/browser/web_ui_message_handler.h" -#include "ui/base/ime/chromeos/input_method_manager.h" -#include "ui/chromeos/events/keyboard_layout_util.h" -#include "ui/chromeos/events/modifier_key.h" -#include "ui/chromeos/events/pref_names.h" -#include "ui/display/manager/display_manager.h" - -using content::WebUIMessageHandler; -using ui::chromeos::ModifierKey; -using ui::WebDialogUI; - -namespace { - -const char kLearnMoreURL[] = -#if defined(OFFICIAL_BUILD) - "chrome-extension://honijodknafkokifofgiaalefdiedpko/" - "main.html?answer=1047364"; -#else - "https://support.google.com/chromebook/answer/183101"; -#endif - -struct ModifierToLabel { - const ModifierKey modifier; - const char* label; -} kModifierToLabels[] = { - {ModifierKey::kSearchKey, "search"}, - {ModifierKey::kControlKey, "ctrl"}, - {ModifierKey::kAltKey, "alt"}, - {ModifierKey::kVoidKey, "disabled"}, - {ModifierKey::kCapsLockKey, "caps lock"}, - {ModifierKey::kEscapeKey, "esc"}, - {ModifierKey::kBackspaceKey, "backspace"}, -}; - -struct I18nContentToMessage { - const char* i18n_content; - int message; -} kI18nContentToMessage[] = { - {"keyboardOverlayAssistantKeyLabel", - IDS_KEYBOARD_OVERLAY_ASSISTANT_KEY_LABEL}, - {"keyboardOverlayPlayPauseKeyLabel", - IDS_KEYBOARD_OVERLAY_PLAY_PAUSE_KEY_LABEL}, - {"keyboardOverlaySystemMenuKeyLabel", - IDS_KEYBOARD_OVERLAY_SYSTEM_MENU_KEY_LABEL}, - {"keyboardOverlayLauncherKeyLabel", - IDS_KEYBOARD_OVERLAY_LAUNCHER_KEY_LABEL}, - {"keyboardOverlayLearnMore", IDS_LEARN_MORE}, - {"keyboardOverlayTitle", IDS_KEYBOARD_OVERLAY_TITLE}, - {"keyboardOverlayEscKeyLabel", IDS_KEYBOARD_OVERLAY_ESC_KEY_LABEL}, - {"keyboardOverlayBackKeyLabel", IDS_KEYBOARD_OVERLAY_BACK_KEY_LABEL}, - {"keyboardOverlayForwardKeyLabel", IDS_KEYBOARD_OVERLAY_FORWARD_KEY_LABEL}, - {"keyboardOverlayReloadKeyLabel", IDS_KEYBOARD_OVERLAY_RELOAD_KEY_LABEL}, - {"keyboardOverlayFullScreenKeyLabel", - IDS_KEYBOARD_OVERLAY_FULL_SCREEN_KEY_LABEL}, - {"keyboardOverlaySwitchWinKeyLabel", - IDS_KEYBOARD_OVERLAY_SWITCH_WIN_KEY_LABEL}, - {"keyboardOverlayBrightDownKeyLabel", - IDS_KEYBOARD_OVERLAY_BRIGHT_DOWN_KEY_LABEL}, - {"keyboardOverlayBrightUpKeyLabel", - IDS_KEYBOARD_OVERLAY_BRIGHT_UP_KEY_LABEL}, - {"keyboardOverlayMuteKeyLabel", IDS_KEYBOARD_OVERLAY_MUTE_KEY_LABEL}, - {"keyboardOverlayVolDownKeyLabel", IDS_KEYBOARD_OVERLAY_VOL_DOWN_KEY_LABEL}, - {"keyboardOverlayVolUpKeyLabel", IDS_KEYBOARD_OVERLAY_VOL_UP_KEY_LABEL}, - {"keyboardOverlayPowerKeyLabel", IDS_KEYBOARD_OVERLAY_POWER_KEY_LABEL}, - {"keyboardOverlayBackspaceKeyLabel", - IDS_KEYBOARD_OVERLAY_BACKSPACE_KEY_LABEL}, - {"keyboardOverlayTabKeyLabel", IDS_KEYBOARD_OVERLAY_TAB_KEY_LABEL}, - {"keyboardOverlaySearchKeyLabel", IDS_KEYBOARD_OVERLAY_SEARCH_KEY_LABEL}, - {"keyboardOverlayEnterKeyLabel", IDS_KEYBOARD_OVERLAY_ENTER_KEY_LABEL}, - {"keyboardOverlayShiftKeyLabel", IDS_KEYBOARD_OVERLAY_SHIFT_KEY_LABEL}, - {"keyboardOverlayCtrlKeyLabel", IDS_KEYBOARD_OVERLAY_CTRL_KEY_LABEL}, - {"keyboardOverlayAltKeyLabel", IDS_KEYBOARD_OVERLAY_ALT_KEY_LABEL}, - {"keyboardOverlayLeftKeyLabel", IDS_KEYBOARD_OVERLAY_LEFT_KEY_LABEL}, - {"keyboardOverlayRightKeyLabel", IDS_KEYBOARD_OVERLAY_RIGHT_KEY_LABEL}, - {"keyboardOverlayUpKeyLabel", IDS_KEYBOARD_OVERLAY_UP_KEY_LABEL}, - {"keyboardOverlayDownKeyLabel", IDS_KEYBOARD_OVERLAY_DOWN_KEY_LABEL}, - {"keyboardOverlayInstructionsHide", IDS_KEYBOARD_OVERLAY_INSTRUCTIONS_HIDE}, - {"keyboardOverlayActivateLastShelfItem", - IDS_KEYBOARD_OVERLAY_ACTIVATE_LAST_SHELF_ITEM}, - {"keyboardOverlayActivateLastTab", IDS_KEYBOARD_OVERLAY_ACTIVATE_LAST_TAB}, - {"keyboardOverlayActivateShelfItem1", - IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_1}, - {"keyboardOverlayActivateShelfItem2", - IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_2}, - {"keyboardOverlayActivateShelfItem3", - IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_3}, - {"keyboardOverlayActivateShelfItem4", - IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_4}, - {"keyboardOverlayActivateShelfItem5", - IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_5}, - {"keyboardOverlayActivateShelfItem6", - IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_6}, - {"keyboardOverlayActivateShelfItem7", - IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_7}, - {"keyboardOverlayActivateShelfItem8", - IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_8}, - {"keyboardOverlayActivateNextTab", IDS_KEYBOARD_OVERLAY_ACTIVATE_NEXT_TAB}, - {"keyboardOverlayActivatePreviousTab", - IDS_KEYBOARD_OVERLAY_ACTIVATE_PREVIOUS_TAB}, - {"keyboardOverlayActivateTab1", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_1}, - {"keyboardOverlayActivateTab2", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_2}, - {"keyboardOverlayActivateTab3", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_3}, - {"keyboardOverlayActivateTab4", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_4}, - {"keyboardOverlayActivateTab5", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_5}, - {"keyboardOverlayActivateTab6", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_6}, - {"keyboardOverlayActivateTab7", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_7}, - {"keyboardOverlayActivateTab8", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_8}, - {"keyboardOverlayAddWwwAndComAndOpenAddress", - IDS_KEYBOARD_OVERLAY_ADD_WWW_AND_COM_AND_OPEN_ADDRESS}, - {"keyboardOverlayBookmarkAllTabs", IDS_KEYBOARD_OVERLAY_BOOKMARK_ALL_TABS}, - {"keyboardOverlayBookmarkCurrentPage", - IDS_KEYBOARD_OVERLAY_BOOKMARK_CURRENT_PAGE}, - {"keyboardOverlayBookmarkManager", IDS_KEYBOARD_OVERLAY_BOOKMARK_MANAGER}, - {"keyboardOverlayCenterWindow", IDS_KEYBOARD_OVERLAY_CENTER_WINDOW}, - {"keyboardOverlayClearBrowsingDataDialog", - IDS_KEYBOARD_OVERLAY_CLEAR_BROWSING_DATA_DIALOG}, - {"keyboardOverlayCloseTab", IDS_KEYBOARD_OVERLAY_CLOSE_TAB}, - {"keyboardOverlayCloseWindow", IDS_KEYBOARD_OVERLAY_CLOSE_WINDOW}, - {"keyboardOverlayContextMenu", IDS_KEYBOARD_OVERLAY_CONTEXT_MENU}, - {"keyboardOverlayCopy", IDS_KEYBOARD_OVERLAY_COPY}, - {"keyboardOverlayCut", IDS_KEYBOARD_OVERLAY_CUT}, - {"keyboardOverlayCycleThroughInputMethods", - IDS_KEYBOARD_OVERLAY_CYCLE_THROUGH_INPUT_METHODS}, - {"keyboardOverlayDecreaseKeyBrightness", - IDS_KEYBOARD_OVERLAY_DECREASE_KEY_BRIGHTNESS}, - {"keyboardOverlayDelete", IDS_KEYBOARD_OVERLAY_DELETE}, - {"keyboardOverlayDeleteWord", IDS_KEYBOARD_OVERLAY_DELETE_WORD}, - {"keyboardOverlayDeveloperTools", IDS_KEYBOARD_OVERLAY_DEVELOPER_TOOLS}, - {"keyboardOverlayDockWindowLeft", IDS_KEYBOARD_OVERLAY_DOCK_WINDOW_LEFT}, - {"keyboardOverlayDockWindowRight", IDS_KEYBOARD_OVERLAY_DOCK_WINDOW_RIGHT}, - {"keyboardOverlayDomInspector", IDS_KEYBOARD_OVERLAY_DOM_INSPECTOR}, - {"keyboardOverlayDownloads", IDS_KEYBOARD_OVERLAY_DOWNLOADS}, - {"keyboardOverlayEnd", IDS_KEYBOARD_OVERLAY_END}, - {"keyboardOverlayF1", IDS_KEYBOARD_OVERLAY_F1}, - {"keyboardOverlayF10", IDS_KEYBOARD_OVERLAY_F10}, - {"keyboardOverlayF11", IDS_KEYBOARD_OVERLAY_F11}, - {"keyboardOverlayF12", IDS_KEYBOARD_OVERLAY_F12}, - {"keyboardOverlayF2", IDS_KEYBOARD_OVERLAY_F2}, - {"keyboardOverlayF3", IDS_KEYBOARD_OVERLAY_F3}, - {"keyboardOverlayF4", IDS_KEYBOARD_OVERLAY_F4}, - {"keyboardOverlayF5", IDS_KEYBOARD_OVERLAY_F5}, - {"keyboardOverlayF6", IDS_KEYBOARD_OVERLAY_F6}, - {"keyboardOverlayF7", IDS_KEYBOARD_OVERLAY_F7}, - {"keyboardOverlayF8", IDS_KEYBOARD_OVERLAY_F8}, - {"keyboardOverlayF9", IDS_KEYBOARD_OVERLAY_F9}, - {"keyboardOverlayFindPreviousText", - IDS_KEYBOARD_OVERLAY_FIND_PREVIOUS_TEXT}, - {"keyboardOverlayFindText", IDS_KEYBOARD_OVERLAY_FIND_TEXT}, - {"keyboardOverlayFindTextAgain", IDS_KEYBOARD_OVERLAY_FIND_TEXT_AGAIN}, - {"keyboardOverlayFocusAddressBar", IDS_KEYBOARD_OVERLAY_FOCUS_ADDRESS_BAR}, - {"keyboardOverlayFocusAddressBarInSearchMode", - IDS_KEYBOARD_OVERLAY_FOCUS_ADDRESS_BAR_IN_SEARCH_MODE}, - {"keyboardOverlayFocusBookmarks", IDS_KEYBOARD_OVERLAY_FOCUS_BOOKMARKS}, - {"keyboardOverlayFocusShelf", IDS_KEYBOARD_OVERLAY_FOCUS_SHELF}, - {"keyboardOverlayFocusNextPane", IDS_KEYBOARD_OVERLAY_FOCUS_NEXT_PANE}, - {"keyboardOverlayFocusPreviousPane", - IDS_KEYBOARD_OVERLAY_FOCUS_PREVIOUS_PANE}, - {"keyboardOverlayFocusToolbar", IDS_KEYBOARD_OVERLAY_FOCUS_TOOLBAR}, - {"keyboardOverlayGoBack", IDS_KEYBOARD_OVERLAY_GO_BACK}, - {"keyboardOverlayGoForward", IDS_KEYBOARD_OVERLAY_GO_FORWARD}, - {"keyboardOverlayHelp", IDS_KEYBOARD_OVERLAY_HELP}, - {"keyboardOverlayHistory", IDS_KEYBOARD_OVERLAY_HISTORY}, - {"keyboardOverlayHome", IDS_KEYBOARD_OVERLAY_HOME}, - {"keyboardOverlayIncreaseKeyBrightness", - IDS_KEYBOARD_OVERLAY_INCREASE_KEY_BRIGHTNESS}, - {"keyboardOverlayInputUnicodeCharacters", - IDS_KEYBOARD_OVERLAY_INPUT_UNICODE_CHARACTERS}, - {"keyboardOverlayInsert", IDS_KEYBOARD_OVERLAY_INSERT}, - {"keyboardOverlayJavascriptConsole", - IDS_KEYBOARD_OVERLAY_JAVASCRIPT_CONSOLE}, - {"keyboardOverlayLockScreen", IDS_KEYBOARD_OVERLAY_LOCK_SCREEN}, - {"keyboardOverlayLockScreenOrPowerOff", - IDS_KEYBOARD_OVERLAY_LOCK_SCREEN_OR_POWER_OFF}, - {"keyboardOverlayMagnifierDecreaseZoom", - IDS_KEYBOARD_OVERLAY_MAGNIFIER_DECREASE_ZOOM}, - {"keyboardOverlayMagnifierIncreaseZoom", - IDS_KEYBOARD_OVERLAY_MAGNIFIER_INCREASE_ZOOM}, - {"keyboardOverlayMaximizeWindow", IDS_KEYBOARD_OVERLAY_MAXIMIZE_WINDOW}, - {"keyboardOverlayMinimizeWindow", IDS_KEYBOARD_OVERLAY_MINIMIZE_WINDOW}, - {"keyboardOverlayMirrorMonitors", IDS_KEYBOARD_OVERLAY_MIRROR_MONITORS}, - // TODO(warx): keyboard overlay name for move window between displays - // shortcuts need to be updated when new keyboard shortcuts helper is there. - {"keyboardOverlayMoveActiveWindowBetweenDisplays", - IDS_KEYBOARD_OVERLAY_MOVE_ACTIVE_WINDOW_BETWEEN_DISPLAYS}, - {"keyboardOverlayNewIncognitoWindow", - IDS_KEYBOARD_OVERLAY_NEW_INCOGNITO_WINDOW}, - {"keyboardOverlayNewTab", IDS_KEYBOARD_OVERLAY_NEW_TAB}, - {"keyboardOverlayNewTerminal", IDS_KEYBOARD_OVERLAY_NEW_TERMINAL}, - {"keyboardOverlayNewWindow", IDS_KEYBOARD_OVERLAY_NEW_WINDOW}, - {"keyboardOverlayNextUser", IDS_KEYBOARD_OVERLAY_NEXT_USER}, - {"keyboardOverlayNextWindow", IDS_KEYBOARD_OVERLAY_NEXT_WINDOW}, - {"keyboardOverlayNextWord", IDS_KEYBOARD_OVERLAY_NEXT_WORD}, - {"keyboardOverlayOpen", IDS_KEYBOARD_OVERLAY_OPEN}, - {"keyboardOverlayOpenAddressInNewTab", - IDS_KEYBOARD_OVERLAY_OPEN_ADDRESS_IN_NEW_TAB}, - {"keyboardOverlayOpenFileManager", IDS_KEYBOARD_OVERLAY_OPEN_FILE_MANAGER}, - {"keyboardOverlayPageDown", IDS_KEYBOARD_OVERLAY_PAGE_DOWN}, - {"keyboardOverlayPageUp", IDS_KEYBOARD_OVERLAY_PAGE_UP}, - {"keyboardOverlayPaste", IDS_KEYBOARD_OVERLAY_PASTE}, - {"keyboardOverlayPasteAsPlainText", - IDS_KEYBOARD_OVERLAY_PASTE_AS_PLAIN_TEXT}, - {"keyboardOverlayPreviousUser", IDS_KEYBOARD_OVERLAY_PREVIOUS_USER}, - {"keyboardOverlayPreviousWindow", IDS_KEYBOARD_OVERLAY_PREVIOUS_WINDOW}, - {"keyboardOverlayPreviousWord", IDS_KEYBOARD_OVERLAY_PREVIOUS_WORD}, - {"keyboardOverlayPrint", IDS_KEYBOARD_OVERLAY_PRINT}, - {"keyboardOverlayReloadCurrentPage", - IDS_KEYBOARD_OVERLAY_RELOAD_CURRENT_PAGE}, - {"keyboardOverlayReloadBypassingCache", - IDS_KEYBOARD_OVERLAY_RELOAD_BYPASSING_CACHE}, - {"keyboardOverlayReopenLastClosedTab", - IDS_KEYBOARD_OVERLAY_REOPEN_LAST_CLOSED_TAB}, - {"keyboardOverlayReportIssue", IDS_KEYBOARD_OVERLAY_REPORT_ISSUE}, - {"keyboardOverlayResetScreenZoom", IDS_KEYBOARD_OVERLAY_RESET_SCREEN_ZOOM}, - {"keyboardOverlayResetZoom", IDS_KEYBOARD_OVERLAY_RESET_ZOOM}, - {"keyboardOverlayRotateScreen", IDS_KEYBOARD_OVERLAY_ROTATE_SCREEN}, - {"keyboardOverlayRotateWindow", IDS_KEYBOARD_OVERLAY_ROTATE_WINDOW}, - {"keyboardOverlaySave", IDS_KEYBOARD_OVERLAY_SAVE}, - {"keyboardOverlayScreenshotRegion", IDS_KEYBOARD_OVERLAY_SCREENSHOT_REGION}, - {"keyboardOverlayScreenshotWindow", IDS_KEYBOARD_OVERLAY_SCREENSHOT_WINDOW}, - {"keyboardOverlayScrollUpOnePage", IDS_KEYBOARD_OVERLAY_SCROLL_UP_ONE_PAGE}, - {"keyboardOverlaySelectAll", IDS_KEYBOARD_OVERLAY_SELECT_ALL}, - {"keyboardOverlaySelectPreviousInputMethod", - IDS_KEYBOARD_OVERLAY_SELECT_PREVIOUS_INPUT_METHOD}, - {"keyboardOverlaySelectWordAtATime", - IDS_KEYBOARD_OVERLAY_SELECT_WORD_AT_A_TIME}, - {"keyboardOverlayShowImeBubble", IDS_KEYBOARD_OVERLAY_SHOW_IME_BUBBLE}, - {"keyboardOverlayShowMessageCenter", - IDS_KEYBOARD_OVERLAY_SHOW_MESSAGE_CENTER}, - {"keyboardOverlayShowStatusMenu", IDS_KEYBOARD_OVERLAY_SHOW_STATUS_MENU}, - {"keyboardOverlayShowStylusTools", IDS_KEYBOARD_OVERLAY_SHOW_STYLUS_TOOLS}, - {"keyboardOverlayShowWrenchMenu", IDS_KEYBOARD_OVERLAY_SHOW_WRENCH_MENU}, - {"keyboardOverlaySignOut", IDS_KEYBOARD_OVERLAY_SIGN_OUT}, - {"keyboardOverlaySuspend", IDS_KEYBOARD_OVERLAY_SUSPEND}, - {"keyboardOverlaySwapPrimaryMonitor", - IDS_KEYBOARD_OVERLAY_SWAP_PRIMARY_MONITOR}, - {"keyboardOverlayTakeScreenshot", IDS_KEYBOARD_OVERLAY_TAKE_SCREENSHOT}, - {"keyboardOverlayTaskManager", IDS_KEYBOARD_OVERLAY_TASK_MANAGER}, - {"keyboardOverlayToggleBookmarkBar", - IDS_KEYBOARD_OVERLAY_TOGGLE_BOOKMARK_BAR}, - {"keyboardOverlayToggleCapsLock", IDS_KEYBOARD_OVERLAY_TOGGLE_CAPS_LOCK}, - {"keyboardOverlayDisableCapsLock", IDS_KEYBOARD_OVERLAY_DISABLE_CAPS_LOCK}, - {"keyboardOverlayToggleChromevoxSpokenFeedback", - IDS_KEYBOARD_OVERLAY_TOGGLE_CHROMEVOX_SPOKEN_FEEDBACK}, - {"keyboardOverlayToggleDictation", IDS_KEYBOARD_OVERLAY_TOGGLE_DICTATION}, - {"keyboardOverlayToggleDockedMagnifier", - IDS_KEYBOARD_OVERLAY_TOGGLE_DOCKED_MAGNIFIER}, - {"keyboardOverlayToggleFullscreenMagnifier", - IDS_KEYBOARD_OVERLAY_TOGGLE_FULLSCREEN_MAGNIFIER}, - {"keyboardOverlayToggleHighContrastMode", - IDS_KEYBOARD_OVERLAY_TOGGLE_HIGH_CONTRAST_MODE}, - {"keyboardOverlayToggleProjectionTouchHud", - IDS_KEYBOARD_OVERLAY_TOGGLE_PROJECTION_TOUCH_HUD}, - {"keyboardOverlayTouchHudModeChange", - IDS_KEYBOARD_OVERLAY_TOUCH_HUD_MODE_CHANGE}, - {"keyboardOverlayUndo", IDS_KEYBOARD_OVERLAY_UNDO}, - {"keyboardOverlayUnpin", IDS_KEYBOARD_OVERLAY_UNPIN}, - {"keyboardOverlayViewKeyboardOverlay", - IDS_KEYBOARD_OVERLAY_VIEW_KEYBOARD_OVERLAY}, - {"keyboardOverlayViewSource", IDS_KEYBOARD_OVERLAY_VIEW_SOURCE}, - {"keyboardOverlayWordMove", IDS_KEYBOARD_OVERLAY_WORD_MOVE}, - {"keyboardOverlayZoomIn", IDS_KEYBOARD_OVERLAY_ZOOM_IN}, - {"keyboardOverlayZoomOut", IDS_KEYBOARD_OVERLAY_ZOOM_OUT}, - {"keyboardOverlayZoomScreenIn", IDS_KEYBOARD_OVERLAY_ZOOM_SCREEN_IN}, - {"keyboardOverlayZoomScreenOut", IDS_KEYBOARD_OVERLAY_ZOOM_SCREEN_OUT}, - {"keyboardOverlayVoiceInteraction", - IDS_KEYBOARD_OVERLAY_VOICE_INTERACTION}}; - -bool TopRowKeysAreFunctionKeys(Profile* profile) { - if (!profile) - return false; - - const PrefService* prefs = profile->GetPrefs(); - return prefs ? prefs->GetBoolean(prefs::kLanguageSendFunctionKeys) : false; -} - -std::string ModifierKeyToLabel(ModifierKey modifier) { - for (size_t i = 0; i < arraysize(kModifierToLabels); ++i) { - if (modifier == kModifierToLabels[i].modifier) { - return kModifierToLabels[i].label; - } - } - return ""; -} - -content::WebUIDataSource* CreateKeyboardOverlayUIHTMLSource(Profile* profile) { - content::WebUIDataSource* source = - content::WebUIDataSource::Create(chrome::kChromeUIKeyboardOverlayHost); - - for (size_t i = 0; i < arraysize(kI18nContentToMessage); ++i) { - source->AddLocalizedString(kI18nContentToMessage[i].i18n_content, - kI18nContentToMessage[i].message); - } - - // |kI18nContentToMessage| is a static array initialized before it's possible - // to call ui::DeviceUsesKeyboardLayout2(), so we add the - // |keyboardOverlayInstructions| string at runtime here. - source->AddLocalizedString("keyboardOverlayInstructions", - ui::DeviceUsesKeyboardLayout2() - ? IDS_KEYBOARD_OVERLAY_INSTRUCTIONS_LAYOUT2 - : IDS_KEYBOARD_OVERLAY_INSTRUCTIONS); - - source->AddString("keyboardOverlayLearnMoreURL", - base::UTF8ToUTF16(kLearnMoreURL)); - source->AddBoolean("keyboardOverlayHasChromeOSDiamondKey", - base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kHasChromeOSDiamondKey)); - source->AddBoolean("keyboardOverlayTopRowKeysAreFunctionKeys", - TopRowKeysAreFunctionKeys(profile)); - source->AddBoolean("voiceInteractionEnabled", - chromeos::switches::IsVoiceInteractionEnabled()); - source->AddBoolean("keyboardOverlayUsesLayout2", - ui::DeviceUsesKeyboardLayout2()); - ash::Shell* shell = ash::Shell::Get(); - display::DisplayManager* display_manager = shell->display_manager(); - source->AddBoolean("keyboardOverlayIsDisplayUIScalingEnabled", - display_manager->IsDisplayUIScalingEnabled()); - source->SetJsonPath("strings.js"); - source->AddResourcePath("keyboard_overlay.js", IDR_KEYBOARD_OVERLAY_JS); - source->SetDefaultResource(IDR_KEYBOARD_OVERLAY_HTML); - return source; -} - -} // namespace - -// The handler for Javascript messages related to the "keyboardoverlay" view. -class KeyboardOverlayHandler - : public WebUIMessageHandler, - public base::SupportsWeakPtr<KeyboardOverlayHandler> { - public: - explicit KeyboardOverlayHandler(Profile* profile); - ~KeyboardOverlayHandler() override; - - // WebUIMessageHandler implementation. - void RegisterMessages() override; - - private: - // Called when the page requires the input method ID corresponding to the - // current input method or keyboard layout during initialization. - void GetInputMethodId(const base::ListValue* args); - - // Called when the page requres the information of modifier key remapping - // during the initialization. - void GetLabelMap(const base::ListValue* args); - - // Called when the learn more link is clicked. - void OpenLearnMorePage(const base::ListValue* args); - - Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(KeyboardOverlayHandler); -}; - -//////////////////////////////////////////////////////////////////////////////// -// -// KeyboardOverlayHandler -// -//////////////////////////////////////////////////////////////////////////////// -KeyboardOverlayHandler::KeyboardOverlayHandler(Profile* profile) - : profile_(profile) { -} - -KeyboardOverlayHandler::~KeyboardOverlayHandler() { -} - -void KeyboardOverlayHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "getInputMethodId", - base::BindRepeating(&KeyboardOverlayHandler::GetInputMethodId, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "getLabelMap", base::BindRepeating(&KeyboardOverlayHandler::GetLabelMap, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "openLearnMorePage", - base::BindRepeating(&KeyboardOverlayHandler::OpenLearnMorePage, - base::Unretained(this))); -} - -void KeyboardOverlayHandler::GetInputMethodId(const base::ListValue* args) { - chromeos::input_method::InputMethodManager* manager = - chromeos::input_method::InputMethodManager::Get(); - const chromeos::input_method::InputMethodDescriptor& descriptor = - manager->GetActiveIMEState()->GetCurrentInputMethod(); - base::Value param(descriptor.id()); - web_ui()->CallJavascriptFunctionUnsafe("initKeyboardOverlayId", param); -} - -void KeyboardOverlayHandler::GetLabelMap(const base::ListValue* args) { - DCHECK(profile_); - PrefService* pref_service = profile_->GetPrefs(); - using ModifierMap = std::map<ModifierKey, ModifierKey>; - ModifierMap modifier_map; - modifier_map[ModifierKey::kSearchKey] = static_cast<ModifierKey>( - pref_service->GetInteger(prefs::kLanguageRemapSearchKeyTo)); - modifier_map[ModifierKey::kControlKey] = static_cast<ModifierKey>( - pref_service->GetInteger(prefs::kLanguageRemapControlKeyTo)); - modifier_map[ModifierKey::kAltKey] = static_cast<ModifierKey>( - pref_service->GetInteger(prefs::kLanguageRemapAltKeyTo)); - // TODO(mazda): Support prefs::kLanguageRemapCapsLockKeyTo once Caps Lock is - // added to the overlay UI. - - base::DictionaryValue dict; - for (ModifierMap::const_iterator i = modifier_map.begin(); - i != modifier_map.end(); ++i) { - dict.SetString(ModifierKeyToLabel(i->first), ModifierKeyToLabel(i->second)); - } - - web_ui()->CallJavascriptFunctionUnsafe("initIdentifierMap", dict); -} - -void KeyboardOverlayHandler::OpenLearnMorePage(const base::ListValue* args) { - web_ui()->GetWebContents()->GetDelegate()->OpenURLFromTab( - web_ui()->GetWebContents(), - content::OpenURLParams(GURL(kLearnMoreURL), content::Referrer(), - WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui::PAGE_TRANSITION_LINK, false)); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// KeyboardOverlayUI -// -//////////////////////////////////////////////////////////////////////////////// - -KeyboardOverlayUI::KeyboardOverlayUI(content::WebUI* web_ui) - : WebDialogUI(web_ui) { - Profile* profile = Profile::FromWebUI(web_ui); - web_ui->AddMessageHandler(std::make_unique<KeyboardOverlayHandler>(profile)); - - // Set up the chrome://keyboardoverlay/ source. - content::WebUIDataSource::Add(profile, - CreateKeyboardOverlayUIHTMLSource(profile)); -} diff --git a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.h b/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.h deleted file mode 100644 index 002dad9c8dd..00000000000 --- a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.h +++ /dev/null @@ -1,19 +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_KEYBOARD_OVERLAY_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_KEYBOARD_OVERLAY_UI_H_ - -#include "base/macros.h" -#include "ui/web_dialogs/web_dialog_ui.h" - -class KeyboardOverlayUI : public ui::WebDialogUI { - public: - explicit KeyboardOverlayUI(content::WebUI* web_ui); - - private: - DISALLOW_COPY_AND_ASSIGN(KeyboardOverlayUI); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_KEYBOARD_OVERLAY_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui_browsertest.cc deleted file mode 100644 index 7e96f446ba0..00000000000 --- a/chromium/chrome/browser/ui/webui/chromeos/keyboard_overlay_ui_browsertest.cc +++ /dev/null @@ -1,178 +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 "ash/public/cpp/accelerators.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/common/url_constants.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_ui_message_handler.h" -#include "content/public/test/browser_test_utils.h" -#include "ui/events/keycodes/keyboard_code_conversion.h" - -namespace { - -class TestWebUIMessageHandler : public content::WebUIMessageHandler { - public: - TestWebUIMessageHandler() = default; - ~TestWebUIMessageHandler() override = default; - - // content::WebUIMessageHandler: - void RegisterMessages() override { - web_ui()->RegisterMessageCallback( - "didPaint", - base::BindRepeating(&TestWebUIMessageHandler::HandleDidPaint, - base::Unretained(this))); - } - - private: - void HandleDidPaint(const base::ListValue*) {} - - DISALLOW_COPY_AND_ASSIGN(TestWebUIMessageHandler); -}; - -content::WebContents* StartKeyboardOverlayUI(Browser* browser) { - ui_test_utils::NavigateToURL(browser, - GURL(chrome::kChromeUIKeyboardOverlayURL)); - content::WebContents* web_contents = - browser->tab_strip_model()->GetActiveWebContents(); - web_contents->GetWebUI()->AddMessageHandler( - std::make_unique<TestWebUIMessageHandler>()); - return web_contents; -} - -bool IsDisplayUIScalingEnabled(content::WebContents* web_contents) { - bool is_display_ui_scaling_enabled; - EXPECT_TRUE(content::ExecuteScriptAndExtractBool( - web_contents, - "domAutomationController.send(isDisplayUIScalingEnabled());", - &is_display_ui_scaling_enabled)); - return is_display_ui_scaling_enabled; -} - -// Skip some accelerators in the tests: -// 1. If the accelerator has no modifier, i.e. ui::EF_NONE, or for "Caps -// Lock", such as ui::VKEY_MENU and ui::VKEY_LWIN, the logic to show it on -// the keyboard overlay is not by the mapping of -// keyboardOverlayData['shortcut'], so it can not be tested by this test. -// 2. If it has debug modifiers: ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN | -// ui::EF_SHIFT_DOWN -bool ShouldSkip(const ash::AcceleratorData& accelerator) { - return accelerator.keycode == ui::VKEY_MENU || - accelerator.keycode == ui::VKEY_LWIN || - accelerator.modifiers == ui::EF_NONE || - accelerator.modifiers == - (ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN | ui::EF_SHIFT_DOWN); -} - -std::string KeyboardCodeToLabel(const ash::AcceleratorData& accelerator, - content::WebContents* web_contents) { - std::string label; - EXPECT_TRUE(content::ExecuteScriptAndExtractString( - web_contents, - "domAutomationController.send(" - " (function(number) {" - " if (!!KEYCODE_TO_LABEL[number]) {" - " return KEYCODE_TO_LABEL[number];" - " } else {" - " return 'NONE';" - " }" - " })(" + - std::to_string(static_cast<unsigned int>(accelerator.keycode)) + - " )" - ");", - &label)); - if (label == "NONE") { - label = base::ToLowerASCII(static_cast<char>( - LocatedToNonLocatedKeyboardCode(accelerator.keycode))); - } - return label; -} - -std::string GenerateShortcutKey(const ash::AcceleratorData& accelerator, - content::WebContents* web_contents) { - std::string shortcut = KeyboardCodeToLabel(accelerator, web_contents); - // The order of the "if" conditions should not be changed because the - // modifiers are expected to be alphabetical sorted in the generated - // shortcut. - if (accelerator.modifiers & ui::EF_ALT_DOWN) - shortcut.append("<>ALT"); - if (accelerator.modifiers & ui::EF_CONTROL_DOWN) - shortcut.append("<>CTRL"); - if (accelerator.modifiers & ui::EF_COMMAND_DOWN) - shortcut.append("<>SEARCH"); - if (accelerator.modifiers & ui::EF_SHIFT_DOWN) - shortcut.append("<>SHIFT"); - return shortcut; -} - -bool ContainsShortcut(const std::string& shortcut, - content::WebContents* web_contents) { - bool contains; - EXPECT_TRUE(content::ExecuteScriptAndExtractBool( - web_contents, - "domAutomationController.send(" - " !!keyboardOverlayData['shortcut']['" + shortcut + "']" - ");", - &contains)); - return contains; -} - -} // namespace - -using KeyboardOverlayUIBrowserTest = InProcessBrowserTest; - -// This test verifies two things: -// -// 1. That all accelerators in kAcceleratorData appear in the keyboard overlay -// UI. This will fail when a new shortcut is added (or replaced) in -// kAcceleratorData but not the overlay UI. -// -// 2. That the number of accelerators shared by the Ash table and the UI is the -// expected value. This will fail when a new shortcut is added to -// kAcceleratorData but not the overlay UI. -IN_PROC_BROWSER_TEST_F(KeyboardOverlayUIBrowserTest, - AcceleratorsShouldHaveKeyboardOverlay) { - content::WebContents* const web_contents = StartKeyboardOverlayUI(browser()); - const bool is_display_ui_scaling_enabled = - IsDisplayUIScalingEnabled(web_contents); - int found_accelerators = 0; - for (size_t i = 0; i < ash::kAcceleratorDataLength; ++i) { - const ash::AcceleratorData& entry = ash::kAcceleratorData[i]; - if (ShouldSkip(entry)) - continue; - - const std::string shortcut = GenerateShortcutKey(entry, web_contents); - if (!is_display_ui_scaling_enabled) { - if (shortcut == "-<>CTRL<>SHIFT" || shortcut == "+<>CTRL<>SHIFT" || - shortcut == "0<>CTRL<>SHIFT") { - continue; - } - } - - if (ContainsShortcut(shortcut, web_contents)) { - found_accelerators++; - } else { - ADD_FAILURE() << "Please add the new accelerators to keyboard " - "overlay. Add one entry '" + - shortcut + - "' in the 'shortcut' section" - " at the bottom of the file of " - "'/chrome/browser/resources/chromeos/" - "keyboard_overlay_data.js'. Please keep it in " - "alphabetical order."; - } - } - - constexpr int kExpectedFoundAccelerators = 62; - DCHECK_EQ(kExpectedFoundAccelerators, found_accelerators) - << "It seems ash::kAcceleratorData or the 'shortcut' section of " - "'/chrome/browser/resources/chromeos/keyboard_overlay_data.js' has " - "changed. Please keep the two in sync. If you've deprecated an " - "accelerator, remove it from keyboard_overlay_data.js. If you have " - "added the accelerator in both places, update " - "kExpectedFoundAccelerators."; -} diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.cc index a20c7a94568..c43fe5c8e40 100644 --- 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 @@ -59,8 +59,8 @@ void AppDownloadingScreenHandler::Bind(AppDownloadingScreen* screen) { void AppDownloadingScreenHandler::Show() { ShowScreen(kScreenId); - CallJS("updateNumberOfSelectedApps", - base::Value(GetNumberOfUserSelectedApps())); + CallJSWithPrefix("updateNumberOfSelectedApps", + base::Value(GetNumberOfUserSelectedApps())); } void AppDownloadingScreenHandler::Hide() {} diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.cc index 79aa13e3464..b05ff748238 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.cc @@ -114,7 +114,7 @@ void AppLaunchSplashScreenHandler::Hide() { } void AppLaunchSplashScreenHandler::ToggleNetworkConfig(bool visible) { - CallJS("toggleNetworkConfig", visible); + CallJSWithPrefix("toggleNetworkConfig", visible); } void AppLaunchSplashScreenHandler::UpdateAppLaunchState(AppLaunchState state) { @@ -228,7 +228,7 @@ void AppLaunchSplashScreenHandler::PopulateAppInfo( } void AppLaunchSplashScreenHandler::SetLaunchText(const std::string& text) { - CallJS("updateMessage", text); + CallJSWithPrefix("updateMessage", text); } int AppLaunchSplashScreenHandler::GetProgressMessageFromState( diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/arc_kiosk_splash_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/arc_kiosk_splash_screen_handler.cc index b271749e419..53d5efa3aa6 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/arc_kiosk_splash_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/arc_kiosk_splash_screen_handler.cc @@ -94,7 +94,7 @@ void ArcKioskSplashScreenHandler::PopulateAppInfo( } void ArcKioskSplashScreenHandler::SetLaunchText(const std::string& text) { - CallJS("updateArcKioskMessage", text); + CallJSWithPrefix("updateArcKioskMessage", text); } int ArcKioskSplashScreenHandler::GetProgressMessageFromState( 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 f1d7e7e852c..1ecd238574d 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 @@ -18,7 +18,7 @@ #include "chrome/browser/consent_auditor/consent_auditor_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/grit/generated_resources.h" #include "chromeos/chromeos_switches.h" #include "chromeos/network/network_handler.h" @@ -28,9 +28,10 @@ #include "components/consent_auditor/consent_auditor.h" #include "components/login/localized_values_builder.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_manager_base.h" +#include "components/user_manager/user_manager.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" +#include "services/identity/public/cpp/identity_manager.h" #include "ui/base/l10n/l10n_util.h" using ArcBackupAndRestoreConsent = @@ -51,7 +52,9 @@ const char kJsScreenPath[] = "login.ArcTermsOfServiceScreen"; namespace chromeos { ArcTermsOfServiceScreenHandler::ArcTermsOfServiceScreenHandler() - : BaseScreenHandler(kScreenId) { + : BaseScreenHandler(kScreenId), + is_child_account_( + user_manager::UserManager::Get()->IsLoggedInAsChildUser()) { set_call_js_prefix(kJsScreenPath); } @@ -84,7 +87,7 @@ void ArcTermsOfServiceScreenHandler::MaybeLoadPlayStoreToS( if (!ignore_network_state && !default_network) return; const std::string country_code = base::CountryCodeForCurrentTimezone(); - CallJS("loadPlayStoreToS", country_code); + CallJSWithPrefix("loadPlayStoreToS", country_code); } void ArcTermsOfServiceScreenHandler::OnCurrentScreenChanged( @@ -123,20 +126,31 @@ void ArcTermsOfServiceScreenHandler::DeclareLocalizedValues( builder->Add("arcTermsOfServiceNextButton", IDS_ARC_OPT_IN_DIALOG_BUTTON_NEXT); builder->Add("arcPolicyLink", IDS_ARC_OPT_IN_PRIVACY_POLICY_LINK); - builder->Add("arcTextBackupRestore", IDS_ARC_OPT_IN_DIALOG_BACKUP_RESTORE); - builder->Add("arcTextLocationService", IDS_ARC_OPT_IN_LOCATION_SETTING); + builder->Add("arcTextBackupRestore", + is_child_account_ ? IDS_ARC_OPT_IN_DIALOG_BACKUP_RESTORE_CHILD + : IDS_ARC_OPT_IN_DIALOG_BACKUP_RESTORE); + builder->Add("arcTextLocationService", + is_child_account_ ? IDS_ARC_OPT_IN_LOCATION_SETTING_CHILD + : IDS_ARC_OPT_IN_LOCATION_SETTING); builder->Add("arcTextPaiService", IDS_ARC_OPT_IN_PAI); builder->Add("arcTextGoogleServiceConfirmation", IDS_ARC_OPT_IN_GOOGLE_SERVICE_CONFIRMATION); + builder->Add("arcTextReviewSettings", IDS_ARC_REVIEW_SETTINGS); 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("arcLearnMoreStatistics", + is_child_account_ ? IDS_ARC_OPT_IN_LEARN_MORE_STATISTICS_CHILD + : IDS_ARC_OPT_IN_LEARN_MORE_STATISTICS); builder->Add("arcLearnMoreLocationService", - IDS_ARC_OPT_IN_LEARN_MORE_LOCATION_SERVICES); + is_child_account_ + ? IDS_ARC_OPT_IN_LEARN_MORE_LOCATION_SERVICES_CHILD + : IDS_ARC_OPT_IN_LEARN_MORE_LOCATION_SERVICES); builder->Add("arcLearnMoreBackupAndRestore", - IDS_ARC_OPT_IN_LEARN_MORE_BACKUP_AND_RESTORE); + is_child_account_ + ? IDS_ARC_OPT_IN_LEARN_MORE_BACKUP_AND_RESTORE_CHILD + : IDS_ARC_OPT_IN_LEARN_MORE_BACKUP_AND_RESTORE); builder->Add("arcLearnMorePaiService", IDS_ARC_OPT_IN_LEARN_MORE_PAI_SERVICE); builder->Add("arcOverlayClose", IDS_ARC_OOBE_TERMS_POPUP_HELP_CLOSE_BUTTON); builder->Add("arcOverlayLoading", IDS_ARC_POPUP_HELP_LOADING); @@ -159,30 +173,39 @@ void ArcTermsOfServiceScreenHandler::OnMetricsModeChanged(bool enabled, // managed flag. const bool owner_profile = !owner.is_valid() || user->GetAccountId() == owner; - if (owner_profile && !managed && !enabled) { - CallJS("setMetricsMode", base::string16(), false); + int message_id; + if (owner_profile && !managed) { + if (is_child_account_) { + message_id = enabled ? IDS_ARC_OOBE_TERMS_DIALOG_METRICS_ENABLED_CHILD + : IDS_ARC_OOBE_TERMS_DIALOG_METRICS_DISABLED_CHILD; + } else { + message_id = enabled ? IDS_ARC_OOBE_TERMS_DIALOG_METRICS_ENABLED + : IDS_ARC_OOBE_TERMS_DIALOG_METRICS_DISABLED; + } } else { - int message_id; - if (owner_profile && !managed) { - message_id = IDS_ARC_OOBE_TERMS_DIALOG_METRICS_ENABLED; + if (is_child_account_) { + message_id = + enabled ? IDS_ARC_OOBE_TERMS_DIALOG_METRICS_MANAGED_ENABLED_CHILD + : IDS_ARC_OOBE_TERMS_DIALOG_METRICS_MANAGED_DISABLED_CHILD; } else { message_id = enabled ? IDS_ARC_OOBE_TERMS_DIALOG_METRICS_MANAGED_ENABLED : IDS_ARC_OOBE_TERMS_DIALOG_METRICS_MANAGED_DISABLED; } - CallJS("setMetricsMode", l10n_util::GetStringUTF16(message_id), true); } + CallJSWithPrefix("setMetricsMode", l10n_util::GetStringUTF16(message_id), + true); } void ArcTermsOfServiceScreenHandler::OnBackupAndRestoreModeChanged( bool enabled, bool managed) { backup_restore_managed_ = managed; - CallJS("setBackupAndRestoreMode", enabled, managed); + CallJSWithPrefix("setBackupAndRestoreMode", enabled, managed); } void ArcTermsOfServiceScreenHandler::OnLocationServicesModeChanged( bool enabled, bool managed) { location_services_managed_ = managed; - CallJS("setLocationServicesMode", enabled, managed); + CallJSWithPrefix("setLocationServicesMode", enabled, managed); } void ArcTermsOfServiceScreenHandler::AddObserver( @@ -246,7 +269,7 @@ void ArcTermsOfServiceScreenHandler::DoShow() { Profile* profile = ProfileManager::GetActiveUserProfile(); CHECK(profile); - CallJS("clearDemoMode"); + CallJSWithPrefix("clearDemoMode"); // Enable ARC to match ArcSessionManager logic. ArcSessionManager expects that // ARC is enabled (prefs::kArcEnabled = true) on showing Terms of Service. If @@ -257,7 +280,7 @@ void ArcTermsOfServiceScreenHandler::DoShow() { // Hide the Skip button if the ToS screen can not be skipped during OOBE. if (base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kEnableArcOobeOptinNoSkip)) { - CallJS("hideSkipButton"); + CallJSWithPrefix("hideSkipButton"); } action_taken_ = false; @@ -265,7 +288,7 @@ void ArcTermsOfServiceScreenHandler::DoShow() { ShowScreen(kScreenId); arc_managed_ = arc::IsArcPlayStoreEnabledPreferenceManagedForProfile(profile); - CallJS("setArcManaged", arc_managed_); + CallJSWithPrefix("setArcManaged", arc_managed_); MaybeLoadPlayStoreToS(true); StartNetworkAndTimeZoneObserving(); @@ -278,7 +301,7 @@ void ArcTermsOfServiceScreenHandler::DoShow() { void ArcTermsOfServiceScreenHandler::DoShowForDemoModeSetup() { DCHECK(arc::IsArcDemoModeSetupFlow()); - CallJS("setupForDemoMode"); + CallJSWithPrefix("setupForDemoMode"); action_taken_ = false; ShowScreen(kScreenId); MaybeLoadPlayStoreToS(true); @@ -303,10 +326,9 @@ void ArcTermsOfServiceScreenHandler::RecordConsents( Profile* profile = ProfileManager::GetActiveUserProfile(); consent_auditor::ConsentAuditor* consent_auditor = ConsentAuditorFactory::GetForProfile(profile); - SigninManagerBase* signin_manager = - SigninManagerFactory::GetForProfile(profile); - DCHECK(signin_manager->IsAuthenticated()); - const std::string account_id = signin_manager->GetAuthenticatedAccountId(); + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); + DCHECK(identity_manager->HasPrimaryAccount()); + const std::string account_id = identity_manager->GetPrimaryAccountId(); ArcPlayTermsOfServiceConsent play_consent; play_consent.set_status(tos_accepted ? UserConsentTypes::GIVEN @@ -325,7 +347,8 @@ void ArcTermsOfServiceScreenHandler::RecordConsents( backup_and_restore_consent.set_confirmation_grd_id( IDS_ARC_OOBE_TERMS_BUTTON_ACCEPT); backup_and_restore_consent.add_description_grd_ids( - IDS_ARC_OPT_IN_DIALOG_BACKUP_RESTORE); + is_child_account_ ? IDS_ARC_OPT_IN_DIALOG_BACKUP_RESTORE_CHILD + : IDS_ARC_OPT_IN_DIALOG_BACKUP_RESTORE); backup_and_restore_consent.set_status(backup_accepted ? UserConsentTypes::GIVEN : UserConsentTypes::NOT_GIVEN); @@ -339,7 +362,8 @@ void ArcTermsOfServiceScreenHandler::RecordConsents( location_service_consent.set_confirmation_grd_id( IDS_ARC_OOBE_TERMS_BUTTON_ACCEPT); location_service_consent.add_description_grd_ids( - IDS_ARC_OPT_IN_LOCATION_SETTING); + is_child_account_ ? IDS_ARC_OPT_IN_LOCATION_SETTING + : IDS_ARC_OPT_IN_LOCATION_SETTING); location_service_consent.set_status(location_accepted ? UserConsentTypes::GIVEN : UserConsentTypes::NOT_GIVEN); @@ -369,10 +393,11 @@ void ArcTermsOfServiceScreenHandler::HandleSkip( void ArcTermsOfServiceScreenHandler::HandleAccept( bool enable_backup_restore, bool enable_location_services, + bool review_arc_settings, const std::string& tos_content) { if (arc::IsArcDemoModeSetupFlow()) { for (auto& observer : observer_list_) - observer.OnAccept(); + observer.OnAccept(false); // TODO(agawronska): Record consent. return; } @@ -390,7 +415,7 @@ void ArcTermsOfServiceScreenHandler::HandleAccept( !location_services_managed_, enable_location_services); for (auto& observer : observer_list_) - observer.OnAccept(); + observer.OnAccept(review_arc_settings); } } // namespace chromeos 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 e63def59f34..1ae7b15c6f6 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 @@ -77,6 +77,7 @@ class ArcTermsOfServiceScreenHandler void HandleSkip(const std::string& tos_content); void HandleAccept(bool enable_backup_restore, bool enable_location_services, + bool review_arc_settings, const std::string& tos_content); // Loads Play Store ToS content in case default network exists. If // |ignore_network_state| is set then network state is not checked. @@ -120,6 +121,9 @@ class ArcTermsOfServiceScreenHandler bool backup_restore_managed_ = false; bool location_services_managed_ = false; + // To track if a child account is being set up. + bool is_child_account_; + std::unique_ptr<arc::ArcOptInPreferenceHandler> pref_handler_; DISALLOW_COPY_AND_ASSIGN(ArcTermsOfServiceScreenHandler); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc index 9a63d3a5d32..e20f1527a0c 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc @@ -12,6 +12,7 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h" #include "chrome/grit/generated_resources.h" +#include "chromeos/services/assistant/public/features.h" #include "chromeos/services/assistant/public/mojom/constants.mojom.h" #include "chromeos/services/assistant/public/proto/settings_ui.pb.h" #include "components/arc/arc_prefs.h" @@ -26,13 +27,14 @@ namespace { constexpr char kJsScreenPath[] = "login.AssistantOptInFlowScreen"; constexpr char kSkipPressed[] = "skip-pressed"; constexpr char kNextPressed[] = "next-pressed"; +constexpr char kRecordPressed[] = "record-pressed"; constexpr char kFlowFinished[] = "flow-finished"; constexpr char kReloadRequested[] = "reload-requested"; } // namespace AssistantOptInFlowScreenHandler::AssistantOptInFlowScreenHandler() - : BaseScreenHandler(kScreenId), weak_factory_(this) { + : BaseScreenHandler(kScreenId), client_binding_(this), weak_factory_(this) { set_call_js_prefix(kJsScreenPath); } @@ -58,7 +60,35 @@ void AssistantOptInFlowScreenHandler::DeclareLocalizedValues( IDS_VOICE_INTERACTION_VALUE_PROP_SKIP_BUTTON); builder->Add("assistantOptinRetryButton", IDS_VOICE_INTERACTION_VALUE_PROP_RETRY_BUTTON); + builder->Add("assistantVoiceMatchTitle", IDS_ASSISTANT_VOICE_MATCH_TITLE); + builder->Add("assistantVoiceMatchMessage", IDS_ASSISTANT_VOICE_MATCH_MESSAGE); + builder->Add("assistantVoiceMatchRecording", + IDS_ASSISTANT_VOICE_MATCH_RECORDING); + builder->Add("assistantVoiceMatchCompleted", + IDS_ASSISTANT_VOICE_MATCH_COMPLETED); + builder->Add("assistantVoiceMatchFooter", IDS_ASSISTANT_VOICE_MATCH_FOOTER); + builder->Add("assistantVoiceMatchInstruction0", + IDS_ASSISTANT_VOICE_MATCH_INSTRUCTION0); + builder->Add("assistantVoiceMatchInstruction1", + IDS_ASSISTANT_VOICE_MATCH_INSTRUCTION1); + builder->Add("assistantVoiceMatchInstruction2", + IDS_ASSISTANT_VOICE_MATCH_INSTRUCTION2); + builder->Add("assistantVoiceMatchInstruction3", + IDS_ASSISTANT_VOICE_MATCH_INSTRUCTION3); + builder->Add("assistantVoiceMatchComplete", + IDS_ASSISTANT_VOICE_MATCH_COMPLETE); + builder->Add("assistantVoiceMatchUploading", + IDS_ASSISTANT_VOICE_MATCH_UPLOADING); + builder->Add("assistantVoiceMatchAlreadySetupTitle", + IDS_ASSISTANT_VOICE_MATCH_ALREADY_SETUP_TITLE); + builder->Add("assistantVoiceMatchAlreadySetupMessage", + IDS_ASSISTANT_VOICE_MATCH_ALREADY_SETUP_MESSAGE); builder->Add("assistantOptinOKButton", IDS_OOBE_OK_BUTTON_TEXT); + builder->Add("assistantOptinNoThanksButton", IDS_ASSISTANT_NO_THANKS_BUTTON); + builder->Add("assistantOptinLaterButton", IDS_ASSISTANT_LATER_BUTTON); + builder->Add("assistantOptinAgreeButton", IDS_ASSISTANT_AGREE_BUTTON); + builder->Add("assistantOptinSaveButton", IDS_ASSISTANT_SAVE_BUTTON); + builder->Add("assistantOptinWaitMessage", IDS_ASSISTANT_WAIT_MESSAGE); builder->Add("assistantReadyTitle", IDS_ASSISTANT_READY_SCREEN_TITLE); builder->Add("assistantReadyMessage", IDS_ASSISTANT_READY_SCREEN_MESSAGE); builder->Add("assistantReadyButton", IDS_ASSISTANT_DONE_BUTTON); @@ -74,6 +104,9 @@ void AssistantOptInFlowScreenHandler::RegisterMessages() { "ThirdPartyScreen.userActed", &AssistantOptInFlowScreenHandler::HandleThirdPartyScreenUserAction); AddPrefixedCallback( + "VoiceMatchScreen.userActed", + &AssistantOptInFlowScreenHandler::HandleVoiceMatchScreenUserAction); + AddPrefixedCallback( "GetMoreScreen.userActed", &AssistantOptInFlowScreenHandler::HandleGetMoreScreenUserAction); AddPrefixedCallback( @@ -133,6 +166,24 @@ void AssistantOptInFlowScreenHandler::Initialize() { show_on_init_ = false; } +void AssistantOptInFlowScreenHandler::OnListeningHotword() { + CallJSWithPrefix("onVoiceMatchUpdate", base::Value("listen")); +} + +void AssistantOptInFlowScreenHandler::OnProcessingHotword() { + CallJSWithPrefix("onVoiceMatchUpdate", base::Value("process")); +} + +void AssistantOptInFlowScreenHandler::OnSpeakerIdEnrollmentDone() { + settings_manager_->StopSpeakerIdEnrollment(base::DoNothing()); + CallJSWithPrefix("onVoiceMatchUpdate", base::Value("done")); +} + +void AssistantOptInFlowScreenHandler::OnSpeakerIdEnrollmentFailure() { + // TODO(updowndota): Show an error message to user, and add an UMA metric. + LOG(ERROR) << "Speaker ID enrollmend failure."; +} + void AssistantOptInFlowScreenHandler::SetupAssistantConnection() { // Make sure enable Assistant service since we need it during the flow. PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); @@ -147,7 +198,7 @@ void AssistantOptInFlowScreenHandler::SetupAssistantConnection() { } void AssistantOptInFlowScreenHandler::ShowNextScreen() { - CallJS("showNextScreen"); + CallJSWithPrefix("showNextScreen"); } void AssistantOptInFlowScreenHandler::OnActivityControlOptInResult( @@ -186,7 +237,15 @@ void AssistantOptInFlowScreenHandler::OnEmailOptInResult(bool opted_in) { void AssistantOptInFlowScreenHandler::OnStateChanged( ash::mojom::VoiceInteractionState state) { if (state != ash::mojom::VoiceInteractionState::NOT_READY) { - BindAssistantSettingsManager(); + if (voice_enrollment_pending) { + voice_enrollment_pending = false; + DCHECK(settings_manager_.is_bound() && + base::FeatureList::IsEnabled( + assistant::features::kAssistantVoiceMatch)); + settings_manager_->StartSpeakerIdEnrollment(true, std::move(client_ptr_)); + } else { + BindAssistantSettingsManager(); + } arc::VoiceInteractionControllerClient::Get()->RemoveObserver(this); } } @@ -201,8 +260,11 @@ void AssistantOptInFlowScreenHandler::BindAssistantSettingsManager() { ProfileManager::GetActiveUserProfile()); connector->BindInterface(assistant::mojom::kServiceName, mojo::MakeRequest(&settings_manager_)); + client_binding_.Bind(mojo::MakeRequest(&client_ptr_)); - SendGetSettingsRequest(); + if (initialized_) { + SendGetSettingsRequest(); + } } void AssistantOptInFlowScreenHandler::SendGetSettingsRequest() { @@ -215,12 +277,12 @@ void AssistantOptInFlowScreenHandler::SendGetSettingsRequest() { } void AssistantOptInFlowScreenHandler::ReloadContent(const base::Value& dict) { - CallJS("reloadContent", dict); + CallJSWithPrefix("reloadContent", dict); } void AssistantOptInFlowScreenHandler::AddSettingZippy(const std::string& type, const base::Value& data) { - CallJS("addSettingZippy", type, data); + CallJSWithPrefix("addSettingZippy", type, data); } void AssistantOptInFlowScreenHandler::OnGetSettingsResponse( @@ -295,7 +357,11 @@ void AssistantOptInFlowScreenHandler::OnGetSettingsResponse( } // Pass string constants dictionary. - ReloadContent(GetSettingsUiStrings(settings_ui, activity_control_needed_)); + auto dictionary = GetSettingsUiStrings(settings_ui, activity_control_needed_); + dictionary.SetKey("voiceMatchFeatureEnabled", + base::Value(base::FeatureList::IsEnabled( + assistant::features::kAssistantVoiceMatch))); + ReloadContent(dictionary); } void AssistantOptInFlowScreenHandler::OnUpdateSettingsResponse( @@ -356,6 +422,33 @@ void AssistantOptInFlowScreenHandler::HandleThirdPartyScreenUserAction( } } +void AssistantOptInFlowScreenHandler::HandleVoiceMatchScreenUserAction( + const std::string& action) { + if (!base::FeatureList::IsEnabled( + assistant::features::kAssistantVoiceMatch)) { + return; + } + PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); + + if (action == kNextPressed) { + ShowNextScreen(); + } else if (action == kSkipPressed) { + prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, false); + settings_manager_->StopSpeakerIdEnrollment(base::DoNothing()); + ShowNextScreen(); + } else if (action == kRecordPressed) { + if (!prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled)) { + // Turn on hotword will restart the Assistant service. Thus the enrollment + // request should be sent after the service restart complete. + voice_enrollment_pending = true; + prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, true); + arc::VoiceInteractionControllerClient::Get()->AddObserver(this); + } else { + settings_manager_->StartSpeakerIdEnrollment(true, std::move(client_ptr_)); + } + } +} + void AssistantOptInFlowScreenHandler::HandleGetMoreScreenUserAction( const bool screen_context, const bool email_opted_in) { @@ -412,9 +505,15 @@ void AssistantOptInFlowScreenHandler::HandleFlowFinished() { if (screen_) screen_->OnUserAction(kFlowFinished); else - CallJS("closeDialog"); + CallJSWithPrefix("closeDialog"); } -void AssistantOptInFlowScreenHandler::HandleFlowInitialized() {} +void AssistantOptInFlowScreenHandler::HandleFlowInitialized() { + initialized_ = true; + + if (settings_manager_.is_bound()) { + SendGetSettingsRequest(); + } +} } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h index 6ddc11065a2..2491cab2adb 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h @@ -13,6 +13,7 @@ #include "chrome/browser/chromeos/login/screens/assistant_optin_flow_screen_view.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "chromeos/services/assistant/public/mojom/settings.mojom.h" +#include "mojo/public/cpp/bindings/binding.h" namespace chromeos { @@ -20,7 +21,8 @@ namespace chromeos { class AssistantOptInFlowScreenHandler : public BaseScreenHandler, public AssistantOptInFlowScreenView, - public arc::VoiceInteractionControllerClient::Observer { + public arc::VoiceInteractionControllerClient::Observer, + assistant::mojom::SpeakerIdEnrollmentClient { public: AssistantOptInFlowScreenHandler(); ~AssistantOptInFlowScreenHandler() override; @@ -36,6 +38,12 @@ class AssistantOptInFlowScreenHandler void Show() override; void Hide() override; + // assistant::mojom::SpeakerIdEnrollmentClient: + void OnListeningHotword() override; + void OnProcessingHotword() override; + void OnSpeakerIdEnrollmentDone() override; + void OnSpeakerIdEnrollmentFailure() override; + // Setup Assistant settings manager connection. void SetupAssistantConnection(); @@ -70,11 +78,13 @@ class AssistantOptInFlowScreenHandler // Handler for JS WebUI message. void HandleValuePropScreenUserAction(const std::string& action); void HandleThirdPartyScreenUserAction(const std::string& action); + void HandleVoiceMatchScreenUserAction(const std::string& action); void HandleGetMoreScreenUserAction(const bool screen_context, const bool email_opted_in); void HandleReadyScreenUserAction(const std::string& action); void HandleValuePropScreenShown(); void HandleThirdPartyScreenShown(); + void HandleVoiceMatchScreenShown(); void HandleGetMoreScreenShown(); void HandleReadyScreenShown(); void HandleLoadingTimeout(); @@ -108,6 +118,14 @@ class AssistantOptInFlowScreenHandler // Counter for the number of loading timeout happens. int loading_timeout_counter_ = 0; + // Whether the screen has been initialized. + bool initialized_ = false; + + // Whether there is a pending voice match enrollment request. + bool voice_enrollment_pending = false; + + mojo::Binding<assistant::mojom::SpeakerIdEnrollmentClient> client_binding_; + assistant::mojom::SpeakerIdEnrollmentClientPtr client_ptr_; assistant::mojom::AssistantSettingsManagerPtr settings_manager_; base::WeakPtrFactory<AssistantOptInFlowScreenHandler> weak_factory_; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.cc index b5a82c2a7de..93aefeb8842 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.cc @@ -60,12 +60,12 @@ void BaseWebUIHandler::CommitContextChanges(const base::DictionaryValue& diff) { if (!page_is_ready()) pending_context_changes_.MergeDictionary(&diff); else - CallJS(kMethodContextChanged, diff); + CallJSWithPrefix(kMethodContextChanged, diff); } void BaseWebUIHandler::GetAdditionalParameters(base::DictionaryValue* dict) {} -void BaseWebUIHandler::CallJS(const std::string& method) { +void BaseWebUIHandler::CallJSWithPrefix(const std::string& method) { web_ui()->CallJavascriptFunctionUnsafe(FullMethodPath(method)); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.h index 37835bcc32c..6f87c341d10 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.h @@ -120,37 +120,39 @@ class BaseWebUIHandler : public content::WebUIMessageHandler, virtual void GetAdditionalParameters(base::DictionaryValue* parameters); // Shortcut for calling JS methods on WebUI side. - void CallJS(const std::string& method); + void CallJSWithPrefix(const std::string& method); template <typename A1> - void CallJS(const std::string& method, const A1& arg1) { + void CallJSWithPrefix(const std::string& method, const A1& arg1) { web_ui()->CallJavascriptFunctionUnsafe(FullMethodPath(method), ::login::MakeValue(arg1)); } template <typename A1, typename A2> - void CallJS(const std::string& method, const A1& arg1, const A2& arg2) { + void CallJSWithPrefix(const std::string& method, + const A1& arg1, + const A2& arg2) { web_ui()->CallJavascriptFunctionUnsafe(FullMethodPath(method), ::login::MakeValue(arg1), ::login::MakeValue(arg2)); } template <typename A1, typename A2, typename A3> - void CallJS(const std::string& method, - const A1& arg1, - const A2& arg2, - const A3& arg3) { + void CallJSWithPrefix(const std::string& method, + const A1& arg1, + const A2& arg2, + const A3& arg3) { web_ui()->CallJavascriptFunctionUnsafe( FullMethodPath(method), ::login::MakeValue(arg1), ::login::MakeValue(arg2), ::login::MakeValue(arg3)); } template <typename A1, typename A2, typename A3, typename A4> - void CallJS(const std::string& method, - const A1& arg1, - const A2& arg2, - const A3& arg3, - const A4& arg4) { + void CallJSWithPrefix(const std::string& method, + const A1& arg1, + const A2& arg2, + const A3& arg3, + const A4& arg4) { web_ui()->CallJavascriptFunctionUnsafe( FullMethodPath(method), ::login::MakeValue(arg1), ::login::MakeValue(arg2), ::login::MakeValue(arg3), @@ -158,10 +160,11 @@ class BaseWebUIHandler : public content::WebUIMessageHandler, } template <typename... Args> - void CallJSOrDefer(const std::string& function_name, const Args&... args) { + void CallJSWithPrefixOrDefer(const std::string& function_name, + const Args&... args) { DCHECK(js_calls_container_); if (js_calls_container_->is_initialized()) { - CallJS(function_name, args...); + CallJSWithPrefix(function_name, args...); } else { // Note that std::conditional is used here in order to obtain a sequence // of base::Value types with the length equal to sizeof...(Args); the C++ @@ -236,7 +239,7 @@ class BaseWebUIHandler : public content::WebUIMessageHandler, template <typename... Args> void ExecuteDeferredJSCall(const std::string& function_name, std::unique_ptr<Args>... args) { - CallJS(function_name, *args...); + CallJSWithPrefix(function_name, *args...); } // Returns full name of JS method based on screen and method diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/controller_pairing_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/controller_pairing_screen_handler.cc index a2c7493c08e..25e7e0c5698 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/controller_pairing_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/controller_pairing_screen_handler.cc @@ -165,7 +165,7 @@ void ControllerPairingScreenHandler::SetDelegate(Delegate* delegate) { void ControllerPairingScreenHandler::OnContextChanged( const base::DictionaryValue& diff) { - CallJS(kMethodContextChanged, diff); + CallJSWithPrefix(kMethodContextChanged, diff); } content::BrowserContext* ControllerPairingScreenHandler::GetBrowserContext() { 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 d0842f5a8fc..7179b1ef347 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 @@ -32,6 +32,7 @@ #include "chrome/browser/chromeos/tpm_firmware_update.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/ui/ash/ash_util.h" +#include "chrome/browser/ui/ash/chrome_keyboard_controller_client.h" #include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h" @@ -50,12 +51,12 @@ #include "content/public/common/service_manager_connection.h" #include "google_apis/google_api_keys.h" #include "services/service_manager/public/cpp/connector.h" +#include "ui/accessibility/accessibility_switches.h" #include "ui/aura/window_tree_host.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" -#include "ui/keyboard/keyboard_controller.h" namespace chromeos { @@ -236,12 +237,12 @@ void CoreOobeHandler::ShowSignInError( const std::string& help_link_text, HelpAppLauncher::HelpTopic help_topic_id) { LOG(ERROR) << "CoreOobeHandler::ShowSignInError: error_text=" << error_text; - CallJSOrDefer("showSignInError", login_attempts, error_text, help_link_text, - static_cast<int>(help_topic_id)); + CallJSWithPrefixOrDefer("showSignInError", login_attempts, error_text, + help_link_text, static_cast<int>(help_topic_id)); } void CoreOobeHandler::ShowTpmError() { - CallJSOrDefer("showTpmError"); + CallJSWithPrefixOrDefer("showTpmError"); } void CoreOobeHandler::ShowDeviceResetScreen() { @@ -259,61 +260,62 @@ void CoreOobeHandler::ShowEnableDebuggingScreen() { void CoreOobeHandler::ShowActiveDirectoryPasswordChangeScreen( const std::string& username) { - CallJSOrDefer("showActiveDirectoryPasswordChangeScreen", username); + CallJSWithPrefixOrDefer("showActiveDirectoryPasswordChangeScreen", username); } void CoreOobeHandler::ShowSignInUI(const std::string& email) { - CallJSOrDefer("showSigninUI", email); + CallJSWithPrefixOrDefer("showSigninUI", email); } void CoreOobeHandler::ResetSignInUI(bool force_online) { - CallJSOrDefer("resetSigninUI", force_online); + CallJSWithPrefixOrDefer("resetSigninUI", force_online); } void CoreOobeHandler::ClearUserPodPassword() { - CallJSOrDefer("clearUserPodPassword"); + CallJSWithPrefixOrDefer("clearUserPodPassword"); } void CoreOobeHandler::RefocusCurrentPod() { - CallJSOrDefer("refocusCurrentPod"); + CallJSWithPrefixOrDefer("refocusCurrentPod"); } void CoreOobeHandler::ShowPasswordChangedScreen(bool show_password_error, const std::string& email) { - CallJSOrDefer("showPasswordChangedScreen", show_password_error, email); + CallJSWithPrefixOrDefer("showPasswordChangedScreen", show_password_error, + email); } void CoreOobeHandler::SetUsageStats(bool checked) { - CallJSOrDefer("setUsageStats", checked); + CallJSWithPrefixOrDefer("setUsageStats", checked); } void CoreOobeHandler::SetTpmPassword(const std::string& tpm_password) { - CallJSOrDefer("setTpmPassword", tpm_password); + CallJSWithPrefixOrDefer("setTpmPassword", tpm_password); } void CoreOobeHandler::ClearErrors() { - CallJSOrDefer("clearErrors"); + CallJSWithPrefixOrDefer("clearErrors"); } void CoreOobeHandler::ReloadContent(const base::DictionaryValue& dictionary) { - CallJSOrDefer("reloadContent", dictionary); + CallJSWithPrefixOrDefer("reloadContent", dictionary); } void CoreOobeHandler::ReloadEulaContent( const base::DictionaryValue& dictionary) { - CallJSOrDefer("reloadEulaContent", dictionary); + CallJSWithPrefixOrDefer("reloadEulaContent", dictionary); } void CoreOobeHandler::ShowControlBar(bool show) { - CallJSOrDefer("showControlBar", show); + CallJSWithPrefixOrDefer("showControlBar", show); } void CoreOobeHandler::SetVirtualKeyboardShown(bool shown) { - CallJSOrDefer("setVirtualKeyboardShown", shown); + CallJSWithPrefixOrDefer("setVirtualKeyboardShown", shown); } void CoreOobeHandler::SetClientAreaSize(int width, int height) { - CallJSOrDefer("setClientAreaSize", width, height); + CallJSWithPrefixOrDefer("setClientAreaSize", width, height); } void CoreOobeHandler::HandleInitialized() { @@ -483,15 +485,15 @@ void CoreOobeHandler::ShowOobeUI(bool show) { void CoreOobeHandler::UpdateShutdownAndRebootVisibility( bool reboot_on_shutdown) { - CallJSOrDefer("showShutdown", !reboot_on_shutdown); + CallJSWithPrefixOrDefer("showShutdown", !reboot_on_shutdown); } void CoreOobeHandler::SetLoginUserCount(int user_count) { - CallJSOrDefer("setLoginUserCount", user_count); + CallJSWithPrefixOrDefer("setLoginUserCount", user_count); } void CoreOobeHandler::ForwardAccelerator(std::string accelerator_name) { - CallJSOrDefer("handleAccelerator", accelerator_name); + CallJSWithPrefixOrDefer("handleAccelerator", accelerator_name); } void CoreOobeHandler::UpdateA11yState() { @@ -507,7 +509,7 @@ void CoreOobeHandler::UpdateA11yState() { a11y_info.SetBoolean( "enableExperimentalA11yFeatures", base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kEnableExperimentalAccessibilityFeatures)); + ::switches::kEnableExperimentalAccessibilityFeatures)); if (!features::IsMultiProcessMash()) { DCHECK(MagnificationManager::Get()); a11y_info.SetBoolean("screenMagnifierEnabled", @@ -522,16 +524,17 @@ void CoreOobeHandler::UpdateA11yState() { } a11y_info.SetBoolean("virtualKeyboardEnabled", AccessibilityManager::Get()->IsVirtualKeyboardEnabled()); - CallJSOrDefer("refreshA11yInfo", a11y_info); + CallJSWithPrefixOrDefer("refreshA11yInfo", a11y_info); } void CoreOobeHandler::UpdateOobeUIVisibility() { const std::string& display = oobe_ui_->display_type(); bool has_api_keys_configured = google_apis::HasAPIKeyConfigured() && google_apis::HasOAuthClientConfigured(); - CallJSOrDefer("showAPIKeysNotice", - !has_api_keys_configured && (display == OobeUI::kOobeDisplay || - display == OobeUI::kLoginDisplay)); + CallJSWithPrefixOrDefer( + "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; @@ -540,10 +543,10 @@ void CoreOobeHandler::UpdateOobeUIVisibility() { channel == version_info::Channel::BETA) { should_show_version = false; } - CallJSOrDefer("showVersion", should_show_version); - CallJSOrDefer("showOobeUI", show_oobe_ui_); + CallJSWithPrefixOrDefer("showVersion", should_show_version); + CallJSWithPrefixOrDefer("showOobeUI", show_oobe_ui_); if (system::InputDeviceSettings::Get()->ForceKeyboardDrivenUINavigation()) - CallJSOrDefer("enableKeyboardFlow", true); + CallJSWithPrefixOrDefer("enableKeyboardFlow", true); } void CoreOobeHandler::OnOSVersionLabelTextUpdated( @@ -553,11 +556,11 @@ void CoreOobeHandler::OnOSVersionLabelTextUpdated( void CoreOobeHandler::OnEnterpriseInfoUpdated(const std::string& message_text, const std::string& asset_id) { - CallJSOrDefer("setEnterpriseInfo", message_text, asset_id); + CallJSWithPrefixOrDefer("setEnterpriseInfo", message_text, asset_id); } void CoreOobeHandler::OnDeviceInfoUpdated(const std::string& bluetooth_name) { - CallJSOrDefer("setBluetoothDeviceInfo", bluetooth_name); + CallJSWithPrefixOrDefer("setBluetoothDeviceInfo", bluetooth_name); } ui::EventSink* CoreOobeHandler::GetEventSink() { @@ -566,7 +569,7 @@ ui::EventSink* CoreOobeHandler::GetEventSink() { void CoreOobeHandler::UpdateLabel(const std::string& id, const std::string& text) { - CallJSOrDefer("setLabelText", id, text); + CallJSWithPrefixOrDefer("setLabelText", id, text); } void CoreOobeHandler::UpdateDeviceRequisition() { @@ -575,8 +578,8 @@ void CoreOobeHandler::UpdateDeviceRequisition() { ->browser_policy_connector_chromeos() ->GetDeviceCloudPolicyManager(); if (policy_manager) { - CallJSOrDefer("updateDeviceRequisition", - policy_manager->GetDeviceRequisition()); + CallJSWithPrefixOrDefer("updateDeviceRequisition", + policy_manager->GetDeviceRequisition()); } } @@ -584,15 +587,15 @@ void CoreOobeHandler::UpdateKeyboardState() { // TODO(crbug.com/646565): Support virtual keyboard under MASH. There is no // KeyboardController in the browser process under MASH. if (!features::IsUsingWindowService()) { - auto* keyboard_controller = keyboard::KeyboardController::Get(); - const bool is_keyboard_shown = keyboard_controller->IsKeyboardVisible(); + const bool is_keyboard_shown = + ChromeKeyboardControllerClient::Get()->is_keyboard_visible(); ShowControlBar(!is_keyboard_shown); SetVirtualKeyboardShown(is_keyboard_shown); } } void CoreOobeHandler::OnTabletModeToggled(bool enabled) { - CallJSOrDefer("setTabletModeState", enabled); + CallJSWithPrefixOrDefer("setTabletModeState", enabled); } void CoreOobeHandler::UpdateClientAreaSize() { @@ -607,7 +610,7 @@ void CoreOobeHandler::OnOobeConfigurationChanged() { OobeConfiguration::Get()->GetConfiguration(), chromeos::configuration::ConfigurationHandlerSide::HANDLER_JS, configuration); - CallJSOrDefer("updateOobeConfiguration", configuration); + CallJSWithPrefixOrDefer("updateOobeConfiguration", configuration); } void CoreOobeHandler::OnAccessibilityStatusChanged( 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 c5b5f83824d..475a236a36f 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 @@ -4,6 +4,9 @@ #include "chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h" +#include "base/strings/string16.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" #include "chrome/browser/chromeos/login/oobe_screen.h" #include "chrome/browser/chromeos/login/screens/demo_setup_screen.h" #include "chrome/grit/generated_resources.h" @@ -38,9 +41,20 @@ 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::OnSetupFailed( + const DemoSetupController::DemoSetupError& error) { + // TODO(wzang): Consider customization for RecoveryMethod::kReboot as well. + CallJSWithPrefix( + "onSetupFailed", + base::JoinString({error.GetLocalizedErrorMessage(), + error.GetLocalizedRecoveryMessage()}, + base::UTF8ToUTF16(" ")), + error.recovery_method() == + DemoSetupController::DemoSetupError::RecoveryMethod::kPowerwash); +} + +void DemoSetupScreenHandler::OnSetupSucceeded() { + CallJSWithPrefix("onSetupSucceeded"); } void DemoSetupScreenHandler::Initialize() {} @@ -51,10 +65,10 @@ void DemoSetupScreenHandler::DeclareLocalizedValues( 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); + builder->Add("demoSetupErrorScreenPowerwashButtonLabel", + IDS_LOCAL_STATE_ERROR_POWERWASH_BUTTON); } } // 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 46c6c14e3f0..ada680e40ca 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 @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DEMO_SETUP_SCREEN_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_DEMO_SETUP_SCREEN_HANDLER_H_ +#include "chrome/browser/chromeos/login/demo_mode/demo_setup_controller.h" #include "chrome/browser/chromeos/login/screens/demo_setup_screen_view.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" @@ -24,7 +25,8 @@ 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; + void OnSetupFailed(const DemoSetupController::DemoSetupError& error) override; + void OnSetupSucceeded() override; // BaseScreenHandler: void Initialize() override; 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 136f9361bb8..17260ecc6ea 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,9 +34,10 @@ void DeviceDisabledScreenHandler::Show() { } if (delegate_) { - CallJS("setSerialNumberAndEnrollmentDomain", delegate_->GetSerialNumber(), - delegate_->GetEnrollmentDomain()); - CallJS("setMessage", delegate_->GetMessage()); + CallJSWithPrefix("setSerialNumberAndEnrollmentDomain", + delegate_->GetSerialNumber(), + delegate_->GetEnrollmentDomain()); + CallJSWithPrefix("setMessage", delegate_->GetMessage()); } ShowScreen(kScreenId); } @@ -53,7 +54,7 @@ void DeviceDisabledScreenHandler::SetDelegate(Delegate* delegate) { void DeviceDisabledScreenHandler::UpdateMessage(const std::string& message) { if (page_is_ready()) - CallJS("setMessage", message); + CallJSWithPrefix("setMessage", message); } void DeviceDisabledScreenHandler::DeclareLocalizedValues( 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 index 636546f33ad..389e69ae5fc 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_manager.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_manager.cc @@ -7,7 +7,6 @@ #include <algorithm> #include "base/logging.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/modules/discover_module_launch_help_app.h" #include "chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.h" @@ -16,16 +15,28 @@ #include "chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_welcome.h" namespace chromeos { +namespace { + +// Owned by ChromeBrowserMainPartsChromeos. +DiscoverManager* g_discover_manager = nullptr; + +} // namespace DiscoverManager::DiscoverManager() { + DCHECK(!g_discover_manager); + g_discover_manager = this; + CreateModules(); } -DiscoverManager::~DiscoverManager() = default; +DiscoverManager::~DiscoverManager() { + DCHECK_EQ(g_discover_manager, this); + g_discover_manager = nullptr; +} // static DiscoverManager* DiscoverManager::Get() { - return g_browser_process->platform_part()->GetDiscoverManager(); + return g_discover_manager; } bool DiscoverManager::IsCompleted() const { diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_window_manager.cc b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_window_manager.cc index 986898a589b..648f2e7b5e4 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_window_manager.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/discover_window_manager.cc @@ -19,6 +19,8 @@ #include "chrome/grit/generated_resources.h" #include "content/public/browser/web_contents.h" #include "ui/aura/client/aura_constants.h" +#include "ui/display/display.h" +#include "ui/display/screen.h" #include "ui/gfx/geometry/rect.h" #include "url/gurl.h" @@ -52,7 +54,7 @@ void DiscoverWindowManager::ShowChromeDiscoverPageForProfile(Profile* profile) { Browser* browser = FindBrowserForProfile(profile); if (browser) { DCHECK(browser->profile() == profile); - const content::WebContents* web_contents = + content::WebContents* web_contents = browser->tab_strip_model()->GetWebContentsAt(0); if (web_contents && web_contents->GetURL() == gurl) { browser->window()->Show(); @@ -87,6 +89,11 @@ void DiscoverWindowManager::ShowChromeDiscoverPageForProfile(Profile* profile) { window->SetProperty(kOverrideWindowIconResourceIdKey, IDR_DISCOVER_APP_192); window->SetProperty(aura::client::kAppType, static_cast<int>(ash::AppType::CHROME_APP)); + // Manually position the window in center of the screen. + gfx::Rect center_in_screen = + display::Screen::GetScreen()->GetDisplayNearestWindow(window).work_area(); + center_in_screen.ClampToCenteredSize(window->bounds().size()); + window->SetBounds(center_in_screen); for (DiscoverWindowManagerObserver& observer : observers_) observer.OnNewDiscoverWindow(params.browser); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc b/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc index 35863208b57..c0d8abefee2 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc @@ -8,6 +8,7 @@ #include "base/i18n/number_formatting.h" #include "base/values.h" +#include "chrome/browser/chromeos/login/quick_unlock/pin_backend.h" #include "chrome/browser/ui/webui/chromeos/login/discover/discover_handler.h" #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" @@ -34,15 +35,22 @@ class DiscoverModulePinSetupHandler : public DiscoverHandler { private: // Message handlers. void HandleGetUserPassword(const std::string& callbackId); + void HandleGetHasLoginSupport(const std::string& callbackId); + + // quick_unlock::PinBackend::HasLoginSupport callback. + void OnPinLoginAvailable(const std::string& callbackId, bool is_available); base::WeakPtr<DiscoverModulePinSetup> module_; + base::WeakPtrFactory<DiscoverModulePinSetupHandler> weak_factory_; DISALLOW_COPY_AND_ASSIGN(DiscoverModulePinSetupHandler); }; DiscoverModulePinSetupHandler::DiscoverModulePinSetupHandler( base::WeakPtr<DiscoverModulePinSetup> module) - : DiscoverHandler(DiscoverModulePinSetup::kModuleName), module_(module) {} + : DiscoverHandler(DiscoverModulePinSetup::kModuleName), + module_(module), + weak_factory_(this) {} void DiscoverModulePinSetupHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) { @@ -57,7 +65,10 @@ void DiscoverModulePinSetupHandler::DeclareLocalizedValues( builder->Add("discoverPinSetupSkip", IDS_DISCOVER_PIN_SETUP_SKIP); builder->Add("discoverPinSetupTitle2", IDS_DISCOVER_PIN_SETUP_TITLE2); builder->Add("discoverPinSetupTitle3", IDS_DISCOVER_PIN_SETUP_TITLE3); - builder->Add("discoverPinSetupSubtitle3", IDS_DISCOVER_PIN_SETUP_SUBTITLE3); + builder->Add("discoverPinSetupSubtitle3NoLogin", + IDS_DISCOVER_PIN_SETUP_SUBTITLE3_NO_LOGIN); + builder->Add("discoverPinSetupSubtitle3WithLogin", + IDS_DISCOVER_PIN_SETUP_SUBTITLE3_WITH_LOGIN); builder->Add("discoverPinSetupPasswordTitle", IDS_DISCOVER_PIN_SETUP_PASSWORD_TITLE); builder->Add("discoverPinSetupPasswordSubTitle", @@ -93,6 +104,8 @@ void DiscoverModulePinSetupHandler::Initialize() {} void DiscoverModulePinSetupHandler::RegisterMessages() { AddCallback("discover.pinSetup.getUserPassword", &DiscoverModulePinSetupHandler::HandleGetUserPassword); + AddCallback("discover.pinSetup.getHasLoginSupport", + &DiscoverModulePinSetupHandler::HandleGetHasLoginSupport); } void DiscoverModulePinSetupHandler::HandleGetUserPassword( @@ -103,6 +116,21 @@ void DiscoverModulePinSetupHandler::HandleGetUserPassword( return; } +void DiscoverModulePinSetupHandler::OnPinLoginAvailable( + const std::string& callbackId, + bool is_available) { + web_ui()->CallJavascriptFunctionUnsafe("window.discoverReturn", + base::Value(callbackId), + base::Value(is_available)); +} + +void DiscoverModulePinSetupHandler::HandleGetHasLoginSupport( + const std::string& callbackId) { + chromeos::quick_unlock::PinBackend::GetInstance()->HasLoginSupport( + base::BindOnce(&DiscoverModulePinSetupHandler::OnPinLoginAvailable, + weak_factory_.GetWeakPtr(), callbackId)); +} + } // anonymous namespace /* ***************************************************************** */ diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc index f7de7178211..647aa3312cc 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc @@ -13,7 +13,7 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "base/task/post_task.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/default_tick_clock.h" @@ -294,7 +294,7 @@ void EncryptionMigrationScreenHandler::SetUserContext( void EncryptionMigrationScreenHandler::SetMode(EncryptionMigrationMode mode) { mode_ = mode; - CallJS("setIsResuming", IsStartImmediately()); + CallJSWithPrefix("setIsResuming", IsStartImmediately()); } void EncryptionMigrationScreenHandler::SetContinueLoginCallback( @@ -309,7 +309,8 @@ void EncryptionMigrationScreenHandler::SetRestartLoginCallback( void EncryptionMigrationScreenHandler::SetupInitialView() { // Pass constant value(s) to the UI. - CallJS("setNecessaryBatteryPercent", arc::kMigrationMinimumBatteryPercent); + CallJSWithPrefix("setNecessaryBatteryPercent", + arc::kMigrationMinimumBatteryPercent); // If old encryption is detected in ARC kiosk mode, skip all checks (user // confirmation, battery level, and remaining space) and start migration @@ -425,10 +426,11 @@ void EncryptionMigrationScreenHandler::PowerChanged( current_battery_percent_ = 100.0; } - CallJS("setBatteryState", *current_battery_percent_, - *current_battery_percent_ >= arc::kMigrationMinimumBatteryPercent, - proto.battery_state() == - power_manager::PowerSupplyProperties_BatteryState_CHARGING); + CallJSWithPrefix( + "setBatteryState", *current_battery_percent_, + *current_battery_percent_ >= arc::kMigrationMinimumBatteryPercent, + proto.battery_state() == + power_manager::PowerSupplyProperties_BatteryState_CHARGING); // If the migration was already requested and the bettery level is enough now, // The migration should start immediately. @@ -486,7 +488,7 @@ void EncryptionMigrationScreenHandler::UpdateUIState(UIState state) { return; current_ui_state_ = state; - CallJS("setUIState", static_cast<int>(state)); + CallJSWithPrefix("setUIState", static_cast<int>(state)); // When this handler is about to show the READY screen, we should get the // latest battery status and show it on the screen. @@ -535,9 +537,9 @@ void EncryptionMigrationScreenHandler::OnGetAvailableStorage(int64_t size) { } } else { RecordFirstScreen(FirstScreen::FIRST_SCREEN_LOW_STORAGE); - CallJS("setAvailableSpaceInString", ui::FormatBytes(size)); - CallJS("setNecessarySpaceInString", - ui::FormatBytes(arc::kMigrationMinimumAvailableStorage)); + CallJSWithPrefix("setAvailableSpaceInString", ui::FormatBytes(size)); + CallJSWithPrefix("setNecessarySpaceInString", + ui::FormatBytes(arc::kMigrationMinimumAvailableStorage)); UpdateUIState(UIState::NOT_ENOUGH_STORAGE); } } @@ -702,7 +704,8 @@ void EncryptionMigrationScreenHandler::DircryptoMigrationProgress( break; case cryptohome::DIRCRYPTO_MIGRATION_IN_PROGRESS: UpdateUIState(GetMigratingUIState()); - CallJS("setMigrationProgress", static_cast<double>(current) / total); + CallJSWithPrefix("setMigrationProgress", + static_cast<double>(current) / total); break; case cryptohome::DIRCRYPTO_MIGRATION_SUCCESS: RecordMigrationResultSuccess(IsResumingIncompleteMigration(), @@ -800,7 +803,7 @@ void EncryptionMigrationScreenHandler::MaybeStopForcingMigration() { // We only want to disable auto-starting migration in the first case. if (mode_ == EncryptionMigrationMode::START_MIGRATION || mode_ == EncryptionMigrationMode::START_MINIMAL_MIGRATION) - CallJS("setIsResuming", false); + CallJSWithPrefix("setIsResuming", false); } } // namespace chromeos 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 7fc1bc3d1ff..6d42c867093 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 @@ -35,6 +35,7 @@ #include "components/login/localized_values_builder.h" #include "components/policy/core/browser/cloud/message_util.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/storage_partition.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/google_service_auth_error.h" @@ -79,8 +80,13 @@ std::string EnrollmentModeToUIMode(policy::EnrollmentConfig::Mode mode) { case policy::EnrollmentConfig::MODE_ATTESTATION_LOCAL_FORCED: case policy::EnrollmentConfig::MODE_ATTESTATION_SERVER_FORCED: case policy::EnrollmentConfig::MODE_ATTESTATION_MANUAL_FALLBACK: + case policy::EnrollmentConfig::MODE_INITIAL_SERVER_FORCED: + case policy::EnrollmentConfig::MODE_ATTESTATION_INITIAL_SERVER_FORCED: + case policy::EnrollmentConfig::MODE_ATTESTATION_INITIAL_MANUAL_FALLBACK: + case policy::EnrollmentConfig::MODE_ATTESTATION_ENROLLMENT_TOKEN: return kEnrollmentModeUIForced; case policy::EnrollmentConfig::MODE_RECOVERY: + case policy::EnrollmentConfig::MODE_ENROLLED_ROLLBACK: return kEnrollmentModeUIRecovery; } @@ -238,7 +244,7 @@ void EnrollmentScreenHandler::ShowSigninScreen() { void EnrollmentScreenHandler::ShowLicenseTypeSelectionScreen( const base::DictionaryValue& license_types) { - CallJS("setAvailableLicenseTypes", license_types); + CallJSWithPrefix("setAvailableLicenseTypes", license_types); ShowStep(kEnrollmentStepPickLicense); } @@ -261,10 +267,10 @@ void EnrollmentScreenHandler::ShowActiveDirectoryScreen( } switch (error) { case authpolicy::ERROR_NONE: { - CallJS("setAdJoinParams", std::string() /* machineName */, - std::string() /* userName */, - static_cast<int>(ActiveDirectoryErrorState::NONE), - show_unlock_password_); + CallJSWithPrefix("setAdJoinParams", std::string() /* machineName */, + std::string() /* userName */, + static_cast<int>(ActiveDirectoryErrorState::NONE), + show_unlock_password_); ShowStep(kEnrollmentStepAdJoin); return; } @@ -274,27 +280,31 @@ void EnrollmentScreenHandler::ShowActiveDirectoryScreen( return; case authpolicy::ERROR_PARSE_UPN_FAILED: case authpolicy::ERROR_BAD_USER_NAME: - CallJS("setAdJoinParams", machine_name, username, - static_cast<int>(ActiveDirectoryErrorState::BAD_USERNAME), - show_unlock_password_); + CallJSWithPrefix( + "setAdJoinParams", machine_name, username, + static_cast<int>(ActiveDirectoryErrorState::BAD_USERNAME), + show_unlock_password_); ShowStep(kEnrollmentStepAdJoin); return; case authpolicy::ERROR_BAD_PASSWORD: - CallJS("setAdJoinParams", machine_name, username, - static_cast<int>(ActiveDirectoryErrorState::BAD_AUTH_PASSWORD), - show_unlock_password_); + CallJSWithPrefix( + "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("setAdJoinParams", machine_name, username, - static_cast<int>(ActiveDirectoryErrorState::MACHINE_NAME_TOO_LONG), - show_unlock_password_); + CallJSWithPrefix( + "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("setAdJoinParams", machine_name, username, - static_cast<int>(ActiveDirectoryErrorState::MACHINE_NAME_INVALID), - show_unlock_password_); + CallJSWithPrefix( + "setAdJoinParams", machine_name, username, + static_cast<int>(ActiveDirectoryErrorState::MACHINE_NAME_INVALID), + show_unlock_password_); ShowStep(kEnrollmentStepAdJoin); return; case authpolicy::ERROR_PASSWORD_EXPIRED: @@ -335,7 +345,7 @@ void EnrollmentScreenHandler::ShowActiveDirectoryScreen( void EnrollmentScreenHandler::ShowAttributePromptScreen( const std::string& asset_id, const std::string& location) { - CallJS("showAttributePromptStep", asset_id, location); + CallJSWithPrefix("showAttributePromptStep", asset_id, location); } void EnrollmentScreenHandler::ShowEnrollmentSpinnerScreen() { @@ -344,8 +354,8 @@ void EnrollmentScreenHandler::ShowEnrollmentSpinnerScreen() { void EnrollmentScreenHandler::ShowAttestationBasedEnrollmentSuccessScreen( const std::string& enterprise_domain) { - CallJS("showAttestationBasedEnrollmentSuccess", ui::GetChromeOSDeviceName(), - enterprise_domain); + CallJSWithPrefix("showAttestationBasedEnrollmentSuccess", + ui::GetChromeOSDeviceName(), enterprise_domain); } void EnrollmentScreenHandler::ShowAuthError( @@ -561,7 +571,10 @@ void EnrollmentScreenHandler::DeclareLocalizedValues( IDS_ENTERPRISE_ENROLLMENT_LOCATION_LABEL); 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("oauthEnrollAbeSuccessDomain", + IDS_ENTERPRISE_ENROLLMENT_SUCCESS_ABE_DOMAIN); + builder->Add("oauthEnrollAbeSuccessSupport", + IDS_ENTERPRISE_ENROLLMENT_SUCCESS_ABE_SUPPORT); /* Active Directory strings */ builder->Add("oauthEnrollAdMachineNameInput", IDS_AD_DEVICE_NAME_INPUT_LABEL); @@ -619,10 +632,11 @@ bool EnrollmentScreenHandler::IsEnrollmentScreenHiddenByError() const { 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_); + CallJSWithPrefix( + "setAdJoinParams", std::string() /* machineName */, + std::string() /* userName */, + static_cast<int>(ActiveDirectoryErrorState::BAD_UNLOCK_PASSWORD), + show_unlock_password_); return; } std::unique_ptr<base::ListValue> options = @@ -631,7 +645,7 @@ void EnrollmentScreenHandler::OnAdConfigurationUnlocked( if (!options) { ShowError(IDS_AD_JOIN_CONFIG_NOT_PARSED, true); show_unlock_password_ = false; - CallJS("setAdJoinConfiguration", base::ListValue()); + CallJSWithPrefix("setAdJoinConfiguration", base::ListValue()); return; } base::DictionaryValue custom; @@ -642,7 +656,7 @@ void EnrollmentScreenHandler::OnAdConfigurationUnlocked( show_unlock_password_ = false; active_directory_join_type_ = ActiveDirectoryDomainJoinType::USING_CONFIGURATION; - CallJS("setAdJoinConfiguration", *options); + CallJSWithPrefix("setAdJoinConfiguration", *options); } void EnrollmentScreenHandler::UpdateState(NetworkError::ErrorReason reason) { @@ -679,7 +693,7 @@ void EnrollmentScreenHandler::UpdateStateInternal( if (is_frame_error) { LOG(WARNING) << "Retry page load"; // TODO(rsorokin): Too many consecutive reloads. - CallJS("doReload"); + CallJSWithPrefix("doReload"); } if (!is_online || is_frame_error) @@ -766,11 +780,40 @@ void EnrollmentScreenHandler::HandleClose(const std::string& reason) { } } -void EnrollmentScreenHandler::HandleCompleteLogin( - const std::string& user, - const std::string& auth_code) { +void EnrollmentScreenHandler::HandleCompleteLogin(const std::string& user) { VLOG(1) << "HandleCompleteLogin"; observe_network_failure_ = false; + + // When the network service is enabled, the webRequest API doesn't expose + // cookie headers. So manually fetch the cookies for the GAIA URL from the + // CookieManager. + login::SigninPartitionManager* signin_partition_manager = + login::SigninPartitionManager::Factory::GetForBrowserContext( + Profile::FromWebUI(web_ui())); + content::StoragePartition* partition = + signin_partition_manager->GetCurrentStoragePartition(); + net::CookieOptions cookie_options; + cookie_options.set_include_httponly(); + + partition->GetCookieManagerForBrowserProcess()->GetCookieList( + GaiaUrls::GetInstance()->gaia_url(), cookie_options, + base::BindOnce(&EnrollmentScreenHandler::OnGetCookiesForCompleteLogin, + weak_ptr_factory_.GetWeakPtr(), user)); +} + +void EnrollmentScreenHandler::OnGetCookiesForCompleteLogin( + const std::string& user, + const std::vector<net::CanonicalCookie>& cookies) { + std::string auth_code; + for (const auto& cookie : cookies) { + if (cookie.Name() == "oauth_code") { + auth_code = cookie.Value(); + break; + } + } + + DCHECK(!auth_code.empty()); + DCHECK(controller_); controller_->OnLoginDone(gaia::SanitizeEmail(user), auth_code); } @@ -827,7 +870,7 @@ void EnrollmentScreenHandler::HandleLicenseTypeSelected( } void EnrollmentScreenHandler::ShowStep(const char* step) { - CallJS("showStep", std::string(step)); + CallJSWithPrefix("showStep", std::string(step)); } void EnrollmentScreenHandler::ShowError(int message_id, bool retry) { @@ -842,7 +885,7 @@ void EnrollmentScreenHandler::ShowErrorForDevice(int message_id, bool retry) { void EnrollmentScreenHandler::ShowErrorMessage(const std::string& message, bool retry) { - CallJS("showError", message, retry); + CallJSWithPrefix("showError", message, retry); } void EnrollmentScreenHandler::DoShow() { 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 a954443ded3..72b47a2cae4 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h @@ -17,6 +17,10 @@ #include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h" #include "net/base/net_errors.h" +namespace net { +class CanonicalCookie; +} + namespace chromeos { class ErrorScreensHistogramHelper; @@ -96,8 +100,10 @@ class EnrollmentScreenHandler // Handlers for WebUI messages. void HandleToggleFakeEnrollment(); void HandleClose(const std::string& reason); - void HandleCompleteLogin(const std::string& user, - const std::string& auth_code); + void HandleCompleteLogin(const std::string& user); + void OnGetCookiesForCompleteLogin( + const std::string& user, + const std::vector<net::CanonicalCookie>& cookies); void HandleAdCompleteLogin(const std::string& machine_name, const std::string& distinguished_name, const std::string& encryption_types, diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.cc index cd4fd7f4593..916a6ac5e90 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.cc @@ -132,15 +132,15 @@ void FingerprintSetupScreenHandler::OnEnrollScanDone( << scan_result << ", enroll_session_complete=" << enroll_session_complete << ", percent_complete=" << percent_complete; - CallJS("onEnrollScanDone", static_cast<int>(scan_result), - enroll_session_complete, percent_complete); + CallJSWithPrefix("onEnrollScanDone", static_cast<int>(scan_result), + enroll_session_complete, percent_complete); if (enroll_session_complete) { enroll_session_started_ = false; ++enrolled_finger_count_; - CallJS("enableAddAnotherFinger", - enrolled_finger_count_ < kMaxAllowedFingerprints); + CallJSWithPrefix("enableAddAnotherFinger", + enrolled_finger_count_ < kMaxAllowedFingerprints); // Update the number of registered fingers, it's fine to override because // this is the first time user log in and have no finger registered. 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 951eb55889b..81f1294ced6 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc @@ -18,7 +18,7 @@ #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "base/task/post_task.h" #include "base/values.h" #include "chrome/browser/browser_process.h" @@ -35,7 +35,6 @@ #include "chrome/browser/chromeos/net/network_portal_detector_impl.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/device_network_configuration_updater.h" -#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/lifetime/browser_shutdown.h" @@ -67,9 +66,11 @@ #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" +#include "content/public/browser/storage_partition.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/nss_temp_certs_cache_chromeos.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" @@ -90,6 +91,9 @@ const char kRestrictiveProxyURL[] = "https://www.google.com/generate_204"; const char kEndpointGen[] = "1.0"; +const char kOAUTHCodeCookie[] = "oauth_code"; +const char kGAPSCookie[] = "GAPS"; + // The possible modes that the Gaia signin screen can be in. enum GaiaScreenMode { // Default Gaia authentication will be used. @@ -351,6 +355,40 @@ void GaiaScreenHandler::LoadGaia(const GaiaContext& context) { void GaiaScreenHandler::LoadGaiaWithPartition( const GaiaContext& context, const std::string& partition_name) { + auto callback = + base::BindOnce(&GaiaScreenHandler::OnSetCookieForLoadGaiaWithPartition, + weak_factory_.GetWeakPtr(), context, partition_name); + if (context.gaps_cookie.empty()) { + std::move(callback).Run(true); + return; + } + + // When the network service is enabled the webRequest API doesn't allow + // modification of the cookie header. So manually write the GAPS cookie into + // the CookieManager. + login::SigninPartitionManager* signin_partition_manager = + login::SigninPartitionManager::Factory::GetForBrowserContext( + Profile::FromWebUI(web_ui())); + content::StoragePartition* partition = + signin_partition_manager->GetCurrentStoragePartition(); + if (!partition) + return; + + std::string gaps_cookie_value(kGAPSCookie); + gaps_cookie_value += "=" + context.gaps_cookie; + std::unique_ptr<net::CanonicalCookie> cc(net::CanonicalCookie::Create( + GaiaUrls::GetInstance()->gaia_url(), gaps_cookie_value, base::Time::Now(), + net::CookieOptions())); + + partition->GetCookieManagerForBrowserProcess()->SetCanonicalCookie( + *cc.get(), true /* secure_source */, true /* modify_http_only */, + std::move(callback)); +} + +void GaiaScreenHandler::OnSetCookieForLoadGaiaWithPartition( + const GaiaContext& context, + const std::string& partition_name, + bool success) { std::unique_ptr<std::string> version = std::make_unique<std::string>(); std::unique_ptr<bool> consent = std::make_unique<bool>(); base::OnceClosure get_version_and_consent = @@ -376,7 +414,6 @@ void GaiaScreenHandler::LoadGaiaWithPartitionAndVersionAndConsent( params.SetString("gaiaId", context.gaia_id); params.SetBoolean("readOnlyEmail", true); params.SetString("email", context.email); - params.SetString("gapsCookie", context.gaps_cookie); UpdateAuthParams(¶ms, IsRestrictiveProxy()); @@ -459,7 +496,7 @@ void GaiaScreenHandler::LoadGaiaWithPartitionAndVersionAndConsent( params.SetString("webviewPartitionName", partition_name); frame_state_ = FRAME_STATE_LOADING; - CallJS("loadAuthExtension", params); + CallJSWithPrefix("loadAuthExtension", params); } void GaiaScreenHandler::ReloadGaia(bool force_reload) { @@ -482,7 +519,7 @@ void GaiaScreenHandler::ReloadGaia(bool force_reload) { } void GaiaScreenHandler::MonitorOfflineIdle(bool is_online) { - CallJS("monitorOfflineIdle", is_online); + CallJSWithPrefix("monitorOfflineIdle", is_online); } void GaiaScreenHandler::DeclareLocalizedValues( @@ -704,16 +741,18 @@ void GaiaScreenHandler::DoAdAuth( break; case authpolicy::ERROR_PARSE_UPN_FAILED: case authpolicy::ERROR_BAD_USER_NAME: - CallJS("invalidateAd", username, - static_cast<int>(ActiveDirectoryErrorState::BAD_USERNAME)); + CallJSWithPrefix( + "invalidateAd", username, + static_cast<int>(ActiveDirectoryErrorState::BAD_USERNAME)); break; case authpolicy::ERROR_BAD_PASSWORD: - CallJS("invalidateAd", username, - static_cast<int>(ActiveDirectoryErrorState::BAD_AUTH_PASSWORD)); + CallJSWithPrefix( + "invalidateAd", username, + static_cast<int>(ActiveDirectoryErrorState::BAD_AUTH_PASSWORD)); break; default: - CallJS("invalidateAd", username, - static_cast<int>(ActiveDirectoryErrorState::NONE)); + CallJSWithPrefix("invalidateAd", username, + static_cast<int>(ActiveDirectoryErrorState::NONE)); core_oobe_view_->ShowSignInError( 0, GetAdErrorMessage(error), std::string(), HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT); @@ -743,13 +782,52 @@ void GaiaScreenHandler::HandleCompleteAuthentication( const std::string& gaia_id, const std::string& email, const std::string& password, - const std::string& auth_code, bool using_saml, - const std::string& gaps_cookie, const ::login::StringList& services) { if (!LoginDisplayHost::default_host()) return; + // When the network service is enabled, the webRequest API doesn't expose + // cookie headers. So manually fetch the cookies for the GAIA URL from the + // CookieManager. + login::SigninPartitionManager* signin_partition_manager = + login::SigninPartitionManager::Factory::GetForBrowserContext( + Profile::FromWebUI(web_ui())); + content::StoragePartition* partition = + signin_partition_manager->GetCurrentStoragePartition(); + if (!partition) + return; + + net::CookieOptions cookie_options; + cookie_options.set_include_httponly(); + + partition->GetCookieManagerForBrowserProcess()->GetCookieList( + GaiaUrls::GetInstance()->gaia_url(), cookie_options, + base::BindOnce(&GaiaScreenHandler::OnGetCookiesForCompleteAuthentication, + weak_factory_.GetWeakPtr(), gaia_id, email, password, + using_saml, services)); +} + +void GaiaScreenHandler::OnGetCookiesForCompleteAuthentication( + const std::string& gaia_id, + const std::string& email, + const std::string& password, + bool using_saml, + const ::login::StringList& services, + const std::vector<net::CanonicalCookie>& cookies) { + std::string auth_code, gaps_cookie; + for (const auto& cookie : cookies) { + if (cookie.Name() == kOAUTHCodeCookie) + auth_code = cookie.Value(); + else if (cookie.Name() == kGAPSCookie) + gaps_cookie = cookie.Value(); + } + + if (auth_code.empty()) { + HandleCompleteLogin(gaia_id, email, password, using_saml); + return; + } + DCHECK(!email.empty()); DCHECK(!gaia_id.empty()); const std::string sanitized_email = gaia::SanitizeEmail(email); @@ -883,9 +961,6 @@ void GaiaScreenHandler::DoCompleteLogin(const std::string& gaia_id, const std::string& typed_email, const std::string& password, bool using_saml) { - if (!LoginDisplayHost::default_host()) - return; - if (using_saml && !using_saml_api_) RecordSAMLScrapingVerificationResultInHistogram(true); @@ -1127,7 +1202,7 @@ void GaiaScreenHandler::ShowGaiaScreenIfReady() { // When the WebUI is destroyed, |untrusted_authority_certs_cache_| will go // out of scope and the certificates will not be held in memory anymore. untrusted_authority_certs_cache_ = - std::make_unique<policy::TempCertsCacheNSS>( + std::make_unique<network::NSSTempCertsCacheChromeOS>( g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->GetDeviceNetworkConfigurationUpdater() @@ -1162,7 +1237,7 @@ void GaiaScreenHandler::ShowWhitelistCheckFailedError() { g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->IsEnterpriseManaged()); - CallJS("showWhitelistCheckFailedError", true, params); + CallJSWithPrefix("showWhitelistCheckFailedError", true, params); } void GaiaScreenHandler::LoadAuthExtension(bool force, 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 f2da30938a3..75fced30d89 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 @@ -20,8 +20,12 @@ class AccountId; -namespace policy { -class TempCertsCacheNSS; +namespace net { +class CanonicalCookie; +} + +namespace network { +class NSSTempCertsCacheChromeOS; } namespace chromeos { @@ -70,6 +74,11 @@ class GaiaScreenHandler : public BaseScreenHandler, void LoadGaiaWithPartition(const GaiaContext& context, const std::string& partition_name); + // Called after the GAPS cookie, if present, is added to the cookie store. + void OnSetCookieForLoadGaiaWithPartition(const GaiaContext& context, + const std::string& partition_name, + bool success); + // Callback that loads GAIA after version and stat consent information has // been retrieved. void LoadGaiaWithPartitionAndVersionAndConsent( @@ -108,10 +117,15 @@ class GaiaScreenHandler : public BaseScreenHandler, void HandleCompleteAuthentication(const std::string& gaia_id, const std::string& email, const std::string& password, - const std::string& auth_code, bool using_saml, - const std::string& gaps_cookie, const ::login::StringList& services); + void OnGetCookiesForCompleteAuthentication( + const std::string& gaia_id, + const std::string& email, + const std::string& password, + bool using_saml, + const ::login::StringList& services, + const std::vector<net::CanonicalCookie>& cookies); void HandleCompleteLogin(const std::string& gaia_id, const std::string& typed_email, const std::string& password, @@ -288,7 +302,8 @@ class GaiaScreenHandler : public BaseScreenHandler, // Makes untrusted authority certificates from device policy available for // client certificate discovery. - std::unique_ptr<policy::TempCertsCacheNSS> untrusted_authority_certs_cache_; + std::unique_ptr<network::NSSTempCertsCacheChromeOS> + untrusted_authority_certs_cache_; base::WeakPtrFactory<GaiaScreenHandler> weak_factory_; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/host_pairing_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/host_pairing_screen_handler.cc index 3d0d0be07c1..5fa2cbb85d0 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/host_pairing_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/host_pairing_screen_handler.cc @@ -118,7 +118,7 @@ void HostPairingScreenHandler::OnContextChanged( context_cache_.ApplyChanges(diff, NULL); return; } - CallJS(kMethodContextChanged, diff); + CallJSWithPrefix(kMethodContextChanged, diff); } std::string HostPairingScreenHandler::GetErrorStringFromAuthError( diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_app_menu_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_app_menu_handler.cc index c490f9533d6..d3bef919dbd 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_app_menu_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_app_menu_handler.cc @@ -11,7 +11,7 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/strings/string_number_conversions.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_autolaunch_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_autolaunch_screen_handler.cc index d2d341d13a6..eff5611b03e 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_autolaunch_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_autolaunch_screen_handler.cc @@ -81,7 +81,7 @@ void KioskAutolaunchScreenHandler::UpdateKioskApp() { icon_url = webui::GetBitmapDataUrl(*app.icon.bitmap()); app_info.SetString("appIconUrl", icon_url); - CallJS("updateApp", app_info); + CallJSWithPrefix("updateApp", app_info); } void KioskAutolaunchScreenHandler::DeclareLocalizedValues( diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc index 16d9eb7ce69..b7934500676 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc @@ -131,7 +131,7 @@ void KioskEnableScreenHandler::OnEnableConsumerKioskAutoLaunch( if (!success) LOG(WARNING) << "Consumer kiosk mode can't be enabled!"; - CallJS("onCompleted", success); + CallJSWithPrefix("onCompleted", success); if (success) { content::NotificationService::current()->Notify( chrome::NOTIFICATION_KIOSK_ENABLED, diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc index 9761fa5a543..21dbb7dbdf7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc @@ -24,8 +24,8 @@ #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/task_runner_util.h" +#include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" -#include "base/threading/thread_restrictions.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/customization/customization_document.h" @@ -349,7 +349,7 @@ void ResolveLanguageListInThreadPool( language_switch_result, const scoped_refptr<base::TaskRunner> task_runner, const UILanguageListResolvedCallback& resolved_callback) { - base::AssertBlockingAllowed(); + base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK); std::string selected_language; if (!language_switch_result) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc index aadf70c5866..8d3dfdc618c 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc @@ -74,7 +74,7 @@ void NetworkScreenHandler::Unbind() { } void NetworkScreenHandler::ShowError(const base::string16& message) { - CallJS("showError", message); + CallJSWithPrefix("showError", message); } void NetworkScreenHandler::ClearErrors() { 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 6d29d83b006..e485a43a713 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc @@ -10,6 +10,7 @@ #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_switches.h" +#include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" #include "base/bind.h" #include "base/command_line.h" #include "base/logging.h" @@ -224,6 +225,8 @@ void AddLockDisplayTypeDefaultResources(content::WebUIDataSource* source) { void AddDiscoverDisplayTypeDefaultResources(content::WebUIDataSource* source) { source->SetDefaultResource(IDR_CHROMEOS_DISCOVER_APP_HTML); source->AddResourcePath(kDiscoverJSPath, IDR_CHROMEOS_DISCOVER_APP_JS); + source->AddResourcePath("manifest.json", IDR_CHROMEOS_DISCOVER_MANIFEST); + source->AddResourcePath("logo.png", IDR_DISCOVER_APP_192); } // Default and non-shared resource definition for kLoginDisplay display type. 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 df7748287f1..cd0f72abb6c 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 @@ -133,7 +133,7 @@ void RecommendAppsScreenHandler::Initialize() {} void RecommendAppsScreenHandler::LoadAppListInUI(const base::Value& app_list) { if (!page_is_ready()) { RecordUmaScreenState(RecommendAppsScreenState::ERROR); - CallJS("showError"); + CallJSWithPrefix("showError"); return; } @@ -142,13 +142,13 @@ void RecommendAppsScreenHandler::LoadAppListInUI(const base::Value& app_list) { 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); + CallJSWithPrefix("setWebview", app_list_webview.as_string()); + CallJSWithPrefix("loadAppList", app_list); } void RecommendAppsScreenHandler::OnLoadError() { RecordUmaScreenState(RecommendAppsScreenState::ERROR); - CallJS("showError"); + CallJSWithPrefix("showError"); } void RecommendAppsScreenHandler::OnLoadSuccess(const base::Value& app_list) { 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 e7d6e4c5de3..13f3646986e 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 @@ -29,7 +29,7 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "chrome/browser/browser_process.h" @@ -530,8 +530,6 @@ void SigninScreenHandler::RegisterMessages() { AddCallback("resyncUserData", &SigninScreenHandler::HandleResyncUserData); AddCallback("loginUIStateChanged", &SigninScreenHandler::HandleLoginUIStateChanged); - AddCallback("unlockOnLoginSuccess", - &SigninScreenHandler::HandleUnlockOnLoginSuccess); AddCallback("showLoadingTimeoutError", &SigninScreenHandler::HandleShowLoadingTimeoutError); AddCallback("focusPod", &SigninScreenHandler::HandleFocusPod); @@ -943,14 +941,14 @@ void SigninScreenHandler::OnWallpaperColorsChanged( dark_muted_color); SkColor scroll_color = SkColorSetA(base_color, ash::login_constants::kScrollTranslucentAlpha); - CallJSOrDefer("login.AccountPickerScreen.setOverlayColors", - color_utils::SkColorToRgbaString(dark_muted_color), - color_utils::SkColorToRgbaString(scroll_color)); + CallJSWithPrefixOrDefer("login.AccountPickerScreen.setOverlayColors", + color_utils::SkColorToRgbaString(dark_muted_color), + color_utils::SkColorToRgbaString(scroll_color)); } void SigninScreenHandler::OnWallpaperBlurChanged(bool blurred) { - CallJSOrDefer("login.AccountPickerScreen.togglePodBackground", - !blurred /*show_pod_background=*/); + CallJSWithPrefixOrDefer("login.AccountPickerScreen.togglePodBackground", + !blurred /*show_pod_background=*/); } void SigninScreenHandler::ClearAndEnablePassword() { @@ -973,26 +971,26 @@ void SigninScreenHandler::UpdatePinKeyboardState(const AccountId& account_id) { void SigninScreenHandler::SetPinEnabledForUser(const AccountId& account_id, bool is_enabled) { - CallJS("login.AccountPickerScreen.setPinEnabledForUser", account_id, - is_enabled); + CallJSWithPrefix("login.AccountPickerScreen.setPinEnabledForUser", account_id, + is_enabled); } void SigninScreenHandler::PreloadPinKeyboard(bool should_preload) { if (should_preload) - CallJS("cr.ui.Oobe.preloadPinKeyboard"); + CallJSWithPrefix("cr.ui.Oobe.preloadPinKeyboard"); } void SigninScreenHandler::OnUserRemoved(const AccountId& account_id, bool last_user_removed) { - CallJS("login.AccountPickerScreen.removeUser", account_id); + CallJSWithPrefix("login.AccountPickerScreen.removeUser", account_id); if (last_user_removed) gaia_screen_handler_->OnShowAddUser(); } void SigninScreenHandler::OnUserImageChanged(const user_manager::User& user) { if (page_is_ready()) { - CallJSOrDefer("login.AccountPickerScreen.updateUserImage", - user.GetAccountId()); + CallJSWithPrefixOrDefer("login.AccountPickerScreen.updateUserImage", + user.GetAccountId()); } } @@ -1067,7 +1065,7 @@ void SigninScreenHandler::ShowWhitelistCheckFailedError() { } void SigninScreenHandler::ShowUnrecoverableCrypthomeErrorDialog() { - CallJS("login.UnrecoverableCryptohomeErrorScreen.show"); + CallJSWithPrefix("login.UnrecoverableCryptohomeErrorScreen.show"); } void SigninScreenHandler::Observe(int type, @@ -1121,7 +1119,8 @@ void SigninScreenHandler::SuspendDone(const base::TimeDelta& sleep_duration) { } void SigninScreenHandler::OnTabletModeToggled(bool enabled) { - CallJSOrDefer("login.AccountPickerScreen.setTabletModeState", enabled); + CallJSWithPrefixOrDefer("login.AccountPickerScreen.setTabletModeState", + enabled); } void SigninScreenHandler::OnSessionStateChanged() { @@ -1170,8 +1169,8 @@ void SigninScreenHandler::OnLockScreenNoteStateChanged( lock_screen_apps_state = kNoLockScreenApps; break; } - CallJSOrDefer("login.AccountPickerScreen.setLockScreenAppsState", - lock_screen_apps_state); + CallJSWithPrefixOrDefer("login.AccountPickerScreen.setLockScreenAppsState", + lock_screen_apps_state); } bool SigninScreenHandler::ShouldLoadGaia() const { @@ -1183,8 +1182,8 @@ bool SigninScreenHandler::ShouldLoadGaia() const { } void SigninScreenHandler::UpdateAddButtonStatus() { - CallJS("cr.ui.login.DisplayManager.updateAddUserButtonStatus", - AllWhitelistedUsersPresent()); + CallJSWithPrefix("cr.ui.login.DisplayManager.updateAddUserButtonStatus", + AllWhitelistedUsersPresent()); } void SigninScreenHandler::HandleAuthenticateUser(const AccountId& account_id, @@ -1221,11 +1220,13 @@ void SigninScreenHandler::AuthenticateExistingUser(const AccountId& account_id, // network. See https://crbug.com/386606 for details. user_context.SetPasswordKey(Key(password)); user_context.SetIsUsingPin(authenticated_by_pin); - if (account_id.GetAccountType() == AccountType::ACTIVE_DIRECTORY && - (user_context.GetUserType() != - user_manager::UserType::USER_TYPE_ACTIVE_DIRECTORY)) { - LOG(FATAL) << "Incorrect Active Directory user type " - << user_context.GetUserType(); + if (account_id.GetAccountType() == AccountType::ACTIVE_DIRECTORY) { + if (user_context.GetUserType() != + user_manager::UserType::USER_TYPE_ACTIVE_DIRECTORY) { + LOG(FATAL) << "Incorrect Active Directory user type " + << user_context.GetUserType(); + } + user_context.SetIsUsingOAuth(false); } delegate_->Login(user_context, SigninSpecifics()); @@ -1345,8 +1346,8 @@ void SigninScreenHandler::HandleToggleKioskAutolaunchScreen() { void SigninScreenHandler::LoadUsers(const user_manager::UserList& users, const base::ListValue& users_list) { - CallJSOrDefer("login.AccountPickerScreen.loadUsers", users_list, - delegate_->IsShowGuest()); + CallJSWithPrefixOrDefer("login.AccountPickerScreen.loadUsers", users_list, + delegate_->IsShowGuest()); // Enable pin for any users who can use it. // TODO(jdufault): Cache pin state in BrowserProcess::local_state() so we @@ -1499,12 +1500,6 @@ void SigninScreenHandler::HandleLoginUIStateChanged(const std::string& source, } } -void SigninScreenHandler::HandleUnlockOnLoginSuccess() { - DCHECK(user_manager::UserManager::Get()->IsUserLoggedIn()); - if (ScreenLocker::default_screen_locker()) - ScreenLocker::default_screen_locker()->UnlockOnLoginSuccess(); -} - void SigninScreenHandler::HandleShowLoadingTimeoutError() { UpdateState(NetworkError::ERROR_REASON_LOADING_TIMEOUT); } @@ -1566,8 +1561,8 @@ void SigninScreenHandler::SendPublicSessionKeyboardLayouts( const AccountId& account_id, const std::string& locale, std::unique_ptr<base::ListValue> keyboard_layouts) { - CallJS("login.AccountPickerScreen.setPublicSessionKeyboardLayouts", - account_id, locale, *keyboard_layouts); + CallJSWithPrefix("login.AccountPickerScreen.setPublicSessionKeyboardLayouts", + account_id, locale, *keyboard_layouts); } void SigninScreenHandler::HandleLaunchKioskApp(const AccountId& app_account_id, @@ -1587,13 +1582,13 @@ void SigninScreenHandler::HandleLaunchArcKioskApp( } void SigninScreenHandler::HandleGetTabletModeState() { - CallJS("login.AccountPickerScreen.setTabletModeState", - TabletModeClient::Get()->tablet_mode_enabled()); + CallJSWithPrefix("login.AccountPickerScreen.setTabletModeState", + TabletModeClient::Get()->tablet_mode_enabled()); } void SigninScreenHandler::HandleGetDemoModeState() { - CallJS("login.AccountPickerScreen.setDemoModeState", - DemoSession::IsDeviceInDemoMode()); + CallJSWithPrefix("login.AccountPickerScreen.setDemoModeState", + DemoSession::IsDeviceInDemoMode()); } void SigninScreenHandler::HandleLogRemoveUserWarningShown() { @@ -1732,7 +1727,8 @@ net::Error SigninScreenHandler::FrameError() const { void SigninScreenHandler::OnCapsLockChanged(bool enabled) { caps_lock_enabled_ = enabled; if (page_is_ready()) - CallJS("login.AccountPickerScreen.setCapsLockState", caps_lock_enabled_); + CallJSWithPrefix("login.AccountPickerScreen.setCapsLockState", + caps_lock_enabled_); } void SigninScreenHandler::OnFeedbackFinished() { @@ -1740,7 +1736,8 @@ void SigninScreenHandler::OnFeedbackFinished() { } void SigninScreenHandler::OnUnrecoverableCryptohomeFeedbackFinished() { - CallJS("login.UnrecoverableCryptohomeErrorScreen.resumeAfterFeedbackUI"); + CallJSWithPrefix( + "login.UnrecoverableCryptohomeErrorScreen.resumeAfterFeedbackUI"); // Recreate user's cryptohome after the feedback is attempted. HandleResyncUserData(); @@ -1791,7 +1788,7 @@ void SigninScreenHandler::UpdateDetachableBaseChangedError() { // focused might be too late to warn the user their keyboard might not be // trusted. if (!focused_pod_account_id_) { - CallJSOrDefer( + CallJSWithPrefixOrDefer( "login.AccountPickerScreen.selectPodForDetachableBaseWarningBubble"); return; } @@ -1818,7 +1815,7 @@ void SigninScreenHandler::UpdateDetachableBaseChangedError() { void SigninScreenHandler::ShowDetachableBaseChangedError() { account_with_detachable_base_error_ = *focused_pod_account_id_; - CallJSOrDefer( + CallJSWithPrefixOrDefer( "cr.ui.login.DisplayManager.showDetachableBaseChangedWarning", *focused_pod_account_id_, l10n_util::GetStringUTF8(IDS_LOGIN_ERROR_DETACHABLE_BASE_CHANGED), @@ -1829,8 +1826,9 @@ void SigninScreenHandler::HideDetachableBaseChangedError() { if (!account_with_detachable_base_error_.has_value()) return; - CallJSOrDefer("cr.ui.login.DisplayManager.hideDetachableBaseChangedWarning", - *account_with_detachable_base_error_); + CallJSWithPrefixOrDefer( + "cr.ui.login.DisplayManager.hideDetachableBaseChangedWarning", + *account_with_detachable_base_error_); account_with_detachable_base_error_ = base::nullopt; } 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 c8e234bf48d..54fd5f42274 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 @@ -386,7 +386,6 @@ class SigninScreenHandler void HandleMigrateUserData(const std::string& password); void HandleResyncUserData(); void HandleLoginUIStateChanged(const std::string& source, bool active); - void HandleUnlockOnLoginSuccess(); void HandleLoginScreenUpdate(); void HandleShowLoadingTimeoutError(); void HandleFocusPod(const AccountId& account_id, bool is_large_pod); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc index 825a45b5fc8..9940e697fd0 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc @@ -4,7 +4,6 @@ #include <stddef.h> -#include "ash/test/ash_test_base.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ptr_util.h" @@ -19,6 +18,7 @@ #include "components/account_id/account_id.h" #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user.h" +#include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -37,7 +37,7 @@ const char* kUsers[] = { namespace chromeos { -class SigninPrepareUserListTest : public ash::AshTestBase, +class SigninPrepareUserListTest : public testing::Test, public MultiProfileUserControllerDelegate { public: SigninPrepareUserListTest() @@ -46,8 +46,9 @@ class SigninPrepareUserListTest : public ash::AshTestBase, ~SigninPrepareUserListTest() override {} + // testing::Test: void SetUp() override { - ash::AshTestBase::SetUp(); + testing::Test::SetUp(); profile_manager_.reset( new TestingProfileManager(TestingBrowserProcess::GetGlobal())); ASSERT_TRUE(profile_manager_->SetUp()); @@ -68,12 +69,16 @@ class SigninPrepareUserListTest : public ash::AshTestBase, void TearDown() override { controller_.reset(); profile_manager_.reset(); - ash::AshTestBase::TearDown(); + testing::Test::TearDown(); } - // MultiProfileUserControllerDelegate overrides: + // MultiProfileUserControllerDelegate: void OnUserNotAllowed(const std::string& user_email) override {} + FakeChromeUserManager* user_manager() { return fake_user_manager_; } + + private: + content::TestBrowserThreadBundle thread_bundle_; ScopedCrosSettingsTestHelper cros_settings_test_helper_; FakeChromeUserManager* fake_user_manager_; user_manager::ScopedUserManager user_manager_enabler_; @@ -85,22 +90,20 @@ class SigninPrepareUserListTest : public ash::AshTestBase, }; TEST_F(SigninPrepareUserListTest, AlwaysKeepOwnerInList) { - EXPECT_LT(kMaxUsers, fake_user_manager_->GetUsers().size()); + EXPECT_LT(kMaxUsers, user_manager()->GetUsers().size()); user_manager::UserList users_to_send = UserSelectionScreen::PrepareUserListForSending( - fake_user_manager_->GetUsers(), AccountId::FromUserEmail(kOwner), - true /* is signin to add */); + user_manager()->GetUsers(), AccountId::FromUserEmail(kOwner), + true /* is_signin_to_add */); EXPECT_EQ(kMaxUsers, users_to_send.size()); EXPECT_EQ(kOwner, users_to_send.back()->GetAccountId().GetUserEmail()); - fake_user_manager_->RemoveUserFromList( - AccountId::FromUserEmail("a16@gmail.com")); - fake_user_manager_->RemoveUserFromList( - AccountId::FromUserEmail("a17@gmail.com")); + user_manager()->RemoveUserFromList(AccountId::FromUserEmail("a16@gmail.com")); + user_manager()->RemoveUserFromList(AccountId::FromUserEmail("a17@gmail.com")); users_to_send = UserSelectionScreen::PrepareUserListForSending( - fake_user_manager_->GetUsers(), AccountId::FromUserEmail(kOwner), - true /* is signin to add */); + user_manager()->GetUsers(), AccountId::FromUserEmail(kOwner), + true /* is_signin_to_add */); EXPECT_EQ(kMaxUsers, users_to_send.size()); EXPECT_EQ("a18@gmail.com", @@ -112,16 +115,16 @@ TEST_F(SigninPrepareUserListTest, AlwaysKeepOwnerInList) { TEST_F(SigninPrepareUserListTest, PublicAccounts) { user_manager::UserList users_to_send = UserSelectionScreen::PrepareUserListForSending( - fake_user_manager_->GetUsers(), AccountId::FromUserEmail(kOwner), - true /* is signin to add */); + user_manager()->GetUsers(), AccountId::FromUserEmail(kOwner), + true /* is_signin_to_add */); EXPECT_EQ(kMaxUsers, users_to_send.size()); EXPECT_EQ("a0@gmail.com", users_to_send.front()->GetAccountId().GetUserEmail()); users_to_send = UserSelectionScreen::PrepareUserListForSending( - fake_user_manager_->GetUsers(), AccountId::FromUserEmail(kOwner), - false /* is signin to add */); + user_manager()->GetUsers(), AccountId::FromUserEmail(kOwner), + false /* is_signin_to_add */); EXPECT_EQ(kMaxUsers, users_to_send.size()); EXPECT_EQ("public0@gmail.com", 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 dbc5fed3484..ac7e6fb4d34 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 @@ -150,7 +150,7 @@ void SyncConsentScreenHandler::Show() { void SyncConsentScreenHandler::Hide() {} void SyncConsentScreenHandler::SetThrobberVisible(bool visible) { - CallJS("setThrobberVisible", visible); + CallJSWithPrefix("setThrobberVisible", visible); } void SyncConsentScreenHandler::Initialize() {} 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 c727fca87fe..f9061891588 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 @@ -177,7 +177,7 @@ void TermsOfServiceScreenHandler::DoShow() { void TermsOfServiceScreenHandler::UpdateDomainInUI() { if (page_is_ready()) - CallJS("setDomain", domain_); + CallJSWithPrefix("setDomain", domain_); } void TermsOfServiceScreenHandler::UpdateTermsOfServiceInUI() { @@ -189,9 +189,9 @@ void TermsOfServiceScreenHandler::UpdateTermsOfServiceInUI() { // download is still in progress and the UI will be updated when the // OnLoadError() or the OnLoadSuccess() callback is called. if (load_error_) - CallJS("setTermsOfServiceLoadError"); + CallJSWithPrefix("setTermsOfServiceLoadError"); else if (!terms_of_service_.empty()) - CallJS("setTermsOfService", terms_of_service_); + CallJSWithPrefix("setTermsOfService", terms_of_service_); } void TermsOfServiceScreenHandler::HandleBack() { diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc index 4add2987606..1a0d37cc75b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc @@ -22,8 +22,6 @@ void UserBoardScreenHandler::DeclareLocalizedValues( void UserBoardScreenHandler::RegisterMessages() { AddCallback("attemptUnlock", &UserBoardScreenHandler::HandleAttemptUnlock); AddCallback("hardlockPod", &UserBoardScreenHandler::HandleHardlockPod); - AddCallback("recordClickOnLockIcon", - &UserBoardScreenHandler::HandleRecordClickOnLockIcon); } void UserBoardScreenHandler::Initialize() { @@ -41,19 +39,13 @@ void UserBoardScreenHandler::HandleAttemptUnlock(const AccountId& account_id) { screen_->AttemptEasyUnlock(account_id); } -void UserBoardScreenHandler::HandleRecordClickOnLockIcon( - const AccountId& account_id) { - CHECK(screen_); - screen_->RecordClickOnLockIcon(account_id); -} - //----------------- API void UserBoardScreenHandler::SetPublicSessionDisplayName( const AccountId& account_id, const std::string& display_name) { - CallJS("login.AccountPickerScreen.setPublicSessionDisplayName", account_id, - display_name); + CallJSWithPrefix("login.AccountPickerScreen.setPublicSessionDisplayName", + account_id, display_name); } void UserBoardScreenHandler::SetPublicSessionLocales( @@ -61,13 +53,20 @@ void UserBoardScreenHandler::SetPublicSessionLocales( std::unique_ptr<base::ListValue> locales, const std::string& default_locale, bool multiple_recommended_locales) { - CallJS("login.AccountPickerScreen.setPublicSessionLocales", account_id, - *locales, default_locale, multiple_recommended_locales); + CallJSWithPrefix("login.AccountPickerScreen.setPublicSessionLocales", + account_id, *locales, default_locale, + multiple_recommended_locales); +} + +void UserBoardScreenHandler::SetPublicSessionShowFullManagementDisclosure( + bool show_full_management_disclosure) { + // This method is only called from browser_tests and shouldn't do anything. } void UserBoardScreenHandler::ShowBannerMessage(const base::string16& message, bool is_warning) { - CallJS("login.AccountPickerScreen.showBannerMessage", message, is_warning); + CallJSWithPrefix("login.AccountPickerScreen.showBannerMessage", message, + is_warning); } void UserBoardScreenHandler::ShowUserPodCustomIcon( @@ -78,20 +77,22 @@ void UserBoardScreenHandler::ShowUserPodCustomIcon( icon_options.ToDictionaryValue(); if (!icon || icon->empty()) return; - CallJS("login.AccountPickerScreen.showUserPodCustomIcon", account_id, *icon); + CallJSWithPrefix("login.AccountPickerScreen.showUserPodCustomIcon", + account_id, *icon); } void UserBoardScreenHandler::HideUserPodCustomIcon( const AccountId& account_id) { - CallJS("login.AccountPickerScreen.hideUserPodCustomIcon", account_id); + CallJSWithPrefix("login.AccountPickerScreen.hideUserPodCustomIcon", + account_id); } void UserBoardScreenHandler::SetAuthType( const AccountId& account_id, proximity_auth::mojom::AuthType auth_type, const base::string16& initial_value) { - CallJS("login.AccountPickerScreen.setAuthType", account_id, - static_cast<int>(auth_type), base::Value(initial_value)); + CallJSWithPrefix("login.AccountPickerScreen.setAuthType", account_id, + static_cast<int>(auth_type), base::Value(initial_value)); } void UserBoardScreenHandler::Bind(UserSelectionScreen* screen) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h index 0d3ee1cf816..471908a2e0f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h @@ -36,7 +36,6 @@ class UserBoardScreenHandler : public BaseScreenHandler, public UserBoardView { // Handlers void HandleHardlockPod(const AccountId& account_id); void HandleAttemptUnlock(const AccountId& account_id); - void HandleRecordClickOnLockIcon(const AccountId& account_id); // UserBoardView implementation: void SetPublicSessionDisplayName(const AccountId& account_id, @@ -45,6 +44,8 @@ class UserBoardScreenHandler : public BaseScreenHandler, public UserBoardView { std::unique_ptr<base::ListValue> locales, const std::string& default_locale, bool multiple_recommended_locales) override; + void SetPublicSessionShowFullManagementDisclosure( + bool show_full_management_disclosure) override; void ShowBannerMessage(const base::string16& message, bool is_warning) override; void ShowUserPodCustomIcon( diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/user_image_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/user_image_screen_handler.cc index c940bc4cae4..053b2242fe5 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/user_image_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/user_image_screen_handler.cc @@ -126,7 +126,7 @@ void UserImageScreenHandler::HandleGetImages() { std::unique_ptr<base::ListValue> default_images = default_user_image::GetAsDictionary(true /* all */); result.Set("images", std::move(default_images)); - CallJS("setDefaultImages", result); + CallJSWithPrefix("setDefaultImages", result); } void UserImageScreenHandler::HandleScreenReady() { @@ -179,7 +179,7 @@ void UserImageScreenHandler::HandleScreenShown() { } void UserImageScreenHandler::HideCurtain() { - CallJS("hideCurtain"); + CallJSWithPrefix("hideCurtain"); } } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.cc index fddcf6302d9..22a3fb42ee7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.cc @@ -39,8 +39,6 @@ #include "components/device_event_log/device_event_log.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/navigation_handle.h" -#include "content/public/browser/render_frame_host.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -65,10 +63,6 @@ const char kJsApiResultOK[] = "ok"; const char kJsDeviceStatusChangedCallback[] = "mobile.MobileSetup.deviceStateChanged"; -const char kJsPortalFrameLoadFailedCallback[] = - "mobile.MobileSetup.portalFrameLoadError"; -const char kJsPortalFrameLoadCompletedCallback[] = - "mobile.MobileSetup.portalFrameLoadCompleted"; const char kJsGetDeviceInfoCallback[] = "mobile.MobileSetupPortal.onGotDeviceInfo"; const char kJsConnectivityChangedCallback[] = @@ -631,33 +625,8 @@ MobileSetupUI::MobileSetupUI(content::WebUI* web_ui) : ui::WebDialogUI(web_ui) { // Set up the chrome://mobilesetup/ source. content::URLDataSource::Add(Profile::FromWebUI(web_ui), std::make_unique<MobileSetupUIHTMLSource>()); - - content::WebContentsObserver::Observe(web_ui->GetWebContents()); } MobileSetupUI::~MobileSetupUI() = default; -void MobileSetupUI::DidFinishNavigation( - content::NavigationHandle* navigation_handle) { - NET_LOG(EVENT) << "MobileSetupUI: DidFinishNavigation. Committed: " - << navigation_handle->HasCommitted() << " Frame: " - << navigation_handle->GetRenderFrameHost()->GetFrameName(); - if (!navigation_handle->HasCommitted() || - navigation_handle->GetRenderFrameHost()->GetFrameName() != - "paymentForm") { - return; - } - - if (navigation_handle->IsErrorPage()) { - NET_LOG(ERROR) << "MobileSetupUI: Error: " - << navigation_handle->GetNetErrorCode(); - base::Value result_value(-navigation_handle->GetNetErrorCode()); - web_ui()->CallJavascriptFunctionUnsafe(kJsPortalFrameLoadFailedCallback, - result_value); - return; - } - - web_ui()->CallJavascriptFunctionUnsafe(kJsPortalFrameLoadCompletedCallback); -} - } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.h b/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.h index a98f2935ff4..8334f116b4a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/mobile_setup_ui.h @@ -12,17 +12,12 @@ namespace chromeos { // A custom WebUI that defines datasource for mobile setup registration page // that is used in Chrome OS activate modem and perform plan subscription tasks. -class MobileSetupUI : public ui::WebDialogUI, - public content::WebContentsObserver { +class MobileSetupUI : public ui::WebDialogUI { public: explicit MobileSetupUI(content::WebUI* web_ui); ~MobileSetupUI() override; private: - // content::WebContentsObserver overrides. - void DidFinishNavigation( - content::NavigationHandle* navigation_handle) override; - DISALLOW_COPY_AND_ASSIGN(MobileSetupUI); }; 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 6c7b76a6e7e..0a43bf28b71 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 @@ -6,12 +6,13 @@ #include "ash/public/cpp/shell_window_ids.h" #include "base/strings/utf_string_conversions.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_handler.h" #include "chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.h" +#include "chrome/browser/ui/webui/metrics_handler.h" #include "chrome/common/url_constants.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/generated_resources.h" @@ -108,6 +109,7 @@ MultiDeviceSetupDialogUI::MultiDeviceSetupDialogUI(content::WebUI* web_ui) } web_ui->AddMessageHandler(std::make_unique<MultideviceSetupHandler>()); + web_ui->AddMessageHandler(std::make_unique<MetricsHandler>()); content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); // Add Mojo bindings to this WebUI so that Mojo calls can occur in JavaScript. diff --git a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc index fa840645971..4945fd1c8eb 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc @@ -6,7 +6,7 @@ #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_handler.h" #include "chrome/common/url_constants.h" diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/OWNERS b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/OWNERS new file mode 100644 index 00000000000..704b95c8e4b --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/OWNERS @@ -0,0 +1 @@ +khorimoto@chromium.org
\ No newline at end of file diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc index fe499876eb0..9312042662d 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/webui/settings/chromeos/smb_handler.h" +#include "chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h" #include <string> #include <utility> @@ -11,10 +11,9 @@ #include "base/values.h" #include "chrome/browser/chromeos/file_system_provider/provided_file_system_info.h" #include "chrome/browser/profiles/profile.h" -#include "content/public/browser/web_ui_message_handler.h" namespace chromeos { -namespace settings { +namespace smb_dialog { namespace { @@ -49,17 +48,20 @@ void SmbHandler::RegisterMessages() { } void SmbHandler::HandleSmbMount(const base::ListValue* args) { - CHECK_EQ(5U, args->GetSize()); + CHECK_EQ(6U, args->GetSize()); + std::string callback_id; + CHECK(args->GetString(0, &callback_id)); + std::string mount_url; std::string mount_name; std::string username; std::string password; bool use_kerberos; - CHECK(args->GetString(0, &mount_url)); - CHECK(args->GetString(1, &mount_name)); - CHECK(args->GetString(2, &username)); - CHECK(args->GetString(3, &password)); - CHECK(args->GetBoolean(4, &use_kerberos)); + CHECK(args->GetString(1, &mount_url)); + CHECK(args->GetString(2, &mount_name)); + CHECK(args->GetString(3, &username)); + CHECK(args->GetString(4, &password)); + CHECK(args->GetBoolean(5, &use_kerberos)); smb_client::SmbService* const service = GetSmbService(profile_); if (!service) { @@ -70,8 +72,9 @@ void SmbHandler::HandleSmbMount(const base::ListValue* args) { mo.display_name = mount_name.empty() ? mount_url : mount_name; mo.writable = true; - auto mount_response = base::BindOnce(&SmbHandler::HandleSmbMountResponse, - weak_ptr_factory_.GetWeakPtr()); + auto mount_response = + base::BindOnce(&SmbHandler::HandleSmbMountResponse, + weak_ptr_factory_.GetWeakPtr(), callback_id); auto mount_call = base::BindOnce(&smb_client::SmbService::Mount, base::Unretained(service), mo, base::FilePath(mount_url), username, password, @@ -84,9 +87,11 @@ void SmbHandler::HandleSmbMount(const base::ListValue* args) { } } -void SmbHandler::HandleSmbMountResponse(SmbMountResult result) { +void SmbHandler::HandleSmbMountResponse(const std::string& callback_id, + SmbMountResult result) { AllowJavascript(); - FireWebUIListener("on-add-smb-share", base::Value(static_cast<int>(result))); + ResolveJavascriptCallback(base::Value(callback_id), + base::Value(static_cast<int>(result))); } void SmbHandler::HandleStartDiscovery(const base::ListValue* args) { @@ -115,6 +120,5 @@ void SmbHandler::HandleGatherSharesResponse( FireWebUIListener("on-shares-found", BuildShareList(shares_gathered)); } - -} // namespace settings +} // namespace smb_dialog } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.h b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h index 42a5602d593..144fe16db71 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/smb_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h @@ -2,33 +2,32 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_SMB_SHARES_SMB_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_SMB_SHARES_SMB_HANDLER_H_ #include "base/callback_forward.h" #include "base/files/file.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/smb_client/smb_service.h" -#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "content/public/browser/web_ui_message_handler.h" class Profile; namespace chromeos { -namespace settings { +namespace smb_dialog { using smb_client::SmbMountResult; -class SmbHandler : public ::settings::SettingsPageUIHandler { +class SmbHandler : public content::WebUIMessageHandler { public: explicit SmbHandler(Profile* profile); ~SmbHandler() override; + private: + // content::WebUIMessageHandler void RegisterMessages() override; - void OnJavascriptAllowed() override {} - void OnJavascriptDisallowed() override {} - private: // WebUI call to mount an Smb Filesystem. void HandleSmbMount(const base::ListValue* args); @@ -36,7 +35,8 @@ class SmbHandler : public ::settings::SettingsPageUIHandler { void HandleStartDiscovery(const base::ListValue* args); // Callback handler for SmbMount. - void HandleSmbMountResponse(SmbMountResult result); + void HandleSmbMountResponse(const std::string& callback_id, + SmbMountResult result); // Callback handler for StartDiscovery. void HandleGatherSharesResponse( @@ -53,7 +53,7 @@ class SmbHandler : public ::settings::SettingsPageUIHandler { DISALLOW_COPY_AND_ASSIGN(SmbHandler); }; -} // namespace settings +} // namespace smb_dialog } // namespace chromeos -#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_SMB_SHARES_SMB_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc new file mode 100644 index 00000000000..9102010d9ce --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc @@ -0,0 +1,87 @@ +// 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/smb_shares/smb_share_dialog.h" + +#include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h" +#include "chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "chrome/grit/generated_resources.h" +#include "components/strings/grit/components_strings.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +namespace chromeos { +namespace smb_dialog { +namespace { + +constexpr int kSmbShareDialogHeight = 442; + +void AddSmbSharesStrings(content::WebUIDataSource* html_source) { + // Add strings specific to smb_dialog. + smb_dialog::AddLocalizedStrings(html_source); + + // Add additional strings that are not specific to smb_dialog. + static const struct { + const char* name; + int id; + } localized_strings[] = { + {"addSmbShare", IDS_SETTINGS_DOWNLOADS_SMB_SHARES_ADD_SHARE}, + {"add", IDS_ADD}, + {"cancel", IDS_CANCEL}, + }; + for (const auto& entry : localized_strings) { + html_source->AddLocalizedString(entry.name, entry.id); + } +} + +} // namespace + +// static +void SmbShareDialog::Show() { + SmbShareDialog* dialog = new SmbShareDialog(); + dialog->ShowSystemDialog(); +} + +SmbShareDialog::SmbShareDialog() + : SystemWebDialogDelegate(GURL(chrome::kChromeUISmbShareURL), + base::string16() /* title */) {} + +SmbShareDialog::~SmbShareDialog() = default; + +void SmbShareDialog::GetDialogSize(gfx::Size* size) const { + size->SetSize(SystemWebDialogDelegate::kDialogWidth, kSmbShareDialogHeight); +} + +SmbShareDialogUI::SmbShareDialogUI(content::WebUI* web_ui) + : ui::WebDialogUI(web_ui) { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(chrome::kChromeUISmbShareHost); + + AddSmbSharesStrings(source); + + const user_manager::User* user = + chromeos::ProfileHelper::Get()->GetUserByProfile( + Profile::FromWebUI(web_ui)); + source->AddBoolean("isActiveDirectoryUser", + user && user->IsActiveDirectoryUser()); + + source->SetJsonPath("strings.js"); + source->SetDefaultResource(IDR_SMB_SHARES_DIALOG_CONTAINER_HTML); + source->AddResourcePath("smb_share_dialog.html", IDR_SMB_SHARES_DIALOG_HTML); + source->AddResourcePath("smb_share_dialog.js", IDR_SMB_SHARES_DIALOG_JS); + + web_ui->AddMessageHandler( + std::make_unique<SmbHandler>(Profile::FromWebUI(web_ui))); + + content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); +} + +SmbShareDialogUI::~SmbShareDialogUI() = default; + +} // namespace smb_dialog +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.h new file mode 100644 index 00000000000..15ff3f6bee9 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.h @@ -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. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_SMB_SHARES_SMB_SHARE_DIALOG_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_SMB_SHARES_SMB_SHARE_DIALOG_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" +#include "ui/web_dialogs/web_dialog_ui.h" + +namespace chromeos { +namespace smb_dialog { + +class SmbShareDialog : public SystemWebDialogDelegate { + public: + // Shows the dialog. + static void Show(); + + protected: + SmbShareDialog(); + ~SmbShareDialog() override; + + // ui::WebDialogDelegate + void GetDialogSize(gfx::Size* size) const override; + + DISALLOW_COPY_AND_ASSIGN(SmbShareDialog); +}; + +class SmbShareDialogUI : public ui::WebDialogUI { + public: + explicit SmbShareDialogUI(content::WebUI* web_ui); + ~SmbShareDialogUI() override; + + DISALLOW_COPY_AND_ASSIGN(SmbShareDialogUI); +}; + +} // namespace smb_dialog +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_SMB_SHARES_SMB_SHARE_DIALOG_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.cc new file mode 100644 index 00000000000..04e14d081c1 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.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/smb_shares/smb_shares_localized_strings_provider.h" + +#include "chrome/grit/generated_resources.h" +#include "content/public/browser/web_ui_data_source.h" + +namespace chromeos { +namespace smb_dialog { + +void AddLocalizedStrings(content::WebUIDataSource* html_source) { + static const struct { + const char* name; + int id; + } localized_strings[] = { + // TODO(baileyberro): Rename these resources since they are no longer in + // settings. + {"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}, + {"smbShareAuthenticationMethod", + IDS_SETTINGS_DOWNLOADS_ADD_SHARE_AUTHENTICATION_METHOD}, + {"smbShareStandardAuthentication", + IDS_SETTINGS_DOWNLOADS_ADD_SHARE_STANDARD_AUTHENTICATION}, + {"smbShareKerberosAuthentication", + IDS_SETTINGS_DOWNLOADS_ADD_SHARE_KERBEROS_AUTHENTICATION}, + {"smbShareAddedSuccessfulMessage", + IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_SUCCESS_MESSAGE}, + {"smbShareAddedErrorMessage", + IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_ERROR_MESSAGE}, + {"smbShareAddedAuthFailedMessage", + IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_AUTH_FAILED_MESSAGE}, + {"smbShareAddedNotFoundMessage", + IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_NOT_FOUND_MESSAGE}, + {"smbShareAddedUnsupportedDeviceMessage", + IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_UNSUPPORTED_DEVICE_MESSAGE}, + {"smbShareAddedMountExistsMessage", + IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_MOUNT_EXISTS_MESSAGE}, + {"smbShareAddedInvalidURLMessage", + IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_MOUNT_INVALID_URL_MESSAGE}, + }; + for (const auto& entry : localized_strings) + html_source->AddLocalizedString(entry.name, entry.id); +} + +} // namespace smb_dialog +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.h b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.h new file mode 100644 index 00000000000..7777906eddb --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.h @@ -0,0 +1,21 @@ +// 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_SMB_SHARES_SMB_SHARES_LOCALIZED_STRINGS_PROVIDER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_SMB_SHARES_SMB_SHARES_LOCALIZED_STRINGS_PROVIDER_H_ + +namespace content { +class WebUIDataSource; +} + +namespace chromeos { +namespace smb_dialog { + +// Adds the strings needed for SMB shares to |html_source|. +void AddLocalizedStrings(content::WebUIDataSource* html_source); + +} // namespace smb_dialog +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_SMB_SHARES_SMB_SHARES_LOCALIZED_STRINGS_PROVIDER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc index eef91e13fa7..d84d732aa42 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc @@ -16,7 +16,7 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/process/process_metrics.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "content/public/browser/browser_thread.h" namespace { diff --git a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h index 7e50ee2b283..5eeb83f85ba 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h +++ b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h @@ -6,14 +6,16 @@ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_SYSTEM_WEB_DIALOG_DELEGATE_H_ #include <string> +#include <vector> #include "base/macros.h" #include "base/strings/string16.h" #include "ui/web_dialogs/web_dialog_delegate.h" #include "url/gurl.h" -// ui::WebDialogDelegate for system Web UI dialogs, e.g. dialogs opened from -// the ash system tray. +// ui::WebDialogDelegate for always-on-top system Web UI dialogs, e.g. dialogs +// opened from the ash system tray. These dialogs are intentionally movable / +// draggable so that content from other pages can be copy-pasted. namespace chromeos { 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 5a36e498cb4..8a1efd471e8 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 @@ -100,9 +100,10 @@ WebContents* ConstrainedWebDialogDelegateBase::GetWebContents() { return web_contents_; } -void ConstrainedWebDialogDelegateBase::HandleKeyboardEvent( +bool ConstrainedWebDialogDelegateBase::HandleKeyboardEvent( content::WebContents* source, const NativeWebKeyboardEvent& event) { + return false; } gfx::Size ConstrainedWebDialogDelegateBase::GetConstrainedWebDialogMinimumSize() diff --git a/chromium/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.h b/chromium/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.h index 56111eb2d2f..bea210cd4c4 100644 --- a/chromium/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.h +++ b/chromium/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.h @@ -51,7 +51,7 @@ class ConstrainedWebDialogDelegateBase void WebContentsDestroyed() override; // WebDialogWebContentsDelegate interface. - void HandleKeyboardEvent( + bool HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; diff --git a/chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc b/chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc index 169792b7339..58b229f3dd6 100644 --- a/chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc +++ b/chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc @@ -20,6 +20,7 @@ #include "content/public/browser/cache_storage_context.h" #include "content/public/browser/indexed_db_context.h" #include "content/public/browser/service_worker_context.h" +#include "content/public/browser/storage_usage_info.h" #include "extensions/buildflags/buildflags.h" #include "net/cookies/canonical_cookie.h" #include "storage/common/fileapi/file_system_types.h" @@ -66,8 +67,6 @@ const char kKeyPersistentUsage[] = "persistentUsage"; const char kKeyCertType[] = "certType"; -const char kKeyScopes[] = "scopes"; - const int64_t kNegligibleUsage = 1024; // 1KiB } // namespace @@ -174,11 +173,12 @@ bool CookiesTreeModelUtil::GetCookieTreeNodeDictionary( case CookieTreeNode::DetailedInfo::TYPE_INDEXED_DB: { dict->SetString(kKeyType, "indexed_db"); - const content::IndexedDBInfo& indexed_db_info = + const content::StorageUsageInfo& indexed_db_info = *node.GetDetailedInfo().indexed_db_info; dict->SetString(kKeyOrigin, indexed_db_info.origin.spec()); - dict->SetString(kKeySize, ui::FormatBytes(indexed_db_info.size)); + dict->SetString(kKeySize, + ui::FormatBytes(indexed_db_info.total_size_bytes)); dict->SetString(kKeyModified, base::UTF16ToUTF8(base::TimeFormatFriendlyDateAndTime( indexed_db_info.last_modified))); @@ -249,18 +249,13 @@ bool CookiesTreeModelUtil::GetCookieTreeNodeDictionary( case CookieTreeNode::DetailedInfo::TYPE_SERVICE_WORKER: { dict->SetString(kKeyType, "service_worker"); - const content::ServiceWorkerUsageInfo& service_worker_info = + const content::StorageUsageInfo& service_worker_info = *node.GetDetailedInfo().service_worker_info; dict->SetString(kKeyOrigin, service_worker_info.origin.spec()); dict->SetString(kKeySize, ui::FormatBytes(service_worker_info.total_size_bytes)); - auto scopes = std::make_unique<base::ListValue>(); - for (auto it = service_worker_info.scopes.begin(); - it != service_worker_info.scopes.end(); ++it) { - scopes->AppendString(it->spec()); - } - dict->Set(kKeyScopes, std::move(scopes)); + // TODO(jsbell): Include kKeyModified like other storage types. break; } case CookieTreeNode::DetailedInfo::TYPE_SHARED_WORKER: { @@ -276,7 +271,7 @@ bool CookiesTreeModelUtil::GetCookieTreeNodeDictionary( case CookieTreeNode::DetailedInfo::TYPE_CACHE_STORAGE: { dict->SetString(kKeyType, "cache_storage"); - const content::CacheStorageUsageInfo& cache_storage_info = + const content::StorageUsageInfo& cache_storage_info = *node.GetDetailedInfo().cache_storage_info; dict->SetString(kKeyOrigin, cache_storage_info.origin.spec()); diff --git a/chromium/chrome/browser/ui/webui/crashes_ui.cc b/chromium/chrome/browser/ui/webui/crashes_ui.cc index 296a09f0863..a5e5fd09899 100644 --- a/chromium/chrome/browser/ui/webui/crashes_ui.cc +++ b/chromium/chrome/browser/ui/webui/crashes_ui.cc @@ -13,7 +13,7 @@ #include "base/macros.h" #include "base/memory/ref_counted_memory.h" #include "base/strings/utf_string_conversions.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/crash_upload_list/crash_upload_list.h" diff --git a/chromium/chrome/browser/ui/webui/devtools_ui.cc b/chromium/chrome/browser/ui/webui/devtools_ui.cc index a99cea43073..cd0819a4600 100644 --- a/chromium/chrome/browser/ui/webui/devtools_ui.cc +++ b/chromium/chrome/browser/ui/webui/devtools_ui.cc @@ -414,11 +414,10 @@ GURL DevToolsUI::GetProxyURL(const std::string& frontend_url) { return GURL(); if (!url.is_valid() || url.host() != kRemoteFrontendDomain) return GURL(); - return GURL(base::StringPrintf("%s://%s/%s/%s", - content::kChromeDevToolsScheme, - chrome::kChromeUIDevToolsHost, - chrome::kChromeUIDevToolsRemotePath, - url.path().substr(1).c_str())); + return GURL(base::StringPrintf( + "%s://%s/%s/%s?%s", content::kChromeDevToolsScheme, + chrome::kChromeUIDevToolsHost, chrome::kChromeUIDevToolsRemotePath, + url.path().substr(1).c_str(), url.query().c_str())); } // static diff --git a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc index 8717e81f821..44340995361 100644 --- a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc +++ b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc @@ -407,6 +407,11 @@ DiscardsUI::DiscardsUI(content::WebUI* web_ui) source->AddResourcePath("sorted_table_behavior.js", IDR_DISCARDS_SORTED_TABLE_BEHAVIOR_JS); + source->AddResourcePath("graph_tab.html", IDR_DISCARDS_GRAPH_TAB_HTML); + source->AddResourcePath("graph_tab.js", IDR_DISCARDS_GRAPH_TAB_JS); + + source->AddResourcePath("mojo_api.html", IDR_DISCARDS_MOJO_API_HTML); + // Full paths (relative to src) are important for Mojom generated files. source->AddResourcePath("chrome/browser/ui/webui/discards/discards.mojom.js", IDR_DISCARDS_MOJO_JS); @@ -421,6 +426,7 @@ DiscardsUI::DiscardsUI(content::WebUI* web_ui) IDR_DISCARDS_MOJO_PUBLIC_BASE_PROCESS_ID_MOJOM_JS); source->SetDefaultResource(IDR_DISCARDS_HTML); + source->UseGzip(); Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource::Add(profile, source.release()); 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 c1398cda519..9a03f2ed840 100644 --- a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc @@ -6,20 +6,16 @@ #include <string> -#include "chrome/browser/domain_reliability/service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" -#include "components/domain_reliability/service.h" +#include "content/public/browser/storage_partition.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" -using domain_reliability::DomainReliabilityService; -using domain_reliability::DomainReliabilityServiceFactory; - DomainReliabilityInternalsUI::DomainReliabilityInternalsUI( content::WebUI* web_ui) - : content::WebUIController(web_ui) { + : content::WebUIController(web_ui), weak_factory_(this) { content::WebUIDataSource* html_source = content::WebUIDataSource::Create( chrome::kChromeUIDomainReliabilityInternalsHost); html_source->OverrideContentSecurityPolicyScriptSrc( @@ -42,29 +38,17 @@ DomainReliabilityInternalsUI::DomainReliabilityInternalsUI( DomainReliabilityInternalsUI::~DomainReliabilityInternalsUI() {} -void DomainReliabilityInternalsUI::UpdateData( - const base::ListValue* args) const { +void DomainReliabilityInternalsUI::UpdateData(const base::ListValue* args) { Profile* profile = Profile::FromWebUI(web_ui()); - DomainReliabilityServiceFactory* factory = - DomainReliabilityServiceFactory::GetInstance(); - DCHECK(profile); - DCHECK(factory); - - DomainReliabilityService* service = factory->GetForBrowserContext(profile); - if (!service) { - base::DictionaryValue* data = new base::DictionaryValue(); - data->SetString("error", "no_service"); - OnDataUpdated(std::unique_ptr<base::Value>(data)); - return; - } - - service->GetWebUIData(base::Bind( - &DomainReliabilityInternalsUI::OnDataUpdated, - base::Unretained(this))); + network::mojom::NetworkContext* network_context = + content::BrowserContext::GetDefaultStoragePartition(profile) + ->GetNetworkContext(); + network_context->GetDomainReliabilityJSON( + base::BindOnce(&DomainReliabilityInternalsUI::OnDataUpdated, + weak_factory_.GetWeakPtr())); } -void DomainReliabilityInternalsUI::OnDataUpdated( - std::unique_ptr<base::Value> data) const { +void DomainReliabilityInternalsUI::OnDataUpdated(base::Value data) const { web_ui()->CallJavascriptFunctionUnsafe( - "DomainReliabilityInternals.onDataUpdated", *data); + "DomainReliabilityInternals.onDataUpdated", data); } diff --git a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.h b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.h index eb29eb65165..62436b50896 100644 --- a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.h +++ b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.h @@ -8,6 +8,7 @@ #include <memory> #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "content/public/browser/web_ui_controller.h" namespace base { @@ -22,8 +23,10 @@ class DomainReliabilityInternalsUI : public content::WebUIController { ~DomainReliabilityInternalsUI() override; private: - void UpdateData(const base::ListValue* args) const; - void OnDataUpdated(std::unique_ptr<base::Value> data) const; + void UpdateData(const base::ListValue* args); + void OnDataUpdated(base::Value data) const; + + base::WeakPtrFactory<DomainReliabilityInternalsUI> weak_factory_; DISALLOW_COPY_AND_ASSIGN(DomainReliabilityInternalsUI); }; diff --git a/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc b/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc index c155bab90ff..7fcbab84ff7 100644 --- a/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc +++ b/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc @@ -16,7 +16,7 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/strings/string_util.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "base/values.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc index dcaad2688c9..eded33bb9ed 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc @@ -203,10 +203,9 @@ void ExtensionIconSource::LoadExtensionImage(const ExtensionResource& icon, int request_id) { ExtensionIconRequest* request = GetData(request_id); ImageLoader::Get(profile_)->LoadImageAsync( - request->extension.get(), - icon, - gfx::Size(request->size, request->size), - base::Bind(&ExtensionIconSource::OnImageLoaded, AsWeakPtr(), request_id)); + request->extension.get(), icon, gfx::Size(request->size, request->size), + base::BindOnce(&ExtensionIconSource::OnImageLoaded, AsWeakPtr(), + request_id)); } void ExtensionIconSource::LoadFaviconImage(int request_id) { diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc b/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc index 39caabc6fc1..4e27efd92d5 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc @@ -6,6 +6,7 @@ #include <string> +#include "base/command_line.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" @@ -17,6 +18,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/web_contents_sizer.h" #include "chrome/common/chrome_paths.h" +#include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/ui_test_utils.h" #include "components/prefs/pref_service.h" @@ -26,6 +28,7 @@ #include "content/public/test/test_utils.h" #include "extensions/browser/extension_dialog_auto_confirm.h" #include "extensions/browser/extension_system.h" +#include "extensions/test/extension_test_message_listener.h" using extensions::Extension; using extensions::TestManagementPolicyProvider; @@ -215,3 +218,56 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsUIBrowserTest, ListenerRegistration) { expect_has_listeners(false); } } + +class ExtensionsActivityLogTest : public ExtensionSettingsUIBrowserTest { + protected: + // Enable command line flags for test. + void SetUpCommandLine(base::CommandLine* command_line) override { + command_line->AppendSwitch(switches::kEnableExtensionActivityLogging); + }; +}; + +IN_PROC_BROWSER_TEST_F(ExtensionsActivityLogTest, TestActivityLogVisible) { + base::FilePath test_data_dir; + ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir)); + test_data_dir = test_data_dir.AppendASCII("extensions"); + extensions::ChromeTestExtensionLoader loader(browser()->profile()); + + ExtensionTestMessageListener listener("ready", false); + scoped_refptr<const extensions::Extension> extension = loader.LoadExtension( + test_data_dir.AppendASCII("activity_log/simple_call")); + ASSERT_TRUE(listener.WaitUntilSatisfied()); + + GURL activity_log_url("chrome://extensions/?activity=" + extension->id()); + ui_test_utils::NavigateToURL(browser(), activity_log_url); + content::WebContents* activity_log_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(activity_log_contents); + EXPECT_EQ(activity_log_url, activity_log_contents->GetLastCommittedURL()); + + // We are looking for the 'tabs.query' entry in the activity log as that is + // the only API call the simple_call.crx extension does. + // The querySelectors and shadowRoots are used here in order to penetrate + // multiple nested shadow DOMs created by Polymer components + // in the chrome://extensions page. + // See chrome/browser/resources/md_extensions for the Polymer code. + // This test only serves as an end to end test, and most of the functionality + // is covered in the JS unit tests. + bool has_api_call = false; + ASSERT_TRUE(content::ExecuteScriptAndExtractBool( + activity_log_contents, + R"(let manager = document.querySelector('extensions-manager'); + let activityLog = + manager.shadowRoot.querySelector('extensions-activity-log'); + activityLog.onDataFetched.promise.then(() => { + Polymer.dom.flush(); + let item = activityLog.shadowRoot.querySelector( + 'activity-log-item'); + let apiCall = item.shadowRoot.getElementById('api-call'); + window.domAutomationController.send( + apiCall.innerText === 'test.sendMessage'); + }); + )", + &has_api_call)); + EXPECT_TRUE(has_api_call); +} diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc index 6b410ca2d28..f1768b469a5 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc @@ -115,10 +115,13 @@ const char* LocationToString(extensions::Manifest::Location loc) { // DICT // "event_listeners": DICT // "count": INT -// "events": LIST +// "listeners": LIST // DICT -// "name": STRING +// "event_name": STRING // "filter": DICT +// "is_for_service_worker": STRING +// "is_lazy": STRING +// "url": STRING // "id": STRING // "keepalive": DICT // "activities": LIST @@ -135,14 +138,18 @@ const char* LocationToString(extensions::Manifest::Location loc) { constexpr base::StringPiece kActivitesKey = "activites"; constexpr base::StringPiece kCountKey = "count"; -constexpr base::StringPiece kEventsKey = "events"; +constexpr base::StringPiece kEventNameKey = "event_name"; constexpr base::StringPiece kEventsListenersKey = "event_listeners"; constexpr base::StringPiece kExtraDataKey = "extra_data"; constexpr base::StringPiece kFilterKey = "filter"; constexpr base::StringPiece kInternalsIdKey = "id"; constexpr base::StringPiece kInternalsNameKey = "name"; constexpr base::StringPiece kInternalsVersionKey = "version"; +constexpr base::StringPiece kIsForServiceWorkerKey = "is_for_service_worker"; +constexpr base::StringPiece kIsLazyKey = "is_lazy"; +constexpr base::StringPiece kListenersKey = "listeners"; constexpr base::StringPiece kKeepaliveKey = "keepalive"; +constexpr base::StringPiece kListenerUrlKey = "url"; constexpr base::StringPiece kLocationKey = "location"; constexpr base::StringPiece kManifestVersionKey = "manifest_version"; constexpr base::StringPiece kPathKey = "path"; @@ -172,30 +179,35 @@ base::Value FormatKeepaliveData(extensions::ProcessManager* process_manager, void AddEventListenerData(extensions::EventRouter* event_router, base::Value* data) { CHECK(data->is_list()); - // A map of extension ID to the event data for that extension, + // A map of extension ID to the listener data for that extension, // which is of type LIST of DICTIONARY. std::unordered_map<base::StringPiece, base::Value, base::StringPieceHash> - events_map; + listeners_map; // Build the map of extension IDs to the list of events. for (const auto& entry : event_router->listeners().listeners()) { for (const auto& listener_entry : entry.second) { - auto& events_list = events_map[listener_entry->extension_id()]; - if (events_list.is_none()) { + auto& listeners_list = listeners_map[listener_entry->extension_id()]; + if (listeners_list.is_none()) { // Not there, so make it a LIST. - events_list = base::Value(base::Value::Type::LIST); + listeners_list = base::Value(base::Value::Type::LIST); } - // The data for each event is a dictionary, with a name and a - // filter. - base::Value event_data(base::Value::Type::DICTIONARY); - event_data.SetKey(kInternalsNameKey, - base::Value(listener_entry->event_name())); + // The data for each listener is a dictionary. + base::Value listener_data(base::Value::Type::DICTIONARY); + listener_data.SetKey(kEventNameKey, + base::Value(listener_entry->event_name())); + listener_data.SetKey( + kIsForServiceWorkerKey, + base::Value(listener_entry->is_for_service_worker())); + listener_data.SetKey(kIsLazyKey, base::Value(listener_entry->IsLazy())); + listener_data.SetKey(kListenerUrlKey, + base::Value(listener_entry->listener_url().spec())); // Add the filter if one exists. base::Value* const filter = listener_entry->filter(); if (filter != nullptr) { - event_data.SetKey(kFilterKey, filter->Clone()); + listener_data.SetKey(kFilterKey, filter->Clone()); } - events_list.GetList().push_back(std::move(event_data)); + listeners_list.GetList().push_back(std::move(listener_data)); } } @@ -203,20 +215,21 @@ void AddEventListenerData(extensions::EventRouter* event_router, for (auto& output_entry : data->GetList()) { const base::Value* const value = output_entry.FindKey(kInternalsIdKey); CHECK(value && value->is_string()); - const auto it = events_map.find(value->GetString()); - base::Value listeners(base::Value::Type::DICTIONARY); - if (it == events_map.end()) { + const auto it = listeners_map.find(value->GetString()); + base::Value event_listeners(base::Value::Type::DICTIONARY); + if (it == listeners_map.end()) { // We didn't find any events, so initialize an empty dictionary. - listeners.SetKey(kCountKey, base::Value(0)); - listeners.SetKey(kEventsKey, base::Value(base::Value::Type::LIST)); + event_listeners.SetKey(kCountKey, base::Value(0)); + event_listeners.SetKey(kListenersKey, + base::Value(base::Value::Type::LIST)); } else { // Set the count and the events values. - listeners.SetKey( + event_listeners.SetKey( kCountKey, base::Value(base::checked_cast<int>(it->second.GetList().size()))); - listeners.SetKey(kEventsKey, std::move(it->second)); + event_listeners.SetKey(kListenersKey, std::move(it->second)); } - output_entry.SetKey(kEventsListenersKey, std::move(listeners)); + output_entry.SetKey(kEventsListenersKey, std::move(event_listeners)); } } diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc index 393653d6692..1b7560672a3 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc @@ -8,6 +8,7 @@ #include <string> #include <utility> +#include "base/command_line.h" #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "base/timer/elapsed_timer.h" @@ -16,6 +17,7 @@ #include "chrome/browser/extensions/chrome_extension_browser_constants.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/metrics_handler.h" +#include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" @@ -48,6 +50,7 @@ namespace extensions { namespace { constexpr char kInDevModeKey[] = "inDevMode"; +constexpr char kShowActivityLogKey[] = "showActivityLog"; constexpr char kLoadTimeClassesKey[] = "loadTimeClasses"; struct LocalizedString { @@ -131,7 +134,8 @@ content::WebUIDataSource* CreateMdExtensionsSource(bool in_dev_mode) { {"noSearchResults", IDS_SEARCH_NO_RESULTS}, {"ok", IDS_OK}, {"save", IDS_SAVE}, - {"searchResults", IDS_SEARCH_RESULTS}, + {"searchResultsPlural", IDS_SEARCH_RESULTS_PLURAL}, + {"searchResultsSingular", IDS_SEARCH_RESULTS_SINGULAR}, // Multi-use strings defined in md_extensions_strings.grdp. {"remove", IDS_MD_EXTENSIONS_REMOVE}, @@ -188,6 +192,7 @@ content::WebUIDataSource* CreateMdExtensionsSource(bool in_dev_mode) { {"accessibilityErrorLine", IDS_MD_EXTENSIONS_ACCESSIBILITY_ERROR_LINE}, {"accessibilityErrorMultiLine", IDS_MD_EXTENSIONS_ACCESSIBILITY_ERROR_MULTI_LINE}, + {"activityLogPageHeading", IDS_MD_EXTENSIONS_ACTIVITY_LOG_PAGE_HEADING}, {"appIcon", IDS_MD_EXTENSIONS_APP_ICON}, {"extensionIcon", IDS_MD_EXTENSIONS_EXTENSION_ICON}, {"extensionA11yAssociation", IDS_MD_EXTENSIONS_EXTENSION_A11Y_ASSOCIATION}, @@ -222,6 +227,8 @@ content::WebUIDataSource* CreateMdExtensionsSource(bool in_dev_mode) { {"loadErrorFileLabel", IDS_MD_EXTENSIONS_LOAD_ERROR_FILE_LABEL}, {"loadErrorErrorLabel", IDS_MD_EXTENSIONS_LOAD_ERROR_ERROR_LABEL}, {"loadErrorRetry", IDS_MD_EXTENSIONS_LOAD_ERROR_RETRY}, + {"loadingActivities", IDS_MD_EXTENSIONS_LOADING_ACTIVITIES}, + {"noActivities", IDS_MD_EXTENSIONS_NO_ACTIVITIES}, {"noErrorsToShow", IDS_EXTENSIONS_ERROR_NO_ERRORS_CODE_MESSAGE}, {"runtimeHostsDialogInputError", IDS_MD_EXTENSIONS_RUNTIME_HOSTS_DIALOG_INPUT_ERROR}, @@ -255,6 +262,7 @@ content::WebUIDataSource* CreateMdExtensionsSource(bool in_dev_mode) { {"toolbarUpdatingToast", IDS_MD_EXTENSIONS_TOOLBAR_UPDATING_TOAST}, {"updateRequiredByPolicy", IDS_MD_EXTENSIONS_DISABLED_UPDATE_REQUIRED_BY_POLICY}, + {"viewActivityLog", IDS_EXTENSIONS_VIEW_ACTIVITY_LOG}, {"viewBackgroundPage", IDS_EXTENSIONS_BACKGROUND_PAGE}, {"viewIncognito", IDS_EXTENSIONS_VIEW_INCOGNITO}, {"viewInactive", IDS_EXTENSIONS_VIEW_INACTIVE}, @@ -314,8 +322,10 @@ content::WebUIDataSource* CreateMdExtensionsSource(bool in_dev_mode) { IDS_MD_EXTENSIONS_HOST_PERMISSIONS_LEARN_MORE, base::ASCIIToUTF16( chrome_extension_constants::kRuntimeHostPermissionsHelpURL))); - source->AddBoolean(kInDevModeKey, in_dev_mode); + source->AddBoolean(kShowActivityLogKey, + base::CommandLine::ForCurrentProcess()->HasSwitch( + ::switches::kEnableExtensionActivityLogging)); source->AddString(kLoadTimeClassesKey, GetLoadTimeClasses(in_dev_mode)); #if BUILDFLAG(OPTIMIZE_WEBUI) diff --git a/chromium/chrome/browser/ui/webui/favicon_source.cc b/chromium/chrome/browser/ui/webui/favicon_source.cc index 79977ba0847..12702ef6e11 100644 --- a/chromium/chrome/browser/ui/webui/favicon_source.cc +++ b/chromium/chrome/browser/ui/webui/favicon_source.cc @@ -13,12 +13,12 @@ #include "chrome/browser/history/top_sites_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/instant_io_context.h" -#include "chrome/browser/sync/profile_sync_service_factory.h" +#include "chrome/browser/sync/session_sync_service_factory.h" #include "chrome/common/url_constants.h" -#include "components/browser_sync/profile_sync_service.h" #include "components/favicon_base/favicon_url_parser.h" #include "components/history/core/browser/top_sites.h" #include "components/sync_sessions/open_tabs_ui_delegate.h" +#include "components/sync_sessions/session_sync_service.h" #include "net/url_request/url_request.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_bundle.h" @@ -160,10 +160,10 @@ bool FaviconSource::ShouldServiceRequest( bool FaviconSource::HandleMissingResource(const IconRequest& request) { // If the favicon is not available, try to use the synced favicon. - browser_sync::ProfileSyncService* sync_service = - ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_); + sync_sessions::SessionSyncService* service = + SessionSyncServiceFactory::GetInstance()->GetForProfile(profile_); sync_sessions::OpenTabsUIDelegate* open_tabs = - sync_service ? sync_service->GetOpenTabsUIDelegate() : nullptr; + service ? service->GetOpenTabsUIDelegate() : nullptr; scoped_refptr<base::RefCountedMemory> response; if (open_tabs && diff --git a/chromium/chrome/browser/ui/webui/flags_ui.cc b/chromium/chrome/browser/ui/webui/flags_ui.cc index 571f79fad3f..37410de78d5 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui.cc +++ b/chromium/chrome/browser/ui/webui/flags_ui.cc @@ -40,7 +40,7 @@ #include "ui/base/resource/resource_bundle.h" #if defined(OS_CHROMEOS) -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h" diff --git a/chromium/chrome/browser/ui/webui/foreign_session_handler.cc b/chromium/chrome/browser/ui/webui/foreign_session_handler.cc index 3ca3252a1c9..873f2030a0e 100644 --- a/chromium/chrome/browser/ui/webui/foreign_session_handler.cc +++ b/chromium/chrome/browser/ui/webui/foreign_session_handler.cc @@ -22,15 +22,15 @@ #include "base/values.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_restore.h" -#include "chrome/browser/sync/profile_sync_service_factory.h" +#include "chrome/browser/sync/session_sync_service_factory.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" -#include "components/browser_sync/profile_sync_service.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/strings/grit/components_strings.h" +#include "components/sync_sessions/session_sync_service.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -142,7 +142,7 @@ std::unique_ptr<base::DictionaryValue> SessionWindowToValue( } // namespace -ForeignSessionHandler::ForeignSessionHandler() : scoped_observer_(this) { +ForeignSessionHandler::ForeignSessionHandler() { load_attempt_time_ = base::TimeTicks::Now(); } @@ -211,25 +211,26 @@ void ForeignSessionHandler::OpenForeignSessionWindows( sync_sessions::OpenTabsUIDelegate* ForeignSessionHandler::GetOpenTabsUIDelegate( content::WebUI* web_ui) { Profile* profile = Profile::FromWebUI(web_ui); - browser_sync::ProfileSyncService* service = - ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile); - - // Only return the delegate if it exists and it is done syncing sessions. - if (service && service->IsSyncFeatureActive()) - return service->GetOpenTabsUIDelegate(); - - return NULL; + sync_sessions::SessionSyncService* service = + SessionSyncServiceFactory::GetInstance()->GetForProfile(profile); + return service ? service->GetOpenTabsUIDelegate() : nullptr; } void ForeignSessionHandler::RegisterMessages() { Profile* profile = Profile::FromWebUI(web_ui()); - browser_sync::ProfileSyncService* service = - ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile); - - // NOTE: The ProfileSyncService can be null in tests. - if (service) - scoped_observer_.Add(service); + sync_sessions::SessionSyncService* service = + SessionSyncServiceFactory::GetInstance()->GetForProfile(profile); + + // NOTE: The SessionSyncService can be null in tests. + if (service) { + // base::Unretained() is safe below because the subscription itself is a + // class member field and handles destruction well. + foreign_session_updated_subscription_ = + service->SubscribeToForeignSessionsChanged( + base::BindRepeating(&ForeignSessionHandler::OnForeignSessionUpdated, + base::Unretained(this))); + } web_ui()->RegisterMessageCallback( "deleteForeignSession", @@ -250,12 +251,7 @@ void ForeignSessionHandler::RegisterMessages() { base::Unretained(this))); } -void ForeignSessionHandler::OnSyncConfigurationCompleted( - syncer::SyncService* sync) { - HandleGetForeignSessions(nullptr); -} - -void ForeignSessionHandler::OnForeignSessionUpdated(syncer::SyncService* sync) { +void ForeignSessionHandler::OnForeignSessionUpdated() { HandleGetForeignSessions(nullptr); } diff --git a/chromium/chrome/browser/ui/webui/foreign_session_handler.h b/chromium/chrome/browser/ui/webui/foreign_session_handler.h index 81712db1c9f..da6b5a1c536 100644 --- a/chromium/chrome/browser/ui/webui/foreign_session_handler.h +++ b/chromium/chrome/browser/ui/webui/foreign_session_handler.h @@ -5,30 +5,25 @@ #ifndef CHROME_BROWSER_UI_WEBUI_FOREIGN_SESSION_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_FOREIGN_SESSION_HANDLER_H_ +#include <memory> #include <string> #include <vector> +#include "base/callback_list.h" #include "base/macros.h" -#include "base/scoped_observer.h" #include "base/time/time.h" #include "chrome/browser/sessions/session_service.h" -#include "components/sync/driver/sync_service_observer.h" #include "components/sync_sessions/open_tabs_ui_delegate.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_message_handler.h" -namespace syncer { -class SyncService; -} - namespace user_prefs { class PrefRegistrySyncable; } namespace browser_sync { -class ForeignSessionHandler : public content::WebUIMessageHandler, - public syncer::SyncServiceObserver { +class ForeignSessionHandler : public content::WebUIMessageHandler { public: // WebUIMessageHandler implementation. void RegisterMessages() override; @@ -53,9 +48,7 @@ class ForeignSessionHandler : public content::WebUIMessageHandler, content::WebUI* web_ui); private: - // syncer::SyncServiceObserver: - void OnSyncConfigurationCompleted(syncer::SyncService* sync) override; - void OnForeignSessionUpdated(syncer::SyncService* sync) override; + void OnForeignSessionUpdated(); // Returns a string used to show the user when a session was last modified. base::string16 FormatSessionTime(const base::Time& time); @@ -78,14 +71,13 @@ class ForeignSessionHandler : public content::WebUIMessageHandler, void HandleSetForeignSessionCollapsed(const base::ListValue* args); - // ScopedObserver used to observe the ProfileSyncService. - ScopedObserver<syncer::SyncService, syncer::SyncServiceObserver> - scoped_observer_; - // The time at which this WebUI was created. Used to calculate how long // the WebUI was present before the sessions data was visible. base::TimeTicks load_attempt_time_; + std::unique_ptr<base::CallbackList<void()>::Subscription> + foreign_session_updated_subscription_; + DISALLOW_COPY_AND_ASSIGN(ForeignSessionHandler); }; diff --git a/chromium/chrome/browser/ui/webui/identity_internals_ui.cc b/chromium/chrome/browser/ui/webui/identity_internals_ui.cc index 8b699ca4cfb..cef07aef301 100644 --- a/chromium/chrome/browser/ui/webui/identity_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/identity_internals_ui.cc @@ -24,7 +24,6 @@ #include "content/public/browser/web_ui_message_handler.h" #include "extensions/browser/extension_registry.h" #include "google_apis/gaia/gaia_auth_fetcher.h" -#include "google_apis/gaia/gaia_constants.h" #include "ui/base/l10n/l10n_util.h" namespace { @@ -275,9 +274,7 @@ IdentityInternalsTokenRevoker::IdentityInternalsTokenRevoker( const std::string& access_token, Profile* profile, IdentityInternalsUIMessageHandler* consumer) - : fetcher_(this, - GaiaConstants::kChromeSource, - profile->GetURLLoaderFactory()), + : fetcher_(this, gaia::GaiaSource::kChrome, profile->GetURLLoaderFactory()), extension_id_(extension_id), access_token_(access_token), consumer_(consumer) { diff --git a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc index d37ffb06772..b75431db9aa 100644 --- a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc +++ b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc @@ -131,8 +131,7 @@ class CaptivePortalBlockingPageWithNetInfo : public CaptivePortalBlockingPage { }; #endif -SSLBlockingPage* CreateSSLBlockingPage(content::WebContents* web_contents, - bool is_superfish) { +SSLBlockingPage* CreateSSLBlockingPage(content::WebContents* web_contents) { // Random parameters for SSL blocking page. int cert_error = net::ERR_CERT_CONTAINS_ERRORS; GURL request_url("https://example.com"); @@ -177,7 +176,7 @@ SSLBlockingPage* CreateSSLBlockingPage(content::WebContents* web_contents, options_mask |= security_interstitials::SSLErrorUI::STRICT_ENFORCEMENT; return SSLBlockingPage::Create( web_contents, cert_error, ssl_info, request_url, options_mask, - time_triggered_, GURL(), nullptr, is_superfish, + time_triggered_, GURL(), nullptr, base::Callback<void(content::CertificateRequestResultType)>()); } @@ -458,11 +457,7 @@ void InterstitialHTMLSource::StartDataRequest( GURL(chrome::kChromeUIInterstitialURL).GetWithEmptyPath().Resolve(path); std::string path_without_query = url.path(); if (path_without_query == "/ssl") { - interstitial_delegate.reset( - CreateSSLBlockingPage(web_contents, false /* is superfish */)); - } else if (path_without_query == "/superfish-ssl") { - interstitial_delegate.reset( - CreateSSLBlockingPage(web_contents, true /* is superfish */)); + interstitial_delegate.reset(CreateSSLBlockingPage(web_contents)); } else if (path_without_query == "/mitm-software-ssl") { interstitial_delegate.reset(CreateMITMSoftwareBlockingPage(web_contents)); } else if (path_without_query == "/safebrowsing") { diff --git a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc index 0543042cbd9..321e9f6ffb8 100644 --- a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc @@ -11,9 +11,11 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/strings/grit/components_strings.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" +#include "ui/base/l10n/l10n_util.h" class InterstitialUITest : public InProcessBrowserTest { public: @@ -21,7 +23,14 @@ class InterstitialUITest : public InProcessBrowserTest { ~InterstitialUITest() override {} protected: - void TestInterstitial(GURL url, const std::string& page_title) { + // Tests interstitial displayed at url to verify that it has the given + // page title and body content that is expected. + // + // page_title must be an exact match, while body content may appear anywhere + // in the rendered page. Thus an empty body_text never fails. + void TestInterstitial(GURL url, + const std::string& page_title, + const base::string16& body_text) { ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ( base::ASCIIToUTF16(page_title), @@ -32,6 +41,30 @@ class InterstitialUITest : public InProcessBrowserTest { DevToolsWindowTesting::OpenDevToolsWindowSync(browser(), true); EXPECT_TRUE(window); DevToolsWindowTesting::CloseDevToolsWindowSync(window); + + if (body_text.empty()) + return; + + content::WebContents* contents = + browser()->tab_strip_model()->GetActiveWebContents(); + + EXPECT_GE(ui_test_utils::FindInPage(contents, body_text, true, true, + nullptr, nullptr), + 1); + } + + // Convenience function to test interstitial pages without provided body_text. + void TestInterstitial(GURL url, + const std::string& page_title) { + TestInterstitial(url, page_title, base::string16()); + } + + // Convenience function to test interstitial pages with l10n message_ids as + // body_text strings. + void TestInterstitial(GURL url, + const std::string& page_title, + int message_id) { + TestInterstitial(url, page_title, l10n_util::GetStringUTF16(message_id)); } }; @@ -57,94 +90,83 @@ IN_PROC_BROWSER_TEST_F(InterstitialUITest, } IN_PROC_BROWSER_TEST_F(InterstitialUITest, SSLInterstitial) { - TestInterstitial( - GURL("chrome://interstitials/ssl"), - "Privacy error"); -} - -IN_PROC_BROWSER_TEST_F(InterstitialUITest, SuperfishInterstitial) { - TestInterstitial(GURL("chrome://interstitials/superfish-ssl"), - "Privacy error"); + TestInterstitial(GURL("chrome://interstitials/ssl"), "Privacy error", + IDS_SSL_V2_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, MITMSoftwareInterstitial) { TestInterstitial(GURL("chrome://interstitials/mitm-software-ssl"), - "Privacy error"); + "Privacy error", IDS_MITM_SOFTWARE_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, PinnedCertInterstitial) { - TestInterstitial(GURL("chrome://interstitials/ssl?type=hpkp_failure"), - "Privacy error"); + TestInterstitial( + GURL("chrome://interstitials/ssl?type=hpkp_failure"), + "Privacy error", + base::ASCIIToUTF16("NET::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN")); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, CTInterstitial) { - TestInterstitial(GURL("chrome://interstitials/ssl?type=ct_failure"), - "Privacy error"); - bool found_ct_error = false; - EXPECT_TRUE(content::ExecuteScriptAndExtractBool( - browser()->tab_strip_model()->GetActiveWebContents(), - "window.domAutomationController.send(document.body.textContent.indexOf('" - "CERTIFICATE_TRANSPARENCY') != -1);", - &found_ct_error)); - EXPECT_TRUE(found_ct_error); + TestInterstitial( + GURL("chrome://interstitials/ssl?type=ct_failure"), + "Privacy error", + base::ASCIIToUTF16("NET::ERR_CERTIFICATE_TRANSPARENCY_REQUIRED")); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, MalwareInterstitial) { - TestInterstitial( - GURL("chrome://interstitials/safebrowsing?type=malware"), - "Security error"); + TestInterstitial(GURL("chrome://interstitials/safebrowsing?type=malware"), + "Security error", IDS_MALWARE_V3_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, PhishingInterstitial) { - TestInterstitial( - GURL("chrome://interstitials/safebrowsing?type=phishing"), - "Security error"); + TestInterstitial(GURL("chrome://interstitials/safebrowsing?type=phishing"), + "Security error", IDS_PHISHING_V4_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, UnwantedSoftwareInterstitial) { TestInterstitial(GURL("chrome://interstitials/safebrowsing?type=unwanted"), - "Security error"); + "Security error", IDS_HARMFUL_V3_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, MalwareInterstitialQuiet) { TestInterstitial( GURL("chrome://interstitials/quietsafebrowsing?type=malware"), - "Security error"); + "Security error", IDS_MALWARE_WEBVIEW_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, PhishingInterstitialQuiet) { TestInterstitial( GURL("chrome://interstitials/quietsafebrowsing?type=phishing"), - "Security error"); + "Security error", IDS_PHISHING_WEBVIEW_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, UnwantedSoftwareInterstitialQuiet) { TestInterstitial( GURL("chrome://interstitials/quietsafebrowsing?type=unwanted"), - "Security error"); + "Security error", IDS_HARMFUL_WEBVIEW_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, BillingInterstitialQuiet) { TestInterstitial( GURL("chrome://interstitials/quietsafebrowsing?type=billing"), - "Security error"); + "Security error", IDS_BILLING_WEBVIEW_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, ClientsideMalwareInterstitial) { TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=clientside_malware"), - "Security error"); + "Security error", IDS_MALWARE_V3_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, ClientsidePhishingInterstitial) { TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=clientside_phishing"), - "Security error"); + "Security error", IDS_PHISHING_V4_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, BillingInterstitial) { TestInterstitial(GURL("chrome://interstitials/safebrowsing?type=billing"), - "Security error"); + "Security error", IDS_BILLING_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, CaptivePortalInterstitial) { diff --git a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.cc index 5227b2379df..deed948d8fc 100644 --- a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.cc @@ -15,6 +15,7 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/flag_descriptions.h" #include "chrome/common/chrome_switches.h" +#include "components/data_reduction_proxy/core/common/data_reduction_proxy_switches.h" #include "components/previews/core/previews_experiments.h" #include "components/previews/core/previews_switches.h" #include "net/nqe/network_quality_estimator_params.h" @@ -49,22 +50,26 @@ const char kOfflinePageFeatureName[] = "OfflinePreviews"; // HTML DOM ID used in the JavaScript code. The IDs are generated here so that // the DOM would have sensible name instead of autogenerated IDs. const char kPreviewsAllowedFlagHtmlId[] = "previews-flag"; -const char kEctFlagHtmlId[] = "ect-flag"; -const char kNoScriptFlagHtmlId[] = "noscript-flag"; -const char kResourceLoadingHintsFlagHtmlId[] = "resource-loading-hints-flag"; const char kOfflinePageFlagHtmlId[] = "offline-page-flag"; +const char kResourceLoadingHintsFlagHtmlId[] = "resource-loading-hints-flag"; +const char kNoScriptFlagHtmlId[] = "noscript-flag"; +const char kEctFlagHtmlId[] = "ect-flag"; const char kIgnorePreviewsBlacklistFlagHtmlId[] = "ignore-previews-blacklist"; +const char kDataSaverAltConfigHtmlId[] = + "data-reduction-proxy-server-experiment"; // Links to flags in chrome://flags. // TODO(thanhdle): Refactor into vector of structs. crbug.com/787010. const char kPreviewsAllowedFlagLink[] = "chrome://flags/#allow-previews"; -const char kEctFlagLink[] = "chrome://flags/#force-effective-connection-type"; -const char kNoScriptFlagLink[] = "chrome://flags/#enable-noscript-previews"; +const char kOfflinePageFlagLink[] = "chrome://flags/#enable-offline-previews"; const char kResourceLoadingHintsFlagLink[] = "chrome://flags/#enable-resource-loading-hints"; -const char kOfflinePageFlagLink[] = "chrome://flags/#enable-offline-previews"; +const char kNoScriptFlagLink[] = "chrome://flags/#enable-noscript-previews"; +const char kEctFlagLink[] = "chrome://flags/#force-effective-connection-type"; const char kIgnorePreviewsBlacklistLink[] = "chrome://flags/#ignore-previews-blacklist"; +const char kDataSaverAltConfigLink[] = + "chrome://flags/#enable-data-reduction-proxy-server-experiment"; const char kDefaultFlagValue[] = "Default"; @@ -203,17 +208,11 @@ void InterventionsInternalsPageHandler::GetPreviewsEnabled( previews_allowed_status->htmlId = kPreviewsAllowedHtmlId; statuses.push_back(std::move(previews_allowed_status)); - auto client_lofi_status = mojom::PreviewsStatus::New(); - client_lofi_status->description = kClientLoFiDescription; - client_lofi_status->enabled = previews::params::IsClientLoFiEnabled(); - client_lofi_status->htmlId = kClientLoFiPreviewsHtmlId; - statuses.push_back(std::move(client_lofi_status)); - - auto noscript_status = mojom::PreviewsStatus::New(); - noscript_status->description = kNoScriptDescription; - noscript_status->enabled = previews::params::IsNoScriptPreviewsEnabled(); - noscript_status->htmlId = kNoScriptPreviewsHtmlId; - statuses.push_back(std::move(noscript_status)); + auto offline_status = mojom::PreviewsStatus::New(); + offline_status->description = kOfflineDesciption; + offline_status->enabled = previews::params::IsOfflinePreviewsEnabled(); + offline_status->htmlId = kOfflinePreviewsHtmlId; + statuses.push_back(std::move(offline_status)); auto resource_loading_hints_status = mojom::PreviewsStatus::New(); resource_loading_hints_status->description = kResourceLoadingHintsDescription; @@ -222,11 +221,17 @@ void InterventionsInternalsPageHandler::GetPreviewsEnabled( resource_loading_hints_status->htmlId = kResourceLoadingHintsHtmlId; statuses.push_back(std::move(resource_loading_hints_status)); - auto offline_status = mojom::PreviewsStatus::New(); - offline_status->description = kOfflineDesciption; - offline_status->enabled = previews::params::IsOfflinePreviewsEnabled(); - offline_status->htmlId = kOfflinePreviewsHtmlId; - statuses.push_back(std::move(offline_status)); + auto noscript_status = mojom::PreviewsStatus::New(); + noscript_status->description = kNoScriptDescription; + noscript_status->enabled = previews::params::IsNoScriptPreviewsEnabled(); + noscript_status->htmlId = kNoScriptPreviewsHtmlId; + statuses.push_back(std::move(noscript_status)); + + auto client_lofi_status = mojom::PreviewsStatus::New(); + client_lofi_status->description = kClientLoFiDescription; + client_lofi_status->enabled = previews::params::IsClientLoFiEnabled(); + client_lofi_status->htmlId = kClientLoFiPreviewsHtmlId; + statuses.push_back(std::move(client_lofi_status)); std::move(callback).Run(std::move(statuses)); } @@ -244,6 +249,35 @@ void InterventionsInternalsPageHandler::GetPreviewsFlagsDetails( previews_allowed_status->htmlId = kPreviewsAllowedFlagHtmlId; flags.push_back(std::move(previews_allowed_status)); + auto offline_page_status = mojom::PreviewsFlag::New(); +#if defined(OS_ANDROID) + offline_page_status->description = + flag_descriptions::kEnableOfflinePreviewsName; + offline_page_status->value = GetFeatureFlagStatus(kOfflinePageFeatureName); +#else + offline_page_status->description = "Offline Page Previews"; + offline_page_status->value = "Only support on Android"; +#endif // OS_ANDROID + offline_page_status->link = kOfflinePageFlagLink; + offline_page_status->htmlId = kOfflinePageFlagHtmlId; + flags.push_back(std::move(offline_page_status)); + + auto resource_loading_hints_status = mojom::PreviewsFlag::New(); + resource_loading_hints_status->description = + flag_descriptions::kEnableResourceLoadingHintsName; + resource_loading_hints_status->link = kResourceLoadingHintsFlagLink; + resource_loading_hints_status->value = + GetFeatureFlagStatus(kResourceLoadingHintsFeatureName); + resource_loading_hints_status->htmlId = kResourceLoadingHintsFlagHtmlId; + flags.push_back(std::move(resource_loading_hints_status)); + + auto noscript_status = mojom::PreviewsFlag::New(); + noscript_status->description = flag_descriptions::kEnableNoScriptPreviewsName; + noscript_status->link = kNoScriptFlagLink; + noscript_status->value = GetFeatureFlagStatus(kNoScriptFeatureName); + noscript_status->htmlId = kNoScriptFlagHtmlId; + flags.push_back(std::move(noscript_status)); + auto ect_status = mojom::PreviewsFlag::New(); ect_status->description = flag_descriptions::kForceEffectiveConnectionTypeName; @@ -264,34 +298,17 @@ void InterventionsInternalsPageHandler::GetPreviewsFlagsDetails( ignore_previews_blacklist->htmlId = kIgnorePreviewsBlacklistFlagHtmlId; flags.push_back(std::move(ignore_previews_blacklist)); - auto noscript_status = mojom::PreviewsFlag::New(); - noscript_status->description = flag_descriptions::kEnableNoScriptPreviewsName; - noscript_status->link = kNoScriptFlagLink; - noscript_status->value = GetFeatureFlagStatus(kNoScriptFeatureName); - noscript_status->htmlId = kNoScriptFlagHtmlId; - flags.push_back(std::move(noscript_status)); - - auto resource_loading_hints_status = mojom::PreviewsFlag::New(); - resource_loading_hints_status->description = - flag_descriptions::kEnableResourceLoadingHintsName; - resource_loading_hints_status->link = kResourceLoadingHintsFlagLink; - resource_loading_hints_status->value = - GetFeatureFlagStatus(kResourceLoadingHintsFeatureName); - resource_loading_hints_status->htmlId = kResourceLoadingHintsFlagHtmlId; - flags.push_back(std::move(resource_loading_hints_status)); - - auto offline_page_status = mojom::PreviewsFlag::New(); -#if defined(OS_ANDROID) - offline_page_status->description = - flag_descriptions::kEnableOfflinePreviewsName; - offline_page_status->value = GetFeatureFlagStatus(kOfflinePageFeatureName); -#else - offline_page_status->description = "Offline Page Previews"; - offline_page_status->value = "Only support on Android"; -#endif // OS_ANDROID - offline_page_status->link = kOfflinePageFlagLink; - offline_page_status->htmlId = kOfflinePageFlagHtmlId; - flags.push_back(std::move(offline_page_status)); + auto alt_config_status = mojom::PreviewsFlag::New(); + alt_config_status->description = + flag_descriptions::kEnableDataReductionProxyServerExperimentDescription; + alt_config_status->link = kDataSaverAltConfigLink; + alt_config_status->value = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + data_reduction_proxy::switches::kDataReductionProxyExperiment); + if (alt_config_status->value.empty()) + alt_config_status->value = kDefaultFlagValue; + alt_config_status->htmlId = kDataSaverAltConfigHtmlId; + flags.push_back(std::move(alt_config_status)); std::move(callback).Run(std::move(flags)); } 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 24fb1d91319..498c0610342 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 @@ -30,6 +30,7 @@ #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" #include "components/blacklist/opt_out_blacklist/opt_out_blacklist_data.h" +#include "components/data_reduction_proxy/core/common/data_reduction_proxy_switches.h" #include "components/previews/content/previews_decider_impl.h" #include "components/previews/content/previews_ui_service.h" #include "components/previews/core/previews_features.h" @@ -48,43 +49,47 @@ namespace { // The HTML DOM ID used in Javascript. constexpr char kPreviewsAllowedHtmlId[] = "previews-allowed-status"; -constexpr char kClientLoFiPreviewsHtmlId[] = "client-lofi-preview-status"; -constexpr char kNoScriptPreviewsHtmlId[] = "noscript-preview-status"; -constexpr char kResourceLoadingHintsHtmlId[] = "resource-loading-hints-status"; constexpr char kOfflinePreviewsHtmlId[] = "offline-preview-status"; +constexpr char kResourceLoadingHintsHtmlId[] = "resource-loading-hints-status"; +constexpr char kNoScriptPreviewsHtmlId[] = "noscript-preview-status"; +constexpr char kClientLoFiPreviewsHtmlId[] = "client-lofi-preview-status"; // Descriptions for previews. constexpr char kPreviewsAllowedDescription[] = "Previews Allowed"; -constexpr char kClientLoFiDescription[] = "Client LoFi Previews"; -constexpr char kNoScriptDescription[] = "NoScript Previews"; +constexpr char kOfflineDesciption[] = "Offline Previews"; constexpr char kResourceLoadingHintsDescription[] = "ResourceLoadingHints Previews"; -constexpr char kOfflineDesciption[] = "Offline Previews"; +constexpr char kNoScriptDescription[] = "NoScript Previews"; +constexpr char kClientLoFiDescription[] = "Client LoFi Previews"; // The HTML DOM ID used in Javascript. +constexpr char kOfflinePageFlagHtmlId[] = "offline-page-flag"; +constexpr char kResourceLoadingHintsFlagHtmlId[] = + "resource-loading-hints-flag"; +constexpr char kNoScriptFlagHtmlId[] = "noscript-flag"; constexpr char kEctFlagHtmlId[] = "ect-flag"; constexpr char kIgnorePreviewsBlacklistFlagHtmlId[] = "ignore-previews-blacklist"; -constexpr char kNoScriptFlagHtmlId[] = "noscript-flag"; -constexpr char kResourceLoadingHintsFlagHtmlId[] = - "resource-loading-hints-flag"; -constexpr char kOfflinePageFlagHtmlId[] = "offline-page-flag"; +constexpr char kDataSaverAltConfigHtmlId[] = + "data-reduction-proxy-server-experiment"; // Links to flags in chrome://flags. -constexpr char kNoScriptFlagLink[] = "chrome://flags/#enable-noscript-previews"; +constexpr char kOfflinePageFlagLink[] = + "chrome://flags/#enable-offline-previews"; constexpr char kResourceLoadingHintsFlagLink[] = "chrome://flags/#enable-resource-loading-hints"; +constexpr char kNoScriptFlagLink[] = "chrome://flags/#enable-noscript-previews"; constexpr char kEctFlagLink[] = "chrome://flags/#force-effective-connection-type"; constexpr char kIgnorePreviewsBlacklistLink[] = "chrome://flags/#ignore-previews-blacklist"; -constexpr char kOfflinePageFlagLink[] = - "chrome://flags/#enable-offline-previews"; +constexpr char kDataSaverAltConfigLink[] = + "chrome://flags/#enable-data-reduction-proxy-server-experiment"; // Flag features names. -constexpr char kNoScriptFeatureName[] = "NoScriptPreviews"; -constexpr char kResourceLoadingHintsFeatureName[] = "ResourceLoadingHints"; constexpr char kOfflinePageFeatureName[] = "OfflinePreviews"; +constexpr char kResourceLoadingHintsFeatureName[] = "ResourceLoadingHints"; +constexpr char kNoScriptFeatureName[] = "NoScriptPreviews"; constexpr char kDefaultFlagValue[] = "Default"; constexpr char kEnabledFlagValue[] = "Enabled"; @@ -203,37 +208,33 @@ class TestPreviewsLogger : public previews::PreviewsLogger { class TestPreviewsDeciderImpl : public previews::PreviewsDeciderImpl { public: TestPreviewsDeciderImpl() - : PreviewsDeciderImpl(nullptr, - nullptr, - base::DefaultClock::GetInstance()) {} + : PreviewsDeciderImpl(base::DefaultClock::GetInstance()) {} // previews::PreviewsDeciderImpl: void Initialize( - base::WeakPtr<previews::PreviewsUIService> previews_ui_service, - std::unique_ptr<blacklist::OptOutStore> opt_out_store, + previews::PreviewsUIService* previews_ui_service, + std::unique_ptr<blacklist::OptOutStore> previews_opt_out_store, std::unique_ptr<previews::PreviewsOptimizationGuide> previews_opt_guide, const previews::PreviewsIsEnabledCallback& is_enabled_callback, - blacklist::BlacklistData::AllowedTypesAndVersions allowed_types) - override { - // Do nothing. - } + blacklist::BlacklistData::AllowedTypesAndVersions allowed_previews) + override {} }; // Mocked TestPreviewsService for testing InterventionsInternalsPageHandler. class TestPreviewsUIService : public previews::PreviewsUIService { public: TestPreviewsUIService( - TestPreviewsDeciderImpl* previews_decider_impl, + std::unique_ptr<previews::PreviewsDeciderImpl> previews_decider_impl, std::unique_ptr<previews::PreviewsLogger> logger, network::TestNetworkQualityTracker* test_network_quality_tracker) - : PreviewsUIService(previews_decider_impl, - nullptr, /* io_task_runner */ - nullptr, /* previews_opt_out_store */ - nullptr, /* previews_opt_guide */ - base::Bind(&MockedPreviewsIsEnabled), - std::move(logger), - blacklist::BlacklistData::AllowedTypesAndVersions(), - test_network_quality_tracker), + : previews::PreviewsUIService( + std::move(previews_decider_impl), + nullptr, /* previews_opt_out_store */ + nullptr, /* previews_opt_guide */ + base::BindRepeating(&MockedPreviewsIsEnabled), + std::move(logger), + blacklist::BlacklistData::AllowedTypesAndVersions(), + test_network_quality_tracker), blacklist_ignored_(false) {} ~TestPreviewsUIService() override {} @@ -258,12 +259,13 @@ class InterventionsInternalsPageHandlerTest : public testing::Test { ~InterventionsInternalsPageHandlerTest() override {} void SetUp() override { - TestPreviewsDeciderImpl io_data; std::unique_ptr<TestPreviewsLogger> logger = std::make_unique<TestPreviewsLogger>(); logger_ = logger.get(); + previews_ui_service_ = std::make_unique<TestPreviewsUIService>( - &io_data, std::move(logger), &test_network_quality_tracker_); + std::make_unique<TestPreviewsDeciderImpl>(), std::move(logger), + &test_network_quality_tracker_); ASSERT_TRUE(profile_manager_.SetUp()); @@ -447,7 +449,7 @@ TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsCount) { page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); - constexpr size_t expected = 6; + constexpr size_t expected = 7; EXPECT_EQ(expected, passed_in_flags.size()); } @@ -642,6 +644,39 @@ TEST_F(InterventionsInternalsPageHandlerTest, resource_loading_hints_flag->second->link); } +TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsAltConfigCustomValue) { + base::test::ScopedCommandLine scoped_command_line; + base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); + std::string flag_value = "alt-porg"; + command_line->AppendSwitchASCII( + data_reduction_proxy::switches::kDataReductionProxyExperiment, + flag_value); + + page_handler_->GetPreviewsFlagsDetails( + base::BindOnce(&MockGetPreviewsFlagsCallback)); + auto alt_config_flag = passed_in_flags.find(kDataSaverAltConfigHtmlId); + + ASSERT_NE(passed_in_flags.end(), alt_config_flag); + EXPECT_EQ( + flag_descriptions::kEnableDataReductionProxyServerExperimentDescription, + alt_config_flag->second->description); + EXPECT_EQ(flag_value, alt_config_flag->second->value); + EXPECT_EQ(kDataSaverAltConfigLink, alt_config_flag->second->link); +} + +TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsAltConfigCustomDefault) { + page_handler_->GetPreviewsFlagsDetails( + base::BindOnce(&MockGetPreviewsFlagsCallback)); + auto alt_config_flag = passed_in_flags.find(kDataSaverAltConfigHtmlId); + + ASSERT_NE(passed_in_flags.end(), alt_config_flag); + EXPECT_EQ( + flag_descriptions::kEnableDataReductionProxyServerExperimentDescription, + alt_config_flag->second->description); + EXPECT_EQ(kDefaultFlagValue, alt_config_flag->second->value); + EXPECT_EQ(kDataSaverAltConfigLink, alt_config_flag->second->link); +} + #if defined(OS_ANDROID) #define TestAndroid(x) x #else 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 5d79f75d4cb..ec6e4d953cf 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 @@ -366,8 +366,6 @@ class LocalDiscoveryUITest : public WebUIBrowserTest { kResponseRegisterComplete); identity::MakePrimaryAccountAvailable( - SigninManagerFactory::GetForProfile(browser()->profile()), - ProfileOAuth2TokenServiceFactory::GetForProfile(browser()->profile()), IdentityManagerFactory::GetForProfile(browser()->profile()), kSampleUser); diff --git a/chromium/chrome/browser/ui/webui/management_ui.cc b/chromium/chrome/browser/ui/webui/management_ui.cc index 5ca91a1dade..3aafbe879b0 100644 --- a/chromium/chrome/browser/ui/webui/management_ui.cc +++ b/chromium/chrome/browser/ui/webui/management_ui.cc @@ -40,6 +40,14 @@ content::WebUIDataSource* CreateManagementUIHtmlSource() { IDS_MANAGEMENT_REPORT_DEVICE_NETWORK_INTERFACES); source->AddLocalizedString(kManagementReportUsers, IDS_MANAGEMENT_REPORT_DEVICE_USERS); + source->AddLocalizedString("localTrustRoots", + IDS_MANAGEMENT_LOCAL_TRUST_ROOTS); + source->AddLocalizedString("managementTrustRootsNotConfigured", + IDS_MANAGEMENT_TRUST_ROOTS_NOT_CONFIGURED); +#if defined(OS_CHROMEOS) + source->AddLocalizedString("managementTrustRootsConfigured", + IDS_MANAGEMENT_TRUST_ROOTS_CONFIGURED); +#endif // defined(OS_CHROMEOS) source->SetJsonPath("strings.js"); // Add required resources. source->AddResourcePath("management.css", IDR_MANAGEMENT_CSS); diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler.cc b/chromium/chrome/browser/ui/webui/management_ui_handler.cc index 494590b0dd1..e3f9cbfb588 100644 --- a/chromium/chrome/browser/ui/webui/management_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/management_ui_handler.cc @@ -28,6 +28,8 @@ #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/policy/device_status_collector.h" +#include "chrome/browser/chromeos/policy/policy_cert_service.h" +#include "chrome/browser/chromeos/policy/policy_cert_service_factory.h" #include "chrome/browser/chromeos/policy/status_uploader.h" #include "chrome/browser/chromeos/policy/system_log_uploader.h" #endif // defined(OS_CHROMEOS) @@ -176,6 +178,10 @@ void ManagementUIHandler::RegisterMessages() { "getExtensions", base::BindRepeating(&ManagementUIHandler::HandleGetExtensions, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getLocalTrustRootsInfo", + base::BindRepeating(&ManagementUIHandler::HandleGetLocalTrustRootsInfo, + base::Unretained(this))); } void ManagementUIHandler::HandleGetDeviceManagementStatus( @@ -225,3 +231,20 @@ void ManagementUIHandler::HandleGetExtensions(const base::ListValue* args) { base::Value(base::Value::Type::LIST)); #endif // BUILDFLAG(ENABLE_EXTENSIONS) } + +void ManagementUIHandler::HandleGetLocalTrustRootsInfo( + const base::ListValue* args) { + CHECK_EQ(1U, args->GetSize()); + base::Value trust_roots_configured(false); +// Only Chrome OS could have installed trusted certificates. +#if defined(OS_CHROMEOS) + policy::PolicyCertService* policy_service = + policy::PolicyCertServiceFactory::GetForProfile( + Profile::FromWebUI(web_ui())); + if (policy_service && policy_service->has_policy_certificates()) + trust_roots_configured = base::Value(true); +#endif // defined(OS_CHROMEOS) + + ResolveJavascriptCallback(args->GetList()[0] /* callback_id */, + trust_roots_configured); +} diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler.h b/chromium/chrome/browser/ui/webui/management_ui_handler.h index b132ce721f5..290a3575b9f 100644 --- a/chromium/chrome/browser/ui/webui/management_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/management_ui_handler.h @@ -39,6 +39,8 @@ class ManagementUIHandler : public content::WebUIMessageHandler { void HandleGetExtensions(const base::ListValue* args); + void HandleGetLocalTrustRootsInfo(const base::ListValue* args); + DISALLOW_COPY_AND_ASSIGN(ManagementUIHandler); }; 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 fea64cc980d..de7b26e67a6 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 @@ -127,6 +127,7 @@ content::WebUIDataSource* CreateMdBookmarksUIHTMLSource(Profile* profile) { IDS_MD_BOOKMARK_MANAGER_SIDEBAR_NODE_COLLAPSE_AX_LABEL); AddLocalizedString(source, "sidebarNodeExpandAxLabel", IDS_MD_BOOKMARK_MANAGER_SIDEBAR_NODE_EXPAND_AX_LABEL); + AddLocalizedString(source, "searchCleared", IDS_SEARCH_CLEARED); AddLocalizedString(source, "searchResults", IDS_SEARCH_RESULTS); AddLocalizedString(source, "saveEdit", IDS_SAVE); AddLocalizedString(source, "title", IDS_MD_BOOKMARK_MANAGER_TITLE); diff --git a/chromium/chrome/browser/ui/webui/md_downloads/OWNERS b/chromium/chrome/browser/ui/webui/md_downloads/OWNERS index 53ef569f103..8eefb55c2d8 100644 --- a/chromium/chrome/browser/ui/webui/md_downloads/OWNERS +++ b/chromium/chrome/browser/ui/webui/md_downloads/OWNERS @@ -1,3 +1,4 @@ asanka@chromium.org +dbeam@chromium.org # COMPONENT: UI>Browser>Downloads 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 a231a3f9753..f90700ec5e2 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 @@ -486,7 +486,7 @@ void MdDownloadsDOMHandler::RetryDownload(const base::ListValue* args) { render_frame_host->GetRoutingID(), 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); + dl_params->set_download_source(download::DownloadSource::RETRY); content::BrowserContext::GetDownloadManager(web_contents->GetBrowserContext()) ->DownloadUrl(std::move(dl_params)); 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 878c3ca58db..8347db4e1cc 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 @@ -44,7 +44,9 @@ content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) { content::WebUIDataSource::Create(chrome::kChromeUIDownloadsHost); source->AddLocalizedString("title", IDS_DOWNLOAD_TITLE); - source->AddLocalizedString("searchResultsFor", IDS_SEARCH_RESULTS); + source->AddLocalizedString("searchResultsPlural", IDS_SEARCH_RESULTS_PLURAL); + source->AddLocalizedString("searchResultsSingular", + IDS_SEARCH_RESULTS_SINGULAR); source->AddLocalizedString("downloads", IDS_DOWNLOAD_TITLE); source->AddLocalizedString("clearAll", IDS_DOWNLOAD_LINK_CLEAR_ALL); @@ -82,6 +84,8 @@ content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) { source->AddLocalizedString("controlCancel", IDS_DOWNLOAD_LINK_CANCEL); source->AddLocalizedString("controlResume", IDS_DOWNLOAD_LINK_RESUME); source->AddLocalizedString("controlRemoveFromList", IDS_DOWNLOAD_LINK_REMOVE); + source->AddLocalizedString("controlRemoveFromListAriaLabel", + IDS_DOWNLOAD_LINK_REMOVE_ARIA_LABEL); source->AddLocalizedString("controlRetry", IDS_MD_DOWNLOAD_LINK_RETRY); source->AddLocalizedString("controlledByUrl", IDS_DOWNLOAD_BY_EXTENSION_URL); diff --git a/chromium/chrome/browser/ui/webui/md_history_ui.cc b/chromium/chrome/browser/ui/webui/md_history_ui.cc index 46df9d42ef5..607573b6de3 100644 --- a/chromium/chrome/browser/ui/webui/md_history_ui.cc +++ b/chromium/chrome/browser/ui/webui/md_history_ui.cc @@ -55,6 +55,8 @@ content::WebUIDataSource* CreateMdHistoryUIHTMLSource(Profile* profile, content::WebUIDataSource::Create(chrome::kChromeUIHistoryHost); // Localized strings (alphabetical order). + source->AddLocalizedString("actionMenuDescription", + IDS_HISTORY_ACTION_MENU_DESCRIPTION); source->AddLocalizedString("bookmarked", IDS_HISTORY_ENTRY_BOOKMARKED); source->AddLocalizedString("cancel", IDS_CANCEL); source->AddLocalizedString("clearBrowsingData", @@ -82,8 +84,6 @@ content::WebUIDataSource* CreateMdHistoryUIHTMLSource(Profile* profile, source->AddLocalizedString("itemsSelected", IDS_MD_HISTORY_ITEMS_SELECTED); source->AddLocalizedString("loading", IDS_HISTORY_LOADING); source->AddLocalizedString("menuPromo", IDS_MD_HISTORY_MENU_PROMO); - source->AddLocalizedString("moreActionsButton", - IDS_HISTORY_ACTION_MENU_DESCRIPTION); source->AddLocalizedString("moreFromSite", IDS_HISTORY_MORE_FROM_SITE); source->AddLocalizedString("openAll", IDS_HISTORY_OTHER_SESSIONS_OPEN_ALL); source->AddLocalizedString("openTabsMenuItem", 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 5c6001c2537..0f8cf09cd95 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 @@ -4,9 +4,6 @@ #include "chrome/browser/ui/webui/media_router/media_router_ui.h" -#include <algorithm> -#include <string> -#include <unordered_map> #include <utility> #include "base/guid.h" @@ -61,7 +58,6 @@ namespace media_router { MediaRouterUI::MediaRouterUI(content::WebUI* web_ui) : ConstrainedWebDialogUI(web_ui), - ui_initialized_(false), weak_factory_(this) { auto handler = std::make_unique<MediaRouterWebUIMessageHandler>(this); handler_ = handler.get(); @@ -106,7 +102,7 @@ bool MediaRouterUI::ConnectRoute(const MediaSink::Id& sink_id, base::Optional<RouteParameters> params = GetRouteParameters(sink_id, MediaCastMode::PRESENTATION); if (!params) { - SendIssueForUnableToCast(MediaCastMode::PRESENTATION); + SendIssueForUnableToCast(MediaCastMode::PRESENTATION, sink_id); return false; } GetIssueManager()->ClearNonBlockingIssues(); @@ -177,7 +173,7 @@ std::string MediaRouterUI::GetPresentationRequestSourceName() const { : GetHostFromURL(gurl); } -const std::set<MediaCastMode>& MediaRouterUI::cast_modes() const { +const std::set<MediaCastMode>& MediaRouterUI::GetCastModes() const { return cast_modes_; } @@ -319,8 +315,6 @@ void MediaRouterUI::OnRouteResponseReceived( route_request_id, sink_id, cast_mode, presentation_request_source_name, result); handler_->OnCreateRouteResponseReceived(sink_id, result.route()); - if (result.result_code() == RouteRequestResult::TIMED_OUT) - SendIssueForRouteTimeout(cast_mode, presentation_request_source_name); } void MediaRouterUI::HandleCreateSessionRequestRouteResponse( @@ -368,14 +362,14 @@ void MediaRouterUI::UpdateCastModes() { // UI. cast_modes_ = query_result_manager()->GetSupportedCastModes(); if (ui_initialized_) { - handler_->UpdateCastModes(cast_modes(), GetPresentationRequestSourceName(), - forced_cast_mode()); + handler_->UpdateCastModes( + GetCastModes(), GetPresentationRequestSourceName(), forced_cast_mode()); } } void MediaRouterUI::UpdateRoutesToCastModesMapping() { std::unordered_map<MediaSource::Id, MediaCastMode> available_source_map; - for (const auto& cast_mode : cast_modes()) { + for (const auto& cast_mode : GetCastModes()) { for (const auto& source : GetSourcesForCastMode(cast_mode)) available_source_map.insert(std::make_pair(source.id(), cast_mode)); } 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 acf5fe70e64..531fdf243f2 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 @@ -5,6 +5,12 @@ #ifndef CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_UI_H_ #define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_UI_H_ +#include <memory> +#include <set> +#include <string> +#include <unordered_map> +#include <vector> + #include "base/macros.h" #include "base/strings/string16.h" #include "chrome/browser/media/router/mojo/media_route_controller.h" @@ -61,7 +67,7 @@ class MediaRouterUI : public MediaRouterUIBase, public ConstrainedWebDialogUI { const std::vector<MediaRoute::Id>& joinable_route_ids() const { return joinable_route_ids_; } - virtual const std::set<MediaCastMode>& cast_modes() const; + virtual const std::set<MediaCastMode>& GetCastModes() const; const std::unordered_map<MediaRoute::Id, MediaCastMode>& routes_and_cast_modes() const { return routes_and_cast_modes_; @@ -128,7 +134,7 @@ class MediaRouterUI : public MediaRouterUIBase, public ConstrainedWebDialogUI { class UIMediaRouteControllerObserver : public MediaRouteController::Observer { public: - explicit UIMediaRouteControllerObserver( + UIMediaRouteControllerObserver( MediaRouterUI* ui, scoped_refptr<MediaRouteController> controller); ~UIMediaRouteControllerObserver() override; @@ -138,7 +144,7 @@ class MediaRouterUI : public MediaRouterUIBase, public ConstrainedWebDialogUI { void OnControllerInvalidated() override; private: - MediaRouterUI* ui_; + MediaRouterUI* const ui_; DISALLOW_COPY_AND_ASSIGN(UIMediaRouteControllerObserver); }; @@ -204,7 +210,7 @@ class MediaRouterUI : public MediaRouterUIBase, public ConstrainedWebDialogUI { MediaRouterWebUIMessageHandler* handler_ = nullptr; // Set to true by |handler_| when the UI has been initialized. - bool ui_initialized_; + bool ui_initialized_ = false; std::vector<MediaRoute::Id> joinable_route_ids_; CastModeSet cast_modes_; diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc index 4db9b29b5ef..865e1044ff7 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc @@ -787,7 +787,7 @@ TEST_F(MediaRouterUITest, SetsForcedCastModeWithPresentationURLs) { media_router_ui_->InitForTest( &mock_router_, web_contents(), message_handler_.get(), std::move(start_presentation_context_), nullptr); - EXPECT_EQ(expected_modes, media_router_ui_->cast_modes()); + EXPECT_EQ(expected_modes, media_router_ui_->GetCastModes()); EXPECT_EQ(base::Optional<MediaCastMode>(MediaCastMode::PRESENTATION), media_router_ui_->forced_cast_mode()); EXPECT_EQ("google.com", media_router_ui_->GetPresentationRequestSourceName()); 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 3f8d6b069df..a401598170c 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 @@ -541,7 +541,7 @@ void MediaRouterWebUIMessageHandler::OnRequestInitialData( media_router_ui_->routes_and_cast_modes())); initial_data.Set("routes", std::move(routes)); - const std::set<MediaCastMode> cast_modes = media_router_ui_->cast_modes(); + const std::set<MediaCastMode>& cast_modes = media_router_ui_->GetCastModes(); std::unique_ptr<base::ListValue> cast_modes_list(CastModesToValue( cast_modes, media_router_ui_->GetPresentationRequestSourceName(), media_router_ui_->forced_cast_mode())); @@ -700,7 +700,11 @@ void MediaRouterWebUIMessageHandler::OnCloseRoute(const base::ListValue* args) { return; } media_router_ui_->TerminateRoute(route_id); - UMA_HISTOGRAM_BOOLEAN("MediaRouter.Ui.Action.StopRoute", !is_local); + if (is_local) { + MediaRouterMetrics::RecordStopLocalRoute(); + } else { + MediaRouterMetrics::RecordStopRemoteRoute(); + } } void MediaRouterWebUIMessageHandler::OnCloseDialog( diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc index ec9102f0988..17268d133eb 100644 --- a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc @@ -5,6 +5,8 @@ #include "chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h" #include <memory> +#include <set> +#include <utility> #include "base/macros.h" #include "base/strings/stringprintf.h" @@ -95,7 +97,7 @@ class MockMediaRouterUI : public MediaRouterUI { MOCK_CONST_METHOD0(UserSelectedTabMirroringForCurrentOrigin, bool()); MOCK_METHOD1(RecordCastModeSelection, void(MediaCastMode cast_mode)); MOCK_CONST_METHOD0(GetPresentationRequestSourceName, std::string()); - MOCK_CONST_METHOD0(cast_modes, const std::set<MediaCastMode>&()); + MOCK_CONST_METHOD0(GetCastModes, const std::set<MediaCastMode>&()); MOCK_METHOD1(OnMediaControllerUIAvailable, void(const MediaRoute::Id& route_id)); MOCK_METHOD0(OnMediaControllerUIClosed, void()); @@ -169,7 +171,7 @@ class MediaRouterWebUIMessageHandlerTest : public MediaRouterWebUITest { // Gets the call data for the function call made to |web_ui_|. There needs // to be one call made, and its function name must be |function_name|. const base::Value* GetCallData(const std::string& function_name) { - CHECK(1u == web_ui_->call_data().size()); + CHECK_EQ(1u, web_ui_->call_data().size()); const content::TestWebUI::CallData& call_data = *web_ui_->call_data()[0]; CHECK(function_name == call_data.function_name()); return call_data.arg1(); @@ -553,7 +555,7 @@ TEST_F(MediaRouterWebUIMessageHandlerTest, RecordCastModeSelection) { TEST_F(MediaRouterWebUIMessageHandlerTest, RetrieveCastModeSelection) { base::ListValue args; std::set<MediaCastMode> cast_modes = {MediaCastMode::TAB_MIRROR}; - EXPECT_CALL(*mock_media_router_ui_, cast_modes()) + EXPECT_CALL(*mock_media_router_ui_, GetCastModes()) .WillRepeatedly(ReturnRef(cast_modes)); EXPECT_CALL(*mock_media_router_ui_, GetPresentationRequestSourceName()) diff --git a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc index a6ba9903433..01ef46ef398 100644 --- a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc @@ -288,8 +288,8 @@ void MemoryInternalsDOMHandler::GetChildProcessesOnIOThread( if (data.process_type == content::PROCESS_TYPE_GPU || data.process_type == content::PROCESS_TYPE_UTILITY) { - result.push_back(MakeProcessInfo(base::GetProcId(data.GetHandle()), - GetChildDescription(data))); + result.push_back( + MakeProcessInfo(data.GetProcess().Pid(), GetChildDescription(data))); } } diff --git a/chromium/chrome/browser/ui/webui/net_export_ui.cc b/chromium/chrome/browser/ui/webui/net_export_ui.cc index 38c8ac0ed0e..62796358a2a 100644 --- a/chromium/chrome/browser/ui/webui/net_export_ui.cc +++ b/chromium/chrome/browser/ui/webui/net_export_ui.cc @@ -250,14 +250,8 @@ void NetExportMessageHandler::OnStopNetLog(const base::ListValue* list) { new base::DictionaryValue()); Profile* profile = Profile::FromWebUI(web_ui()); - SetIfNotNull(ui_thread_polled_data.get(), "dataReductionProxyInfo", - chrome_browser_net::GetDataReductionProxyInfo(profile)); - SetIfNotNull(ui_thread_polled_data.get(), "historicNetworkStats", - chrome_browser_net::GetHistoricNetworkStats(profile)); SetIfNotNull(ui_thread_polled_data.get(), "prerenderInfo", chrome_browser_net::GetPrerenderInfo(profile)); - SetIfNotNull(ui_thread_polled_data.get(), "sessionNetworkStats", - chrome_browser_net::GetSessionNetworkStats(profile)); SetIfNotNull(ui_thread_polled_data.get(), "extensionInfo", chrome_browser_net::GetExtensionInfo(profile)); #if defined(OS_WIN) diff --git a/chromium/chrome/browser/ui/webui/ntp/OWNERS b/chromium/chrome/browser/ui/webui/ntp/OWNERS index 32b85cb193d..733c1f71bc6 100644 --- a/chromium/chrome/browser/ui/webui/ntp/OWNERS +++ b/chromium/chrome/browser/ui/webui/ntp/OWNERS @@ -1,3 +1,4 @@ +dbeam@chromium.org estade@chromium.org # TEAM: ntp-dev@chromium.org 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 597a280ee27..7d3fd2a849e 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 @@ -54,10 +54,8 @@ std::string GetStringFromDeletePageResult( return "Store failure"; case offline_pages::DeletePageResult::DEVICE_FAILURE: return "Device failure"; - case offline_pages::DeletePageResult::NOT_FOUND: + case offline_pages::DeletePageResult::DEPRECATED_NOT_FOUND: return "Not found"; - case offline_pages::DeletePageResult::RESULT_COUNT: - break; } NOTREACHED(); return "Unknown"; diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc index 217f35bbd06..fa6ed72c61a 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc @@ -18,10 +18,16 @@ OmniboxUI::OmniboxUI(content::WebUI* web_ui) : ui::MojoWebUIController(web_ui) { // Set up the chrome://omnibox/ source. content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOmniboxHost); + source->AddResourcePath("omnibox_column_widths.css", + IDR_OMNIBOX_COLUMN_WIDTHS_CSS); source->AddResourcePath("omnibox.css", IDR_OMNIBOX_CSS); + source->AddResourcePath("omnibox_element.js", IDR_OMNIBOX_ELEMENT_JS); + source->AddResourcePath("omnibox_inputs.js", IDR_OMNIBOX_INPUTS_JS); + source->AddResourcePath("omnibox_output.js", IDR_OMNIBOX_OUTPUT_JS); source->AddResourcePath("omnibox.js", IDR_OMNIBOX_JS); - source->AddResourcePath("chrome/browser/ui/webui/omnibox/omnibox.mojom.js", - IDR_OMNIBOX_MOJO_JS); + source->AddResourcePath( + "chrome/browser/ui/webui/omnibox/omnibox.mojom-lite.js", + IDR_OMNIBOX_MOJO_JS); source->SetDefaultResource(IDR_OMNIBOX_HTML); source->UseGzip(); diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc index 1e70ce18dc3..f0d90a0df65 100644 --- a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc @@ -70,7 +70,7 @@ #include "chrome/browser/chromeos/policy/device_local_account_policy_service.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/policy/user_policy_manager_factory_chromeos.h" -#include "chrome/browser/chromeos/settings/install_attributes.h" +#include "chromeos/settings/install_attributes.h" #include "components/user_manager/user_manager.h" #else #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.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 c8fbaecf194..e64492fa3cc 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 @@ -190,6 +190,12 @@ void LocalPrinterHandlerChromeos::HandlePrinterSetup( policies.SetInteger( printing::kAllowedDuplexModes, profile_->GetPrefs()->GetInteger(prefs::kPrintingAllowedDuplexModes)); + policies.SetInteger( + printing::kDefaultColorMode, + profile_->GetPrefs()->GetInteger(prefs::kPrintingColorDefault)); + policies.SetInteger( + printing::kDefaultDuplexMode, + profile_->GetPrefs()->GetInteger(prefs::kPrintingDuplexDefault)); // fetch settings on the blocking pool and invoke callback. FetchCapabilities(std::move(printer), std::move(policies), std::move(cb)); return; diff --git a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler_win_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler_win_unittest.cc index f46f4498638..03e57126c61 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler_win_unittest.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler_win_unittest.cc @@ -22,9 +22,18 @@ using content::WebContents; namespace { -class FakePdfPrinterHandler; -bool GetOpenFileNameImpl(OPENFILENAME* ofn); -bool GetSaveFileNameImpl(FakePdfPrinterHandler* handler, OPENFILENAME* ofn); +void ExecuteCancelledSelectFileDialog( + ui::SelectFileDialog::Type type, + const base::string16& title, + const base::FilePath& default_path, + const std::vector<ui::FileFilterSpec>& filter, + int file_type_index, + const base::string16& default_extension, + HWND owner, + ui::OnSelectFileExecutedCallback on_select_file_executed_callback) { + // Send an empty result to simulate a cancelled dialog. + std::move(on_select_file_executed_callback).Run({}, 0); +} class FakePdfPrinterHandler : public PdfPrinterHandler { public: @@ -32,7 +41,6 @@ class FakePdfPrinterHandler : public PdfPrinterHandler { content::WebContents* contents, printing::StickySettings* sticky_settings) : PdfPrinterHandler(profile, contents, sticky_settings), - init_called_(false), save_failed_(false) {} void FileSelected(const base::FilePath& path, @@ -55,10 +63,6 @@ class FakePdfPrinterHandler : public PdfPrinterHandler { bool save_failed() const { return save_failed_; } - bool init_called() const { return init_called_; } - - void set_init_called() { init_called_ = true; } - private: // Simplified version of select file to avoid checking preferences and sticky // settings in the test @@ -70,7 +74,7 @@ class FakePdfPrinterHandler : public PdfPrinterHandler { file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("pdf")); select_file_dialog_ = ui::CreateWinSelectFileDialog( this, nullptr /*policy already checked*/, - base::Bind(GetOpenFileNameImpl), base::Bind(GetSaveFileNameImpl, this)); + base::BindRepeating(&ExecuteCancelledSelectFileDialog)); select_file_dialog_->SelectFile( ui::SelectFileDialog::SELECT_SAVEAS_FILE, base::string16(), default_filename, &file_type_info, 0, base::FilePath::StringType(), @@ -78,38 +82,10 @@ class FakePdfPrinterHandler : public PdfPrinterHandler { nullptr); } - bool init_called_; bool save_failed_; base::RunLoop run_loop_; }; -// Hook function to cancel the dialog when it is successfully initialized. -UINT_PTR CALLBACK PdfPrinterHandlerTestHookFunction(HWND hdlg, - UINT message, - WPARAM wparam, - LPARAM lparam) { - if (message != WM_INITDIALOG) - return 0; - OPENFILENAME* ofn = reinterpret_cast<OPENFILENAME*>(lparam); - FakePdfPrinterHandler* handler = - reinterpret_cast<FakePdfPrinterHandler*>(ofn->lCustData); - handler->set_init_called(); - PostMessage(GetParent(hdlg), WM_COMMAND, MAKEWPARAM(IDCANCEL, 0), 0); - return 1; -} - -bool GetOpenFileNameImpl(OPENFILENAME* ofn) { - return ::GetOpenFileName(ofn); -} - -bool GetSaveFileNameImpl(FakePdfPrinterHandler* handler, OPENFILENAME* ofn) { - // Modify ofn so that the hook function will be called. - ofn->Flags |= OFN_ENABLEHOOK; - ofn->lpfnHook = PdfPrinterHandlerTestHookFunction; - ofn->lCustData = reinterpret_cast<LPARAM>(handler); - return ::GetSaveFileName(ofn); -} - } // namespace class PdfPrinterHandlerWinTest : public BrowserWithTestWindowTest { @@ -138,7 +114,6 @@ class PdfPrinterHandlerWinTest : public BrowserWithTestWindowTest { TEST_F(PdfPrinterHandlerWinTest, TestSaveAsPdf) { pdf_printer_->StartPrintToPdf(L"111111111111111111111.html"); - EXPECT_TRUE(pdf_printer_->init_called()); EXPECT_TRUE(pdf_printer_->save_failed()); } @@ -149,6 +124,5 @@ TEST_F(PdfPrinterHandlerWinTest, TestSaveAsPdfLongFileName) { L"11111111111111111111111111111111111111111111111111111111111111111111111" L"11111111111111111111111111111111111111111111111111111111111111111111111" L"1111111111111111111111111111111111111111111111111.html"); - EXPECT_TRUE(pdf_printer_->init_called()); EXPECT_TRUE(pdf_printer_->save_failed()); } 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 84859e4e29a..11d6da900aa 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 @@ -63,8 +63,8 @@ #include "components/printing/common/cloud_print_cdd_conversion.h" #include "components/printing/common/print_messages.h" #include "components/printing/common/printer_capabilities.h" +#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/gaia_cookie_manager_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_manager.h" #include "content/public/browser/browser_context.h" @@ -628,6 +628,7 @@ void PrintPreviewHandler::RegisterMessages() { } void PrintPreviewHandler::OnJavascriptAllowed() { + print_preview_ui()->SetPreviewUIId(); // Now that the UI is initialized, any future account changes will require // a printer list refresh. RegisterForGaiaCookieChanges(); @@ -637,6 +638,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(); + print_preview_ui()->ClearPreviewUIId(); preview_callbacks_.clear(); preview_failures_.clear(); UnregisterForGaiaCookieChanges(); @@ -773,7 +775,7 @@ void PrintPreviewHandler::HandleGetPreview(const base::ListValue* args) { // Add an additional key in order to identify |print_preview_ui| later on // when calling PrintPreviewUI::ShouldCancelRequest() on the IO thread. settings->SetInteger(printing::kPreviewUIID, - print_preview_ui()->GetIDForPrintPreviewUI()); + print_preview_ui()->GetIDForPrintPreviewUI().value()); // Increment request count. ++regenerate_preview_request_count_; @@ -975,6 +977,7 @@ void PrintPreviewHandler::HandleGetAccessToken(const base::ListValue* args) { token_service_->RequestToken(type, callback_id); } +// TODO(rbpotter): Remove this when the old Print Preview page is deleted. void PrintPreviewHandler::HandleManagePrinters(const base::ListValue* args) { GURL local_printers_manage_url( chrome::GetSettingsUrl(chrome::kPrintingSettingsSubPage)); @@ -995,9 +998,8 @@ void PrintPreviewHandler::HandleShowSystemDialog( return; auto* print_view_manager = PrintViewManager::FromWebContents(initiator); - print_view_manager->PrintForSystemDialogNow( - base::Bind(&PrintPreviewHandler::ClosePreviewDialog, - weak_factory_.GetWeakPtr())); + print_view_manager->PrintForSystemDialogNow(base::BindOnce( + &PrintPreviewHandler::ClosePreviewDialog, weak_factory_.GetWeakPtr())); // Cancel the pending preview request if exists. print_preview_ui()->OnCancelPendingPreviewRequest(); @@ -1050,6 +1052,7 @@ void PrintPreviewHandler::HandleGetInitialSettings( weak_factory_.GetWeakPtr(), callback_id)); } +// TODO(rbpotter): Remove this when the old Print Preview page is deleted. void PrintPreviewHandler::HandleForceOpenNewTab(const base::ListValue* args) { std::string url; if (!args->GetString(0, &url)) 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 88a08b47aaf..9ffc03e2209 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 @@ -229,6 +229,7 @@ class PrintPreviewHandler // Brings up Chrome printing setting page to allow the user to configure local // printers or Google Cloud printers. |args| is unused. + // TODO (rbpotter): Remove this when the old Print Preview page is deleted. void HandleManagePrinters(const base::ListValue* args); // Gathers UMA stats when the print preview dialog is about to close. @@ -246,6 +247,7 @@ class PrintPreviewHandler // Javascript's "window.open" opens a new window popup (since initiated from // async HTTP request) and worse yet, on Windows and Chrome OS, the opened // window opens behind the initiator window. + // TODO(rbpotter): Remove this when the old Print Preview page is deleted. void HandleForceOpenNewTab(const base::ListValue* args); void SendInitialSettings(const std::string& callback_id, 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 24f69d8e8b2..075015dcffd 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 @@ -27,6 +27,7 @@ #include "chrome/browser/printing/background_printing_manager.h" #include "chrome/browser/printing/print_preview_data_service.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/webui/metrics_handler.h" #include "chrome/browser/ui/webui/print_preview/print_preview_handler.h" #include "chrome/browser/ui/webui/theme_source.h" @@ -213,10 +214,6 @@ void AddPrintPreviewStrings(content::WebUIDataSource* source) { source->AddLocalizedString("optionTwoSided", IDS_PRINT_PREVIEW_OPTION_TWO_SIDED); source->AddLocalizedString("pagesLabel", IDS_PRINT_PREVIEW_PAGES_LABEL); - source->AddLocalizedString("pageRangeTextBox", - IDS_PRINT_PREVIEW_PAGE_RANGE_TEXT); - source->AddLocalizedString("pageRangeRadio", - IDS_PRINT_PREVIEW_PAGE_RANGE_RADIO); source->AddLocalizedString("printToPDF", IDS_PRINT_PREVIEW_PRINT_TO_PDF); source->AddLocalizedString("printPreviewSummaryFormatShort", IDS_PRINT_PREVIEW_SUMMARY_FORMAT_SHORT); @@ -244,13 +241,8 @@ void AddPrintPreviewStrings(content::WebUIDataSource* source) { "resolveExtensionUSBErrorMessage", IDS_PRINT_PREVIEW_RESOLVE_EXTENSION_USB_ERROR_MESSAGE); source->AddString( - "printWithCloudPrintWait", - l10n_util::GetStringFUTF16( - IDS_PRINT_PREVIEW_PRINT_WITH_CLOUD_PRINT_WAIT, - l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT))); - source->AddString( - "noDestsPromoLearnMoreUrl", - chrome::kCloudPrintNoDestinationsLearnMoreURL); + "settingsPrintingPage", + chrome::GetSettingsUrl(chrome::kPrintingSettingsSubPage).spec()); source->AddString("gcpCertificateErrorLearnMoreURL", chrome::kCloudPrintCertificateErrorLearnMoreURL); source->AddLocalizedString("pageRangeLimitInstruction", @@ -457,8 +449,6 @@ void SetupPrintPreviewPlugin(content::WebUIDataSource* source) { IDR_PDF_GESTURE_DETECTOR_JS); source->AddResourcePath("pdf/browser_api.js", IDR_PDF_BROWSER_API_JS); source->AddResourcePath("pdf/metrics.js", IDR_PDF_METRICS_JS); - source->AddResourcePath("pdf/coords_transformer.js", - IDR_PDF_COORDS_TRANSFORMER_JS); source->AddResourcePath("pdf/elements/shared-vars.html", IDR_PDF_SHARED_VARS_HTML); @@ -580,17 +570,13 @@ PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui, std::unique_ptr<PrintPreviewHandler> handler) : ConstrainedWebDialogUI(web_ui), initial_preview_start_time_(base::TimeTicks::Now()), - id_(g_print_preview_ui_id_map.Get().Add(this)), handler_(handler.get()) { web_ui->AddMessageHandler(std::move(handler)); - - g_print_preview_request_id_map.Get().Set(id_, -1); } PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui) : ConstrainedWebDialogUI(web_ui), initial_preview_start_time_(base::TimeTicks::Now()), - id_(g_print_preview_ui_id_map.Get().Add(this)), handler_(CreatePrintPreviewHandlers(web_ui)) { // Set up the chrome://print/ data source. Profile* profile = Profile::FromWebUI(web_ui); @@ -607,31 +593,37 @@ PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui) // Set up the chrome://theme/ source. content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile)); - - g_print_preview_request_id_map.Get().Set(id_, -1); } PrintPreviewUI::~PrintPreviewUI() { - PrintPreviewDataService::GetInstance()->RemoveEntry(id_); - g_print_preview_request_id_map.Get().Erase(id_); - g_print_preview_ui_id_map.Get().Remove(id_); + ClearPreviewUIId(); +} + +void PrintPreviewUI::ClearPreviewUIId() { + if (!id_) + return; + + PrintPreviewDataService::GetInstance()->RemoveEntry(*id_); + g_print_preview_request_id_map.Get().Erase(*id_); + g_print_preview_ui_id_map.Get().Remove(*id_); + id_.reset(); } void PrintPreviewUI::GetPrintPreviewDataForIndex( int index, scoped_refptr<base::RefCountedMemory>* data) const { - PrintPreviewDataService::GetInstance()->GetDataEntry(id_, index, data); + PrintPreviewDataService::GetInstance()->GetDataEntry(*id_, index, data); } void PrintPreviewUI::SetPrintPreviewDataForIndex( int index, scoped_refptr<base::RefCountedMemory> data) { - PrintPreviewDataService::GetInstance()->SetDataEntry(id_, index, + PrintPreviewDataService::GetInstance()->SetDataEntry(*id_, index, std::move(data)); } void PrintPreviewUI::ClearAllPreviewData() { - PrintPreviewDataService::GetInstance()->RemoveEntry(id_); + PrintPreviewDataService::GetInstance()->RemoveEntry(*id_); } void PrintPreviewUI::SetInitiatorTitle( @@ -685,7 +677,7 @@ bool PrintPreviewUI::ShouldCancelRequest(const PrintHostMsg_PreviewIds& ids) { return ids.request_id != current_id; } -int32_t PrintPreviewUI::GetIDForPrintPreviewUI() const { +base::Optional<int32_t> PrintPreviewUI::GetIDForPrintPreviewUI() const { return id_; } @@ -724,7 +716,7 @@ void PrintPreviewUI::OnPrintPreviewRequest(int request_id) { UMA_HISTOGRAM_TIMES("PrintPreview.InitializationTime", base::TimeTicks::Now() - initial_preview_start_time_); } - g_print_preview_request_id_map.Get().Set(id_, request_id); + g_print_preview_request_id_map.Get().Set(*id_, request_id); } void PrintPreviewUI::OnDidStartPreview( @@ -795,7 +787,7 @@ void PrintPreviewUI::OnDidPreviewPage( if (g_testing_delegate) g_testing_delegate->DidRenderPreviewPage(web_ui()->GetWebContents()); - handler_->SendPagePreviewReady(page_number, id_, preview_request_id); + handler_->SendPagePreviewReady(page_number, *id_, preview_request_id); } void PrintPreviewUI::OnPreviewDataIsAvailable( @@ -819,11 +811,11 @@ void PrintPreviewUI::OnPreviewDataIsAvailable( SetPrintPreviewDataForIndex(printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, std::move(data)); - handler_->OnPrintPreviewReady(id_, preview_request_id); + handler_->OnPrintPreviewReady(*id_, preview_request_id); } void PrintPreviewUI::OnCancelPendingPreviewRequest() { - g_print_preview_request_id_map.Get().Set(id_, -1); + g_print_preview_request_id_map.Get().Set(*id_, -1); } void PrintPreviewUI::OnPrintPreviewFailed(int request_id) { @@ -902,3 +894,9 @@ void PrintPreviewUI::SetPrintPreviewDataForIndexForTest( void PrintPreviewUI::ClearAllPreviewDataForTest() { ClearAllPreviewData(); } + +void PrintPreviewUI::SetPreviewUIId() { + DCHECK(!id_); + id_ = g_print_preview_ui_id_map.Get().Add(this); + g_print_preview_request_id_map.Get().Set(*id_, -1); +} 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 5135daaa6e4..7a5c43e6374 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 @@ -15,6 +15,7 @@ #include "base/macros.h" #include "base/memory/read_only_shared_memory_region.h" #include "base/memory/ref_counted.h" +#include "base/optional.h" #include "base/time/time.h" #include "chrome/browser/ui/webui/constrained_web_dialog_ui.h" #include "ui/gfx/geometry/rect.h" @@ -94,7 +95,7 @@ class PrintPreviewUI : public ConstrainedWebDialogUI { static bool ShouldCancelRequest(const PrintHostMsg_PreviewIds& ids); // Returns an id to uniquely identify this PrintPreviewUI. - int32_t GetIDForPrintPreviewUI() const; + base::Optional<int32_t> GetIDForPrintPreviewUI() const; // Notifies the Web UI of a print preview request with |request_id|. virtual void OnPrintPreviewRequest(int request_id); @@ -194,6 +195,14 @@ class PrintPreviewUI : public ConstrainedWebDialogUI { // See ClearAllPreviewData(). void ClearAllPreviewDataForTest(); + // Sets a new valid Print Preview UI ID for this instance. Called by + // PrintPreviewHandler in OnJavascriptAllowed(). + void SetPreviewUIId(); + + // Clears the UI ID. Called by PrintPreviewHandler in + // OnJavascriptDisallowed(). + void ClearPreviewUIId(); + protected: // Alternate constructor for tests PrintPreviewUI(content::WebUI* web_ui, @@ -217,7 +226,7 @@ class PrintPreviewUI : public ConstrainedWebDialogUI { // The unique ID for this class instance. Stored here to avoid calling // GetIDForPrintPreviewUI() everywhere. - const int32_t id_; + base::Optional<int32_t> id_; // Weak pointer to the WebUI handler. PrintPreviewHandler* const handler_; 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 eca93878206..c385a3585ab 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 @@ -87,6 +87,7 @@ TEST_F(PrintPreviewUIUnitTest, PrintPreviewData) { PrintPreviewUI* preview_ui = static_cast<PrintPreviewUI*>( preview_dialog->GetWebUI()->GetController()); ASSERT_TRUE(preview_ui); + preview_ui->SetPreviewUIId(); scoped_refptr<base::RefCountedMemory> data; preview_ui->GetPrintPreviewDataForIndex( @@ -134,6 +135,7 @@ TEST_F(PrintPreviewUIUnitTest, PrintPreviewDraftPages) { PrintPreviewUI* preview_ui = static_cast<PrintPreviewUI*>( preview_dialog->GetWebUI()->GetController()); ASSERT_TRUE(preview_ui); + preview_ui->SetPreviewUIId(); scoped_refptr<base::RefCountedMemory> data; preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, &data); @@ -194,6 +196,7 @@ TEST_F(PrintPreviewUIUnitTest, ShouldCancelRequest) { PrintPreviewUI* preview_ui = static_cast<PrintPreviewUI*>( preview_dialog->GetWebUI()->GetController()); ASSERT_TRUE(preview_ui); + preview_ui->SetPreviewUIId(); // Test with invalid UI ID. const int32_t kInvalidId = -5; @@ -201,7 +204,7 @@ TEST_F(PrintPreviewUIUnitTest, ShouldCancelRequest) { const int kFirstRequestId = 1000; const int kSecondRequestId = 1001; - const int32_t preview_id = preview_ui->GetIDForPrintPreviewUI(); + const int32_t preview_id = preview_ui->GetIDForPrintPreviewUI().value(); // Test with kFirstRequestId. preview_ui->OnPrintPreviewRequest(kFirstRequestId); diff --git a/chromium/chrome/browser/ui/webui/profile_info_watcher.cc b/chromium/chrome/browser/ui/webui/profile_info_watcher.cc index 422472e4ebb..a4f62d805c8 100644 --- a/chromium/chrome/browser/ui/webui/profile_info_watcher.cc +++ b/chromium/chrome/browser/ui/webui/profile_info_watcher.cc @@ -9,11 +9,11 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_pref_names.h" +#include "services/identity/public/cpp/identity_manager.h" ProfileInfoWatcher::ProfileInfoWatcher( Profile* profile, const base::Closure& callback) @@ -44,17 +44,17 @@ void ProfileInfoWatcher::OnProfileAuthInfoChanged( std::string ProfileInfoWatcher::GetAuthenticatedUsername() const { std::string username; - SigninManagerBase* signin_manager = GetSigninManager(); - if (signin_manager) - username = signin_manager->GetAuthenticatedAccountInfo().email; + auto* identity_manager = GetIdentityManager(); + if (identity_manager) + username = identity_manager->GetPrimaryAccountInfo().email; return username; } -SigninManagerBase* ProfileInfoWatcher::GetSigninManager() const { - return SigninManagerFactory::GetForProfile(profile_); +identity::IdentityManager* ProfileInfoWatcher::GetIdentityManager() const { + return IdentityManagerFactory::GetForProfile(profile_); } void ProfileInfoWatcher::RunCallback() { - if (GetSigninManager()) + if (GetIdentityManager()) callback_.Run(); } diff --git a/chromium/chrome/browser/ui/webui/profile_info_watcher.h b/chromium/chrome/browser/ui/webui/profile_info_watcher.h index 114282d6a32..98493150379 100644 --- a/chromium/chrome/browser/ui/webui/profile_info_watcher.h +++ b/chromium/chrome/browser/ui/webui/profile_info_watcher.h @@ -13,7 +13,10 @@ #include "components/prefs/pref_member.h" class Profile; -class SigninManagerBase; + +namespace identity { +class IdentityManager; +} // Watches profiles for changes in their cached info (e.g. the authenticated // username changes). @@ -29,10 +32,10 @@ class ProfileInfoWatcher : public ProfileAttributesStorage::Observer { // ProfileAttributesStorage::Observer: void OnProfileAuthInfoChanged(const base::FilePath& profile_path) override; - // Gets the SigninManagerBase for |profile_|. - SigninManagerBase* GetSigninManager() const; + // Gets the IdentityManager for |profile_|. + identity::IdentityManager* GetIdentityManager() const; - // Runs |callback_| when a profile changes. No-ops if |GetSigninManager()| + // Runs |callback_| when a profile changes. No-ops if |GetIdentityManager()| // returns nullptr. void RunCallback(); diff --git a/chromium/chrome/browser/ui/webui/reset_password/OWNERS b/chromium/chrome/browser/ui/webui/reset_password/OWNERS index 22146bac43e..310210ec249 100644 --- a/chromium/chrome/browser/ui/webui/reset_password/OWNERS +++ b/chromium/chrome/browser/ui/webui/reset_password/OWNERS @@ -1,8 +1,7 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS -jialiul@chromium.org nparker@chromium.org vakh@chromium.org -# COMPONENT: Services>Safebrowsing +# COMPONENT: UI>Browser>Safebrowsing diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.cc b/chromium/chrome/browser/ui/webui/settings/about_handler.cc index 2486208d075..c372368a1e0 100644 --- a/chromium/chrome/browser/ui/webui/settings/about_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/about_handler.cc @@ -53,7 +53,7 @@ #if defined(OS_CHROMEOS) #include "base/i18n/time_formatting.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc index 63783ab71f7..439b6fea161 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc @@ -76,8 +76,16 @@ void CrostiniHandler::HandleRemoveCrostiniSharedPath( std::string path; CHECK(args->GetString(0, &path)); - crostini::UnsharePath(profile_, crostini::kCrostiniDefaultVmName, - base::FilePath(path), base::DoNothing()); + crostini::CrostiniSharePath::GetForProfile(profile_)->UnsharePath( + crostini::kCrostiniDefaultVmName, base::FilePath(path), + base::BindOnce( + [](const std::string& path, bool result, std::string failure_reason) { + if (!result) { + LOG(ERROR) << "Error unsharing " << path << ": " + << failure_reason; + } + }, + path)); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h index a43ff984077..37b71f5d4f2 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h @@ -11,7 +11,7 @@ class Profile; namespace crostini { -enum class ConciergeClientResult; +enum class CrostiniResult; } namespace chromeos { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc index 7556aa92135..15f648a7215 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc @@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/values.h" +#include "chrome/browser/ui/ash/ksv/keyboard_shortcut_viewer_util.h" #include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chromeos/chromeos_switches.h" #include "content/public/browser/web_ui.h" @@ -68,8 +69,8 @@ void KeyboardHandler::RegisterMessages() { base::BindRepeating(&KeyboardHandler::HandleInitialize, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "showKeyboardShortcutsOverlay", - base::BindRepeating(&KeyboardHandler::HandleShowKeyboardShortcutsOverlay, + "showKeyboardShortcutViewer", + base::BindRepeating(&KeyboardHandler::HandleShowKeyboardShortcutViewer, base::Unretained(this))); web_ui()->RegisterMessageCallback( "initializeKeyboardWatcher", @@ -97,13 +98,9 @@ void KeyboardHandler::HandleInitialize(const base::ListValue* args) { UpdateKeyboards(); } -void KeyboardHandler::HandleShowKeyboardShortcutsOverlay( +void KeyboardHandler::HandleShowKeyboardShortcutViewer( const base::ListValue* args) const { - ash::mojom::NewWindowControllerPtr new_window_controller; - content::ServiceManagerConnection::GetForProcess() - ->GetConnector() - ->BindInterface(ash::mojom::kServiceName, &new_window_controller); - new_window_controller->ShowKeyboardOverlay(); + keyboard_shortcut_viewer_util::ToggleKeyboardShortcutViewer(); } void KeyboardHandler::HandleKeyboardChange(const base::ListValue* args) { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h index be8f0ae6e0b..6b071f0e217 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h @@ -58,8 +58,8 @@ class KeyboardHandler // Initializes the page with the current keyboard information. void HandleInitialize(const base::ListValue* args); - // Shows the Ash keyboard shortcuts overlay. - void HandleShowKeyboardShortcutsOverlay(const base::ListValue* args) const; + // Shows the Ash keyboard shortcut viewer. + void HandleShowKeyboardShortcutViewer(const base::ListValue* args) const; // Determines what types of keyboards are attached. void HandleKeyboardChange(const base::ListValue* args); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc index 6c907c084c2..04ddbb99df5 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc @@ -14,7 +14,9 @@ #include "content/public/test/test_web_ui.h" #include "services/ws/public/cpp/input_devices/input_device_client_test_api.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/aura/test/aura_test_utils.h" #include "ui/events/devices/input_device.h" +#include "ui/events/devices/input_device_manager.h" namespace chromeos { namespace settings { @@ -32,6 +34,8 @@ class TestKeyboardHandler : public KeyboardHandler { class KeyboardHandlerTest : public testing::Test { public: KeyboardHandlerTest() : handler_test_api_(&handler_) { + input_device_manager_ = aura::test::CreateTestInputDeviceManager(); + handler_.set_web_ui(&web_ui_); handler_.RegisterMessages(); handler_.AllowJavascriptForTesting(); @@ -157,6 +161,7 @@ class KeyboardHandlerTest : public testing::Test { return has_internal_search_key; } + std::unique_ptr<ui::InputDeviceManager> input_device_manager_; ws::InputDeviceClientTestApi input_device_client_test_api_; content::TestWebUI web_ui_; TestKeyboardHandler handler_; 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 e2b4af37067..a846c92fd02 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 @@ -10,7 +10,7 @@ #include <string> #include "base/files/file_util.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "base/task/post_task.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browsing_data/browsing_data_appcache_helper.h" @@ -341,7 +341,7 @@ void StorageHandler::UpdateCrostiniSize() { weak_ptr_factory_.GetWeakPtr())); } -void StorageHandler::OnGetCrostiniSize(crostini::ConciergeClientResult result, +void StorageHandler::OnGetCrostiniSize(crostini::CrostiniResult result, int64_t size) { updating_crostini_size_ = false; FireWebUIListener("storage-crostini-size-changed", 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 8d5f7b04ceb..7021667406a 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 @@ -22,7 +22,7 @@ class Profile; namespace crostini { -enum class ConciergeClientResult; +enum class CrostiniResult; } // namespace crostini namespace chromeos { @@ -94,7 +94,7 @@ class StorageHandler : public ::settings::SettingsPageUIHandler { void UpdateCrostiniSize(); // Callback to update the UI about Crostini VMs and their apps and cache. - void OnGetCrostiniSize(crostini::ConciergeClientResult result, int64_t size); + void OnGetCrostiniSize(crostini::CrostiniResult result, int64_t size); // Requests updating the total size of other users' data. void UpdateOtherUsersSize(); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.cc deleted file mode 100644 index 371edb36ef3..00000000000 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.cc +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.h" - -#include <string> - -#include "base/bind.h" -#include "base/command_line.h" -#include "base/macros.h" -#include "base/values.h" -#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/pref_names.h" -#include "chromeos/components/proximity_auth/switches.h" -#include "content/public/browser/web_ui.h" -#include "content/public/browser/web_ui_data_source.h" - -namespace chromeos { -namespace settings { - -EasyUnlockSettingsHandler::EasyUnlockSettingsHandler(Profile* profile) - : profile_(profile) { - profile_pref_registrar_.Init(profile->GetPrefs()); -} - -EasyUnlockSettingsHandler::~EasyUnlockSettingsHandler() { - EasyUnlockService::Get(profile_)->RemoveObserver(this); -} - -EasyUnlockSettingsHandler* EasyUnlockSettingsHandler::Create( - content::WebUIDataSource* html_source, - Profile* profile) { - EasyUnlockService* easy_unlock_service = EasyUnlockService::Get(profile); - // The service is not created for LockScreenApp profiles or "off the record". - if (!easy_unlock_service) - return nullptr; - - bool allowed = easy_unlock_service->IsAllowed(); - html_source->AddBoolean("easyUnlockAllowed", allowed); - html_source->AddBoolean("easyUnlockEnabled", - allowed ? easy_unlock_service->IsEnabled() : false); - // TODO(crbug.com/894585): Remove this legacy special case after M71. - html_source->AddBoolean("easyUnlockInLegacyHostMode", - allowed && easy_unlock_service->IsInLegacyHostMode()); - - if (!allowed) - return nullptr; - - return new EasyUnlockSettingsHandler(profile); -} - -void EasyUnlockSettingsHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "easyUnlockGetEnabledStatus", - base::BindRepeating(&EasyUnlockSettingsHandler::HandleGetEnabledStatus, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "easyUnlockStartTurnOnFlow", - base::BindRepeating(&EasyUnlockSettingsHandler::HandleStartTurnOnFlow, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "easyUnlockGetTurnOffFlowStatus", - base::BindRepeating( - &EasyUnlockSettingsHandler::HandleGetTurnOffFlowStatus, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "easyUnlockStartTurnOffFlow", - base::BindRepeating(&EasyUnlockSettingsHandler::HandleStartTurnOffFlow, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "easyUnlockCancelTurnOffFlow", - base::BindRepeating(&EasyUnlockSettingsHandler::HandleCancelTurnOffFlow, - base::Unretained(this))); -} - -void EasyUnlockSettingsHandler::OnJavascriptAllowed() { - EasyUnlockService::Get(profile_)->AddObserver(this); - - profile_pref_registrar_.Add( - prefs::kEasyUnlockPairing, - base::Bind(&EasyUnlockSettingsHandler::SendEnabledStatus, - base::Unretained(this))); -} - -void EasyUnlockSettingsHandler::OnJavascriptDisallowed() { - EasyUnlockService::Get(profile_)->RemoveObserver(this); - profile_pref_registrar_.RemoveAll(); -} - -void EasyUnlockSettingsHandler::OnTurnOffOperationStatusChanged() { - FireWebUIListener("easy-unlock-turn-off-flow-status", - base::Value(GetTurnOffFlowStatus())); -} - -void EasyUnlockSettingsHandler::SendEnabledStatus() { - CallJavascriptFunction( - "cr.webUIListenerCallback", base::Value("easy-unlock-enabled-status"), - base::Value(EasyUnlockService::Get(profile_)->IsEnabled())); -} - -std::string EasyUnlockSettingsHandler::GetTurnOffFlowStatus() { - EasyUnlockService::TurnOffFlowStatus status = - EasyUnlockService::Get(profile_)->GetTurnOffFlowStatus(); - - // Translate status into JS UI state string. Note the translated string - // should match UIState defined in easy_unlock_turn_off_dialog.js. - std::string status_string; - switch (status) { - case EasyUnlockService::IDLE: - status_string = "idle"; - break; - case EasyUnlockService::PENDING: - status_string = "pending"; - break; - case EasyUnlockService::FAIL: - status_string = "server-error"; - break; - default: - LOG(ERROR) << "Unknown Easy unlock turn-off operation status: " << status; - status_string = "idle"; - break; - } - - return status_string; -} - -void EasyUnlockSettingsHandler::HandleGetEnabledStatus( - const base::ListValue* args) { - AllowJavascript(); - - CHECK_EQ(1U, args->GetSize()); - const base::Value* callback_id; - CHECK(args->Get(0, &callback_id)); - ResolveJavascriptCallback( - *callback_id, base::Value(EasyUnlockService::Get(profile_)->IsEnabled())); -} - -void EasyUnlockSettingsHandler::HandleStartTurnOnFlow( - const base::ListValue* args) { - EasyUnlockService::Get(profile_)->LaunchSetup(); -} - -void EasyUnlockSettingsHandler::HandleGetTurnOffFlowStatus( - const base::ListValue* args) { - CHECK_EQ(1U, args->GetSize()); - const base::Value* callback_id; - CHECK(args->Get(0, &callback_id)); - ResolveJavascriptCallback(*callback_id, base::Value(GetTurnOffFlowStatus())); -} - -void EasyUnlockSettingsHandler::HandleStartTurnOffFlow( - const base::ListValue* args) { - EasyUnlockService::Get(profile_)->RunTurnOffFlow(); -} - -void EasyUnlockSettingsHandler::HandleCancelTurnOffFlow( - const base::ListValue* args) { - EasyUnlockService::Get(profile_)->ResetTurnOffFlow(); -} - -} // namespace settings -} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.h deleted file mode 100644 index e4509d75036..00000000000 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.h +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_EASY_UNLOCK_SETTINGS_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_EASY_UNLOCK_SETTINGS_HANDLER_H_ - -#include "base/macros.h" -#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_observer.h" -#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" -#include "components/prefs/pref_change_registrar.h" - -namespace content { -class WebUIDataSource; -} - -class Profile; - -namespace chromeos { -namespace settings { - -class EasyUnlockSettingsHandler : public ::settings::SettingsPageUIHandler, - public EasyUnlockServiceObserver { - public: - // Returns nullptr if EasyUnlock is not allowed for this device. - static EasyUnlockSettingsHandler* Create( - content::WebUIDataSource* html_source, - Profile* profile); - - ~EasyUnlockSettingsHandler() override; - - // SettingsPageUIHandler: - void RegisterMessages() override; - void OnJavascriptAllowed() override; - void OnJavascriptDisallowed() override; - - // EasyUnlockServiceObserver: - void OnTurnOffOperationStatusChanged() override; - - protected: - explicit EasyUnlockSettingsHandler(Profile* profile); - - private: - FRIEND_TEST_ALL_PREFIXES(EasyUnlockSettingsHandlerTest, EnabledStatus); - FRIEND_TEST_ALL_PREFIXES(EasyUnlockSettingsHandlerTest, TurnOffFlowStatus); - - void SendEnabledStatus(); - std::string GetTurnOffFlowStatus(); - - // JS callbacks. - void HandleGetEnabledStatus(const base::ListValue* args); - void HandleStartTurnOnFlow(const base::ListValue* args); - void HandleGetTurnOffFlowStatus(const base::ListValue* args); - void HandleStartTurnOffFlow(const base::ListValue* args); - void HandleCancelTurnOffFlow(const base::ListValue* args); - - Profile* const profile_; - - PrefChangeRegistrar profile_pref_registrar_; - - DISALLOW_COPY_AND_ASSIGN(EasyUnlockSettingsHandler); -}; - -} // namespace settings -} // namespace chromeos - -#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_EASY_UNLOCK_SETTINGS_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc deleted file mode 100644 index f69e29ce1a1..00000000000 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler_unittest.cc +++ /dev/null @@ -1,281 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.h" - -#include <memory> - -#include "base/bind.h" -#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service.h" -#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_factory.h" -#include "chrome/test/base/testing_profile.h" -#include "content/public/browser/web_ui_data_source.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "content/public/test/test_web_ui.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromeos { -namespace settings { - -namespace { - -class FakeEasyUnlockService : public EasyUnlockService { - public: - explicit FakeEasyUnlockService(Profile* profile) - : EasyUnlockService(profile, nullptr /* secure_channel_client */), - turn_off_status_(IDLE), - is_allowed_(true), - is_enabled_(false) {} - - TurnOffFlowStatus GetTurnOffFlowStatus() const override { - return turn_off_status_; - } - - bool IsAllowed() const override { return is_allowed_; } - void set_is_allowed(bool is_allowed) { is_allowed_ = is_allowed; } - - bool IsEnabled() const override { return is_enabled_; } - void set_is_enabled(bool is_enabled) { is_enabled_ = is_enabled; } - - void RunTurnOffFlow() override { - turn_off_status_ = PENDING; - NotifyTurnOffOperationStatusChanged(); - } - - void ResetTurnOffFlow() override { - turn_off_status_ = IDLE; - NotifyTurnOffOperationStatusChanged(); - } - - void SetTurnOffFlowFailForTest() { - turn_off_status_ = FAIL; - NotifyTurnOffOperationStatusChanged(); - } - - private: - Type GetType() const override { return TYPE_REGULAR; } - AccountId GetAccountId() const override { return EmptyAccountId(); } - void LaunchSetup() override {} - void ClearPermitAccess() override {} - - const base::ListValue* GetRemoteDevices() const override { return nullptr; } - void SetRemoteDevices(const base::ListValue& devices) override {} - - std::string GetChallenge() const override { return std::string(); } - std::string GetWrappedSecret() const override { return std::string(); } - void RecordEasySignInOutcome(const AccountId& account_id, - bool success) const override {} - void RecordPasswordLoginEvent(const AccountId& account_id) const override {} - - void InitializeInternal() override {} - void ShutdownInternal() override {} - bool IsAllowedInternal() const override { return false; } - void OnWillFinalizeUnlock(bool success) override {} - void OnSuspendDoneInternal() override {} - - TurnOffFlowStatus turn_off_status_; - bool is_allowed_; - bool is_enabled_; -}; - -class TestEasyUnlockSettingsHandler : public EasyUnlockSettingsHandler { - public: - explicit TestEasyUnlockSettingsHandler(Profile* profile) - : EasyUnlockSettingsHandler(profile) {} - - using EasyUnlockSettingsHandler::set_web_ui; -}; - -std::unique_ptr<KeyedService> CreateEasyUnlockServiceForTest( - content::BrowserContext* context) { - return std::make_unique<FakeEasyUnlockService>( - Profile::FromBrowserContext(context)); -} - -std::unique_ptr<KeyedService> CreateNullEasyUnlockServiceForTest( - content::BrowserContext* context) { - return nullptr; -} - -} // namespace - -class EasyUnlockSettingsHandlerTest : public testing::Test { - public: - EasyUnlockSettingsHandlerTest() {} - - void SetUp() override { - TestingProfile::Builder builder; - builder.AddTestingFactory( - EasyUnlockServiceFactory::GetInstance(), - base::BindRepeating(&CreateEasyUnlockServiceForTest)); - profile_ = builder.Build(); - } - - Profile* profile() { return profile_.get(); } - content::TestWebUI* web_ui() { return &web_ui_; } - FakeEasyUnlockService* fake_easy_unlock_service() { - return static_cast<FakeEasyUnlockService*>( - EasyUnlockService::Get(profile_.get())); - } - - void MakeEasyUnlockServiceNull() { - TestingProfile::Builder builder; - builder.AddTestingFactory( - EasyUnlockServiceFactory::GetInstance(), - base::BindRepeating(&CreateNullEasyUnlockServiceForTest)); - profile_ = builder.Build(); - } - - void VerifyEnabledStatusCallback(size_t expected_total_calls, - bool expected_status) { - std::string event; - bool status; - - EXPECT_EQ(expected_total_calls, web_ui_.call_data().size()); - - const content::TestWebUI::CallData& data = *web_ui_.call_data().back(); - EXPECT_EQ("cr.webUIListenerCallback", data.function_name()); - ASSERT_TRUE(data.arg1()->GetAsString(&event)); - EXPECT_EQ("easy-unlock-enabled-status", event); - ASSERT_TRUE(data.arg2()->GetAsBoolean(&status)); - - EXPECT_EQ(expected_status, status); - } - - void VerifyTurnOffFlowStatusWebUIListenerCallback( - size_t expected_total_calls, - const std::string& expected_status) { - std::string event; - std::string status; - - EXPECT_EQ(expected_total_calls, web_ui_.call_data().size()); - - const content::TestWebUI::CallData& data = *web_ui_.call_data().back(); - EXPECT_EQ("cr.webUIListenerCallback", data.function_name()); - ASSERT_TRUE(data.arg1()->GetAsString(&event)); - EXPECT_EQ("easy-unlock-turn-off-flow-status", event); - ASSERT_TRUE(data.arg2()->GetAsString(&status)); - - EXPECT_EQ(expected_status, status); - } - - void VerifyTurnOffFlowStatusWebUIResponse( - size_t expected_total_calls, - const std::string& expected_callback_id, - const std::string& expected_status) { - EXPECT_EQ(expected_total_calls, web_ui()->call_data().size()); - - const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); - EXPECT_EQ("cr.webUIResponse", data.function_name()); - - std::string callback_id; - ASSERT_TRUE(data.arg1()->GetAsString(&callback_id)); - EXPECT_EQ(expected_callback_id, callback_id); - - std::string actual_status; - ASSERT_TRUE(data.arg3()->GetAsString(&actual_status)); - EXPECT_EQ(expected_status, actual_status); - } - - private: - content::TestBrowserThreadBundle thread_bundle_; - std::unique_ptr<TestingProfile> profile_; - content::TestWebUI web_ui_; -}; - -TEST_F(EasyUnlockSettingsHandlerTest, OnlyCreatedWhenEasyUnlockAllowed) { - std::unique_ptr<EasyUnlockSettingsHandler> handler; - content::WebUIDataSource* data_source = - content::WebUIDataSource::Create("test-data-source"); - content::WebUIDataSource::Add(profile(), data_source); - handler.reset( - EasyUnlockSettingsHandler::Create(data_source, profile())); - EXPECT_TRUE(handler.get()); - - fake_easy_unlock_service()->set_is_allowed(false); - handler.reset(EasyUnlockSettingsHandler::Create(data_source, profile())); - EXPECT_FALSE(handler.get()); -} - -TEST_F(EasyUnlockSettingsHandlerTest, NotCreatedWhenEasyUnlockServiceNull) { - MakeEasyUnlockServiceNull(); - std::unique_ptr<EasyUnlockSettingsHandler> handler; - content::WebUIDataSource* data_source = - content::WebUIDataSource::Create("test-data-source"); - content::WebUIDataSource::Add(profile(), data_source); - handler.reset(EasyUnlockSettingsHandler::Create(data_source, profile())); - EXPECT_FALSE(handler.get()); -} - -TEST_F(EasyUnlockSettingsHandlerTest, EnabledStatus) { - std::unique_ptr<EasyUnlockSettingsHandler> handler; - handler.reset(new TestEasyUnlockSettingsHandler(profile())); - handler->set_web_ui(web_ui()); - - // Test the JS -> C++ -> JS callback path. - base::ListValue list_args; - list_args.AppendString("test-callback-id"); - handler->HandleGetEnabledStatus(&list_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()); - - std::string callback_id; - ASSERT_TRUE(data.arg1()->GetAsString(&callback_id)); - EXPECT_EQ("test-callback-id", callback_id); - - bool enabled_status = false; - ASSERT_TRUE(data.arg3()->GetAsBoolean(&enabled_status)); - EXPECT_FALSE(enabled_status); - - // Test the C++ -> JS push path. - handler->SendEnabledStatus(); - VerifyEnabledStatusCallback(2U, false); - - fake_easy_unlock_service()->set_is_enabled(true); - handler->SendEnabledStatus(); - VerifyEnabledStatusCallback(3U, true); -} - -TEST_F(EasyUnlockSettingsHandlerTest, TurnOffFlowStatus) { - std::unique_ptr<EasyUnlockSettingsHandler> handler; - handler.reset(new TestEasyUnlockSettingsHandler(profile())); - handler->set_web_ui(web_ui()); - - // Send an initial status query to turn on service observer. - base::ListValue list_args1; - list_args1.AppendString("test-callback-id-1"); - handler->HandleGetEnabledStatus(&list_args1); - EXPECT_EQ(1U, web_ui()->call_data().size()); - - base::ListValue list_args2; - list_args2.AppendString("test-callback-id-2"); - handler->HandleGetTurnOffFlowStatus(&list_args2); - VerifyTurnOffFlowStatusWebUIResponse(2U, "test-callback-id-2", "idle"); - - handler->HandleStartTurnOffFlow(nullptr); - VerifyTurnOffFlowStatusWebUIListenerCallback(3U, "pending"); - - base::ListValue list_args3; - list_args3.AppendString("test-callback-id-3"); - handler->HandleGetTurnOffFlowStatus(&list_args3); - VerifyTurnOffFlowStatusWebUIResponse(4U, "test-callback-id-3", "pending"); - - handler->HandleCancelTurnOffFlow(nullptr); - VerifyTurnOffFlowStatusWebUIListenerCallback(5U, "idle"); - - fake_easy_unlock_service()->SetTurnOffFlowFailForTest(); - VerifyTurnOffFlowStatusWebUIListenerCallback(6U, "server-error"); - - base::ListValue list_args4; - list_args4.AppendString("test-callback-id-4"); - handler->HandleGetTurnOffFlowStatus(&list_args4); - VerifyTurnOffFlowStatusWebUIResponse(7U, "test-callback-id-4", - "server-error"); -} - -} // namespace settings -} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler_unittest.cc index 679b5cfdd3d..75a86bfae5d 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler_unittest.cc @@ -53,8 +53,6 @@ class InternetHandlerTest : public BrowserWithTestWindowTest { fake_tracker_.get()); } - void TearDown() override { BrowserWithTestWindowTest::TearDown(); } - void RequestGmsCoreNotificationsDisabledDeviceNames() { handler_->RequestGmsCoreNotificationsDisabledDeviceNames(nullptr); } diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc index c9f32d271f2..aaf9de111c8 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc @@ -137,8 +137,8 @@ void MultideviceHandler::UpdatePageContent() { std::unique_ptr<base::DictionaryValue> page_content_dictionary = GeneratePageContentDataDictionary(); DCHECK(page_content_dictionary); - PA_LOG(INFO) << "Updating MultiDevice settings page content with: " - << *page_content_dictionary << "."; + PA_LOG(VERBOSE) << "Updating MultiDevice settings page content with: " + << *page_content_dictionary << "."; FireWebUIListener("settings.updateMultidevicePageContentData", *page_content_dictionary); } @@ -166,8 +166,8 @@ void MultideviceHandler::HandleGetPageContent(const base::ListValue* args) { std::unique_ptr<base::DictionaryValue> page_content_dictionary = GeneratePageContentDataDictionary(); DCHECK(page_content_dictionary); - PA_LOG(INFO) << "Responding to getPageContentData() request with: " - << *page_content_dictionary << "."; + PA_LOG(VERBOSE) << "Responding to getPageContentData() request with: " + << *page_content_dictionary << "."; ResolveJavascriptCallback(base::Value(callback_id), *page_content_dictionary); } @@ -213,9 +213,8 @@ void MultideviceHandler::HandleRetryPendingHostSetup( } void MultideviceHandler::HandleSetUpAndroidSms(const base::ListValue* args) { - PA_LOG(INFO) << "SetUpSMS triggered."; DCHECK(args->empty()); - android_sms_app_helper_->InstallAndLaunchAndroidSmsApp(); + android_sms_app_helper_->SetUpAndLaunchAndroidSmsApp(); } void MultideviceHandler::HandleGetSmartLockSignInEnabled( diff --git a/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc b/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc index 69675d49bc5..3632a26b706 100644 --- a/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc +++ b/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc @@ -152,7 +152,7 @@ void CustomHomePagesTableModel::Remove(int index) { } void CustomHomePagesTableModel::SetToCurrentlyOpenPages( - const content::WebContents* ignore_contents) { + content::WebContents* ignore_contents) { // Remove the current entries. while (RowCount()) RemoveWithoutNotification(0); @@ -166,7 +166,7 @@ void CustomHomePagesTableModel::SetToCurrentlyOpenPages( for (int tab_index = 0; tab_index < browser->tab_strip_model()->count(); ++tab_index) { - const content::WebContents* contents = + content::WebContents* contents = browser->tab_strip_model()->GetWebContentsAt(tab_index); if (contents == ignore_contents) continue; diff --git a/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.h b/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.h index 04760e43e7b..80937b2d8fe 100644 --- a/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.h +++ b/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.h @@ -54,7 +54,7 @@ class CustomHomePagesTableModel : public ui::TableModel { // Clears any entries and fills the list with pages currently opened in the // browser. |ignore_contents| is omitted from the open pages. - void SetToCurrentlyOpenPages(const content::WebContents* ignore_contents); + void SetToCurrentlyOpenPages(content::WebContents* ignore_contents); // Returns the set of urls this model contains. std::vector<GURL> GetURLs(); diff --git a/chromium/chrome/browser/ui/webui/settings/languages_handler.cc b/chromium/chrome/browser/ui/webui/settings/languages_handler.cc index 0346fa16e01..68aa52886fa 100644 --- a/chromium/chrome/browser/ui/webui/settings/languages_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/languages_handler.cc @@ -70,14 +70,6 @@ void LanguagesHandler::HandleSetProspectiveUILanguage( std::string language_code; CHECK(args->GetString(0, &language_code)); -#if defined(OS_CHROMEOS) - // 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(language::prefs::kApplicationLocale, language_code); 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 c235469b5f0..ab6b01e39cf 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 @@ -21,6 +21,7 @@ #include "chrome/browser/profiles/profile_shortcut_manager.h" #include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/sync/profile_sync_service_factory.h" +#include "chrome/browser/ui/passwords/manage_passwords_view_utils.h" #include "chrome/browser/ui/webui/policy_indicator_localized_strings_provider.h" #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" @@ -36,6 +37,7 @@ #include "components/browser_sync/profile_sync_service.h" #include "components/google/core/common/google_util.h" #include "components/omnibox/browser/omnibox_field_trial.h" +#include "components/password_manager/core/browser/manage_passwords_referrer.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/signin/core/browser/signin_buildflags.h" @@ -47,13 +49,14 @@ #include "content/public/common/content_features.h" #include "media/base/media_switches.h" #include "services/device/public/cpp/device_features.h" +#include "ui/accessibility/accessibility_switches.h" #include "ui/base/l10n/l10n_util.h" #if defined(OS_CHROMEOS) #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_switches.h" #include "ash/public/interfaces/voice_interaction_controller.mojom.h" -#include "base/sys_info.h" +#include "base/system/sys_info.h" #include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h" @@ -61,6 +64,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 "chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.h" #include "chromeos/chromeos_features.h" #include "chromeos/chromeos_switches.h" #include "chromeos/services/multidevice_setup/public/cpp/url_provider.h" @@ -79,6 +83,10 @@ #if defined(GOOGLE_CHROME_BUILD) #include "base/metrics/field_trial_params.h" +#include "base/strings/strcat.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/grit/chrome_unscaled_resources.h" +#include "ui/base/resource/resource_bundle.h" #endif #endif // defined(OS_WIN) @@ -147,10 +155,13 @@ void AddCommonStrings(content::WebUIDataSource* html_source, Profile* profile) { {"retry", IDS_SETTINGS_RETRY}, {"save", IDS_SAVE}, {"settings", IDS_SETTINGS_SETTINGS}, + {"settingsAltPageTitle", IDS_SETTINGS_ALT_PAGE_TITLE}, {"toggleOn", IDS_SETTINGS_TOGGLE_ON}, {"toggleOff", IDS_SETTINGS_TOGGLE_OFF}, {"notValid", IDS_SETTINGS_NOT_VALID}, {"notValidWebAddress", IDS_SETTINGS_NOT_VALID_WEB_ADDRESS}, + {"notValidWebAddressForContentType", + IDS_SETTINGS_NOT_VALID_WEB_ADDRESS_FOR_CONTENT_TYPE}, }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); @@ -209,6 +220,29 @@ 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}, + {"autoclickEventTypeLabel", IDS_SETTINGS_AUTOCLICK_EVENT_TYPE_LABEL}, + {"autoclickEventTypeLeftClick", + IDS_SETTINGS_AUTOCLICK_EVENT_TYPE_LEFT_CLICK}, + {"autoclickEventTypeRightClick", + IDS_SETTINGS_AUTOCLICK_EVENT_TYPE_RIGHT_CLICK}, + {"autoclickEventTypeDragAndDrop", + IDS_SETTINGS_AUTOCLICK_EVENT_TYPE_DRAG_AND_DROP}, + {"autoclickEventTypeDoubleClick", + IDS_SETTINGS_AUTOCLICK_EVENT_TYPE_DOUBLE_CLICK}, + {"autoclickEventTypeNoAction", IDS_SETTINGS_AUTOCLICK_EVENT_TYPE_NO_ACTION}, + {"autoclickRevertToLeftClick", IDS_SETTINGS_AUTOCLICK_REVERT_TO_LEFT_CLICK}, + {"autoclickMovementThresholdLabel", + IDS_SETTINGS_AUTOCLICK_MOVEMENT_THRESHOLD_LABEL}, + {"autoclickMovementThresholdExtraSmall", + IDS_SETTINGS_AUTOCLICK_MOVEMENT_THRESHOLD_EXTRA_SMALL}, + {"autoclickMovementThresholdSmall", + IDS_SETTINGS_AUTOCLICK_MOVEMENT_THRESHOLD_SMALL}, + {"autoclickMovementThresholdDefault", + IDS_SETTINGS_AUTOCLICK_MOVEMENT_THRESHOLD_DEFAULT}, + {"autoclickMovementThresholdLarge", + IDS_SETTINGS_AUTOCLICK_MOVEMENT_THRESHOLD_LARGE}, + {"autoclickMovementThresholdExtraLarge", + IDS_SETTINGS_AUTOCLICK_MOVEMENT_THRESHOLD_EXTRA_LARGE}, {"dictationDescription", IDS_SETTINGS_ACCESSIBILITY_DICTATION_DESCRIPTION}, {"dictationLabel", IDS_SETTINGS_ACCESSIBILITY_DICTATION_LABEL}, {"onScreenKeyboardLabel", IDS_SETTINGS_ON_SCREEN_KEYBOARD_LABEL}, @@ -301,7 +335,17 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { html_source->AddBoolean( "showExperimentalA11yFeatures", base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kEnableExperimentalAccessibilityFeatures)); + ::switches::kEnableExperimentalAccessibilityFeatures)); + + html_source->AddBoolean( + "showExperimentalAccessibilityAutoclick", + base::CommandLine::ForCurrentProcess()->HasSwitch( + ::switches::kEnableExperimentalAccessibilityAutoclick)); + + html_source->AddBoolean( + "showExperimentalAccessibilitySwitchAccess", + base::CommandLine::ForCurrentProcess()->HasSwitch( + ::switches::kEnableExperimentalAccessibilitySwitchAccess)); html_source->AddBoolean("dockedMagnifierFeatureEnabled", ash::features::IsDockedMagnifierEnabled()); @@ -477,6 +521,7 @@ void AddAppearanceStrings(content::WebUIDataSource* html_source, #endif #if defined(OS_MACOSX) {"tabsToLinks", IDS_SETTINGS_TABS_TO_LINKS_PREF}, + {"warnBeforeQuitting", IDS_SETTINGS_WARN_BEFORE_QUITTING_PREF}, #endif }; AddLocalizedStringsBulk(html_source, localized_strings, @@ -516,7 +561,7 @@ void AddBluetoothStrings(content::WebUIDataSource* html_source) { void AddChangePasswordStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"changePasswordPageTitle", IDS_SETTINGS_CHANGE_PASSWORD_TITLE}, - {"changePasswordPageDetails", IDS_SETTINGS_CHANGE_PASSWORD_DETAIL}, + {"changePasswordPageDetails", IDS_PAGE_INFO_CHANGE_PASSWORD_DETAILS}, {"changePasswordPageButton", IDS_SETTINGS_CHANGE_PASSWORD_BUTTON}, }; AddLocalizedStringsBulk(html_source, localized_strings, @@ -655,8 +700,8 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { {"keyRepeatRate", IDS_SETTINGS_KEYBOARD_AUTO_REPEAT_RATE}, {"keyRepeatRateSlow", IDS_SETTINGS_KEYBOARD_AUTO_REPEAT_RATE_SLOW}, {"keyRepeatRateFast", IDS_SETTINGS_KEYBOARD_AUTO_REPEAT_FAST}, - {"showKeyboardShortcutsOverlay", - IDS_SETTINGS_KEYBOARD_SHOW_KEYBOARD_SHORTCUTS_OVERLAY}, + {"showKeyboardShortcutViewer", + IDS_SETTINGS_KEYBOARD_SHOW_SHORTCUT_VIEWER}, {"keyboardShowLanguageAndInput", IDS_SETTINGS_KEYBOARD_SHOW_LANGUAGE_AND_INPUT}, }; @@ -839,10 +884,6 @@ void AddDownloadsStrings(content::WebUIDataSource* html_source) { {"smbSharesLearnMoreLabel", 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", IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_SUCCESS_MESSAGE}, {"smbShareAddedErrorMessage", @@ -857,20 +898,14 @@ void AddDownloadsStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_MOUNT_EXISTS_MESSAGE}, {"smbShareAddedInvalidURLMessage", IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_MOUNT_INVALID_URL_MESSAGE}, - {"smbShareAuthenticationMethod", - IDS_SETTINGS_DOWNLOADS_ADD_SHARE_AUTHENTICATION_METHOD}, - {"smbShareStandardAuthentication", - IDS_SETTINGS_DOWNLOADS_ADD_SHARE_STANDARD_AUTHENTICATION}, - {"smbShareKerberosAuthentication", - IDS_SETTINGS_DOWNLOADS_ADD_SHARE_KERBEROS_AUTHENTICATION}, #endif }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); #if defined(OS_CHROMEOS) - html_source->AddBoolean("enableNativeSmbSetting", - base::FeatureList::IsEnabled(features::kNativeSmb)); + chromeos::smb_dialog::AddLocalizedStrings(html_source); + html_source->AddString("smbSharesLearnMoreURL", GetHelpUrlWithBoard(chrome::kSmbSharesLearnMoreURL)); #endif @@ -952,9 +987,18 @@ void AddChromeCleanupStrings(content::WebUIDataSource* html_source) { .spec(); html_source->AddString("chromeCleanupLearnMoreUrl", cleanup_learn_more_url); + // The "powered by" footer contains an HTML fragment with the SVG logo of the + // partner. The logo is added directly to the DOM, rather than as an <img> + // src, to make sure that screen readers can find accessibility tags inside + // the SVG. + const std::string powered_by_element = + base::StrCat({"<span id='powered-by-logo'>", + ui::ResourceBundle::GetSharedInstance().GetRawDataResource( + IDR_CHROME_CLEANUP_PARTNER), + "</span>"}); const base::string16 powered_by_html = l10n_util::GetStringFUTF16(IDS_SETTINGS_RESET_CLEANUP_FOOTER_POWERED_BY, - L"<span id='powered-by-logo'></span>"); + base::UTF8ToUTF16(powered_by_element)); html_source->AddString("chromeCleanupPoweredByHtml", powered_by_html); const base::string16 cleanup_details_explanation = @@ -1103,29 +1147,6 @@ void AddDateTimeStrings(content::WebUIDataSource* html_source) { void AddEasyUnlockStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"easyUnlockSectionTitle", IDS_SETTINGS_EASY_UNLOCK_SECTION_TITLE}, - {"easyUnlockSetupButton", IDS_SETTINGS_EASY_UNLOCK_SETUP}, - // Easy Unlock turn-off dialog. - {"easyUnlockTurnOffButton", IDS_SETTINGS_EASY_UNLOCK_TURN_OFF}, - {"easyUnlockTurnOffOfflineTitle", - IDS_SETTINGS_EASY_UNLOCK_TURN_OFF_OFFLINE_TITLE}, - {"easyUnlockTurnOffOfflineMessage", - IDS_SETTINGS_EASY_UNLOCK_TURN_OFF_OFFLINE_MESSAGE}, - {"easyUnlockTurnOffErrorTitle", - IDS_SETTINGS_EASY_UNLOCK_TURN_OFF_ERROR_TITLE}, - {"easyUnlockTurnOffErrorMessage", - IDS_SETTINGS_EASY_UNLOCK_TURN_OFF_ERROR_MESSAGE}, - {"easyUnlockAllowSignInLabel", - IDS_SETTINGS_EASY_UNLOCK_ALLOW_SIGN_IN_LABEL}, - {"easyUnlockProximityThresholdLabel", - IDS_SETTINGS_EASY_UNLOCK_PROXIMITY_THRESHOLD_LABEL}, - {"easyUnlockProximityThresholdVeryClose", - IDS_SETTINGS_EASY_UNLOCK_PROXIMITY_THRESHOLD_VERY_CLOSE}, - {"easyUnlockProximityThresholdClose", - IDS_SETTINGS_EASY_UNLOCK_PROXIMITY_THRESHOLD_CLOSE}, - {"easyUnlockProximityThresholdFar", - IDS_SETTINGS_EASY_UNLOCK_PROXIMITY_THRESHOLD_FAR}, - {"easyUnlockProximityThresholdVeryFar", - IDS_SETTINGS_EASY_UNLOCK_PROXIMITY_THRESHOLD_VERY_FAR}, {"easyUnlockUnlockDeviceOnly", IDS_SETTINGS_EASY_UNLOCK_UNLOCK_DEVICE_ONLY}, {"easyUnlockUnlockDeviceAndAllowSignin", @@ -1133,32 +1154,6 @@ void AddEasyUnlockStrings(content::WebUIDataSource* html_source) { }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); - - base::string16 device_name = - l10n_util::GetStringUTF16(ui::GetChromeOSDeviceTypeResourceId()); - html_source->AddString( - "easyUnlockSetupIntro", - l10n_util::GetStringFUTF16(IDS_SETTINGS_EASY_UNLOCK_SETUP_INTRO, - device_name)); - html_source->AddString( - "easyUnlockDescription", - l10n_util::GetStringFUTF16(IDS_SETTINGS_EASY_UNLOCK_DESCRIPTION, - device_name)); - html_source->AddString( - "easyUnlockTurnOffTitle", - l10n_util::GetStringFUTF16(IDS_SETTINGS_EASY_UNLOCK_TURN_OFF_TITLE, - device_name)); - html_source->AddString( - "easyUnlockTurnOffDescription", - l10n_util::GetStringFUTF16(IDS_SETTINGS_EASY_UNLOCK_TURN_OFF_DESCRIPTION, - device_name)); - html_source->AddString( - "easyUnlockProximityThresholdLabel", - l10n_util::GetStringFUTF16( - IDS_SETTINGS_EASY_UNLOCK_PROXIMITY_THRESHOLD_LABEL, device_name)); - - html_source->AddString("easyUnlockLearnMoreURL", - GetHelpUrlWithBoard(chrome::kEasyUnlockLearnMoreUrl)); } void AddInternetStrings(content::WebUIDataSource* html_source) { @@ -1204,6 +1199,7 @@ void AddInternetStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_INTERNET_KNOWN_NETWORKS_MENU_FORGET}, {"networkAllowDataRoaming", IDS_SETTINGS_SETTINGS_NETWORK_ALLOW_DATA_ROAMING}, + {"networkAlwaysOnVpn", IDS_SETTINGS_INTERNET_NETWORK_ALWAYS_ON_VPN}, {"networkAutoConnect", IDS_SETTINGS_INTERNET_NETWORK_AUTO_CONNECT}, {"networkButtonActivate", IDS_SETTINGS_INTERNET_BUTTON_ACTIVATE}, {"networkButtonConfigure", IDS_SETTINGS_INTERNET_BUTTON_CONFIGURE}, @@ -1413,11 +1409,13 @@ void AddOnStartupStrings(content::WebUIDataSource* html_source) { arraysize(localized_strings)); } -void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source, - Profile* profile) { +void AddAutofillStrings(content::WebUIDataSource* html_source, + Profile* profile) { LocalizedString localized_strings[] = { - {"passwordsAndAutofillPageTitle", - IDS_SETTINGS_PASSWORDS_AND_AUTOFILL_PAGE_TITLE}, + {"autofillPageTitle", IDS_SETTINGS_AUTOFILL}, + {"passwords", IDS_SETTINGS_PASSWORDS}, + {"creditCards", IDS_AUTOFILL_PAYMENT_METHODS}, + {"noCreditCardsFound", IDS_SETTINGS_PAYMENT_METHODS_NONE}, {"googlePayments", IDS_SETTINGS_GOOGLE_PAYMENTS}, {"googlePaymentsCached", IDS_SETTINGS_GOOGLE_PAYMENTS_CACHED}, {"enableProfilesLabel", IDS_AUTOFILL_ENABLE_PROFILES_TOGGLE_LABEL}, @@ -1435,7 +1433,6 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source, {"removeAddress", IDS_SETTINGS_ADDRESS_REMOVE}, {"removeCreditCard", IDS_SETTINGS_CREDIT_CARD_REMOVE}, {"clearCreditCard", IDS_SETTINGS_CREDIT_CARD_CLEAR}, - {"creditCardsDetail", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_DETAIL}, {"creditCardType", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_TYPE_COLUMN_LABEL}, {"creditCardExpiration", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_DATE}, {"creditCardName", IDS_SETTINGS_NAME_ON_CREDIT_CARD}, @@ -1445,10 +1442,7 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source, {"creditCardExpired", IDS_SETTINGS_CREDIT_CARD_EXPIRED}, {"editCreditCardTitle", IDS_SETTINGS_EDIT_CREDIT_CARD_TITLE}, {"addCreditCardTitle", IDS_SETTINGS_ADD_CREDIT_CARD_TITLE}, - {"migrateCreditCardsLabelSingle", - IDS_SETTINGS_SINGLE_MIGRATABLE_CARD_LABEL}, - {"migrateCreditCardsLabelMultiple", - IDS_SETTINGS_MULTIPLE_MIGRATABLE_CARDS_LABEL}, + {"migrateCreditCardsLabel", IDS_SETTINGS_MIGRATABLE_CARDS_LABEL}, {"migratableCardsInfoSingle", IDS_SETTINGS_SINGLE_MIGRATABLE_CARD_INFO}, {"migratableCardsInfoMultiple", IDS_SETTINGS_MULTIPLE_MIGRATABLE_CARDS_INFO}, @@ -1460,7 +1454,6 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL}, {"passwordsAutosigninDescription", IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC}, - {"passwordsDetail", IDS_SETTINGS_PASSWORDS_DETAIL}, {"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING}, {"passwordExceptionsHeading", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_HEADING}, {"deletePasswordException", IDS_SETTINGS_PASSWORDS_DELETE_EXCEPTION}, @@ -1497,31 +1490,16 @@ 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_AUTOFILL_ADDRESSES_SETTINGS_TITLE); - html_source->AddLocalizedString("passwords", - IDS_SETTINGS_PASSWORDS_AUTOFILL_HOME); - html_source->AddLocalizedString("creditCards", - IDS_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); - } + GURL google_password_manager_url = GetGooglePasswordManagerURL( + password_manager::ManagePasswordsReferrer::kChromeSettings); html_source->AddString( "managePasswordsLabel", l10n_util::GetStringFUTF16( IDS_SETTINGS_PASSWORDS_MANAGE_PASSWORDS, - l10n_util::GetStringUTF16(IDS_PASSWORDS_WEB_LINK))); + base::UTF8ToUTF16(google_password_manager_url.spec()))); + html_source->AddString("googlePasswordManagerUrl", + google_password_manager_url.spec()); html_source->AddString("passwordManagerLearnMoreURL", chrome::kPasswordManagerLearnMoreURL); html_source->AddString("manageAddressesUrl", @@ -1554,9 +1532,6 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source, sync_service->IsUsingSecondaryPassphrase()); html_source->AddBoolean( "uploadToGoogleActive", - base::FeatureList::IsEnabled( - autofill::features:: - kAutofillEnablePaymentsInteractionsOnAuthError) || syncer::GetUploadToGoogleState( sync_service, syncer::ModelType::AUTOFILL_WALLET_DATA) == syncer::UploadState::ACTIVE); @@ -1593,10 +1568,6 @@ void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source, AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); - - html_source->AddBoolean("EnableCompanyName", - base::FeatureList::IsEnabled( - autofill::features::kAutofillEnableCompanyName)); } void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { @@ -1713,7 +1684,9 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"editPerson", IDS_SETTINGS_EDIT_PERSON}, {"profileNameAndPicture", IDS_SETTINGS_PROFILE_NAME_AND_PICTURE}, {"showShortcutLabel", IDS_SETTINGS_PROFILE_SHORTCUT_TOGGLE_LABEL}, - {"syncWillStart", IDS_SETTINGS_SYNC_WILL_START}, + {"syncWillStart", unified_consent::IsUnifiedConsentFeatureEnabled() + ? IDS_SETTINGS_SYNC_WILL_START_UNITY + : IDS_SETTINGS_SYNC_WILL_START}, {"syncSettingsSavedToast", IDS_SETTINGS_SYNC_SETTINGS_SAVED_TOAST_LABEL}, {"cancelSync", IDS_SETTINGS_SYNC_SETTINGS_CANCEL_SYNC}, #endif // defined(OS_CHROMEOS) @@ -1736,12 +1709,9 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"syncSignInPromptWithNoAccount", IDS_SETTINGS_SYNC_SIGN_IN_PROMPT_WITH_NO_ACCOUNT}, #endif - {"syncUnifiedConsentToggleTitle", - IDS_SETTINGS_PEOPLE_SYNC_UNIFIED_CONSENT_TOGGLE_TITLE}, {"syncOverview", IDS_SETTINGS_SYNC_OVERVIEW}, {"syncDisabled", IDS_PROFILES_DICE_SYNC_DISABLED_TITLE}, - {"syncDisabledByAdministrator", - IDS_SETTINGS_SYNC_DISABLED_BY_ADMINISTRATOR}, + {"syncDisabledByAdministrator", IDS_SIGNED_IN_WITH_SYNC_DISABLED}, {"syncSignin", IDS_SETTINGS_SYNC_SIGNIN}, {"syncDisconnect", IDS_SETTINGS_PEOPLE_SIGN_OUT}, {"syncDisconnectTitle", IDS_SETTINGS_SYNC_DISCONNECT_TITLE}, @@ -1756,28 +1726,20 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"deleteProfileWarningWithoutCounts", IDS_SETTINGS_SYNC_DISCONNECT_DELETE_PROFILE_WARNING_WITHOUT_COUNTS}, {"syncDisconnectConfirm", IDS_SETTINGS_SYNC_DISCONNECT_CONFIRM}, - {"sync", unified_consent::IsUnifiedConsentFeatureEnabled() - ? IDS_SETTINGS_SYNC_UNIFIED_CONSENT - : IDS_SETTINGS_SYNC}, - {"syncDescription", unified_consent::IsUnifiedConsentFeatureEnabled() - ? IDS_SETTINGS_SYNC_DESCRIPTION_UNIFIED_CONSENT - : IDS_SETTINGS_SYNC_DESCRIPTION}, + {"sync", IDS_SETTINGS_SYNC}, {"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}, {"syncAndNonPersonalizedServices", IDS_SETTINGS_SYNC_SYNC_AND_NON_PERSONALIZED_SERVICES}, {"syncPageTitle", unified_consent::IsUnifiedConsentFeatureEnabled() ? IDS_SETTINGS_SYNC_SYNC_AND_NON_PERSONALIZED_SERVICES : IDS_SETTINGS_SYNC_PAGE_TITLE}, + {"syncAdvancedPageTitle", IDS_SETTINGS_SYNC_ADVANCED_PAGE_TITLE}, {"syncLoading", IDS_SETTINGS_SYNC_LOADING}, {"syncTimeout", IDS_SETTINGS_SYNC_TIMEOUT}, {"syncEverythingCheckboxLabel", IDS_SETTINGS_SYNC_EVERYTHING_CHECKBOX_LABEL}, + {"manageGoogleAccount", IDS_SETTINGS_MANAGE_GOOGLE_ACCOUNT}, {"appCheckboxLabel", IDS_SETTINGS_APPS_CHECKBOX_LABEL}, {"extensionsCheckboxLabel", IDS_SETTINGS_EXTENSIONS_CHECKBOX_LABEL}, {"settingsCheckboxLabel", IDS_SETTINGS_SETTINGS_CHECKBOX_LABEL}, @@ -1788,11 +1750,12 @@ 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}, - {"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}, + {"manageSyncedDataTitle", + unified_consent::IsUnifiedConsentFeatureEnabled() + ? IDS_SETTINGS_MANAGE_SYNCED_DATA_TITLE_UNIFIED_CONSENT + : IDS_SETTINGS_MANAGE_SYNCED_DATA_TITLE}, {"encryptionOptionsTitle", IDS_SETTINGS_ENCRYPTION_OPTIONS}, {"syncDataEncryptedText", IDS_SETTINGS_SYNC_DATA_ENCRYPTED_TEXT}, {"encryptWithGoogleCredentialsLabel", @@ -1808,22 +1771,12 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"personalizeGoogleServicesTitle", IDS_SETTINGS_PERSONALIZE_GOOGLE_SERVICES_TITLE}, {"existingPassphraseTitle", IDS_SETTINGS_EXISTING_PASSPHRASE_TITLE}, + {"enablePaymentsIntegrationCheckboxLabel", + IDS_AUTOFILL_ENABLE_PAYMENTS_INTEGRATION_CHECKBOX_LABEL}, }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); - if (base::FeatureList::IsEnabled(password_manager::features::kAutofillHome)) { - // TODO(https://crbug.com/854562): Integrate this string into the - // |localized_strings| array once Autofill Home is fully launched. - html_source->AddLocalizedString( - "enablePaymentsIntegrationCheckboxLabel", - IDS_AUTOFILL_ENABLE_PAYMENTS_INTEGRATION_CHECKBOX_LABEL); - } 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), @@ -1920,6 +1873,8 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { html_source->AddString("activityControlsUrl", chrome::kGoogleAccountActivityControlsURL); + html_source->AddString("googleAccountUrl", chrome::kGoogleAccountURL); + html_source->AddBoolean("profileShortcutsEnabled", ProfileShortcutManager::IsFeatureEnabled()); @@ -2328,7 +2283,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_COOKIES_LOCAL_STORAGE_LAST_MODIFIED_LABEL}, {"noUsbDevicesFound", IDS_SETTINGS_NO_USB_DEVICES_FOUND}, {"serviceWorkerOrigin", IDS_SETTINGS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL}, - {"serviceWorkerScopes", IDS_SETTINGS_COOKIES_SERVICE_WORKER_SCOPES_LABEL}, {"serviceWorkerSize", IDS_SETTINGS_COOKIES_LOCAL_STORAGE_SIZE_ON_DISK_LABEL}, {"sharedWorkerWorker", IDS_SETTINGS_COOKIES_SHARED_WORKER_WORKER_LABEL}, @@ -2734,10 +2688,6 @@ void AddMultideviceStrings(content::WebUIDataSource* html_source) { AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); - html_source->AddBoolean( - "enableMultideviceSettings", - base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSettings)); html_source->AddString( "multideviceVerificationText", l10n_util::GetStringFUTF16( @@ -2788,6 +2738,7 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, Profile* profile) { AddA11yStrings(html_source); AddAboutStrings(html_source); + AddAutofillStrings(html_source, profile); AddAppearanceStrings(html_source, profile); #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) @@ -2801,7 +2752,6 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, AddDownloadsStrings(html_source); AddLanguagesStrings(html_source); AddOnStartupStrings(html_source); - AddPasswordsAndFormsStrings(html_source, profile); AddPeopleStrings(html_source, profile); AddPrintingStrings(html_source); AddPrivacyStrings(html_source, profile); 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 051c36122b7..257e8c6dd6c 100644 --- a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc +++ b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc @@ -16,6 +16,7 @@ #include "base/metrics/histogram_macros.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/passwords/manage_passwords_view_utils.h" #include "chrome/browser/ui/webui/metrics_handler.h" #include "chrome/browser/ui/webui/settings/about_handler.h" #include "chrome/browser/ui/webui/settings/appearance_handler.h" @@ -30,7 +31,6 @@ #include "chrome/browser/ui/webui/settings/profile_info_handler.h" #include "chrome/browser/ui/webui/settings/protocol_handlers_handler.h" #include "chrome/browser/ui/webui/settings/reset_settings_handler.h" -#include "chrome/browser/ui/webui/settings/safe_browsing_handler.h" #include "chrome/browser/ui/webui/settings/search_engines_handler.h" #include "chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h" #include "chrome/browser/ui/webui/settings/settings_cookies_view_handler.h" @@ -61,7 +61,6 @@ #include "chrome/browser/conflicts/incompatible_applications_updater_win.h" #include "chrome/browser/conflicts/token_util_win.h" #include "chrome/browser/ui/webui/settings/incompatible_applications_handler_win.h" -#include "chrome/grit/chrome_unscaled_resources.h" #endif #endif // defined(OS_WIN) @@ -71,6 +70,7 @@ #endif // defined(OS_WIN) || defined(OS_CHROMEOS) #if defined(OS_CHROMEOS) +#include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" #include "ash/public/cpp/stylus_utils.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/arc/arc_util.h" @@ -80,6 +80,7 @@ #include "chrome/browser/chromeos/multidevice_setup/android_sms_app_helper_delegate_impl.h" #include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_client_factory.h" #include "chrome/browser/signin/account_tracker_service_factory.h" +#include "chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h" @@ -92,17 +93,18 @@ #include "chrome/browser/ui/webui/settings/chromeos/device_power_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.h" -#include "chrome/browser/ui/webui/settings/chromeos/easy_unlock_settings_handler.h" #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/browser/web_applications/system_web_app_manager.h" #include "chrome/common/chrome_switches.h" +#include "chrome/grit/browser_resources.h" #include "chromeos/account_manager/account_manager.h" #include "chromeos/account_manager/account_manager_factory.h" #include "chromeos/chromeos_features.h" #include "chromeos/chromeos_switches.h" +#include "chromeos/services/multidevice_setup/public/cpp/prefs.h" #include "components/arc/arc_util.h" #include "ui/base/ui_base_features.h" #else // !defined(OS_CHROMEOS) @@ -177,8 +179,6 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) AddSettingsPageUIHandler(std::make_unique<PeopleHandler>(profile)); AddSettingsPageUIHandler(std::make_unique<ProfileInfoHandler>(profile)); AddSettingsPageUIHandler(std::make_unique<ProtocolHandlersHandler>()); - AddSettingsPageUIHandler( - std::make_unique<SafeBrowsingHandler>(profile->GetPrefs())); AddSettingsPageUIHandler(std::make_unique<SearchEnginesHandler>(profile)); AddSettingsPageUIHandler(std::make_unique<SiteSettingsHandler>(profile)); AddSettingsPageUIHandler(std::make_unique<StartupPagesHandler>(web_ui)); @@ -219,32 +219,17 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) } AddSettingsPageUIHandler( std::make_unique<chromeos::settings::KeyboardHandler>()); - if (!profile->IsGuestSession() && - base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSetup) && - base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSettings) && - base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { - AddSettingsPageUIHandler( - std::make_unique<chromeos::settings::MultideviceHandler>( - profile->GetPrefs(), - chromeos::multidevice_setup::MultiDeviceSetupClientFactory:: - GetForProfile(profile), - std::make_unique< - chromeos::multidevice_setup::AndroidSmsAppHelperDelegateImpl>( - profile))); - } AddSettingsPageUIHandler( std::make_unique<chromeos::settings::PointerHandler>()); AddSettingsPageUIHandler( - std::make_unique<chromeos::settings::SmbHandler>(profile)); - AddSettingsPageUIHandler( std::make_unique<chromeos::settings::StorageHandler>(profile)); AddSettingsPageUIHandler( std::make_unique<chromeos::settings::StylusHandler>()); AddSettingsPageUIHandler( std::make_unique<chromeos::settings::InternetHandler>(profile)); AddSettingsPageUIHandler(std::make_unique<TtsHandler>()); + AddSettingsPageUIHandler( + std::make_unique<chromeos::smb_dialog::SmbHandler>(profile)); #else AddSettingsPageUIHandler(std::make_unique<DefaultBrowserHandler>()); AddSettingsPageUIHandler(std::make_unique<ManageProfileHandler>(profile)); @@ -260,13 +245,6 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) #if defined(OS_WIN) AddSettingsPageUIHandler(std::make_unique<ChromeCleanupHandler>(profile)); - -#if defined(GOOGLE_CHROME_BUILD) - html_source->AddResourcePath("partner-logo.svg", IDR_CHROME_CLEANUP_PARTNER); -#if BUILDFLAG(OPTIMIZE_WEBUI) - exclude_from_gzip.push_back("partner-logo.svg"); -#endif -#endif // defined(GOOGLE_CHROME_BUILD) #endif // defined(OS_WIN) #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) @@ -297,11 +275,29 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) password_protection_available); #if defined(OS_CHROMEOS) - chromeos::settings::EasyUnlockSettingsHandler* easy_unlock_handler = - chromeos::settings::EasyUnlockSettingsHandler::Create(html_source, - profile); - if (easy_unlock_handler) - AddSettingsPageUIHandler(base::WrapUnique(easy_unlock_handler)); + if (!profile->IsGuestSession() && + base::FeatureList::IsEnabled( + chromeos::features::kEnableUnifiedMultiDeviceSetup) && + base::FeatureList::IsEnabled( + chromeos::features::kEnableUnifiedMultiDeviceSettings) && + base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { + AddSettingsPageUIHandler( + std::make_unique<chromeos::settings::MultideviceHandler>( + profile->GetPrefs(), + chromeos::multidevice_setup::MultiDeviceSetupClientFactory:: + GetForProfile(profile), + std::make_unique< + chromeos::multidevice_setup::AndroidSmsAppHelperDelegateImpl>( + profile))); + } + html_source->AddBoolean( + "enableMultideviceSettings", + base::FeatureList::IsEnabled( + chromeos::features::kEnableUnifiedMultiDeviceSettings)); + html_source->AddBoolean( + "multideviceAllowedByPolicy", + chromeos::multidevice_setup::AreAnyMultiDeviceFeaturesAllowed( + profile->GetPrefs())); AddSettingsPageUIHandler(base::WrapUnique( chromeos::settings::DateTimeHandler::Create(html_source))); @@ -314,8 +310,9 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) html_source->AddBoolean( "quickUnlockDisabledByPolicy", chromeos::quick_unlock::IsPinDisabledByPolicy(profile->GetPrefs())); - html_source->AddBoolean("fingerprintUnlockEnabled", - chromeos::quick_unlock::IsFingerprintEnabled()); + html_source->AddBoolean( + "fingerprintUnlockEnabled", + chromeos::quick_unlock::IsFingerprintEnabled(profile)); html_source->AddBoolean("lockScreenNotificationsEnabled", ash::features::IsLockScreenNotificationsEnabled()); html_source->AddBoolean( @@ -327,9 +324,7 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) html_source->AddBoolean("showCrostini", crostini::IsCrostiniUIAllowedForProfile(profile)); - // TODO(crbug.com/868747): Show an explanatory message instead of hiding the - // storage management info. - html_source->AddBoolean("hideStorageInfo", + html_source->AddBoolean("isDemoSession", chromeos::DemoSession::IsDeviceInDemoMode()); // We have 2 variants of Android apps settings. Default case, when the Play @@ -360,11 +355,9 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) html_source->AddBoolean("unifiedConsentEnabled", unified_consent::IsUnifiedConsentFeatureEnabled()); - // TODO(jdoerrie): https://crbug.com/854562. - // Remove once Autofill Home is launched. html_source->AddBoolean( - "autofillHomeEnabled", - base::FeatureList::IsEnabled(password_manager::features::kAutofillHome)); + "navigateToGooglePasswordManager", + ShouldManagePasswordsinGooglePasswordManager(profile)); html_source->AddBoolean("showImportPasswords", base::FeatureList::IsEnabled( @@ -378,6 +371,18 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) // Add the metrics handler to write uma stats. web_ui->AddMessageHandler(std::make_unique<MetricsHandler>()); +#if defined(OS_CHROMEOS) + // Add the System Web App resources for Settings. + if (web_app::SystemWebAppManager::ShouldEnableForProfile(profile)) { + html_source->AddResourcePath("icon-192.png", IDR_SETTINGS_LOGO_192); + html_source->AddResourcePath("pwa.html", IDR_PWA_HTML); +#if BUILDFLAG(OPTIMIZE_WEBUI) + exclude_from_gzip.push_back("icon-192.png"); + exclude_from_gzip.push_back("pwa.html"); +#endif // BUILDFLAG(OPTIMIZE_WEBUI) + } +#endif // defined (OS_CHROMEOS) + #if BUILDFLAG(OPTIMIZE_WEBUI) const bool use_polymer_2 = base::FeatureList::IsEnabled(features::kWebUIPolymer2); @@ -392,6 +397,9 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui) ? IDR_MD_SETTINGS_VULCANIZED_P2_HTML : IDR_MD_SETTINGS_VULCANIZED_HTML); html_source->UseGzip(exclude_from_gzip); +#if defined(OS_CHROMEOS) + html_source->AddResourcePath("manifest.json", IDR_MD_SETTINGS_MANIFEST); +#endif // defined (OS_CHROMEOS) #else // Add all settings resources. for (size_t i = 0; i < kSettingsResourcesSize; ++i) { diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.cc b/chromium/chrome/browser/ui/webui/settings/people_handler.cc index 7d6abb49ada..a1e56381edc 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/identity_manager_factory.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" @@ -41,7 +42,7 @@ #include "components/autofill/core/common/autofill_prefs.h" #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/account_consistency_method.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" @@ -49,7 +50,6 @@ #include "components/signin/core/browser/signin_pref_names.h" #include "components/strings/grit/components_strings.h" #include "components/sync/base/passphrase_enums.h" -#include "components/sync/base/sync_prefs.h" #include "components/unified_consent/feature.h" #include "components/unified_consent/unified_consent_metrics.h" #include "content/public/browser/render_view_host.h" @@ -66,7 +66,6 @@ #include "components/signin/core/browser/signin_manager_base.h" #else #include "chrome/browser/signin/signin_util.h" -#include "chrome/browser/ui/user_manager.h" #include "chrome/browser/ui/webui/profile_helper.h" #include "components/signin/core/browser/signin_manager.h" #endif @@ -220,7 +219,7 @@ const char PeopleHandler::kPassphraseFailedPageStatus[] = "passphraseFailed"; PeopleHandler::PeopleHandler(Profile* profile) : profile_(profile), configuring_sync_(false), - signin_observer_(this), + identity_manager_observer_(this), #if BUILDFLAG(ENABLE_DICE_SUPPORT) sync_service_observer_(this), account_tracker_observer_(this) { @@ -262,14 +261,6 @@ void PeopleHandler::RegisterMessages() { "SyncSetupGetSyncStatus", base::BindRepeating(&PeopleHandler::HandleGetSyncStatus, base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "SyncSetupManageOtherPeople", - base::BindRepeating(&PeopleHandler::HandleManageOtherPeople, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "UnifiedConsentToggleChanged", - base::BindRepeating(&PeopleHandler::OnUnifiedConsentToggleChanged, - base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( "AttemptUserExit", @@ -310,10 +301,10 @@ void PeopleHandler::OnJavascriptAllowed() { prefs::kSigninAllowed, base::Bind(&PeopleHandler::UpdateSyncStatus, base::Unretained(this))); - SigninManagerBase* signin_manager( - SigninManagerFactory::GetInstance()->GetForProfile(profile_)); - if (signin_manager) - signin_observer_.Add(signin_manager); + identity::IdentityManager* identity_manager( + IdentityManagerFactory::GetInstance()->GetForProfile(profile_)); + if (identity_manager) + identity_manager_observer_.Add(identity_manager); // This is intentionally not using GetSyncService(), to go around the // Profile::IsSyncAllowed() check. @@ -332,7 +323,7 @@ void PeopleHandler::OnJavascriptAllowed() { void PeopleHandler::OnJavascriptDisallowed() { profile_pref_registrar_.RemoveAll(); - signin_observer_.RemoveAll(); + identity_manager_observer_.RemoveAll(); sync_service_observer_.RemoveAll(); #if BUILDFLAG(ENABLE_DICE_SUPPORT) account_tracker_observer_.RemoveAll(); @@ -497,8 +488,8 @@ void PeopleHandler::HandleSetDatatypes(const base::ListValue* args) { return; } - service->OnUserChoseDatatypes(configuration.sync_everything, - configuration.data_types); + service->GetUserSettings()->SetChosenDataTypes(configuration.sync_everything, + configuration.data_types); // Choosing data types to sync never fails. ResolveJavascriptCallback(*callback_id, base::Value(kConfigurePageStatus)); @@ -608,7 +599,7 @@ void PeopleHandler::HandleSetEncryption(const base::ListValue* args) { // Don't allow "encrypt all" if the ProfileSyncService doesn't allow it. // The UI is hidden, but the user may have enabled it e.g. by fiddling with // the web inspector. - if (!service->IsEncryptEverythingAllowed()) + if (!service->GetUserSettings()->IsEncryptEverythingAllowed()) configuration.encrypt_all = false; // Note: Data encryption will not occur until configuration is complete @@ -616,34 +607,35 @@ void PeopleHandler::HandleSetEncryption(const base::ListValue* args) { // engine), so the user still has a chance to cancel out of the operation // if (for example) some kind of passphrase error is encountered. if (configuration.encrypt_all) - service->EnableEncryptEverything(); + service->GetUserSettings()->EnableEncryptEverything(); bool passphrase_failed = false; if (!configuration.passphrase.empty()) { // We call IsPassphraseRequired() here (instead of // IsPassphraseRequiredForDecryption()) because the user may try to enter // a passphrase even though no encrypted data types are enabled. - if (service->IsPassphraseRequired()) { + if (service->GetUserSettings()->IsPassphraseRequired()) { // If we have pending keys, try to decrypt them with the provided // passphrase. We track if this succeeds or fails because a failed // decryption should result in an error even if there aren't any encrypted // data types. - passphrase_failed = - !service->SetDecryptionPassphrase(configuration.passphrase); + passphrase_failed = !service->GetUserSettings()->SetDecryptionPassphrase( + configuration.passphrase); } else { // OK, the user sent us a passphrase, but we don't have pending keys. So // it either means that the pending keys were resolved somehow since the // time the UI was displayed (re-encryption, pending passphrase change, // etc) or the user wants to re-encrypt. if (configuration.set_new_passphrase && - !service->IsUsingSecondaryPassphrase()) { - service->SetEncryptionPassphrase(configuration.passphrase, - ProfileSyncService::EXPLICIT); + !service->GetUserSettings()->IsUsingSecondaryPassphrase()) { + service->GetUserSettings()->SetEncryptionPassphrase( + configuration.passphrase); } } } - if (passphrase_failed || service->IsPassphraseRequiredForDecryption()) { + if (passphrase_failed || + service->GetUserSettings()->IsPassphraseRequiredForDecryption()) { // If the user doesn't enter any passphrase, we won't call // SetDecryptionPassphrase() (passphrase_failed == false), but we still // want to display an error message to let the user know that their blank @@ -672,6 +664,9 @@ void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { if (service && !sync_blocker_) sync_blocker_ = service->GetSetupInProgressHandle(); + // TODO(treib): Should we also call SetSyncRequested(true) here? That's what + // happens in the non-Unity code path. + GetLoginUIService()->SetLoginUI(this); PushSyncPrefs(); @@ -709,14 +704,13 @@ void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { return; if (!service->IsEngineInitialized() || - service->HasDisableReason( - syncer::SyncService::DISABLE_REASON_USER_CHOICE)) { + !service->GetUserSettings()->IsSyncRequested()) { // Requesting the sync service to start may trigger call to PushSyncPrefs. // Setting up the startup tracker beforehand correctly signals the // re-entrant call to early exit. sync_startup_tracker_ = std::make_unique<SyncStartupTracker>(profile_, this); - // RequestStart() does two things: + // SetSyncRequested(true) does two things: // 1) If DISABLE_REASON_USER_CHOICE is set (meaning that Sync was reset via // the dashboard), clears it. // 2) Pokes the sync service to start *immediately*, i.e. bypass deferred @@ -727,7 +721,7 @@ void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { // already running in standalone transport mode and so the engine is already // initialized. In that case, this will trigger the service to switch to // full Sync-the-feature mode. - service->RequestStart(); + service->GetUserSettings()->SetSyncRequested(true); // See if it's even possible to bring up the sync engine - if not // (unrecoverable error?), don't bother displaying a spinner that will be @@ -798,7 +792,9 @@ void PeopleHandler::HandleSignout(const base::ListValue* args) { DCHECK(!delete_profile) << "Deleting the profile should only be offered the user is syncing."; ProfileOAuth2TokenServiceFactory::GetForProfile(profile_) - ->RevokeAllCredentials(); + ->RevokeAllCredentials( + signin_metrics::SourceForRefreshTokenOperation:: + kSettings_Signout); } } @@ -814,7 +810,8 @@ void PeopleHandler::HandlePauseSync(const base::ListValue* args) { DCHECK(signin_manager->IsAuthenticated()); ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->UpdateCredentials( signin_manager->GetAuthenticatedAccountId(), - OAuth2TokenServiceDelegate::kInvalidRefreshToken); + OAuth2TokenServiceDelegate::kInvalidRefreshToken, + signin_metrics::SourceForRefreshTokenOperation::kSettings_PauseSync); } #endif @@ -828,22 +825,6 @@ void PeopleHandler::HandleGetSyncStatus(const base::ListValue* args) { ResolveJavascriptCallback(*callback_id, *GetSyncStatusDictionary()); } -void PeopleHandler::HandleManageOtherPeople(const base::ListValue* /* args */) { -#if !defined(OS_CHROMEOS) - UserManager::Show(base::FilePath(), - profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION); -#endif // !defined(OS_CHROMEOS) -} - -void PeopleHandler::OnUnifiedConsentToggleChanged(const base::ListValue* args) { - bool is_toggle_checked = args->GetList()[0].GetBool(); - if (!is_toggle_checked) { - unified_consent::metrics::RecordUnifiedConsentRevoked( - unified_consent::metrics::UnifiedConsentRevokeReason:: - kUserDisabledSettingsToggle); - } -} - void PeopleHandler::CloseSyncSetup() { // Stop a timer to handle timeout in waiting for checking network connection. engine_start_timer_.reset(); @@ -860,9 +841,10 @@ void PeopleHandler::CloseSyncSetup() { // Don't log a cancel event if the sync setup dialog is being // automatically closed due to an auth error. if ((service->current_login_ui() == this) && - (!sync_service || (!sync_service->IsFirstSetupComplete() && - sync_service->GetAuthError().state() == - GoogleServiceAuthError::NONE))) { + (!sync_service || + (!sync_service->GetUserSettings()->IsFirstSetupComplete() && + sync_service->GetAuthError().state() == + GoogleServiceAuthError::NONE))) { if (configuring_sync_) { ProfileSyncService::SyncEvent( ProfileSyncService::CANCEL_DURING_CONFIGURE); @@ -924,13 +906,13 @@ void PeopleHandler::CloseUI() { FireWebUIListener("page-status-changed", base::Value(kDonePageStatus)); } -void PeopleHandler::GoogleSigninSucceeded(const std::string& /* account_id */, - const std::string& /* username */) { +void PeopleHandler::OnPrimaryAccountSet( + const AccountInfo& primary_account_info) { UpdateSyncStatus(); } -void PeopleHandler::GoogleSignedOut(const std::string& /* account_id */, - const std::string& /* username */) { +void PeopleHandler::OnPrimaryAccountCleared( + const AccountInfo& previous_primary_account_info) { UpdateSyncStatus(); } @@ -957,6 +939,10 @@ PeopleHandler::GetSyncStatusDictionary() { SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile_); DCHECK(signin); + + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile_); + DCHECK(identity_manager); + #if !defined(OS_CHROMEOS) // Signout is not allowed if the user has policy (crbug.com/172204). if (!signin_util::IsUserSignoutAllowedForProfile(profile_)) { @@ -992,18 +978,18 @@ PeopleHandler::GetSyncStatusDictionary() { &link_label, &action_type) == sync_ui_util::SYNC_ERROR; sync_status->SetString("statusText", status_label); + sync_status->SetString("statusActionText", link_label); sync_status->SetBoolean("hasError", status_has_error); sync_status->SetString("statusAction", GetSyncErrorAction(action_type)); sync_status->SetBoolean("managed", disallowed_by_policy); sync_status->SetBoolean( - "disabled", - !service || disallowed_by_policy || - service->HasDisableReason( - syncer::SyncService::DISABLE_REASON_PLATFORM_OVERRIDE)); + "disabled", !service || disallowed_by_policy || + !service->GetUserSettings()->IsSyncAllowedByPlatform()); sync_status->SetBoolean("signedIn", signin->IsAuthenticated()); - sync_status->SetString("signedInUsername", - signin_ui_util::GetAuthenticatedUsername(signin)); + sync_status->SetString( + "signedInUsername", + signin_ui_util::GetAuthenticatedUsername(identity_manager)); sync_status->SetBoolean("hasUnrecoverableError", service && service->HasUnrecoverableError()); return sync_status; @@ -1055,28 +1041,32 @@ void PeopleHandler::PushSyncPrefs() { // TODO(treib): How do we want to handle pref groups, i.e. when only some of // the sync types behind a checkbox are force-enabled? crbug.com/403326 } - PrefService* pref_service = profile_->GetPrefs(); - syncer::SyncPrefs sync_prefs(pref_service); - args.SetBoolean("syncAllDataTypes", sync_prefs.HasKeepEverythingSynced()); - args.SetBoolean("paymentsIntegrationEnabled", - autofill::prefs::IsPaymentsIntegrationEnabled(pref_service)); - args.SetBoolean("encryptAllData", service->IsEncryptEverythingEnabled()); + args.SetBoolean("syncAllDataTypes", + service->GetUserSettings()->IsSyncEverythingEnabled()); + args.SetBoolean( + "paymentsIntegrationEnabled", + autofill::prefs::IsPaymentsIntegrationEnabled(profile_->GetPrefs())); + args.SetBoolean("encryptAllData", + service->GetUserSettings()->IsEncryptEverythingEnabled()); args.SetBoolean("encryptAllDataAllowed", - service->IsEncryptEverythingAllowed()); + service->GetUserSettings()->IsEncryptEverythingAllowed()); // We call IsPassphraseRequired() here, instead of calling // IsPassphraseRequiredForDecryption(), because we want to show the passphrase // UI even if no encrypted data types are enabled. - args.SetBoolean("passphraseRequired", service->IsPassphraseRequired()); + args.SetBoolean("passphraseRequired", + service->GetUserSettings()->IsPassphraseRequired()); // To distinguish between PassphraseType::FROZEN_IMPLICIT_PASSPHRASE and // PassphraseType::CUSTOM_PASSPHRASE // we only set passphraseTypeIsCustom for PassphraseType::CUSTOM_PASSPHRASE. args.SetBoolean("passphraseTypeIsCustom", - service->GetPassphraseType() == + service->GetUserSettings()->GetPassphraseType() == syncer::PassphraseType::CUSTOM_PASSPHRASE); - base::Time passphrase_time = service->GetExplicitPassphraseTime(); - syncer::PassphraseType passphrase_type = service->GetPassphraseType(); + base::Time passphrase_time = + service->GetUserSettings()->GetExplicitPassphraseTime(); + syncer::PassphraseType passphrase_type = + service->GetUserSettings()->GetPassphraseType(); if (!passphrase_time.is_null()) { base::string16 passphrase_time_str = base::TimeFormatShortDate(passphrase_time); @@ -1128,7 +1118,7 @@ void PeopleHandler::MarkFirstSetupComplete() { ProfileSyncService* service = GetSyncService(); // The sync service may be nullptr if it has been just disabled by policy. - if (!service || service->IsFirstSetupComplete()) + if (!service || service->GetUserSettings()->IsFirstSetupComplete()) return; // This is the first time configuring sync, so log it. @@ -1138,7 +1128,7 @@ void PeopleHandler::MarkFirstSetupComplete() { // We're done configuring, so notify ProfileSyncService that it is OK to // start syncing. sync_blocker_.reset(); - service->SetFirstSetupComplete(); + service->GetUserSettings()->SetFirstSetupComplete(); FireWebUIListener("sync-settings-saved"); } diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.h b/chromium/chrome/browser/ui/webui/settings/people_handler.h index 6652b50d0a1..6af3d98b7ec 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.h @@ -21,15 +21,14 @@ #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "components/prefs/pref_change_registrar.h" #include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_manager_base.h" #include "components/sync/driver/sync_service_observer.h" +#include "services/identity/public/cpp/identity_manager.h" #if BUILDFLAG(ENABLE_DICE_SUPPORT) #include "components/signin/core/browser/account_tracker_service.h" #endif class LoginUIService; -class SigninManagerBase; namespace browser_sync { class ProfileSyncService; @@ -50,7 +49,7 @@ class SyncSetupInProgressHandle; namespace settings { class PeopleHandler : public SettingsPageUIHandler, - public SigninManagerBase::Observer, + public identity::IdentityManager::Observer, public SyncStartupTracker::Observer, #if BUILDFLAG(ENABLE_DICE_SUPPORT) public AccountTrackerService::Observer, @@ -136,11 +135,10 @@ class PeopleHandler : public SettingsPageUIHandler, // LoginUIService::LoginUI implementation. void FocusUI() 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; + // IdentityManager::Observer implementation. + void OnPrimaryAccountSet(const AccountInfo& primary_account_info) override; + void OnPrimaryAccountCleared( + const AccountInfo& previous_primary_account_info) override; // syncer::SyncServiceObserver implementation. void OnStateChanged(syncer::SyncService* sync) override; @@ -180,8 +178,6 @@ class PeopleHandler : public SettingsPageUIHandler, void HandlePauseSync(const base::ListValue* args); #endif void HandleGetSyncStatus(const base::ListValue* args); - void HandleManageOtherPeople(const base::ListValue* args); - void OnUnifiedConsentToggleChanged(const base::ListValue* args); #if !defined(OS_CHROMEOS) // Displays the GAIA login form. @@ -258,7 +254,8 @@ class PeopleHandler : public SettingsPageUIHandler, PrefChangeRegistrar profile_pref_registrar_; // Manages observer lifetimes. - ScopedObserver<SigninManagerBase, PeopleHandler> signin_observer_; + ScopedObserver<identity::IdentityManager, PeopleHandler> + identity_manager_observer_; ScopedObserver<browser_sync::ProfileSyncService, PeopleHandler> sync_service_observer_; 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 02cc8300a10..f8566400196 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc @@ -15,12 +15,10 @@ #include "base/stl_util.h" #include "base/values.h" #include "build/build_config.h" -#include "chrome/browser/signin/account_tracker_service_factory.h" -#include "chrome/browser/signin/fake_signin_manager_builder.h" +#include "chrome/browser/signin/identity_test_environment_profile_adaptor.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/scoped_account_consistency.h" #include "chrome/browser/signin/signin_error_controller_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_test_util.h" #include "chrome/browser/ui/chrome_pages.h" @@ -35,8 +33,6 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/fake_auth_status_provider.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_manager.h" #include "components/sync/base/sync_prefs.h" @@ -50,6 +46,8 @@ #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "content/public/test/web_contents_tester.h" +#include "google_apis/gaia/oauth2_token_service_delegate.h" +#include "services/identity/public/cpp/identity_manager.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/layout.h" @@ -113,7 +111,6 @@ 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); @@ -161,7 +158,6 @@ 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 @@ -206,10 +202,12 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { error_ = GoogleServiceAuthError::AuthErrorNone(); // Sign in the user. - mock_signin_ = SigninManagerFactory::GetForProfile(profile()); + identity_test_env_adaptor_ = + std::make_unique<IdentityTestEnvironmentProfileAdaptor>(profile()); + std::string username = GetTestUser(); if (!username.empty()) - mock_signin_->SetAuthenticatedAccountInfo(username, username); + identity_test_env()->SetPrimaryAccount(username); mock_pss_ = static_cast<ProfileSyncServiceMock*>( ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse( @@ -236,9 +234,18 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { handler_->set_web_ui(nullptr); handler_->DisallowJavascript(); handler_->sync_startup_tracker_.reset(); + identity_test_env_adaptor_.reset(); ChromeRenderViewHostTestHarness::TearDown(); } + content::BrowserContext* CreateBrowserContext() override { + // Setup the profile. + std::unique_ptr<TestingProfile> profile = + IdentityTestEnvironmentProfileAdaptor:: + CreateProfileForIdentityTestEnvironment(); + return profile.release(); + } + // Setup the expectations for calls made when displaying the config page. void SetDefaultExpectationsForConfigPage() { ON_CALL(*mock_pss_, GetDisableReasons()) @@ -258,7 +265,6 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { void SetupInitializedProfileSyncService() { // An initialized ProfileSyncService will have already completed sync setup // and will have an initialized sync engine. - ASSERT_TRUE(mock_signin_->IsInitialized()); ON_CALL(*mock_pss_, GetTransportState()) .WillByDefault(Return(syncer::SyncService::TransportState::ACTIVE)); } @@ -325,9 +331,14 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { return std::string(kTestUser); } + identity::IdentityTestEnvironment* identity_test_env() { + return identity_test_env_adaptor_->identity_test_env(); + } + ProfileSyncServiceMock* mock_pss_; GoogleServiceAuthError error_; - SigninManagerBase* mock_signin_; + std::unique_ptr<IdentityTestEnvironmentProfileAdaptor> + identity_test_env_adaptor_; content::TestWebUI web_ui_; TestWebUIProvider test_provider_; std::unique_ptr<TestChromeWebUIControllerFactory> test_factory_; @@ -347,9 +358,7 @@ TEST_F(PeopleHandlerFirstSigninTest, DisplayBasicLogin) { .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN)); ON_CALL(*mock_pss_, IsFirstSetupComplete()).WillByDefault(Return(false)); // Ensure that the user is not signed in before calling |HandleStartSignin()|. - SigninManager* manager = SigninManager::FromSigninManagerBase(mock_signin_); - manager->SignOut(signin_metrics::SIGNOUT_TEST, - signin_metrics::SignoutDelete::IGNORE_METRIC); + identity_test_env()->ClearPrimaryAccount(); base::ListValue list_args; handler_->HandleStartSignin(&list_args); @@ -696,9 +705,7 @@ TEST_F(PeopleHandlerTest, SetNewCustomPassphrase) { ON_CALL(*mock_pss_, IsUsingSecondaryPassphrase()) .WillByDefault(Return(false)); SetupInitializedProfileSyncService(); - EXPECT_CALL(*mock_pss_, - SetEncryptionPassphrase("custom_passphrase", - ProfileSyncService::EXPLICIT)); + EXPECT_CALL(*mock_pss_, SetEncryptionPassphrase("custom_passphrase")); handler_->HandleSetEncryption(&list_args); ExpectPageStatusResponse(PeopleHandler::kConfigurePageStatus); @@ -820,10 +827,20 @@ TEST_F(PeopleHandlerTest, ShowSigninOnAuthError) { GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); SetupInitializedProfileSyncService(); - mock_signin_->SetAuthenticatedAccountInfo(kTestUser, kTestUser); - FakeAuthStatusProvider provider( - SigninErrorControllerFactory::GetForProfile(profile())); - provider.SetAuthError(kTestUser, error_); + DCHECK_EQ( + identity_test_env()->identity_manager()->GetPrimaryAccountInfo().email, + kTestUser); + const std::string& account_id = identity_test_env() + ->identity_manager() + ->GetPrimaryAccountInfo() + .account_id; + ProfileOAuth2TokenService* token_service = + ProfileOAuth2TokenServiceFactory::GetForProfile(profile()); + token_service->UpdateCredentials(account_id, "refresh_token"); + // TODO(https://crbug.com/836212): Do not use the delegate directly, because + // it is internal API. + token_service->GetDelegate()->UpdateAuthError(account_id, error_); + ON_CALL(*mock_pss_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); ON_CALL(*mock_pss_, IsPassphraseRequired()).WillByDefault(Return(false)); @@ -876,7 +893,6 @@ 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); @@ -1022,28 +1038,26 @@ TEST_P(PeopleHandlerDiceUnifiedConsentTest, StoredAccountsList) { std::tie(dice_enabled, unified_consent_enabled) = GetParam(); unified_consent::ScopedUnifiedConsent unified_consent( unified_consent_enabled - ? unified_consent::UnifiedConsentFeatureState::kEnabledWithBump + ? unified_consent::UnifiedConsentFeatureState::kEnabled : unified_consent::UnifiedConsentFeatureState::kDisabled); ScopedAccountConsistency dice( dice_enabled ? signin::AccountConsistencyMethod::kDice : signin::AccountConsistencyMethod::kDiceFixAuthErrors); // Setup the profile. - TestingProfile profile; - AccountTrackerService* account_tracker = - AccountTrackerServiceFactory::GetForProfile(&profile); - SigninManager* signin_manager = SigninManagerFactory::GetForProfile(&profile); - ProfileOAuth2TokenService* token_service = - ProfileOAuth2TokenServiceFactory::GetForProfile(&profile); - std::string account_1 = - account_tracker->SeedAccountInfo("1234", "a@gmail.com"); - std::string account_2 = - account_tracker->SeedAccountInfo("5678", "b@gmail.com"); - token_service->UpdateCredentials(account_1, "token"); - token_service->UpdateCredentials(account_2, "token"); - signin_manager->SetAuthenticatedAccountInfo("1234", "a@gmail.com"); - - PeopleHandler handler(&profile); + std::unique_ptr<TestingProfile> profile = + IdentityTestEnvironmentProfileAdaptor:: + CreateProfileForIdentityTestEnvironment(); + + auto identity_test_env_adaptor = + std::make_unique<IdentityTestEnvironmentProfileAdaptor>(profile.get()); + auto* identity_test_env = identity_test_env_adaptor->identity_test_env(); + + auto account_1 = identity_test_env->MakeAccountAvailable("a@gmail.com"); + auto account_2 = identity_test_env->MakeAccountAvailable("b@gmail.com"); + identity_test_env->SetPrimaryAccount(account_1.email); + + PeopleHandler handler(profile.get()); std::unique_ptr<base::ListValue> accounts_list = handler.GetStoredAccountsList(); diff --git a/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc b/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc deleted file mode 100644 index 56b43446319..00000000000 --- a/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.cc +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/settings/safe_browsing_handler.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/values.h" -#include "components/prefs/pref_service.h" -#include "components/safe_browsing/common/safe_browsing_prefs.h" -#include "content/public/browser/web_ui.h" - -namespace settings { - -namespace { - -base::DictionaryValue GetSberStateDictionaryValue(const PrefService& prefs) { - base::DictionaryValue dict; - dict.SetBoolean("enabled", safe_browsing::IsExtendedReportingEnabled(prefs)); - // TODO(crbug.com/813107): SBEROIA policy is being deprecated, revisit this - // after it is removed. - dict.SetBoolean("managed", - !safe_browsing::IsExtendedReportingOptInAllowed(prefs) || - safe_browsing::IsExtendedReportingPolicyManaged(prefs)); - return dict; -} - -} // namespace - -SafeBrowsingHandler::SafeBrowsingHandler(PrefService* prefs) : prefs_(prefs) {} -SafeBrowsingHandler::~SafeBrowsingHandler() {} - -void SafeBrowsingHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "getSafeBrowsingExtendedReporting", - base::BindRepeating( - &SafeBrowsingHandler::HandleGetSafeBrowsingExtendedReporting, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "setSafeBrowsingExtendedReportingEnabled", - base::BindRepeating( - &SafeBrowsingHandler::HandleSetSafeBrowsingExtendedReportingEnabled, - base::Unretained(this))); -} - -void SafeBrowsingHandler::OnJavascriptAllowed() { - profile_pref_registrar_.Init(prefs_); - profile_pref_registrar_.Add( - prefs::kSafeBrowsingScoutReportingEnabled, - base::Bind(&SafeBrowsingHandler::OnPrefChanged, base::Unretained(this))); -} - -void SafeBrowsingHandler::OnJavascriptDisallowed() { - profile_pref_registrar_.RemoveAll(); -} - -void SafeBrowsingHandler::HandleGetSafeBrowsingExtendedReporting( - const base::ListValue* args) { - AllowJavascript(); - const base::Value* callback_id; - CHECK(args->Get(0, &callback_id)); - - ResolveJavascriptCallback(*callback_id, GetSberStateDictionaryValue(*prefs_)); -} - -void SafeBrowsingHandler::HandleSetSafeBrowsingExtendedReportingEnabled( - const base::ListValue* args) { - bool enabled; - CHECK(args->GetBoolean(0, &enabled)); - safe_browsing::SetExtendedReportingPrefAndMetric( - prefs_, enabled, safe_browsing::SBER_OPTIN_SITE_CHROME_SETTINGS); -} - -void SafeBrowsingHandler::OnPrefChanged(const std::string& pref_name) { - DCHECK(pref_name == prefs::kSafeBrowsingScoutReportingEnabled); - - FireWebUIListener("safe-browsing-extended-reporting-change", - GetSberStateDictionaryValue(*prefs_)); -} - -} // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.h b/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.h deleted file mode 100644 index 45d3bd21df2..00000000000 --- a/chromium/chrome/browser/ui/webui/settings/safe_browsing_handler.h +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_SAFE_BROWSING_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_SETTINGS_SAFE_BROWSING_HANDLER_H_ - -#include <string> - -#include "base/macros.h" -#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" -#include "components/prefs/pref_change_registrar.h" - -namespace settings { - -class SafeBrowsingHandler : public SettingsPageUIHandler { - public: - explicit SafeBrowsingHandler(PrefService* prefs); - ~SafeBrowsingHandler() override; - - // SettingsPageUIHandler: - void RegisterMessages() override; - void OnJavascriptAllowed() override; - void OnJavascriptDisallowed() override; - - private: - // Handler for "getSafeBrowsingExtendedReporting" message. Passed a single - // callback ID argument. - void HandleGetSafeBrowsingExtendedReporting(const base::ListValue* args); - - // Handler for "setSafeBrowsingExtendedReportingEnabled" message. Passed a - // single |enabled| boolean argument. - void HandleSetSafeBrowsingExtendedReportingEnabled( - const base::ListValue* args); - - // Called when the local state pref controlling Safe Browsing extended - // reporting changes. - void OnPrefChanged(const std::string& pref_name); - - // Used to track pref changes that affect whether Safe Browsing extended - // reporting is enabled. - PrefChangeRegistrar profile_pref_registrar_; - - // Weak pointer. - PrefService* prefs_; - - DISALLOW_COPY_AND_ASSIGN(SafeBrowsingHandler); -}; - -} // namespace settings - -#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_SAFE_BROWSING_HANDLER_H_ 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 88ecd47d81d..39487b81589 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 @@ -351,7 +351,8 @@ void ClearBrowsingDataHandler::UpdateSyncState() { base::Value(sync_service_ && sync_service_->IsSyncFeatureActive() && sync_service_->GetActiveDataTypes().Has( syncer::HISTORY_DELETE_DIRECTIVES)), - base::Value(ShouldShowCookieException(profile_))); + base::Value( + browsing_data_counter_utils::ShouldShowCookieException(profile_))); } void ClearBrowsingDataHandler::RefreshHistoryNotice() { @@ -391,7 +392,8 @@ void ClearBrowsingDataHandler::UpdateCounterText( CallJavascriptFunction( "cr.webUIListenerCallback", base::Value("update-counter-text"), base::Value(result->source()->GetPrefName()), - base::Value(GetChromeCounterTextFromResult(result.get(), profile_))); + base::Value(browsing_data_counter_utils::GetChromeCounterTextFromResult( + result.get(), profile_))); } void ClearBrowsingDataHandler::HandleTimePeriodChanged( 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 721518a1f17..71096cd9445 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 @@ -30,7 +30,7 @@ #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/signin/core/browser/profile_management_switches.h" +#include "components/signin/core/browser/account_consistency_method.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_ui.h" diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc index 76a7f5baab6..bf646ef3d11 100644 --- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc @@ -38,6 +38,7 @@ #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/browser/website_settings_registry.h" #include "components/content_settings/core/common/content_settings_types.h" #include "components/content_settings/core/common/content_settings_utils.h" #include "components/crx_file/id_util.h" @@ -47,6 +48,7 @@ #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" +#include "content/public/common/origin_util.h" #include "content/public/common/page_zoom.h" #include "content/public/common/url_constants.h" #include "extensions/browser/extension_registry.h" @@ -65,6 +67,10 @@ namespace settings { namespace { +// Keys of the dictionary returned by HandleIsPatternValidForType. +constexpr char kIsValidKey[] = "isValid"; +constexpr char kReasonKey[] = "reason"; + constexpr char kEffectiveTopLevelDomainPlus1Name[] = "etldPlus1"; constexpr char kOriginList[] = "origins"; constexpr char kNumCookies[] = "numCookies"; @@ -182,6 +188,40 @@ void ConvertSiteGroupMapToListValue( } } +bool IsPatternValidForType(const std::string& pattern_string, + const std::string& type, + Profile* profile, + std::string* out_error) { + ContentSettingsType content_type = + site_settings::ContentSettingsTypeFromGroupName(type); + + ContentSettingsPattern pattern = + ContentSettingsPattern::FromString(pattern_string); + + HostContentSettingsMap* map = + HostContentSettingsMapFactory::GetForProfile(profile); + + // Don't allow an input of '*', even though it's a valid pattern. This + // changes the default setting. + if (!pattern.IsValid() || pattern == ContentSettingsPattern::Wildcard()) { + *out_error = l10n_util::GetStringUTF8(IDS_SETTINGS_NOT_VALID_WEB_ADDRESS); + return false; + } + + // Check if a setting can be set for this url and setting type, and if not, + // return false with a string saying why. + GURL url(pattern_string); + if (url.is_valid() && map->IsRestrictedToSecureOrigins(content_type) && + !content::IsOriginSecure(url)) { + *out_error = l10n_util::GetStringUTF8( + IDS_SETTINGS_NOT_VALID_WEB_ADDRESS_FOR_CONTENT_TYPE); + return false; + } + + // The pattern is valid. + return true; +} + } // namespace SiteSettingsHandler::SiteSettingsHandler(Profile* profile) @@ -258,8 +298,8 @@ void SiteSettingsHandler::RegisterMessages() { base::BindRepeating(&SiteSettingsHandler::HandleIsOriginValid, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "isPatternValid", - base::BindRepeating(&SiteSettingsHandler::HandleIsPatternValid, + "isPatternValidForType", + base::BindRepeating(&SiteSettingsHandler::HandleIsPatternValidForType, base::Unretained(this))); web_ui()->RegisterMessageCallback( "updateIncognitoStatus", @@ -1001,25 +1041,25 @@ void SiteSettingsHandler::HandleIsOriginValid(const base::ListValue* args) { base::Value(GURL(origin_string).is_valid())); } -void SiteSettingsHandler::HandleIsPatternValid( +void SiteSettingsHandler::HandleIsPatternValidForType( const base::ListValue* args) { AllowJavascript(); - CHECK_EQ(2U, args->GetSize()); + CHECK_EQ(3U, args->GetSize()); const base::Value* callback_id; CHECK(args->Get(0, &callback_id)); std::string pattern_string; CHECK(args->GetString(1, &pattern_string)); + std::string type; + CHECK(args->GetString(2, &type)); - ContentSettingsPattern pattern = - ContentSettingsPattern::FromString(pattern_string); - bool valid = pattern.IsValid(); - - // If the input is just '*' don't allow it, even though it's a valid pattern. - // This changes the default setting. - if (pattern == ContentSettingsPattern::Wildcard()) - valid = false; + std::string reason = ""; + bool is_valid = + IsPatternValidForType(pattern_string, type, profile_, &reason); - ResolveJavascriptCallback(*callback_id, base::Value(valid)); + base::Value return_value(base::Value::Type::DICTIONARY); + return_value.SetKey(kIsValidKey, base::Value(is_valid)); + return_value.SetKey(kReasonKey, base::Value(std::move(reason))); + ResolveJavascriptCallback(*callback_id, return_value); } void SiteSettingsHandler::HandleUpdateIncognitoStatus( 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 7a5f9c9b787..902f8fc7b11 100644 --- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h @@ -87,6 +87,7 @@ class SiteSettingsHandler : public SettingsPageUIHandler, FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAllSitesLocalStorage); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Origins); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Patterns); + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, PatternsAndContentType); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ZoomLevels); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerInfobarTest, SettingPermissionsTriggersInfobar); @@ -146,8 +147,8 @@ class SiteSettingsHandler : public SettingsPageUIHandler, // Returns whether a given string is a valid origin. void HandleIsOriginValid(const base::ListValue* args); - // Returns whether a given pattern is valid. - void HandleIsPatternValid(const base::ListValue* args); + // Returns whether the pattern is valid given the type. + void HandleIsPatternValidForType(const base::ListValue* args); // Looks up whether an incognito session is active. void HandleUpdateIncognitoStatus(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 301b05f54d6..577253bd64f 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 @@ -54,6 +54,23 @@ constexpr char kSetting[] = "setting"; constexpr char kSource[] = "source"; constexpr char kExtensionName[] = "Test Extension"; +const struct PatternContentTypeTestCase { + struct { + const char* const pattern; + const char* const content_type; + } arguments; + struct { + const bool validity; + const char* const reason; + } expected; +} kPatternsAndContentTypeTestCases[]{ + {{"https://google.com", "cookies"}, {true, ""}}, + {{";", "cookies"}, {false, "Not a valid web address"}}, + {{"*", "cookies"}, {false, "Not a valid web address"}}, + {{"http://google.com", "location"}, {false, "Origin must be secure"}}, + {{"http://127.0.0.1", "location"}, {true, ""}}, // Localhost is secure. + {{"http://[::1]", "location"}, {true, ""}}}; + #if BUILDFLAG(ENABLE_PLUGINS) // Waits until a change is observed in content settings. class FlashContentSettingsChangeWaiter : public content_settings::Observer { @@ -270,7 +287,9 @@ class SiteSettingsHandlerTest : public testing::Test { EXPECT_EQ(0U, exceptions->GetSize()); } - void ValidatePattern(bool expected_validity, size_t expected_total_calls) { + void ValidatePattern(bool expected_validity, + size_t expected_total_calls, + std::string expected_reason) { EXPECT_EQ(expected_total_calls, web_ui()->call_data().size()); const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); @@ -284,9 +303,16 @@ class SiteSettingsHandlerTest : public testing::Test { ASSERT_TRUE(data.arg2()->GetAsBoolean(&success)); ASSERT_TRUE(success); - bool valid; - ASSERT_TRUE(data.arg3()->GetAsBoolean(&valid)); + const base::DictionaryValue* result = nullptr; + ASSERT_TRUE(data.arg3()->GetAsDictionary(&result)); + + bool valid = false; + ASSERT_TRUE(result->GetBoolean("isValid", &valid)); EXPECT_EQ(expected_validity, valid); + + std::string reason; + ASSERT_TRUE(result->GetString("reason", &reason)); + EXPECT_EQ(expected_reason, reason); } void ValidateIncognitoExists( @@ -973,30 +999,18 @@ TEST_F(SiteSettingsHandlerTest, ExtensionDisplayName) { site_settings::SiteSettingSource::kDefault, 1U); } -TEST_F(SiteSettingsHandlerTest, Patterns) { - base::ListValue args; - std::string pattern("[*.]google.com"); - args.AppendString(kCallbackId); - args.AppendString(pattern); - handler()->HandleIsPatternValid(&args); - ValidatePattern(true, 1U); - - base::ListValue invalid; - std::string bad_pattern(";"); - invalid.AppendString(kCallbackId); - invalid.AppendString(bad_pattern); - handler()->HandleIsPatternValid(&invalid); - ValidatePattern(false, 2U); - - // The wildcard pattern ('*') is a valid pattern, but not allowed to be - // entered in site settings as it changes the default setting. - // (crbug.com/709539). - base::ListValue invalid_wildcard; - std::string bad_pattern_wildcard("*"); - invalid_wildcard.AppendString(kCallbackId); - invalid_wildcard.AppendString(bad_pattern_wildcard); - handler()->HandleIsPatternValid(&invalid_wildcard); - ValidatePattern(false, 3U); +TEST_F(SiteSettingsHandlerTest, PatternsAndContentType) { + unsigned counter = 1; + for (const auto& test_case : kPatternsAndContentTypeTestCases) { + base::ListValue args; + args.AppendString(kCallbackId); + args.AppendString(test_case.arguments.pattern); + args.AppendString(test_case.arguments.content_type); + handler()->HandleIsPatternValidForType(&args); + ValidatePattern(test_case.expected.validity, counter, + test_case.expected.reason); + ++counter; + } } TEST_F(SiteSettingsHandlerTest, Incognito) { diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc index 4a02d3dc710..9ac54fa35a3 100644 --- a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc @@ -11,10 +11,9 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_observer.h" -#include "chrome/browser/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/tts_controller.h" #include "content/public/browser/web_ui.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_registry.h" @@ -28,7 +27,7 @@ namespace settings { TtsHandler::TtsHandler() : weak_factory_(this) {} TtsHandler::~TtsHandler() { - TtsController::GetInstance()->RemoveVoicesChangedDelegate(this); + content::TtsController::GetInstance()->RemoveVoicesChangedDelegate(this); } void TtsHandler::HandleGetAllTtsVoiceData(const base::ListValue* args) { @@ -53,7 +52,7 @@ void TtsHandler::HandleGetTtsExtensions(const base::ListValue* args) { registry->GetInstalledExtension(extension_id); if (!extension) { // The extension is still loading from OnVoicesChange call to - // TtsControllerImpl::GetVoices(). Don't do any work, voices will + // TtsController::GetVoices(). Don't do any work, voices will // be updated again after extension load. continue; } @@ -73,9 +72,10 @@ void TtsHandler::HandleGetTtsExtensions(const base::ListValue* args) { } void TtsHandler::OnVoicesChanged() { - TtsControllerImpl* impl = TtsControllerImpl::GetInstance(); - std::vector<VoiceData> voices; - impl->GetVoices(Profile::FromWebUI(web_ui()), &voices); + content::TtsController* tts_controller = + content::TtsController::GetInstance(); + std::vector<content::VoiceData> voices; + tts_controller->GetVoices(Profile::FromWebUI(web_ui()), &voices); const std::string& app_locale = g_browser_process->GetApplicationLocale(); base::ListValue responses; for (const auto& voice : voices) { @@ -125,14 +125,15 @@ void TtsHandler::HandlePreviewTtsVoice(const base::ListValue* args) { json->GetString("name", &name); json->GetString("extension", &extension_id); - Utterance* utterance = new Utterance(Profile::FromWebUI(web_ui())); + content::Utterance* utterance = + new content::Utterance(Profile::FromWebUI(web_ui())); utterance->set_text(text); utterance->set_voice_name(name); utterance->set_extension_id(extension_id); utterance->set_src_url(GURL("chrome://settings/manageAccessibility/tts")); utterance->set_event_delegate(nullptr); - TtsController::GetInstance()->Stop(); - TtsController::GetInstance()->SpeakOrEnqueue(utterance); + content::TtsController::GetInstance()->Stop(); + content::TtsController::GetInstance()->SpeakOrEnqueue(utterance); } void TtsHandler::RegisterMessages() { @@ -153,14 +154,14 @@ void TtsHandler::RegisterMessages() { } void TtsHandler::OnJavascriptAllowed() { - TtsController::GetInstance()->AddVoicesChangedDelegate(this); + content::TtsController::GetInstance()->AddVoicesChangedDelegate(this); } void TtsHandler::OnJavascriptDisallowed() { - TtsController::GetInstance()->RemoveVoicesChangedDelegate(this); + content::TtsController::GetInstance()->RemoveVoicesChangedDelegate(this); } -int TtsHandler::GetVoiceLangMatchScore(const VoiceData* voice, +int TtsHandler::GetVoiceLangMatchScore(const content::VoiceData* voice, const std::string& app_locale) { if (voice->lang.empty() || app_locale.empty()) return 0; @@ -176,7 +177,7 @@ void TtsHandler::WakeTtsEngine(const base::ListValue* args) { Profile* profile = Profile::FromWebUI(web_ui()); TtsExtensionEngine::GetInstance()->LoadBuiltInTtsExtension(profile); extensions::ProcessManager::Get(profile)->WakeEventPage( - extension_misc::kSpeechSynthesisExtensionId, + extension_misc::kGoogleSpeechSynthesisExtensionId, base::BindOnce(&TtsHandler::OnTtsEngineAwake, weak_factory_.GetWeakPtr())); } diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.h b/chromium/chrome/browser/ui/webui/settings/tts_handler.h index 0f9d26426d8..3263578a4b8 100644 --- a/chromium/chrome/browser/ui/webui/settings/tts_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.h @@ -6,15 +6,16 @@ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_TTS_HANDLER_H_ #include "base/memory/weak_ptr.h" -#include "chrome/browser/speech/tts_controller.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "content/public/browser/tts_controller.h" class Profile; namespace settings { // Chrome "/manageAccessibility/tts/*" settings page UI handler. -class TtsHandler : public SettingsPageUIHandler, public VoicesChangedDelegate { +class TtsHandler : public SettingsPageUIHandler, + public content::VoicesChangedDelegate { public: TtsHandler(); ~TtsHandler() override; @@ -34,7 +35,7 @@ class TtsHandler : public SettingsPageUIHandler, public VoicesChangedDelegate { private: void WakeTtsEngine(const base::ListValue* args); void OnTtsEngineAwake(bool success); - int GetVoiceLangMatchScore(const VoiceData* voice, + int GetVoiceLangMatchScore(const content::VoiceData* voice, const std::string& app_locale); base::WeakPtrFactory<TtsHandler> weak_factory_; diff --git a/chromium/chrome/browser/ui/webui/settings_utils_win.cc b/chromium/chrome/browser/ui/webui/settings_utils_win.cc index 5261c2dfe55..8c583fe33c5 100644 --- a/chromium/chrome/browser/ui/webui/settings_utils_win.cc +++ b/chromium/chrome/browser/ui/webui/settings_utils_win.cc @@ -41,26 +41,29 @@ class ManageCertificatesDialog : public ui::BaseShellDialogImpl { return; } - RunState run_state = BeginRun(parent); - run_state.dialog_task_runner->PostTaskAndReply( + std::unique_ptr<RunState> run_state = BeginRun(parent); + + base::SingleThreadTaskRunner* task_runner = + run_state->dialog_task_runner.get(); + task_runner->PostTaskAndReply( FROM_HERE, - base::Bind(&ManageCertificatesDialog::ShowOnDialogThread, - base::Unretained(this), run_state), - base::Bind(&ManageCertificatesDialog::OnDialogClosed, - base::Unretained(this), run_state, callback)); + base::BindOnce(&ManageCertificatesDialog::ShowOnDialogThread, + base::Unretained(this), parent), + base::BindOnce(&ManageCertificatesDialog::OnDialogClosed, + base::Unretained(this), std::move(run_state), callback)); } private: - void ShowOnDialogThread(const RunState& run_state) { + void ShowOnDialogThread(HWND owner) { CRYPTUI_CERT_MGR_STRUCT cert_mgr = {0}; cert_mgr.dwSize = sizeof(CRYPTUI_CERT_MGR_STRUCT); - cert_mgr.hwndParent = run_state.owner; + cert_mgr.hwndParent = owner; ::CryptUIDlgCertMgr(&cert_mgr); } - void OnDialogClosed(const RunState& run_state, + void OnDialogClosed(std::unique_ptr<RunState> run_state, const base::Closure& callback) { - EndRun(run_state); + EndRun(std::move(run_state)); // May delete |this|. callback.Run(); } 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 6f8e2de423a..aed13d723e3 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 @@ -29,9 +29,9 @@ #include "components/browser_sync/profile_sync_service.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/prefs/pref_service.h" +#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/account_tracker_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_metrics.h" #include "components/signin/core/browser/signin_pref_names.h" @@ -374,17 +374,21 @@ void DiceTurnSyncOnHelper::ShowSyncConfirmationUI() { void DiceTurnSyncOnHelper::FinishSyncSetupAndDelete( LoginUIService::SyncConfirmationUIClosedResult result) { + unified_consent::UnifiedConsentService* consent_service = + UnifiedConsentServiceFactory::GetForProfile(profile_); + switch (result) { case LoginUIService::CONFIGURE_SYNC_FIRST: - EnableUnifiedConsentIfNeeded(); + if (consent_service) + consent_service->EnableGoogleServices(); delegate_->ShowSyncSettings(); break; case LoginUIService::SYNC_WITH_DEFAULT_SETTINGS: { browser_sync::ProfileSyncService* sync_service = GetProfileSyncService(); - if (sync_service) { - sync_service->SetFirstSetupComplete(); - EnableUnifiedConsentIfNeeded(); - } + if (sync_service) + sync_service->GetUserSettings()->SetFirstSetupComplete(); + if (consent_service) + consent_service->EnableGoogleServices(); break; } case LoginUIService::ABORT_SIGNIN: @@ -401,14 +405,10 @@ void DiceTurnSyncOnHelper::AbortAndDelete() { if (signin_aborted_mode_ == SigninAbortedMode::REMOVE_ACCOUNT) { // Revoke the token, and the AccountReconcilor and/or the Gaia server will // take care of invalidating the cookies. - token_service_->RevokeCredentials(account_info_.account_id); + token_service_->RevokeCredentials( + account_info_.account_id, + signin_metrics::SourceForRefreshTokenOperation:: + kDiceTurnOnSyncHelper_Abort); } delete this; } - -void DiceTurnSyncOnHelper::EnableUnifiedConsentIfNeeded() { - if (unified_consent::IsUnifiedConsentFeatureEnabled()) { - 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 5f706f75bdc..28af6e6555a 100644 --- a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h +++ b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h @@ -186,10 +186,6 @@ 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 0ab30779fd0..23e34792933 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 @@ -20,14 +20,14 @@ #include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h" #include "chrome/browser/signin/fake_signin_manager_builder.h" +#include "chrome/browser/signin/identity_manager_factory.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/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/browser/unified_consent/chrome_unified_consent_service_client.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" @@ -40,15 +40,17 @@ #include "components/signin/core/browser/signin_pref_names.h" #include "components/unified_consent/feature.h" #include "components/unified_consent/scoped_unified_consent.h" -#include "components/unified_consent/unified_consent_service.h" +#include "components/unified_consent/url_keyed_data_collection_consent_helper.h" #include "content/public/test/test_browser_thread_bundle.h" #include "google_apis/gaia/google_service_auth_error.h" +#include "services/identity/public/cpp/identity_manager.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; +using namespace unified_consent; class DiceTurnSyncOnHelperTestBase; @@ -125,20 +127,17 @@ class FakeUserPolicySigninService : public policy::UserPolicySigninService { static std::unique_ptr<KeyedService> Build(content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); return std::make_unique<FakeUserPolicySigninService>( - profile, SigninManagerFactory::GetForProfile(profile), - ProfileOAuth2TokenServiceFactory::GetForProfile(profile)); + profile, IdentityManagerFactory::GetForProfile(profile)); } FakeUserPolicySigninService(Profile* profile, - SigninManager* signin_manager, - ProfileOAuth2TokenService* oauth2_token_service) + identity::IdentityManager* identity_manager) : UserPolicySigninService(profile, nullptr, nullptr, nullptr, - signin_manager, - nullptr, - oauth2_token_service) {} + identity_manager, + nullptr) {} void set_dm_token(const std::string& dm_token) { dm_token_ = dm_token; } void set_client_id(const std::string& client_id) { client_id_ = client_id; } @@ -192,7 +191,7 @@ class DiceTurnSyncOnHelperTestBase : public testing::Test { base::BindRepeating(&BuildFakeProfileOAuth2TokenService)); profile_builder.AddTestingFactory( SigninManagerFactory::GetInstance(), - base::BindRepeating(&BuildFakeSigninManagerBase)); + base::BindRepeating(&BuildFakeSigninManagerForTesting)); profile_builder.AddTestingFactory( ChromeSigninClientFactory::GetInstance(), base::BindRepeating(&signin::BuildTestSigninClient)); @@ -202,9 +201,6 @@ class DiceTurnSyncOnHelperTestBase : public testing::Test { profile_builder.AddTestingFactory( policy::UserPolicySigninServiceFactory::GetInstance(), base::BindRepeating(&FakeUserPolicySigninService::Build)); - profile_builder.AddTestingFactory( - UnifiedConsentServiceFactory::GetInstance(), - base::BindRepeating(&BuildUnifiedConsentServiceForTesting)); profile_ = profile_builder.Build(); account_tracker_service_ = AccountTrackerServiceFactory::GetForProfile(profile()); @@ -418,13 +414,12 @@ class DiceTurnSyncOnHelperTestWithUnifiedConsent : public DiceTurnSyncOnHelperTestBase { public: DiceTurnSyncOnHelperTestWithUnifiedConsent() - : scoped_unified_consent_( - unified_consent::UnifiedConsentFeatureState::kEnabledNoBump) {} + : scoped_unified_consent_(UnifiedConsentFeatureState::kEnabled) {} ~DiceTurnSyncOnHelperTestWithUnifiedConsent() override {} private: ScopedAccountConsistencyDice scoped_dice_; - unified_consent::ScopedUnifiedConsent scoped_unified_consent_; + ScopedUnifiedConsent scoped_unified_consent_; }; // TestDiceTurnSyncOnHelperDelegate implementation. @@ -705,13 +700,31 @@ TEST_F(DiceTurnSyncOnHelperTest, ShowSyncDialogForEndConsumerAccount) { // Tests that the user enabled unified consent, TEST_F(DiceTurnSyncOnHelperTestWithUnifiedConsent, ShowSyncDialogForEndConsumerAccount_UnifiedConsentEnabled) { - ASSERT_TRUE(unified_consent::IsUnifiedConsentFeatureEnabled()); + ASSERT_TRUE(IsUnifiedConsentFeatureEnabled()); // Set expectations. expected_sync_confirmation_shown_ = true; sync_confirmation_result_ = LoginUIService::SyncConfirmationUIClosedResult:: SYNC_WITH_DEFAULT_SETTINGS; SetExpectationsForSyncStartupCompleted(); EXPECT_CALL(*GetProfileSyncServiceMock(), SetFirstSetupComplete()).Times(1); + using Service = UnifiedConsentServiceClient::Service; + using ServiceState = UnifiedConsentServiceClient::ServiceState; + PrefService* pref_service = profile()->GetPrefs(); + ChromeUnifiedConsentServiceClient consent_service_client(pref_service); + std::unique_ptr<UrlKeyedDataCollectionConsentHelper> + url_keyed_collection_helper = UrlKeyedDataCollectionConsentHelper:: + NewAnonymizedDataCollectionConsentHelper( + pref_service, + ProfileSyncServiceFactory::GetForProfile(profile())); + for (int i = 0; i <= static_cast<int>(Service::kLast); ++i) { + Service service = static_cast<Service>(i); + if (consent_service_client.IsServiceSupported(service)) { + consent_service_client.SetServiceEnabled(service, false); + EXPECT_EQ(ServiceState::kDisabled, + consent_service_client.GetServiceState(service)); + } + } + EXPECT_FALSE(url_keyed_collection_helper->IsEnabled()); // Signin flow. EXPECT_FALSE(signin_manager()->IsAuthenticated()); @@ -722,8 +735,14 @@ TEST_F(DiceTurnSyncOnHelperTestWithUnifiedConsent, EXPECT_TRUE(token_service()->RefreshTokenIsAvailable(account_id())); EXPECT_EQ(account_id(), signin_manager()->GetAuthenticatedAccountId()); CheckDelegateCalls(); - EXPECT_TRUE(UnifiedConsentServiceFactory::GetForProfile(profile()) - ->IsUnifiedConsentGiven()); + for (int i = 0; i <= static_cast<int>(Service::kLast); ++i) { + Service service = static_cast<Service>(i); + if (consent_service_client.IsServiceSupported(service)) { + EXPECT_EQ(ServiceState::kEnabled, + consent_service_client.GetServiceState(service)); + } + } + EXPECT_TRUE(url_keyed_collection_helper->IsEnabled()); } // For enterprise user, tests that the user is signed in only after Sync engine 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 6657d8fa3fa..7e04d93e318 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc @@ -83,7 +83,6 @@ void InlineLoginHandler::HandleInitializeMessage(const base::ListValue* args) { content::StoragePartition::REMOVE_DATA_MASK_ALL, content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(), - content::StoragePartition::OriginMatcherFunction(), base::Time(), base::Time::Max(), base::Bind(&InlineLoginHandler::ContinueHandleInitializeMessage, diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc index d729f382c40..6f4050218f1 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc @@ -17,7 +17,6 @@ #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" @@ -45,7 +44,7 @@ class SigninHelper : public GaiaAuthConsumer { close_dialog_closure_(close_dialog_closure), email_(email), gaia_auth_fetcher_(this, - GaiaConstants::kChromeSource, + gaia::GaiaSource::kChrome, url_loader_factory) { account_key_ = chromeos::AccountManager::AccountKey{ gaia_id, chromeos::account_manager::AccountType::ACCOUNT_TYPE_GAIA}; 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 index 035f5a54a7f..d77fc7e62b3 100644 --- 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 @@ -6,17 +6,29 @@ #include <string> +#include "base/logging.h" #include "base/macros.h" #include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" #include "chrome/common/webui_url_constants.h" +#include "ui/aura/window.h" namespace chromeos { +namespace { + +InlineLoginHandlerDialogChromeOS* dialog = nullptr; + +} // namespace + // static void InlineLoginHandlerDialogChromeOS::Show() { + if (dialog) { + dialog->dialog_window()->Focus(); + return; + } + // Will be deleted by |SystemWebDialogDelegate::OnDialogClosed|. - InlineLoginHandlerDialogChromeOS* dialog = - new InlineLoginHandlerDialogChromeOS(); + dialog = new InlineLoginHandlerDialogChromeOS(); dialog->ShowSystemDialog(false /* is_minimal_style */); } @@ -24,7 +36,10 @@ InlineLoginHandlerDialogChromeOS::InlineLoginHandlerDialogChromeOS() : SystemWebDialogDelegate(GURL(chrome::kChromeUIChromeSigninURL), base::string16() /* title */) {} -InlineLoginHandlerDialogChromeOS::~InlineLoginHandlerDialogChromeOS() = default; +InlineLoginHandlerDialogChromeOS::~InlineLoginHandlerDialogChromeOS() { + DCHECK_EQ(this, dialog); + dialog = nullptr; +} std::string InlineLoginHandlerDialogChromeOS::GetDialogArgs() const { return std::string(); 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 index a03b1647d75..0ee3792924f 100644 --- 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 @@ -12,6 +12,9 @@ namespace chromeos { +// Extends from |SystemWebDialogDelegate| to create an always-on-top but movable +// dialog. It is intentionally made movable so that users can copy-paste account +// passwords from password managers. class InlineLoginHandlerDialogChromeOS : public SystemWebDialogDelegate { public: static void Show(); 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 9c3e2817ff1..ed0e79f6473 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 @@ -22,6 +22,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" +#include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/profiles/profile.h" @@ -69,11 +70,16 @@ #include "content/public/browser/web_ui.h" #include "google_apis/gaia/gaia_auth_fetcher.h" #include "google_apis/gaia/gaia_auth_util.h" -#include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/gaia_urls.h" #include "net/base/url_util.h" #include "ui/base/l10n/l10n_util.h" +#if defined(OS_WIN) + +#include "chrome/credential_provider/common/gcp_strings.h" + +#endif // defined(OS_WIN) + namespace { void LogHistogramValue(signin_metrics::AccessPointAction action) { @@ -171,9 +177,7 @@ InlineSigninHelper::InlineSigninHelper( bool choose_what_to_sync, bool confirm_untrusted_signin, bool is_force_sign_in_with_usermanager) - : gaia_auth_fetcher_(this, - GaiaConstants::kChromeSource, - url_loader_factory), + : gaia_auth_fetcher_(this, gaia::GaiaSource::kChrome, url_loader_factory), handler_(handler), profile_(profile), create_status_(create_status), @@ -218,19 +222,41 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( browser = handler_->GetDesktopBrowser(); } + signin_metrics::AccessPoint access_point = + signin::GetAccessPointForPromoURL(current_url_); + signin_metrics::Reason reason = + signin::GetSigninReasonForPromoURL(current_url_); + if (reason == signin_metrics::Reason::REASON_FETCH_LST_ONLY) { +// Constants are only available on Windows for the Google Credential +// Provider for Windows. Other platforms will just close the dialog here. +#if defined(OS_WIN) + std::string json_retval; + base::Value args(base::Value::Type::DICTIONARY); + args.SetKey(credential_provider::kKeyEmail, base::Value(email_)); + args.SetKey(credential_provider::kKeyPassword, base::Value(password_)); + args.SetKey(credential_provider::kKeyId, base::Value(gaia_id_)); + args.SetKey(credential_provider::kKeyRefreshToken, + base::Value(result.refresh_token)); + args.SetKey(credential_provider::kKeyAccessToken, + base::Value(result.access_token)); + + handler_->SendLSTFetchResultsMessage(args); +#else + if (handler_) + handler_->CloseDialogFromJavascript(); +#endif // defined(OS_WIN) + base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); + return; + } + AboutSigninInternals* about_signin_internals = AboutSigninInternalsFactory::GetForProfile(profile_); about_signin_internals->OnRefreshTokenReceived("Successful"); // Prime the account tracker with this combination of gaia id/display email. std::string account_id = - AccountTrackerServiceFactory::GetForProfile(profile_) - ->SeedAccountInfo(gaia_id_, email_); - - signin_metrics::AccessPoint access_point = - signin::GetAccessPointForPromoURL(current_url_); - signin_metrics::Reason reason = - signin::GetSigninReasonForPromoURL(current_url_); + AccountTrackerServiceFactory::GetForProfile(profile_)->SeedAccountInfo( + gaia_id_, email_); SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_); std::string primary_email = @@ -259,8 +285,10 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION || reason == signin_metrics::Reason::REASON_UNLOCK || reason == signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT) { - ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)-> - UpdateCredentials(account_id, result.refresh_token); + ProfileOAuth2TokenServiceFactory::GetForProfile(profile_) + ->UpdateCredentials(account_id, result.refresh_token, + signin_metrics::SourceForRefreshTokenOperation:: + kInlineLoginHandler_Signin); if (signin::IsAutoCloseEnabledInURL(current_url_)) { // Close the gaia sign in tab via a task to make sure we aren't in the @@ -296,9 +324,9 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( } OneClickSigninSyncStarter::ConfirmationRequired confirmation_required = - confirm_untrusted_signin_ ? - OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN : - OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN; + confirm_untrusted_signin_ + ? OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN + : OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN; bool start_signin = !HandleCrossAccountError( result.refresh_token, confirmation_required, start_mode); @@ -393,29 +421,30 @@ void InlineSigninHelper::ConfirmEmailAction( } void InlineSigninHelper::OnClientOAuthFailure( - const GoogleServiceAuthError& error) { + const GoogleServiceAuthError& error) { if (handler_) handler_->HandleLoginError(error.ToString(), base::string16()); - AboutSigninInternals* about_signin_internals = - AboutSigninInternalsFactory::GetForProfile(profile_); - about_signin_internals->OnRefreshTokenReceived("Failure"); + signin_metrics::Reason reason = + signin::GetSigninReasonForPromoURL(current_url_); + if (reason != signin_metrics::Reason::REASON_FETCH_LST_ONLY) { + AboutSigninInternals* about_signin_internals = + AboutSigninInternalsFactory::GetForProfile(profile_); + about_signin_internals->OnRefreshTokenReceived("Failure"); + } base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); } InlineLoginHandlerImpl::InlineLoginHandlerImpl() - : confirm_untrusted_signin_(false), - weak_factory_(this) { -} + : confirm_untrusted_signin_(false), weak_factory_(this) {} InlineLoginHandlerImpl::~InlineLoginHandlerImpl() {} // This method is not called with webview sign in enabled. void InlineLoginHandlerImpl::DidFinishNavigation( content::NavigationHandle* navigation_handle) { - if (!web_contents() || - !navigation_handle->HasCommitted() || + if (!web_contents() || !navigation_handle->HasCommitted() || navigation_handle->IsErrorPage()) { return; } @@ -433,8 +462,7 @@ void InlineLoginHandlerImpl::DidFinishNavigation( if (!navigation_handle->GetURL().is_empty()) { GURL origin(navigation_handle->GetURL().GetOrigin()); if (navigation_handle->GetURL().spec() != url::kAboutBlankURL && - origin != kGaiaExtOrigin && - !gaia::IsGaiaSignonRealm(origin)) { + origin != kGaiaExtOrigin && !gaia::IsGaiaSignonRealm(origin)) { confirm_untrusted_signin_ = true; } } @@ -455,29 +483,40 @@ void InlineLoginHandlerImpl::SetExtraInitParams(base::DictionaryValue& params) { signin_metrics::Reason reason = signin::GetSigninReasonForPromoURL(current_url); - const GURL& url = GaiaUrls::GetInstance()->embedded_signin_url(); - params.SetBoolean("isNewGaiaFlow", true); - params.SetString("clientId", - GaiaUrls::GetInstance()->oauth2_chrome_client_id()); - params.SetString("gaiaPath", url.path().substr(1)); - - std::string flow; - switch (reason) { - case signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT: - flow = "addaccount"; - break; - case signin_metrics::Reason::REASON_REAUTHENTICATION: - case signin_metrics::Reason::REASON_UNLOCK: - flow = "reauth"; - break; - case signin_metrics::Reason::REASON_FORCED_SIGNIN_PRIMARY_ACCOUNT: - flow = "enterprisefsi"; - break; - default: - flow = "signin"; - break; +#if defined(OS_WIN) + if (reason == signin_metrics::Reason::REASON_FETCH_LST_ONLY) { + std::string email_domain; + if (net::GetValueForKeyInQuery( + current_url, credential_provider::kEmailDomainSigninPromoParameter, + &email_domain)) { + params.SetString("emailDomain", email_domain); } - params.SetString("flow", flow); + } +#endif + + const GURL& url = GaiaUrls::GetInstance()->embedded_signin_url(); + params.SetBoolean("isNewGaiaFlow", true); + params.SetString("clientId", + GaiaUrls::GetInstance()->oauth2_chrome_client_id()); + params.SetString("gaiaPath", url.path().substr(1)); + + std::string flow; + switch (reason) { + case signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT: + flow = "addaccount"; + break; + case signin_metrics::Reason::REASON_REAUTHENTICATION: + case signin_metrics::Reason::REASON_UNLOCK: + flow = "reauth"; + break; + case signin_metrics::Reason::REASON_FORCED_SIGNIN_PRIMARY_ACCOUNT: + flow = "enterprisefsi"; + break; + default: + flow = "signin"; + break; + } + params.SetString("flow", flow); content::WebContentsObserver::Observe(contents); LogHistogramValue(signin_metrics::HISTOGRAM_SHOWN); @@ -516,16 +555,18 @@ void InlineLoginHandlerImpl::CompleteLogin(const std::string& email, // the current profile is the system profile. In this case, use the email to // find the right profile to reauthenticate. Otherwise the profile can be // taken from web_ui(). + signin_metrics::Reason reason = + signin::GetSigninReasonForPromoURL(current_url); + Profile* profile = Profile::FromWebUI(web_ui()); - if (IsSystemProfile(profile)) { + if (reason != signin_metrics::Reason::REASON_FETCH_LST_ONLY && + IsSystemProfile(profile)) { ProfileManager* manager = g_browser_process->profile_manager(); base::FilePath path = profiles::GetPathOfProfileWithEmail(manager, email); if (path.empty()) { path = UserManager::GetSigninProfilePath(); } if (!path.empty()) { - signin_metrics::Reason reason = - signin::GetSigninReasonForPromoURL(current_url); // If we are only reauthenticating a profile in the user manager (and not // unlocking it), load the profile and finish the login. if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION) { @@ -595,8 +636,8 @@ InlineLoginHandlerImpl::FinishCompleteLoginParams::FinishCompleteLoginParams( InlineLoginHandlerImpl::FinishCompleteLoginParams::FinishCompleteLoginParams( const FinishCompleteLoginParams& other) = default; -InlineLoginHandlerImpl:: - FinishCompleteLoginParams::~FinishCompleteLoginParams() {} +InlineLoginHandlerImpl::FinishCompleteLoginParams:: + ~FinishCompleteLoginParams() {} // static void InlineLoginHandlerImpl::FinishCompleteLogin( @@ -632,9 +673,9 @@ void InlineLoginHandlerImpl::FinishCompleteLogin( bool switch_to_advanced = params.choose_what_to_sync && (access_point != signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); - LogHistogramValue( - switch_to_advanced ? signin_metrics::HISTOGRAM_WITH_ADVANCED : - signin_metrics::HISTOGRAM_WITH_DEFAULTS); + LogHistogramValue(switch_to_advanced + ? signin_metrics::HISTOGRAM_WITH_ADVANCED + : signin_metrics::HISTOGRAM_WITH_DEFAULTS); CanOfferSigninType can_offer_for = CAN_OFFER_SIGNIN_FOR_ALL_ACCOUNTS; switch (reason) { @@ -657,7 +698,8 @@ void InlineLoginHandlerImpl::FinishCompleteLogin( } std::string error_msg; - bool can_offer = CanOfferSignin(profile, can_offer_for, params.gaia_id, + bool can_offer = reason == signin_metrics::Reason::REASON_FETCH_LST_ONLY || + CanOfferSignin(profile, can_offer_for, params.gaia_id, params.email, &error_msg); if (!can_offer) { if (params.handler) { @@ -669,7 +711,8 @@ void InlineLoginHandlerImpl::FinishCompleteLogin( AboutSigninInternals* about_signin_internals = AboutSigninInternalsFactory::GetForProfile(profile); - about_signin_internals->OnAuthenticationResultReceived("Successful"); + if (about_signin_internals) + about_signin_internals->OnAuthenticationResultReceived("Successful"); std::string signin_scoped_device_id = GetSigninScopedDeviceIdForProfile(profile); @@ -688,13 +731,23 @@ void InlineLoginHandlerImpl::FinishCompleteLogin( // If opened from user manager to unlock a profile, make sure the user manager // is closed and that the profile is marked as unlocked. - if (!params.is_force_sign_in_with_usermanager) { + if (reason != signin_metrics::Reason::REASON_FETCH_LST_ONLY && + !params.is_force_sign_in_with_usermanager) { UnlockProfileAndHideLoginUI(params.profile_path, params.handler); } } void InlineLoginHandlerImpl::HandleLoginError(const std::string& error_msg, const base::string16& email) { + content::WebContents* contents = web_ui()->GetWebContents(); + const GURL& current_url = contents->GetURL(); + signin_metrics::Reason reason = + signin::GetSigninReasonForPromoURL(current_url); + + if (reason == signin_metrics::Reason::REASON_FETCH_LST_ONLY) { + SendLSTFetchResultsMessage(base::Value(base::Value::Type::DICTIONARY)); + return; + } SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE); Browser* browser = GetDesktopBrowser(); Profile* profile = Profile::FromWebUI(web_ui()); @@ -709,9 +762,15 @@ void InlineLoginHandlerImpl::HandleLoginError(const std::string& error_msg, } } +void InlineLoginHandlerImpl::SendLSTFetchResultsMessage( + const base::Value& arg) { + if (IsJavascriptAllowed()) + CallJavascriptFunction("inline.login.sendLSTFetchResults", arg); +} + Browser* InlineLoginHandlerImpl::GetDesktopBrowser() { - Browser* browser = chrome::FindBrowserWithWebContents( - web_ui()->GetWebContents()); + Browser* browser = + chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()); if (!browser) browser = chrome::FindLastActiveWithProfile(Profile::FromWebUI(web_ui())); return browser; 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 8234ded1ed7..d1f29795f30 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 @@ -47,6 +47,13 @@ class InlineLoginHandlerImpl : public InlineLoginHandler, void HandleLoginError(const std::string& error_msg, const base::string16& email); + // Calls the javascript function 'sendLSTFetchResults' with the given + // base::Value result. This value will be passed to another + // WebUiMessageHandler which needs to handle the 'lstFetchResults' message + // with a single argument that is the dictionary of values relevant for the + // sign in of the user. + void SendLSTFetchResultsMessage(const base::Value& arg); + private: // InlineLoginHandler overrides: void SetExtraInitParams(base::DictionaryValue& params) override; 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 3f0c38f29f8..893269f1fc8 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc @@ -19,7 +19,7 @@ #include "chrome/grit/browser_resources.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" -#include "components/signin/core/browser/profile_management_switches.h" +#include "components/signin/core/browser/account_consistency_method.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/common/content_switches.h" diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_ui_browsertest.cc index e6ead2da79a..2bed898f697 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 @@ -42,8 +42,8 @@ #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" +#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" -#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_pref_names.h" #include "content/public/browser/render_frame_host.h" @@ -274,7 +274,6 @@ class InlineLoginUIBrowserTest : public InProcessBrowserTest { void SetUpSigninManager(const std::string& username); void EnableSigninAllowed(bool enable); - void EnableOneClick(bool enable); void AddEmailToOneClickRejectedList(const std::string& email); void AllowSigninCookies(bool enable); void SetAllowedUsernamePattern(const std::string& pattern); @@ -297,11 +296,6 @@ void InlineLoginUIBrowserTest::EnableSigninAllowed(bool enable) { pref_service->SetBoolean(prefs::kSigninAllowed, enable); } -void InlineLoginUIBrowserTest::EnableOneClick(bool enable) { - PrefService* pref_service = browser()->profile()->GetPrefs(); - pref_service->SetBoolean(prefs::kReverseAutologinEnabled, enable); -} - void InlineLoginUIBrowserTest::AddEmailToOneClickRejectedList( const std::string& email) { PrefService* pref_service = browser()->profile()->GetPrefs(); @@ -380,13 +374,10 @@ IN_PROC_BROWSER_TEST_F(InlineLoginUIBrowserTest, CanOfferNoProfile) { } IN_PROC_BROWSER_TEST_F(InlineLoginUIBrowserTest, CanOffer) { - EnableOneClick(true); EXPECT_TRUE(CanOfferSignin(browser()->profile(), CAN_OFFER_SIGNIN_FOR_ALL_ACCOUNTS, "12345", "user@gmail.com", NULL)); - EnableOneClick(false); - std::string error_message; EXPECT_TRUE(CanOfferSignin(browser()->profile(), @@ -469,7 +460,7 @@ class InlineLoginHelperBrowserTest : public InProcessBrowserTest { // creating the browser so that a bunch of classes don't register as // observers and end up needing to unregister when the fake is substituted. SigninManagerFactory::GetInstance()->SetTestingFactory( - context, base::BindRepeating(&BuildFakeSigninManagerBase)); + context, base::BindRepeating(&BuildFakeSigninManagerForTesting)); ProfileOAuth2TokenServiceFactory::GetInstance()->SetTestingFactory( context, base::BindRepeating(&BuildFakeProfileOAuth2TokenService)); } 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 53b61e31173..c6649e87c65 100644 --- a/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc +++ b/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc @@ -17,165 +17,11 @@ #include "chrome/browser/ui/scoped_tabbed_browser_displayer.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/url_constants.h" -#include "components/signin/core/browser/profile_management_switches.h" +#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/signin_header_helper.h" #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/sync/profile_sync_service_factory.h" -#include "chrome/browser/sync/sync_ui_util.h" -#include "chrome/browser/ui/browser_finder.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/browser/ui/browser_list_observer.h" #include "chrome/browser/ui/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/feature.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 OAuth2TokenService::Observer { - public: - // Creates a ConsentBumpActivator for |profile| which is owned by - // |login_ui_service|. - ConsentBumpActivator(LoginUIService* login_ui_service, Profile* profile) - : login_ui_service_(login_ui_service), - profile_(profile), - scoped_browser_list_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_); - if (consent_service->ShouldShowConsentBump()) { - consent_service->RecordConsentBumpSuppressReason( - unified_consent::metrics::ConsentBumpSuppressReason::kSyncPaused); - } - return; - } - - // Check if there is already an active browser window for |profile|. - Browser* active_browser = chrome::FindLastActiveWithProfile(profile_); - if (active_browser) - OnBrowserSetLastActive(active_browser); - else - scoped_browser_list_observer_.Add(BrowserList::GetInstance()); - } - - // BrowserListObserver: - void OnBrowserSetLastActive(Browser* browser) override { - if (browser->profile() != profile_) - return; - // We only try to show the consent bump once after startup, so remove |this| - // as a |BrowserListObserver|. - scoped_browser_list_observer_.RemoveAll(); - - if (ShouldShowConsentBumpFor(profile_)) { - selected_browser_ = browser; - scoped_login_ui_service_observer_.Add(login_ui_service_); - selected_browser_->signin_view_controller()->ShowModalSyncConsentBump( - selected_browser_); - } - } - - // LoginUIService::Observer: - void OnSyncConfirmationUIClosed( - LoginUIService::SyncConfirmationUIClosedResult result) override { - scoped_login_ui_service_observer_.RemoveAll(); - - 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: - // 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; - } - } - - // 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() || - !unified_consent::IsUnifiedConsentFeatureWithBumpEnabled() || - !ProfileSyncServiceFactory::HasProfileSyncService(profile)) - return false; - - 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)); - - return sync_status == sync_ui_util::SYNCED; - } - - private: - LoginUIService* login_ui_service_; // owner - - Profile* profile_; - - ScopedObserver<BrowserList, ConsentBumpActivator> - 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; - - DISALLOW_COPY_AND_ASSIGN(ConsentBumpActivator); -}; - #endif // !defined(OS_CHROMEOS) LoginUIService::LoginUIService(Profile* profile) @@ -183,12 +29,6 @@ LoginUIService::LoginUIService(Profile* profile) : profile_(profile) #endif { -#if !defined(OS_CHROMEOS) - if (unified_consent::IsUnifiedConsentFeatureWithBumpEnabled()) { - consent_bump_activator_ = - std::make_unique<ConsentBumpActivator>(this, profile); - } -#endif } LoginUIService::~LoginUIService() {} diff --git a/chromium/chrome/browser/ui/webui/signin/login_ui_service.h b/chromium/chrome/browser/ui/webui/signin/login_ui_service.h index 7b154a3037e..61b80a7dbfc 100644 --- a/chromium/chrome/browser/ui/webui/signin/login_ui_service.h +++ b/chromium/chrome/browser/ui/webui/signin/login_ui_service.h @@ -15,7 +15,6 @@ class Browser; class Profile; -class ConsentBumpActivator; // The LoginUIService helps track per-profile information for the login related // UIs - for example, whether there is login UI currently on-screen. @@ -107,7 +106,6 @@ class LoginUIService : public KeyedService { std::list<LoginUI*> ui_list_; #if !defined(OS_CHROMEOS) Profile* profile_; - std::unique_ptr<ConsentBumpActivator> consent_bump_activator_; #endif // List of observers. diff --git a/chromium/chrome/browser/ui/webui/signin/signin_utils_desktop.cc b/chromium/chrome/browser/ui/webui/signin/signin_utils_desktop.cc index 7fe0ef7d8e3..5c72f193747 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_utils_desktop.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_utils_desktop.cc @@ -12,14 +12,16 @@ #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/chrome_signin_client.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/investigator_dependency_provider.h" -#include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/signin/signin_util.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/guest_view/browser/guest_view_manager.h" +#include "components/signin/core/browser/identity_utils.h" #include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_pref_names.h" +#include "services/identity/public/cpp/identity_manager.h" #include "ui/base/l10n/l10n_util.h" bool CanOfferSignin(Profile* profile, @@ -33,19 +35,21 @@ bool CanOfferSignin(Profile* profile, if (!profile) return false; - SigninManager* manager = SigninManagerFactory::GetForProfile(profile); - if (manager && !manager->IsSigninAllowed()) + if (!profile->GetPrefs()->GetBoolean(prefs::kSigninAllowed)) return false; if (!ChromeSigninClient::ProfileAllowsSigninCookies(profile)) return false; if (!email.empty()) { - if (!manager) + auto* identity_manager = IdentityManagerFactory::GetForProfile(profile); + if (!identity_manager) return false; // Make sure this username is not prohibited by policy. - if (!manager->IsAllowedUsername(email)) { + if (!identity::LegacyIsUsernameAllowedByPatternFromPrefs( + g_browser_process->local_state(), email, + prefs::kGoogleServicesUsernamePattern)) { if (error_message) { error_message->assign( l10n_util::GetStringUTF8(IDS_SYNC_LOGIN_NAME_PROHIBITED)); @@ -59,7 +63,7 @@ bool CanOfferSignin(Profile* profile, // If the signin manager already has an authenticated name, then this is a // re-auth scenario. Make sure the email just signed in corresponds to // the one sign in manager expects. - std::string current_email = manager->GetAuthenticatedAccountInfo().email; + std::string current_email = identity_manager->GetPrimaryAccountInfo().email; const bool same_email = gaia::AreEmailsSame(current_email, email); if (!current_email.empty() && !same_email) { UMA_HISTOGRAM_ENUMERATION("Signin.Reauth", 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 06d478de150..32ec47bd42a 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc @@ -30,19 +30,6 @@ #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( @@ -67,12 +54,7 @@ SyncConfirmationHandler::~SyncConfirmationHandler() { // sync confirmation dialog are taken by the user. if (!did_user_explicitly_interact) { HandleUndo(nullptr); - if (IsUnifiedConsentBumpDialog()) { - UMA_HISTOGRAM_ENUMERATION("UnifiedConsent.ConsentBump.Action", - UnifiedConsentBumpAction::kAbort); - } else { - base::RecordAction(base::UserMetricsAction("Signin_Abort_Signin")); - } + base::RecordAction(base::UserMetricsAction("Signin_Abort_Signin")); } } @@ -221,22 +203,18 @@ void SyncConfirmationHandler::OnAccountUpdated(const AccountInfo& info) { void SyncConfirmationHandler::CloseModalSigninWindow( LoginUIService::SyncConfirmationUIClosedResult result) { - 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; - } + 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); @@ -276,8 +254,3 @@ 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 9269e688a2e..f7d9746b39f 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.h +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.h @@ -87,10 +87,6 @@ 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_; 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 5a808d1128d..2146cf89c42 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 @@ -65,7 +65,6 @@ class TestingSyncConfirmationHandler : public SyncConfirmationHandler { using SyncConfirmationHandler::HandleGoToSettings; using SyncConfirmationHandler::RecordConsent; using SyncConfirmationHandler::SetUserImageURL; - using SyncConfirmationHandler::IsUnifiedConsentBumpDialog; private: DISALLOW_COPY_AND_ASSIGN(TestingSyncConfirmationHandler); @@ -105,32 +104,16 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest, 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 && 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 { - histogram_tester_.ExpectTotalCount("UnifiedConsent.ConsentBump.Action", - 0); - } - - EXPECT_EQ( - did_user_explicitly_interact || is_unified_consent_bump_dialog ? 0 : 1, - user_action_tester()->GetActionCount("Signin_Abort_Signin")); + EXPECT_EQ(did_user_explicitly_interact ? 0 : 1, + user_action_tester()->GetActionCount("Signin_Abort_Signin")); } TestingSyncConfirmationHandler* handler() { return handler_; } @@ -172,7 +155,7 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest, {AccountFetcherServiceFactory::GetInstance(), base::BindRepeating(&FakeAccountFetcherServiceBuilder::BuildForTests)}, {SigninManagerFactory::GetInstance(), - base::BindRepeating(&BuildFakeSigninManagerBase)}, + base::BindRepeating(&BuildFakeSigninManagerForTesting)}, {ConsentAuditorFactory::GetInstance(), base::BindRepeating(&BuildFakeConsentAuditor)}}; } @@ -347,31 +330,6 @@ 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; 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 df687d3b6c2..148826408ce 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc @@ -56,44 +56,24 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) source->AddResourcePath("sync_confirmation.js", IDR_DICE_SYNC_CONFIRMATION_JS); - AddStringResource(source, "syncConfirmationChromeSyncBody", - IDS_SYNC_CONFIRMATION_DICE_CHROME_SYNC_MESSAGE); - AddStringResource(source, "syncConfirmationPersonalizeServicesBody", - IDS_SYNC_CONFIRMATION_DICE_PERSONALIZE_SERVICES_BODY); - AddStringResource(source, "syncConfirmationGoogleServicesBody", - IDS_SYNC_CONFIRMATION_DICE_GOOGLE_SERVICES_BODY); - AddStringResource(source, "syncConfirmationSyncSettingsLinkBody", - IDS_SYNC_CONFIRMATION_DICE_SYNC_SETTINGS_LINK_BODY); - AddStringResource(source, "syncConfirmationSyncSettingsDescription", - IDS_SYNC_CONFIRMATION_DICE_SYNC_SETTINGS_DESCRIPTION); + AddStringResource(source, "syncConfirmationSyncInfoTitle", + IDS_SYNC_CONFIRMATION_UNITY_SYNC_INFO_TITLE); + AddStringResource(source, "syncConfirmationSyncInfoDesc", + IDS_SYNC_CONFIRMATION_UNITY_SYNC_INFO_DESC); + AddStringResource(source, "syncConfirmationSpellcheckInfoTitle", + IDS_SYNC_CONFIRMATION_UNITY_SPELLCHECK_INFO_TITLE); + AddStringResource(source, "syncConfirmationSpellcheckInfoDesc", + IDS_SYNC_CONFIRMATION_UNITY_SPELLCHECK_INFO_DESC); + AddStringResource(source, "syncConfirmationImproveChromeInfoTitle", + IDS_SYNC_CONFIRMATION_UNITY_IMPROVE_CHROME_INFO_TITLE); + AddStringResource(source, "syncConfirmationImproveChromeInfoDesc", + IDS_SYNC_CONFIRMATION_UNITY_IMPROVE_CHROME_INFO_DESC); + AddStringResource(source, "syncConfirmationSettingsInfo", + IDS_SYNC_CONFIRMATION_UNITY_SETTINGS_INFO); + AddStringResource(source, "syncConfirmationSettingsLabel", IDS_SYNC_CONFIRMATION_DICE_SETTINGS_BUTTON_LABEL); - AddStringResource(source, "syncConfirmationMoreOptionsLabel", - IDS_SYNC_CONFIRMATION_UNITY_MORE_OPTIONS_BUTTON_LABEL); - AddStringResource(source, "syncConfirmationOptionsTitle", - IDS_SYNC_CONFIRMATION_UNITY_MORE_OPTIONS_TITLE); - AddStringResource(source, "syncConfirmationOptionsSubtitle", - IDS_SYNC_CONFIRMATION_UNITY_MORE_OPTIONS_SUBTITLE); - AddStringResource( - source, "syncConfirmationOptionsReviewSettingsTitle", - IDS_SYNC_CONFIRMATION_UNITY_OPTIONS_REVIEW_SETTINGS_TITLE); - AddStringResource( - source, "syncConfirmationOptionsMakeNoChangesTitle", - IDS_SYNC_CONFIRMATION_UNITY_OPTIONS_MAKE_NO_CHANGES_TITLE); - AddStringResource( - source, "syncConfirmationOptionsMakeNoChangesSubtitle", - IDS_SYNC_CONFIRMATION_UNITY_OPTIONS_MAKE_NO_CHANGES_SUBTITLE); - AddStringResource(source, "syncConfirmationOptionsUseDefaultTitle", - IDS_SYNC_CONFIRMATION_UNITY_OPTIONS_USE_DEFAULT_TITLE); - AddStringResource(source, "syncConfirmationOptionsUseDefaultSubtitle", - IDS_SYNC_CONFIRMATION_UNITY_OPTIONS_USE_DEFAULT_SUBTITLE); - AddStringResource(source, "syncConfirmationOptionsConfirmLabel", IDS_OK); - AddStringResource(source, "syncConfirmationOptionsBackLabel", - IDS_SYNC_CONFIRMATION_UNITY_OPTIONS_BACK_BUTTON_LABEL); - AddStringResource(source, "syncConsentBumpTitle", - IDS_SYNC_CONFIRMATION_UNITY_CONSENT_BUMP_TITLE); - constexpr int kAccountPictureSize = 68; std::string custom_picture_url = profiles::GetPlaceholderAvatarIconUrl(); GURL account_picture_url(IdentityManagerFactory::GetForProfile(profile) 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 2892d4b3c27..6b61b9791a0 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 @@ -50,7 +50,7 @@ #include "chrome/grit/generated_resources.h" #include "components/account_id/account_id.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/profile_management_switches.h" +#include "components/signin/core/browser/account_consistency_method.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/storage_partition.h" diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc index 3f32dcc185c..5a2ee839d85 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 @@ -23,7 +23,7 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/ui_test_utils.h" -#include "components/signin/core/browser/profile_management_switches.h" +#include "components/signin/core/browser/account_consistency_method.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "testing/gmock/include/gmock/gmock.h" @@ -143,6 +143,7 @@ class UserManagerUIAuthenticatedUserBrowserTest IN_PROC_BROWSER_TEST_F(UserManagerUIAuthenticatedUserBrowserTest, Reauth) { Init(); + signin_util::SetForceSigninForTesting(true); entry_->SetLocalAuthCredentials("1mock_credentials"); LaunchAuthenticatedUser("email@mock.com"); diff --git a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc index 861389f5877..a2b491984f3 100644 --- a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc @@ -83,9 +83,8 @@ bool SignInInternalsUI::OverrideHandleWebUIMessage( std::vector<gaia::ListedAccount> signed_out_accounts; GaiaCookieManagerService* cookie_manager_service = GaiaCookieManagerServiceFactory::GetForProfile(profile); - if (cookie_manager_service->ListAccounts( - &cookie_accounts, &signed_out_accounts, - "ChromiumSignInInternalsUI")) { + if (cookie_manager_service->ListAccounts(&cookie_accounts, + &signed_out_accounts)) { about_signin_internals->OnGaiaAccountsInCookieUpdated( cookie_accounts, signed_out_accounts, diff --git a/chromium/chrome/browser/ui/webui/site_settings_helper.cc b/chromium/chrome/browser/ui/webui/site_settings_helper.cc index d39d5f329ed..98658e9c67f 100644 --- a/chromium/chrome/browser/ui/webui/site_settings_helper.cc +++ b/chromium/chrome/browser/ui/webui/site_settings_helper.cc @@ -4,8 +4,8 @@ #include "chrome/browser/ui/webui/site_settings_helper.h" +#include <algorithm> #include <functional> -#include <string> #include "base/feature_list.h" #include "base/values.h" @@ -99,6 +99,7 @@ const ContentSettingsTypeNameEntry kContentSettingsTypeGroupNames[] = { {CONTENT_SETTINGS_TYPE_CLIPBOARD_WRITE, nullptr}, {CONTENT_SETTINGS_TYPE_PLUGINS_DATA, nullptr}, {CONTENT_SETTINGS_TYPE_BACKGROUND_FETCH, nullptr}, + {CONTENT_SETTINGS_TYPE_INTENT_PICKER_DISPLAY, nullptr}, }; static_assert(arraysize(kContentSettingsTypeGroupNames) == // ContentSettingsType starts at -1, so add 1 here. @@ -590,6 +591,12 @@ void GetChooserExceptionsFromProfile(Profile* profile, chooser_context->GetAllGrantedObjects(); AllOriginObjects all_origin_objects; for (const auto& object : objects) { + // Skip policy controlled objects until they are ready to be displayed. + // TODO(https://crbug.com/854329): Include policy controlled objects + // when the UI is capable of displaying them properly as policy controlled + // objects. + if (object->source == SiteSettingSourceToString(SiteSettingSource::kPolicy)) + continue; std::string name = chooser_context->GetObjectName(object->object); // It is safe for this structure to hold references into |objects| because // they are both destroyed at the end of this function. 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 bc6b01b9fa3..55c7e9f22f2 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc @@ -4,11 +4,10 @@ #include "chrome/browser/ui/webui/sync_internals_message_handler.h" -#include <stdint.h> - #include <utility> #include <vector> +#include "base/command_line.h" #include "base/feature_list.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" @@ -17,9 +16,7 @@ #include "chrome/browser/sync/user_event_service_factory.h" #include "chrome/common/channel_info.h" #include "components/browser_sync/profile_sync_service.h" -#include "components/sync/base/enum_set.h" #include "components/sync/base/model_type.h" -#include "components/sync/base/weak_handle.h" #include "components/sync/driver/about_sync_util.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/driver/sync_service.h" @@ -36,11 +33,7 @@ using base::DictionaryValue; using base::ListValue; using base::Value; -using browser_sync::ProfileSyncService; -using syncer::JsEventDetails; -using syncer::ModelTypeSet; using syncer::SyncService; -using syncer::WeakHandle; namespace { @@ -224,7 +217,7 @@ void SyncInternalsMessageHandler::HandleRequestListOfTypes( DictionaryValue event_details; auto type_list = std::make_unique<ListValue>(); - ModelTypeSet protocol_types = syncer::ProtocolTypes(); + syncer::ModelTypeSet protocol_types = syncer::ProtocolTypes(); for (syncer::ModelType type : protocol_types) { type_list->AppendString(ModelTypeToString(type)); } @@ -314,11 +307,11 @@ void SyncInternalsMessageHandler::HandleRequestStart( if (!service) return; - service->RequestStart(); + service->GetUserSettings()->SetSyncRequested(true); // If the service was previously stopped with CLEAR_DATA, then the // "first-setup-complete" bit was also cleared, and now the service wouldn't // fully start up. So set that too. - service->SetFirstSetupComplete(); + service->GetUserSettings()->SetFirstSetupComplete(); } void SyncInternalsMessageHandler::HandleRequestStopKeepData( @@ -329,7 +322,7 @@ void SyncInternalsMessageHandler::HandleRequestStopKeepData( if (!service) return; - service->RequestStop(SyncService::KEEP_DATA); + service->GetUserSettings()->SetSyncRequested(false); } void SyncInternalsMessageHandler::HandleRequestStopClearData( @@ -404,7 +397,7 @@ void SyncInternalsMessageHandler::EmitCounterUpdate( void SyncInternalsMessageHandler::HandleJsEvent( const std::string& name, - const JsEventDetails& details) { + const syncer::JsEventDetails& details) { DVLOG(1) << "Handling event: " << name << " with details " << details.ToString(); DispatchEvent(name, details.Get()); 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 3f94dce4a93..73c613c6191 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_message_handler.h +++ b/chromium/chrome/browser/ui/webui/sync_internals_message_handler.h @@ -8,10 +8,8 @@ #include <memory> #include <string> -#include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "base/scoped_observer.h" #include "base/values.h" #include "components/sync/driver/sync_service_observer.h" #include "components/sync/engine/cycle/type_debug_info_observer.h" @@ -21,10 +19,6 @@ #include "components/version_info/channel.h" #include "content/public/browser/web_ui_message_handler.h" -namespace browser_sync { -class ProfileSyncService; -} // namespace browser_sync - namespace syncer { class SyncService; } // namespace syncer diff --git a/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc b/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc index 04878a3bfdb..3b37b29bc14 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc @@ -9,9 +9,9 @@ #include "base/bind.h" #include "base/command_line.h" -#include "base/memory/ref_counted.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/user_event_service_factory.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/browser_sync/browser_sync_switches.h" #include "components/sync/driver/about_sync_util.h" @@ -21,9 +21,7 @@ #include "components/sync/user_events/fake_user_event_service.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" -#include "testing/gtest/include/gtest/gtest.h" using base::DictionaryValue; using base::ListValue; @@ -106,20 +104,22 @@ static std::unique_ptr<KeyedService> BuildFakeUserEventService( return std::make_unique<FakeUserEventService>(); } -class SyncInternalsMessageHandlerTest : public ::testing::Test { +class SyncInternalsMessageHandlerTest : public ChromeRenderViewHostTestHarness { protected: - SyncInternalsMessageHandlerTest() { - site_instance_ = content::SiteInstance::Create(&profile_); - web_contents_ = content::WebContents::Create( - content::WebContents::CreateParams(&profile_, site_instance_.get())); - web_ui_.set_web_contents(web_contents_.get()); + SyncInternalsMessageHandlerTest() = default; + ~SyncInternalsMessageHandlerTest() override = default; + + void SetUp() override { + ChromeRenderViewHostTestHarness::SetUp(); + + web_ui_.set_web_contents(web_contents()); test_sync_service_ = static_cast<TestSyncService*>( ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse( - &profile_, base::BindRepeating(&BuildTestSyncService))); + profile(), base::BindRepeating(&BuildTestSyncService))); fake_user_event_service_ = static_cast<FakeUserEventService*>( browser_sync::UserEventServiceFactory::GetInstance() ->SetTestingFactoryAndUse( - &profile_, base::BindRepeating(&BuildFakeUserEventService))); + profile(), base::BindRepeating(&BuildFakeUserEventService))); handler_.reset(new TestableSyncInternalsMessageHandler( &web_ui_, base::BindRepeating( @@ -127,6 +127,12 @@ class SyncInternalsMessageHandlerTest : public ::testing::Test { base::Unretained(this)))); } + void TearDown() override { + // Destroy |handler_| before |web_contents()|. + handler_ = nullptr; + ChromeRenderViewHostTestHarness::TearDown(); + } + std::unique_ptr<DictionaryValue> ConstructAboutInformation( SyncService* service, version_info::Channel channel) { @@ -167,8 +173,6 @@ class SyncInternalsMessageHandlerTest : public ::testing::Test { EXPECT_TRUE(web_ui_.call_data().empty()); } - TestingProfile* profile() { return &profile_; } - TestSyncService* test_sync_service() { return test_sync_service_; } FakeUserEventService* fake_user_event_service() { @@ -198,16 +202,14 @@ class SyncInternalsMessageHandlerTest : public ::testing::Test { void ResetHandler() { handler_.reset(); } private: - content::TestBrowserThreadBundle thread_bundle_; - TestingProfile profile_; - scoped_refptr<content::SiteInstance> site_instance_; - std::unique_ptr<content::WebContents> web_contents_; content::TestWebUI web_ui_; TestSyncService* test_sync_service_; FakeUserEventService* fake_user_event_service_; std::unique_ptr<TestableSyncInternalsMessageHandler> handler_; int about_sync_data_delegate_call_count_ = 0; SyncService* last_delegate_sync_service_ = nullptr; + + DISALLOW_COPY_AND_ASSIGN(SyncInternalsMessageHandlerTest); }; TEST_F(SyncInternalsMessageHandlerTest, AddRemoveObservers) { diff --git a/chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.cc b/chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.cc index 0b69b7bb827..1823905d48c 100644 --- a/chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.cc @@ -29,6 +29,7 @@ content::WebUIDataSource* CreateUkmHTMLSource() { content::WebUIDataSource::Create(chrome::kChromeUIUkmHost); source->AddResourcePath("ukm_internals.js", IDR_UKM_INTERNALS_JS); + source->AddResourcePath("ukm_internals.css", IDR_UKM_INTERNALS_CSS); source->SetDefaultResource(IDR_UKM_INTERNALS_HTML); source->UseGzip(); return source; diff --git a/chromium/chrome/browser/ui/webui/user_actions/user_actions_ui.cc b/chromium/chrome/browser/ui/webui/user_actions/user_actions_ui.cc index 96ece30d95b..f41ffc6133e 100644 --- a/chromium/chrome/browser/ui/webui/user_actions/user_actions_ui.cc +++ b/chromium/chrome/browser/ui/webui/user_actions/user_actions_ui.cc @@ -9,7 +9,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/user_actions/user_actions_ui_handler.h" #include "chrome/common/url_constants.h" -#include "chrome/grit/browser_resources.h" +#include "components/grit/components_resources.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_controller.h" #include "content/public/browser/web_ui_data_source.h" diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/BUILD.gn b/chromium/chrome/browser/ui/webui/welcome/nux/BUILD.gn deleted file mode 100644 index 718b6efc23d..00000000000 --- a/chromium/chrome/browser/ui/webui/welcome/nux/BUILD.gn +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright 2018 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/chrome_build.gni") - -source_set("constants") { - sources = [ - "constants.cc", - "constants.h", - ] - - public_deps = [ - "//base", - ] -} - -static_library("email_feature") { - sources = [ - "email_handler.cc", - "email_handler.h", - ] - - public_deps = [ - "//base", - "//net", - "//url", - ] - - deps = [ - "//chrome/app:generated_resources", - "//chrome/browser:resources", - "//components/bookmarks/browser", - "//components/bookmarks/common", - "//components/favicon/core", - "//components/pref_registry", - "//components/prefs", - "//components/resources", - "//components/strings", - "//components/variations", - "//content/public/browser", - "//ui/base", - ] -} - -static_library("google_apps_feature") { - sources = [ - "google_apps_handler.cc", - "google_apps_handler.h", - ] - - public_deps = [ - "//base", - "//net", - "//url", - ] - - deps = [ - "//chrome/app:generated_resources", - "//chrome/browser:resources", - "//components/bookmarks/browser", - "//components/bookmarks/common", - "//components/favicon/core", - "//components/pref_registry", - "//components/prefs", - "//components/resources", - "//components/strings", - "//components/variations", - "//content/public/browser", - "//ui/base", - ] -} diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.cc b/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.cc new file mode 100644 index 00000000000..e09ec04fbc0 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.cc @@ -0,0 +1,49 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/welcome/nux/bookmark_handler.h" + +#include "base/bind.h" +#include "chrome/grit/browser_resources.h" +#include "components/bookmarks/common/bookmark_pref_names.h" +#include "components/prefs/pref_service.h" +#include "content/public/browser/web_ui_data_source.h" + +namespace nux { + +BookmarkHandler::BookmarkHandler(PrefService* prefs) : prefs_(prefs) {} + +BookmarkHandler::~BookmarkHandler() {} + +void BookmarkHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "toggleBookmarkBar", + base::BindRepeating(&BookmarkHandler::HandleToggleBookmarkBar, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "isBookmarkBarShown", + base::BindRepeating(&BookmarkHandler::HandleIsBookmarkBarShown, + base::Unretained(this))); +} + +void BookmarkHandler::HandleToggleBookmarkBar(const base::ListValue* args) { + bool show; + CHECK(args->GetBoolean(0, &show)); + prefs_->SetBoolean(bookmarks::prefs::kShowBookmarkBar, show); +} + +void BookmarkHandler::HandleIsBookmarkBarShown(const base::ListValue* args) { + AllowJavascript(); + + CHECK_EQ(1U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + + ResolveJavascriptCallback( + *callback_id, + base::Value(prefs_->GetBoolean(bookmarks::prefs::kShowBookmarkBar))); +} + +} // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.h b/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.h new file mode 100644 index 00000000000..b9240c93816 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.h @@ -0,0 +1,37 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_HANDLER_H_ + +#include "base/macros.h" +#include "base/values.h" +#include "content/public/browser/web_ui_message_handler.h" + +class PrefService; + +namespace nux { + +class BookmarkHandler : public content::WebUIMessageHandler { + public: + explicit BookmarkHandler(PrefService* prefs); + ~BookmarkHandler() override; + + // WebUIMessageHandler: + void RegisterMessages() override; + + // Callbacks for JS APIs. + void HandleToggleBookmarkBar(const base::ListValue* args); + void HandleIsBookmarkBarShown(const base::ListValue* args); + + private: + // Weak reference. + PrefService* prefs_; + + DISALLOW_COPY_AND_ASSIGN(BookmarkHandler); +}; + +} // namespace nux + +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.cc b/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.cc new file mode 100644 index 00000000000..e1e9e062382 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.cc @@ -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. + +#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" + +#include "base/strings/string16.h" +#include "base/values.h" + +namespace nux { + +base::ListValue bookmarkItemsToListValue(const BookmarkItem items[], + size_t count) { + base::ListValue list_value; + for (size_t i = 0; i < count; ++i) { + auto element = std::make_unique<base::DictionaryValue>(); + + element->SetInteger("id", items[i].id); + element->SetString("name", items[i].name); + element->SetString("icon", items[i].webui_icon); + element->SetString("url", items[i].url); + + list_value.Append(std::move(element)); + } + return list_value; +} + +base::ListValue bookmarkItemsToListValue( + const std::vector<BookmarkItem>& items) { + base::ListValue list_value; + for (const auto& item : items) { + auto element = std::make_unique<base::DictionaryValue>(); + + element->SetInteger("id", item.id); + element->SetString("name", item.name); + element->SetString("icon", item.webui_icon); + element->SetString("url", item.url); + + list_value.Append(std::move(element)); + } + return list_value; +} + +} // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.h b/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.h new file mode 100644 index 00000000000..8a0d6b69642 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.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_WELCOME_NUX_BOOKMARK_ITEM_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_ITEM_H_ + +#include <stddef.h> +#include <vector> + +namespace base { +class ListValue; +} // namespace base + +namespace nux { + +struct BookmarkItem { + const int id; + const char* name; + const char* webui_icon; + const char* url; + const int icon; // Corresponds with resource ID, used for bookmark cache. +}; + +base::ListValue bookmarkItemsToListValue(const BookmarkItem items[], + size_t count); + +base::ListValue bookmarkItemsToListValue( + const std::vector<BookmarkItem>& items); + +} // namespace nux + +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_ITEM_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/constants.cc b/chromium/chrome/browser/ui/webui/welcome/nux/constants.cc index ce936c04d9b..d616532f1ce 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/constants.cc +++ b/chromium/chrome/browser/ui/webui/welcome/nux/constants.cc @@ -8,16 +8,18 @@ namespace nux { -extern const base::Feature kNuxEmailFeature{"NuxEmail", - base::FEATURE_DISABLED_BY_DEFAULT}; - -extern const base::Feature kNuxGoogleAppsFeature{ - "NuxGoogleApps", base::FEATURE_DISABLED_BY_DEFAULT}; - -extern const base::Feature kNuxOnboardingFeature{ - "NuxOnboarding", base::FEATURE_DISABLED_BY_DEFAULT}; - -extern const char kNuxEmailUrl[] = "chrome://welcome/email"; -extern const char kNuxGoogleAppsUrl[] = "chrome://welcome/apps"; - -} // namespace nux
\ No newline at end of file +const base::Feature kNuxOnboardingFeature{"NuxOnboarding", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// The value of these FeatureParam values should be a comma-delimited list +// of element names whitelisted in the MODULES_WHITELIST list, defined in +// chrome/browser/resources/welcome/onboarding_welcome/welcome_app.js +const base::FeatureParam<std::string> kNuxOnboardingNewUserModules{ + &kNuxOnboardingFeature, "new-user-modules", + "nux-email,nux-google-apps,nux-set-as-default,signin-view"}; +const base::FeatureParam<std::string> kNuxOnboardingReturningUserModules{ + &kNuxOnboardingFeature, "returning-user-modules", "nux-set-as-default"}; +const base::FeatureParam<bool> kNuxOnboardingShowEmailInterstitial{ + &kNuxOnboardingFeature, "show-email-interstitial", true}; + +} // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/constants.h b/chromium/chrome/browser/ui/webui/welcome/nux/constants.h index 8f72a0cec64..0ea4f52d8ba 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/constants.h +++ b/chromium/chrome/browser/ui/webui/welcome/nux/constants.h @@ -5,17 +5,20 @@ #ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_CONSTANTS_H_ #define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_CONSTANTS_H_ +#include <string> +#include "base/metrics/field_trial_params.h" + namespace base { struct Feature; } // namespace base namespace nux { -extern const base::Feature kNuxEmailFeature; -extern const base::Feature kNuxGoogleAppsFeature; extern const base::Feature kNuxOnboardingFeature; -extern const char kNuxEmailUrl[]; -extern const char kNuxGoogleAppsUrl[]; + +extern const base::FeatureParam<std::string> kNuxOnboardingNewUserModules; +extern const base::FeatureParam<std::string> kNuxOnboardingReturningUserModules; +extern const base::FeatureParam<bool> kNuxOnboardingShowEmailInterstitial; } // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/email_handler.cc b/chromium/chrome/browser/ui/webui/welcome/nux/email_handler.cc index 5e45b1e1721..329f4692f35 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/email_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/nux/email_handler.cc @@ -9,14 +9,16 @@ #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/ui/webui/welcome/nux/show_promo_delegate.h" -#include "chrome/grit/browser_resources.h" +#include "chrome/browser/favicon/favicon_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" +#include "chrome/browser/ui/webui/welcome/nux/email_providers_list.h" #include "chrome/grit/generated_resources.h" -#include "components/bookmarks/common/bookmark_pref_names.h" +#include "chrome/grit/onboarding_welcome_resources.h" +#include "components/country_codes/country_codes.h" #include "components/favicon/core/favicon_service.h" #include "components/grit/components_resources.h" #include "components/grit/components_scaled_resources.h" -#include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -25,50 +27,13 @@ namespace nux { -// These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. -enum class EmailProviders { - kGmail = 0, - kYahoo = 1, - kOutlook = 2, - kAol = 3, - kiCloud = 4, - kCount, -}; - -struct EmailProviderType { - const EmailProviders id; - const char* name; // Icon in WebUI should use name to match CSS. - const char* url; - const int icon; // Corresponds with resource ID, used for bookmark cache. -}; - const char* kEmailInteractionHistogram = "FirstRun.NewUserExperience.EmailInteraction"; -// Strings in costants not translated because this is an experiment. -// Translate before wide release. -// TODO(hcarmona): populate with icon ids. -const EmailProviderType kEmail[] = { - {EmailProviders::kGmail, "Gmail", - "https://accounts.google.com/b/0/AddMailService", IDR_NUX_EMAIL_GMAIL_1X}, - {EmailProviders::kYahoo, "Yahoo", "https://mail.yahoo.com", - IDR_NUX_EMAIL_YAHOO_1X}, - {EmailProviders::kOutlook, "Outlook", "https://login.live.com/login.srf?", - IDR_NUX_EMAIL_OUTLOOK_1X}, - {EmailProviders::kAol, "AOL", "https://mail.aol.com", IDR_NUX_EMAIL_AOL_1X}, - {EmailProviders::kiCloud, "iCloud", "https://www.icloud.com/mail", - IDR_NUX_EMAIL_ICLOUD_1X}, -}; - constexpr const int kEmailIconSize = 48; // Pixels. -static_assert(base::size(kEmail) == (size_t)EmailProviders::kCount, - "names and histograms must match"); - -EmailHandler::EmailHandler(PrefService* prefs, - favicon::FaviconService* favicon_service) - : prefs_(prefs), favicon_service_(favicon_service) {} +EmailHandler::EmailHandler() + : email_providers_(GetCurrentCountryEmailProviders()) {} EmailHandler::~EmailHandler() {} @@ -78,19 +43,18 @@ void EmailHandler::RegisterMessages() { base::Unretained(this))); web_ui()->RegisterMessageCallback( - "toggleBookmarkBar", - base::BindRepeating(&EmailHandler::HandleToggleBookmarkBar, - base::Unretained(this))); + "getEmailList", base::BindRepeating(&EmailHandler::HandleGetEmailList, + base::Unretained(this))); } void EmailHandler::HandleCacheEmailIcon(const base::ListValue* args) { int emailId; args->GetInteger(0, &emailId); - const EmailProviderType* selectedEmail = NULL; - for (size_t i = 0; i < base::size(kEmail); i++) { - if ((int)kEmail[i].id == emailId) { - selectedEmail = &kEmail[i]; + const BookmarkItem* selectedEmail = NULL; + for (const auto& provider : email_providers_) { + if (provider.id == emailId) { + selectedEmail = &provider; break; } } @@ -100,72 +64,28 @@ void EmailHandler::HandleCacheEmailIcon(const base::ListValue* args) { // pre-populated bookmarks don't have favicons and look bad. Favicons are // updated automatically when a user visits a site. GURL app_url = GURL(selectedEmail->url); - favicon_service_->MergeFavicon( - app_url, app_url, favicon_base::IconType::kFavicon, - ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes( - selectedEmail->icon), - gfx::Size(kEmailIconSize, kEmailIconSize)); + FaviconServiceFactory::GetForProfile(Profile::FromWebUI(web_ui()), + ServiceAccessType::EXPLICIT_ACCESS) + ->MergeFavicon( + app_url, app_url, favicon_base::IconType::kFavicon, + ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes( + selectedEmail->icon), + gfx::Size(kEmailIconSize, kEmailIconSize)); } -void EmailHandler::HandleToggleBookmarkBar(const base::ListValue* args) { - bool show = false; - CHECK(args->GetBoolean(0, &show)); - prefs_->SetBoolean(bookmarks::prefs::kShowBookmarkBar, show); +void EmailHandler::HandleGetEmailList(const base::ListValue* args) { + AllowJavascript(); + CHECK_EQ(1U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + ResolveJavascriptCallback(*callback_id, + bookmarkItemsToListValue(email_providers_)); } -void EmailHandler::AddSources(content::WebUIDataSource* html_source, - PrefService* prefs) { - // Localized strings. - html_source->AddLocalizedString("noThanks", IDS_NO_THANKS); - html_source->AddLocalizedString("getStarted", IDS_NUX_EMAIL_GET_STARTED); - html_source->AddLocalizedString("welcomeTitle", IDS_NUX_EMAIL_WELCOME_TITLE); - html_source->AddLocalizedString("emailPrompt", IDS_NUX_EMAIL_PROMPT); - html_source->AddLocalizedString("bookmarkAdded", - IDS_NUX_EMAIL_BOOKMARK_ADDED); - html_source->AddLocalizedString("bookmarkRemoved", - IDS_NUX_EMAIL_BOOKMARK_REMOVED); - html_source->AddLocalizedString("bookmarkReplaced", - IDS_NUX_EMAIL_BOOKMARK_REPLACED); - - // Add required resources. - html_source->AddResourcePath("email", IDR_NUX_EMAIL_HTML); - html_source->AddResourcePath("email/nux_email.js", IDR_NUX_EMAIL_JS); - - html_source->AddResourcePath("email/nux_email_proxy.html", - IDR_NUX_EMAIL_PROXY_HTML); - html_source->AddResourcePath("email/nux_email_proxy.js", - IDR_NUX_EMAIL_PROXY_JS); - - html_source->AddResourcePath("email/email_chooser.html", - IDR_NUX_EMAIL_CHOOSER_HTML); - html_source->AddResourcePath("email/email_chooser.js", - IDR_NUX_EMAIL_CHOOSER_JS); - - // Add icons - html_source->AddResourcePath("email/aol_1x.png", IDR_NUX_EMAIL_AOL_1X); - html_source->AddResourcePath("email/aol_2x.png", IDR_NUX_EMAIL_AOL_2X); - html_source->AddResourcePath("email/gmail_1x.png", IDR_NUX_EMAIL_GMAIL_1X); - html_source->AddResourcePath("email/gmail_2x.png", IDR_NUX_EMAIL_GMAIL_2X); - html_source->AddResourcePath("email/icloud_1x.png", IDR_NUX_EMAIL_ICLOUD_1X); - html_source->AddResourcePath("email/icloud_2x.png", IDR_NUX_EMAIL_ICLOUD_2X); - html_source->AddResourcePath("email/outlook_1x.png", - IDR_NUX_EMAIL_OUTLOOK_1X); - html_source->AddResourcePath("email/outlook_2x.png", - IDR_NUX_EMAIL_OUTLOOK_2X); - html_source->AddResourcePath("email/yahoo_1x.png", IDR_NUX_EMAIL_YAHOO_1X); - html_source->AddResourcePath("email/yahoo_2x.png", IDR_NUX_EMAIL_YAHOO_2X); - +void EmailHandler::AddSources(content::WebUIDataSource* html_source) { // Add constants to loadtime data - for (size_t i = 0; i < (size_t)EmailProviders::kCount; ++i) { - html_source->AddInteger("email_id_" + std::to_string(i), (int)kEmail[i].id); - html_source->AddString("email_name_" + std::to_string(i), kEmail[i].name); - html_source->AddString("email_url_" + std::to_string(i), kEmail[i].url); - } - html_source->AddInteger("email_count", (int)EmailProviders::kCount); - html_source->AddBoolean( - "bookmark_bar_shown", - prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar)); + html_source->AddInteger("email_providers_enum_count", EmailProviders::kCount); html_source->SetJsonPath("strings.js"); } -} // namespace nux
\ No newline at end of file +} // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/email_handler.h b/chromium/chrome/browser/ui/webui/welcome/nux/email_handler.h index e66e56e7f8d..926790dd8e0 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/email_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/nux/email_handler.h @@ -5,22 +5,20 @@ #ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_EMAIL_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_EMAIL_HANDLER_H_ +#include <vector> + #include "base/macros.h" #include "base/values.h" #include "content/public/browser/web_ui_message_handler.h" -class PrefService; - namespace content { class WebUIDataSource; } // namespace content -namespace favicon { -class FaviconService; -} // namespace favicon - namespace nux { +struct BookmarkItem; + extern const char* kEmailInteractionHistogram; // These values are persisted to logs. Entries should not be renumbered and @@ -34,7 +32,7 @@ enum class EmailInteraction { class EmailHandler : public content::WebUIMessageHandler { public: - EmailHandler(PrefService* prefs, favicon::FaviconService* favicon_service); + EmailHandler(); ~EmailHandler() override; // WebUIMessageHandler: @@ -42,18 +40,13 @@ class EmailHandler : public content::WebUIMessageHandler { // Callbacks for JS APIs. void HandleCacheEmailIcon(const base::ListValue* args); - void HandleToggleBookmarkBar(const base::ListValue* args); + void HandleGetEmailList(const base::ListValue* args); // Adds webui sources. - static void AddSources(content::WebUIDataSource* html_source, - PrefService* prefs); + static void AddSources(content::WebUIDataSource* html_source); private: - // Weak reference. - PrefService* prefs_; - - // Weak reference. - favicon::FaviconService* favicon_service_; + const std::vector<BookmarkItem> email_providers_; DISALLOW_COPY_AND_ASSIGN(EmailHandler); }; diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/email_providers_list.cc b/chromium/chrome/browser/ui/webui/welcome/nux/email_providers_list.cc new file mode 100644 index 00000000000..76a01b65c11 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/welcome/nux/email_providers_list.cc @@ -0,0 +1,52 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/welcome/nux/email_providers_list.h" + +#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" +#include "chrome/grit/onboarding_welcome_resources.h" +#include "components/country_codes/country_codes.h" + +namespace nux { + +std::vector<BookmarkItem> GetCurrentCountryEmailProviders() { + switch (country_codes::GetCurrentCountryID()) { + case country_codes::CountryCharsToCountryID('U', 'S'): { + return { + {EmailProviders::kGmail, "Gmail", "gmail", + "https://accounts.google.com/b/0/AddMailService", + IDR_NUX_EMAIL_GMAIL_1X}, + {EmailProviders::kYahoo, "Yahoo", "yahoo", "https://mail.yahoo.com", + IDR_NUX_EMAIL_YAHOO_1X}, + {EmailProviders::kOutlook, "Outlook", "outlook", + "https://login.live.com/login.srf?", IDR_NUX_EMAIL_OUTLOOK_1X}, + {EmailProviders::kAol, "AOL", "aol", "https://mail.aol.com", + IDR_NUX_EMAIL_AOL_1X}, + {EmailProviders::kiCloud, "iCloud", "icloud", + "https://www.icloud.com/mail", IDR_NUX_EMAIL_ICLOUD_1X}, + }; + } + + // TODO(scottchen): define all supported countries here. + + default: { + // TODO(scottchen): examine if we want these US providers as default. + return { + {EmailProviders::kGmail, "Gmail", "gmail", + "https://accounts.google.com/b/0/AddMailService", + IDR_NUX_EMAIL_GMAIL_1X}, + {static_cast<int>(EmailProviders::kYahoo), "Yahoo", "yahoo", + "https://mail.yahoo.com", IDR_NUX_EMAIL_YAHOO_1X}, + {static_cast<int>(EmailProviders::kOutlook), "Outlook", "outlook", + "https://login.live.com/login.srf?", IDR_NUX_EMAIL_OUTLOOK_1X}, + {static_cast<int>(EmailProviders::kAol), "AOL", "aol", + "https://mail.aol.com", IDR_NUX_EMAIL_AOL_1X}, + {static_cast<int>(EmailProviders::kiCloud), "iCloud", "icloud", + "https://www.icloud.com/mail", IDR_NUX_EMAIL_ICLOUD_1X}, + }; + } + } +} + +} // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/email_providers_list.h b/chromium/chrome/browser/ui/webui/welcome/nux/email_providers_list.h new file mode 100644 index 00000000000..926bcd620ed --- /dev/null +++ b/chromium/chrome/browser/ui/webui/welcome/nux/email_providers_list.h @@ -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. + +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_EMAIL_PROVIDERS_LIST_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_EMAIL_PROVIDERS_LIST_H_ + +#include <vector> + +#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" + +namespace nux { + +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum EmailProviders { + kGmail = 0, + kYahoo = 1, + kOutlook = 2, + kAol = 3, + kiCloud = 4, + kCount, +}; + +std::vector<BookmarkItem> GetCurrentCountryEmailProviders(); + +} // namespace nux + +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_EMAIL_PROVIDERS_LIST_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.cc b/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.cc index cef05302dab..33584ab99ad 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.cc @@ -8,20 +8,17 @@ #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/ui/webui/welcome/nux/show_promo_delegate.h" -#include "chrome/grit/browser_resources.h" +#include "chrome/browser/favicon/favicon_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" #include "chrome/grit/generated_resources.h" -#include "components/bookmarks/browser/bookmark_model.h" -#include "components/bookmarks/common/bookmark_pref_names.h" +#include "chrome/grit/onboarding_welcome_resources.h" #include "components/favicon/core/favicon_service.h" #include "components/grit/components_resources.h" #include "components/grit/components_scaled_resources.h" -#include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" -#include "content/public/browser/web_ui_data_source.h" #include "ui/base/resource/resource_bundle.h" namespace nux { @@ -29,7 +26,7 @@ namespace nux { // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. enum class GoogleApps { - kGmail = 0, + kGmailDoNotUse = 0, // Deprecated. kYouTube = 1, kMaps = 2, kTranslate = 3, @@ -42,147 +39,72 @@ const char* kGoogleAppsInteractionHistogram = "FirstRun.NewUserExperience.GoogleAppsInteraction"; // Strings in costants not translated because this is an experiment. -// Translate before wide release. - -constexpr const char* kGoogleAppNames[] = { - "Gmail", "YouTube", "Maps", "Translate", "News", "Chrome Web Store", -}; - -constexpr const char* kGoogleAppUrls[] = { - "https://gmail.com", "https://youtube.com", - "https://maps.google.com", "https://translate.google.com", - "https://news.google.com", "https://chrome.google.com/webstore", +// TODO(hcarmona): Translate before wide release. +const BookmarkItem kGoogleApps[] = { + {static_cast<int>(GoogleApps::kYouTube), "YouTube", "youtube", + "https://youtube.com", IDR_NUX_GOOGLE_APPS_YOUTUBE_1X}, + {static_cast<int>(GoogleApps::kMaps), "Maps", "maps", + "https://maps.google.com", IDR_NUX_GOOGLE_APPS_MAPS_1X}, + {static_cast<int>(GoogleApps::kNews), "News", "news", + "https://news.google.com", IDR_NUX_GOOGLE_APPS_NEWS_1X}, + {static_cast<int>(GoogleApps::kTranslate), "Translate", "translate", + "https://translate.google.com", IDR_NUX_GOOGLE_APPS_TRANSLATE_1X}, + {static_cast<int>(GoogleApps::kChromeWebStore), "Web Store", "web-store", + "https://chrome.google.com/webstore", IDR_NUX_GOOGLE_APPS_CHROME_STORE_1X}, }; constexpr const int kGoogleAppIconSize = 48; // Pixels. -constexpr const int kGoogleAppIcons[] = { - IDR_NUX_EMAIL_GMAIL_1X, IDR_NUX_GOOGLE_APPS_YOUTUBE_1X, - IDR_NUX_GOOGLE_APPS_MAPS_1X, IDR_NUX_GOOGLE_APPS_TRANSLATE_1X, - IDR_NUX_GOOGLE_APPS_NEWS_1X, IDR_NUX_GOOGLE_APPS_CHROME_STORE_1X, -}; -static_assert(base::size(kGoogleAppNames) == base::size(kGoogleAppUrls), - "names and urls must match"); -static_assert(base::size(kGoogleAppNames) == (size_t)GoogleApps::kCount, - "names and histograms must match"); -static_assert(base::size(kGoogleAppNames) == base::size(kGoogleAppIcons), - "names and icons must match"); - -GoogleAppsHandler::GoogleAppsHandler(PrefService* prefs, - favicon::FaviconService* favicon_service, - bookmarks::BookmarkModel* bookmark_model) - : prefs_(prefs), - favicon_service_(favicon_service), - bookmark_model_(bookmark_model) {} +GoogleAppsHandler::GoogleAppsHandler() {} GoogleAppsHandler::~GoogleAppsHandler() {} void GoogleAppsHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "rejectGoogleApps", - base::BindRepeating(&GoogleAppsHandler::HandleRejectGoogleApps, + "cacheGoogleAppIcon", + base::BindRepeating(&GoogleAppsHandler::HandleCacheGoogleAppIcon, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "addGoogleApps", - base::BindRepeating(&GoogleAppsHandler::HandleAddGoogleApps, + "getGoogleAppsList", + base::BindRepeating(&GoogleAppsHandler::HandleGetGoogleAppsList, base::Unretained(this))); } -void GoogleAppsHandler::HandleRejectGoogleApps(const base::ListValue* args) { - UMA_HISTOGRAM_ENUMERATION(kGoogleAppsInteractionHistogram, - GoogleAppsInteraction::kNoThanks, - GoogleAppsInteraction::kCount); -} +void GoogleAppsHandler::HandleCacheGoogleAppIcon(const base::ListValue* args) { + int appId; + args->GetInteger(0, &appId); -void GoogleAppsHandler::HandleAddGoogleApps(const base::ListValue* args) { - // Add bookmarks for all selected apps. - int bookmarkIndex = 0; - for (size_t i = 0; i < (size_t)GoogleApps::kCount; ++i) { - bool selected = false; - CHECK(args->GetBoolean(i, &selected)); - if (selected) { - UMA_HISTOGRAM_ENUMERATION( - "FirstRun.NewUserExperience.GoogleAppsSelection", (GoogleApps)i, - GoogleApps::kCount); - GURL app_url = GURL(kGoogleAppUrls[i]); - bookmark_model_->AddURL(bookmark_model_->bookmark_bar_node(), - bookmarkIndex++, - base::ASCIIToUTF16(kGoogleAppNames[i]), app_url); - - // Preload the favicon cache with Chrome-bundled images. Otherwise, the - // pre-populated bookmarks don't have favicons and look bad. Favicons are - // updated automatically when a user visits a site. - favicon_service_->MergeFavicon( + const BookmarkItem* selectedApp = NULL; + for (size_t i = 0; i < base::size(kGoogleApps); i++) { + if (static_cast<int>(kGoogleApps[i].id) == appId) { + selectedApp = &kGoogleApps[i]; + break; + } + } + CHECK(selectedApp); // WebUI should not be able to pass non-existent ID. + + // Preload the favicon cache with Chrome-bundled images. Otherwise, the + // pre-populated bookmarks don't have favicons and look bad. Favicons are + // updated automatically when a user visits a site. + GURL app_url = GURL(selectedApp->url); + FaviconServiceFactory::GetForProfile(Profile::FromWebUI(web_ui()), + ServiceAccessType::EXPLICIT_ACCESS) + ->MergeFavicon( app_url, app_url, favicon_base::IconType::kFavicon, ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes( - kGoogleAppIcons[i]), + selectedApp->icon), gfx::Size(kGoogleAppIconSize, kGoogleAppIconSize)); - } - } - - // Enable bookmark bar. - prefs_->SetBoolean(bookmarks::prefs::kShowBookmarkBar, true); - - // Show bookmark bubble. - ShowPromoDelegate::CreatePromoDelegate( - IDS_NUX_GOOGLE_APPS_DESCRIPTION_PROMO_BUBBLE) - ->ShowForNode(bookmark_model_->bookmark_bar_node()->GetChild(0)); - - UMA_HISTOGRAM_ENUMERATION(kGoogleAppsInteractionHistogram, - GoogleAppsInteraction::kGetStarted, - GoogleAppsInteraction::kCount); } -void GoogleAppsHandler::AddSources(content::WebUIDataSource* html_source) { - // Localized strings. - html_source->AddLocalizedString("noThanks", IDS_NO_THANKS); - html_source->AddLocalizedString("getStarted", - IDS_NUX_GOOGLE_APPS_GET_STARTED); - html_source->AddLocalizedString("googleAppsDescription", - IDS_NUX_GOOGLE_APPS_DESCRIPTION); - - // Add required resources. - html_source->AddResourcePath("apps", IDR_NUX_GOOGLE_APPS_HTML); - html_source->AddResourcePath("apps/nux_google_apps.js", - IDR_NUX_GOOGLE_APPS_JS); - - html_source->AddResourcePath("apps/nux_google_apps_proxy.html", - IDR_NUX_GOOGLE_APPS_PROXY_HTML); - html_source->AddResourcePath("apps/nux_google_apps_proxy.js", - IDR_NUX_GOOGLE_APPS_PROXY_JS); - - html_source->AddResourcePath("apps/apps_chooser.html", - IDR_NUX_GOOGLE_APPS_CHOOSER_HTML); - html_source->AddResourcePath("apps/apps_chooser.js", - IDR_NUX_GOOGLE_APPS_CHOOSER_JS); - - // Add icons - html_source->AddResourcePath("apps/chrome_store_1x.png", - IDR_NUX_GOOGLE_APPS_CHROME_STORE_1X); - html_source->AddResourcePath("apps/chrome_store_2x.png", - IDR_NUX_GOOGLE_APPS_CHROME_STORE_2X); - // TODO: rename and centralize to make it easier to share icons between NUX. - html_source->AddResourcePath("apps/gmail_1x.png", - IDR_NUX_EMAIL_GMAIL_1X); - html_source->AddResourcePath("apps/gmail_2x.png", - IDR_NUX_EMAIL_GMAIL_2X); - html_source->AddResourcePath("apps/google_apps_1x.png", - IDR_NUX_GOOGLE_APPS_LOGO_1X); - html_source->AddResourcePath("apps/google_apps_2x.png", - IDR_NUX_GOOGLE_APPS_LOGO_2X); - html_source->AddResourcePath("apps/maps_1x.png", IDR_NUX_GOOGLE_APPS_MAPS_1X); - html_source->AddResourcePath("apps/maps_2x.png", IDR_NUX_GOOGLE_APPS_MAPS_2X); - html_source->AddResourcePath("apps/news_1x.png", IDR_NUX_GOOGLE_APPS_NEWS_1X); - html_source->AddResourcePath("apps/news_2x.png", IDR_NUX_GOOGLE_APPS_NEWS_2X); - html_source->AddResourcePath("apps/translate_1x.png", - IDR_NUX_GOOGLE_APPS_TRANSLATE_1X); - html_source->AddResourcePath("apps/translate_2x.png", - IDR_NUX_GOOGLE_APPS_TRANSLATE_2X); - html_source->AddResourcePath("apps/youtube_1x.png", - IDR_NUX_GOOGLE_APPS_YOUTUBE_1X); - html_source->AddResourcePath("apps/youtube_2x.png", - IDR_NUX_GOOGLE_APPS_YOUTUBE_2X); +void GoogleAppsHandler::HandleGetGoogleAppsList(const base::ListValue* args) { + AllowJavascript(); + CHECK_EQ(1U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + ResolveJavascriptCallback( + *callback_id, + bookmarkItemsToListValue(kGoogleApps, base::size(kGoogleApps))); } } // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.h b/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.h index d506d191d96..518b62bac50 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.h @@ -9,20 +9,6 @@ #include "base/values.h" #include "content/public/browser/web_ui_message_handler.h" -class PrefService; - -namespace bookmarks { -class BookmarkModel; -} // namespace bookmarks - -namespace content { -class WebUIDataSource; -} // namespace content - -namespace favicon { -class FaviconService; -} // namespace favicon - namespace nux { extern const char* kGoogleAppsInteractionHistogram; @@ -38,30 +24,15 @@ enum class GoogleAppsInteraction { class GoogleAppsHandler : public content::WebUIMessageHandler { public: - GoogleAppsHandler(PrefService* prefs, - favicon::FaviconService* favicon_service, - bookmarks::BookmarkModel* bookmark_model); + GoogleAppsHandler(); ~GoogleAppsHandler() override; // WebUIMessageHandler: void RegisterMessages() override; // Callbacks for JS APIs. - void HandleRejectGoogleApps(const base::ListValue* args); - void HandleAddGoogleApps(const base::ListValue* args); - - // Adds webui sources. - static void AddSources(content::WebUIDataSource* html_source); - - private: - // Weak reference. - PrefService* prefs_; - - // Weak reference. - favicon::FaviconService* favicon_service_; - - // Weak reference. - bookmarks::BookmarkModel* bookmark_model_; + void HandleCacheGoogleAppIcon(const base::ListValue* args); + void HandleGetGoogleAppsList(const base::ListValue* args); DISALLOW_COPY_AND_ASSIGN(GoogleAppsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.cc b/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.cc index 88ea473b0fa..0bd0c361198 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.cc @@ -4,14 +4,6 @@ #include "chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h" -#include "base/metrics/field_trial_params.h" -#include "base/metrics/histogram_macros.h" -#include "chrome/grit/browser_resources.h" -#include "chrome/grit/generated_resources.h" -#include "components/grit/components_resources.h" -#include "components/strings/grit/components_strings.h" -#include "content/public/browser/web_ui_data_source.h" - namespace nux { SetAsDefaultHandler::SetAsDefaultHandler() @@ -23,20 +15,4 @@ void SetAsDefaultHandler::RecordSetAsDefaultUMA() { // TODO(scottchen): Add UMA tracking. } -void SetAsDefaultHandler::AddSources(content::WebUIDataSource* html_source) { - // Localized strings. - - // Add required resources. - html_source->AddResourcePath("nux_set_as_default.html", - IDR_NUX_SET_AS_DEFAULT_HTML); - html_source->AddResourcePath("nux_set_as_default.js", - IDR_NUX_SET_AS_DEFAULT_JS); - html_source->AddResourcePath("nux_set_as_default_proxy.html", - IDR_NUX_SET_AS_DEFAULT_PROXY_HTML); - html_source->AddResourcePath("nux_set_as_default_proxy.js", - IDR_NUX_SET_AS_DEFAULT_PROXY_JS); - - // Add icons -} - -} // namespace nux
\ No newline at end of file +} // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h b/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h index 9621e65618e..5f70e699ea6 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h @@ -8,10 +8,6 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/settings/settings_default_browser_handler.h" -namespace content { -class WebUIDataSource; -} // namespace content - namespace nux { class SetAsDefaultHandler : public settings::DefaultBrowserHandler { @@ -19,9 +15,6 @@ class SetAsDefaultHandler : public settings::DefaultBrowserHandler { SetAsDefaultHandler(); ~SetAsDefaultHandler() override; - // Adds webui sources. - static void AddSources(content::WebUIDataSource* html_source); - protected: void RecordSetAsDefaultUMA() override; diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/show_promo_delegate.h b/chromium/chrome/browser/ui/webui/welcome/nux/show_promo_delegate.h deleted file mode 100644 index c95b16cc526..00000000000 --- a/chromium/chrome/browser/ui/webui/welcome/nux/show_promo_delegate.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_SHOW_PROMO_DELEGATE_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_SHOW_PROMO_DELEGATE_H_ - -#include <memory> - -namespace bookmarks { -class BookmarkNode; -} // namespace bookmarks - -class ShowPromoDelegate { - public: - virtual ~ShowPromoDelegate() = default; - - // Shows a promotional popup for the specified bookmark node. - virtual void ShowForNode(const bookmarks::BookmarkNode* node) = 0; - - // Return an instance of the promo delegate. - static std::unique_ptr<ShowPromoDelegate> CreatePromoDelegate( - int string_specifier); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_SHOW_PROMO_DELEGATE_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc b/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc index a9617a4f1be..e74a933cee7 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc +++ b/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc @@ -3,31 +3,100 @@ // found in the LICENSE file. #include "chrome/browser/ui/webui/welcome/nux_helper.h" + +#include <string> + #include "base/feature_list.h" +#include "base/metrics/field_trial.h" +#include "base/metrics/field_trial_params.h" +#include "base/values.h" #include "build/build_config.h" - -// TODO(scottchen): remove #if guard once components/nux/ is moved to -// chrome/browser/ui/webui/welcome/ and included by non-win platforms. -// Also check if it makes sense to merge nux_helper.* with nux/constants.*. -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#include "chrome/browser/metrics/chrome_metrics_service_accessor.h" +#include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/welcome/nux/constants.h" -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#include "chrome/common/pref_names.h" +#include "components/prefs/pref_service.h" namespace nux { // This feature flag is used to force the feature to be turned on for non-win // and non-branded builds, like with tests or development on other platforms. -extern const base::Feature kNuxOnboardingForceEnabled{ +const base::Feature kNuxOnboardingForceEnabled = { "NuxOnboardingForceEnabled", base::FEATURE_DISABLED_BY_DEFAULT}; -bool IsNuxOnboardingEnabled() { +// The value of these FeatureParam values should be a comma-delimited list +// of element names whitelisted in the MODULES_WHITELIST list, defined in +// chrome/browser/resources/welcome/onboarding_welcome/welcome_app.js +const base::FeatureParam<std::string> kNuxOnboardingForceEnabledNewUserModules = + {&kNuxOnboardingForceEnabled, "new-user-modules", + "nux-email,nux-google-apps,nux-set-as-default,signin-view"}; +const base::FeatureParam<std::string> + kNuxOnboardingForceEnabledReturningUserModules = { + &kNuxOnboardingForceEnabled, "returning-user-modules", + "nux-set-as-default"}; +const base::FeatureParam<bool> kNuxOnboardingForceEnabledShowEmailInterstitial = + {&kNuxOnboardingForceEnabled, "show-email-interstitial", true}; + +// Must match study name in configs. +const char kNuxOnboardingStudyName[] = "NaviOnboarding"; + +std::string GetOnboardingGroup() { + // We need to use |base::GetFieldTrialParamValue| instead of + // |base::FeatureParam| because our control group needs a custom value for + // this param. + return base::GetFieldTrialParamValue(kNuxOnboardingStudyName, + "onboarding-group"); +} + +bool IsNuxOnboardingEnabled(Profile* profile) { if (base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled)) { return true; } else { #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) + // To avoid diluting data collection, existing users should not be assigned + // an onboarding group. So, |prefs::kNaviOnboardGroup| is used to + // short-circuit the feature checks below. + PrefService* prefs = profile->GetPrefs(); + if (!prefs) + return false; + + std::string onboard_group = prefs->GetString(prefs::kNaviOnboardGroup); + + if (onboard_group.empty()) + return false; + + // User will be tied to their original onboarding group, even after + // experiment ends. + ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial( + "NaviOnboardingSynthetic", onboard_group); + return base::FeatureList::IsEnabled(nux::kNuxOnboardingFeature); #else return false; #endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) } } + +base::DictionaryValue GetNuxOnboardingModules(Profile* profile) { + // This function should not be called when nux onboarding feature is not on. + DCHECK(nux::IsNuxOnboardingEnabled(profile)); + + base::DictionaryValue modules; + + if (base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled)) { + modules.SetString("new-user", + kNuxOnboardingForceEnabledNewUserModules.Get()); + modules.SetString("returning-user", + kNuxOnboardingForceEnabledReturningUserModules.Get()); + modules.SetBoolean("show-email-interstitial", + kNuxOnboardingForceEnabledShowEmailInterstitial.Get()); + } else { // This means |nux::kNuxOnboardingFeature| is enabled. + modules.SetString("new-user", kNuxOnboardingNewUserModules.Get()); + modules.SetString("returning-user", + kNuxOnboardingReturningUserModules.Get()); + modules.SetBoolean("show-email-interstitial", + kNuxOnboardingShowEmailInterstitial.Get()); + } + + return modules; +} } // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux_helper.h b/chromium/chrome/browser/ui/webui/welcome/nux_helper.h index b27b3373ebd..f0368af081e 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux_helper.h +++ b/chromium/chrome/browser/ui/webui/welcome/nux_helper.h @@ -5,10 +5,40 @@ #ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_HELPER_H_ #define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_HELPER_H_ +#include <string> + #include "base/macros.h" +#include "base/metrics/field_trial_params.h" + +namespace base { +class DictionaryValue; +struct Feature; +} // namespace base + +class Profile; namespace nux { -bool IsNuxOnboardingEnabled(); -}; // namespace nux +extern const base::Feature kNuxOnboardingForceEnabled; + +extern const base::FeatureParam<std::string> + kNuxOnboardingForceEnabledNewUserModules; +extern const base::FeatureParam<std::string> + kNuxOnboardingForceEnabledReturningUserModules; +extern const base::FeatureParam<bool> + kNuxOnboardingForceEnabledShowEmailInterstitial; + +// Get the group for users who onboard in this experiment. +// Groups are: +// - Specified by study +// - The same for all experiments in study +// - Incremented with each new version +// - Not reused +// - Cleared out when experiment ends +std::string GetOnboardingGroup(); + +bool IsNuxOnboardingEnabled(Profile* profile); + +base::DictionaryValue GetNuxOnboardingModules(Profile* profile); +} // namespace nux #endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_HELPER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc index 7c8087386b3..383e5dd2ece 100644 --- a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc @@ -19,17 +19,25 @@ #include "ui/base/page_transition_types.h" const char kWelcomeReturningUserUrl[] = "chrome://welcome/returning-user"; +const char kWelcomeEmailInterstitial[] = "chrome://welcome/email-interstitial"; WelcomeHandler::WelcomeHandler(content::WebUI* web_ui) : profile_(Profile::FromWebUI(web_ui)), login_ui_service_(LoginUIServiceFactory::GetForProfile(profile_)), - result_(WelcomeResult::DEFAULT) { + result_(WelcomeResult::DEFAULT), + is_redirected_welcome_impression_(false) { login_ui_service_->AddObserver(this); } WelcomeHandler::~WelcomeHandler() { login_ui_service_->RemoveObserver(this); + // If this instance is spawned due to being redirected back to welcome page + // by the onboarding logic, there's no need to log sign-in metrics again. + if (is_redirected_welcome_impression_) { + return; + } + // We log that an impression occurred at destruct-time. This can't be done at // construct-time on some platforms because this page is shown immediately // after a new installation of Chrome and loads while the user is deciding @@ -41,6 +49,14 @@ WelcomeHandler::~WelcomeHandler() { WelcomeResult::WELCOME_RESULT_MAX); } +bool WelcomeHandler::isValidRedirectUrl() { + GURL current_url = web_ui()->GetWebContents()->GetVisibleURL(); + + return current_url == kWelcomeReturningUserUrl || + current_url.spec().find(kWelcomeEmailInterstitial) != + std::string::npos; +} + // Override from LoginUIService::Observer. void WelcomeHandler::OnSyncConfirmationUIClosed( LoginUIService::SyncConfirmationUIClosedResult result) { @@ -50,9 +66,9 @@ void WelcomeHandler::OnSyncConfirmationUIClosed( // When signed in from NUX onboarding flow, it's possible to come back to // chrome://welcome/... after closing sync-confirmation UI. If current URL // matches such a case, do not navigate away. - GURL current_url = web_ui()->GetWebContents()->GetVisibleURL(); - if (current_url != kWelcomeReturningUserUrl) + if (!is_redirected_welcome_impression_) { GoToNewTabPage(); + } } } @@ -90,11 +106,26 @@ void WelcomeHandler::HandleUserDecline(const base::ListValue* args) { result_ = (result_ == WelcomeResult::ATTEMPTED) ? WelcomeResult::ATTEMPTED_DECLINED : WelcomeResult::DECLINED; - GoToNewTabPage(); + + if (args->GetSize() == 1U) { + std::string url_string; + CHECK(args->GetString(0, &url_string)); + GURL redirect_url = GURL(url_string); + DCHECK(redirect_url.is_valid()); + + GoToURL(redirect_url); + } else { + GoToNewTabPage(); + } } // Override from WebUIMessageHandler. void WelcomeHandler::RegisterMessages() { + // Check if this instance of WelcomeHandler is spawned by onboarding flow + // redirecting users back to welcome page. This is done here instead of + // constructor, because web_ui hasn't loaded yet at that time. + is_redirected_welcome_impression_ = isValidRedirectUrl(); + web_ui()->RegisterMessageCallback( "handleActivateSignIn", base::BindRepeating(&WelcomeHandler::HandleActivateSignIn, @@ -106,7 +137,11 @@ void WelcomeHandler::RegisterMessages() { } void WelcomeHandler::GoToNewTabPage() { - NavigateParams params(GetBrowser(), GURL(chrome::kChromeUINewTabURL), + WelcomeHandler::GoToURL(GURL(chrome::kChromeUINewTabURL)); +} + +void WelcomeHandler::GoToURL(GURL url) { + NavigateParams params(GetBrowser(), url, ui::PageTransition::PAGE_TRANSITION_LINK); params.source_contents = web_ui()->GetWebContents(); Navigate(¶ms); diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.h b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.h index 7959b41750b..e34e4b8ac67 100644 --- a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.h @@ -11,6 +11,7 @@ class Browser; class Profile; +class GURL; // Handles actions on Welcome page. class WelcomeHandler : public content::WebUIMessageHandler, @@ -47,6 +48,8 @@ class WelcomeHandler : public content::WebUIMessageHandler, void HandleActivateSignIn(const base::ListValue* args); void HandleUserDecline(const base::ListValue* args); void GoToNewTabPage(); + void GoToURL(GURL url); + bool isValidRedirectUrl(); Browser* GetBrowser(); @@ -54,6 +57,10 @@ class WelcomeHandler : public content::WebUIMessageHandler, LoginUIService* login_ui_service_; WelcomeResult result_; + // Indicates whether this WelcomeHandler instance is spawned due to users + // being redirected back to welcome page as part of the onboarding flow. + bool is_redirected_welcome_impression_; + DISALLOW_COPY_AND_ASSIGN(WelcomeHandler); }; diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc index a07f37c2307..8d67c0e0d72 100644 --- a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc +++ b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc @@ -7,9 +7,14 @@ #include <memory> #include <string> +#include "base/metrics/histogram_macros.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/nux/bookmark_handler.h" +#include "chrome/browser/ui/webui/welcome/nux/constants.h" +#include "chrome/browser/ui/webui/welcome/nux/email_handler.h" +#include "chrome/browser/ui/webui/welcome/nux/google_apps_handler.h" +#include "chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h" #include "chrome/browser/ui/webui/welcome/nux_helper.h" #include "chrome/browser/ui/webui/welcome/welcome_handler.h" #include "chrome/common/pref_names.h" @@ -17,21 +22,18 @@ #include "chrome/grit/chrome_unscaled_resources.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" +#include "chrome/grit/onboarding_welcome_resources.h" +#include "chrome/grit/onboarding_welcome_resources_map.h" #include "components/prefs/pref_service.h" +#include "components/strings/grit/components_strings.h" +#include "content/public/browser/web_contents.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 "chrome/browser/ui/webui/welcome/nux/constants.h" -#include "chrome/browser/ui/webui/welcome/nux/email_handler.h" -#include "chrome/browser/ui/webui/welcome/nux/google_apps_handler.h" -#include "chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h" -#include "chrome/browser/ui/webui/welcome/nux/show_promo_delegate.h" -#include "content/public/browser/web_contents.h" -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) +#include "base/win/windows_version.h" +#endif namespace { const bool kIsBranded = @@ -42,6 +44,69 @@ const bool kIsBranded = #endif } // namespace +// TODO(scottchen): reuse instead of copy from +// md_settings_localized_strings_provider.cc. +struct LocalizedString { + const char* name; + int id; +}; + +void AddOnboardingStrings(content::WebUIDataSource* html_source) { + static constexpr LocalizedString kLocalizedStrings[] = { + // Shared strings. + {"acceptText", IDS_WELCOME_ACCEPT_BUTTON}, + {"bookmarkAdded", IDS_ONBOARDING_WELCOME_BOOKMARK_ADDED}, + {"bookmarksAdded", IDS_ONBOARDING_WELCOME_BOOKMARKS_ADDED}, + {"bookmarkRemoved", IDS_ONBOARDING_WELCOME_BOOKMARK_REMOVED}, + {"bookmarksRemoved", IDS_ONBOARDING_WELCOME_BOOKMARKS_REMOVED}, + {"bookmarkReplaced", IDS_ONBOARDING_WELCOME_BOOKMARK_REPLACED}, + {"getStarted", IDS_ONBOARDING_WELCOME_GET_STARTED}, + {"headerText", IDS_WELCOME_HEADER}, + {"next", IDS_ONBOARDING_WELCOME_NEXT}, + {"noThanks", IDS_NO_THANKS}, + {"skip", IDS_ONBOARDING_WELCOME_SKIP}, + + // Sign-in view strings. + {"signInHeader", IDS_ONBOARDING_WELCOME_SIGNIN_VIEW_HEADER}, + {"signInSubHeader", IDS_ONBOARDING_WELCOME_SIGNIN_VIEW_SUB_HEADER}, + {"signIn", IDS_ONBOARDING_WELCOME_SIGNIN_VIEW_SIGNIN}, + + // Email provider module strings. + {"emailProviderTitle", IDS_ONBOARDING_WELCOME_NUX_EMAIL_TITLE}, + + // Google apps module strings. + {"googleAppsDescription", + IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_DESCRIPTION}, + + // Set as default module strings. + {"setDefaultHeader", IDS_ONBOARDING_WELCOME_NUX_SET_AS_DEFAULT_HEADER}, + {"setDefaultSubHeader", + IDS_ONBOARDING_WELCOME_NUX_SET_AS_DEFAULT_SUB_HEADER}, + {"setDefaultSkip", IDS_ONBOARDING_WELCOME_NUX_SET_AS_DEFAULT_SKIP}, + {"setDefaultConfirm", + IDS_ONBOARDING_WELCOME_NUX_SET_AS_DEFAULT_SET_AS_DEFAULT}, + + // Landing view strings. + {"landingTitle", IDS_ONBOARDING_WELCOME_LANDING_TITLE}, + {"landingDescription", IDS_ONBOARDING_WELCOME_LANDING_DESCRIPTION}, + {"landingNewUser", IDS_ONBOARDING_WELCOME_LANDING_NEW_USER}, + {"landingExistingUser", IDS_ONBOARDING_WELCOME_LANDING_EXISTING_USER}, + + // Email interstitial strings. + {"emailInterstitialTitle", + IDS_ONBOARDING_WELCOME_EMAIL_INTERSTITIAL_TITLE}, + {"emailInterstitialContinue", + IDS_ONBOARDING_WELCOME_EMAIL_INTERSTITIAL_CONTINUE}, + }; + + // TODO(scottchen): reuse instead of copy from + // md_settings_localized_strings_provider.cc. + for (size_t i = 0; i < base::size(kLocalizedStrings); i++) { + html_source->AddLocalizedString(kLocalizedStrings[i].name, + kLocalizedStrings[i].id); + } +} + WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) : content::WebUIController(web_ui) { Profile* profile = Profile::FromWebUI(web_ui); @@ -53,7 +118,7 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) return; } - StorePageSeen(profile, url); + StorePageSeen(profile); web_ui->AddMessageHandler(std::make_unique<WelcomeHandler>(web_ui)); @@ -68,36 +133,55 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) html_source->AddResourcePath("logo.png", IDR_PRODUCT_LOGO_128); html_source->AddResourcePath("logo2x.png", IDR_PRODUCT_LOGO_256); - if (nux::IsNuxOnboardingEnabled()) { + if (nux::IsNuxOnboardingEnabled(profile)) { // Add Onboarding welcome strings. - html_source->AddLocalizedString("headerText", IDS_WELCOME_HEADER); - html_source->AddLocalizedString("acceptText", IDS_WELCOME_ACCEPT_BUTTON); + AddOnboardingStrings(html_source); - // Add onboarding welcome resources. + // Add all Onboarding resources. + for (size_t i = 0; i < kOnboardingWelcomeResourcesSize; ++i) { + html_source->AddResourcePath(kOnboardingWelcomeResources[i].name, + kOnboardingWelcomeResources[i].value); + } + + // chrome://welcome html_source->SetDefaultResource( IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_HTML); + + // chrome://welcome/email-interstitial html_source->AddResourcePath( - "landing_view.html", IDR_WELCOME_ONBOARDING_WELCOME_LANDING_VIEW_HTML); - html_source->AddResourcePath( - "landing_view.js", IDR_WELCOME_ONBOARDING_WELCOME_LANDING_VIEW_JS); - html_source->AddResourcePath( - "navigation_behavior.html", - IDR_WELCOME_ONBOARDING_WELCOME_NAVIGATION_BEHAVIOR_HTML); - html_source->AddResourcePath( - "navigation_behavior.js", - IDR_WELCOME_ONBOARDING_WELCOME_NAVIGATION_BEHAVIOR_JS); - html_source->AddResourcePath("welcome.css", - IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_CSS); - html_source->AddResourcePath( - "welcome_app.html", IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_APP_HTML); - html_source->AddResourcePath("welcome_app.js", - IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_APP_JS); - html_source->AddResourcePath( - "welcome_browser_proxy.html", - IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_BROWSER_PROXY_HTML); - html_source->AddResourcePath( - "welcome_browser_proxy.js", - IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_BROWSER_PROXY_JS); + "email-interstitial", + IDR_WELCOME_ONBOARDING_WELCOME_EMAIL_INTERSTITIAL_HTML); + +#if defined(OS_WIN) + html_source->AddBoolean( + "is_win10", base::win::GetVersion() >= base::win::VERSION_WIN10); +#endif + + // Add the shared bookmark handler for onboarding modules. + web_ui->AddMessageHandler( + std::make_unique<nux::BookmarkHandler>(profile->GetPrefs())); + + // Add email provider bookmarking onboarding module. + web_ui->AddMessageHandler(std::make_unique<nux::EmailHandler>()); + nux::EmailHandler::AddSources(html_source); + + // Add google apps bookmarking onboarding module. + web_ui->AddMessageHandler(std::make_unique<nux::GoogleAppsHandler>()); + + // Add set-as-default onboarding module. + web_ui->AddMessageHandler(std::make_unique<nux::SetAsDefaultHandler>()); + + html_source->AddString( + "newUserModules", + nux::GetNuxOnboardingModules(profile).FindKey("new-user")->GetString()); + html_source->AddString("returningUserModules", + nux::GetNuxOnboardingModules(profile) + .FindKey("returning-user") + ->GetString()); + html_source->AddBoolean("showEmailInterstitial", + nux::GetNuxOnboardingModules(profile) + .FindKey("show-email-interstitial") + ->GetBool()); } else if (kIsBranded && is_dice) { // Use special layout if the application is branded and DICE is enabled. html_source->AddLocalizedString("headerText", IDS_WELCOME_HEADER); @@ -143,81 +227,12 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) html_source->SetDefaultResource(IDR_WELCOME_HTML); } -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) - // TODO(hcarmona): Move this behind nux::kNuxOnboardingFeature when email and - // apps experiments end. - html_source->AddResourcePath("shared/chooser_shared_css.html", - IDR_NUX_CHOOSER_SHARED_CSS); - html_source->AddResourcePath( - "shared/i18n_setup.html", - IDR_WELCOME_ONBOARDING_WELCOME_SHARED_I18N_SETUP_HTML); - - if (base::FeatureList::IsEnabled(nux::kNuxOnboardingFeature)) { - web_ui->AddMessageHandler(std::make_unique<nux::SetAsDefaultHandler>()); - nux::SetAsDefaultHandler::AddSources(html_source); - - // TODO(scottchen): move all NUX features under this flag once individual - // experiments launch. - } - - // To avoid diluting data collection, existing users should not be assigned - // an NUX group. So, the kOnboardDuringNUX flag is used to short-circuit the - // feature checks below. - PrefService* prefs = profile->GetPrefs(); - bool onboard_during_nux = - prefs && prefs->GetBoolean(prefs::kOnboardDuringNUX); - - if (onboard_during_nux && - base::FeatureList::IsEnabled(nux::kNuxEmailFeature)) { - web_ui->AddMessageHandler(std::make_unique<nux::EmailHandler>( - profile->GetPrefs(), FaviconServiceFactory::GetForProfile( - profile, ServiceAccessType::EXPLICIT_ACCESS))); - - nux::EmailHandler::AddSources(html_source, profile->GetPrefs()); - } - - if (onboard_during_nux && - base::FeatureList::IsEnabled(nux::kNuxGoogleAppsFeature)) { - content::BrowserContext* browser_context = - web_ui->GetWebContents()->GetBrowserContext(); - web_ui->AddMessageHandler(std::make_unique<nux::GoogleAppsHandler>( - profile->GetPrefs(), - FaviconServiceFactory::GetForProfile( - profile, ServiceAccessType::EXPLICIT_ACCESS), - BookmarkModelFactory::GetForBrowserContext(browser_context))); - - nux::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::kNuxGoogleAppsUrl))) { - // Record that the new user experience page was visited. - profile->GetPrefs()->SetBoolean(prefs::kHasSeenGoogleAppsPromoPage, true); - - // Record UMA. - UMA_HISTOGRAM_ENUMERATION(nux::kGoogleAppsInteractionHistogram, - nux::GoogleAppsInteraction::kPromptShown, - nux::GoogleAppsInteraction::kCount); - return; - } - - if (url.EqualsIgnoringRef(GURL(nux::kNuxEmailUrl))) { - // Record that the new user experience page was visited. - profile->GetPrefs()->SetBoolean(prefs::kHasSeenEmailPromoPage, true); - - // TODO(scottchen): Record UMA. - - return; - } -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) - +void WelcomeUI::StorePageSeen(Profile* profile) { // 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/welcome_ui.h b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h index acadd2f3582..a352818777f 100644 --- a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h +++ b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h @@ -19,7 +19,9 @@ class WelcomeUI : public content::WebUIController { ~WelcomeUI() override; private: - void StorePageSeen(Profile* profile, const GURL& url); + void StorePageSeen(Profile* profile); + + DISALLOW_COPY_AND_ASSIGN(WelcomeUI); }; #endif // CHROME_BROWSER_UI_WEBUI_WELCOME_WELCOME_UI_H_ |